diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha new file mode 100644 index 0000000..1a0e196 --- /dev/null +++ b/.github/computer-mcp-host.sha @@ -0,0 +1 @@ +dec7150f3dc94411c290309e6f26e59d95da248d diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c54d6fa..d7349d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,22 +20,38 @@ jobs: python-version: ['3.13', '3.14'] env: PYTHONDONTWRITEBYTECODE: '1' + defaults: + run: + working-directory: plugin steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + path: plugin persist-credentials: false - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 with: python-version: ${{ matrix.python-version }} - - run: | - python3 -m unittest discover -s tests -p 'test_*.py' - python3 scripts/build_package.py dist > package-receipt.json + - name: Read the pinned Host revision + id: host + shell: bash + run: | + revision=$(cat .github/computer-mcp-host.sha) + [[ "$revision" =~ ^[0-9a-f]{40}$ && "$revision" != 0000000000000000000000000000000000000000 ]] + printf 'revision=%s\n' "$revision" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: computer-mcp/computer-mcp + ref: ${{ steps.host.outputs.revision }} + path: host + persist-credentials: false + - uses: ./host/.github/actions/provision-plugin-smoke + - run: python3 scripts/test_plugin.py dist > package-receipt.json - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: cursor-plugin-${{ github.sha }}-${{ matrix.python-version }} path: | - dist/cursor.zip - package-receipt.json + plugin/dist/cursor.zip + plugin/package-receipt.json if-no-files-found: error unsupported-runtime: runs-on: macos-latest @@ -53,9 +69,42 @@ jobs: - run: python3 tests/check_runtime_rejection.py runtime: uses: computer-mcp/github-workflows/.github/workflows/plugin-runtime.yml@d1235cc8d2d86df99770c30b5a0b64469085e931 + interop-scope: + runs-on: ubuntu-latest + outputs: + required: ${{ steps.scope.outputs.required }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + persist-credentials: false + - name: Check for changes to the plugin or interop contract + id: scope + env: + BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + shell: bash + run: | + required=true + if [[ -n "$BASE" ]] && git cat-file -e "$BASE^{commit}" 2>/dev/null; then + changes=$(git diff --name-only --no-renames "$BASE" HEAD -- \ + bin/ skills/ Examples/ computer-mcp-plugin.toml cli-tree.json \ + cursor-vendor-execution.json scripts/build_package.py \ + scripts/validate_host.py scripts/validate_host_source.py scripts/test-interop.sh \ + tests/Fixtures/ tests/Interop/ .github/computer-mcp-host.sha .github/workflows/ci.yml \ + .github/workflows/host-interop.yml .github/workflows/release.yml) + if [[ -z "$changes" ]]; then required=false; fi + fi + printf 'required=%s\n' "$required" >> "$GITHUB_OUTPUT" + host-consumer: + needs: interop-scope + if: needs.interop-scope.outputs.required == 'true' + uses: ./.github/workflows/host-interop.yml + with: + ref: ${{ github.sha }} validate: if: always() - needs: [package, unsupported-runtime, runtime] + needs: [package, unsupported-runtime, runtime, interop-scope, host-consumer] uses: computer-mcp/github-workflows/.github/workflows/result.yml@d1235cc8d2d86df99770c30b5a0b64469085e931 with: needs-json: ${{ toJSON(needs) }} + optional-jobs: ${{ needs.interop-scope.outputs.required == 'false' && '["host-consumer"]' || '[]' }} diff --git a/.github/workflows/host-interop.yml b/.github/workflows/host-interop.yml new file mode 100644 index 0000000..298b55a --- /dev/null +++ b/.github/workflows/host-interop.yml @@ -0,0 +1,68 @@ +name: Host interoperability +on: + workflow_call: + inputs: + ref: + description: Plugin revision to check out + required: true + type: string + outputs: + commit: + description: Full plugin commit validated against the pinned Host + value: ${{ jobs.host-consumer.outputs.commit }} +permissions: + contents: read +jobs: + host-consumer: + runs-on: macos-latest + timeout-minutes: 25 + outputs: + commit: ${{ steps.verify.outputs.commit }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + with: + python-version: '3.14' + - run: python3 -B -m unittest discover -s tests/Interop -p 'test_*.py' + - name: Verify the consumer against pinned Host source + id: verify + shell: bash + env: + GIT_TERMINAL_PROMPT: '0' + GIT_ASKPASS: /usr/bin/false + GIT_CONFIG_GLOBAL: /dev/null + GIT_CONFIG_NOSYSTEM: '1' + GIT_ALLOW_PROTOCOL: file:https + run: | + host_sha=$(cat .github/computer-mcp-host.sha) + [[ "$host_sha" =~ ^[0-9a-f]{40}$ && "$host_sha" != 0000000000000000000000000000000000000000 ]] + plugin_sha=$(git rev-parse HEAD) + [[ "$plugin_sha" =~ ^[0-9a-f]{40}$ ]] + host_source="$RUNNER_TEMP/computer-mcp-host" + git init "$host_source" + git -C "$host_source" -c credential.helper= fetch --no-tags --depth=1 \ + https://github.com/computer-mcp/computer-mcp.git "$host_sha" + git -C "$host_source" checkout --detach "$host_sha" + test "$(git -C "$host_source" rev-parse HEAD)" = "$host_sha" + sh "scripts/test-interop.sh" "$host_source" "$host_sha" "$RUNNER_TEMP/host-consumer" + printf 'commit=%s\n' "$plugin_sha" >> "$GITHUB_OUTPUT" + - name: Retain consumer evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: cursor-host-consumer-${{ steps.verify.outputs.commit || github.run_id }} + path: | + ${{ runner.temp }}/host-consumer/*/receipt.json + ${{ runner.temp }}/host-consumer/*/cases.json + ${{ runner.temp }}/host-consumer/vendor-stop/archive-validation.log + ${{ runner.temp }}/host-consumer/vendor-stop/archive/*.json + ${{ runner.temp }}/host-consumer/host-source-export.log + ${{ runner.temp }}/host-consumer/plugin-source-export.log + ${{ runner.temp }}/host-consumer/package-build.log + ${{ runner.temp }}/host-consumer/swift-test.log + ${{ runner.temp }}/host-consumer/swift-test.xml + if-no-files-found: ignore + retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 99b03e2..195dda6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,15 +12,25 @@ on: default: false permissions: {} jobs: + host-interop: + permissions: + contents: read + uses: ./.github/workflows/host-interop.yml + with: + ref: ${{ inputs.ref }} release: + needs: host-interop permissions: contents: write actions: read - uses: computer-mcp/github-workflows/.github/workflows/plugin-release.yml@d1235cc8d2d86df99770c30b5a0b64469085e931 + uses: computer-mcp/github-workflows/.github/workflows/plugin-release.yml@46a24bd92aed806eeea4aa870e7e402cad956204 with: + require_immutable_release: false ref: ${{ inputs.ref }} publish: ${{ inputs.publish }} - build: python3 scripts/build_package.py + build: >- + test "$(git rev-parse HEAD)" = "${{ needs.host-interop.outputs.commit }}" + && python3 scripts/build_package.py ci_artifact: cursor-plugin-${commit}-3.13 notify-catalog: needs: release diff --git a/CHANGELOG.md b/CHANGELOG.md index 2d87e6d..113f925 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,3 +3,9 @@ All notable user-visible changes to the Cursor plugin are documented here. ## Unreleased + +## 0.1.0 — 2026-11-30 + +### Added + +- Open or resume Cursor sessions through ACP. Start prompts in the background, follow events, answer permission requests, questions and plans, or cancel the active prompt. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index db6880d..ede4ce3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,16 +2,32 @@ Read the [architecture](docs/Architecture/README.md) and [interface contract](docs/Reference/Interface.md). Keep vendor-specific behavior in this repository and preserve the host manifest/CLITree/MCP boundaries. -CI runs these checks on Python 3.13 and 3.14; run them before opening a pull request: +Run the same package and plugin suite as CI on Python 3.13 or 3.14. +On macOS, set `COMPUTER_MCP_TEST_HOST` to the provisioned fixture for the pinned +Host revision before running this command. ```sh -python3 -m unittest discover -s tests -p 'test_*.py' -v -python3 scripts/build_package.py /new/output/directory +python3 scripts/test_plugin.py /new/output/directory ``` -CI also runs `python3 tests/check_runtime_rejection.py` on Python 3.11 and 3.12 to confirm that unsupported interpreters are refused. When changing the native interface, inspect the matching real executable and run `scripts/validate_native.py --executable PATH`. Never use authenticated model calls as ordinary unit tests. +The suite runs the archive's adapter with deterministic ACP and Host channel +peers. It checks CLI binding, MCP metadata, permission choices, native result +translation, cancellation, and cleanup reporting. On macOS, the provisioned +Host also installs the same ZIP and checks a public one-shot ACP call. For +portable package and plugin coverage, run +`python3 scripts/test_plugin.py --plugin-only /new/output/directory`. +CI also runs +`python3 tests/check_runtime_rejection.py` on Python 3.11 and 3.12 to verify that +the packaged entrypoint refuses unsupported interpreters before vendor execution. +When changing the native interface, inspect the matching real executable with +`scripts/validate_native.py --executable PATH`. Do not commit caches, local credentials or generated runtime state. Publishing a repository or release is a separate explicit action. Contributions are licensed under this repository's [LICENSE](LICENSE), FSL-1.1-ALv2. + +The [exact-pair interop gate](docs/Reference/Installation.md#deterministic-source-consumer) +checks actual Host installation, authorization, sandbox enforcement, and process +ownership. CI requires it when plugin implementation or the interop contract +changes. Release dry runs and publication require it for the release commit. diff --git a/Examples/settings.json b/Examples/settings.json index d08a51a..d9f0a57 100644 --- a/Examples/settings.json +++ b/Examples/settings.json @@ -7,10 +7,6 @@ "acp": { "enabled": true, "hostServices": false, - "args": [ - "--executable", - "/absolute/path/to/agent" - ], "exposure": "reexport", "prefix": "", "allowAnyTool": true diff --git a/README.md b/README.md index 6455ab5..d5978ee 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ vendor behavior needs no host release. The CLI contribution describes verified non-interactive commands; the native baseline and its exact version assertion live in `cli-tree.json`. It is deliberately partial: interactive setup, installation and unsupported administrative flows are not callable tools. The adapter owns -streaming and session and run state. The host owns registration, profile grants, the initial +streaming and session and run state. The host owns registration, provider/caller grants, private containers, the initial working directory and audit. ## Quick look @@ -50,8 +50,8 @@ from `Examples/settings.json`. ## Install -1. Install and authenticate Cursor Agent yourself, and provide Python 3.13 or newer on the - Computer MCP launch `PATH`. The plugin installs neither and never copies credentials. +1. Install Cursor Agent separately and sign in on your computer using Cursor. + Provide Python 3.13 or newer on the Computer MCP launch `PATH`. 2. Build the archive: ```sh @@ -61,9 +61,13 @@ from `Examples/settings.json`. 3. Install the ZIP through Computer MCP's plugin UI or the owner CLI. Installation is neither activation nor a permission grant. 4. Review `Examples/settings.json`, replace its placeholder paths, and configure the plugin - through the same UI or `plugins configure`. The CLI dependency binding selects the executable - for the CLI contribution; the MCP launch `args` supply `--executable` for the adapter. Point - both at the same verified installation. + through the same UI or `plugins configure`. The `cursor-agent` dependency selects the + executable for the CLI and Host-managed ACP contributions. + +At enablement, review the provider Project-write request, MCP caller requirements +and sandbox network request. The request covers `api2.cursor.sh` and +`api5.cursor.sh`. The owner can narrow it, and Host policy still applies. +Sandbox execution is the default. See the [installation guide](docs/Reference/Installation.md) for revisions, configuration publication and validation. @@ -92,8 +96,7 @@ semantics. ## Requirements - Computer MCP on an arm64 computer. -- Cursor Agent (`agent`), installed and authenticated separately; its version must match - `cli-tree.json`. +- Cursor Agent (`agent`) at the version declared in `cli-tree.json`. - Python 3.13 or newer. ## Documentation @@ -102,11 +105,14 @@ The [documentation index](docs/README.md) links the architecture, the interface, guide and the [release process](docs/Reference/Release.md). To validate a checkout: ```sh -python3 -m unittest discover -s tests -p 'test_*.py' -v +python3 scripts/test_plugin.py /new/output/directory python3 scripts/validate_native.py --executable /absolute/path/to/agent ``` -Tests use deterministic peers, not a model. Authenticated execution and production activation are +The [source consumer](docs/Reference/Installation.md#deterministic-source-consumer) +takes explicit clean full-SHA host/plugin inputs and exercises all three contributions +with isolated host-owned state. Its native host execution and the final host pin remain +integration acceptance steps. Tests use deterministic peers, not a model. Authenticated execution and production activation are separate acceptance steps. ## Contributing diff --git a/VERSIONING.md b/VERSIONING.md new file mode 100644 index 0000000..892221f --- /dev/null +++ b/VERSIONING.md @@ -0,0 +1,8 @@ +# Versioning + +This plugin adopts the organization's +[versioning policy](https://github.com/computer-mcp/.github/blob/master/VERSIONING.md) +with one exception. Maintainers may replace the attachments of a published +GitHub Release while keeping its signed tag on the original source commit. +Replace the checksums and release receipt with the records for the replacement +archive. The receipt must identify the CI artifacts that produced those bytes. diff --git a/bin/cursor-mcp-adapter b/bin/cursor-mcp-adapter index 898a6c5..dc1d2f5 100755 --- a/bin/cursor-mcp-adapter +++ b/bin/cursor-mcp-adapter @@ -14,11 +14,14 @@ from plugin_runtime import (EventBuffer, Failure, Job, MCPServer, Process, Tool, decoded, encoded, expected_version, integer_schema, load_package, resolve_executable, schema, text_schema, validate, verify_version) +from cursor_vendor_execution import CAPABILITY, HostVendorRefusal, ManagedCursorProcess, VendorChannel + MANIFEST, TREE = load_package(__file__) VERSION = MANIFEST['version'] POLICY = {'type':'string','enum':['reject-once','allow-once','allow-always','manual'],'default':'reject-once'} SESSION = text_schema(64) MODE = {'type':'string','enum':['agent','plan','ask']} +ACP_AUTH_REQUIRED = -32000 OPEN_FIELDS = {'resume_session_id':text_schema(512),'mode':MODE,'permission_policy':POLICY,'timeout_seconds':integer_schema(1,60,45)} PROMPT_FIELDS = {'prompt':text_schema(),'timeout_seconds':integer_schema(1,1800,300),'max_events':integer_schema(1,256,128)} @@ -84,7 +87,12 @@ def checked_response(method, params, response): class Session: - def __init__(self, handle, executable, policy, work_invocation=None): + def __init__(self, handle, executable, policy, work_invocation=None, channel=None): + self.channel = channel + self.managed = None + self.acquisition_job = None + self.prompt_job = None + self.native_stop_sent = False self.handle, self.executable, self.policy = handle, executable, policy self.work_invocation = work_invocation self.vendor_id = None @@ -135,13 +143,19 @@ class Session: self.startup_done.clear() try: deadline = time.monotonic()+args.get('timeout_seconds',45) - verify_version(self.executable,expected_version(TREE),job,os.getcwd(),self.retain_version_process) - with self.lock: self.version_process = None - job.check() - with self.lock: - if self.closed.is_set(): - raise Failure('cancelled','Session was closed during startup') - self.process = Process([self.executable,'acp'],os.getcwd()) + if self.channel is not None: + self.acquisition_job = job + self.managed = ManagedCursorProcess(self.channel, self.handle, job) + self.managed.launch(job) + self.process = self.managed + else: + verify_version(self.executable,expected_version(TREE),job,os.getcwd(),self.retain_version_process) + with self.lock: self.version_process = None + job.check() + with self.lock: + if self.closed.is_set(): + raise Failure('cancelled','Session was closed during startup') + self.process = Process([self.executable,'acp'],os.getcwd()) self.initialization = self.request('initialize',{'protocolVersion':1,'clientCapabilities':{'fs':{'readTextFile':False,'writeTextFile':False},'terminal':False},'clientInfo':{'name':'computer-mcp-cursor-adapter','version':VERSION}},deadline,job) if type(self.initialization.get('protocolVersion')) is not int or self.initialization['protocolVersion'] != 1: raise Failure('unsupported_protocol','Cursor did not negotiate ACP protocol 1') @@ -163,6 +177,7 @@ class Session: raise Failure('invalid_vendor_response','Cursor returned no sessionId') if args.get('mode'): self.set_mode(args['mode'],deadline,job) + if self.managed: self.managed.ready(job) return {**self.info(),'agent_capabilities':self.initialization.get('agentCapabilities',{}),'session_info':self.session_info} except Failure as error: if error.code=='cleanup_unconfirmed': @@ -173,10 +188,16 @@ class Session: self.startup_job = None self.startup_thread = None self.startup_done.set() - def respond_raw(self, request_id, result=None, error=None, deadline=None): + def send(self, message, deadline, job, kind, token=None): + if self.managed: + self.managed.send(message, deadline, job, kind, token) + else: + self.process.send(message, deadline, job if kind in ('setup', 'prompt', 'mode') else None) + def respond_raw(self, request_id, result=None, error=None, deadline=None, job=None, token=None): reply = {'jsonrpc':'2.0','id':request_id} reply['error' if error is not None else 'result'] = error if error is not None else result - self.process.send(reply,min(deadline or float('inf'),time.monotonic()+2)) + self.send(reply,min(deadline or float('inf'),time.monotonic()+2), + job or self.active_operation['job'], 'answer' if job else 'housekeeping', token) def check_session(self, method, params): if not isinstance(params,dict): raise Failure('invalid_vendor_request','ACP parameters must be an object') @@ -209,6 +230,7 @@ class Session: self.respond_raw(message['id'],{'outcome':{'outcome':'cancelled'}},deadline=deadline) return token = uuid.uuid4().hex + if self.managed: self.managed.pending(operation['job'], token) self.pending[token] = {'id':message['id'],'method':method,'params':params,'deadline':deadline,'operation':operation['id']} self.events.append({'method':method,'request_id':token,'params':params}) else: @@ -216,6 +238,8 @@ class Session: def request(self, method, params, deadline, job): if not self.operation.acquire(blocking=False): raise Failure('busy','Another request owns this Cursor session') + settled_rpc_error = False + kind = 'setup' try: if self.closed.is_set(): raise Failure('session_closed','Cursor session is closed') @@ -223,7 +247,14 @@ class Session: self.sequence += 1 request_id = self.sequence self.active_operation = {'id':request_id,'deadline':deadline,'job':job,'method':method} - self.process.send({'jsonrpc':'2.0','id':request_id,'method':method,'params':params},deadline,job) + if method == 'session/prompt': + kind = 'prompt' + elif method == 'session/set_mode' and self.startup_job is None: + kind = 'mode' + with self.lock: + if self.managed and kind == 'prompt' and (job.cancelled.is_set() or self.cancelled.is_set()): + raise Failure('vendor_queued_cancelled', 'Cursor prompt was cancelled before dispatch') + self.send({'jsonrpc':'2.0','id':request_id,'method':method,'params':params},deadline,job,kind) cancellation_sent = False while True: if self.closed.is_set(): @@ -232,17 +263,21 @@ class Session: if cancel and not cancellation_sent: if method != 'session/prompt': raise Failure('cancelled','Cursor operation cancelled') - self.process.send({'jsonrpc':'2.0','method':'session/cancel','params':{'sessionId':self.vendor_id}},min(deadline,time.monotonic()+1)) + with self.lock: + if not self.native_stop_sent: + self.send_native_stop(job, min(deadline,time.monotonic()+1)) cancellation_sent = True deadline = min(deadline,time.monotonic()+2) self.cancel_pending(deadline) try: - raw = self.process.read(min(deadline,time.monotonic()+.1)) + until = min(deadline,time.monotonic()+.1) + raw = self.managed.read(until,job) if self.managed else self.process.read(until) except Failure as error: if error.code=='timeout' and time.monotonic()capacity else: raise Failure('invalid_vendor_response','Unexpected ACP response identity') - except Exception: - self.close() + except Exception as error: + if not settled_rpc_error and getattr(error, 'code', None) != 'vendor_queued_cancelled': + self.close(job) + if getattr(error, 'code', None) == 'vendor_queued_cancelled': + raise Failure('cancelled', str(error)) from error raise finally: try: self.cancel_pending(deadline) + if (self.managed and not self.closed.is_set() and kind == 'mode' + and job is not self.acquisition_job): + self.managed.finish(job) except Exception: - self.close() + self.close(job) raise finally: with self.lock: self.active_operation = None self.operation.release() + def send_native_stop(self, job, deadline): + self.send({'jsonrpc':'2.0','method':'session/cancel','params':{'sessionId':self.vendor_id}}, + deadline,job,'cancel') + self.native_stop_sent = True + def request_stop(self, job): + with self.lock: + if not self.managed: + if self.busy: self.cancelled.set() + return self.busy + stopped = self.managed.stop(job) + if (not self.prompt_job or stopped.get('turn') != self.prompt_job.work_invocation): + return False + if stopped.get('dispatched') and not (stopped.get('sent') or self.native_stop_sent): + self.send_native_stop(job, time.monotonic()+1) + self.cancelled.set() + return True def set_mode(self, mode, deadline, job): available = self.session_info.get('modes',{}).get('availableModes',[]) if not any(isinstance(x,dict) and x.get('id')==mode for x in available): @@ -308,16 +366,18 @@ class Session: self.busy = True if not reserved: self.cancelled.clear() + self.native_stop_sent = False + self.prompt_job = job self.text = bytearray() self.text_truncated = False before = self.events.cursor try: result = self.request('session/prompt',{'sessionId':self.vendor_id,'prompt':[{'type':'text','text':args['prompt']}]},time.monotonic()+args.get('timeout_seconds',300),job) if not isinstance(result.get('stopReason'), str) or not result['stopReason']: - self.close() + self.close(job) raise Failure('invalid_vendor_response', 'Cursor prompt result lacks a stop reason') if len(encoded(result)) > 131072: - self.close() + self.close(job) raise Failure('result_too_large', 'Cursor prompt result exceeds its byte bound') text = self.text.decode('utf-8',errors='ignore') # JSON escaping counts against the text budget as well as UTF-8 bytes. @@ -332,23 +392,32 @@ class Session: page = self.events.page(before,args.get('max_events',128)) return {**self.info(),'busy':False,'stop_reason':result.get('stopReason'),'text':text,'text_truncated':self.text_truncated,'events':[row['event'] for row in page['events']],'event_page':{k:v for k,v in page.items() if k!='events'},'events_truncated':page['has_more'] or page['missed_events'] or any(row['event'].get('omitted',False) for row in page['events']),'native_result':result,'is_error':bool(result.get('cancelled',False)) or result['stopReason']=='cancelled'} finally: - with self.lock: self.busy = False + try: + if self.managed and not self.closed.is_set() and job is not self.acquisition_job: + self.managed.finish(job) + finally: + with self.lock: + self.busy = False + self.prompt_job = None def start_prompt(self, args, job): job.check() with self.lock: if self.busy or self.closed.is_set() or (self.prompt_thread and self.prompt_thread.is_alive()): raise Failure('busy','Session cannot admit another prompt') + if self.managed: self.managed.detach(job) self.busy = True self.cancelled.clear() + self.native_stop_sent = False self.prompt_id = uuid.uuid4().hex self.prompt_value = None self.prompt_done.clear() - self.prompt_thread = threading.Thread(target=self.background_prompt,args=(dict(args),)) + self.prompt_job = Job(work_invocation=job.work_invocation) + self.prompt_thread = threading.Thread(target=self.background_prompt,args=(dict(args),self.prompt_job)) self.prompt_thread.start() return {'session':self.handle,'prompt_id':self.prompt_id,'completed':False} - def background_prompt(self, args): + def background_prompt(self, args, job): try: - value = self.prompt(args,Job(),reserved=True) + value = self.prompt(args,job,reserved=True) except Failure as error: value = {'is_error':True,'error':{'code':error.code,'message':str(error)}} except Exception: @@ -369,11 +438,11 @@ class Session: until = min(deadline or float('inf'),time.monotonic()+2) try: if not self.closed.is_set(): - for item in self.pending.values(): - self.respond_raw(item['id'],{'outcome':{'outcome':'cancelled'}},deadline=until) + for token, item in self.pending.items(): + self.respond_raw(item['id'],{'outcome':{'outcome':'cancelled'}},deadline=until,token=token) finally: self.pending.clear() - def answer(self, token, response): + def answer(self, token, response, job=None): with self.lock: item = self.pending.get(token) operation = self.active_operation @@ -381,7 +450,10 @@ class Session: raise Failure('stale_request','Interactive request no longer belongs to an active operation') checked_response(item['method'],item['params'],response) try: - self.respond_raw(item['id'],response,deadline=item['deadline']) + self.respond_raw(item['id'],response,deadline=item['deadline'],job=job if self.managed else None,token=token) + except HostVendorRefusal as error: + # The turn still owns the pending request and will settle it on stop or completion. + raise Failure('response_refused', 'Host refused the interactive response before delivery') from error except Exception as error: self.closed.set() self.pending.clear() @@ -390,11 +462,13 @@ class Session: del self.pending[token] self.events.append({'method':'adapter/response','request_id':token,'response':response}) return {'answered':True,'request_id':token} - try: self.close() + try: self.close(operation['job']) finally: raise Failure('response_unknown','Interactive response delivery failed; do not replay it') from failure - def close(self): + def close(self, job=None): with self.lock: + if self.cleanup_confirmed: + return self.closed.set() self.pending.clear() if self.startup_job: self.startup_job.cancel() @@ -403,7 +477,9 @@ class Session: if not self.startup_done.wait(10): raise Failure('cleanup_unconfirmed','Session startup has not confirmed cleanup') if self.startup_cleanup_failure is not None: raise self.startup_cleanup_failure - if self.process is not None: + if self.managed is not None: + self.managed.close(job or self.acquisition_job) + elif self.process is not None: self.process.close() if self.version_process is not None: self.version_process.close() @@ -415,14 +491,16 @@ class Session: class Cursor: - def __init__(self, executable): + def __init__(self, executable, channel=None): + self.channel = channel self.executable = executable self.sessions = {} self.lock = threading.RLock() self.stopping = False def open(self,args,job): - executable = resolve_executable(self.executable,'CURSOR_AGENT_EXECUTABLE','agent') - session = Session(uuid.uuid4().hex,executable,args.get('permission_policy','reject-once'),job.work_invocation) + executable = None if self.channel else resolve_executable(self.executable,'CURSOR_AGENT_EXECUTABLE','agent') + session = Session(uuid.uuid4().hex,executable,args.get('permission_policy','reject-once'), + job.work_invocation,self.channel) with self.lock: self.sessions = {k:v for k,v in self.sessions.items() if not v.released()} if self.stopping or len(self.sessions)>=8: @@ -442,7 +520,7 @@ class Cursor: def close(self,args,_job): with self.lock: session = self.sessions.get(args['session']) if session: - session.close() + session.close(_job) with self.lock: self.sessions.pop(args['session'],None) return {'closed':True,'already_closed':session is None} def once(self,args,job): @@ -462,16 +540,13 @@ class Cursor: return self.get(args['session']).prompt_result(args['prompt_id']) def cancel(self,args,_job): session = self.get(args['session']) - with session.lock: - active = session.busy - if active: session.cancelled.set() - return {'cancel_requested':active,'session':session.handle} + return {'cancel_requested':session.request_stop(_job),'session':session.handle} def pending(self,args,_job): session = self.get(args['session']) with session.lock: return {'requests':[{'request_id':key,'method':value['method'],'params':value['params']} for key,value in session.pending.items()]} def answer(self,args,_job): - return self.get(args['session']).answer(args['request_id'],args['response']) + return self.get(args['session']).answer(args['request_id'],args['response'],_job) def events(self,args,_job): return self.get(args['session']).events.page(args.get('after_cursor',0),args.get('limit',128),args.get('max_bytes',196608)) def listing(self,_args,_job): @@ -487,6 +562,10 @@ class Cursor: with self.lock: self.stopping = True sessions = list(self.sessions.values()) + if self.channel: + # Closing the carrier signals the Host to seal and drain its children. + self.channel.close() + return errors = [] for session in sessions: try: @@ -500,7 +579,7 @@ class Cursor: def tools(self): return [ Tool('cursor.acp.prompt','Run one Cursor ACP prompt and retire its owned process. Use explicit sessions for interactive input.',schema({**OPEN_FIELDS,**PROMPT_FIELDS},['prompt']),self.once,risk='full-shell'), - Tool('cursor.acp.session.open','Initialize Cursor ACP, authenticate existing vendor credentials, and create or load a session in the host-selected working directory.',schema(OPEN_FIELDS),self.open,risk='full-shell'), + Tool('cursor.acp.session.open','Initialize Cursor ACP and create or load a session in the host-selected working directory.',schema(OPEN_FIELDS),self.open,risk='full-shell'), Tool('cursor.acp.session.prompt','Prompt an existing Cursor ACP session; read events and answer pending requests concurrently.',schema({'session':SESSION,**PROMPT_FIELDS},['session','prompt']),self.prompt,risk='full-shell',continuation=('cursor.session','session')), Tool('cursor.acp.session.prompt.start','Start a prompt without holding a long MCP request; use its prompt ID to read completion.',schema({'session':SESSION,**PROMPT_FIELDS},['session','prompt']),self.start_prompt,risk='full-shell',continuation=('cursor.session','session')), Tool('cursor.acp.session.prompt.result','Read the most recent background prompt result without replaying it.',schema({'session':SESSION,'prompt_id':text_schema(64)},['session','prompt_id']),self.prompt_result,risk='read-only',continuation=('cursor.session','session')), @@ -514,13 +593,28 @@ class Cursor: ] +class ManagedCursorMCPServer(MCPServer): + def emit(self, message): + result = message.get('result') + if self.initialized and isinstance(result, dict) and 'protocolVersion' in result: + result['capabilities']['experimental'] = {CAPABILITY: True} + super().emit(message) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--version',action='version',version=VERSION) parser.add_argument('--executable',help='Absolute user-owned Cursor Agent path; otherwise CURSOR_AGENT_EXECUTABLE or PATH') + parser.add_argument('--host-vendor-execution',action='store_true',help=argparse.SUPPRESS) args = parser.parse_args() - cursor = Cursor(args.executable) - MCPServer('cursor-mcp-adapter',VERSION,cursor.tools(),cursor.shutdown,work=cursor.work_resources).serve() + managed = args.host_vendor_execution or 'COMPUTER_MCP_HOST_CONTEXT' in os.environ + channel = VendorChannel() if managed else None + cursor = Cursor(args.executable, channel=channel) + try: + server = ManagedCursorMCPServer if channel else MCPServer + server('cursor-mcp-adapter',VERSION,cursor.tools(),cursor.shutdown,work=cursor.work_resources).serve() + finally: + if channel: channel.close() if __name__=='__main__': main() diff --git a/bin/cursor_vendor_execution.py b/bin/cursor_vendor_execution.py new file mode 100644 index 0000000..a71e696 --- /dev/null +++ b/bin/cursor_vendor_execution.py @@ -0,0 +1,228 @@ +"""Cursor's private channel to the Host-owned version and ACP children.""" + +import base64 +import os +import queue +import socket +import threading +import time + +from plugin_runtime import Failure, LineReader, MAX_FRAME, decoded, encoded, write_bytes + + +CAPABILITY = 'io.github.computer-mcp/vendor-execution-v1' + + +class HostVendorRefusal(Failure): + """A definitive Host reply that the operation failed before delivery.""" + + +class VendorChannel: + def __init__(self): + if (os.environ.get('COMPUTER_MCP_HOST_CONTEXT') != CAPABILITY + or os.environ.get('COMPUTER_MCP_HOST_FD') != '3'): + raise Failure('host_execution_required', 'Managed Cursor requires the Host vendor channel') + self.socket = socket.socket(fileno=3) + os.set_inheritable(3, False) + self.socket.setblocking(False) + self.reader = LineReader(self.socket) + self.lock, self.writer = threading.Lock(), threading.Lock() + self.pending = {} + self.sequence = 0 + self.closed = threading.Event() + threading.Thread(target=self._receive, daemon=True).start() + try: + if self.call('initialize', capability=CAPABILITY).get('capability') != CAPABILITY: + raise Failure('host_execution_required', 'Host did not negotiate Cursor vendor execution') + except BaseException: + self.close() + raise + + def _receive(self): + try: + while not self.closed.is_set(): + try: + raw = self.reader.next(time.monotonic() + .1) + except Failure as error: + if error.code == 'timeout': + continue + raise + if raw is None: + break + result = decoded(raw) + with self.lock: + pending = self.pending.get(result['id']) + if pending is not None: + pending.put_nowait(result) + except (Failure, ValueError, KeyError, TypeError, queue.Full): + pass + finally: + self.closed.set() + + def begin(self, op, deadline, **fields): + pending = queue.Queue(maxsize=1) + with self.lock: + if self.closed.is_set() or len(self.pending) >= 16: + raise Failure('host_execution_closed', 'Cursor vendor channel is unavailable') + self.sequence += 1 + request = self.sequence + self.pending[request] = pending + try: + data = encoded({'id': request, 'op': op, **fields}) + b'\n' + if len(data) > MAX_FRAME: + raise Failure('frame_too_large', 'Cursor vendor channel frame exceeds its bound') + with self.writer: + try: + write_bytes(self.socket.fileno(), data, deadline, self.closed) + except Failure: + self.close() + raise + return request, pending + except BaseException: + self.discard(request) + raise + + def discard(self, request): + with self.lock: + self.pending.pop(request, None) + + def wait(self, handle, deadline, *, keep_pending=False): + request, pending = handle + while not self.closed.is_set(): + remaining = deadline - time.monotonic() + if remaining <= 0: + if not keep_pending: + self.discard(request) + raise Failure('timeout', 'Host vendor operation did not confirm its result') + try: + reply = pending.get(timeout=min(.05, remaining)) + except queue.Empty: + continue + self.discard(request) + if 'error' in reply: + code = reply['error'] + if 'result' not in reply and code in ('vendor_effect_denied', 'vendor_effect_stale'): + raise HostVendorRefusal(code, 'Host did not dispatch the Cursor vendor effect') + if 'result' not in reply and isinstance(code, str): + raise Failure(code, 'Host could not settle the Cursor vendor effect') + raise Failure('invalid_host_reply', 'Host returned an invalid Cursor vendor reply') + if not isinstance(reply.get('result'), dict): + raise Failure('invalid_host_reply', 'Host returned an invalid Cursor vendor result') + return reply['result'] + self.discard(request) + raise Failure('host_execution_closed', 'Cursor vendor channel closed') + + def call(self, op, *, timeout=10, **fields): + deadline = time.monotonic() + timeout + return self.wait(self.begin(op, deadline, **fields), deadline) + + def close(self): + self.closed.set() + self.reader.close() + self.socket.close() + + +class ManagedCursorProcess: + """Owns adapter-side correlation only. The Host owns both child generations.""" + + def __init__(self, channel, session, job): + if job.work_invocation is None: + raise Failure('host_execution_required', 'Host did not correlate the Cursor acquisition') + self.channel = channel + self.session = session + self.acquisition = job.work_invocation + self.probe = None + self.workload = None + self.output = bytearray() + self.output_cursor = 0 + self.read_handle = None + + def _call(self, op, job, *, child=None, **fields): + if job is None or job.work_invocation is None: + raise Failure('host_execution_required', 'Host did not correlate the Cursor effect') + return self.channel.call(op, call=job.work_invocation, acquisition=self.acquisition, + child=child or self.workload, **fields) + + def launch(self, job): + bound = self._call('bind', job, session=self.session) + self.probe, self.workload = bound['probe'], bound['workload'] + job.check() + self._call('probe', job, child=self.probe) + job.check() + try: + self._call('launch', job) + except Failure as error: + if error.code == 'timeout': + # A lost reply can establish ownership through the receipt, never by replay. + self._call('receipt', job) + raise + + def ready(self, job): + self._call('ready', job) + + def send(self, value, deadline, job, kind, token=None): + remaining = deadline - time.monotonic() + if remaining <= 0: + raise Failure('timeout', 'Cursor operation exceeded its deadline') + self._call('write', job, kind=kind, data=encoded(value).decode('utf-8'), + token=token, timeout=min(10, remaining)) + + def read(self, deadline, job): + while time.monotonic() < deadline: + newline = self.output.find(b'\n') + if newline >= 0: + line = bytes(self.output[:newline+1]) + del self.output[:newline+1] + return line + # A short local wait leaves at most one Host read in flight for this child. + handle = self.read_handle + if handle is None: + handle = self.channel.begin( + 'read', time.monotonic() + 1, call=job.work_invocation, + acquisition=self.acquisition, child=self.workload, after=self.output_cursor) + self.read_handle = handle + try: + reply = self.channel.wait(handle, deadline, keep_pending=True) + except Failure as error: + if error.code != 'timeout': + self.read_handle = None + raise + self.read_handle = None + if 'data' in reply: + cursor = reply.get('cursor') + if type(cursor) is not int or cursor != self.output_cursor + 1: + raise Failure('invalid_vendor_response', 'Host returned an unexpected Cursor output cursor') + self.output.extend(base64.b64decode(reply['data'], validate=True)) + if len(self.output) > MAX_FRAME: + raise Failure('frame_too_large', 'Cursor emitted an oversized frame') + self.output_cursor = cursor + elif reply.get('eof'): + return None + else: + time.sleep(.01) + raise Failure('timeout', 'Cursor operation exceeded its deadline') + + def pending(self, job, token): + self._call('pending', job, token=token) + + def stop(self, job): + return self._call('stop', job) + + def detach(self, job): + self._call('detach', job) + + def finish(self, job): + self._call('finish', job) + + def close(self, job): + if self.read_handle is not None: + self.channel.discard(self.read_handle[0]) + self.read_handle = None + try: + receipt = self._call('retire', job) + except Failure as error: + if error.code not in ('timeout', 'vendor_effect_stale'): + raise + receipt = self._call('receipt', job) + if not all(receipt.get(flag) is True for flag in ('retired', 'probe_settled', 'workload_settled')): + raise Failure('cleanup_unconfirmed', 'Host could not confirm both Cursor child receipts') diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index badb804..7cc5d65 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -8,8 +8,8 @@ description = "Cursor Agent CLI automation plus an ACP-to-MCP adapter." [[dependencies]] id = "cursor-agent" commands = ["agent"] -instructions = "Install and authenticate Cursor Agent separately. This plugin never installs, updates, logs in, or copies Cursor credentials." -documentation = "https://cursor.com/docs/cli/overview" +instructions = "Install Cursor Agent separately and sign in on your computer using Cursor." +documentation = "https://cursor.com/docs/cli/reference/authentication" [[dependencies]] id = "python-runtime" @@ -17,6 +17,15 @@ commands = ["python3"] instructions = "Provide Python 3.13 or newer on the Computer MCP launch PATH. The plugin does not install Python." documentation = "https://www.python.org/downloads/" +[[permissions]] +id = "project" +access = "write" +purpose = "Open Cursor sessions and run requested project tasks and edits in owner-selected worktrees, including cancellation and native response delivery." + +[sandbox] +network = { level = "custom", hosts = ["api2.cursor.sh", "api5.cursor.sh"], include_trusted = false } +purpose = "Connect Cursor Agent to the official Cursor API and agent endpoints." + [[cli]] id = "agent" executable = { dependency = "cursor-agent" } @@ -29,6 +38,19 @@ transport = "stdio" executable = { path = "bin/cursor-mcp-adapter" } prefix = "cursor" capabilities = ["tools", "resources"] +requirements = { project = "write" } +tool_requirements = { "cursor.acp.session.prompt.result" = { project = "read" }, "cursor.acp.session.list" = { project = "read" }, "cursor.acp.events.read" = { project = "read" }, "cursor.acp.requests.list" = { project = "read" } } + +[mcp.vendor_execution] +dependency = "cursor-agent" +signature = "cursor-vendor-execution.json" + +[mcp.vendor_execution.files] +"bin/cursor-mcp-adapter" = "c2d54c86d558c9abc02062d2235e35435670aa7588206f46b8203de92aa57fa4" +"bin/cursor_vendor_execution.py" = "27478badaaf35e9c2499efdb4858ebeae048e7117b7d07377452b5d7e52bd2b3" +"bin/plugin_runtime.py" = "5a9f797bfca4b6ab31a9a648017fb1d09400593a9aab0d2250d426efa51f97cf" +"cli-tree.json" = "cc52c0bc7662f93d8596f715625d2ed274d05d95c681bac4d32c0faf273b64a3" +"cursor-vendor-execution.json" = "b50a088d4db85f42f2c4b9bd78fd26ee8b84e3009bdec0867beb60df2c738d2f" [[skills]] id = "cursor-agent" diff --git a/cursor-vendor-execution.json b/cursor-vendor-execution.json new file mode 100644 index 0000000..e9e44a4 --- /dev/null +++ b/cursor-vendor-execution.json @@ -0,0 +1,25 @@ +{ + "capability": "io.github.computer-mcp/vendor-execution-v1", + "dependency": "cursor-agent", + "tools": { + "cursor.acp.prompt": "acquire", + "cursor.acp.session.open": "acquire", + "cursor.acp.session.prompt": "prompt", + "cursor.acp.session.prompt.start": "detached_prompt", + "cursor.acp.session.prompt.result": "observe", + "cursor.acp.session.list": "observe", + "cursor.acp.session.mode": "mode", + "cursor.acp.session.cancel": "stop", + "cursor.acp.session.close": "close", + "cursor.acp.events.read": "observe", + "cursor.acp.requests.list": "observe", + "cursor.acp.requests.respond": "answer" + }, + "probe": [ + "--version" + ], + "workload": [ + "acp" + ], + "version_stdout": "2026.05.04-08e5280\n" +} diff --git a/docs/Architecture/Package.md b/docs/Architecture/Package.md index 0ae0cd8..1784f35 100644 --- a/docs/Architecture/Package.md +++ b/docs/Architecture/Package.md @@ -1,6 +1,6 @@ # Package architecture -The package is independently maintained and distributed. Computer MCP owns registration, authorization, project selection, CLI argument encoding and audit; this repository owns the Cursor CLI description and ACP-to-MCP translation. No host module, private database or optional Host Services callback is required. +The package is independently maintained and distributed. Computer MCP owns registration, authorization, project selection, CLI argument encoding and audit. This repository owns the Cursor CLI description, the reviewed vendor launch signature and ACP-to-MCP translation. `computer-mcp-plugin.toml` composes the file-backed CLI tree, the packaged stdio adapter and Skills. `cli-tree.json` is the sole native command/version description. Adapter request schemas remain vendor-specific rather than imposing an Agent framework on the host. @@ -13,6 +13,17 @@ Background threads and unconfirmed cleanup remain owned even after the creating tool returns. Host configuration generations and continuation routing remain host responsibilities. The resource does not introduce another task lifecycle. -The supervisor lifeline and cleanup receipt are private implementation channels, not plugin-host protocol extensions. Vendor subprocesses inherit neither channel nor host private descriptors. Explicit cleanup acknowledgement is separate from exit status. Runtime errors do not authorize retries or privilege escalation. +The managed adapter uses `bin/cursor_vendor_execution.py` to correlate the Host's +version probe, workload and cleanup receipts. The Host owns those processes. +Standalone execution uses the shared runtime's local supervisor and lifeline. +Vendor subprocesses do not inherit the managed channel or the local supervisor +lifeline. Explicit cleanup acknowledgment is separate from exit status. -Scripts provide deterministic packaging, non-model native interface checks and isolated unchanged-host integration checks. Tests exercise deterministic peers and lifecycle failures. The distribution excludes build/test/evidence files. No full native GUI, Windows backend or hosted API is claimed by this package. +Scripts provide deterministic packaging, non-model native interface checks and isolated exact-source consumer checks and separate archive identity checks. Tests exercise deterministic peers and lifecycle failures. The distribution excludes build/test/evidence files. No full native GUI, Windows backend or hosted API is claimed by this package. + +The manifest owns provider purposes and MCP caller default/exact-name requirements. +The host owns review, dual-authority admission, persistent provider containers, selected +worktrees and lifecycle. Source consumer fixtures use separate owner/admin and caller +profiles and generation-aware host lifecycle dispatch; they never import vendor login +state or authorize native choices. The offline sandbox declaration is omitted pending +native environment evidence and the owner's runtime decision. diff --git a/docs/Reference/Installation.md b/docs/Reference/Installation.md index 8883611..bfa6acb 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -4,52 +4,118 @@ The process supervisor requires the macOS `os.waitid` interface exposed by Python 3.13+. Older interpreters are rejected before any vendor process is started. -Install and authenticate Cursor separately. The native executable version must match `cli-tree.json`; its `executable_checks` are applied before CLI calls and before adapter execution. The package does not install/update a vendor, perform interactive login, or copy credentials. - -Provide Python 3.13 or newer as `python3` on the environment PATH that launches Computer MCP. The packaged executable uses `#!/usr/bin/env python3`. A host dependency binding alone does not rewrite this interpreter lookup. A supported interpreter is required even when the vendor executable is explicitly bound. - -Install the ZIP through Computer MCP's plugin UI or owner CLI. Installation is not activation or a permission grant. Use `plugins list/show` to obtain the current revision and installation identity. Review `Examples/settings.json`, replace its placeholder paths, then configure the plugin through the same UI or `plugins configure` command. The CLI dependency binding selects the vendor for the CLI contribution; the MCP launch `args` independently supply `--executable` for the adapter. These two choices should normally point to the same verified installation. +Install Cursor Agent separately and sign in on your computer using Cursor. +The plugin bridges Cursor Agent to Computer MCP. The installed provider runs +in a Host-provisioned container, so signing in on your computer does not +establish that Cursor Agent can use that session from the container. +[Cursor CLI authentication](https://cursor.com/docs/cli/reference/authentication) + +The native executable version must match `cli-tree.json`. Its `executable_checks` +apply before CLI calls and adapter execution. + +Provide Python 3.13 or newer. Computer MCP can resolve the declared `python-runtime` +dependency for the packaged adapter. A direct standalone launch uses the adapter's +`#!/usr/bin/env python3` shebang and the launch environment's PATH. + +Install the ZIP through the plugin UI or owner CLI of a Computer MCP host that +supports managed vendor execution. Installation is separate from activation and +permission review. Use `plugins list/show` to obtain the current revision and +installation identity. Review `Examples/settings.json`, replace its placeholder +path, then configure the plugin through the same UI or `plugins configure`. +The `cursor-agent` dependency binding selects one verified executable for the CLI +and managed ACP contributions. The example exposes this plugin's complete MCP tool catalog with no extra prefix. It is a host choice, not authorization embedded in the package. Authorize the desired tools/registration and project in the calling profile. Obtain projected CLI and MCP names from the actual host `tools/list`, rather than constructing names. `plugins doctor` checks files and configuration; an MCP connection check verifies initialization/catalog, not model execution. Computer MCP publishes plugin configuration changes to connected clients atomically. New calls use the current configuration; existing work keeps its owning runtime until release. Installation does not grant access, and later calls use current authorization. -No host binary replacement or host release is required. Do not restart the active development control connection merely to test installation. +Use the isolated checks below to verify a candidate without restarting the active +development control connection. ## Build ```sh -python3 -m unittest discover -s tests -p 'test_*.py' -v +python3 scripts/test_plugin.py /new/output/directory python3 scripts/validate_native.py --executable /absolute/path/to/agent -python3 scripts/build_package.py /new/output/directory ``` -The builder produces `cursor.zip` and prints an ID/version/SHA-256 receipt. Identical source bytes produce identical archive bytes. It refuses to overwrite a different existing artifact. The archive contains the manifest, canonical CLI tree, adapters, Skills, examples, manuals and notices. It excludes tests, build scripts, local evidence, caches and credentials. Only executable entrypoints receive executable mode. +The builder produces `cursor.zip` and prints an ID/version/SHA-256 receipt. Identical source bytes produce identical archive bytes. It refuses to overwrite a different existing artifact. The archive contains the manifest, canonical CLI tree, vendor launch signature, adapters, Skills, examples, manuals and notices. It excludes tests, build scripts, local evidence, caches and credentials. Only executable entrypoints receive executable mode. + +The ordinary CI command builds the ZIP first and exercises its shipped adapter +against deterministic peers with a clean environment. On macOS it then asks the +provisioned Host to install that ZIP and check a one-shot prompt through the +public gateway. Set `COMPUTER_MCP_TEST_HOST` to the fixture directory for +[the pinned Host revision](../../.github/computer-mcp-host.sha). Use +`--plugin-only` for the portable package and plugin checks. Native validation checks +the actual version, help, and required flags. ACP initialization without +authentication is a separate non-model protocol probe for Cursor. Full +authenticated prompt execution remains a separately authorized acceptance run. + +## Deterministic source consumer + +Use explicit clean host and plugin repository roots and full lowercase 40-character +commit SHAs. Choose a fresh absolute output path outside both checkouts and their +ancestors. The driver verifies both HEADs and clean status, exports committed sources +into the output directory, and injects the companion fixture into the isolated +host snapshot. It uses the real package identity, declaration review, provider grants, +separate consumer profiles and host-owned worktrees. No installed App, production control +socket or moving ref is used. The host test target must provide its +committed `FixedHostFixture`, permission fixtures and standalone generation API. -CI runs deterministic fixture tests and packaging; it does not install a vendor or invoke a model. Native validation checks the actual version/help and required flags only. ACP initialization without authentication is a separate non-model protocol probe for Cursor. Full authenticated prompt execution remains a separately authorized acceptance run because it can consume subscription/API usage and perform vendor actions. - -## Isolated host interoperability +```sh +python3 -m unittest discover -s tests/Interop -p 'test_*.py' +python3 scripts/validate_host_source.py --suite both \ + --host-source /absolute/path/to/host --host-sha FULL_HOST_SHA \ + --plugin-source /absolute/path/to/plugin-cursor --plugin-sha FULL_PLUGIN_SHA \ + --output /absolute/path/to/validation-runs/cursor-consumer-run +``` -After packaging, validate the exact ZIP against the reviewed Computer MCP binary. Select its release version explicitly; a mismatch fails before package extraction: +Replace both SHA placeholders with reviewed commits. The registered CI job uses +the plugin commit under test and fetches [the pinned Host SHA](../../.github/computer-mcp-host.sha) +from the public Host repository. The SHA must be publicly fetchable before CI can pass. +CI uses `--suite both` to build the staged Host's `ComputerMCPMacOSTests` +product with Swift Build and run both Cursor tests. The fixture serializes +independent cases that use the Host's synchronous worktree bridge and keeps +concurrent calls within the same case. CI uploads the shared Swift test log +and result XML alongside separate +`source/` and `vendor-stop/` directories with independent run IDs, case files +and receipts. +Python is the driver's current interpreter +(recorded with its hash); the host launch environment must independently supply Python +3.13+ for the adapter. The driver does not alter PATH or install dependencies. + +Fresh nonzero case evidence is required before a receipt can pass. The suite exercises +CLI, ACP and Skills, dual authority/read-versus-write admission, container persistence, +selected-worktree writes, protected sentinels, manual native responses, retained turns, +cancellation, scoped client revocation and host removal with joined process ownership. +The driver bounds subprocess groups and logs, removes source/build snapshots, and retains +only logs, case evidence and a pair-specific receipt. Failure receipts distinguish +export cleanup from unverified fixture-process cleanup. Source/runtime acceptance must +be run by the integration owner after the draft is committed; lint alone proves no +runtime behavior. + +Use `--suite source` or `--suite vendor-stop` to run a single test and write its +case file and receipt directly to the output directory. The source consumer +registers the development snapshot. The vendor-stop test builds the +archive from the staged plugin commit, installs it using the Host's archive +worker in an isolated fixture store, and records the archive digest. The driver +also checks that archive with the compiled Host CLI and saves the identity receipt +under `archive/` in the vendor-stop output. The test +exercises child acquisition, native settlement, pending permission cleanup, +independent retirement, lost start replies and closure during startup. + +## Packaged identity check + +After packaging, validate the exact ZIP through the selected host's bounded archive +worker. This checks extraction, manifest, signature and runtime file identity, executable mode and cache exclusion; +it does not establish package-principal runtime admission or container behavior. ```sh python3 scripts/validate_host.py \ - --host "/absolute/path/to/candidate/computer-mcp" \ - --expected-host-version X.Y.Z \ - --archive /output/PLUGIN.zip \ - --output /new/evidence/directory + --host /absolute/path/to/computer-mcp --expected-host-version X.Y.Z \ + --archive /output/cursor.zip --output /new/evidence/directory ``` -Replace `X.Y.Z` with the selected host's exact release version and `PLUGIN.zip` with the package's actual archive name. This uses a temporary directory and the selected host's archive worker and standalone MCP entrypoint. It does not connect to the production App's control socket or database. Vendor tool execution is replaced with inert fixtures; the native version/help check is a separate command. A new evidence directory is required to avoid overwriting an earlier run. - -For a candidate host implementing the provider-work contract, add -`--require-work-ownership`. This gate verifies the same connection retains an -opened session, a detached prompt waiting for input and an idle session, then -observes no owners after confirmed session close. It also checks that the -gateway does not reexport the downstream-only resource declaration. Hosts -without this observation surface can still run the ordinary interoperability -gate without that option. - A real ACP handshake can be checked independently, without authenticating, opening a conversation or invoking a model: ```sh @@ -58,4 +124,4 @@ python3 scripts/probe_acp.py --executable /absolute/path/to/agent --output /outp ## Result interpretation -Fixture success proves adapter protocol/ownership behavior against the tested peer, not a real account or model. A native version/help check proves the installed command surface, not backend availability. An unchanged-host isolated catalog/call check proves interoperability for that tested configuration; it is not production installation or public release evidence. Keep these results separate in delivery receipts. +Fixture success proves adapter protocol/ownership behavior against the tested peer, not a real account or model. A native version/help check proves the installed command surface, not backend availability. A clean-source consumer proves deterministic interoperability only for its recorded source pair; it is not production installation or public release evidence. Keep these results separate in delivery receipts. diff --git a/docs/Reference/Interface.md b/docs/Reference/Interface.md index 8196e53..d2bf965 100644 --- a/docs/Reference/Interface.md +++ b/docs/Reference/Interface.md @@ -8,6 +8,34 @@ The CLI contribution preserves the declared argv order, optional native flags an The MCP adapter implements standard newline-delimited JSON-RPC over stdio, with MCP initialization, tools/list, tools/call, ping and cancellation notifications. Supported MCP dates are 2024-11-05, 2025-03-26 and 2025-06-18. An unsupported proposed date receives the adapter's supported date rather than an unimplemented echo. Tool results use `structuredContent.result`; tool failures set `isError` and include an error code. Protocol errors remain JSON-RPC errors. Tool schemas are the callable source of truth. +## Reviewed provider and caller permissions + +The manifest requests provider Project write to open Cursor sessions and run requested +project tasks in owner-selected worktrees. MCP callers need Project write by default. +Exactly `cursor.acp.session.prompt.result`, `cursor.acp.session.list`, +`cursor.acp.events.read` and `cursor.acp.requests.list` require Project read. +These complete per-tool overrides replace the manifest default; host effect requirements +remain additive. Cancellation, close, mode and native-response delivery require write. +Both caller authority and provider authority must admit the effect. Plugin use alone +does not authorize project execution. Runtime metadata never sets caller requirements. +CLI invocation retains Project write plus Plugin use; Skills consumption retains Skills +plus Plugin use. Shipping a skill does not request provider Skills authority. + +The sandbox requests a custom network ceiling of `api2.cursor.sh` for Cursor +API requests and `api5.cursor.sh` for agent requests. The owner reviews that +ceiling at enablement and must approve updates that widen it. The owner may +narrow the selection, and Host policy limits effective access. Trusted +hosts are excluded and Full access defaults to off. +[Cursor ACP](https://cursor.com/docs/cli/acp) and +[Cursor network configuration](https://cursor.com/docs/enterprise/network-configuration#ip-allowlisting) + +The installed provider uses host-provisioned persistent container paths for +HOME, cache and state. Temporary storage is execution-local. + +The host selects the worktree, protects unrelated projects, host data and +other containers, and retires writers before removal. This adapter does not +request `projects-v1` or perform host lifecycle calls. + ## Host risk metadata Every MCP tool declares `_meta["io.github.computer-mcp/risk"]`. Model execution @@ -56,6 +84,25 @@ work. The adapter does not require resource subscriptions; hosts may poll. See the host's [provider work contract](https://github.com/computer-mcp/computer-mcp/blob/master/Documentation/Reference/MCPProtocol.md#downstream-provider-work) for acquisition expiry, snapshot validation and host-side uncertainty. +## Vendor execution + +Computer MCP runs the registered ACP contribution using the reviewed +`cursor-vendor-execution.json` signature. It selects the `cursor-agent` +dependency, verifies the version probe, and owns the separate probe and +workload children for each acquisition. The adapter negotiates the private +vendor channel before advertising managed execution. Managed startup requires +that channel and does not fall back to launching a local child. Standalone +stdio clients use the local supervisor and select the executable through +`--executable`, `CURSOR_AGENT_EXECUTABLE`, or PATH. + +The adapter initializes ACP and calls `authenticate` with the advertised +`cursor_login` method so Cursor Agent can use its existing sign-in before the +adapter creates or loads a session. An authentication RPC rejection stops setup. +The adapter reports `authentication_required` for ACP Authentication Required +(`-32000`) and `vendor_error` for other authentication rejections. Both include +the numeric RPC code and omit the vendor message and data. [Cursor ACP](https://cursor.com/docs/cli/acp) · +[ACP error codes](https://agentclientprotocol.com/protocol/v1/schema#errorcode) + ## Tools | Native MCP tool | Behavior | @@ -89,13 +136,25 @@ The default permission policy is `reject-once`. Explicit `allow-once`/`allow-alw Question answers must use the offered question and option IDs and obey single/multiple selection. Plans accept `accepted`, `rejected` or `cancelled` and their documented optional fields. Duplicate, stale and unoffered replies fail. Each request is bound to its active native operation and session; response delivery and operation retirement are serialized. Unknown vendor requests receive method-not-found, not fabricated success. +A definitive Host refusal before writing returns `response_refused`. The active +turn retains ownership of its pending request through stop or completion. +Unknown delivery returns `response_unknown` and retires the affected session +without replaying the answer. + ## Bounds, cancellation and failures An ACP frame is bounded to 1 MiB before waiting for a newline. Event retention is bounded by both 256 events and 256 KiB. Text accumulation and its serialized JSON value are each bounded to 128 KiB; omissions/truncation are reported. Pages use absolute cursors, `next_cursor`, `has_more` and `missed_events`. An event larger than the requested page becomes explicit omission metadata so pagination can progress. Responses retain the bounded native prompt result; absent stopReason is an error, and native cancellation is not successful task completion. -Prompts default to 300 seconds and accept up to 1800 seconds. Session setup defaults to 45 seconds. Transport startup and cleanup can add bounded latency. Pending requests expire with their native operation. Cancellation sends ACP session/cancel, waits for native settlement, and retires the owned process if it cannot settle within its grace period. A cancelled background request is not automatically replayed. Cancelling the start call after it returned does not identify the background task: use the returned session/prompt handle. +Prompts default to 300 seconds and accept up to 1800 seconds. Session setup defaults to 45 seconds. Transport startup and cleanup can add bounded latency. Pending requests expire with their native operation. Cancellation of a dispatched prompt sends ACP `session/cancel` once and waits up to two seconds for the correlated reply. The adapter preserves a native cancellation, a completion that won the race, or a native error. A settled cancellation or completion permits session reuse. A correlated managed prompt error also leaves the session available. If managed cancellation cannot settle within the grace period, the adapter retires the affected session and reports `cancellation_unsettled`. A cancelled background request is not automatically replayed. To cancel background work after the start call returns, select its session handle. -The private supervisor observes adapter EOF/termination and owns the vendor process group. It retains the leader until termination and reaping, then sends a separate bounded cleanup acknowledgement. Missing acknowledgement is `cleanup_unconfirmed`, never a clean success inferred from exit alone. A session with unconfirmed cleanup remains retained and counts against admission capacity; repeating close cannot erase the failure. Escaped, independently reparented processes are not claimed as owned. Host callback descriptors/COMPUTER_MCP metadata are not forwarded to the vendor. The process working directory is not an OS sandbox. +For managed execution, the Host supplies cleanup receipts for both child phases. +An unconfirmed start is reconciled against its existing reservation. Standalone +execution uses a private supervisor that observes adapter EOF or termination. +It retains the process group leader until termination and reaping, then sends +a separate cleanup acknowledgment. A session with unconfirmed cleanup remains +charged against capacity. Vendor processes receive neither the private channel +nor reserved Host environment metadata. The working directory alone provides +no sandbox enforcement. Representative errors include invalid_arguments, unknown_session, busy, incompatible_vendor, vendor_failed, invalid_vendor_response, frame_too_large, result_too_large, timeout, cancelled and cleanup_unconfirmed. Failed/unknown writes are not automatically retried. Native output may contain sensitive user content; callers must handle it accordingly. diff --git a/docs/Reference/Release.md b/docs/Reference/Release.md index 0cae108..35cde13 100644 --- a/docs/Reference/Release.md +++ b/docs/Reference/Release.md @@ -3,7 +3,8 @@ Release status: [CI](https://github.com/computer-mcp/plugin-cursor/blob/master/.github/workflows/ci.yml) builds candidate archives on pull requests, `master` pushes and manual runs. [`release.yml`](https://github.com/computer-mcp/plugin-cursor/blob/master/.github/workflows/release.yml) -implements dry runs and publication; native and host acceptance are manual. +requires exact-pair Host interoperability for dry runs and publication. +Native version/help and ACP initialization are separate acceptance checks. The organization [VERSIONING](https://github.com/computer-mcp/.github/blob/master/VERSIONING.md) owns version rules, including tags, version choice and the changelog. This @@ -18,7 +19,8 @@ describes workflow verification and recovery. | --- | --- | --- | --- | --- | | `cursor.zip` plugin package | Package version | `version` in [`computer-mcp-plugin.toml`](../../computer-mcp-plugin.toml) | adapter `--version`, builder receipt, release tag, `release-receipt.json`, catalog entry | Edit the manifest; `tests/test_package.py` checks the packaged adapter's `--version` | -The archive contains the manifest, `cli-tree.json`, `bin/`, `skills/`, the README, +The archive contains the manifest, `cli-tree.json`, `cursor-vendor-execution.json`, +`bin/`, `skills/`, the README, contribution guide, license, notices, `docs/`, `Examples/`, and the README images `.github/assets/logo/logo-light.png` and `.github/assets/logo/logo-dark.png`. Tests, build scripts and workflows are excluded from the archive. @@ -60,8 +62,10 @@ Adapter and probe callers extract the native assertion from the CLI tree with ## Candidate, Acceptance and Publication -Publication depends on the repository's GitHub release immutability setting. -The shared workflow checks that setting before writing a Release. +The release workflow verifies the package against the tagged source and accepted +CI artifact. After the workflow finishes, maintainers can replace release +attachments under this repository's [versioning policy](https://github.com/computer-mcp/plugin-cursor/blob/master/VERSIONING.md). +Consumers that pin an archive digest must approve the replacement digest. ### Publish @@ -69,23 +73,24 @@ The shared workflow checks that setting before writing a Release. and that the reviewed `master` commit has successful `ci.yml` from a `push`. Its exact archive artifact name is `cursor-plugin--3.13`. 2. Dispatch `.github/workflows/release.yml` with `ref` set to that full commit - SHA and `publish: false` (the default). The pinned organization workflow - runs `python3 scripts/build_package.py` with an output-directory argument, + SHA and `publish: false` (the default). The preflight tests that commit with + the pinned Host. The pinned organization workflow rebuilds the same commit + using `python3 scripts/build_package.py` with an output-directory argument, verifies the CI source and artifact digest, and requires the rebuilt `cursor.zip` to match the CI archive byte for byte. 3. Inspect the `plugin-release--` Actions artifact. Its `assets/` directory contains `cursor.zip`, the generated `release-receipt.json` and `SHA256SUMS`. An untagged dry run reports the signed annotated tag still needed for publication. -4. Run the native version/help, ACP initialization and isolated host checks in - [Installation](Installation.md#isolated-host-interoperability) against that - exact archive. Record the manual acceptance results and their limits in the +4. Run the native version/help and ACP initialization checks in + [Installation](Installation.md#packaged-identity-check). Record the manual + acceptance results and their limits in the draft Release notes. Create and push the version tag that [VERSIONING](https://github.com/computer-mcp/.github/blob/master/VERSIONING.md) requires on the accepted commit, and target the draft Release at that full commit SHA. 5. Dispatch `release.yml` with `ref` set to that version tag and `publish: true`. - The workflow verifies the tag signature and manifest version, repeats the - source and archive checks, completes and verifies the draft assets, and + The workflow repeats exact-pair interoperability for the tag, verifies the + tag signature and manifest version, compares archive bytes, and verifies the draft assets before it publishes. Its dependent notifier runs only when `publish` is true and the shared workflow reports `published: true`. @@ -136,10 +141,10 @@ acceptance record. | Operation | Existing command or explicit manual procedure | Required access | | --- | --- | --- | -| Version update and check | Edit `computer-mcp-plugin.toml`; `python3 -m unittest discover -s tests -p 'test_*.py'` | Local checkout | -| Candidate validation and build | `ci.yml`; locally `python3 scripts/build_package.py dist` | CI or local checkout | +| Version update and check | Edit `computer-mcp-plugin.toml` and run `python3 scripts/test_plugin.py dist` | Local checkout | +| Candidate validation and build | `ci.yml` or locally `python3 scripts/test_plugin.py dist` | CI or local checkout | | Native acceptance | `python3 scripts/validate_native.py --executable `; `python3 scripts/probe_acp.py --executable --output ` | User-installed native executable | -| Exact archive host acceptance | `python3 scripts/validate_host.py --host --expected-host-version X.Y.Z --archive dist/cursor.zip --output `; see [Installation](Installation.md#isolated-host-interoperability) | Selected host binary and candidate archive | +| Exact archive host acceptance | `python3 scripts/validate_host.py --host --expected-host-version X.Y.Z --archive dist/cursor.zip --output `; see [Installation](Installation.md#packaged-identity-check) | Selected host binary and candidate archive | | Acceptance and publication | Manual checks above; dispatch `release.yml`, dry run first | Repository Actions; publication also needs a signing key and release write access | | Status and interrupted-run recovery | Inspect CI or `release.yml`; follow [Retry](#retry) | Repository Actions | | Cleanup | Delete obsolete output and evidence under ignored `dist/`, and `package-receipt.json` | Local checkout | @@ -152,11 +157,11 @@ per-artifact retention override. ### Retry -For a failed publication, use **Re-run failed jobs**. Recovery preserves the -receipt's frozen CI provenance and retains matching draft assets. Follow the +For a failed publication, use **Re-run failed jobs**. The publish job can +reuse its verified bundle. A fresh verification reconstructs the receipt from +the selected CI artifact and retains matching draft assets. Follow the organization's [release recovery guide](https://github.com/computer-mcp/github-workflows/blob/master/docs/plugin-release.md#run-and-recover) -for conflicts or unavailable source artifacts. Published releases are verified -without changing their assets. +for conflicts or unavailable source artifacts. For a missed or failed notification, rerun only the notifier or dispatch: diff --git a/scripts/build_package.py b/scripts/build_package.py index a7a4821..47b0c35 100644 --- a/scripts/build_package.py +++ b/scripts/build_package.py @@ -19,6 +19,7 @@ *README_ASSETS, "computer-mcp-plugin.toml", "cli-tree.json", + "cursor-vendor-execution.json", "bin", "skills", "README.md", diff --git a/scripts/test-interop.sh b/scripts/test-interop.sh new file mode 100644 index 0000000..329d88f --- /dev/null +++ b/scripts/test-interop.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +exec python3 -B scripts/validate_host_source.py --suite both \ + --host-source "${1:?Host checkout}" --host-sha "${2:?Host commit}" \ + --plugin-source "$PWD" --plugin-sha "$(git rev-parse HEAD)" \ + --output "${3:?Evidence directory}" --timeout 1200 diff --git a/scripts/test_plugin.py b/scripts/test_plugin.py new file mode 100644 index 0000000..9e7d702 --- /dev/null +++ b/scripts/test_plugin.py @@ -0,0 +1,74 @@ +"""Build and test the Cursor archive, including the provisioned Host smoke on macOS.""" + +import argparse +from contextlib import contextmanager, ExitStack +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parent.parent + + +@contextmanager +def host_smoke_command(python, archive): + directory = os.environ.get("COMPUTER_MCP_TEST_HOST") + if not directory: + raise ValueError("Set COMPUTER_MCP_TEST_HOST to the provisioned macOS Host fixture.") + verifier = Path(directory).resolve() / "verify-package.py" + if not verifier.is_file(): + raise ValueError(f"Cannot find the provisioned Host verifier at {verifier}.") + + revision = (ROOT / ".github/computer-mcp-host.sha").read_text().strip() + if not re.fullmatch(r"[0-9a-f]{40}", revision) or revision == "0" * 40: + raise ValueError("The Host pin must be a full lowercase commit SHA.") + + fixtures = ROOT / "tests/Fixtures" + runtime = Path(python[0]).resolve() + # The Host gives the vendor a fixed PATH. Bind its test peer to the same + # interpreter as the adapter so the sandbox can admit the actual executable. + source = (fixtures / "vendor.py").read_bytes().split(b"\n", 1)[1] + with tempfile.TemporaryDirectory(prefix="host-smoke-", dir=archive.parent) as directory: + vendor = Path(directory) / "cursor-agent" + vendor.write_bytes(f"#!{runtime}\n".encode() + source) + vendor.chmod(0o700) + yield [ + *python, str(verifier), "--host-revision", revision, "--archive", str(archive), + "--case", str(fixtures / "package-smoke.json"), + "--bind", "cursor-agent", str(vendor), + "--bind", "python-runtime", str(runtime), + ] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output_directory", type=Path) + parser.add_argument("--plugin-only", action="store_true", + help="run only the portable package and plugin tests") + args = parser.parse_args() + output = args.output_directory.resolve() + archive = output / "cursor.zip" + python = [sys.executable, "-B"] + receipt = subprocess.check_output( + [*python, str(ROOT / "scripts/build_package.py"), str(output)], cwd=ROOT) + with ExitStack() as stack: + smoke = None + if sys.platform == "darwin" and not args.plugin_only: + try: + smoke = stack.enter_context(host_smoke_command(python, archive)) + except (OSError, ValueError) as error: + parser.error(str(error)) + + environment = dict(os.environ, CURSOR_TEST_ARCHIVE=str(archive)) + subprocess.run( + [*python, "-m", "unittest", "discover", "-s", "tests", "-p", "test_*.py"], + cwd=ROOT, env=environment, check=True) + if smoke is not None: + subprocess.run(smoke, cwd=ROOT, stdout=sys.stderr, check=True) + sys.stdout.buffer.write(receipt) + + +if __name__ == "__main__": + main() diff --git a/scripts/validate_host.py b/scripts/validate_host.py index 2494cdd..ca47e73 100644 --- a/scripts/validate_host.py +++ b/scripts/validate_host.py @@ -1,8 +1,8 @@ """Validate an exact plugin archive against an unchanged, isolated host binary. -Uses the host's bounded archive worker and standalone MCP runtime. It never +Uses only the host's bounded archive worker. It never connects to production control sockets, registers a production plugin, loads -production credentials, or invokes a real model. Runtime calls use fixtures. +production credentials, or invokes a vendor. """ import argparse import datetime @@ -10,16 +10,12 @@ import json import os from pathlib import Path -import shutil import subprocess import sys import tempfile -import time import tomllib ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / 'tests')) -from support import Client def require(condition, message): @@ -40,82 +36,12 @@ def capture(arguments, cwd, environment, timeout=30): return result.stdout -def checked(client, name, arguments=None): - response = client.call(name, arguments or {}, timeout=20) - require('error' not in response and not response['result'].get('isError'), - 'Tool failed: ' + name + '\n' + json.dumps(response)[:8192]) - return Client.value(response) - - -def wait_for(callback, predicate, seconds=15): - deadline = time.monotonic() + seconds - while time.monotonic() < deadline: - value = callback() - if predicate(value): - return value - time.sleep(.03) - raise AssertionError('Isolated execution did not reach its postcondition') - - -def configuration(package, project, cli_fixture, acp_fixture, vendor, readonly=False): - quote = json.dumps - return f'''schema_version = 1 -[server] -name = "plugin-contract-validation" -[runtime] -caller = "local-mcp" -profile = "validation" -project_id = "primary" -[policy] -default_timeout_ms = 15000 -max_output_bytes = 1048576 -shell_enabled = true -[[profiles]] -id = "validation" -mode = "{'read-only' if readonly else 'local-full-access'}" -confirmation_policy = "never" -capabilities = ["*"] -projects = ["primary"] -allowed_callers = ["local-mcp"] -full_shell_enabled = {'false' if readonly else 'true'} -[[projects]] -id = "primary" -display_name = "Isolated fixture project" -path = {quote(str(project))} -[[cli.commands]] -id = "fixture-cli" -executable = {quote(str(cli_fixture))} -allow_any_args = false -tree = {{ kind = "file", path = {quote(str(package / 'cli-tree.json'))} }} -[[mcp.servers]] -id = "fixture-adapter" -transport = "stdio" -command = {quote(str(package / f'bin/{vendor}-mcp-adapter'))} -args = ["--executable", {quote(str(acp_fixture))}] -exposure = "reexport" -prefix = "" -allow_any_tool = true -capabilities = ["tools"] -startup_timeout_ms = 10000 -request_timeout_ms = 20000 -[skills] -enabled = true -[[skills.roots]] -id = "fixture-skills" -path = {quote(str(package / 'skills'))} -[builtin] -enabled = [] -''' - - -def validate(host, archive, output, expected_host_version, require_work_ownership=False): +def validate(host, archive, output, expected_host_version): host = host.resolve(strict=True) archive = archive.resolve(strict=True) output.mkdir(parents=True, exist_ok=False) manifest = tomllib.loads((ROOT / 'computer-mcp-plugin.toml').read_text()) vendor = manifest['id'] - tree = json.loads((ROOT / 'cli-tree.json').read_text()) - expected_version = next(c['stdout'] for c in tree['executable_checks'] if c['args'] == ['--version']) host_hash = digest(host) archive_hash = digest(archive) checks = {} @@ -141,117 +67,20 @@ def validate(host, archive, output, expected_host_version, require_work_ownershi 'Extracted manifest differs from source') require((package / 'cli-tree.json').read_bytes() == (ROOT / 'cli-tree.json').read_bytes(), 'Extracted CLI contract differs from source') + for path in ('cursor-vendor-execution.json', 'bin/cursor_vendor_execution.py', + 'bin/plugin_runtime.py', 'bin/cursor-mcp-adapter'): + require((package / path).read_bytes() == (ROOT / path).read_bytes(), + f'Extracted managed execution file differs from source: {path}') require(os.access(package / f'bin/{vendor}-mcp-adapter', os.X_OK), 'Host extraction lost executable mode') checks['archive_and_manifest'] = 'passed' require(not list(package.rglob('*.pyc')) and not list(package.rglob('__pycache__')), 'Archive contains Python cache') - project = work / 'project' - project.mkdir() - version_file = work / 'version.txt' - version_file.write_text(expected_version) - cli_fixture = work / 'native-cli-fixture' - cli_fixture.write_text('#!' + sys.executable + '\nimport json,sys\nfrom pathlib import Path\n' - + 'if sys.argv[1:]==["--version"]:\n print(Path(' + repr(str(version_file)) + ').read_text(),end="")\n' - + 'else:\n print(json.dumps({"argv":sys.argv[1:],"stdin":sys.stdin.read()}))\n') - cli_fixture.chmod(0o755) - config = work / 'gateway.toml' - config.write_text(configuration(package, project, cli_fixture, ROOT / 'tests/Fixtures/vendor.py', vendor)) - checked_config = capture([str(host), 'config', 'validate', '--config', str(config)], work, environment) - (output / 'configuration-validation.txt').write_bytes(checked_config) - client = Client(str(project), environment, [str(host), 'serve', 'stdio', '--config', str(config)]) - try: - catalog = client.request('tools/list')['result']['tools'] - (output / 'catalog.json').write_text(json.dumps(catalog, indent=2)+'\n') - projected = [tool for tool in catalog if tool.get('_meta', {}).get('cli', {}).get('command') == 'print'] - require(len(projected) == 1, 'Expected one real host-projected print tool') - native_names = [tool['name'] for tool in catalog if tool['name'].startswith(vendor + '.')] - require(len(native_names) == 12, 'Adapter catalog missing required tools') - checks['catalog'] = {'status':'passed', 'cli_tools':len(projected), 'mcp_tools':len(native_names)} - if require_work_ownership: - require(all(key not in tool.get('_meta',{}) for tool in catalog - for key in ('io.github.computer-mcp/work','io.github.computer-mcp/continuation')), - 'Gateway exports advertise downstream-only ownership metadata') - def work_status(count): - def observe(): - servers = checked(client,'mcp.servers.status',{'server':'fixture-adapter'})['servers'] - value = servers[0]['connection'].get('provider_work') - require(isinstance(value,dict), 'Candidate host does not expose provider-work observation') - return value - return wait_for(observe, lambda value:value['resource_count']==count - and value['unsettled_invocation_count']==0 and not value['observation_pending']) - prompt = "--leading 'quotes' 中文\nnot-a-shell-command" - arguments = {'prompt': prompt} - result = checked(client, projected[0]['name'], arguments) - argv = result['data']['argv'] - require(argv[-2:] == ['--', prompt], 'Host did not preserve exact argv argument boundaries') - require(result['exit_code'] == 0, 'CLI result did not capture exit status') - checks['cli_argv_and_json'] = 'passed' - invalid = client.call(projected[0]['name'], dict(arguments, unknown_argument=True)) - require('error' in invalid or invalid['result'].get('isError'), 'Unknown CLI arguments were accepted') - version_file.write_text('incompatible-fixture-version\n') - mismatch = client.call(projected[0]['name'], arguments) - require('error' in mismatch or mismatch['result'].get('isError'), 'Incompatible CLI version was executed') - version_file.write_text(expected_version) - bypass = client.call('cli.exec', {'id':'fixture-cli', 'argv':['--help']}) - require('error' in bypass or bypass['result'].get('isError'), 'Raw execution bypassed the CLI tree') - checks['cli_negative_contracts'] = 'passed' - - session = checked(client, 'cursor.acp.session.open', {'permission_policy':'manual'})['session'] - work_evidence = {'opened':work_status(1)} if require_work_ownership else None - run = checked(client, 'cursor.acp.session.prompt.start', {'session':session,'prompt':'permission'})['prompt_id'] - pending = wait_for(lambda: checked(client, 'cursor.acp.requests.list', {'session':session}), lambda v: bool(v['requests']))['requests'][0] - if work_evidence is not None: work_evidence['waiting_for_input'] = work_status(1) - checked(client, 'cursor.acp.requests.respond', {'session':session,'request_id':pending['request_id'], - 'response':{'outcome':{'outcome':'selected','optionId':'opaque-no'}}}) - completed = wait_for(lambda: checked(client, 'cursor.acp.session.prompt.result', {'session':session,'prompt_id':run}), lambda v:v.get('completed')) - require(not completed.get('is_error'), 'Background ACP fixture failed') - if work_evidence is not None: work_evidence['idle_session'] = work_status(1) - checked(client, 'cursor.acp.events.read', {'session':session,'max_bytes':2048}) - checked(client, 'cursor.acp.session.close', {'session':session}) - require(not checked(client, 'cursor.acp.session.list')['sessions'], 'Closed ACP session remains live') - if work_evidence is not None: - work_evidence['released'] = work_status(0) - require(len({state['instance_id'] for state in work_evidence.values()})==1, - 'Provider connection changed during session ownership acceptance') - checks['provider_work'] = work_evidence - checks['mcp_execution_and_events'] = 'passed' - finally: - client.close() - checks['standalone_shutdown'] = 'passed' - config.write_text(configuration(package, project, cli_fixture, ROOT / 'tests/Fixtures/vendor.py', vendor, readonly=True)) - client = Client(str(project), environment, [str(host), 'serve', 'stdio', '--config', str(config)]) - try: - readonly_tools = client.request('tools/list')['result']['tools'] - require(not any(tool.get('_meta',{}).get('cli') for tool in readonly_tools), 'Read-only profile exposed arbitrary CLI execution') - require(not any(tool['name'].startswith(vendor+'.') for tool in readonly_tools), 'Read-only profile exposed vendor execution') - finally: - client.close() - checks['read_only_profile'] = 'passed' - restricted = configuration(package, project, cli_fixture, ROOT / 'tests/Fixtures/vendor.py', vendor) - restricted = restricted.replace('mode = "local-full-access"', 'mode = "project-operations"') - restricted = restricted.replace('full_shell_enabled = true', 'full_shell_enabled = false') - execution_tool = 'cursor.acp.prompt' - # An explicit low host risk must not bypass the publisher's execution floor. - restricted += '\n[mcp.servers.tool_risks]\n' + json.dumps(execution_tool) + ' = "read-only"\n' - config.write_text(restricted) - client = Client(str(project), environment, [str(host), 'serve', 'stdio', '--config', str(config)]) - try: - tools = client.request('tools/list')['result']['tools'] - require(execution_tool not in {tool['name'] for tool in tools}, 'Restricted profile exposed arbitrary vendor execution') - checked(client, 'cursor.acp.session.list') - for name, arguments in [(execution_tool, {'prompt':'must-not-execute'}), - ('mcp.tools.call', {'server':'fixture-adapter','tool':execution_tool,'arguments':{'prompt':'must-not-execute'}})]: - denied = client.call(name, arguments) - require('error' in denied or denied['result'].get('isError'), 'Restricted profile admitted vendor execution') - finally: - client.close() - checks['publisher_floor_under_restricted_profile'] = 'passed' require(digest(host) == host_hash and digest(archive) == archive_hash, 'Host or archive changed during acceptance') report = {'status':'passed', 'observed_at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'plugin_id':vendor, 'plugin_version':manifest['version'], 'host_version':version, 'expected_host_version':expected_host_version, 'host_sha256':host_hash, 'archive_sha256':archive_hash, 'checks':checks, - 'scope':'host archive validation and ordinary standalone registrations with inert vendor fixtures', + 'scope':'host archive worker and package identity only; runtime acceptance uses validate_host_source.py', 'production_installation':False, 'authenticated_model_execution':False, 'host_database_or_control_socket_used':False} (output / 'acceptance.json').write_text(json.dumps(report, indent=2)+'\n') @@ -265,10 +94,8 @@ def main(): help='Exact reviewed host release version, for example 1.3.0') parser.add_argument('--archive', required=True, type=Path) parser.add_argument('--output', required=True, type=Path) - parser.add_argument('--require-work-ownership', action='store_true', - help='Require a candidate host to observe session ownership through final release') args = parser.parse_args() - validate(args.host, args.archive, args.output, args.expected_host_version, args.require_work_ownership) + validate(args.host, args.archive, args.output, args.expected_host_version) if __name__ == '__main__': diff --git a/scripts/validate_host_source.py b/scripts/validate_host_source.py new file mode 100644 index 0000000..5f5079f --- /dev/null +++ b/scripts/validate_host_source.py @@ -0,0 +1,505 @@ +"""Run the deterministic Cursor companion against explicit clean source commits. + +The driver exports both commits into a fresh external run directory. It never edits +input checkouts, contacts an installed App or launches the vendor's executable. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import sys +import tarfile +import time +import xml.etree.ElementTree as ET + +FIXTURE = "CursorSourceIntegrationTests.swift" +TEST_PRODUCT = "ComputerMCPMacOSTests" +CASES = { + "package", "declarations", "dual-authority", "cli", "mcp", "skills", + "worktree", "container", "boundaries", "continuation", "cancellation", + "scoped-revocation", "host-removal", "cleanup", +} +VENDOR_CASES = { + "dual-authority", "cold-warm-ownership", "seatbelt-boundaries", "ordinary-cancel", + "native-result-races", "pending-answer-cancel", "forced-stop-isolation", "startup-cancellation", + "lost-start-reply", "pending-start-closure", "cleanup", +} +SELECTORS = { + "source": "CursorSourceIntegrationTests/sourceConsumer", + "vendor-stop": "CursorSourceIntegrationTests/registeredVendorStop", +} +INPUTS = ( + "computer-mcp-plugin.toml", "tests/Fixtures/" + FIXTURE + ".txt", + "tests/Fixtures/vendor.py", "tests/Fixtures/vendor_start_transport.py", + "scripts/validate_host_source.py", + "bin/cursor-mcp-adapter", "bin/plugin_runtime.py", "cli-tree.json", + "bin/cursor_vendor_execution.py", "cursor-vendor-execution.json", + "scripts/build_package.py", "scripts/validate_host.py", +) + + +def digest(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def revision(value): + if not re.fullmatch(r"[0-9a-f]{40}", value): + raise argparse.ArgumentTypeError("Use a full lowercase 40-character commit SHA") + return value + + +def absolute(value): + path = Path(value) + if not path.is_absolute(): + raise argparse.ArgumentTypeError("Use an absolute path") + return path.resolve() + + +def git(root, *arguments): + return subprocess.check_output( + ["git", "-C", str(root), *arguments], text=True, + stderr=subprocess.PIPE, timeout=15).strip() + + +def verify_source(root, sha): + revision(sha) + if not root.is_dir() or git(root, "rev-parse", "--show-toplevel") != str(root): + raise ValueError("Source must be an existing repository root") + if git(root, "rev-parse", "HEAD") != sha: + raise ValueError("Source HEAD differs from its supplied commit") + if git(root, "status", "--porcelain=v1", "--untracked-files=all"): + raise ValueError("Source checkout must be clean, including untracked files") + + +def contains(parent, child): + return child == parent or parent in child.parents + + +def location_contains(parent, child): + if contains(parent, child): + return True + try: + parent_info = parent.stat() + except FileNotFoundError: + return False + # A fresh output can have missing components beneath an existing ancestor. + for path in (child, *child.parents): + try: + path_info = path.stat() + except FileNotFoundError: + continue + if os.path.samestat(parent_info, path_info): + return True + return False + + +def validate_locations(host, plugin, output): + if location_contains(host, plugin) or location_contains(plugin, host): + raise ValueError("Host and plugin must be separate, non-nested source checkouts") + if not output.is_absolute(): + raise ValueError("Output must be an absolute path") + if output.is_symlink(): + raise ValueError("Output must be a new external directory") + output = output.resolve() + if any(location_contains(root, output) or location_contains(output, root) for root in (host, plugin)): + raise ValueError("Output must be outside both source checkouts and their ancestors") + if output.exists(): + raise ValueError("Output must be a new external directory") + return output + + +def run_process(command, cwd, environment, log, timeout, *, exit_codes=(0,)): + """Bound execution/output and reap the driver-owned command group on every exit.""" + with log.open("wb") as stream: + process = subprocess.Popen( + command, cwd=cwd, env=environment, stdout=stream, + stderr=subprocess.STDOUT, start_new_session=True) + deadline = time.monotonic() + timeout + failure = None + try: + while process.poll() is None: + if time.monotonic() >= deadline: + raise TimeoutError("Command exceeded its deadline") + if log.stat().st_size > 32 * 1024 * 1024: + raise RuntimeError("Command exceeded its 32 MiB output bound") + time.sleep(0.05) + if process.returncode not in exit_codes: + raise RuntimeError(f"Command exited {process.returncode}; inspect {log}") + except BaseException as error: + failure = error + finally: + try: + try: + os.killpg(process.pid, 0) + except ProcessLookupError: + pass + else: + os.killpg(process.pid, signal.SIGKILL) + if failure is None: + failure = RuntimeError("Command left descendants; its group was terminated") + finally: + process.wait(timeout=5) + if failure: + raise failure + if log.stat().st_size > 32 * 1024 * 1024: + raise RuntimeError("Command exceeded its 32 MiB output bound") + return process.returncode + + +def extract_source(archive, destination): + """Export only bounded regular files and directories into a fresh directory.""" + if archive.stat().st_size > 128 * 1024 * 1024: + raise ValueError("Source archive exceeds 128 MiB") + destination.mkdir() + total = 0 + with tarfile.open(archive, "r:") as source: + for index, entry in enumerate(source): + target = destination / entry.name + if (index >= 20000 or entry.name.startswith("/") + or ".." in Path(entry.name).parts or not contains(destination, target) + or not (entry.isdir() or entry.isfile())): + raise ValueError("Unsafe or oversized source archive") + total += entry.size + if total > 128 * 1024 * 1024: + raise ValueError("Expanded source exceeds 128 MiB") + if entry.isdir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + with source.extractfile(entry) as incoming, target.open("xb") as outgoing: + shutil.copyfileobj(incoming, outgoing) + target.chmod(0o755 if entry.mode & 0o111 else 0o644) + + +def export_source(root, sha, destination, environment, output): + archive = output / (destination.name + ".tar") + try: + run_process( + ["git", "-C", str(root), "archive", "--format=tar", "--output", str(archive), sha], + output, environment, output / (destination.name + "-export.log"), 30) + extract_source(archive, destination) + finally: + archive.unlink(missing_ok=True) + + +def validate_evidence(observed, run_id, expected_cases=CASES): + if not isinstance(observed, dict): + raise ValueError("Consumer case evidence must be an object") + cases = observed.get("cases") + if (observed.get("kind") != "deterministic" or observed.get("run_id") != run_id + or type(observed.get("tests_executed")) is not int or observed["tests_executed"] < 1 + or not isinstance(cases, list) or len(cases) != len(expected_cases) + or any(not isinstance(case, str) for case in cases) or set(cases) != expected_cases): + raise ValueError("Consumer case evidence is incomplete, duplicated or stale") + + +def validate_acquisitions(rows): + if not isinstance(rows, list) or len(rows) != 2 or any(not isinstance(row, dict) for row in rows): + raise ValueError("Host did not record the cold and warm Cursor acquisitions") + + def root(row, phase): + pid = row.get(f"{phase}_pid") + identity = row.get(f"{phase}_identity") + if (type(pid) is not int or pid <= 0 or not isinstance(identity, str) + or not re.fullmatch(r"[1-9][0-9]{0,19}", identity)): + raise ValueError("Cursor acquisition is missing a durable process identity") + return pid, identity + + cold, warm = rows + adapter = root(cold, "adapter") + if root(warm, "adapter") != adapter or warm.get("adapter_child") != cold.get("adapter_child"): + raise ValueError("Warm Cursor acquisition did not reuse the cold adapter") + roots = [adapter] + ids = [cold.get("adapter_child")] + for row in rows: + proofs = row.get("authorization_ids") + if not isinstance(proofs, list) or len(proofs) != 2: + raise ValueError("Cursor acquisition is missing caller or provider authority") + ids.extend([row.get("execution"), *proofs]) + for phase in ("probe", "workload"): + roots.append(root(row, phase)) + ids.append(row.get(f"{phase}_child")) + if (len(set(roots)) != len(roots) + or any(not isinstance(value, str) or not re.fullmatch( + r"[0-9A-F]{8}-(?:[0-9A-F]{4}-){3}[0-9A-F]{12}", value) for value in ids) + or len(set(ids)) != len(ids)): + raise ValueError("Cursor acquisitions reused a launch, child, execution, or authorization") + + +def validate_native_stops(stops, acquisitions): + expected = ("slow", "permission-on-cancel", "error-on-cancel", "ignore-cancel", "complete-on-cancel") + if not isinstance(stops, list) or len(stops) != len(expected): + raise ValueError("Cursor did not record all addressed stops") + requests = [] + turns = [] + for index, (stop, prompt) in enumerate(zip(stops, expected)): + owner = acquisitions[0 if index < 4 else 1] + if (not isinstance(stop, dict) or stop.get("prompt") != prompt + or stop.get("peer_pid") != owner["workload_pid"] + or stop.get("peer_identity") != owner["workload_identity"] + or type(stop.get("acp_id")) is not int or stop["acp_id"] <= 0): + raise ValueError("Cursor stop was not correlated with its acquired workload and ACP turn") + turns.append((stop["peer_pid"], stop["peer_identity"], stop["acp_id"])) + requests.extend(stop.get(field) for field in ("stop_request_id", "prompt_request_id")) + downstream_id = stop.get("downstream_request_id") + if index == 4 and (not isinstance(downstream_id, str) or not downstream_id): + raise ValueError("Cursor sibling stop is missing its retained downstream request ID") + if (len(set(turns)) != len(turns) + or any(not isinstance(value, str) or not value for value in requests) + or len(set(requests)) != len(requests)): + raise ValueError("Cursor stop evidence reused an MCP request or ACP turn") + + +def validate_startup_cancellation(evidence): + if not isinstance(evidence, dict): + raise ValueError("Host did not record startup cancellation") + control = evidence.get("control") + cancelled = evidence.get("cancelled") + if not isinstance(control, dict) or not isinstance(cancelled, dict): + raise ValueError("Host did not record both startup trials") + phase_ids = [trial.get(key) for trial in (control, cancelled) + for key in ("acquisition", "execution", "probe", "workload")] + if (any(not isinstance(value, str) or not re.fullmatch( + r"[0-9A-F]{8}-(?:[0-9A-F]{4}-){3}[0-9A-F]{12}", value) + for value in phase_ids) or len(set(phase_ids)) != len(phase_ids)): + raise ValueError("Startup phase identities are missing or shared") + pids = [evidence.get("adapter_pid"), evidence.get("sibling_pid"), + control.get("probe_pid"), control.get("workload_pid"), cancelled.get("probe_pid")] + if (any(type(pid) is not int or pid <= 0 for pid in pids) or len(set(pids)) != len(pids) + or any(trial.get("probe_state") != "retired" for trial in (control, cancelled)) + or control.get("result") != "opened" or control.get("workload_starts") != 1 + or cancelled.get("result") != "cancelled" or cancelled.get("workload_starts") != 0 + or cancelled.get("workload_state") != "never_dispatched"): + raise ValueError("Startup cancellation did not prove exact workload sealing") + + +def validate_start_recovery(lost, closure): + phases = (("before_dispatch", "never_dispatched", 0), ("after_dispatch", "retired", 1)) + if not isinstance(closure, dict): + raise ValueError("Host did not record pending connection closure") + for record in (lost, *(closure.get(key) for key, _, _ in phases)): + if not isinstance(record, dict): + raise ValueError("Host did not record startup recovery") + identities = [record.get(key) for key in ("acquisition", "execution", "probe", "workload")] + if (any(not isinstance(value, str) or not re.fullmatch( + r"[0-9A-F]{8}-(?:[0-9A-F]{4}-){3}[0-9A-F]{12}", value) + for value in identities) or len(set(identities)) != len(identities) + or not all(isinstance(record.get(key), str) and record[key] + for key in ("request_id", "downstream_request_id"))): + raise ValueError("Startup recovery identities are incomplete") + pids = [lost.get("workload_pid"), lost.get("sibling_pid")] + if (any(type(pid) is not int or pid <= 0 for pid in pids) or pids[0] == pids[1] + or lost.get("retired_at_lookup") is not False + or lost.get("retired_after_cleanup") is not True + or type(lost.get("workload_starts")) is not int or lost["workload_starts"] != 1 + or lost.get("workload_state") != "retired" or lost.get("result") != "timeout"): + raise ValueError("Lost start reply did not reconcile exactly one retired workload") + for key, workload_state, workload_starts in phases: + record = closure[key] + if (type(record.get("workload_starts")) is not int or record["workload_starts"] != workload_starts + or record.get("probe_state") != "retired" or record.get("workload_state") != workload_state + or record.get("result") != "outcome_unknown" or record.get("cleanup") != "confirmed"): + raise ValueError(f"Private channel closure did not confirm cleanup {key}") + + +def swift_test_results(report, suites, exit_code): + if report.stat().st_size > 65536: + raise ValueError("Swift test report exceeds its bound") + try: + root = ET.parse(report).getroot() + except ET.ParseError as error: + raise ValueError("Invalid Swift test report") from error + expected = {SELECTORS[suite].split("/")[1] + "()": suite for suite in suites} + results = {} + for row in root.findall(".//testcase"): + suite = expected.get(row.get("name")) + if (suite is None or suite in results + or row.get("classname") != f"{TEST_PRODUCT}.CursorSourceIntegrationTests" + or row.find("skipped") is not None): + raise ValueError("Swift test report did not match the selected cases") + results[suite] = row.find("failure") is None and row.find("error") is None + if results.keys() != set(suites) or exit_code != int(not all(results.values())): + raise ValueError("Swift test report did not account for the runner result") + return results + + +def verify_suite(suite, evidence, result): + if evidence.stat().st_size > 65536: + raise ValueError("Case evidence exceeds its bound") + observed = json.loads(evidence.read_text()) + validate_evidence(observed, result["run_id"], VENDOR_CASES if suite == "vendor-stop" else CASES) + if observed["tests_executed"] != 1: + raise ValueError("Case evidence count differs from the Swift test report") + if suite == "vendor-stop": + acquisitions = observed.get("acquisitions") + validate_acquisitions(acquisitions) + native_stops = observed.get("native_stops") + validate_native_stops(native_stops, acquisitions) + startup = observed.get("startup_cancellation") + validate_startup_cancellation(startup) + lost = observed.get("lost_start_reply") + closure = observed.get("pending_start_closure") + validate_start_recovery(lost, closure) + result.update( + acquisitions=acquisitions, native_stops=native_stops, startup_cancellation=startup, + lost_start_reply=lost, pending_start_closure=closure) + result["cases"] = sorted(observed["cases"]) + result["tests_executed"] = observed["tests_executed"] + + +def verify_packaged_identity(host, plugin, scratch, archive, environment, output): + bin_path = subprocess.check_output( + ["/usr/bin/swift", "build", "--build-system", "swiftbuild", "--scratch-path", str(scratch), + "--show-bin-path"], cwd=host, env=environment, stderr=subprocess.PIPE, + text=True, timeout=15).strip() + worker = (Path(bin_path) / "computer-mcp").resolve(strict=True) + if not worker.is_relative_to(scratch): + raise ValueError("Archive worker is outside the run's Host build") + host_version = json.loads((host / "Version.json").read_text())["version"] + run_process( + [sys.executable, "-B", str(plugin / "scripts/validate_host.py"), + "--host", str(worker), "--expected-host-version", host_version, + "--archive", str(archive), "--output", str(output / "archive")], + plugin, environment, output / "archive-validation.log", 120) + + +def run(args): + output = validate_locations(args.host_source, args.plugin_source, args.output) + verify_source(args.host_source, args.host_sha) + verify_source(args.plugin_source, args.plugin_sha) + suites = tuple(SELECTORS) if args.suite == "both" else (args.suite,) + before = {name: digest(args.plugin_source / name) for name in INPUTS} + output.mkdir(parents=True) + host = output / "host-source" + plugin = output / "plugin-source" + scratch = output / "build" + packages = output / "package" + report = output / "swift-test.xml" + log = output / "swift-test.log" + results = {} + suite_outputs = {suite: output / suite if len(suites) > 1 else output for suite in suites} + common_result = { + "host_sha": args.host_sha, "plugin_sha": args.plugin_sha, "inputs_sha256": before, + "kind": "deterministic", "native_verified": False, "python": sys.executable, + "python_sha256": digest(Path(sys.executable)), "status": "failed", "cleanup": "pending", + } + environment = dict(os.environ) + # Bind the fixture and native archive worker to this run's staged sources and build. + for key in list(environment): + if key.startswith("COMPUTER_MCP_CURSOR_") or key == "COMPUTER_MCP_TEST_GATEWAY_EXECUTABLE": + del environment[key] + environment.update({ + "COMPUTER_MCP_CURSOR_PLUGIN": str(plugin), + "COMPUTER_MCP_CURSOR_PYTHON": sys.executable, + }) + for suite, directory in suite_outputs.items(): + if directory != output: + directory.mkdir() + run_id = os.urandom(16).hex() + results[suite] = dict(common_result, suite=suite, run_id=run_id) + prefix = "COMPUTER_MCP_CURSOR_" + suite.upper().replace("-", "_") + environment[prefix + "_CASES"] = str(directory / "cases.json") + environment[prefix + "_RUN_ID"] = run_id + failures = [] + try: + export_source(args.host_source, args.host_sha, host, environment, output) + export_source(args.plugin_source, args.plugin_sha, plugin, environment, output) + for name, expected in before.items(): + if digest(plugin / name) != expected: + raise ValueError("Exported plugin differs from its source commit") + target = host / "Tests" / TEST_PRODUCT / FIXTURE + if not target.parent.is_dir(): + raise ValueError("Host does not provide the required macOS test target") + with target.open("xb") as destination: + destination.write((plugin / INPUTS[1]).read_bytes()) + if "vendor-stop" in suites: + run_process( + [sys.executable, "-B", str(plugin / "scripts/build_package.py"), str(packages)], + plugin, environment, output / "package-build.log", 30) + archive = packages / "cursor.zip" + archive_sha256 = digest(archive) + results["vendor-stop"]["archive_sha256"] = archive_sha256 + environment["COMPUTER_MCP_CURSOR_ARCHIVE"] = str(archive) + environment["COMPUTER_MCP_CURSOR_ARCHIVE_SHA256"] = archive_sha256 + command = [ + "/usr/bin/swift", "test", "--build-system", "swiftbuild", "--test-product", TEST_PRODUCT, + "--disable-index-store", + "--force-resolved-versions", "--scratch-path", str(scratch), "--disable-xctest", + "--xunit-output", str(report), + "--parallel" if len(suites) > 1 else "--no-parallel", + ] + for suite in suites: + command.extend(["--filter", SELECTORS[suite]]) + exit_code = run_process(command, host, environment, log, args.timeout, exit_codes=(0, 1)) + if exit_code and not report.is_file(): + raise RuntimeError(f"Swift build or test runner failed; inspect {log}") + swift_results = swift_test_results(report, suites, exit_code) + for suite, result in results.items(): + try: + if not swift_results[suite]: + raise ValueError(f"Swift test failed; inspect {log}") + directory = suite_outputs[suite] + verify_suite(suite, directory / "cases.json", result) + if suite == "vendor-stop": + verify_packaged_identity(host, plugin, scratch, archive, environment, directory) + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: + result["error"] = str(error) + failures.append(f"{suite}: {error}") + else: + result["status"] = "passed" + finally: + # Logs/case evidence survive; all exported sources and build output are owned here. + try: + for path in (host, plugin, scratch, packages): + if path.is_symlink(): + raise RuntimeError("Run-owned cleanup target was replaced by a symlink") + if path.exists(): + shutil.rmtree(path) + for result in results.values(): + result["cleanup"] = ("confirmed" if result.get("tests_executed") == 1 + else "exports-removed; fixture-process-cleanup-unverified") + verify_source(args.host_source, args.host_sha) + verify_source(args.plugin_source, args.plugin_sha) + if {name: digest(args.plugin_source / name) for name in INPUTS} != before: + raise ValueError("Source input changed during verification") + except BaseException: + for result in results.values(): + result["status"] = "failed" + raise + finally: + for suite, result in results.items(): + receipt = suite_outputs[suite] / "receipt.json" + receipt.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + if failures: + raise ValueError("; ".join(failures)) + for suite, directory in suite_outputs.items(): + print(json.dumps({"suite": suite, "receipt": str(directory / "receipt.json"), "status": "passed"})) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--host-source", required=True, type=absolute) + parser.add_argument("--host-sha", required=True, type=revision) + parser.add_argument("--plugin-source", required=True, type=absolute) + parser.add_argument("--plugin-sha", required=True, type=revision) + parser.add_argument("--output", required=True, type=Path, + help="fresh absolute directory outside both source checkouts and their ancestors") + parser.add_argument("--suite", choices=(*SELECTORS, "both"), default="source") + parser.add_argument("--timeout", type=int, default=900) + args = parser.parse_args(argv) + if not 1 <= args.timeout <= 1800: + parser.error("--timeout must be between 1 and 1800 seconds") + try: + run(args) + except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: + parser.exit(1, f"Source verification failed: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/skills/cursor-agent/SKILL.md b/skills/cursor-agent/SKILL.md index 968e819..6736427 100644 --- a/skills/cursor-agent/SKILL.md +++ b/skills/cursor-agent/SKILL.md @@ -15,4 +15,4 @@ The default permission policy is reject-once. Choose manual when approvals must `completed: true` is settlement, not necessarily success. Inspect is_error, stop_reason, native_result, truncation and missed-event markers. Use session.cancel to cancel active work and session.close when finished. After adapter replacement, old handles are invalid; use an explicit saved native conversation ID with resume_session_id only when continuation is intended. -Vendor installation, authentication, updates and account setup remain local user operations. Host grants and Cursor permissions are distinct. A working directory is not a sandbox. Protocol fixtures, native initialization and real model execution are different verification claims. +The owner signs in on their computer using Cursor. If session setup returns `authentication_required`, report Cursor Agent's rejection to the owner. Vendor installation, updates and account setup remain local user operations. Host grants and Cursor permissions are distinct. A working directory is not a sandbox. Protocol fixtures, native initialization and real model execution are different verification claims. diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt new file mode 100644 index 0000000..6e3f79e --- /dev/null +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -0,0 +1,2030 @@ +import ComputerMCPDarwinTestSupport +import ComputerMCPMacOS +import ComputerMCPPermissions +import ComputerMCPSandbox +import ComputerMCPTestSupport +import Foundation +import Testing + +@testable import ComputerMCPConfiguration +@testable import ComputerMCPCore +@testable import ComputerMCPGateway +@testable import ComputerMCPPlugins +@testable import ComputerMCPProcess + +private let cursorReadTools: Set = [ + "cursor.acp.session.prompt.result", "cursor.acp.session.list", + "cursor.acp.events.read", "cursor.acp.requests.list", +] +private let cursorWriteTools: Set = [ + "cursor.acp.prompt", "cursor.acp.session.open", "cursor.acp.session.prompt", + "cursor.acp.session.prompt.start", "cursor.acp.session.mode", "cursor.acp.requests.respond", + "cursor.acp.session.cancel", "cursor.acp.session.close", +] + +// Independent fixtures share the cooperative pool used by the Host's worktree bridge. +@Suite(.nativeIntegration, .serialized) +struct CursorSourceIntegrationTests { + @Test(.timeLimit(.minutes(10))) func registeredVendorStop() async throws { + let env = ProcessInfo.processInfo.environment + _ = try #require(env["COMPUTER_MCP_CURSOR_ARCHIVE"]) + _ = try #require(env["COMPUTER_MCP_CURSOR_ARCHIVE_SHA256"]) + let source = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_PLUGIN"])) + let package = try PluginPackage.load(at: source) + + var details = try await registeredStops(package) + details["startup_cancellation"] = try await registeredStartupCancellation(package) + try await requireRegisteredDenials(package) + details.merge(try await registeredStartupRecovery(package)) { _, value in value } + let cases = [ + "dual-authority", "cold-warm-ownership", "seatbelt-boundaries", "ordinary-cancel", + "native-result-races", "pending-answer-cancel", "forced-stop-isolation", "cleanup", + "startup-cancellation", "lost-start-reply", "pending-start-closure", + ] + try writeCursorEvidence("VENDOR_STOP", cases: cases, details: details) + } + + private func requireRegisteredDenials(_ package: PluginPackage) async throws { + for (caller, provider) in [(1, true), (2, false)] { + try await withCursor(package, caller: caller, provider: provider, installArchive: true) { h in + try await h.discover() + let before = h.mcpObservations.members.count + let hostBefore = h.base.observations.members.count + let denied = try await h.call("cursor.acp.session.open") + try cursorDenied(denied) + try #require( + denied.objectValue?["structuredContent"]?.objectValue?["error"]?.objectValue?["code"] + == .string("permission.required")) + try #require(h.mcpObservations.members.count == before) + try #require(h.base.observations.members.count == hostBefore) + print( + "Cursor gate denial preserved (caller write: \(caller == 2), provider write: \(provider))" + ) + } + } + } + + private func registeredStops(_ package: PluginPackage) async throws -> [String: Any] { + var measured: [[String: Any]] = [] + var nativeStops: [[String: Any]] = [] + try await withCursor(package, installArchive: true) { h in + try await h.discover() + let baseline = h.mcpObservations.members.count + let hostBaseline = h.base.observations.members.count + let a = try await h.open() + let warm = h.mcpObservations.members.count + let b = try await h.open() + let aRoute = try await h.observeSession(a) + let bRoute = try await h.observeSession(b) + try #require(aRoute.connectionID == bRoute.connectionID) + try #require(aRoute.instanceID == bRoute.instanceID) + try #require(aRoute.acquiredBy != bRoute.acquiredBy) + let peers = try h.vendorEffects() + try #require( + peers.compactMap { $0["phase"]?.stringValue } == ["probe", "workload", "probe", "workload"]) + let roots = try peers.map { try h.peerMember($0) } + try #require(Set(roots).count == 4) + let coldRoots = Array(roots.prefix(2)) + let warmRoots = Array(roots.suffix(2)) + let coldLaunches = Array( + h.mcpObservations.members.dropFirst(baseline).prefix(warm - baseline)) + let adapterCandidates = Set(coldLaunches).subtracting(coldRoots) + try #require(adapterCandidates.count == 1) + let adapter = try #require(adapterCandidates.first) + try h.requireMCPLaunches(coldLaunches, exactly: coldRoots + [adapter]) + try h.requireMCPLaunches(since: warm, exactly: warmRoots) + measured = try h.verifyAcquisitions(first: coldRoots, second: warmRoots, adapter: adapter) + print( + "Cursor cold/warm proof counted five MCP roots and \(h.base.observations.members.count - hostBaseline) separate Host launches" + ) + let aRoot = roots[1] + let bRoot = roots[3] + let aPID = aRoot.processID + let bPID = bRoot.processID + let aOwner = try h.processOwner(aRoot) + let bOwner = try h.processOwner(bRoot) + print("Cursor gate acquired A \(aPID) and B \(bPID) in adapter \(adapter.processID)") + + async let normal = h.prompt(a, "slow") + try await h.waitVendorPrompt(pid: aPID, prompt: "slow") + let normalStop = try await h.stop(a) + try #require(try cursorValue(normalStop)["cancel_requested"] == .bool(true)) + let normalReply = try await normal + h.reportStop(pid: aPID, prompt: "slow", stop: normalStop, reply: normalReply) + let stopped = try cursorNativeValue(normalReply) + try #require(stopped["stop_reason"] == .string("cancelled")) + try #require( + stopped["native_result"]?.objectValue?["usage"]?.objectValue?["tokens"] == .integer(3)) + try #require(stopped["closed"] == .bool(false)) + try #require(try await aOwner.members().contains(aRoot)) + let afterStop = try cursorValue( + try await h.call("cursor.acp.requests.list", ["session": .string(a)])) + try #require(afterStop["requests"] == .array([])) + let environment = try cursorValue(try await h.prompt(a, "env")) + try #require( + environment["session"] == .string(a) && environment["stop_reason"] == .string("end_turn")) + try #require(environment["text"] == .string("[]")) + try await h.waitVendorPrompt(pid: aPID, prompt: "env") + try #require(try await h.observeSession(a) == aRoute) + try #require(try await h.observeSession(b) == bRoute) + try h.requireMCPLaunches(since: baseline, exactly: roots + [adapter]) + + async let interactive = h.prompt(a, "permission-on-cancel") + _ = try await h.waitPending(a) + let beforeAnswer = try h.vendorEffects().count + let interactiveStop = try await h.stop(a) + try #require(try cursorValue(interactiveStop)["cancel_requested"] == .bool(true)) + let interactiveReply = try await interactive + h.reportStop( + pid: aPID, prompt: "permission-on-cancel", stop: interactiveStop, reply: interactiveReply) + let interactiveResult = try cursorNativeValue(interactiveReply) + try #require(interactiveResult["stop_reason"] == .string("cancelled")) + let answers = try h.vendorEffects().dropFirst(beforeAnswer).filter { + $0["phase"] == .string("answer") && $0["pid"]?.intValue == Int(aPID) + } + try #require( + answers.compactMap { $0["response"] } == [ + .object(["outcome": .object(["outcome": .string("cancelled")])]) + ]) + let pendingAfterStop = try cursorValue( + try await h.call("cursor.acp.requests.list", ["session": .string(a)])) + try #require(pendingAfterStop["requests"] == .array([])) + let outside = String( + decoding: try JSONSerialization.data(withJSONObject: h.outside.map(\.path)), + as: UTF8.self) + let sandboxPrompt = "boundaries:" + outside + let boundary = try cursorValue(try await h.prompt(a, sandboxPrompt)) + try #require( + boundary["session"] == .string(a) && boundary["stop_reason"] == .string("end_turn")) + try await h.waitVendorPrompt(pid: aPID, prompt: sandboxPrompt) + let allowed = h.worktree.appendingPathComponent("cursor-selected-write") + try #require(try String(contentsOf: allowed, encoding: .utf8) == "written") + for url in h.outside { + try #require(try String(contentsOf: url, encoding: .utf8) == "sentinel") + } + + async let nativeError = h.prompt(a, "error-on-cancel") + try await h.waitVendorPrompt(pid: aPID, prompt: "error-on-cancel") + let errorStop = try await h.stop(a) + _ = try cursorValue(errorStop) + let errorReply = try await nativeError + h.reportStop(pid: aPID, prompt: "error-on-cancel", stop: errorStop, reply: errorReply) + let error = try cursorNativeValue(errorReply)["error"]?.objectValue + try #require(error?["code"] == .string("vendor_error")) + try #require(error?["message"]?.stringValue?.contains("-32023") == true) + + let isolationStarted = ContinuousClock.now + let bPrompt = "complete-on-cancel" + let bRequestID = "cursor-vendor-isolation-b" + // Retain B's original MCP result after dispatch so its wait cannot hold a Gateway worker. + let startedB = try cursorValue( + try await h.call( + "cursor.acp.session.prompt", ["session": .string(b), "prompt": .string(bPrompt)], + startRequestID: bRequestID)) + try #require(startedB["request_id"] == .string(bRequestID)) + try #require(startedB["state"] == .string("running")) + let bDownstreamID = try #require(startedB["downstream_request_id"]?.stringValue) + try await h.waitVendorPrompt(pid: bPID, prompt: bPrompt) + let bStarted = try h.vendorTurn(pid: bPID, prompt: bPrompt) + let bNativeID = try #require(bStarted.first?["acp_id"]?.intValue) + h.reportIsolation( + "B retained MCP request \(bDownstreamID) reached peer as ACP request \(bNativeID)", + started: isolationStarted) + async let ignored = h.observedPrompt( + a, "ignore-cancel", pid: aPID, started: isolationStarted) + try await h.waitVendorPrompt(pid: aPID, prompt: "ignore-cancel") + h.reportIsolation("A prompt reached peer", started: isolationStarted) + let ignoredStop = try await h.stop(a) + h.reportIsolation("A stop returned", started: isolationStarted) + if let stopRequestID = ignoredStop.objectValue?["structuredContent"]?.objectValue?[ + "gateway_execution"]?.objectValue?["request_id"]?.stringValue, + let audit = try? h.base.database.auditEvents(requestID: stopRequestID) + { + let admitted = audit.first { $0.errorCode == "permission.admitted" }?.occurredAt + h.reportIsolation( + "A stop audit request \(stopRequestID) admitted_ms " + + (admitted.map { String(Int64($0.timeIntervalSince1970 * 1_000)) } ?? "none"), + started: isolationStarted) + } + if ignoredStop.objectValue?["isError"] == .bool(true) { + h.reportStop(pid: aPID, prompt: "ignore-cancel", stop: ignoredStop, reply: .null) + } + try #require(try cursorValue(ignoredStop)["cancel_requested"] == .bool(true)) + let ignoredReply = try await ignored + h.reportStop(pid: aPID, prompt: "ignore-cancel", stop: ignoredStop, reply: ignoredReply) + let unsettled = try cursorNativeValue(ignoredReply)["error"]?.objectValue + try #require(unsettled?["code"] == .string("cancellation_unsettled")) + try #require(unsettled?["message"]?.stringValue?.contains("did not settle") == true) + let aMembers = try await aOwner.members() + let bMembers = try await bOwner.members() + let siblingAlive = bMembers.contains { $0.processID == bPID } + h.reportIsolation( + "A settled; A members \(aMembers.map(\.processID)), B members \(bMembers.map(\.processID))", + started: isolationStarted) + if !siblingAlive { + let adapterOwner = try? h.processOwner(adapter) + let adapterMembers = try? await adapterOwner?.members() + h.reportIsolation( + "adapter members \(adapterMembers?.map(\.processID) ?? [])", + started: isolationStarted) + h.reportAcquisitionLifetimes(measured, started: isolationStarted) + } + try #require(aMembers.isEmpty) + try #require(siblingAlive) + let bPending = try h.vendorTurn(pid: bPID, prompt: bPrompt) + try #require(bPending.map { $0["phase"]?.stringValue } == ["prompt"]) + try #require(bPending.first?["acp_id"]?.intValue == bNativeID) + let pendingReceipt = try await h.requestReceipt(bRequestID) + try #require(pendingReceipt["state"] == .string("running")) + try #require(pendingReceipt["downstream_request_id"] == .string(bDownstreamID)) + + let completionStop = try await h.stop(b) + try #require(try cursorValue(completionStop)["cancel_requested"] == .bool(true)) + let completedReceipt = try await h.waitRequestReceipt(bRequestID) + try #require(completedReceipt["state"] == .string("succeeded"), "\(completedReceipt)") + try #require(completedReceipt["request_id"] == .string(bRequestID)) + try #require(completedReceipt["downstream_request_id"] == .string(bDownstreamID)) + let completionReply = try #require(completedReceipt["result"]) + h.reportStop(pid: bPID, prompt: bPrompt, stop: completionStop, reply: completionReply) + let won = try cursorValue(completionReply) + try #require(won["session"] == .string(b)) + try #require(won["stop_reason"] == .string("end_turn")) + try #require( + won["native_result"]?.objectValue?["usage"]?.objectValue?["tokens"] == .integer(7)) + let bSettled = try h.vendorTurn(pid: bPID, prompt: bPrompt) + try #require(bSettled.map { $0["phase"]?.stringValue } == ["prompt", "cancel", "terminal"]) + try #require(bSettled.last?["acp_id"]?.intValue == bNativeID) + try #require(bSettled.last?["outcome"]?.objectValue?["result"] == won["native_result"]) + try #require(try await h.observeSession(b) == bRoute) + let freshB = try await h.verifySiblingIO(b, root: bRoot, suffix: "forced-stop") + let freshTurn = try h.vendorTurn(pid: bPID, prompt: freshB) + let freshNativeID = try #require(freshTurn.first?["acp_id"]?.intValue) + try #require(freshNativeID > bNativeID) + try #require(try h.nativeStarts == 2) + try h.requireMCPLaunches(since: baseline, exactly: roots + [adapter]) + _ = try cursorValue( + try await h.call("cursor.acp.session.close", ["session": .string(b)])) + try #require(try await bOwner.members().isEmpty) + + // Correlate each addressed stop with the peer turn and then require that + // these exact deliveries account for every cancel, including after close. + let correlations = try [ + h.nativeStop(aRoot, prompt: "slow", stop: normalStop, promptReply: normalReply), + h.nativeStop( + aRoot, prompt: "permission-on-cancel", stop: interactiveStop, + promptReply: interactiveReply, terminalLogged: false), + h.nativeStop( + aRoot, prompt: "error-on-cancel", stop: errorStop, promptReply: errorReply), + h.nativeStop( + aRoot, prompt: "ignore-cancel", stop: ignoredStop, promptReply: ignoredReply, + terminalLogged: false), + h.nativeStop( + bRoot, prompt: bPrompt, stop: completionStop, promptReply: .object(completedReceipt)), + ] + let effects = try h.vendorEffects() + try #require(effects.filter { $0["phase"] == .string("probe") }.count == 2) + let actualCancels = effects.filter { $0["phase"] == .string("cancel") } + try #require(actualCancels == correlations.map(\.event)) + nativeStops = correlations.map(\.receipt) + } + return ["acquisitions": measured, "native_stops": nativeStops] + } + + private func registeredStartupRecovery(_ package: PluginPackage) async throws -> [String: Any] { + let lost = try await registeredLostStartReply(package) + let closure = try await registeredPendingStartClosure(package) + return ["lost_start_reply": lost, "pending_start_closure": closure] + } + + private func registeredStartupCancellation(_ package: PluginPackage) async throws + -> [String: Any] + { + var evidence: [String: Any] = [:] + for withdraw in [false, true] { + try await withCursor(package, installArchive: true, observeStartup: true) { h in + try await h.discover() + let b = try await h.open() + let bRoot = try h.lastWorkload() + let bPrompt = "complete-on-cancel" + let bRequestID = "startup-sibling" + let bStarted = try cursorValue( + try await h.call( + "cursor.acp.session.prompt", ["session": .string(b), "prompt": .string(bPrompt)], + startRequestID: bRequestID)) + try #require(bStarted["state"] == .string("running")) + let bDownstream = try #require(bStarted["downstream_request_id"]) + try await h.waitVendorPrompt(pid: bRoot.processID, prompt: bPrompt) + let bNative = try #require( + try h.vendorTurn(pid: bRoot.processID, prompt: bPrompt).first?["acp_id"]) + let requestID = withdraw ? "startup-withdraw" : "startup-control" + let before = h.mcpObservations.members.count + let startCount = try h.nativeStarts + try h.armStartupFault("hold-launch") + let started = try await h.startOpen(requestID) + let downstream = try #require(started["downstream_request_id"]?.stringValue) + let held = try await h.waitTransport("launch-held") + let boundary = try await h.startupBoundary(held) + let beforeStop = try h.startupChildren(boundary) + let probeRoot = try #require(beforeStop.probe.recovery?.root) + try #require(beforeStop.probe.completed && beforeStop.probe.recovery?.sandboxed == true) + try #require(!beforeStop.workload.completed && beforeStop.workload.recovery == nil) + try h.requireMCPLaunches(since: before, exactly: [probeRoot]) + try h.requirePeerEvidence(probeRoot, phase: "probe") + + var trial = h.startupEvidence(boundary, requestID: requestID, downstream: downstream) + trial["probe_state"] = "retired" + trial["probe_pid"] = Int(probeRoot.processID) + if withdraw { + let cancelled = try cursorValue( + try await h.consumer.generations.callFixtureTool( + name: "mcp.requests.cancel", + arguments: .object([ + "server": .string("cursor-fixture"), "request_id": .string(requestID), + ]), context: .empty)) + try #require(cancelled["cancellation_requested"] == .bool(true)) + try #require(cancelled["request_id"] == .string(requestID)) + } + try h.releaseTransport("launch-held") + let delivered = try await h.waitTransport("launch-delivered") + try #require(delivered.request == held.request) + let terminal = try await h.waitRequestReceipt(requestID) + try #require(terminal["request_id"] == .string(requestID)) + try #require(terminal["downstream_request_id"] == .string(downstream)) + let reply = try #require(terminal["result"]) + if withdraw { + try #require(delivered.reply?["error"] == .string("cancelled")) + try #require(terminal["state"] == .string("failed"), "\(terminal)") + try #require(terminal["cancellation"] == .string("sent")) + try #require(reply.objectValue?["isError"] == .bool(true)) + let payload = reply.objectValue?["structuredContent"]?.objectValue?["result"] + try #require(payload?.objectValue?["error"]?.objectValue?["code"] == .string("cancelled")) + try await h.requireNeverLaunched(boundary, probe: probeRoot) + try h.requireMCPLaunches(since: before, exactly: [probeRoot]) + try #require(try h.nativeStarts == startCount) + trial["workload_state"] = "never_dispatched" + trial["workload_starts"] = 0 + trial["result"] = "cancelled" + try #require( + boundary.adapter != bRoot && bRoot != probeRoot && boundary.adapter != probeRoot) + evidence["adapter_pid"] = Int(boundary.adapter.processID) + evidence["sibling_pid"] = Int(bRoot.processID) + } else { + let hostReceipt = try h.startupReply(delivered, boundary: boundary) + try #require(hostReceipt["retired"] == .bool(false)) + try #require(terminal["state"] == .string("succeeded"), "\(terminal)") + let session = try #require(try cursorValue(reply)["session"]?.stringValue) + _ = try await h.observeSession(session) + let live = try h.startupChildren(boundary) + let root = try #require(live.workload.recovery?.root) + try #require(!live.workload.completed && live.workload.recovery?.sandboxed == true) + try h.requireMCPLaunches(since: before, exactly: [probeRoot, root]) + try h.requirePeerEvidence(root, phase: "workload") + try #require(try h.nativeStarts == startCount + 1) + _ = try cursorValue( + try await h.call("cursor.acp.session.close", ["session": .string(session)])) + let owner = try h.processOwner(root) + try #require(try await owner.members().isEmpty) + trial["workload_pid"] = Int(root.processID) + trial["workload_starts"] = 1 + trial["result"] = "opened" + } + let siblingPending = try h.vendorTurn(pid: bRoot.processID, prompt: bPrompt) + try #require(siblingPending.map { $0["phase"] } == [.string("prompt")]) + let bStop = try cursorValue(try await h.stop(b)) + try #require(bStop["cancel_requested"] == .bool(true)) + let finished = try await h.waitRequestReceipt(bRequestID) + try #require(finished["state"] == .string("succeeded")) + try #require(finished["downstream_request_id"] == bDownstream) + let bReply = try cursorValue(try #require(finished["result"])) + try #require( + bReply["session"] == .string(b) && bReply["stop_reason"] == .string("end_turn")) + let siblingSettled = try h.vendorTurn(pid: bRoot.processID, prompt: bPrompt) + try #require( + siblingSettled.map { $0["phase"] } == [ + .string("prompt"), .string("cancel"), .string("terminal"), + ]) + try #require(siblingSettled.last?["acp_id"] == bNative) + try #require( + siblingSettled.last?["outcome"]?.objectValue?["result"] == bReply["native_result"]) + _ = try await h.verifySiblingIO( + b, root: bRoot, suffix: withdraw ? "after-startup-cancellation" : "after-control-close") + _ = try cursorValue(try await h.call("cursor.acp.session.close", ["session": .string(b)])) + let bOwner = try h.processOwner(bRoot) + try #require(try await bOwner.members().isEmpty) + evidence[withdraw ? "cancelled" : "control"] = trial + } + } + return evidence + } + + private func registeredLostStartReply(_ package: PluginPackage) async throws -> [String: Any] { + var evidence: [String: Any] = [:] + try await withCursor(package, installArchive: true, observeStartup: true) { h in + try await h.discover() + let b = try await h.open() + let bRoot = try h.lastWorkload() + let before = h.mcpObservations.members.count + try h.armStartupFault("lose-reply") + let requestID = "startup-lost-reply" + let started = try await h.startOpen(requestID) + let downstream = try #require(started["downstream_request_id"]?.stringValue) + let dropped = try await h.waitTransport("launch-dropped") + let boundary = try await h.startupBoundary(dropped) + let launch = try h.startupReply(dropped, boundary: boundary) + try #require(launch["retired"] == .bool(false)) + let recovered = try await h.waitTransport("receipt", timeout: .seconds(14)) + try h.requireNewRequest(recovered, after: dropped) + let lookup = try h.startupReply(recovered, boundary: boundary) + try #require( + lookup["probe_state"] == .string("retired") && lookup["probe_settled"] == .bool(true)) + try #require( + lookup["workload_state"] == .string("pending") && lookup["workload_settled"] == .bool(false) + ) + try #require(lookup["retired"] == .bool(false)) + let live = try h.startupChildren(boundary) + let root = try #require(live.workload.recovery?.root) + let probe = try #require(live.probe.recovery?.root) + try #require(live.probe.completed && !live.workload.completed) + try h.requirePeerEvidence(root, phase: "workload") + try h.requirePeerEvidence(probe, phase: "probe") + let durable = try h.phaseJournal(boundary.workloadID, boundary: boundary) + try #require(durable.recovery.root == root && !durable.completed && !durable.released) + let aOwner = try h.processOwner(root) + try #require(try await aOwner.members().contains(root)) + let bOwner = try h.processOwner(bRoot) + try #require(try await bOwner.members().contains(bRoot)) + _ = try await h.verifySiblingIO(b, root: bRoot, suffix: "while-launch-reply-lost") + try h.releaseTransport("receipt") + + let retired = try await h.waitTransport("retire") + try h.requireNewRequest(retired, after: recovered) + let settled = try h.startupReply(retired, boundary: boundary) + try #require( + settled["probe_state"] == .string("retired") && settled["probe_settled"] == .bool(true)) + try #require( + settled["workload_state"] == .string("retired") + && settled["workload_settled"] == .bool(true)) + try #require(settled["retired"] == .bool(true)) + let complete = try h.startupChildren(boundary) + try #require(complete.probe.completed && complete.probe.recovery?.root == probe) + try #require(complete.workload.completed && complete.workload.recovery?.root == root) + let journal = try h.phaseJournal(boundary.workloadID, boundary: boundary) + try #require(journal.completed && journal.recovery.root == root) + try #require(try await aOwner.members().isEmpty) + try h.releaseTransport("retire") + + let terminal = try await h.waitRequestReceipt(requestID) + try #require(terminal["state"] == .string("failed"), "\(terminal)") + try #require(terminal["downstream_request_id"] == .string(downstream)) + let reply = try #require(terminal["result"]) + try #require(reply.objectValue?["isError"] == .bool(true)) + let payload = reply.objectValue?["structuredContent"]?.objectValue?["result"] + try #require(payload?.objectValue?["error"]?.objectValue?["code"] == .string("timeout")) + let repeated = try cursorValue( + try await h.call( + "cursor.acp.session.open", ["permission_policy": .string("manual")], + startRequestID: requestID)) + try #require(repeated["state"] == .string("failed")) + try #require(repeated["downstream_request_id"] == .string(downstream)) + try #require(repeated["result"] == reply && repeated["replayed"] == .bool(false)) + try h.requireNoTransportEvent("launch-replayed") + _ = try await h.verifySiblingIO(b, root: bRoot, suffix: "after-lost-launch-reply") + try h.requireMCPLaunches(since: before, exactly: [probe, root]) + let starts = try h.vendorEffects().filter { $0["phase"] == .string("workload") } + try #require( + starts.compactMap { $0["pid"]?.intValue } == [Int(bRoot.processID), Int(root.processID)]) + try #require(try h.nativeStarts == 1) + evidence = h.startupEvidence(boundary, requestID: requestID, downstream: downstream) + evidence["workload_pid"] = Int(root.processID) + evidence["sibling_pid"] = Int(bRoot.processID) + evidence["workload_starts"] = starts.count - 1 + evidence["workload_state"] = settled["workload_state"]?.stringValue + evidence["retired_at_lookup"] = lookup["retired"] == .bool(true) + evidence["retired_after_cleanup"] = settled["retired"] == .bool(true) + evidence["result"] = "timeout" + _ = try cursorValue(try await h.call("cursor.acp.session.close", ["session": .string(b)])) + } + return evidence + } + + private func registeredPendingStartClosure(_ package: PluginPackage) async throws -> [String: Any] + { + var evidence: [String: Any] = [:] + for dispatched in [false, true] { + try await withCursor(package, installArchive: true, observeStartup: true) { h in + try await h.discover() + _ = try await h.open() + let sibling = try h.lastWorkload() + let siblingOwner = try h.processOwner(sibling) + let before = h.mcpObservations.members.count + try h.armStartupFault(dispatched ? "hold-launch-reply" : "hold-launch") + let requestID = + dispatched ? "startup-close-after-dispatch" : "startup-close-before-dispatch" + let started = try await h.startOpen(requestID) + let downstream = try #require(started["downstream_request_id"]?.stringValue) + let held = try await h.waitTransport(dispatched ? "launch-reply-held" : "launch-held") + let boundary = try await h.startupBoundary(held) + let live = try h.startupChildren(boundary) + let probe = try #require(live.probe.recovery?.root) + let workload: ExecutionMember? + try #require(live.probe.completed && !live.workload.completed) + try h.requirePeerEvidence(probe, phase: "probe") + var roots = [probe] + if dispatched { + let launch = try h.startupReply(held, boundary: boundary) + try #require( + launch["retired"] == .bool(false) && launch["workload_settled"] == .bool(false)) + let root = try await h.waitStartedWorkload(boundary) + workload = root + roots.append(root) + } else { + try #require(live.workload.recovery == nil) + workload = nil + } + let owner = try await h.vendorRequestOwner(requestID) + let clock = ContinuousClock() + let start = clock.now + let result = try await h.closeVendorConnection(owner) + try #require(start.duration(to: clock.now) < .seconds(8)) + try #require(result["transport_closed"] == .bool(true)) + try #require(result["connection_id"] == .string(owner.connectionID.uuidString)) + try #require(result["managed_process_exit_confirmed"] == .bool(true)) + try #require(result["work_cleanup"] == .string("confirmed"), "\(result)") + try #require(result["remaining_owners"] == .integer(0), "\(result)") + if let workload { + let paired = try h.startupChildren(boundary) + try #require(paired.probe.completed && paired.probe.recovery?.root == probe) + try #require(paired.workload.completed && paired.workload.recovery?.root == workload) + for (child, root) in [(boundary.probeID, probe), (boundary.workloadID, workload)] { + let journal = try h.phaseJournal(child, boundary: boundary) + try #require(journal.completed && journal.recovery.root == root) + let process = try h.processOwner(root) + try #require(try await process.members().isEmpty) + } + } else { + try await h.requireNeverLaunched(boundary, probe: probe) + try h.requireNoTransportEvent("launch-delivered") + } + try h.requireNoTransportEvent("launch-replayed") + try #require(try await siblingOwner.members().isEmpty) + let adapter = try h.processOwner(boundary.adapter) + try #require(try await adapter.members().isEmpty) + try h.requireMCPLaunches(since: before, exactly: roots) + let terminal = try await h.waitRequestReceipt(requestID) + try #require(terminal["state"] == .string("outcome_unknown")) + try #require(terminal["cleanup"] == .string("confirmed")) + try #require(terminal["downstream_request_id"] == .string(downstream)) + try #require(try h.nativeStarts == 1) + var trial = h.startupEvidence(boundary, requestID: requestID, downstream: downstream) + trial["probe_state"] = "retired" + trial["workload_starts"] = roots.count - 1 + trial["workload_state"] = dispatched ? "retired" : "never_dispatched" + trial["result"] = "outcome_unknown" + trial["cleanup"] = "confirmed" + evidence[dispatched ? "after_dispatch" : "before_dispatch"] = trial + } + } + return evidence + } + + @Test(.timeLimit(.minutes(5))) func sourceConsumer() async throws { + let env = ProcessInfo.processInfo.environment + let source = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_PLUGIN"])) + let package = try PluginPackage.load(at: source) + try #require(package.manifest.id == "cursor") + try #require(package.manifest.permissions?.map(\.id) == [.project]) + try #require(package.manifest.permissions?.first?.access == .write) + let sandbox = try #require(package.manifest.sandbox) + try #require(!sandbox.fullAccess && sandbox.readExceptions == nil) + try #require( + sandbox.network + == .custom(hosts: ["api2.cursor.sh", "api5.cursor.sh"], includeTrusted: false)) + let requirements = try PluginContributionRequirements( + sourceDigest: PluginStore.manifestDigest(package.manifest), + declarations: .init(package.manifest), componentID: "acp") + let contribution = try #require(requirements.contribution) + try #require(Set(contribution.toolRequirements.keys) == cursorReadTools) + for name in cursorReadTools { + try #require(requirements.requirements(for: name)?.project == .read) + try #require( + requirements.applying(to: .init(access: .projectWrite), tool: name).access == .projectWrite) + } + for name in cursorWriteTools { + try #require(requirements.requirements(for: name)?.project == .write) + } + for (caller, provider, use) in [ + (0, true, true), (1, true, true), (2, false, true), (2, true, false), + ] { + try await withCursor(package, caller: caller, provider: provider, use: use) { h in + if use { try await h.discover() } + let requestsBefore = Set( + try h.gateway.permissionRuntime.service.view(owner: h.owner).requests.map(\.request.id)) + let before = try h.nativeStarts + let denied: JSONValue + if use { + denied = try await h.call("cursor.acp.session.open") + } else { + denied = try await h.catalog() + } + try cursorDenied(denied) + try #require( + denied.objectValue?["structuredContent"]?.objectValue?["error"]?.objectValue?["code"] + == .string("permission.required")) + let requests = try h.gateway.permissionRuntime.service.view(owner: h.owner).requests.map( + \.request + ).filter { + !requestsBefore.contains($0.id) + } + try #require(!requests.isEmpty) + for request in requests { + guard case .permission(let content) = request.content else { + Issue.record("Expected a permission request, not another admission failure") + continue + } + if use { + guard case .project(let project) = content.requirement.permission else { + Issue.record("Expected Project write authority") + continue + } + try #require(project == h.projectID || project == "fixture") + try #require(content.requirement.value == .write) + } else { + try #require(content.requirement.permission == .plugin("cursor")) + try #require(content.requirement.value == .use) + } + if provider { + try #require(content.principal != .plugin(.package("cursor"))) + } else { + try #require(content.principal == .plugin(.package("cursor"))) + } + } + try #require(try h.nativeStarts == before) + let cli = try #require( + try h.gateway.listTools(context: .empty).first { + $0.meta?.objectValue?["cli"]?.objectValue?["command"] == .string("print") + }) + do { + let result = try await h.gateway.callFixtureTool( + name: cli.name, arguments: .object(["prompt": .string("denied")]), context: .empty) + try cursorDenied(result) + } catch is GatewayPermissionCallError {} + try #require(!FileManager.default.fileExists(atPath: h.worktree.path + "/cursor-cli-write")) + if caller == 1 && provider && use { + _ = try cursorValue(try await h.call("cursor.acp.session.list")) + } + } + } + try await withCursor(package) { h in + try await h.discover() + let cli = try #require( + try h.gateway.listTools(context: .empty).first { + $0.meta?.objectValue?["cli"]?.objectValue?["command"] == .string("print") + }) + let prompt = "--leading 'quotes' 中文\nfixture" + let cliResult = try cursorValue(try await h.callCLI(cli.name, prompt: prompt)) + try #require(cliResult["exit_code"] == .integer(0)) + let cliData = try #require(cliResult["data"]?.objectValue) + try #require(cliData["argv"]?.arrayValue?.suffix(2) == [.string("--"), .string(prompt)]) + try cursorWorkingDirectory(try #require(cliData["cwd"]?.stringValue), matches: h.worktree) + try #require( + try String( + contentsOf: h.worktree.appendingPathComponent("cursor-cli-write"), encoding: .utf8) + == "written") + let skill = try cursorValue( + try await h.gateway.callFixtureTool( + name: "skills.read", arguments: .object(["name": .string("cursor-agent")]), + context: .empty)) + try #require(skill["name"] == .string("cursor-agent")) + let session = try await h.open() + let nativeStarts = try h.nativeStarts + try #require(nativeStarts == 1) + try #require(session != "fixture-session") + let args: [String: JSONValue] = ["session": .string(session)] + let paths = String( + decoding: try JSONSerialization.data(withJSONObject: h.outside.map(\.path)), as: UTF8.self) + for _ in 0..<2 { + _ = try cursorValue( + try await h.call( + "cursor.acp.session.prompt", + args.merging([ + "prompt": .string("boundaries:" + paths) + ]) { _, b in b })) + } + try #require( + try String( + contentsOf: h.worktree.appendingPathComponent("cursor-selected-write"), encoding: .utf8) + == "written") + for path in h.outside { + try #require(try String(contentsOf: path, encoding: .utf8) == "sentinel") + } + let events = try cursorValue(try await h.call("cursor.acp.events.read", args)) + let rows = try #require(events["events"]?.arrayValue) + let records = rows.compactMap { row -> String? in + row.objectValue?["event"]?.objectValue?["params"]?.objectValue?["update"]?.objectValue?[ + "content"]?.objectValue?["text"]?.stringValue + }.filter { $0.hasPrefix("{\"cwd\"") } + try #require(records.count == 2) + for text in records { + let record = try #require( + try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any]) + try cursorWorkingDirectory(try #require(record["cwd"] as? String), matches: h.worktree) + // Project write includes read access to the source checkout, which stays read-only. + try #require( + record["denied"] as? [[String]] == [["a"], ["r", "a"], ["r", "a"], ["r", "a"]]) + } + let container = try h.base.database.prepareProviderContainer(.package("cursor")).sandbox + let firstRecord = try #require( + try JSONSerialization.jsonObject(with: Data(records[0].utf8)) as? [String: Any]) + let locations = try #require(firstRecord["paths"] as? [String: String]) + try #require( + locations == [ + "HOME": container.home.value, "XDG_CACHE_HOME": container.cache.value, + "XDG_CONFIG_HOME": container.home.value + "/.config", + "XDG_STATE_HOME": container.state.value, + ]) + for path in [container.home, container.cache, container.state] { + try #require( + try String(contentsOfFile: path.value + "/cursor-container-marker", encoding: .utf8) + == "xx") + } + // Exercise the actual offered native choice, then a retained cancelled turn. + let run = try cursorValue( + try await h.call( + "cursor.acp.session.prompt.start", + args.merging([ + "prompt": .string("permission") + ]) { _, b in b })) + let pending = try await h.waitPending(session) + let request = try #require(pending["request_id"]?.stringValue) + _ = try cursorValue( + try await h.call( + "cursor.acp.requests.respond", + [ + "session": .string(session), "request_id": .string(request), + "response": .object([ + "outcome": .object(["outcome": .string("selected"), "optionId": .string("opaque-no")]) + ]), + ])) + let completed = try await h.waitResult( + session, prompt: try #require(run["prompt_id"]?.stringValue)) + try #require(completed["is_error"] == .bool(false)) + try #require(completed["text"]?.stringValue?.contains("opaque-no") == true) + let slow = try cursorValue( + try await h.call( + "cursor.acp.session.prompt.start", args.merging(["prompt": .string("slow")]) { _, b in b } + )) + try await h.waitStarted(session) + _ = try cursorValue(try await h.call("cursor.acp.session.cancel", args)) + let cancelled = try await h.waitResult( + session, prompt: try #require(slow["prompt_id"]?.stringValue), + expectingCancellation: true) + try #require(cancelled["closed"] == .bool(false)) + try #require(try h.nativeStarts == nativeStarts) + let aRoot = try h.lastWorkload() + let aExecutions = try h.sourceWorktreeExecutions(since: 0, profileID: h.consumerID) + let aExecution = try #require(aExecutions[aRoot]) + + // Client B uses a separate authority and kill domain in the same provider container. + let beforeB = h.mcpObservations.members.count + let secondID = try #require(GatewayProfileID(rawValue: "cursor-second")) + let second = try h.makeConsumer(secondID.rawValue, caller: 2, use: true) + h.other = second + try await h.discover(gateway: second) + let secondSession = try await h.open(gateway: second) + let bRoute = try await h.observeSession(secondSession, gateway: second) + let bRoot = try h.lastWorkload() + let bExecutions = try h.sourceWorktreeExecutions(since: beforeB, profileID: secondID) + let bExecution = try #require(bExecutions[bRoot]) + try #require(aRoot != bRoot && aExecution != bExecution) + let bOwner = try h.processOwner(bRoot) + try #require(try await h.processOwner(aRoot).members().contains(aRoot)) + try #require(try await bOwner.members().contains(bRoot)) + try #require(try h.nativeStarts == 2) + print( + "Cursor revocation workloads A=\(aRoot) execution=\(aExecution)" + + " B=\(bRoot) execution=\(bExecution)") + + let service = h.gateway.permissionRuntime.service + let revocation = try service.revokePermission( + .plugin("cursor"), profileID: h.consumerID, owner: h.owner, + expectedRevision: service.view(owner: h.owner).revision) + try #require(revocation.executionsToTerminate.contains(aExecution)) + try #require(!revocation.executionsToTerminate.contains(bExecution)) + try await h.gateway.permissionRuntime.coordinator.reconcile() + try cursorDenied( + try await h.call( + "cursor.acp.session.prompt", + ["session": .string(session), "prompt": .string("must not run")])) + try await h.requireWorktreeRootsJoined(Array(aExecutions.keys)) + let siblingPrompt = "hello after Cursor A revocation" + let sibling = try cursorValue( + try await h.call( + "cursor.acp.session.prompt", + ["session": .string(secondSession), "prompt": .string(siblingPrompt)], gateway: second)) + try #require(sibling["session"] == .string(secondSession)) + try #require(sibling["stop_reason"] == .string("end_turn")) + try #require(try h.vendorTurn(pid: bRoot.processID, prompt: siblingPrompt).count == 1) + try #require(try await bOwner.members().contains(bRoot)) + try #require(try await h.observeSession(secondSession, gateway: second) == bRoute) + + // Removal is performed by the host while B still owns a live native session. + let remainingExecutions = try h.sourceWorktreeExecutions(since: beforeB, profileID: secondID) + try await h.removeWorktree() + try cursorDenied( + try await h.call( + "cursor.acp.session.prompt", + ["session": .string(secondSession), "prompt": .string("must not run")], gateway: second)) + try await h.requireWorktreeRootsJoined(Array(remainingExecutions.keys)) + } + try writeCursorEvidence( + "SOURCE", + cases: [ + "package", "declarations", "dual-authority", "cli", "mcp", "skills", "worktree", + "container", "boundaries", "continuation", "cancellation", "scoped-revocation", + "host-removal", "cleanup", + ]) + } +} + +private func writeCursorEvidence( + _ suite: String, cases: [String], details: [String: Any] = [:] +) throws { + let env = ProcessInfo.processInfo.environment + let path = try #require(env["COMPUTER_MCP_CURSOR_\(suite)_CASES"]) + var evidence = details + evidence["kind"] = "deterministic" + evidence["tests_executed"] = 1 + evidence["run_id"] = try #require(env["COMPUTER_MCP_CURSOR_\(suite)_RUN_ID"]) + evidence["cases"] = cases + try JSONSerialization.data(withJSONObject: evidence).write( + to: URL(fileURLWithPath: path), options: .atomic) +} + +private func cursorWorkingDirectory(_ reported: String, matches selected: URL) throws { + let actual = URL(fileURLWithPath: reported, isDirectory: true) + for location in [actual, selected] { + var isDirectory: ObjCBool = false + try #require(FileManager.default.fileExists(atPath: location.path, isDirectory: &isDirectory)) + try #require(isDirectory.boolValue) + } + try #require( + actual.resolvingSymlinksInPath().standardizedFileURL + == selected.resolvingSymlinksInPath().standardizedFileURL) +} + +private func cursorValue(_ value: JSONValue) throws -> [String: JSONValue] { + try #require(value.objectValue?["isError"] != .bool(true), "\(value)") + var result = try #require( + value.objectValue?["structuredContent"]?.objectValue?["result"]?.objectValue) + if let nested = result["structuredContent"]?.objectValue?["result"]?.objectValue { + try #require(result["isError"] != .bool(true), "\(value)") + result = nested + } + return result +} +private func cursorNativeValue(_ value: JSONValue) throws -> [String: JSONValue] { + let outer = try #require( + value.objectValue?["structuredContent"]?.objectValue?["result"]?.objectValue) + return try #require(outer["structuredContent"]?.objectValue?["result"]?.objectValue, "\(value)") +} + +private func cursorPromptResult( + _ reply: JSONValue, session: String, prompt: String, expectingCancellation: Bool +) throws -> [String: JSONValue] { + // The Host returns a successful envelope around Cursor's MCP reply. + try #require(reply.objectValue?["isError"] == .bool(false), "\(reply)") + let downstream = try #require( + reply.objectValue?["structuredContent"]?.objectValue?["result"]?.objectValue) + let result = try #require( + downstream["structuredContent"]?.objectValue?["result"]?.objectValue) + try #require(result["session"] == .string(session) && result["prompt_id"] == .string(prompt)) + let completed = try #require(result["completed"]?.boolValue as Bool?) + let cancelled = completed && expectingCancellation + try #require(downstream["isError"] == .bool(cancelled) && result["error"] == nil, "\(reply)") + if completed { + try #require(result["is_error"] == .bool(cancelled), "\(reply)") + } + if cancelled { + try #require(result["stop_reason"] == .string("cancelled")) + try #require(result["native_result"]?.objectValue?["stopReason"] == .string("cancelled")) + } + return result +} + +private func cursorDenied(_ value: JSONValue) throws { + try #require(value.objectValue?["isError"] == .bool(true), "\(value)") + let code = try #require( + value.objectValue?["structuredContent"]?.objectValue?["error"]?.objectValue?["code"]? + .stringValue) + try #require( + code != "permission.catalog_required", "Catalog discovery is a fixture precondition: \(value)") +} +extension GatewayAsyncToolServing { + fileprivate func callFixtureTool( + name: String, arguments: JSONValue?, context: InvocationContext + ) async throws -> JSONValue { + try Task.checkCancellation() + // Worktree preparation can wait synchronously for native Git operations. + let task = ExecutionTasks.startThrowing { + try await self.callToolForMCPAsync(name: name, arguments: arguments, context: context) + } + return try await withTaskCancellationHandler { + try await task.value + } onCancel: { + task.cancel() + } + } +} + +private func withCursor( + _ package: PluginPackage, caller: Int = 2, provider: Bool = true, + use: Bool = true, installArchive: Bool = false, observeStartup: Bool = false, + body: (CursorHarness) async throws -> Void +) async throws { + let h = try await CursorHarness.make( + package, caller: caller, provider: provider, use: use, installArchive: installArchive, + observeStartup: observeStartup) + do { try await body(h) } catch { + do { try await h.close() } catch { Issue.record("Cursor cleanup failed: \(error)") } + throw error + } + try await h.close() +} + +private struct CursorStartupBoundary { + let acquisitionID: UUID + let executionID: UUID + let probeID: UUID + let workloadID: UUID + let adapter: ExecutionMember +} + +private struct CursorTransportEvent: Decodable { + let adapterPID: Int32 + let request: [String: JSONValue] + let reply: [String: JSONValue]? + + enum CodingKeys: String, CodingKey { + case adapterPID = "adapter_pid" + case request, reply + } + + var result: [String: JSONValue]? { reply?["result"]?.objectValue } +} + +private struct CursorConsumer { + let runtime: GatewayRuntime + let generations: GatewayStandaloneGenerations +} + +private final class CursorHarness: @unchecked Sendable { + let base: FixedHostFixture + // The real proxy's launcher observes adapter and vendor starts independently + // of the platform launcher used for Host Git and CLI work. + let mcpObservations = ExecutionObservations() + let lifecycle: GatewayStandaloneGenerations + let package: PluginPackage + let plugin: ResolvedPlugin + let projectID: String + let worktree: URL + let outside: [URL] + let owner: GatewayPermissionOwner + let consumerID = GatewayProfileID(rawValue: "cursor-consumer")! + var consumer: CursorConsumer! + var gateway: GatewayRuntime { consumer.runtime } + var other: CursorConsumer? + var removed = false + + init( + base: FixedHostFixture, lifecycle: GatewayStandaloneGenerations, package: PluginPackage, + plugin: ResolvedPlugin, projectID: String, worktree: URL, outside: [URL], + owner: GatewayPermissionOwner + ) { + self.base = base + self.lifecycle = lifecycle + self.package = package + self.plugin = plugin + self.projectID = projectID + self.worktree = worktree + self.outside = outside + self.owner = owner + } + static func make( + _ package: PluginPackage, caller: Int, provider: Bool, use: Bool, installArchive: Bool, + observeStartup: Bool + ) async throws -> CursorHarness { + let base = try FixedHostFixture(fullAccess: false, lifecycle: true) + let lifecycle = GatewayStandaloneGenerations(base.runtime) + var pending: CursorHarness? + var created: String? + var stage = "worktree and package registration" + do { + let unrelated = base.root.appendingPathComponent("unrelated-project") + try FileManager.default.createDirectory(at: unrelated, withIntermediateDirectories: false) + try base.database.saveProject( + .init(id: "unrelated", displayName: "Unrelated", rootPath: unrelated.path)) + try await base.initializeRepository() + let value = try cursorValue( + try await lifecycle.callFixtureTool( + name: "git.worktree_add", arguments: .object(["name": .string("cursor")]), + context: .init(session: base.session))) + let project = try #require(value["project_id"]?.stringValue) + created = project + let path = URL(fileURLWithPath: try #require(value["path"]?.stringValue)) + let foreign = try base.database.prepareProviderContainer(.package("foreign")).sandbox + let outside = [ + base.project.appendingPathComponent("source-main"), + unrelated.appendingPathComponent("value.txt"), + base.database.permissionExecutionRoot.appendingPathComponent("host-secret"), + URL(fileURLWithPath: foreign.state.value).appendingPathComponent("foreign-secret"), + ] + for file in outside { try Data("sentinel".utf8).write(to: file) } + let peer = base.root.appendingPathComponent("cursor-peer") + let python = URL( + fileURLWithPath: try #require( + ProcessInfo.processInfo.environment["COMPUTER_MCP_CURSOR_PYTHON"]) + ).resolvingSymlinksInPath().path + let adapterPython: String + if observeStartup { + let launcher = base.root.appendingPathComponent("cursor-transport-python") + let fixture = package.root.appendingPathComponent( + "tests/Fixtures/vendor_start_transport.py") + let source = try String(contentsOf: fixture, encoding: .utf8) + try ("#!\(python)\n" + source).write(to: launcher, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes( + [.posixPermissions: 0o755], ofItemAtPath: launcher.path) + adapterPython = launcher.path + } else { + adapterPython = python + } + let fixture = package.root.appendingPathComponent("tests/Fixtures/vendor.py") + let fixtureSource = try Data(contentsOf: fixture).map { String(format: "%02x", $0) }.joined() + try """ + #!\(python) + import json, os, sys, traceback + os.environ['CURSOR_SOURCE_FIXTURE'] = '1' + def record_failure(detail): + # Failure-only diagnostics use the provider container, never the project. + try: + path = os.path.join(os.environ['HOME'], 'cursor-peer-failure.json') + with open(path, 'w') as stream: + json.dump({'version_probe': sys.argv[1:] == ['--version'], + 'detail': detail[:8192]}, stream) + except Exception as error: + print('Cursor peer diagnostic unavailable: ' + str(error), file=sys.stderr) + try: + exec(compile(bytes.fromhex('\(fixtureSource)'), 'cursor-fixture/vendor.py', 'exec')) + except SystemExit as error: + if error.code not in (None, 0): + record_failure('SystemExit: ' + str(error.code)) + raise + except BaseException: + record_failure(traceback.format_exc()) + raise + """.write(to: peer, atomically: true, encoding: .utf8) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: peer.path) + let beforeRegistration = base.observations.members.count + let store = PluginStore(database: base.database, platform: base.platform) + let env = ProcessInfo.processInfo.environment + let origin: PluginSource + let registered: PluginStoreSnapshot + if installArchive { + let archive = try #require(env["COMPUTER_MCP_CURSOR_ARCHIVE"]) + let installed = try await store.installArchive( + at: URL(fileURLWithPath: archive), + expectedSHA256: try #require(env["COMPUTER_MCP_CURSOR_ARCHIVE_SHA256"]), + pluginID: package.manifest.id, version: package.manifest.version, + hostVersion: PluginVersion(ComputerMCPCLI.version), architecture: PluginHost.architecture, + storageRoot: base.root.appendingPathComponent("plugins"), + workerExecutable: nativeGatewayTestExecutable(), + expectedRevision: store.snapshot().revision) + registered = installed.snapshot + try #require(installed.issues.isEmpty) + let selected = try #require(registered.selectedInstallations["cursor"]) + origin = try #require(registered.installations.first { $0.id == selected }).source + try #require( + origin.kind == .artifact + && origin.artifactSHA256 == env["COMPUTER_MCP_CURSOR_ARCHIVE_SHA256"]) + for path in [ + PluginManifest.filename, "cursor-vendor-execution.json", "cli-tree.json", + "bin/cursor-mcp-adapter", "bin/cursor_vendor_execution.py", "bin/plugin_runtime.py", + ] { + try #require( + try Data(contentsOf: origin.root.appendingPathComponent(path)) + == Data(contentsOf: package.root.appendingPathComponent(path))) + } + } else { + registered = try await store.registerDevelopment( + at: package.root, expectedRevision: store.snapshot().revision) + origin = .init(kind: .development, root: package.root) + } + // Archive verification may start the Host worker. Settings and approval start no provider. + let beforeSettings = base.observations.members.count + let runtimePackage = try PluginPackage.load(at: origin.root) + try #require(registered.settings["cursor"]?.enabled == false) + let settings = PluginSettings( + enabled: true, + mcp: [ + "acp": .init( + registrationID: "cursor-fixture", exposure: .reexport, prefix: "", allowAnyTool: true, + toolRisks: Dictionary( + uniqueKeysWithValues: cursorReadTools.map { ($0, CapabilityRisk.readOnly) })) + ], + cli: ["agent": .init(registrationID: "cursor-cli")], + dependencyExecutables: ["cursor-agent": peer.path, "python-runtime": adapterPython]) + _ = try await store.setSettings( + settings, for: "cursor", expectedRevision: store.snapshot().revision) + let plugin = try PluginResolver.resolve( + package: runtimePackage, source: origin, + settings: settings, + dependencyExecutables: [ + "cursor-agent": peer, "python-runtime": URL(fileURLWithPath: adapterPython), + ], + hostVersion: PluginVersion(ComputerMCPCLI.version), architecture: PluginHost.architecture) + try #require( + plugin.diagnostics.isEmpty && plugin.cliCommands.count == 1 && plugin.mcpServers.count == 1 + && plugin.skillRoots.count == 1) + let riskConfiguration = GatewayConfiguration(mcp: .init(servers: plugin.mcpServers)) + for name in cursorReadTools { + try #require( + riskConfiguration.mcpRisk(for: .init(serverID: "cursor-fixture", toolName: name)) + == .readOnly) + } + for name in cursorWriteTools.union(["cursor.acp.unknown"]) { + try #require( + riskConfiguration.mcpRisk(for: .init(serverID: "cursor-fixture", toolName: name)) + == .externalWrite) + } + let adapter = try #require(plugin.mcpServers.first) + let adapterCommand = try #require(adapter.command) + try #require( + URL(fileURLWithPath: adapterCommand).resolvingSymlinksInPath() + == URL(fileURLWithPath: adapterPython).resolvingSymlinksInPath()) + try #require(adapter.args.count == 1) + let adapterPath = URL(fileURLWithPath: try #require(adapter.args.first)) + let installedAdapter = runtimePackage.root.appendingPathComponent("bin/cursor-mcp-adapter") + try #require( + adapterPath.resolvingSymlinksInPath() == installedAdapter.resolvingSymlinksInPath()) + print( + "Cursor fixture adapter launch: \(adapterCommand) \(adapter.args); native peer interpreter: \(python)" + ) + let owner = try GatewayPermissionOwner( + context: .init( + caller: .localApp, profileID: .localAdmin, trustedPrincipalID: "cursor-owner"), + validate: {}) + let h = CursorHarness( + base: base, lifecycle: lifecycle, package: runtimePackage, plugin: plugin, + projectID: project, + worktree: path, outside: outside, owner: owner) + pending = h + let lifecycleProfile = try #require( + base.database.profiles().first { $0.id == base.configuration.runtime.profileID }) + stage = "consumer generation" + h.consumer = try h.makeConsumer("cursor-consumer", caller: caller, use: use) + try #require( + base.database.profiles().first { $0.id == lifecycleProfile.id } == lifecycleProfile) + try #require(base.observations.members.count == beforeSettings) + try #require(h.mcpObservations.members.isEmpty) + if origin.kind == .development { + try #require(beforeSettings == beforeRegistration) + } + try #require(try h.nativeStarts == 0) + stage = "provider approval" + try fixtureApprovePlugin( + runtimePackage, database: base.database, runtime: h.gateway.permissionRuntime, + permissions: fixturePermissions([.project("fixture"): .granted(provider ? .write : .read)])) + let approval = try #require( + h.gateway.permissionRuntime.service.view(owner: owner).providers.first { + $0.identity == .package("cursor") + }) + try #require(approval.enabled && approval.fullAccessConsent == nil) + return h + } catch let setupError { + print("Cursor fixture setup failed during \(stage) in \(base.root.path): \(setupError)") + do { + if let pending { + try await pending.close() + } else { + if let created { + _ = try cursorValue( + try await lifecycle.callFixtureTool( + name: "git.worktree_remove", + arguments: .object(["project_id": .string(created), "force": .bool(true)]), + context: .init(session: base.session))) + } + await lifecycle.shutdown() + base.session.end() + await base.runtime.shutdown() + try FileManager.default.removeItem(at: base.root) + } + } catch { + if pending == nil { + await lifecycle.shutdown() + base.session.end() + await base.runtime.shutdown() + } + Issue.record("Cursor fixture setup cleanup failed in \(base.root.path): \(error)") + } + throw setupError + } + } + var nativeStarts: Int { + get throws { + let home = try base.database.prepareProviderContainer(.package("cursor")).sandbox.home + let path = URL(fileURLWithPath: home.value).appendingPathComponent( + "cursor-native-starts.jsonl") + return (try? String(contentsOf: path, encoding: .utf8).split(separator: "\n").count) ?? 0 + } + } + func makeConsumer(_ name: String, caller: Int, use: Bool) throws -> CursorConsumer { + let id = try #require(GatewayProfileID(rawValue: name)) + try #require(id != .localAdmin && id != base.configuration.runtime.profileID) + var permissions = fixturePermissions([ + .skills: .granted(.access), .machineInformation: .granted(.access), + ]) + if caller > 0 { + try permissions.set(.granted(caller == 2 ? .write : .read), for: .project("fixture")) + } + if use { try permissions.set(.granted(.use), for: .plugin("cursor")) } + let grant = ProfileGrant(id: id, permissions: permissions, allowedCallers: [.localMCP]) + try base.database.saveProfile(grant) + let gateway = try GatewayRuntime( + configuration: .init( + runtime: .init(caller: .localMCP, profileID: id), + profiles: base.configuration.profiles + [.init(grant: grant)]), + context: .init( + caller: .localMCP, profileID: id, projectID: projectID, trustedPrincipalID: name), + database: base.database, registeredProjects: base.database.projects(), + platform: base.platform, + mcpClient: MCPProxyClient(launcher: testExecutionLauncher(observations: mcpObservations)), + plugins: [plugin], bundledPlugins: .init(packages: [], issues: [])) + _ = try gateway.makeControlSession() + return .init(runtime: gateway, generations: GatewayStandaloneGenerations(gateway)) + } + func catalog(gateway selected: CursorConsumer? = nil) async throws -> JSONValue { + try await (selected ?? consumer!).generations.callFixtureTool( + name: "mcp.tools.list", arguments: .object(["server": .string("cursor-fixture")]), + context: .empty) + } + func discover(gateway selected: CursorConsumer? = nil) async throws { + let firstOwnership = mcpObservations.ownerships.count + let result = try await catalog(gateway: selected) + if result.objectValue?["isError"] == .bool(true) { + await reportLaunchFailure( + mcpObservations.ownerships.dropFirst(firstOwnership), operation: "discovery") + } + try #require(result.objectValue?["isError"] != .bool(true), "\(result)") + let tools = try #require( + result.objectValue?["structuredContent"]?.objectValue?["result"]?.arrayValue) + let names = Set(tools.compactMap { $0.objectValue?["name"]?.stringValue }) + try #require(names == cursorReadTools.union(cursorWriteTools)) + } + func callCLI(_ name: String, prompt: String) async throws -> JSONValue { + let firstOwnership = base.observations.ownerships.count + let result = try await gateway.callFixtureTool( + name: name, arguments: .object(["prompt": .string(prompt)]), context: .empty) + if result.objectValue?["isError"] == .bool(true) { + await reportLaunchFailure( + base.observations.ownerships.dropFirst(firstOwnership), + operation: "CLI compatibility/target") + let home = try base.database.prepareProviderContainer(.package("cursor")).sandbox.home + let diagnostic = URL(fileURLWithPath: home.value).appendingPathComponent( + "cursor-peer-failure.json") + if let stream = try? FileHandle(forReadingFrom: diagnostic) { + defer { try? stream.close() } + let data = try stream.read(upToCount: 16384) ?? Data() + print("Cursor peer failure diagnostic: \(String(decoding: data, as: UTF8.self))") + } else { + print( + "Cursor peer recorded no Python failure diagnostic; startup/termination/output matching remains unconfirmed" + ) + } + } + return result + } + func reportLaunchFailure( + _ ownerships: ArraySlice, operation: String + ) async { + for ownership in ownerships { + do { + let exit = try await ownership.wait(until: .now.advanced(by: .milliseconds(250))) + print( + "Cursor \(operation) process exit: status=\(exit.status), signal=\(String(describing: exit.signal))" + ) + } catch { + print("Cursor \(operation) process exit unconfirmed: \(error)") + } + do { + print("Cursor \(operation) process remaining members: \(try await ownership.members())") + } catch { + print("Cursor \(operation) process membership unavailable: \(error)") + } + } + } + func call( + _ name: String, _ args: [String: JSONValue] = [:], gateway selected: CursorConsumer? = nil, + startRequestID: String? = nil + ) async throws -> JSONValue { + var arguments: [String: JSONValue] = [ + "server": .string("cursor-fixture"), "tool": .string(name), "arguments": .object(args), + ] + if let startRequestID { + arguments["request_id"] = .string(startRequestID) + arguments["wait_for_result"] = .bool(false) + } + let client = selected ?? consumer! + do { + return try await client.generations.callFixtureTool( + name: "mcp.tools.call", arguments: .object(arguments), context: .empty) + } catch { + return client.runtime.routingErrorForMCP( + error, name: "mcp.tools.call", arguments: .object(arguments), invocationContext: .empty) + } + } + func requestReceipt(_ id: String) async throws -> [String: JSONValue] { + try cursorValue( + try await consumer.generations.callFixtureTool( + name: "mcp.requests.read", + arguments: .object(["server": .string("cursor-fixture"), "request_id": .string(id)]), + context: .empty)) + } + func requireMCPLaunches(since index: Int, exactly expected: [ExecutionMember]) throws { + try requireMCPLaunches(Array(mcpObservations.members.dropFirst(index)), exactly: expected) + } + + func requireMCPLaunches(_ observed: [ExecutionMember], exactly expected: [ExecutionMember]) throws + { + try #require(observed.count == expected.count) + try #require(Set(observed) == Set(expected)) + } + + func processOwner(_ member: ExecutionMember) throws -> any ExecutionOwnership { + let matches = mcpObservations.ownerships.filter { (try? $0.recoveryState().root) == member } + try #require(matches.count == 1) + return try #require(matches.first) + } + + func processMember(pid: Int32) throws -> ExecutionMember { + let matches = mcpObservations.members.filter { $0.processID == pid } + try #require(matches.count == 1) + return try #require(matches.first) + } + + func peerMember(_ effect: [String: JSONValue]) throws -> ExecutionMember { + let pid = try #require(effect["pid"]?.intValue.flatMap(Int32.init(exactly:))) + return try processMember(pid: pid) + } + + func lastWorkload() throws -> ExecutionMember { + try peerMember(try #require(try vendorEffects().last { $0["phase"] == .string("workload") })) + } + + func sourceWorktreeExecutions(since index: Int, profileID: GatewayProfileID) throws + -> [ExecutionMember: UUID] + { + let roots = mcpObservations.members.dropFirst(index) + let provider = PluginIdentity.package("cursor") + return try gateway.permissionRuntime.store.readWithDatabase { database, ledger in + let records = try ExecutionRuntimeRecord.all(database) + var worktree: [ExecutionMember: UUID] = [:] + for root in roots { + let matches = records.filter { record in + record.children.values.contains { $0.recovery?.root == root } + } + let identity = "pid=\(root.processID) identity=\(root.identity)" + try #require(matches.count == 1, "\(identity) must have one Host execution") + let record = try #require(matches.first) + let execution = try #require(ledger.executions[record.id]) + if execution.owner == .plugin(provider) && execution.delegatedTo == nil { + // Catalog discovery uses the provider's grant without a worktree reservation. + try #require(record.worktreeUse == nil && record.auditIdentity?.projectID == nil) + try #require(execution.authorizationIDs.count == 1) + print("Cursor discovery for \(profileID.rawValue) \(identity) execution=\(record.id)") + } else { + try #require(execution.delegatedTo == provider && execution.authorizationIDs.count == 2) + try #require(record.auditIdentity?.profileID == profileID) + try #require(record.worktreeUse?.admission.projectID == projectID) + worktree[root] = record.id + print("Cursor \(profileID.rawValue) worktree \(identity) execution=\(record.id)") + } + } + return worktree + } + } + + func requireWorktreeRootsJoined(_ roots: [ExecutionMember]) async throws { + let deadline = ContinuousClock.now + .seconds(2) + for root in roots { + let ownership = try processOwner(root) + do { + _ = try await ownership.wait(until: deadline) + let remaining = try await ownership.members() + try #require(remaining.isEmpty, "Cursor worktree root \(root): \(remaining)") + } catch { + print("Cursor worktree root \(root) did not join: \(error)") + throw error + } + } + } + + func requirePeerEvidence(_ root: ExecutionMember, phase: String) throws { + let matching = try vendorEffects().filter { + $0["phase"] == .string(phase) && $0["pid"] == .integer(Int64(root.processID)) + } + try #require(matching.count == 1) + try #require(try peerMember(try #require(matching.first)) == root) + } + + func waitStartedWorkload(_ boundary: CursorStartupBoundary) async throws -> ExecutionMember { + let deadline = ContinuousClock.now + .seconds(4) + repeat { + let workload = try startupChildren(boundary).workload + if let root = workload.recovery?.root, + try vendorEffects().contains(where: { + $0["phase"] == .string("workload") && $0["pid"]?.intValue == Int(root.processID) + }) + { + try #require(!workload.completed && workload.recovery?.sandboxed == true) + try requirePeerEvidence(root, phase: "workload") + return root + } + try await Task.sleep(for: .milliseconds(20)) + } while ContinuousClock.now < deadline + throw CursorFixtureError.deadline + } + + func verifySiblingIO(_ session: String, root: ExecutionMember, suffix: String) async throws + -> String + { + let fixture = worktree.appendingPathComponent("cursor-sibling-io") + let initial = "owner-provided-\(suffix):" + try Data(initial.utf8).write(to: fixture) + let promptText = "worktree-io:\(suffix)" + let reply = try cursorValue(try await prompt(session, promptText)) + try #require( + reply["session"] == .string(session) && reply["stop_reason"] == .string("end_turn")) + try #require(reply["text"] == .string(initial)) + try #require(try String(contentsOf: fixture, encoding: .utf8) == initial + suffix) + try await waitVendorPrompt(pid: root.processID, prompt: promptText) + let owner = try processOwner(root) + try #require(try await owner.members().contains(root)) + return promptText + } + + private var transportDirectory: URL { + get throws { + let home = try base.database.prepareProviderContainer(.package("cursor")).sandbox.home + return URL(fileURLWithPath: home.value).appendingPathComponent("cursor-start-transport") + } + } + + func armStartupFault(_ fault: String) throws { + try fault.write( + to: transportDirectory.appendingPathComponent("fault"), atomically: true, encoding: .utf8) + } + + func releaseTransport(_ name: String) throws { + try Data().write( + to: transportDirectory.appendingPathComponent(name + ".release"), options: .atomic) + } + + func requireNoTransportEvent(_ name: String) throws { + let path = try transportDirectory.appendingPathComponent(name + ".json") + try #require(!FileManager.default.fileExists(atPath: path.path)) + } + + func waitTransport(_ name: String, timeout: Duration = .seconds(7)) async throws + -> CursorTransportEvent + { + let path = try transportDirectory.appendingPathComponent(name + ".json") + let deadline = ContinuousClock.now + timeout + repeat { + if FileManager.default.fileExists(atPath: path.path) { + let event = try JSONDecoder().decode( + CursorTransportEvent.self, from: Data(contentsOf: path)) + if let reply = event.reply { try #require(reply["id"] == event.request["id"]) } + return event + } + try await Task.sleep(for: .milliseconds(20)) + } while ContinuousClock.now < deadline + Issue.record("Cursor fixture did not observe \(name)") + throw CursorFixtureError.deadline + } + + func startOpen(_ id: String) async throws -> [String: JSONValue] { + let started = try cursorValue( + try await call( + "cursor.acp.session.open", ["permission_policy": .string("manual")], startRequestID: id)) + try #require(started["request_id"] == .string(id) && started["state"] == .string("running")) + return started + } + + func startupBoundary(_ launch: CursorTransportEvent) async throws -> CursorStartupBoundary { + let bind = try await waitTransport("bind") + let probe = try await waitTransport("probe") + let binding = try #require(bind.result) + let acquisition = try #require( + launch.request["acquisition"]?.stringValue.flatMap { UUID(uuidString: $0) }) + let probeID = try #require(binding["probe"]?.stringValue.flatMap { UUID(uuidString: $0) }) + let workloadID = try #require(binding["workload"]?.stringValue.flatMap { UUID(uuidString: $0) }) + try #require( + launch.request["op"] == .string("launch") && launch.request["child"] == binding["workload"]) + try #require(bind.request["op"] == .string("bind") && probe.request["op"] == .string("probe")) + try #require(probe.request["child"] == binding["probe"]) + for event in [bind, probe, launch] { + try #require(event.adapterPID == launch.adapterPID) + try #require(event.request["acquisition"] == launch.request["acquisition"]) + try #require(event.request["call"] == launch.request["acquisition"]) + } + let adapter = try processMember(pid: launch.adapterPID) + try #require(try processOwner(adapter).recoveryState().sandboxed) + let matching = try gateway.permissionRuntime.store.readWithDatabase { database, ledger in + try ledger.executions.values.compactMap { execution -> UUID? in + guard execution.delegatedTo == .package("cursor"), + let record = try ExecutionRuntimeRecord.load(execution.id, database), + record.children[probeID] != nil, record.children[workloadID] != nil + else { return nil } + try #require(record.children.count == 2) + return execution.id + } + } + try #require(matching.count == 1) + let execution = try #require(matching.first) + let boundary = CursorStartupBoundary( + acquisitionID: acquisition, executionID: execution, probeID: probeID, workloadID: workloadID, + adapter: adapter) + let receipt = try startupReply(probe, boundary: boundary) + try #require( + receipt["probe_state"] == .string("retired") && receipt["probe_settled"] == .bool(true)) + try #require(receipt["workload_settled"] == .bool(false)) + return boundary + } + + func startupReply(_ event: CursorTransportEvent, boundary: CursorStartupBoundary) throws + -> [String: JSONValue] + { + let value = try #require(event.result) + try #require( + event.request["acquisition"] == .string(boundary.acquisitionID.uuidString.lowercased())) + try #require(value["probe"] == .string(boundary.probeID.uuidString.lowercased())) + try #require(value["workload"] == .string(boundary.workloadID.uuidString.lowercased())) + return value + } + + func requireNewRequest(_ event: CursorTransportEvent, after earlier: CursorTransportEvent) throws + { + let newerID = try #require(event.request["id"]?.intValue) + let earlierID = try #require(earlier.request["id"]?.intValue) + try #require(newerID > earlierID) + for field in ["acquisition", "call", "child"] { + try #require(event.request[field] == earlier.request[field]) + } + } + + func startupChildren(_ boundary: CursorStartupBoundary) throws + -> (probe: ExecutionRuntimeRecord.Child, workload: ExecutionRuntimeRecord.Child) + { + try gateway.permissionRuntime.store.readWithDatabase { database, ledger in + try #require(ledger.executions[boundary.executionID]?.delegatedTo == .package("cursor")) + let record = try #require(try ExecutionRuntimeRecord.load(boundary.executionID, database)) + let probe = try #require(record.children[boundary.probeID]) + let workload = try #require(record.children[boundary.workloadID]) + try #require(record.children.count == 2) + return (probe, workload) + } + } + + func phaseJournal(_ child: UUID, boundary: CursorStartupBoundary) throws + -> ExecutionRecoveryJournal.Entry + { + try phaseJournal(child, execution: boundary.executionID) + } + + func phaseJournal(_ child: UUID, execution: UUID) throws -> ExecutionRecoveryJournal.Entry { + let path = base.database.permissionExecutionRoot.appendingPathComponent("ownership") + .appendingPathComponent(child.uuidString + ".json") + let entry = try JSONDecoder().decode( + ExecutionRecoveryJournal.Entry.self, from: Data(contentsOf: path)) + try #require(entry.child == child && entry.execution == execution) + try #require(entry.recovery.sandboxed) + return entry + } + + func requireNeverLaunched(_ boundary: CursorStartupBoundary, probe: ExecutionMember) async throws + { + let stopped = try startupChildren(boundary) + try #require(stopped.probe.completed && stopped.probe.recovery?.root == probe) + try #require(stopped.workload.completed && stopped.workload.recovery == nil) + let durable = try phaseJournal(boundary.probeID, boundary: boundary) + try #require(durable.completed && durable.recovery.root == probe) + let missing = base.database.permissionExecutionRoot.appendingPathComponent("ownership") + .appendingPathComponent(boundary.workloadID.uuidString + ".json") + try #require(!FileManager.default.fileExists(atPath: missing.path)) + let owner = try processOwner(probe) + try #require(try await owner.members().isEmpty) + } + + func startupEvidence( + _ boundary: CursorStartupBoundary, requestID: String, downstream: String + ) -> [String: Any] { + [ + "request_id": requestID, "downstream_request_id": downstream, + "acquisition": boundary.acquisitionID.uuidString, + "execution": boundary.executionID.uuidString, + "probe": boundary.probeID.uuidString, "workload": boundary.workloadID.uuidString, + ] + } + + func vendorRequestOwner(_ id: String) async throws -> (locator: JSONValue, connectionID: UUID) { + // A parked request has a host lease before the adapter can report a session resource. + let live = gateway.ownedWork.snapshot.filter { $0.kind == .mcpRequest && $0.resourceID == id } + try #require( + live.count == 1, "Pending MCP request \(id) in \(projectID), host leases \(live)") + let request = try #require(live.first) + try #require(request.projectID == projectID && request.registrationID == "cursor-fixture") + let connectionID = try #require(request.connectionID) + let report = try cursorValue( + try await consumer.generations.callFixtureTool( + name: "runtime.owners.list", + arguments: .object([ + "project_id": .string(projectID), "server": .string("cursor-fixture"), + ]), context: .empty)) + let owners = try #require(report["owners"]?.arrayValue) + let matches = owners.compactMap(\.objectValue).filter { + $0["kind"] == .string("mcpRequest") && $0["resource_id"] == .string(id) + } + let visible = owners.prefix(8).compactMap(\.objectValue).map { + [$0["kind"], $0["resource_id"], $0["connection_id"]] + } + try #require( + matches.count == 1, "Pending MCP request \(id) in \(projectID), public owners \(visible)") + let row = try #require(matches.first) + try #require(row["server"] == .string("cursor-fixture")) + try #require(row["connection_id"] == .string(connectionID.uuidString)) + let locator = try #require(row["owner"]) + let selected = try GatewayOwnerSelection(locator) + try #require(selected.runtimeID == gateway.generationID && selected.projectID == projectID) + try #require(selected.ownershipID == request.id) + print( + "Cursor startup request \(id) is owned by \(request.id) in \(projectID), connection \(connectionID)" + ) + return (locator, connectionID) + } + func closeVendorConnection(_ owner: (locator: JSONValue, connectionID: UUID)) async throws + -> [String: JSONValue] + { + try cursorValue( + try await consumer.generations.callFixtureTool( + name: "runtime.owners.call", + arguments: .object([ + "project_id": .string(projectID), "owner": owner.locator, + "tool": .string("mcp.connections.close"), + "arguments": .object(["server": .string("cursor-fixture")]), + ]), context: .empty)) + } + func waitRequestReceipt(_ id: String) async throws -> [String: JSONValue] { + let deadline = ContinuousClock.now + .seconds(5) + repeat { + let receipt = try await requestReceipt(id) + if receipt["state"] != .string("running") { return receipt } + try await Task.sleep(for: .milliseconds(20)) + } while ContinuousClock.now < deadline + throw CursorFixtureError.deadline + } + func open(gateway selected: CursorConsumer? = nil) async throws -> String { + let session = try #require( + try cursorValue( + try await call( + "cursor.acp.session.open", ["permission_policy": .string("manual")], gateway: selected + ))["session"]?.stringValue) + _ = try await observeSession(session, gateway: selected) + return session + } + + func observeSession(_ session: String, gateway selected: CursorConsumer? = nil) async throws + -> MCPContinuationDirectory.Match + { + let runtime = (selected ?? consumer!).runtime + let arguments = JSONValue.object([ + "server": .string("cursor-fixture"), "tool": .string("cursor.acp.requests.list"), + "arguments": .object(["session": .string(session)]), + ]) + // Wait only for the Host's asynchronous ownership report; no tool is dispatched here. + let deadline = ContinuousClock.now + .seconds(5) + repeat { + let lookups = try runtime.continuationLookups( + name: "mcp.tools.call", arguments: arguments, projectID: projectID) + let reports = lookups.flatMap { $0.observation.matches } + if !reports.isEmpty { + try #require(reports.count == 1) + let report = try #require(reports.first) + try #require(report.connected && !report.uncertain) + return report + } + try await Task.sleep(for: .milliseconds(20)) + } while ContinuousClock.now < deadline + Issue.record("Host did not observe the Cursor session owner") + throw CursorFixtureError.deadline + } + + func prompt(_ session: String, _ prompt: String) async throws -> JSONValue { + try await call( + "cursor.acp.session.prompt", ["session": .string(session), "prompt": .string(prompt)]) + } + func observedPrompt( + _ session: String, _ text: String, pid: Int32, started: ContinuousClock.Instant + ) async throws -> JSONValue { + reportIsolation("starting \(text) on \(pid)", started: started) + do { + let reply = try await prompt(session, text) + let outer = reply.objectValue?["structuredContent"]?.objectValue + let inner = outer?["result"]?.objectValue + let result = inner?["structuredContent"]?.objectValue?["result"]?.objectValue + let requestID = outer?["gateway_execution"]?.objectValue?["request_id"]?.stringValue + let audit = requestID.flatMap { try? base.database.auditEvent(requestID: $0) } + let outcome = JSONValue.object([ + "request_id": requestID.map(JSONValue.string) ?? .null, + "gateway_duration_ms": audit?.durationMilliseconds.map { .integer(Int64($0)) } ?? .null, + "outer_error": outer?["error"] ?? .null, + "adapter_error": result?["error"] ?? .null, + "native_result": result?["native_result"] ?? .null, + ]) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = try encoder.encode(outcome) + reportIsolation( + "\(text) returned " + String(decoding: data.prefix(2_048), as: UTF8.self), + started: started) + return reply + } catch { + reportIsolation("\(text) threw \(error)", started: started) + throw error + } + } + func reportIsolation(_ event: String, started: ContinuousClock.Instant) { + let elapsed = started.duration(to: .now).components + let elapsedMS = elapsed.seconds * 1_000 + elapsed.attoseconds / 1_000_000_000_000_000 + let wallMS = Int64(Date().timeIntervalSince1970 * 1_000) + print("Cursor isolation [\(wallMS) +\(elapsedMS)ms] \(event)") + } + func reportAcquisitionLifetimes( + _ acquisitions: [[String: Any]], started: ContinuousClock.Instant + ) { + let ids = acquisitions.compactMap { + ($0["execution"] as? String).flatMap(UUID.init(uuidString:)) + } + do { + let states = try gateway.permissionRuntime.store.readWithDatabase { database, ledger in + try ids.map { id -> String in + guard let execution = ledger.executions[id] else { return "\(id) unavailable" } + let record = try ExecutionRuntimeRecord.load(id, database) + let ended = + execution.endedAt.map { + String(Int64($0.timeIntervalSince1970 * 1_000)) + } ?? "none" + let children = + record?.children.values.compactMap { child -> String? in + guard let pid = child.recovery?.root.processID else { return nil } + return "\(pid) completed=\(child.completed)" + }.sorted() ?? [] + let limit = execution.limitEndReason?.rawValue ?? "none" + return + "\(id) running=\(execution.isRunning) end_ms=\(ended) limit_end=\(limit) children=\(children)" + } + } + for state in states { reportIsolation(state, started: started) } + } catch { + reportIsolation("ledger read failed \(error)", started: started) + } + } + func stop(_ session: String) async throws -> JSONValue { + try await call("cursor.acp.session.cancel", ["session": .string(session)]) + } + func vendorEffects() throws -> [[String: JSONValue]] { + let home = try base.database.prepareProviderContainer(.package("cursor")).sandbox.home + let path = URL(fileURLWithPath: home.value).appendingPathComponent( + "cursor-vendor-effects.jsonl") + guard let data = try? String(contentsOf: path, encoding: .utf8) else { return [] } + return try data.split(separator: "\n").map { + try JSONDecoder().decode([String: JSONValue].self, from: Data($0.utf8)) + } + } + func waitVendorPrompt(pid: Int32, prompt: String) async throws { + for _ in 0..<400 { + if try vendorEffects().contains(where: { + $0["pid"]?.intValue == Int(pid) && $0["phase"]?.stringValue == "prompt" + && $0["prompt"]?.stringValue == prompt + }) { + return + } + try await Task.sleep(for: .milliseconds(10)) + } + throw CursorFixtureError.deadline + } + func vendorTurn(pid: Int32, prompt: String) throws -> [[String: JSONValue]] { + let rows = try vendorEffects() + let turn = rows.last { + $0["phase"]?.stringValue == "prompt" && $0["pid"]?.intValue == Int(pid) + && $0["prompt"]?.stringValue == prompt + }?["acp_id"] + return rows.filter { + turn != nil && $0["pid"]?.intValue == Int(pid) && $0["acp_id"] == turn + } + } + func nativeStop( + _ root: ExecutionMember, prompt: String, stop: JSONValue, promptReply: JSONValue, + terminalLogged: Bool = true + ) throws -> (event: [String: JSONValue], receipt: [String: Any]) { + let turn = try vendorTurn(pid: root.processID, prompt: prompt) + let expectedPhases: [String?] = + terminalLogged ? ["prompt", "cancel", "terminal"] : ["prompt", "cancel"] + try #require(turn.map { $0["phase"]?.stringValue } == expectedPhases, "\(turn)") + let event = try #require(turn.dropFirst().first) + let acpID = try #require(event["acp_id"]?.intValue) + try #require(event["native_session"] == turn.first?["native_session"]) + let stopID = try #require( + stop.objectValue?["structuredContent"]?.objectValue?["gateway_execution"]?.objectValue?[ + "request_id"]?.stringValue) + let promptID = try #require( + promptReply.objectValue?["request_id"]?.stringValue + ?? promptReply.objectValue?["structuredContent"]?.objectValue?["gateway_execution"]? + .objectValue?["request_id"]?.stringValue) + var receipt: [String: Any] = [ + "prompt": prompt, "peer_pid": Int(root.processID), "peer_identity": String(root.identity), + "acp_id": acpID, "stop_request_id": stopID, "prompt_request_id": promptID, + ] + if let downstream = promptReply.objectValue?["downstream_request_id"]?.stringValue { + receipt["downstream_request_id"] = downstream + } + return (event, receipt) + } + + func reportStop(pid: Int32, prompt: String, stop: JSONValue, reply: JSONValue) { + let effects = (try? vendorTurn(pid: pid, prompt: prompt)) ?? [] + let trace = JSONValue.object([ + "prompt": .string(prompt), "peer_pid": .integer(Int64(pid)), + "peer": .array(effects.prefix(5).map(JSONValue.object)), + "stop": stop, "reply": reply, + ]) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + if let data = try? encoder.encode(trace) { + print("Cursor gate stop " + String(decoding: data.prefix(8_192), as: UTF8.self)) + } + } + func verifyAcquisitions( + first: [ExecutionMember], second: [ExecutionMember], adapter: ExecutionMember + ) throws -> [[String: Any]] { + try gateway.permissionRuntime.store.readWithDatabase { database, ledger in + var rows: [[String: Any]] = [] + var executions: Set = [] + var proofs: Set = [] + var children: Set = [] + for pair in [first, second] { + let roots = Set(pair) + var matched = false + for execution in ledger.executions.values where execution.delegatedTo == .package("cursor") + { + guard let record = try ExecutionRuntimeRecord.load(execution.id, database) else { + continue + } + let slots = record.children.filter { _, record in + record.recovery.map { roots.contains($0.root) } ?? false + } + guard slots.count == 2 else { continue } + let newExecution = executions.insert(execution.id).inserted + try #require(!matched && newExecution) + matched = true + try #require(execution.authorizationIDs.count == 2) + for id in execution.authorizationIDs { + let newProof = proofs.insert(id).inserted + try #require(newProof && ledger.authorizations[id]?.executionID == execution.id) + } + for id in slots.keys { + let newChild = children.insert(id).inserted + try #require(newChild) + } + var row: [String: Any] = [ + "execution": execution.id.uuidString, + "authorization_ids": execution.authorizationIDs.map(\.uuidString).sorted(), + "adapter_pid": adapter.processID, + "adapter_identity": String(adapter.identity), + ] + if rows.isEmpty { + try #require(record.children.count == 3) + let adapterSlot = try #require( + record.children.first { $0.value.recovery?.root == adapter }) + let inserted = children.insert(adapterSlot.key).inserted + try #require(inserted) + try verifyDurableLaunch(adapterSlot.key, in: record, root: adapter, completed: false) + row["adapter_child"] = adapterSlot.key.uuidString + } else { + try #require(record.children.count == 2) + row["adapter_child"] = rows[0]["adapter_child"] + } + for (phase, root) in zip(["probe", "workload"], pair) { + let slot = try #require(slots.first { $0.value.recovery?.root == root }) + try verifyDurableLaunch(slot.key, in: record, root: root, completed: phase == "probe") + row[phase + "_child"] = slot.key.uuidString + row[phase + "_pid"] = root.processID + row[phase + "_identity"] = String(root.identity) + } + rows.append(row) + } + try #require(matched) + } + return rows + } + } + private func verifyDurableLaunch( + _ child: UUID, in record: ExecutionRuntimeRecord, root: ExecutionMember, completed: Bool + ) throws { + let slot = try #require(record.children[child]) + try #require(slot.recovery?.root == root && slot.recovery?.sandboxed == true) + try #require(slot.completed == completed) + let entry = try phaseJournal(child, execution: record.id) + try #require(entry.owner == record.ownerID && entry.boot == record.boot) + try #require(entry.recovery.root == root && entry.completed == completed) + _ = try processOwner(root) + } + + func waitPending(_ session: String) async throws -> [String: JSONValue] { + for _ in 0..<200 { + let value = try cursorValue( + try await call("cursor.acp.requests.list", ["session": .string(session)])) + if let item = value["requests"]?.arrayValue?.first?.objectValue { return item } + try await Task.sleep(for: .milliseconds(10)) + } + throw CursorFixtureError.deadline + } + func waitStarted(_ session: String) async throws { + for _ in 0..<200 { + let value = try cursorValue( + try await call("cursor.acp.events.read", ["session": .string(session)])) + let rows = value["events"]?.arrayValue ?? [] + if rows.contains(where: { row in + row.objectValue?["event"]?.objectValue?["params"]?.objectValue?["update"]?.objectValue?[ + "content"]?.objectValue?["text"] == .string("started") + }) { + return + } + try await Task.sleep(for: .milliseconds(10)) + } + throw CursorFixtureError.deadline + } + func waitResult(_ session: String, prompt: String, expectingCancellation: Bool = false) + async throws -> [String: JSONValue] + { + for _ in 0..<200 { + let reply = try await call( + "cursor.acp.session.prompt.result", + ["session": .string(session), "prompt_id": .string(prompt)]) + let value = try cursorPromptResult( + reply, session: session, prompt: prompt, expectingCancellation: expectingCancellation) + if value["completed"] == .bool(true) { return value } + try await Task.sleep(for: .milliseconds(10)) + } + throw CursorFixtureError.deadline + } + func removeWorktree() async throws { + _ = try cursorValue( + try await lifecycle.callFixtureTool( + name: "git.worktree_remove", + arguments: .object(["project_id": .string(projectID), "force": .bool(true)]), + context: .init(session: base.session))) + removed = true + try #require(!FileManager.default.fileExists(atPath: worktree.path)) + } + func requireJoined() async throws { + for _ in 0..<200 { + try await (consumer?.runtime ?? base.runtime).permissionRuntime.coordinator.reconcile() + var live = false + for ownership in base.observations.ownerships + mcpObservations.ownerships { + if try await ownership.members().isEmpty == false { live = true } + } + if !live { return } + try await Task.sleep(for: .milliseconds(10)) + } + throw CursorFixtureError.deadline + } + func close() async throws { + await consumer?.generations.shutdown() + await other?.generations.shutdown() + let cleanupError: (any Error)? + do { + if !removed { try await removeWorktree() } + try await requireJoined() + try await base.requireNoScratch() + cleanupError = nil + } catch { + cleanupError = error + } + await lifecycle.shutdown() + base.session.end() + await base.runtime.shutdown() + if let cleanupError { throw cleanupError } + try FileManager.default.removeItem(at: base.root) + try #require(!FileManager.default.fileExists(atPath: base.root.path)) + } +} +private enum CursorFixtureError: Error { case deadline } diff --git a/tests/Fixtures/package-smoke.json b/tests/Fixtures/package-smoke.json new file mode 100644 index 0000000..1a048cf --- /dev/null +++ b/tests/Fixtures/package-smoke.json @@ -0,0 +1,29 @@ +{ + "call": { + "kind": "mcp", + "component": "acp", + "tool": "cursor.acp.prompt", + "arguments": { + "prompt": "hello" + } + }, + "expected": { + "isError": false, + "structuredContent": { + "result": { + "isError": false, + "structuredContent": { + "result": { + "session_id": "fixture-session", + "stop_reason": "end_turn", + "text": "hello", + "native_result": { + "stopReason": "end_turn" + }, + "closed": true + } + } + } + } + } +} diff --git a/tests/Fixtures/vendor.py b/tests/Fixtures/vendor.py index cddefd7..5e5a3dd 100755 --- a/tests/Fixtures/vendor.py +++ b/tests/Fixtures/vendor.py @@ -7,14 +7,61 @@ import sys import time +def observe(phase, **fields): + if os.environ.get('CURSOR_SOURCE_FIXTURE') == '1': + with (Path(os.environ['HOME']) / 'cursor-vendor-effects.jsonl').open('a') as stream: + stream.write(json.dumps({'pid': os.getpid(), 'phase': phase, + 'time_ms': time.time_ns() // 1000000, **fields}) + '\n') + + if sys.argv[1:]==['--version']: + observe('probe') + if release := os.environ.get('FIXTURE_VERSION_RELEASE'): + deadline = time.monotonic() + 15 + while not Path(release).is_file() and time.monotonic() < deadline: + time.sleep(.02) print('unsupported' if os.environ.get('FIXTURE_WRONG_VERSION') else '2026.05.04-08e5280') raise SystemExit -assert sys.argv[1:]==['acp'] +def boundaries(paths): + record = {'cwd': os.getcwd(), 'paths': {}, 'denied': []} + Path('cursor-selected-write').write_text('written') + for key in ('HOME', 'XDG_CACHE_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME'): + directory = Path(os.environ[key]) + directory.mkdir(parents=True, exist_ok=True) + marker = directory / 'cursor-container-marker' + previous = marker.read_text() if marker.exists() else '' + marker.write_text(previous + 'x') + record['paths'][key] = str(directory) + for path in paths: + denied = [] + for mode in ('r', 'a'): + try: + with open(path, mode) as stream: + if mode == 'r': stream.read(1) + else: stream.write('escaped') + except PermissionError: + denied.append(mode) + record['denied'].append(denied) + return record + +if sys.argv[1:] != ['acp']: + assert '--' in sys.argv[1:] + print(json.dumps({'argv': sys.argv[1:], 'cwd': os.getcwd()})) + Path('cursor-cli-write').write_text('written') + raise SystemExit + +observe('workload') session='fixture-session' waiting={} active=None -ignore_cancel=False +completion_permission = os.environ.get('FIXTURE_COMPLETION_PERMISSION') == '1' +cancel_replies = { + 'slow': {'result': {'stopReason': 'cancelled', 'usage': {'tokens': 3}, '_meta': {'fixture': 'settled'}}}, + 'complete-on-cancel': {'result': {'stopReason': 'end_turn', 'usage': {'tokens': 7}, '_meta': {'fixture': 'completed'}}}, + 'error-on-cancel': {'error': {'code': -32023, 'message': 'Fixture prompt error'}}, + 'invalid-result-on-cancel': {'result': []}, + 'missing-stop-on-cancel': {'result': {'usage': {'tokens': 1}}}, +} def emit(value):print(json.dumps(value),flush=True) def reply(identifier,value):emit({'jsonrpc':'2.0','id':identifier,'result':value}) @@ -25,24 +72,43 @@ def finish(identifier,reason='end_turn'):reply(identifier,{'stopReason':reason}) q=json.loads(line);method=q.get('method');identifier=q.get('id');params=q.get('params',{}) if method=='initialize': reply(identifier,{'protocolVersion':1,'agentCapabilities':{'loadSession':True},'authMethods':[{'id':'cursor_login','name':'Existing CLI login'}]}) - elif method=='authenticate':reply(identifier,{}) + elif method=='authenticate': + rejection = os.environ.get('FIXTURE_AUTH_ERROR_CODE') + if rejection is None: + reply(identifier,{}) + else: + assert params == {'methodId': 'cursor_login'} + observe('rejected_authentication') + emit({'jsonrpc': '2.0', 'id': identifier, 'error': { + 'code': int(rejection), 'message': os.environ['FIXTURE_AUTH_ERROR_MESSAGE'], + 'data': {'token': 'fixture-sensitive-data'}, + }}) elif method in ('session/new','session/load'): + if os.environ.get('CURSOR_SOURCE_FIXTURE') == '1': + with (Path(os.environ['HOME']) / 'cursor-native-starts.jsonl').open('a') as stream: + stream.write(json.dumps({'pid': os.getpid(), 'cwd': os.getcwd()}) + '\n') session=params.get('sessionId','fixture-session') reply(identifier,{'sessionId':session,'modes':{'currentModeId':'agent','availableModes':[{'id':m,'name':m} for m in ['agent','ask','plan']]}}) elif method=='session/set_mode':reply(identifier,{'observed_mode':params['modeId']}) elif method=='session/prompt': prompt=params['prompt'][0]['text'];active=identifier - ignore_cancel=prompt=='ignore-cancel' - if prompt in ('permission','question','plan'): - if prompt=='permission': - name='session/request_permission';value={'sessionId':session,'toolCall':{'toolCallId':'fixture-tool','title':'Fixture permission'},'options':[{'optionId':'opaque-yes','kind':'allow_once','name':'Allow once'},{'optionId':'opaque-no','kind':'reject_once','name':'Reject once'}]} + observe('prompt', prompt=prompt, acp_id=identifier, native_session=session) + permission = (prompt in ('permission','permission-on-cancel','permission-mislabelled') + or (completion_permission and prompt == 'complete-on-cancel')) + if permission or prompt in ('question','plan'): + if permission: + options = [{'optionId':'opaque-yes','kind':'allow_once','name':'Allow once'}, + {'optionId':'opaque-no','kind':'reject_once','name':'Reject once'}] + if prompt == 'permission-mislabelled': + options = [{'optionId':'reject-once','kind':'allow_always','name':'Allow always'}] + name='session/request_permission';value={'sessionId':session,'toolCall':{'toolCallId':'fixture-tool','title':'Fixture permission'},'options':options} elif prompt=='question': name='cursor/ask_question';value={'toolCallId':'fixture-question','questions':[{'id':'q1','prompt':'Choose','options':[{'id':'a','label':'A'},{'id':'b','label':'B'}],'allowMultiple':False}]} else: name='cursor/create_plan';value={'toolCallId':'fixture-plan','plan':'Fixture plan','todos':[]} waiting[900]=identifier emit({'jsonrpc':'2.0','id':900,'method':name,'params':value}) - elif prompt in ('slow','ignore-cancel'):update('started') + elif prompt in cancel_replies or prompt=='ignore-cancel':update('started') elif prompt=='fork': child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(120)']) Path(os.environ['FIXTURE_MARKER']).write_text(json.dumps([os.getpid(),child.pid])) @@ -53,14 +119,40 @@ def finish(identifier,reason='end_turn'):reply(identifier,{'stopReason':reason}) for i in range(600):update('x'*4096) finish(identifier) elif prompt=='exit-fast':finish(identifier);raise SystemExit + elif prompt=='missing-stop':reply(identifier,{}) + elif prompt=='native-cancelled':reply(identifier,{'stopReason':'cancelled','usage':{'tokens':0}}) + elif prompt.startswith('boundaries:'): + update(json.dumps(boundaries(json.loads(prompt[len('boundaries:'):])))) + finish(identifier) + elif prompt.startswith('worktree-io:') and os.environ.get('CURSOR_SOURCE_FIXTURE') == '1': + marker = Path('cursor-sibling-io') + previous = marker.read_text() + marker.write_text(previous + prompt.removeprefix('worktree-io:')) + update(previous) + finish(identifier) elif prompt=='env': update(json.dumps([k for k in os.environ if k.startswith('COMPUTER_MCP_')])) finish(identifier) else:update('hello');finish(identifier) elif method=='session/cancel': - if active is not None and not ignore_cancel:finish(active,'cancelled');active=None + assert q == {'jsonrpc': '2.0', 'method': 'session/cancel', 'params': {'sessionId': session}} + observe('cancel', acp_id=active, native_session=session) + if active is not None and prompt == 'permission-on-cancel' and 900 in waiting: + continue + if active is not None and prompt != 'ignore-cancel': + terminal = cancel_replies.get(prompt, {'result': {'stopReason': 'cancelled'}}) + emit({'jsonrpc': '2.0', 'id': active, **terminal}) + observe('terminal', acp_id=active, native_session=session, outcome=terminal) + active = None elif method is None and identifier in waiting: - update(json.dumps({'received_response':q.get('result')})) - finish(waiting.pop(identifier)) + response = q.get('result') + observe('answer', acp_id=identifier, native_session=session, response=response) + turn = waiting.pop(identifier) + if completion_permission and active != turn: + continue + update(json.dumps({'received_response':response})) + cancelled = prompt == 'permission-on-cancel' and response == {'outcome': {'outcome': 'cancelled'}} + finish(turn, 'cancelled' if cancelled else 'end_turn') + active = None elif identifier is not None: emit({'jsonrpc':'2.0','id':identifier,'error':{'code':-32601,'message':'Unknown fixture method'}}) diff --git a/tests/Fixtures/vendor_start_transport.py b/tests/Fixtures/vendor_start_transport.py new file mode 100644 index 0000000..7f0ba6d --- /dev/null +++ b/tests/Fixtures/vendor_start_transport.py @@ -0,0 +1,172 @@ +"""Test interpreter for the registered adapter's inherited vendor channel. + +Relay the production frames unchanged. A fixture may hold one launch request +before delivery, or drop one real launch reply and hold its recovery replies +long enough for the test to read the Host's durable state. +""" + +import json +import os +from pathlib import Path +import runpy +import socket +import sys +import threading +import time + + +MAX_FRAME = 1_048_576 + + +def relay(upstream, downstream, control): + lock = threading.Lock() + pending = {} + deferred = [] + writers = {upstream: threading.Lock(), downstream: threading.Lock()} + target = None + fault = None + launch_seen = False + ended = threading.Event() + + def stage(name, request, reply=None): + value = {'adapter_pid': os.getpid(), 'request': request} + if reply is not None: + value['reply'] = reply + path = control / (name + '.json') + temporary = path.with_suffix('.tmp') + temporary.write_text(json.dumps(value)) + temporary.replace(path) + + def send(destination, line): + with writers[destination]: + if not ended.is_set(): + destination.sendall(line) + + def hold(name, destination, line): + def forward(): + deadline = time.monotonic() + 18 + try: + while not ended.is_set(): + if (control / (name + '.release')).is_file(): + send(destination, line) + return + if time.monotonic() >= deadline: + raise TimeoutError(name) + ended.wait(.02) + except OSError as error: + if not ended.is_set(): + print(f'Cursor fixture relay: {type(error).__name__}: {error}', file=sys.stderr) + try: + destination.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + thread = threading.Thread(target=forward, daemon=True) + with lock: + if len(deferred) >= 3: + raise ValueError("Unexpected duplicate held vendor frames") + deferred.append(thread) + thread.start() + + def transfer(source, destination, to_host): + nonlocal target, fault, launch_seen + try: + with source.makefile('rb') as stream: + while not ended.is_set(): + line = stream.readline(MAX_FRAME + 1) + if not line: + break + if len(line) > MAX_FRAME or not line.endswith(b'\n'): + raise ValueError("Unbounded vendor channel frame") + frame = json.loads(line) + if to_host: + with lock: + if len(pending) >= 32 or frame['id'] in pending: + raise ValueError("Invalid pending vendor channel frame") + pending[frame['id']] = frame + choice = control / 'fault' + if target is None and frame['op'] == 'bind' and choice.is_file(): + fault = choice.read_text() + target = frame['acquisition'] + selected = frame.get('acquisition') == target and target is not None + if selected and frame['op'] == 'launch': + if launch_seen: + stage('launch-replayed', frame) + launch_seen = True + if fault == 'hold-launch': + stage('launch-held', frame) + hold('launch-held', destination, line) + continue + else: + with lock: + request = pending.pop(frame['id']) + selected = request.get('acquisition') == target and target is not None + if selected and request['op'] in ('bind', 'probe'): + stage(request['op'], request, frame) + elif selected and fault == 'lose-reply': + if request['op'] == 'launch' and 'result' in frame: + stage('launch-dropped', request, frame) + continue + if request['op'] in ('receipt', 'retire'): + stage(request['op'], request, frame) + hold(request['op'], destination, line) + continue + elif selected and fault == 'hold-launch-reply' and request['op'] == 'launch': + stage('launch-reply-held', request, frame) + hold('launch-reply-held', destination, line) + continue + elif selected and fault == 'hold-launch' and request['op'] == 'launch': + stage('launch-delivered', request, frame) + send(destination, line) + except (OSError, ValueError, KeyError) as error: + if not ended.is_set(): + print(f'Cursor fixture relay: {type(error).__name__}: {error}', file=sys.stderr) + finally: + ended.set() + for endpoint in (source, destination): + try: + endpoint.shutdown(socket.SHUT_RDWR) + except OSError: + pass + + threads = [ + threading.Thread(target=transfer, args=(downstream, upstream, True), daemon=True), + threading.Thread(target=transfer, args=(upstream, downstream, False), daemon=True), + ] + for thread in threads: + thread.start() + return ended, threads, deferred + + +def main(): + adapter = sys.argv[1] + if sys.argv[2:] != ['--host-vendor-execution']: + raise ValueError("Expected the registered managed Cursor adapter") + control = Path(os.environ['HOME']) / 'cursor-start-transport' + control.mkdir(exist_ok=True) + # Only the real adapter consumes fd 3. The test owns the other socket ends. + upstream = socket.socket(fileno=os.dup(3)) + upstream.setblocking(True) + adapter_end, downstream = socket.socketpair() + os.dup2(adapter_end.fileno(), 3, inheritable=False) + adapter_end.close() + ended, threads, deferred = relay(upstream, downstream, control) + try: + sys.argv = sys.argv[1:] + sys.path.insert(0, str(Path(adapter).parent)) + runpy.run_path(adapter, run_name='__main__') + finally: + ended.set() + for endpoint in (upstream, downstream): + try: + endpoint.shutdown(socket.SHUT_RDWR) + except OSError: + pass + for thread in threads + deferred: + thread.join(timeout=1) + upstream.close() + downstream.close() + + +if __name__ == '__main__': + main() diff --git a/tests/Interop/test_host_source.py b/tests/Interop/test_host_source.py new file mode 100644 index 0000000..5594d3e --- /dev/null +++ b/tests/Interop/test_host_source.py @@ -0,0 +1,260 @@ +"""Source driver checks do not build a host or execute a native vendor.""" +import argparse +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('host_source', ROOT / 'scripts/validate_host_source.py') +driver = importlib.util.module_from_spec(spec) +spec.loader.exec_module(driver) + + +class HostSourceTests(unittest.TestCase): + def test_cli_requires_explicit_sources_and_commits(self): + result = subprocess.run([sys.executable, str(ROOT / 'scripts/validate_host_source.py'), '--help'], capture_output=True, text=True, timeout=5) + self.assertEqual(result.returncode, 0) + for name in ('--host-source', '--plugin-source', '--host-sha', '--plugin-sha', '--output'): + self.assertIn(name, result.stdout) + for value in ('master', 'a' * 39, 'A' * 40): + with self.assertRaises(argparse.ArgumentTypeError): driver.revision(value) + + def test_evidence_must_be_fresh_complete_and_nonzero(self): + good = {'kind': 'deterministic', 'run_id': 'fresh', 'tests_executed': 1, 'cases': sorted(driver.CASES)} + driver.validate_evidence(good, 'fresh') + for patch in ({'tests_executed': 0}, {'tests_executed': True}, {'run_id': 'stale'}, {'cases': []}, {'cases': good['cases'] + good['cases'][:1]}): + with self.assertRaises(ValueError): driver.validate_evidence(dict(good, **patch), 'fresh') + + def test_acquisition_receipt_requires_durable_distinct_launches(self): + def identifier(number): + return f"00000000-0000-0000-0000-{number:012X}" + + def acquisition(offset): + return { + "execution": identifier(offset), + "authorization_ids": [identifier(offset + 1), identifier(offset + 2)], + "adapter_child": identifier(1), "adapter_pid": 11, "adapter_identity": "101", + "probe_child": identifier(offset + 3), "probe_pid": 12, + "probe_identity": str(offset + 100), + "workload_child": identifier(offset + 4), "workload_pid": offset + 100, + "workload_identity": str(offset + 200), + } + + cold, warm = acquisition(10), acquisition(20) + driver.validate_acquisitions([cold, warm]) + for field, value in (("workload_identity", None), ("adapter_identity", "102"), + ("probe_child", cold["probe_child"]), + ("probe_identity", cold["probe_identity"])): + with self.subTest(field=field), self.assertRaises(ValueError): + driver.validate_acquisitions([cold, dict(warm, **{field: value})]) + + def test_native_stops_require_one_turn_per_addressed_request(self): + owners = [{"workload_pid": 10, "workload_identity": "11"}, + {"workload_pid": 20, "workload_identity": "21"}] + stops = [ + {"prompt": label, "peer_pid": 10 if index < 4 else 20, + "peer_identity": "11" if index < 4 else "21", "acp_id": 10 + index, + "stop_request_id": f"stop-{index}", "prompt_request_id": f"prompt-{index}"} + for index, label in enumerate(("slow", "permission-on-cancel", "error-on-cancel", + "ignore-cancel", "complete-on-cancel")) + ] + stops[-1]["downstream_request_id"] = "retained-invocation" + driver.validate_native_stops(stops, owners) + for changes in ({"acp_id": 10}, {"stop_request_id": "stop-0"}, {"peer_pid": 20}): + with self.assertRaises(ValueError): + driver.validate_native_stops([stops[0], dict(stops[1], **changes), *stops[2:]], owners) + for invalid in ([stops[0], *stops], [stops[0], *stops[2:]]): + with self.assertRaises(ValueError): + driver.validate_native_stops(invalid, owners) + + def test_source_identity_and_dirt_are_rejected(self): + sha = 'a' * 40 + with patch.object(driver, 'git', side_effect=[str(ROOT), sha, '']): + driver.verify_source(ROOT, sha) + with patch.object(driver, 'git', side_effect=[str(ROOT), 'b' * 40]): + with self.assertRaises(ValueError): driver.verify_source(ROOT, sha) + with patch.object(driver, 'git', side_effect=[str(ROOT), sha, '?? untracked']): + with self.assertRaises(ValueError): driver.verify_source(ROOT, sha) + + def test_only_fresh_external_run_outputs(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp).resolve() + host = root / 'sources' / 'host' + plugin = root / 'sources' / 'plugin' + host.mkdir(parents=True) + plugin.mkdir() + output = root / 'evidence' / 'run' + self.assertEqual(driver.validate_locations(host, plugin, output), output) + self.assertFalse(output.parent.exists()) + + existing = root / 'existing' + existing.mkdir() + file = root / 'file' + file.touch() + host_alias = root / 'host-alias' + host_alias.symlink_to(host, target_is_directory=True) + dangling = root / 'dangling' + dangling.symlink_to(output) + for invalid in (Path('relative'), host, plugin, host / 'run', plugin / 'run', + host.parent, root, existing, file, host_alias / 'run', dangling): + with self.subTest(output=invalid), self.assertRaises(ValueError): + driver.validate_locations(host, plugin, invalid) + for first, second in ((host, host), (host, host / 'nested'), (plugin / 'nested', plugin)): + with self.subTest(host=first, plugin=second), self.assertRaises(ValueError): + driver.validate_locations(first, second, output) + + def test_case_aliases_follow_filesystem_identity(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp).resolve() + sources = root / 'sources' + host = sources / 'host' + plugin = sources / 'plugin' + host.mkdir(parents=True) + plugin.mkdir() + host_alias = sources / 'HOST' + plugin_alias = sources / 'PLUGIN' + candidates = (host_alias / 'fresh' / 'run', plugin_alias / 'fresh' / 'run') + + if host_alias.exists(): + self.assertTrue(host_alias.samefile(host)) + self.assertTrue(plugin_alias.samefile(plugin)) + for output in (*candidates, root / 'SOURCES'): + with self.subTest(output=output), self.assertRaisesRegex(ValueError, 'outside both'): + driver.validate_locations(host, plugin, output) + with self.assertRaisesRegex(ValueError, 'separate, non-nested'): + driver.validate_locations(host, host_alias, root / 'evidence') + result = subprocess.run( + [sys.executable, str(ROOT / 'scripts/validate_host_source.py'), + '--host-source', str(host), '--host-sha', 'a' * 40, + '--plugin-source', str(plugin), '--plugin-sha', 'b' * 40, + '--output', str(candidates[0])], + capture_output=True, text=True, timeout=5) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn('Source verification failed: Output must be outside both', result.stderr) + else: + for output in candidates: + with self.subTest(output=output): + self.assertEqual(driver.validate_locations(host, plugin, output), output) + + for output in candidates: + self.assertFalse(output.parent.exists()) + + def test_snapshot_rejects_links_and_path_escape(self): + for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp); archive = root / 'source.tar' + with tarfile.open(archive, 'w') as tar: + item = tarfile.TarInfo(name); item.type = kind; item.linkname = '/tmp/target'; tar.addfile(item) + with self.assertRaises(ValueError): driver.extract_source(archive, root / 'export') + self.assertFalse((root / 'escape').exists()) + + def test_staged_run_records_pair_and_removes_owned_snapshots(self): + import shutil + from types import SimpleNamespace + with tempfile.TemporaryDirectory() as temp: + root = Path(temp).resolve() + output = root / 'run' + args = SimpleNamespace(host_source=root / 'host', plugin_source=ROOT, suite='both', + host_sha='a' * 40, plugin_sha='b' * 40, output=output, timeout=3) + def export(root, sha, destination, environment, work): + destination.mkdir() + if root == args.host_source: + (destination / 'Tests/ComputerMCPMacOSTests').mkdir(parents=True) + else: + for name in driver.INPUTS: + target = destination / name; target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / name, target) + def execute(command, cwd, environment, log, timeout, *, exit_codes=(0,)): + if command[0] == sys.executable: + self.assertEqual(cwd, output / 'plugin-source') + packages = Path(command[-1]) + packages.mkdir() + (packages / 'cursor.zip').write_bytes(b'archive') + return 0 + + self.assertEqual(cwd, output / 'host-source') + self.assertEqual(command[1:6], ['test', '--build-system', 'swiftbuild', + '--test-product', 'ComputerMCPMacOSTests']) + self.assertEqual(command[-4:], ['--filter', driver.SELECTORS['source'], + '--filter', driver.SELECTORS['vendor-stop']]) + self.assertIn('--parallel', command) + self.assertEqual(exit_codes, (0, 1)) + self.assertTrue((cwd / 'Tests/ComputerMCPMacOSTests' / driver.FIXTURE).is_file()) + self.assertEqual(environment['COMPUTER_MCP_CURSOR_PLUGIN'], str(output / 'plugin-source')) + self.assertNotIn('COMPUTER_MCP_TEST_GATEWAY_EXECUTABLE', environment) + self.assertEqual( + environment['COMPUTER_MCP_CURSOR_ARCHIVE_SHA256'], + driver.digest(output / 'package' / 'cursor.zip')) + self.assertNotEqual(environment['COMPUTER_MCP_CURSOR_SOURCE_RUN_ID'], + environment['COMPUTER_MCP_CURSOR_VENDOR_STOP_RUN_ID']) + self.assertEqual(environment['COMPUTER_MCP_CURSOR_VENDOR_STOP_CASES'], + str(output / 'vendor-stop' / 'cases.json')) + (output / 'build').mkdir() + Path(environment['COMPUTER_MCP_CURSOR_SOURCE_CASES']).write_text(json.dumps({ + 'kind': 'deterministic', 'run_id': environment['COMPUTER_MCP_CURSOR_SOURCE_RUN_ID'], + 'tests_executed': 1, 'cases': sorted(driver.CASES)})) + (output / 'swift-test.xml').write_text(""" + + + + + """) + return 1 + + with (patch.dict(os.environ, {'COMPUTER_MCP_TEST_GATEWAY_EXECUTABLE': '/other/host'}), + patch.object(driver, 'verify_source'), + patch.object(driver, 'export_source', side_effect=export) as exports, + patch.object(driver, 'run_process', side_effect=execute) as commands): + with self.assertRaisesRegex(ValueError, 'vendor-stop: Swift test failed'): + driver.run(args) + self.assertEqual(exports.call_count, 2) + self.assertEqual(commands.call_count, 2) + receipt = json.loads((output / 'source' / 'receipt.json').read_text()) + self.assertEqual(receipt['host_sha'], args.host_sha) + self.assertEqual(receipt['plugin_sha'], args.plugin_sha) + self.assertEqual(receipt['status'], 'passed') + self.assertEqual(receipt['tests_executed'], 1) + self.assertEqual(receipt['cleanup'], 'confirmed') + self.assertFalse(receipt['native_verified']) + failed = json.loads((output / 'vendor-stop' / 'receipt.json').read_text()) + self.assertNotEqual(failed['run_id'], receipt['run_id']) + self.assertEqual(failed['status'], 'failed') + self.assertNotIn('tests_executed', failed) + for name in ('host-source', 'plugin-source', 'build', 'package'): + self.assertFalse((output / name).exists()) + + def test_swift_report_requires_exact_selected_completed_tests(self): + source = ('') + with tempfile.TemporaryDirectory() as temp: + report = Path(temp) / 'swift-test.xml' + report.write_text(f'{source}') + self.assertEqual(driver.swift_test_results(report, ('source',), 0), {'source': True}) + with self.assertRaisesRegex(ValueError, 'runner result'): + driver.swift_test_results(report, ('source', 'vendor-stop'), 0) + with self.assertRaisesRegex(ValueError, 'runner result'): + driver.swift_test_results(report, ('source',), 1) + for rows in (source + source, source.replace('/>', '>'), + source.replace('ComputerMCPMacOSTests.', 'SomeOtherTarget.')): + report.write_text(f'{rows}') + with self.assertRaisesRegex(ValueError, 'selected cases'): + driver.swift_test_results(report, ('source',), 0) + + def test_bounded_command_failure_and_timeout(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp); log = root / 'process.log' + driver.run_process([sys.executable, '-c', 'print("ok")'], root, dict(os.environ), log, 3) + self.assertEqual(log.read_text(), 'ok\n') + with self.assertRaises(RuntimeError): driver.run_process([sys.executable, '-c', 'raise SystemExit(7)'], root, dict(os.environ), log, 3) + with self.assertRaises(TimeoutError): driver.run_process([sys.executable, '-c', 'import time; time.sleep(30)'], root, dict(os.environ), log, .1) + +if __name__ == '__main__': unittest.main() diff --git a/tests/check_runtime_rejection.py b/tests/check_runtime_rejection.py index 92cf325..6c70cf5 100644 --- a/tests/check_runtime_rejection.py +++ b/tests/check_runtime_rejection.py @@ -3,19 +3,24 @@ import subprocess import sys import tempfile +import zipfile def check(): if sys.version_info >= (3, 13): raise AssertionError('This check must run on Python older than 3.13') - entrypoints = list((Path(__file__).resolve().parent.parent / 'bin').glob('*-mcp-adapter')) - assert len(entrypoints) == 1 + root = Path(__file__).resolve().parent.parent with tempfile.TemporaryDirectory() as directory: + subprocess.run( + [sys.executable, '-B', str(root / 'scripts/build_package.py'), directory], + stdout=subprocess.DEVNULL, check=True, timeout=5) + with zipfile.ZipFile(Path(directory) / 'cursor.zip') as archive: + entrypoint = archive.extract('bin/cursor-mcp-adapter', directory) marker = Path(directory) / 'vendor-started' vendor = Path(directory) / 'vendor' vendor.write_text('#!/bin/sh\n: > "' + str(marker) + '"\n') vendor.chmod(0o755) - result = subprocess.run([sys.executable, str(entrypoints[0]), '--executable', str(vendor)], + result = subprocess.run([sys.executable, entrypoint, '--executable', str(vendor)], input=b'', capture_output=True, timeout=5, cwd=directory) assert result.returncode != 0 assert b'Python 3.13+' in result.stderr, result.stderr diff --git a/tests/support.py b/tests/support.py index 91fc915..9267c04 100644 --- a/tests/support.py +++ b/tests/support.py @@ -2,25 +2,67 @@ import json import os from pathlib import Path +from functools import cache import selectors +import stat import subprocess import sys +import tempfile import time -import tomllib +import zipfile ROOT = Path(__file__).resolve().parent.parent -VENDOR = tomllib.loads((ROOT / 'computer-mcp-plugin.toml').read_text())['id'] +PEER = ROOT / 'tests/Fixtures/vendor.py' + + +def smoke_call(): + case = json.loads((ROOT / 'tests/Fixtures/package-smoke.json').read_text()) + reply = case['expected']['structuredContent']['result'] + return case['call'], reply['structuredContent']['result'] + + +@cache +def packaged_directory(): + stage = tempfile.TemporaryDirectory(prefix='cursor-package-tests-') + directory = Path(stage.name) + artifact = os.environ.get('CURSOR_TEST_ARCHIVE') + if artifact is None: + # Individual unittest modules can also run from a clean checkout. + subprocess.run( + [sys.executable, '-B', str(ROOT / 'scripts/build_package.py'), stage.name], + stdout=subprocess.DEVNULL, check=True, timeout=5) + artifact = directory / 'cursor.zip' + with zipfile.ZipFile(artifact) as archive: + archive.extractall(directory) + for entry in archive.infolist(): + (directory / entry.filename).chmod(stat.S_IMODE(entry.external_attr >> 16)) + return stage + + +def packaged_root(): + return Path(packaged_directory().name) + + +def clean_environment(home): + return { + 'HOME': str(home), + 'PATH': os.pathsep.join((str(Path(sys.executable).parent), '/usr/bin', '/bin')), + 'PYTHONDONTWRITEBYTECODE': '1', + } + class Client: - def __init__(self, directory, environment=None, command=None): - env = dict(os.environ) if command is None else {} + def __init__(self, directory, environment=None, command=None, pass_fds=(), *, + protocol='2025-06-18'): + env = clean_environment(directory) env.update(environment or {}) - env['CURSOR_AGENT_EXECUTABLE' if VENDOR=='cursor' else 'CLAUDE_CODE_EXECUTABLE'] = str(ROOT/'tests/Fixtures/vendor.py') - self.process = subprocess.Popen(command or [sys.executable,str(ROOT/f'bin/{VENDOR}-mcp-adapter')],cwd=directory,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + env['CURSOR_AGENT_EXECUTABLE'] = str(PEER) + entry = [sys.executable, '-B', str(packaged_root() / 'bin/cursor-mcp-adapter')] + self.process = subprocess.Popen(command or entry,cwd=directory,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,pass_fds=pass_fds) self.buffer = bytearray() self.serial = 1 self.saved = {} - self.request('initialize',{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'fixture','version':'1'}}) + self.initialization = self.request('initialize',{'protocolVersion':protocol,'capabilities':{},'clientInfo':{'name':'fixture','version':'1'}}) self.send({'jsonrpc':'2.0','method':'notifications/initialized'}) def send(self, value): self.process.stdin.write(json.dumps(value).encode()+b'\n');self.process.stdin.flush() diff --git a/tests/test_adapter.py b/tests/test_adapter.py index 43cfd82..a33a36e 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -1,8 +1,9 @@ import json +from pathlib import Path import tempfile import time import unittest -from support import Client +from support import Client, smoke_call class AdapterTests(unittest.TestCase): @@ -23,9 +24,40 @@ def test_catalog_declares_execution_and_inspection_risk(self): self.assertEqual(tool['annotations']['readOnlyHint'],risk=='read-only') self.assertEqual(tool['annotations']['destructiveHint'],risk in {'destructive','full-shell'}) def test_acp_prompt_through_mcp(self): - r=self.value(self.call('prompt',{'prompt':'hello'})) - self.assertEqual(r['text'],'hello');self.assertEqual(r['stop_reason'],'end_turn') + self.assertNotIn('experimental', self.client.initialization['result']['capabilities']) + call, expected = smoke_call() + result = self.value(self.client.call(call['tool'], call['arguments'])) + self.assertEqual({key: result[key] for key in expected}, expected) self.assertEqual(self.value(self.call('session.list'))['sessions'],[]) + def test_authentication_rejection_stops_before_native_session_setup(self): + cases = [ + (-32000, 'fixture-sensitive-message', 'authentication_required', + 'Cursor sign-in required (RPC code -32000).'), + (-32602, 'Failed to open browser for login. Please visit: https://example.test/fixture-sensitive-url', + 'vendor_error', 'Cursor rejected authenticate (RPC code -32602).'), + (-32603, 'fixture-sensitive-message', 'vendor_error', + 'Cursor rejected authenticate (RPC code -32603).'), + ] + for rpc_code, vendor_message, code, message in cases: + with self.subTest(rpc_code=rpc_code), tempfile.TemporaryDirectory() as directory: + client = Client(directory, { + 'HOME': directory, 'CURSOR_SOURCE_FIXTURE': '1', + 'FIXTURE_AUTH_ERROR_CODE': str(rpc_code), + 'FIXTURE_AUTH_ERROR_MESSAGE': vendor_message, + }) + try: + response = client.call('cursor.acp.session.open') + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['error'], {'code': code, 'message': message}) + self.assertNotIn('fixture-sensitive', json.dumps(response)) + self.assertNotIn('https://example.test/', json.dumps(response)) + self.assertEqual(self.value(client.call('cursor.acp.session.list'))['sessions'], []) + finally: + client.close() + effects = (Path(directory) / 'cursor-vendor-effects.jsonl').read_text().splitlines() + self.assertEqual([json.loads(line)['phase'] for line in effects], + ['probe', 'workload', 'rejected_authentication']) + self.assertFalse((Path(directory) / 'cursor-native-starts.jsonl').exists()) def test_reuse_session_and_explicit_native_resume(self): session=self.open(resume_session_id='saved-conversation',mode='plan') for prompt in ['first','second']: @@ -36,6 +68,9 @@ def test_reuse_session_and_explicit_native_resume(self): def test_opaque_permission_ids_follow_offered_kind(self): r=self.value(self.call('prompt',{'prompt':'permission','permission_policy':'allow-once'})) self.assertIn('opaque-yes',r['text']) + result = self.value(self.call('prompt', {'prompt': 'permission-mislabelled'})) + self.assertEqual(json.loads(result['text']), + {'received_response': {'outcome': {'outcome': 'cancelled'}}}) def test_unoffered_allow_falls_back_to_reject(self): r=self.value(self.call('prompt',{'prompt':'permission','permission_policy':'allow-always'})) self.assertIn('opaque-no',r['text']) @@ -62,16 +97,86 @@ def test_question_response(self): self.interactive('question',{'outcome':{'outcome':'answered','answers':[{'questionId':'q1','selectedOptionIds':['a']}]}}) def test_plan_response(self): self.interactive('plan',{'outcome':{'outcome':'accepted'}}) - def test_native_cancel_settles_prompt_and_session_can_be_reused(self): - session=self.open() - request=self.client.begin('cursor.acp.session.prompt',{'session':session,'prompt':'slow'}) + def begin_cancel_case(self, session, prompt): + request = self.client.begin('cursor.acp.session.prompt', { + 'session': session, 'prompt': prompt, 'timeout_seconds': 10, + }) for _ in range(80): - page=self.value(self.call('events.read',{'session':session})) - if page['events']:break + page = self.value(self.call('events.read', {'session': session})) + if page['events']: + return request time.sleep(.02) - self.value(self.call('session.cancel',{'session':session})) - self.assertEqual(Client.value(self.client.wait(request))['stop_reason'],'cancelled') - self.value(self.call('session.prompt',{'session':session,'prompt':'after-cancel'})) + self.fail('Native prompt did not start') + + def cancel_and_wait(self, session, request): + self.assertEqual(self.value(self.call('session.cancel', {'session': session})), + {'cancel_requested': True, 'session': session}) + return self.client.wait(request, timeout=5) + + def test_native_cancel_settles_prompt_and_session_can_be_reused(self): + session = self.open(resume_session_id='cancel-target') + request = self.begin_cancel_case(session, 'slow') + response = self.cancel_and_wait(session, request) + self.assertTrue(response['result']['isError']) + result = Client.value(response) + self.assertEqual(result['stop_reason'], 'cancelled') + self.assertTrue(result['is_error']) + self.assertEqual(result['native_result'], { + 'stopReason': 'cancelled', 'usage': {'tokens': 3}, '_meta': {'fixture': 'settled'}, + }) + reused = self.value(self.call('session.prompt', {'session': session, 'prompt': 'after-cancel'})) + self.assertEqual(reused['session_id'], 'cancel-target') + self.assertEqual(reused['stop_reason'], 'end_turn') + + def test_native_completion_can_win_cancellation_without_affecting_sibling(self): + target = self.open(resume_session_id='cancel-target') + sibling = self.open(resume_session_id='unrelated-sibling', permission_policy='manual') + sibling_request = self.client.begin('cursor.acp.session.prompt', { + 'session': sibling, 'prompt': 'permission', 'timeout_seconds': 15, + }) + pending = self.pending(sibling) + target_request = self.begin_cancel_case(target, 'complete-on-cancel') + result = self.value(self.cancel_and_wait(target, target_request)) + self.assertEqual(result['stop_reason'], 'end_turn') + self.assertFalse(result['is_error']) + self.assertEqual(result['native_result'], { + 'stopReason': 'end_turn', 'usage': {'tokens': 7}, '_meta': {'fixture': 'completed'}, + }) + self.assertEqual(self.value(self.call('requests.list', {'session': sibling}))['requests'], + [pending]) + self.value(self.call('requests.respond', { + 'session': sibling, 'request_id': pending['request_id'], + 'response': {'outcome': {'outcome': 'selected', 'optionId': 'opaque-yes'}}, + })) + sibling_result = self.value(self.client.wait(sibling_request, timeout=5)) + self.assertEqual(sibling_result['session_id'], 'unrelated-sibling') + self.assertEqual(sibling_result['stop_reason'], 'end_turn') + self.assertIn('opaque-yes', sibling_result['text']) + + def test_cancel_preserves_native_error_and_result_validation(self): + for prompt, code, detail in [ + ('error-on-cancel', 'vendor_error', '-32023'), + ('invalid-result-on-cancel', 'invalid_vendor_response', 'must be an object'), + ('missing-stop-on-cancel', 'invalid_vendor_response', 'lacks a stop reason'), + ]: + with self.subTest(prompt=prompt): + session = self.open() + request = self.begin_cancel_case(session, prompt) + response = self.cancel_and_wait(session, request) + self.assertTrue(response['result']['isError']) + error = Client.value(response)['error'] + self.assertEqual(error['code'], code) + self.assertIn(detail, error['message']) + closed = self.call('session.prompt', {'session': session, 'prompt': 'after'}) + self.assertEqual(Client.value(closed)['error']['code'], 'session_closed') + def test_native_terminal_result_without_a_client_stop(self): + response = self.call('prompt', {'prompt': 'native-cancelled'}) + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['native_result'], + {'stopReason': 'cancelled', 'usage': {'tokens': 0}}) + response = self.call('prompt', {'prompt': 'missing-stop'}) + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['error']['code'], 'invalid_vendor_response') def test_unsettled_native_cancellation_retires_owned_session(self): session=self.open() request=self.client.begin('cursor.acp.session.prompt',{'session':session,'prompt':'ignore-cancel'}) diff --git a/tests/test_cleanup_receipt.py b/tests/test_cleanup_receipt.py index 6cb7e8a..4d68f12 100644 --- a/tests/test_cleanup_receipt.py +++ b/tests/test_cleanup_receipt.py @@ -2,8 +2,8 @@ import os import sys import unittest -from support import ROOT -sys.path.insert(0, str(ROOT / 'bin')) +from support import packaged_root +sys.path.insert(0, str(packaged_root() / 'bin')) from plugin_runtime import Failure, Process class CleanupReceiptTests(unittest.TestCase): diff --git a/tests/test_completion.py b/tests/test_completion.py index 259ca84..de9dc2d 100644 --- a/tests/test_completion.py +++ b/tests/test_completion.py @@ -3,12 +3,13 @@ import importlib.util import sys import unittest -from support import ROOT, VENDOR +from support import packaged_root -sys.path.insert(0, str(ROOT / 'bin')) -from plugin_runtime import Failure, Job +sys.path.insert(0, str(packaged_root() / 'bin')) +from plugin_runtime import Job -loader = importlib.machinery.SourceFileLoader('completion_adapter', str(ROOT / f'bin/{VENDOR}-mcp-adapter')) +loader = importlib.machinery.SourceFileLoader( + 'completion_adapter', str(packaged_root() / 'bin/cursor-mcp-adapter')) spec = importlib.util.spec_from_loader(loader.name, loader) adapter = importlib.util.module_from_spec(spec) loader.exec_module(adapter) @@ -25,28 +26,5 @@ def request(*args): return {'stopReason': 'cancelled', 'cancelled': True} session.request = request self.assertTrue(session.prompt({'prompt': 'not-executed'}, Job(), reserved=True)['is_error']) - - - def test_missing_stop_reason_is_not_success(self): - session = adapter.Session('local-handle', '/unused', 'reject-once') - session.request = lambda *args: {} - with self.assertRaises(Failure) as context: - session.prompt({'prompt': 'not-executed'}, Job()) - self.assertEqual(context.exception.code, 'invalid_vendor_response') - - - def test_native_cancelled_result_is_not_reported_successful(self): - session = adapter.Session('local-handle', '/unused', 'reject-once') - session.request = lambda *args: {'stopReason': 'cancelled', 'usage': {'tokens': 0}} - value = session.prompt({'prompt': 'not-executed'}, Job()) - self.assertTrue(value['is_error']) - self.assertEqual(value['native_result']['usage'], {'tokens': 0}) - - - - def test_permission_id_cannot_override_its_declared_kind(self): - request = {'options':[{'optionId':'reject-once','kind':'allow_always'}]} - self.assertEqual(adapter.permission_choice(request,'reject-once'), {'outcome':{'outcome':'cancelled'}}) - if __name__ == '__main__': unittest.main() diff --git a/tests/test_declarations.py b/tests/test_declarations.py new file mode 100644 index 0000000..5d86551 --- /dev/null +++ b/tests/test_declarations.py @@ -0,0 +1,38 @@ +import tempfile +import tomllib +import unittest +from support import Client, packaged_root + +READ = {'cursor.acp.session.prompt.result', 'cursor.acp.session.list', 'cursor.acp.events.read', 'cursor.acp.requests.list'} + +class DeclarationTests(unittest.TestCase): + def test_manifest_matches_actual_catalog(self): + manifest = tomllib.loads((packaged_root() / 'computer-mcp-plugin.toml').read_text()) + self.assertEqual([(permission['id'], permission['access']) + for permission in manifest['permissions']], [('project', 'write')]) + self.assertNotIn('host_service_contract', manifest['mcp'][0]) + mcp = manifest['mcp'][0] + self.assertEqual(mcp['requirements'], {'project': 'write'}) + self.assertEqual(mcp['tool_requirements'], {name: {'project': 'read'} for name in READ}) + with tempfile.TemporaryDirectory() as temp: + client = Client(temp) + try: + tools = client.request('tools/list')['result']['tools'] + self.assertEqual(len(tools), 12) + self.assertEqual({tool['name'] for tool in tools if tool['_meta']['io.github.computer-mcp/risk'] == 'read-only'}, READ) + for tool in tools: + self.assertNotIn('requirements', tool.get('_meta', {})) + finally: client.close() + self.assertEqual([c['id'] for c in manifest['cli']], ['agent']) + self.assertEqual([c['id'] for c in manifest['skills']], ['cursor-agent']) + + def test_sandbox_requests_only_official_agent_api_hosts(self): + sandbox = tomllib.loads((packaged_root() / 'computer-mcp-plugin.toml').read_text())['sandbox'] + self.assertEqual(set(sandbox), {'network', 'purpose'}) + self.assertTrue(sandbox['purpose']) + self.assertEqual(sandbox['network'], { + 'level': 'custom', 'hosts': ['api2.cursor.sh', 'api5.cursor.sh'], + 'include_trusted': False, + }) + +if __name__ == '__main__': unittest.main() diff --git a/tests/test_json.py b/tests/test_json.py index ec7f545..89967ec 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -1,8 +1,8 @@ """Bounded numeric validation must not silently admit nonfinite values.""" import sys import unittest -from support import ROOT -sys.path.insert(0, str(ROOT / 'bin')) +from support import packaged_root +sys.path.insert(0, str(packaged_root() / 'bin')) from plugin_runtime import Failure, decoded, validate class JSONTests(unittest.TestCase): diff --git a/tests/test_lifecycle.py b/tests/test_lifecycle.py index 166ec13..c43e0d3 100644 --- a/tests/test_lifecycle.py +++ b/tests/test_lifecycle.py @@ -9,9 +9,9 @@ import tempfile import time import unittest -from support import Client, ROOT, VENDOR, wait_file, wait_stopped +from support import Client, ROOT, packaged_root, wait_file, wait_stopped -sys.path.insert(0,str(ROOT/'bin')) +sys.path.insert(0, str(packaged_root() / 'bin')) from plugin_runtime import EventBuffer @@ -21,8 +21,7 @@ def scenario(self,termination): marker=Path(temp)/'pids.json' client=Client(temp,{'FIXTURE_MARKER':str(marker)}) try: - name='cursor.acp.prompt' if VENDOR=='cursor' else 'claude.run' - client.begin(name,{'prompt':'fork','timeout_seconds':30}) + client.begin('cursor.acp.prompt',{'prompt':'fork','timeout_seconds':30}) pids=wait_file(marker) if termination=='eof':client.process.stdin.close() else:os.kill(client.process.pid,termination) @@ -34,18 +33,27 @@ def test_sigterm_retires_vendor_and_descendant(self):self.scenario(signal.SIGTER def test_sigkill_parent_loss_is_detected_by_supervisor(self):self.scenario(signal.SIGKILL) def test_host_context_is_not_forwarded_to_vendor(self): with tempfile.TemporaryDirectory() as temp: - client=Client(temp,{'COMPUTER_MCP_TEST_PRIVATE':'must-not-inherit'}) + working_directory = Path(temp, 'project').resolve() + home = Path(temp, 'home').resolve() + working_directory.mkdir() + home.mkdir() + client=Client(working_directory, { + 'COMPUTER_MCP_TEST_PRIVATE': 'must-not-inherit', 'HOME': str(home), + 'CURSOR_SOURCE_FIXTURE': '1', + }) try: - response=client.call('cursor.acp.prompt' if VENDOR=='cursor' else 'claude.run',{'prompt':'env'}) + response=client.call('cursor.acp.prompt',{'prompt':'env'}) value=Client.value(response) self.assertFalse(response['result']['isError'],value) - self.assertEqual(value['text'] if VENDOR=='cursor' else value['result'],'[]') + self.assertEqual(value['text'],'[]') + [launch] = (home / 'cursor-native-starts.jsonl').read_text().splitlines() + self.assertEqual(json.loads(launch)['cwd'], str(working_directory)) finally:client.close() def test_version_mismatch_prevents_execution(self): with tempfile.TemporaryDirectory() as temp: client=Client(temp,{'FIXTURE_WRONG_VERSION':'1'}) try: - response=client.call('cursor.acp.prompt' if VENDOR=='cursor' else 'claude.run',{'prompt':'hello'}) + response=client.call('cursor.acp.prompt',{'prompt':'hello'}) self.assertEqual(Client.value(response)['error']['code'],'incompatible_vendor') finally:client.close() def test_acp_initialization_probe_uses_native_assertion(self): diff --git a/tests/test_managed_adapter.py b/tests/test_managed_adapter.py new file mode 100644 index 0000000..3ed808b --- /dev/null +++ b/tests/test_managed_adapter.py @@ -0,0 +1,360 @@ +"""Exercise the packaged Cursor adapter on its private carrier and ordinary MCP.""" + +import base64 +import json +import os +from pathlib import Path +import select +import socket +import subprocess +import sys +import tempfile +import threading +import time +import unittest +import uuid + +from support import Client, PEER, ROOT, clean_environment, packaged_root, smoke_call + +CAPABILITY = 'io.github.computer-mcp/vendor-execution-v1' +METADATA = 'io.github.computer-mcp/work-invocation' +START_TRANSPORT = ROOT / 'tests/Fixtures/vendor_start_transport.py' +REFUSAL = 'vendor_effect_denied' + + +class VendorFixture: + """Drive the adapter contract with a local socket and a deterministic ACP peer.""" + + def __init__(self, home, answer_error, vendor_env=None, *, settle_workload=True): + self.socket, self.adapter_socket = socket.socketpair() + self.home = home + self.answer_error = answer_error + self.vendor_env = {**clean_environment(home), 'CURSOR_SOURCE_FIXTURE': '1', + **(vendor_env or {})} + self.settle_workload = settle_workload + self.thread = threading.Thread(target=self.serve, daemon=True) + self.vendor = None + self.turn = None + self.stop_requested = False + self.stop_sent = False + self.stop_call = None + self.cancel_writes = [] + self.hold_stop_output = self.vendor_env.get('FIXTURE_COMPLETION_PERMISSION') == '1' + self.answers = [] + self.retirements = 0 + self.launches = 0 + self.error = None + self.thread.start() + + def serve(self): + try: + with self.socket.makefile('rb') as incoming: + for line in incoming: + request = json.loads(line) + result = self.respond(request) + self.socket.sendall(json.dumps({'id': request['id'], **result}).encode() + b'\n') + except (BrokenPipeError, ConnectionResetError): + pass + except Exception as error: + self.error = error + self.socket.shutdown(socket.SHUT_RDWR) + finally: + self.retire() + self.socket.close() + + def respond(self, request): + op = request['op'] + result = {} + if op == 'initialize': + result = {'capability': request['capability']} + elif op == 'bind': + result = {'probe': 'probe', 'workload': 'workload'} + elif op == 'probe': + completed = subprocess.run( + [sys.executable, str(PEER), '--version'], env=clean_environment(self.home), + capture_output=True, timeout=3, check=True) + assert completed.stdout == b'2026.05.04-08e5280\n', completed + elif op == 'launch': + assert self.vendor is None + self.launches += 1 + self.vendor = subprocess.Popen( + [sys.executable, str(PEER), 'acp'], cwd=self.home, + env=self.vendor_env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + elif op == 'read': + if self.vendor is None: + return {'error': 'vendor_effect_stale'} + if self.hold_stop_output and self.stop_requested: + # The adapter must drain the pending answer before it can read the terminal reply. + return {'result': {'eof': False}} + if select.select([self.vendor.stdout], [], [], .02)[0]: + data = os.read(self.vendor.stdout.fileno(), 65536) + result = ({'data': base64.b64encode(data).decode(), 'cursor': request['after'] + 1} + if data else {'eof': True}) + else: + result = {'eof': False} + elif op == 'write': + message = json.loads(request['data']) + kind = request['kind'] + if kind == 'prompt': + self.turn = request['call'] + self.stop_requested = self.stop_sent = False + if kind == 'cancel': + self.cancel_writes.append(request['call']) + if not self.stop_requested or self.stop_sent or self.turn is None: + return {'error': 'vendor_effect_stale'} + self.stop_sent = True + if kind == 'answer' and self.answer_error == REFUSAL: + return {'error': REFUSAL} + if kind in ('answer', 'housekeeping'): + self.answers.append(message) + if kind == 'housekeeping': + self.hold_stop_output = False + self.vendor.stdin.write(request['data'].encode() + b'\n') + self.vendor.stdin.flush() + if kind == 'answer' and self.answer_error: + return {'error': self.answer_error} + elif op == 'stop': + if self.turn is not None: + # The carrier records the request. The adapter sends the ACP cancel frame. + self.stop_requested = True + self.stop_call = request['call'] + result = {'turn': self.turn, 'dispatched': True, 'sent': self.stop_sent} + elif op == 'finish' and request['call'] == self.turn: + self.turn = None + elif op == 'receipt': + result = {'retired': self.vendor is None, 'probe': 'probe', 'workload': 'workload'} + elif op == 'retire': + self.retire() + self.retirements += 1 + result = {'retired': True, 'probe_settled': True, + 'workload_settled': self.settle_workload} + else: + assert op in ('ready', 'pending', 'finish', 'detach'), request + return {'result': result} + + def retire(self): + if self.vendor is not None: + process, self.vendor = self.vendor, None + try: + process.stdin.close() + process.wait(timeout=2) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=2) + raise + finally: + process.stdout.close() + process.stderr.close() + + def close(self): + self.adapter_socket.close() + self.thread.join(timeout=5) + if self.thread.is_alive(): + self.socket.shutdown(socket.SHUT_RDWR) + self.thread.join(timeout=5) + if self.thread.is_alive(): + raise AssertionError('Fixture carrier did not finish') + if self.error: + raise self.error + + +class ManagedAdapterTests(unittest.TestCase): + def setUp(self): + self.home = Path(self.enterContext(tempfile.TemporaryDirectory())) + self.adapter = packaged_root() / 'bin/cursor-mcp-adapter' + + def managed(self, answer_error=None, *, transport=False, vendor_env=None, settle_workload=True): + host = VendorFixture(self.home, answer_error, vendor_env, settle_workload=settle_workload) + self.addCleanup(host.close) + fd = host.adapter_socket.fileno() + bootstrap = ( + 'import os,sys; fd=int(sys.argv[1]); ' + 'os.dup2(fd,3); os.set_inheritable(3,True); ' + 'os.close(fd) if fd!=3 else None; os.execv(sys.executable,[sys.executable,*sys.argv[2:]])' + ) + entry = [str(START_TRANSPORT), str(self.adapter)] if transport else [str(self.adapter)] + client = Client(self.home, { + 'COMPUTER_MCP_HOST_CONTEXT': CAPABILITY, 'COMPUTER_MCP_HOST_FD': '3', + 'HOME': str(self.home), + }, [sys.executable, '-B', '-c', bootstrap, str(fd), *entry, '--host-vendor-execution'], + pass_fds=(fd,)) + self.addCleanup(client.close) + host.adapter_socket.close() + self.assertIs(client.initialization['result']['capabilities']['experimental'][CAPABILITY], True) + return client, host + + def raw_call(self, client, name, arguments=None, *, wait=True): + client.serial += 1 + identifier = client.serial + client.send({ + 'jsonrpc': '2.0', 'id': identifier, 'method': 'tools/call', + 'params': {'name': 'cursor.acp.' + name, 'arguments': arguments or {}, + '_meta': {METADATA: str(uuid.uuid4())}}, + }) + return client.wait(identifier, timeout=10) if wait else identifier + + def value(self, response): + self.assertFalse(response['result']['isError'], response) + return Client.value(response) + + def pending(self, client, session): + deadline = time.monotonic() + 3 + while time.monotonic() < deadline: + requests = self.value(self.raw_call(client, 'requests.list', {'session': session}))['requests'] + if requests: + return requests[0] + time.sleep(.01) + self.fail('Peer did not request a manual answer') + + def interactive(self, client): + session = self.value(self.raw_call(client, 'session.open', {'permission_policy': 'manual'}))['session'] + prompt = self.raw_call(client, 'session.prompt', { + 'session': session, 'prompt': 'permission-on-cancel', 'timeout_seconds': 10, + }, wait=False) + token = self.pending(client, session)['request_id'] + answer = {'outcome': {'outcome': 'selected', 'optionId': 'opaque-yes'}} + response = self.raw_call(client, 'requests.respond', { + 'session': session, 'request_id': token, 'response': answer, + }) + self.assertTrue(response['result']['isError']) + return session, prompt, token, Client.value(response)['error']['code'] + + def test_definitive_answer_refusal_leaves_turn_to_settle_pending_and_reuse_session(self): + client, host = self.managed(REFUSAL) + session, prompt, token, code = self.interactive(client) + self.assertEqual(code, 'response_refused') + self.assertEqual(self.pending(client, session)['request_id'], token) + self.assertTrue(self.value(self.raw_call(client, 'session.cancel', {'session': session}))['cancel_requested']) + stopped = client.wait(prompt, timeout=5) + self.assertTrue(stopped['result']['isError']) + self.assertEqual(Client.value(stopped)['native_result'], {'stopReason': 'cancelled'}) + self.assertEqual(host.answers, [ + {'jsonrpc': '2.0', 'id': 900, 'result': {'outcome': {'outcome': 'cancelled'}}}, + ]) + self.assertEqual(host.retirements, 0) + self.assertEqual(self.value(self.raw_call(client, 'requests.list', {'session': session}))['requests'], []) + reused = self.value(self.raw_call(client, 'session.prompt', {'session': session, 'prompt': 'hello'})) + self.assertEqual(reused['text'], 'hello') + self.assertEqual((self.home / 'cursor-native-starts.jsonl').read_text().count('\n'), 1) + self.value(self.raw_call(client, 'session.close', {'session': session})) + self.assertEqual(host.retirements, 1) + + def test_unknown_answer_delivery_retires_without_replaying_answer(self): + client, host = self.managed('cleanup_unconfirmed') + session, prompt, _, code = self.interactive(client) + self.assertEqual(code, 'response_unknown') + client.wait(prompt, timeout=5) + self.assertEqual(host.answers, [ + {'jsonrpc': '2.0', 'id': 900, + 'result': {'outcome': {'outcome': 'selected', 'optionId': 'opaque-yes'}}}, + ]) + self.assertGreaterEqual(host.retirements, 1) + result = self.raw_call(client, 'session.prompt', {'session': session, 'prompt': 'hello'}) + self.assertTrue(result['result']['isError']) + + def test_packaged_adapter_reconciles_a_dropped_launch_reply_without_replay(self): + client, host = self.managed(None, transport=True) + control = self.home / 'cursor-start-transport' + (control / 'fault').write_text('lose-reply') + opening = self.raw_call(client, 'session.open', wait=False) + + def event(name, timeout=3): + path = control / (name + '.json') + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if path.is_file(): + return json.loads(path.read_text()) + time.sleep(.01) + self.fail('Fixture did not observe ' + name) + + dropped = event('launch-dropped') + lookup = event('receipt', timeout=12) + for field in ('call', 'acquisition', 'child'): + self.assertEqual(dropped['request'][field], lookup['request'][field]) + self.assertFalse(lookup['reply']['result']['retired']) + self.assertIsNone(host.vendor.poll()) + effects = self.home / 'cursor-vendor-effects.jsonl' + self.assertEqual([(row['phase'], row['pid']) for row in map(json.loads, effects.read_text().splitlines())], + [('workload', host.vendor.pid)]) + (control / 'receipt.release').touch() + retired = event('retire') + self.assertTrue(retired['reply']['result']['retired']) + self.assertIsNone(host.vendor) + (control / 'retire.release').touch() + response = client.wait(opening, timeout=5) + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['error']['code'], 'timeout') + self.assertEqual((host.launches, host.retirements), (1, 1)) + self.assertFalse((control / 'launch-replayed.json').exists()) + self.assertFalse((self.home / 'cursor-native-starts.jsonl').exists()) + + def test_managed_authentication_required_stops_before_session_load(self): + client, host = self.managed(None, vendor_env={ + 'FIXTURE_AUTH_ERROR_CODE': '-32000', + 'FIXTURE_AUTH_ERROR_MESSAGE': 'fixture-sensitive-message', + }) + response = self.raw_call(client, 'session.open', {'resume_session_id': 'saved-conversation'}) + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['error'], { + 'code': 'authentication_required', + 'message': 'Cursor sign-in required (RPC code -32000).', + }) + self.assertNotIn('fixture-sensitive', json.dumps(response)) + self.assertFalse((self.home / 'cursor-native-starts.jsonl').exists()) + self.assertEqual(host.launches, 1) + self.assertIsNone(host.vendor) + + def test_managed_launch_without_host_negotiation_does_not_run_vendor(self): + environment = {**clean_environment(self.home), 'CURSOR_SOURCE_FIXTURE': '1'} + missing = subprocess.run( + [sys.executable, '-B', str(self.adapter), '--host-vendor-execution', '--executable', str(PEER)], + env=environment, capture_output=True, timeout=5) + self.assertNotEqual(missing.returncode, 0) + self.assertIn(b'Managed Cursor requires the Host vendor channel', missing.stderr) + self.assertFalse((self.home / 'cursor-vendor-effects.jsonl').exists()) + + def test_managed_one_shot_smoke_call(self): + call, expected = smoke_call() + client, host = self.managed() + result = self.value(self.raw_call( + client, call['tool'].removeprefix('cursor.acp.'), call['arguments'])) + self.assertEqual({key: result[key] for key in expected}, expected) + self.assertEqual((host.launches, host.retirements), (1, 1)) + + def test_managed_stop_preserves_native_completion(self): + client, host = self.managed(vendor_env={'FIXTURE_COMPLETION_PERMISSION': '1'}) + session = self.value(self.raw_call(client, 'session.open', {'permission_policy': 'manual'}))['session'] + prompt = self.raw_call(client, 'session.prompt', { + 'session': session, 'prompt': 'complete-on-cancel', + }, wait=False) + self.pending(client, session) + self.assertTrue(self.value(self.raw_call(client, 'session.cancel', { + 'session': session, + }))['cancel_requested']) + result = self.value(client.wait(prompt, timeout=5)) + self.assertEqual(result['native_result'], { + 'stopReason': 'end_turn', 'usage': {'tokens': 7}, '_meta': {'fixture': 'completed'}, + }) + self.assertEqual(host.answers, [ + {'jsonrpc': '2.0', 'id': 900, 'result': {'outcome': {'outcome': 'cancelled'}}}, + ]) + self.assertEqual((host.launches, host.retirements), (1, 0)) + self.value(self.raw_call(client, 'session.close', {'session': session})) + effects = self.home / 'cursor-vendor-effects.jsonl' + turn = [row for row in map(json.loads, effects.read_text().splitlines()) + if row['phase'] in ('prompt', 'cancel', 'terminal')] + self.assertEqual([row['phase'] for row in turn], ['prompt', 'cancel', 'terminal']) + self.assertIsNotNone(host.stop_call) + self.assertEqual(host.cancel_writes, [host.stop_call]) + self.assertEqual(len({(row['pid'], row['acp_id']) for row in turn}), 1) + + def test_managed_close_requires_both_child_receipts(self): + client, _ = self.managed(settle_workload=False) + session = self.value(self.raw_call(client, 'session.open'))['session'] + response = self.raw_call(client, 'session.close', {'session': session}) + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['error']['code'], 'cleanup_unconfirmed') + evidence = client.request('resources/read', {'uri': 'computer-mcp://runtime/work/v1'}) + [resource] = json.loads(evidence['result']['contents'][0]['text'])['resources'] + self.assertEqual((resource['id'], resource['state']), (session, 'uncertain')) diff --git a/tests/test_package.py b/tests/test_package.py index c43c5f6..34a2711 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -1,3 +1,4 @@ +import hashlib import importlib.util import io import json @@ -9,13 +10,36 @@ import tempfile import tomllib import unittest +from unittest.mock import patch import zipfile +from scripts.test_plugin import host_smoke_command +from support import PEER, clean_environment, packaged_root ROOT=Path(__file__).resolve().parent.parent spec=importlib.util.spec_from_file_location('build_package',ROOT/'scripts/build_package.py') builder=importlib.util.module_from_spec(spec);spec.loader.exec_module(builder) class PackageTests(unittest.TestCase): + def test_installed_smoke_binds_peer_to_the_adapter_python(self): + with tempfile.TemporaryDirectory() as directory: + stage = Path(directory).resolve() + (stage / 'verify-package.py').touch() + python = [sys.executable, '-B'] + with patch.dict('os.environ', {'COMPUTER_MCP_TEST_HOST': str(stage)}): + with host_smoke_command(python, stage / 'cursor.zip') as command: + vendor_flag, vendor_id, vendor_path, runtime_flag, runtime_id, runtime = command[-6:] + self.assertEqual((vendor_flag, vendor_id, runtime_flag, runtime_id), + ('--bind', 'cursor-agent', '--bind', 'python-runtime')) + self.assertEqual(runtime, str(Path(sys.executable).resolve())) + vendor = Path(vendor_path) + self.assertEqual(vendor.read_bytes().split(b'\n', 1)[0], f'#!{runtime}'.encode()) + signature = json.loads((ROOT / 'cursor-vendor-execution.json').read_text()) + # The peer must start even when PATH cannot provide Python. + result = subprocess.check_output( + [vendor_path, *signature['probe']], env={'PATH': str(stage)}, timeout=5) + self.assertEqual(result.decode(), signature['version_stdout']) + self.assertFalse(vendor.exists()) + def test_reproducible_archive_and_executable_mode(self): first,manifest=builder.package_bytes(ROOT) self.assertEqual(first,builder.package_bytes(ROOT)[0]) @@ -27,6 +51,45 @@ def test_reproducible_archive_and_executable_mode(self): self.assertEqual(tomllib.loads(archive.read('computer-mcp-plugin.toml').decode()),manifest) self.assertIn('cli-tree.json',names) self.assertIn('bin/plugin_runtime.py',names) + signature = json.loads(archive.read('cursor-vendor-execution.json')) + tree = json.loads(archive.read('cli-tree.json')) + self.assertEqual(signature, { + 'capability': 'io.github.computer-mcp/vendor-execution-v1', + 'dependency': 'cursor-agent', + 'tools': { + 'cursor.acp.prompt': 'acquire', + 'cursor.acp.session.open': 'acquire', + 'cursor.acp.session.prompt': 'prompt', + 'cursor.acp.session.prompt.start': 'detached_prompt', + 'cursor.acp.session.prompt.result': 'observe', + 'cursor.acp.session.list': 'observe', + 'cursor.acp.session.mode': 'mode', + 'cursor.acp.session.cancel': 'stop', + 'cursor.acp.session.close': 'close', + 'cursor.acp.events.read': 'observe', + 'cursor.acp.requests.list': 'observe', + 'cursor.acp.requests.respond': 'answer', + }, + 'probe': ['--version'], + 'workload': ['acp'], + 'version_stdout': next(check['stdout'] for check in tree['executable_checks'] + if check['args'] == ['--version']), + }) + self.assertIn(signature['dependency'], {dependency['id'] for dependency in manifest['dependencies']}) + [acp] = manifest['mcp'] + self.assertEqual((acp['id'], acp['transport']), ('acp', 'stdio')) + declaration = acp['vendor_execution'] + self.assertEqual(declaration['signature'], 'cursor-vendor-execution.json') + self.assertEqual(declaration['dependency'], signature['dependency']) + self.assertEqual({name for name, effect in signature['tools'].items() if effect == 'observe'}, + set(acp['tool_requirements'])) + self.assertEqual(set(declaration['files']), { + declaration['signature'], acp['executable']['path'], 'bin/cursor_vendor_execution.py', + 'bin/plugin_runtime.py', 'cli-tree.json', + }) + for name, digest in declaration['files'].items(): + self.assertEqual(archive.read(name), (ROOT / name).read_bytes()) + self.assertEqual(hashlib.sha256(archive.read(name)).hexdigest(), digest) assets={'.github/assets/logo/logo-light.png', '.github/assets/logo/logo-dark.png'} self.assertEqual({name for name in names if name.startswith('.github/')},assets) for name in assets: @@ -58,12 +121,38 @@ def test_bytecode_and_local_metadata_cannot_change_release_bytes(self): (cache/'arbitrary.pyc').write_bytes(b'not-release-content') (copy/'bin/.DS_Store').write_bytes(b'not-release-content') self.assertEqual(before,builder.package_bytes(copy)[0]) - def test_cli_prompt_mapping_has_an_explicit_option_separator(self): - tree=json.loads((ROOT/'cli-tree.json').read_text()) - for command in tree['commands']: - tokens=command.get('argv',[]) - position=next((i for i,x in enumerate(tokens) if x.get('parameter')=='prompt'),None) - if position is not None: - self.assertEqual(tokens[position-1],{'kind':'literal','value':'--'}) + def test_packaged_cli_binding_preserves_prompt_and_json_output(self): + package = packaged_root() + manifest = tomllib.loads((package / 'computer-mcp-plugin.toml').read_text()) + [cli] = manifest['cli'] + self.assertEqual(cli['id'], 'agent') + self.assertEqual(cli['executable'], {'dependency': 'cursor-agent'}) + self.assertEqual(cli['tree']['kind'], 'file') + tree = json.loads((package / cli['tree']['path']).read_text()) + print_command = next(command for command in tree['commands'] if command['id'] == 'print') + self.assertIs(print_command['executable'], True) + self.assertEqual(print_command['path'], []) + self.assertEqual(print_command['stdout'], 'json') + self.assertEqual([parameter['name'] for parameter in print_command['parameters'] + if parameter['required']], ['prompt']) + for parameter in print_command['parameters']: + if parameter['name'] != 'prompt': + self.assertIs(parameter.get('default', False), False) + tokens = print_command['argv'] + self.assertEqual(tokens[-2:], [ + {'kind': 'literal', 'value': '--'}, {'kind': 'positional', 'parameter': 'prompt'}, + ]) + argv = [token['value'] for token in tokens if token['kind'] == 'literal'] + self.assertEqual(argv, ['-p', '--output-format=json', '--']) + prompt = "--leading 'quotes' 中文\nfixture" + with tempfile.TemporaryDirectory() as directory: + cwd = Path(directory).resolve() + env = clean_environment(cwd) + [version] = tree['executable_checks'] + probe = subprocess.check_output([str(PEER), *version['args']], cwd=cwd, env=env, timeout=5) + self.assertEqual(probe.decode(), version['stdout']) + result = subprocess.check_output([str(PEER), *argv, prompt], cwd=cwd, env=env, timeout=5) + self.assertEqual(json.loads(result), {'argv': [*argv, prompt], 'cwd': str(cwd)}) + self.assertEqual((cwd / 'cursor-cli-write').read_text(), 'written') if __name__=='__main__':unittest.main() diff --git a/tests/test_protocol_admission.py b/tests/test_protocol_admission.py index 29c7dc7..a3eaeed 100644 --- a/tests/test_protocol_admission.py +++ b/tests/test_protocol_admission.py @@ -4,8 +4,8 @@ import threading import unittest from unittest.mock import patch -from support import ROOT -sys.path.insert(0,str(ROOT/'bin')) +from support import packaged_root +sys.path.insert(0, str(packaged_root() / 'bin')) import plugin_runtime as runtime class ProtocolAdmissionTests(unittest.TestCase): diff --git a/tests/test_review_regressions.py b/tests/test_review_regressions.py index d2f88e7..0a7b508 100644 --- a/tests/test_review_regressions.py +++ b/tests/test_review_regressions.py @@ -52,14 +52,6 @@ def pending(self,session): if session.pending:return next(iter(session.pending)) time.sleep(.001) self.fail('Native request did not become pending') - def test_close_during_version_probe_prevents_later_native_launch(self): - session=adapter.Session('handle','/unused','manual');job=Job() - def verify(*_):session.close() - with patch.object(adapter,'verify_version',side_effect=verify),patch.object(adapter,'Process') as process: - with self.assertRaises(Failure) as error:session.open({},job) - self.assertEqual(error.exception.code,'cancelled') - process.assert_not_called() - def test_missing_version_assertion_prevents_native_launch(self): for tree in ({}, {'executable_checks': []}, {'executable_checks': [{'args': ['--help'], 'stdout': 'usage\n'}]}, diff --git a/tests/test_robustness.py b/tests/test_robustness.py index 97e19a6..ab9138d 100644 --- a/tests/test_robustness.py +++ b/tests/test_robustness.py @@ -1,96 +1,31 @@ -"""Executable regressions; fixtures never contact Cursor or a model.""" -import json -import os -from pathlib import Path -import selectors -import subprocess -import sys +"""Exercise malformed requests on the shipped stdio entrypoint.""" + import tempfile -import time import unittest -ROOT = Path(__file__).resolve().parent.parent -FAKE = '''#!/usr/bin/env python3 -import json, sys -if sys.argv[1:] == ["--version"]: - print("2026.05.04-08e5280"); raise SystemExit -for line in sys.stdin: - q = json.loads(line) - method = q.get("method") - if method == "initialize": - value = {"protocolVersion":1,"agentCapabilities":{"loadSession":True},"authMethods":[{"id":"cursor_login","name":"Login"}]} - elif method == "session/new": - value = {"sessionId":"fixture-session"} - elif method == "session/prompt": - value = {"stopReason":"end_turn"} - else: - value = {} - if "id" in q: print(json.dumps({"jsonrpc":"2.0","id":q["id"],"result":value}),flush=True) -''' +from support import Client + class RobustnessTests(unittest.TestCase): def setUp(self): - self.temp = tempfile.TemporaryDirectory() - self.addCleanup(self.temp.cleanup) - fake = Path(self.temp.name) / "agent" - fake.write_text(FAKE) - fake.chmod(0o755) - env = dict(os.environ, CURSOR_AGENT_EXECUTABLE=str(fake)) - self.p = subprocess.Popen([sys.executable,str(ROOT/'bin/cursor-mcp-adapter')],cwd=self.temp.name,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) - self.addCleanup(self.stop) - self.buffer = b'' - self.serial = 2 - self.request({'id':1,'method':'initialize','params':{'protocolVersion':'2025-06-18','capabilities':{},'clientInfo':{'name':'fixture','version':'1'}}}) - self.send({'method':'notifications/initialized'}) - - def stop(self): - if not self.p.stdin.closed: self.p.stdin.close() - try: self.p.wait(timeout=3) - except subprocess.TimeoutExpired: - self.p.kill(); self.p.wait(timeout=3) - self.p.stdout.close(); self.p.stderr.close() - - def send(self, q): - self.p.stdin.write((json.dumps(dict(jsonrpc='2.0',**q))+'\n').encode()); self.p.stdin.flush() - - def receive(self, seconds=5): - deadline=time.monotonic()+seconds - with selectors.DefaultSelector() as selector: - selector.register(self.p.stdout,selectors.EVENT_READ) - while b'\n' not in self.buffer: - remaining=deadline-time.monotonic() - if remaining<=0 or not selector.select(remaining): self.fail('MCP response timeout') - chunk=os.read(self.p.stdout.fileno(),65536) - if not chunk: self.fail('MCP exited before a response') - self.buffer+=chunk - raw,self.buffer=self.buffer.split(b'\n',1) - return json.loads(raw) - - def request(self,q): self.send(q); return self.receive() - def call(self,args): - self.serial+=1 - return self.request({'id':self.serial,'method':'tools/call','params':{'name':'cursor.acp.prompt','arguments':args}}) + directory = self.enterContext(tempfile.TemporaryDirectory()) + self.client = Client(directory, protocol='9999-01-01') + self.addCleanup(self.client.close) def test_unknown_arguments_are_rejected(self): - r=self.call({'prompt':'hello','arbitrary_cwd':'/outside'}) - self.assertTrue(r.get('error') or r['result']['isError']) + response = self.client.call('cursor.acp.prompt', { + 'prompt': 'hello', 'arbitrary_cwd': '/outside', + }) + self.assertTrue(response.get('error') or response['result']['isError']) - def test_ping_is_supported(self): - self.assertEqual(self.request({'id':10,'method':'ping'})['result'],{}) - - def test_unimplemented_protocol_is_not_echoed(self): - # A new server is needed because initialize is single-use. - self.stop() - self.setUp() - self.p.stdin.close(); self.p.wait(timeout=3) - self.p.stdout.close(); self.p.stderr.close() - self.p=subprocess.Popen([sys.executable,str(ROOT/'bin/cursor-mcp-adapter')],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) - self.buffer=b'' - r=self.request({'id':11,'method':'initialize','params':{'protocolVersion':'9999-01-01','capabilities':{},'clientInfo':{'name':'fixture','version':'1'}}}) - self.assertEqual(r['result']['protocolVersion'],'2025-06-18') + def test_unimplemented_protocol_is_not_echoed_and_connection_works(self): + self.assertEqual(self.client.initialization['result']['protocolVersion'], '2025-06-18') + self.assertEqual(self.client.request('ping')['result'], {}) def test_non_object_request_has_protocol_error(self): - self.p.stdin.write(b'[]\n');self.p.stdin.flush() - self.assertEqual(self.receive()['error']['code'],-32600) + self.client.send([]) + self.assertEqual(self.client.receive()['error']['code'], -32600) + -if __name__=='__main__': unittest.main() +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_runtime_requirement.py b/tests/test_runtime_requirement.py deleted file mode 100644 index d275db2..0000000 --- a/tests/test_runtime_requirement.py +++ /dev/null @@ -1,20 +0,0 @@ -"""The public entrypoint must reject old runtimes before loading the adapter.""" -from pathlib import Path -import subprocess -import sys -import unittest - - -class RuntimeRequirementTests(unittest.TestCase): - def test_unsupported_interpreter_exits_with_actionable_diagnostic(self): - entry = next((Path(__file__).resolve().parent.parent / 'bin').glob('*-mcp-adapter')) - script = "import sys,runpy;sys.version_info=(3,12,99);runpy.run_path(sys.argv[1],run_name='__main__')" - result = subprocess.run([sys.executable, '-c', script, str(entry)], - capture_output=True, input=b'', timeout=5) - self.assertNotEqual(result.returncode, 0) - self.assertIn(b'Python 3.13+', result.stderr) - self.assertEqual(result.stdout, b'') - - -if __name__ == '__main__': - unittest.main() diff --git a/tests/test_work_resources.py b/tests/test_work_resources.py index 02dbe20..f4ef3ec 100644 --- a/tests/test_work_resources.py +++ b/tests/test_work_resources.py @@ -1,13 +1,14 @@ """Connection-owned Cursor sessions outlive their MCP creation responses.""" import json import os +from pathlib import Path import tempfile import threading import time import unittest import uuid from unittest.mock import Mock, patch -from support import Client +from support import Client, wait_file from test_completion import adapter from plugin_runtime import CONTINUATION_METADATA, Failure, Job, MCPServer, Process, WORK_INVOCATION, WORK_METADATA, WORK_URI @@ -183,34 +184,37 @@ def close_then_finish(): session.prompt_thread.join(2) self.assertTrue(session.released()) - def test_pending_startup_is_owned_before_native_execution(self): + def test_closing_reported_startup_during_version_probe_prevents_workload(self): origin = str(uuid.uuid4()) - cursor = adapter.Cursor('/unused') - entered, release = threading.Event(), threading.Event() - errors = [] - def verify(*_): - entered.set() - if not release.wait(2): raise AssertionError('Probe not released') - raise Failure('incompatible_vendor','No native session was launched') - def run(): - try: cursor.open({},Job(work_invocation=origin)) - except Exception as error: errors.append(error) - with patch.object(adapter,'resolve_executable',return_value='/unused'),patch.object(adapter,'verify_version',side_effect=verify),patch.object(adapter,'Process') as process: - thread = threading.Thread(target=run) - thread.start() + with tempfile.TemporaryDirectory() as root: + release = Path(root) / 'release-probe' + effects = Path(root) / 'cursor-vendor-effects.jsonl' + client = Client(root, { + 'CURSOR_SOURCE_FIXTURE': '1', 'FIXTURE_VERSION_RELEASE': str(release), + }) try: - self.assertTrue(entered.wait(1)) - rows = cursor.work_resources() - self.assertEqual(len(rows),1) - self.assertEqual(rows[0]['acquired_by'],origin) - self.assertEqual(rows[0]['state'],'active') + client.serial += 1 + opening = client.serial + client.send({ + 'jsonrpc': '2.0', 'id': opening, 'method': 'tools/call', + 'params': {'name': 'cursor.acp.session.open', + '_meta': {WORK_INVOCATION: origin}}, + }) + self.assertEqual(wait_file(effects)['phase'], 'probe') + [resource] = self.snapshot(client)['resources'] + self.assertEqual((resource['acquired_by'], resource['state']), (origin, 'active')) + closed = client.call('cursor.acp.session.close', {'session': resource['id']}) + self.assertFalse(closed['result']['isError']) + self.assertIs(Client.value(closed)['closed'], True) + response = client.wait(opening) + self.assertTrue(response['result']['isError']) + self.assertEqual(Client.value(response)['error']['code'], 'cancelled') + self.assertEqual(self.snapshot(client)['resources'], []) + self.assertEqual([json.loads(line)['phase'] for line in effects.read_text().splitlines()], + ['probe']) finally: - release.set() - thread.join(3) - self.assertFalse(thread.is_alive()) - process.assert_not_called() - self.assertEqual(len(errors),1) - self.assertEqual(cursor.work_resources(),[]) + release.touch() + client.close() def test_version_probe_cleanup_uncertainty_retains_its_session(self): origin = str(uuid.uuid4())