From 365deb00df325f643cdbcd861fbeef6e2d824479 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:27:26 +0800 Subject: [PATCH 01/29] feat: manage Cursor vendor sessions through host acquisitions --- CONTRIBUTING.md | 9 + Examples/settings.json | 4 - README.md | 16 +- bin/cursor-mcp-adapter | 178 +- bin/cursor_vendor_execution.py | 228 +++ computer-mcp-plugin.toml | 7 + cursor-vendor-execution.json | 8 + docs/Architecture/Package.md | 17 +- docs/Reference/Installation.md | 81 +- docs/Reference/Interface.md | 48 +- docs/Reference/Release.md | 3 +- scripts/build_package.py | 1 + scripts/validate_host.py | 191 +- scripts/validate_host_source.py | 334 ++++ .../CursorSourceIntegrationTests.swift.txt | 1668 +++++++++++++++++ tests/Fixtures/vendor.py | 78 +- tests/support.py | 6 +- tests/test_adapter.py | 78 +- tests/test_declarations.py | 30 + tests/test_host_source.py | 106 ++ tests/test_managed_adapter.py | 248 +++ tests/test_package.py | 17 + 22 files changed, 3074 insertions(+), 282 deletions(-) create mode 100644 bin/cursor_vendor_execution.py create mode 100644 cursor-vendor-execution.json create mode 100644 scripts/validate_host_source.py create mode 100644 tests/Fixtures/CursorSourceIntegrationTests.swift.txt create mode 100644 tests/test_declarations.py create mode 100644 tests/test_host_source.py create mode 100644 tests/test_managed_adapter.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index db6880d..623afea 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,3 +15,12 @@ Do not commit caches, local credentials or generated runtime state. Publishing a Contributions are licensed under this repository's [LICENSE](LICENSE), FSL-1.1-ALv2. + +Manifest caller requirements must agree with the actual adapter catalog; run +`python3 -m unittest discover -s tests -p 'test_declarations.py' -v` and +`python3 -m unittest discover -s tests -p 'test_host_source.py' -v` for focused checks. +The exact-source consumer and separate archive identity check are documented in the +[installation guide](docs/Reference/Installation.md). Use only clean reviewed full-SHA +pairs; never direct plugin commands to an implicit App control socket. The deterministic +fixture preserves native permission choices and does not establish authentication or +real-model sandbox suitability. CI host acquisition awaits the reviewed host pin. 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..abb8744 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 @@ -61,9 +61,12 @@ 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. + +Review the provider Project-write purpose and MCP caller requirements in the manifest. +The offline draft uses sandbox mode with network none and no user-config read exceptions; +native login/network/config and execution-mode acceptance remain pending owner decisions. See the [installation guide](docs/Reference/Installation.md) for revisions, configuration publication and validation. @@ -106,7 +109,10 @@ python3 -m unittest discover -s tests -p 'test_*.py' -v 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/bin/cursor-mcp-adapter b/bin/cursor-mcp-adapter index 898a6c5..bc277b4 100755 --- a/bin/cursor-mcp-adapter +++ b/bin/cursor-mcp-adapter @@ -14,6 +14,8 @@ 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'} @@ -84,7 +86,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 +142,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 +176,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 +187,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 +229,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 +237,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 +246,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 +262,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 +362,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 +388,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 +434,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 +446,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 +458,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 +473,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 +487,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 +516,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 +536,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 +558,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: @@ -514,13 +589,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..88b83ce 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -17,6 +17,11 @@ 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." + [[cli]] id = "agent" executable = { dependency = "cursor-agent" } @@ -29,6 +34,8 @@ 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" } } [[skills]] id = "cursor-agent" diff --git a/cursor-vendor-execution.json b/cursor-vendor-execution.json new file mode 100644 index 0000000..91e54da --- /dev/null +++ b/cursor-vendor-execution.json @@ -0,0 +1,8 @@ +{ + "capability": "io.github.computer-mcp/vendor-execution-v1", + "dependency": "cursor-agent", + "acquire": ["cursor.acp.session.open", "cursor.acp.prompt"], + "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..63e9ca8 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -6,15 +6,24 @@ The process supervisor requires the macOS `os.waitid` interface exposed by Pytho 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. +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 @@ -24,31 +33,61 @@ 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. 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 +## Deterministic source consumer -After packaging, validate the exact ZIP against the reviewed Computer MCP binary. Select its release version explicitly; a mismatch fails before package extraction: +Use explicit clean host and plugin repository roots and full lowercase 40-character +commit SHAs. The driver verifies both HEADs and clean status, exports committed sources +into a fresh ignored run 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. ```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 +python3 scripts/validate_host_source.py \ + --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/plugin-cursor/.agent/host6/source-run ``` -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. +Both SHA placeholders must be replaced with reviewed commits. The final host pin and CI +acquisition remain integration-owner decisions. 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. + +Run the same command with `--suite vendor-stop` and a fresh output directory +to select `CursorSourceIntegrationTests/registeredVendorStop`. This 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 test +exercises child acquisition, native settlement, pending permission cleanup, +independent retirement, lost start replies and closure during startup. The +default `--suite source` selects `CursorSourceIntegrationTests/sourceConsumer`. + +## 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. -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. +```sh +python3 scripts/validate_host.py \ + --host /absolute/path/to/computer-mcp --expected-host-version X.Y.Z \ + --archive /output/cursor.zip --output /new/evidence/directory +``` A real ACP handshake can be checked independently, without authenticating, opening a conversation or invoking a model: @@ -58,4 +97,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..b6fa707 100644 --- a/docs/Reference/Interface.md +++ b/docs/Reference/Interface.md @@ -8,6 +8,27 @@ 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 offline draft omits sandbox declarations: sandbox mode, network none and no existing +user-config read exceptions. Provider HOME/cache/state are host-provisioned persistent +container paths; temporary storage is execution-local. The host selects the worktree, +protects unrelated projects/host data/other containers and retires writers before removal. +This adapter does not request `projects-v1` or perform host lifecycle calls. Native login, +config reads, network and any Full access choice require measured facts and an owner +decision. The deterministic fixture does not establish real-model suitability. + ## Host risk metadata Every MCP tool declares `_meta["io.github.computer-mcp/risk"]`. Model execution @@ -56,6 +77,17 @@ 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. + ## Tools | Native MCP tool | Behavior | @@ -89,13 +121,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..ca1e16e 100644 --- a/docs/Reference/Release.md +++ b/docs/Reference/Release.md @@ -18,7 +18,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. 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/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..4fe8fce --- /dev/null +++ b/scripts/validate_host_source.py @@ -0,0 +1,334 @@ +"""Run the deterministic Cursor companion against explicit clean source commits. + +The driver exports both commits into an ignored 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 + +FIXTURE = "CursorSourceIntegrationTests.swift" +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", "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", +) + + +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 validate_locations(host, plugin, output): + if contains(host, plugin) or contains(plugin, host): + raise ValueError("Host and plugin must be separate, non-nested source checkouts") + owned = plugin / ".agent/host6" + if not contains(owned, output) or output == owned: + raise ValueError("Output must be a new run directory under plugin .agent/host6") + if contains(host, output): + raise ValueError("Output must be outside the host source") + if not git(plugin, "check-ignore", str(output / "receipt.json")): + raise ValueError("Run output must be ignored") + if output.exists() or output.is_symlink(): + raise ValueError("Output must be a new directory") + + +def run_process(command, cwd, environment, log, timeout): + """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: + 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") + + +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): + 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_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): + for record in (lost, closure): + if not isinstance(record, dict): + raise ValueError("Host did not record startup recovery") + phases = [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 phases) or len(set(phases)) != len(phases) + 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("charged_at_lookup") is not True + or lost.get("charged_after_retirement") is not False + 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") + if (type(closure.get("workload_starts")) is not int or closure["workload_starts"] != 0 + or closure.get("probe_state") != "retired" + or closure.get("workload_state") != "never_dispatched" + or closure.get("result") != "outcome_unknown" or closure.get("cleanup") != "confirmed"): + raise ValueError("Private channel closure did not confirm pending start cleanup") + + +def run(args): + 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) + suite = args.suite + before = {name: digest(args.plugin_source / name) for name in INPUTS} + args.output.mkdir(parents=True) + output = args.output + host = output / "host-source" + plugin = output / "plugin-source" + evidence = output / "cases.json" + run_id = os.urandom(16).hex() + result = { + "host_sha": args.host_sha, "plugin_sha": args.plugin_sha, "suite": suite, + "inputs_sha256": before, "run_id": run_id, "kind": "deterministic", + "native_verified": False, "python": sys.executable, "python_sha256": digest(Path(sys.executable)), "status": "failed", "cleanup": "pending", + } + environment = dict(os.environ) + # No implicit Cursor source, target or evidence selection from the parent session. + for key in list(environment): + if key.startswith("COMPUTER_MCP_CURSOR_"): + del environment[key] + environment.update({ + "COMPUTER_MCP_CURSOR_PLUGIN": str(plugin), + "COMPUTER_MCP_CURSOR_CASES": str(evidence), + "COMPUTER_MCP_CURSOR_RUN_ID": run_id, + "COMPUTER_MCP_CURSOR_PYTHON": sys.executable, + }) + 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/ComputerMCPMacOSTests" / 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 suite == "vendor-stop": + packages = output / "package" + run_process( + [sys.executable, "-B", str(plugin / "scripts/build_package.py"), str(packages)], + plugin, environment, output / "package-build.log", 30) + archive = packages / "cursor.zip" + result["archive_sha256"] = digest(archive) + environment["COMPUTER_MCP_CURSOR_ARCHIVE"] = str(archive) + environment["COMPUTER_MCP_CURSOR_ARCHIVE_SHA256"] = result["archive_sha256"] + run_process( + ["/usr/bin/swift", "test", "--build-system", "native", "--scratch-path", + str(output / "build"), "--no-parallel", "--filter", SELECTORS[suite]], + host, environment, output / "swift-test.log", args.timeout) + if evidence.stat().st_size > 65536: + raise ValueError("Case evidence exceeds its bound") + observed = json.loads(evidence.read_text()) + validate_evidence(observed, run_id, VENDOR_CASES if suite == "vendor-stop" else CASES) + if suite == "vendor-stop": + acquisitions = observed.get("acquisitions") + if not isinstance(acquisitions, list) or len(acquisitions) != 2: + raise ValueError("Host did not record the two acquired vendor workloads") + result["acquisitions"] = acquisitions + result["startup_cancellation"] = observed.get("startup_cancellation") + validate_startup_cancellation(result["startup_cancellation"]) + result["lost_start_reply"] = observed.get("lost_start_reply") + result["pending_start_closure"] = observed.get("pending_start_closure") + validate_start_recovery(result["lost_start_reply"], result["pending_start_closure"]) + if {name: digest(args.plugin_source / name) for name in INPUTS} != before: + raise ValueError("Source input changed during verification") + result["cases"] = sorted(observed["cases"]) + result["tests_executed"] = observed["tests_executed"] + result["status"] = "passed" + finally: + # Logs/case evidence survive; all exported sources and build output are owned here. + for path in (host, plugin, output / "build", output / "package"): + if path.is_symlink(): + raise RuntimeError("Run-owned cleanup target was replaced by a symlink") + if path.exists(): + shutil.rmtree(path) + result["cleanup"] = ("confirmed" if result["status"] == "passed" + else "exports-removed; fixture-process-cleanup-unverified") + try: + verify_source(args.host_source, args.host_sha) + verify_source(args.plugin_source, args.plugin_sha) + except BaseException: + result["status"] = "failed" + raise + finally: + (output / "receipt.json").write_text(json.dumps(result, indent=2, sort_keys=True) + "\n") + print(json.dumps({"receipt": str(output / "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=absolute) + parser.add_argument("--suite", choices=SELECTORS, 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/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt new file mode 100644 index 0000000..5c5db29 --- /dev/null +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -0,0 +1,1668 @@ +import ComputerMCPMacOS +import ComputerMCPPermissions +import ComputerMCPTestSupport +import Foundation +import Testing + +@testable import ComputerMCPConfiguration +@testable import ComputerMCPCore +@testable import ComputerMCPGateway +@testable import ComputerMCPPlugins + +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", +] + +@Suite(.nativeIntegration, .serialized, .timeLimit(.minutes(5))) +struct CursorSourceIntegrationTests { + @Test 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) + for (caller, provider) in [(1, true), (2, false)] { + try await withCursor(package, caller: caller, provider: provider) { h in + try await h.discover() + let before = h.base.observations.launches.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.base.observations.launches.count == before) + print( + "Cursor gate denial preserved (caller write: \(caller == 2), provider write: \(provider))" + ) + } + } + + var measured: [[String: Any]] = [] + try await withCursor(package) { h in + func providerLaunches() -> [ExecutionObservations.Launch] { + h.base.observations.launches.filter { $0.executable != h.base.platform.gitExecutable } + } + try await h.discover() + let cold = providerLaunches().count + let a = try await h.open() + let warm = providerLaunches().count + let b = try await h.open() + let launches = providerLaunches() + let first = Array(launches.dropFirst(cold).prefix(warm - cold)) + let second = Array(launches.dropFirst(warm)) + try #require(first.count == 3, "\(first)") + try #require(second.count == 2, "\(second)") + let adapter = try #require(first.first) + try #require(adapter.arguments.last == "--host-vendor-execution") + try #require(first.dropFirst().map(\.arguments) == [["--version"], ["acp"]]) + try #require(second.map(\.arguments) == [["--version"], ["acp"]]) + let allLaunchesSandboxed = (first + second).allSatisfy { $0.sandboxed } + try #require(allLaunchesSandboxed) + measured = try h.verifyAcquisitions( + first: Array(first.dropFirst()), second: second, adapterPID: adapter.member.processID) + let aPID = try #require(first.last?.member.processID) + let bPID = try #require(second.last?.member.processID) + print("Cursor gate acquired A \(aPID) and B \(bPID) in adapter \(adapter.member.processID)") + print( + "Cursor gate binaries \(adapter.executable) / \(first[1].executable) / \(second[0].executable)" + ) + let aOwner = try #require( + h.base.observations.ownerships.first { + (try? $0.recoveryState().root.processID) == aPID + }) + let bOwner = try #require( + h.base.observations.ownerships.first { + (try? $0.recoveryState().root.processID) == bPID + }) + let noFD = try cursorValue(try await h.prompt(a, "env")) + try #require(noFD["text"] == .string("[]")) + let outside = String( + decoding: try JSONSerialization.data(withJSONObject: h.outside.map(\.path)), + as: UTF8.self) + _ = try cursorValue(try await h.prompt(a, "boundaries:" + outside)) + 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 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(try await aOwner.members().contains(where: { $0.processID == aPID })) + _ = try cursorValue(try await h.prompt(a, "hello after cancellation")) + + async let interactive = h.prompt(a, "permission-on-cancel") + _ = try await h.waitPending(a) + let beforeAnswer = try h.vendorEffects().count + let interactiveStop = try cursorValue(try await h.stop(a)) + try #require(interactiveStop["cancel_requested"] == .bool(true)) + let interactiveResult = try cursorNativeValue(try await interactive) + 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([])) + _ = try cursorValue(try await h.prompt(a, "hello after pending cancellation")) + + 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 = h.base.observations.ownerships.first { + (try? $0.recoveryState().root.processID) == adapter.member.processID + } + 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"]) + let freshB = "fresh B prompt after A retirement" + let freshReply = try cursorValue(try await h.prompt(b, freshB)) + try #require(freshReply["session"] == .string(b)) + try #require(freshReply["stop_reason"] == .string("end_turn")) + try await h.waitVendorPrompt(pid: bPID, prompt: freshB) + let freshTurn = try h.vendorTurn(pid: bPID, prompt: freshB) + let freshNativeID = try #require(freshTurn.first?["acp_id"]?.intValue) + try #require(freshNativeID > bNativeID) + let effects = try h.vendorEffects() + try #require(effects.filter { $0["phase"]?.stringValue == "probe" }.count == 2) + try #require( + effects.filter { + $0["pid"]?.intValue == Int(aPID) && $0["phase"]?.stringValue == "cancel" + }.count == 3) + try #require( + effects.filter { + $0["pid"]?.intValue == Int(bPID) && $0["phase"]?.stringValue == "cancel" + }.count == 1) + try #require(try h.nativeStarts == 2) + try #require(providerLaunches().count == launches.count) + _ = try cursorValue( + try await h.call("cursor.acp.session.close", ["session": .string(b)])) + try #require(try await bOwner.members().isEmpty) + } + let evidence = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_CASES"])) + var cases = [ + "dual-authority", "cold-warm-ownership", "seatbelt-boundaries", "ordinary-cancel", + "native-result-races", "pending-answer-cancel", "forced-stop-isolation", "cleanup", + ] + var details: [String: Any] = ["acquisitions": measured] + #if DEBUG + details["startup_cancellation"] = try await registeredStartupCancellation(package) + details["lost_start_reply"] = try await registeredLostStartReply(package) + details["pending_start_closure"] = try await registeredPendingStartClosure(package) + cases += ["startup-cancellation", "lost-start-reply", "pending-start-closure"] + #endif + details["kind"] = "deterministic" + details["tests_executed"] = 1 + let runID = try #require(env["COMPUTER_MCP_CURSOR_RUN_ID"]) + details["run_id"] = runID + details["cases"] = cases + try JSONSerialization.data(withJSONObject: details).write(to: evidence, options: .atomic) + } + + #if DEBUG + private func registeredStartupCancellation(_ package: PluginPackage) async throws + -> [String: Any] + { + var evidence: [String: Any] = [:] + try await withCursor(package) { h in + try await h.discover() + // Discovery and delegated execution use separate pool authority. + let executionBaseline = h.vendorLaunches.count + let b = try await h.open() + let launches = Array(h.vendorLaunches.dropFirst(executionBaseline)) + try #require(launches.count == 3) + try #require(launches.dropFirst().map(\.arguments) == [["--version"], ["acp"]]) + let bPID = try #require(launches.last?.member.processID) + let adapter = try #require(launches.first) + try #require(adapter.arguments.last == "--host-vendor-execution") + let adapterPID = adapter.member.processID + let bOwner = try #require( + h.base.observations.ownerships.first { + (try? $0.recoveryState().root.processID) == bPID + }) + let bPrompt = "complete-on-cancel" + let bRequest = "startup-sibling" + let bStarted = try cursorValue( + try await h.call( + "cursor.acp.session.prompt", ["session": .string(b), "prompt": .string(bPrompt)], + startRequestID: bRequest)) + try #require(bStarted["state"] == .string("running")) + let bDownstream = try #require(bStarted["downstream_request_id"]) + try await h.waitVendorPrompt(pid: bPID, prompt: bPrompt) + let bPending = try h.vendorTurn(pid: bPID, prompt: bPrompt) + try #require(bPending.map { $0["phase"]?.stringValue } == ["prompt"]) + let bNative = try #require(bPending.first?["acp_id"]) + + for withdraw in [false, true] { + let requestID = withdraw ? "startup-withdraw" : "startup-control" + let gate = CursorStartupBarrier() + let launchCount = h.vendorLaunches.count + let startCount = try h.nativeStarts + try await h.withStartupBarrier(gate) { + let started = try cursorValue( + try await h.call( + "cursor.acp.session.open", ["permission_policy": .string("manual")], + startRequestID: requestID)) + try #require(started["request_id"] == .string(requestID)) + try #require(started["state"] == .string("running")) + let downstream = try #require(started["downstream_request_id"]?.stringValue) + let boundary = try await gate.wait() + let initialReceipts = boundary.receipts() + try #require(initialReceipts.probe == "retired") + try #require(initialReceipts.workload == "pending") + let before = try h.startupChildren(boundary) + let probePID = try #require(before.probe.recovery?.root.processID) + try #require(before.probe.completed) + try #require(before.workload.recovery == nil && !before.workload.completed) + let atBoundary = Array(h.vendorLaunches.dropFirst(launchCount)) + try #require(atBoundary.map(\.arguments) == [["--version"]]) + try #require(atBoundary.first?.member.processID == probePID) + try #require(atBoundary.first?.sandboxed == true) + var trial: [String: Any] = [ + "acquisition": boundary.acquisitionID.uuidString, + "execution": boundary.executionID.uuidString, + "probe": boundary.probeID.uuidString, + "workload": boundary.workloadID.uuidString, + "probe_pid": Int(probePID), + "probe_state": initialReceipts.probe, + "request_id": requestID, + "downstream_request_id": downstream, + ] + + if withdraw { + let cancellation = try cursorValue( + try await h.gateway.callToolForMCPAsync( + name: "mcp.requests.cancel", + arguments: .object([ + "server": .string("cursor-fixture"), "request_id": .string(requestID), + ]), context: .empty)) + try #require(cancellation["cancellation_requested"] == .bool(true)) + try #require(cancellation["request_id"] == .string(requestID)) + let sealed = try h.startupChildren(boundary) + let receipts = boundary.receipts() + try #require(receipts.probe == "retired") + try #require(receipts.workload == "never_dispatched") + try #require(sealed.probe.completed) + try #require(sealed.probe.recovery?.root.processID == probePID) + try #require(sealed.workload.completed && sealed.workload.recovery == nil) + try #require(h.vendorLaunches.count == launchCount + 1) + trial["workload_state"] = receipts.workload + print("Cursor startup sealed \(boundary.acquisitionID) before workload bootstrap") + } + + gate.release() + let receipt = try await h.waitRequestReceipt(requestID) + try #require(receipt["request_id"] == .string(requestID)) + try #require(receipt["downstream_request_id"] == .string(downstream)) + let reply = try #require(receipt["result"]) + if withdraw { + try #require(receipt["state"] == .string("failed"), "\(receipt)") + try #require(receipt["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 #require(h.vendorLaunches.count == launchCount + 1) + try #require(try h.nativeStarts == startCount) + trial["workload_starts"] = 0 + trial["result"] = "cancelled" + } else { + try #require(receipt["state"] == .string("succeeded"), "\(receipt)") + let opened = try cursorValue(reply) + let session = try #require(opened["session"]?.stringValue) + let live = try h.startupChildren(boundary) + let workloadPID = try #require(live.workload.recovery?.root.processID) + try #require(!live.workload.completed) + let launches = Array(h.vendorLaunches.dropFirst(launchCount)) + try #require(launches.map(\.arguments) == [["--version"], ["acp"]]) + try #require(launches.last?.member.processID == workloadPID) + try #require(launches.last?.sandboxed == true) + try #require(try h.nativeStarts == startCount + 1) + let owner = try #require( + h.base.observations.ownerships.first { + (try? $0.recoveryState().root.processID) == workloadPID + }) + _ = try cursorValue( + try await h.call("cursor.acp.session.close", ["session": .string(session)])) + try #require(try await owner.members().isEmpty) + trial["workload_pid"] = Int(workloadPID) + trial["workload_starts"] = 1 + trial["result"] = "opened" + print("Cursor startup control \(boundary.acquisitionID) launched \(workloadPID)") + } + evidence[withdraw ? "cancelled" : "control"] = trial + } + } + + try #require(try await bOwner.members().contains(where: { $0.processID == bPID })) + let stillPending = try h.vendorTurn(pid: bPID, prompt: bPrompt) + try #require(stillPending.map { $0["phase"]?.stringValue } == ["prompt"]) + try #require(stillPending.first?["acp_id"] == bNative) + let stop = try cursorValue(try await h.stop(b)) + try #require(stop["cancel_requested"] == .bool(true)) + let completed = try await h.waitRequestReceipt(bRequest) + try #require(completed["state"] == .string("succeeded"), "\(completed)") + try #require(completed["downstream_request_id"] == bDownstream) + let result = try cursorValue(try #require(completed["result"])) + try #require( + result["session"] == .string(b) && result["stop_reason"] == .string("end_turn")) + let settled = try h.vendorTurn(pid: bPID, prompt: bPrompt) + try #require(settled.map { $0["phase"]?.stringValue } == ["prompt", "cancel", "terminal"]) + try #require(settled.last?["acp_id"] == bNative) + try #require(settled.last?["outcome"]?.objectValue?["result"] == result["native_result"]) + let fresh = "fresh B after startup cancellation" + let reply = try cursorValue(try await h.prompt(b, fresh)) + try #require(reply["session"] == .string(b) && reply["stop_reason"] == .string("end_turn")) + try await h.waitVendorPrompt(pid: bPID, prompt: fresh) + let freshTurn = try h.vendorTurn(pid: bPID, prompt: fresh) + let freshID = try #require(freshTurn.first?["acp_id"]?.intValue) + let originalID = try #require(bNative.intValue) + try #require(freshID > originalID) + _ = try cursorValue(try await h.call("cursor.acp.session.close", ["session": .string(b)])) + try #require(try await bOwner.members().isEmpty) + let adapters = h.vendorLaunches.dropFirst(executionBaseline).filter { + $0.arguments.last == "--host-vendor-execution" + } + try #require(adapters.map(\.member.processID) == [adapterPID]) + evidence["sibling_pid"] = Int(bPID) + evidence["adapter_pid"] = Int(adapterPID) + } + return evidence + } + + private func registeredLostStartReply(_ package: PluginPackage) async throws -> [String: Any] { + var evidence: [String: Any] = [:] + try await withCursor(package) { h in + try await h.discover() + let b = try await h.open() + let bPID = try #require(h.vendorLaunches.last?.member.processID) + let before = h.vendorLaunches.count + let launch = CursorStartupBarrier() + let lookup = CursorStartupBarrier() + let retire = CursorStartupBarrier() + try await h.withVendorReplyObserver( + { reply in + switch reply.operation { + case .launch: + await launch.park(reply) + return true + case .receipt: + await lookup.park(reply) + return false + case .retire: + await retire.park(reply) + return false + } + }, + release: { + launch.release() + lookup.release() + retire.release() + } + ) { + let requestID = "startup-lost-reply" + let arguments: [String: JSONValue] = ["permission_policy": .string("manual")] + let started = try cursorValue( + try await h.call("cursor.acp.session.open", arguments, startRequestID: requestID)) + try #require(started["state"] == .string("running")) + try #require(started["request_id"] == .string(requestID)) + let downstream = try #require(started["downstream_request_id"]?.stringValue) + let withheld = try await launch.wait() + let boundary = withheld.boundary + let probeID = JSONValue.string(boundary.probeID.uuidString.lowercased()) + let workloadID = JSONValue.string(boundary.workloadID.uuidString.lowercased()) + let pid = try await h.waitForNewWorkload(since: before) + let live = try h.startupChildren(boundary) + let member = try #require(live.workload.recovery?.root) + try #require(member.processID == pid) + try #require(withheld.requestedWorkloadID == boundary.workloadID) + let durable = try h.workloadJournal(boundary) + try #require(durable.recovery.root == member && !durable.completed) + try #require(withheld.charged) + print("Cursor startup reply dropped for \(boundary.workloadID) after peer \(pid) started") + launch.release() + + let recovered = try await lookup.wait(timeout: .seconds(15)) + try #require(recovered.boundary.acquisitionID == boundary.acquisitionID) + try #require(recovered.boundary.executionID == boundary.executionID) + try #require(recovered.requestedWorkloadID == boundary.workloadID) + try #require(recovered.payload["probe"] == probeID) + try #require(recovered.payload["workload"] == workloadID) + try #require(recovered.payload["probe_state"] == .string("retired")) + try #require(recovered.payload["workload_state"] == .string("pending")) + try #require(recovered.payload["retired"] == .bool(false)) + try #require(recovered.charged) + print("Cursor startup lookup recovered \(boundary.workloadID) while still charged") + let pending = try h.workloadJournal(boundary) + try #require(pending.recovery.root == member && !pending.completed) + let during = "B while A start receipt is pending" + let bReply = try cursorValue(try await h.prompt(b, during)) + try #require( + bReply["session"] == .string(b) && bReply["stop_reason"] == .string("end_turn")) + try await h.waitVendorPrompt(pid: bPID, prompt: during) + lookup.release() + + let settled = try await retire.wait() + try #require(settled.boundary.acquisitionID == boundary.acquisitionID) + try #require(settled.requestedWorkloadID == boundary.workloadID) + try #require(settled.payload["probe"] == probeID) + try #require(settled.payload["workload"] == workloadID) + try #require(settled.payload["workload_state"] == .string("retired")) + try #require(settled.payload["retired"] == .bool(true) && !settled.charged) + let complete = try h.workloadJournal(boundary) + try #require(complete.completed && complete.recovery.root == member) + let owner = try #require( + h.base.observations.ownerships.first { + (try? $0.recoveryState().root) == member + }) + try #require(try await owner.members().isEmpty) + print("Cursor startup retired \(boundary.workloadID) and released its capacity") + retire.release() + + 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", arguments, startRequestID: requestID)) + try #require(repeated["state"] == .string("failed")) + try #require(repeated["downstream_request_id"] == .string(downstream)) + try #require(repeated["result"] == reply) + try #require(repeated["replayed"] == .bool(false)) + + let fresh = "B after lost start reply settlement" + let bFresh = try cursorValue(try await h.prompt(b, fresh)) + try #require( + bFresh["session"] == .string(b) && bFresh["stop_reason"] == .string("end_turn")) + try await h.waitVendorPrompt(pid: bPID, prompt: fresh) + let measured = Array(h.vendorLaunches.dropFirst(before)) + try #require(measured.map(\.arguments) == [["--version"], ["acp"]]) + let peers = try h.vendorEffects().filter { $0["phase"] == .string("workload") } + try #require(peers.compactMap { $0["pid"]?.intValue } == [Int(bPID), Int(pid)]) + try #require(try h.nativeStarts == 1) + evidence = [ + "request_id": requestID, "downstream_request_id": downstream, + "acquisition": boundary.acquisitionID.uuidString, + "execution": boundary.executionID.uuidString, "probe": boundary.probeID.uuidString, + "workload": boundary.workloadID.uuidString, "workload_pid": Int(pid), + "sibling_pid": Int(bPID), "charged_at_lookup": recovered.charged, + "charged_after_retirement": settled.charged, "workload_starts": peers.count - 1, + "workload_state": "retired", "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] = [:] + try await withCursor(package) { h in + try await h.discover() + _ = try await h.open() + let bPID = try #require(h.vendorLaunches.last?.member.processID) + let bOwner = try #require( + h.base.observations.ownerships.first { + (try? $0.recoveryState().root.processID) == bPID + }) + let before = h.vendorLaunches.count + let gate = CursorStartupBarrier() + try await h.withStartupBarrier(gate) { + let requestID = "startup-connection-closure" + let started = try cursorValue( + try await h.call( + "cursor.acp.session.open", ["permission_policy": .string("manual")], + startRequestID: requestID)) + try #require(started["state"] == .string("running")) + let downstream = try #require(started["downstream_request_id"]?.stringValue) + let boundary = try await gate.wait() + let beforeClosure = try h.startupChildren(boundary) + let probeRoot = try #require(beforeClosure.probe.recovery?.root) + try #require(beforeClosure.probe.completed && !beforeClosure.workload.completed) + try #require(beforeClosure.workload.recovery == nil) + let owner = try await h.vendorRequestOwner(requestID) + async let close = h.closeVendorConnection(owner) + do { + try await h.waitForStartupDrain(boundary) + } catch { + gate.release() + _ = try? await close + throw error + } + gate.release() + + let result = try await close + 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)") + print("Cursor private channel close joined pending startup \(boundary.acquisitionID)") + let after = try h.startupChildren(boundary) + try #require(after.probe.completed && after.workload.completed) + try #require(after.probe.recovery?.root == probeRoot) + try #require(after.workload.recovery == nil) + try #require(try await bOwner.members().isEmpty) + let measured = Array(h.vendorLaunches.dropFirst(before)) + try #require(measured.map(\.arguments) == [["--version"]]) + 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) + evidence = [ + "request_id": requestID, "downstream_request_id": downstream, + "acquisition": boundary.acquisitionID.uuidString, + "execution": boundary.executionID.uuidString, "probe": boundary.probeID.uuidString, + "workload": boundary.workloadID.uuidString, "workload_starts": measured.count - 1, + "probe_state": boundary.receipts().probe, + "workload_state": boundary.receipts().workload, + "result": "outcome_unknown", "cleanup": "confirmed", + ] + } + } + return evidence + } + #endif + + @Test 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) + try #require(package.manifest.sandbox == nil) + 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.callToolForMCPAsync( + 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.callToolForMCPAsync( + 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) + try #require( + record["denied"] as? [[String]] == Array(repeating: ["r", "a"], count: h.outside.count)) + } + 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)) + try #require(cancelled["is_error"] == .bool(true)) + try #require(try h.nativeStarts == nativeStarts) + // Client B uses a separate authority and kill domain in the same provider container. + let firstOwnerships = h.base.observations.ownerships + var retained = false + for ownership in firstOwnerships { + if try await ownership.members().isEmpty == false { retained = true } + } + try #require(retained) + let second = try h.makeConsumer("cursor-second", caller: 2, use: true) + h.other = second + try await h.discover(gateway: second) + let secondSession = try #require( + try cursorValue(try await h.call("cursor.acp.session.open", gateway: second))["session"]? + .stringValue) + let service = h.gateway.permissionRuntime.service + _ = try service.revokePermission( + .plugin("cursor"), profileID: h.consumerID, owner: h.owner, + expectedRevision: service.view(owner: h.owner).revision) + 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 cursorValue( + try await h.call( + "cursor.acp.session.prompt", + ["session": .string(secondSession), "prompt": .string("hello")], gateway: second)) + for _ in 0..<200 { + var live = false + for ownership in firstOwnerships { + if try await ownership.members().isEmpty == false { live = true } + } + if !live { break } + try await Task.sleep(for: .milliseconds(10)) + } + for ownership in firstOwnerships { try #require(try await ownership.members().isEmpty) } + // Removal is performed by the host while B still owns a live native session. + 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.requireJoined() + } + let evidence = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_CASES"])) + try JSONSerialization.data(withJSONObject: [ + "kind": "deterministic", "tests_executed": 1, + "run_id": try #require(env["COMPUTER_MCP_CURSOR_RUN_ID"]), + "cases": [ + "package", "declarations", "dual-authority", "cli", "mcp", "skills", "worktree", + "container", "boundaries", "continuation", "cancellation", "scoped-revocation", + "host-removal", "cleanup", + ], + ]).write(to: evidence, 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 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)") +} +private func withCursor( + _ package: PluginPackage, caller: Int = 2, provider: Bool = true, + use: Bool = true, body: (CursorHarness) async throws -> Void +) async throws { + let h = try await CursorHarness.make(package, caller: caller, provider: provider, use: use) + do { try await body(h) } catch { + do { try await h.close() } catch { Issue.record("Cursor cleanup failed: \(error)") } + throw error + } + try await h.close() +} + +#if DEBUG + private typealias CursorStartupBoundary = CursorVendorStartupObservation.Boundary + private typealias CursorStartupReply = CursorVendorStartupObservation.Reply + + private final class CursorStartupBarrier: Sendable { + private let arrival = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + private let permission = AsyncStream.makeStream() + + func park(_ boundary: Value) async { + arrival.continuation.yield(boundary) + arrival.continuation.finish() + var permit = permission.stream.makeAsyncIterator() + _ = await permit.next() + } + + func wait(timeout: Duration = .seconds(10)) async throws -> Value { + try await withThrowingTaskGroup(of: Value.self) { group in + group.addTask { + var events = self.arrival.stream.makeAsyncIterator() + guard let boundary = await events.next() else { throw CursorFixtureError.deadline } + return boundary + } + group.addTask { + try await Task.sleep(for: timeout) + throw CursorFixtureError.deadline + } + defer { group.cancelAll() } + guard let boundary = try await group.next() else { throw CursorFixtureError.deadline } + return boundary + } + } + + func release() { permission.continuation.finish() } + } +#endif + +private final class CursorHarness: @unchecked Sendable { + let base: FixedHostFixture + 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 gateway: GatewayRuntime! + var other: GatewayRuntime? + 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) async throws + -> CursorHarness + { + let base = try FixedHostFixture(fullAccess: false, lifecycle: true) + let lifecycle = GatewayStandaloneGenerations(base.runtime) + var pending: CursorHarness? + var created: String? + do { + try await base.initializeRepository() + let value = try cursorValue( + try await lifecycle.callToolForMCPAsync( + 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"), + base.root.appendingPathComponent("unrelated"), + 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 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 let archive = 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": python]) + _ = 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: python), + ], + 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: python).resolvingSymlinksInPath()) + try #require( + adapter.args == [runtimePackage.root.appendingPathComponent("bin/cursor-mcp-adapter").path]) + 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 }) + h.gateway = 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) + if origin.kind == .development { + try #require(beforeSettings == beforeRegistration) + } + try #require(try h.nativeStarts == 0) + 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 { + if let pending { + try await pending.close() + } else { + if let created { + _ = try await lifecycle.callToolForMCPAsync( + 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) + } + throw error + } + } + 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 -> GatewayRuntime { + 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, plugins: [plugin], bundledPlugins: .init(packages: [], issues: [])) + _ = try gateway.makeControlSession() + return gateway + } + func catalog(gateway selected: GatewayRuntime? = nil) async throws -> JSONValue { + try await (selected ?? gateway!).callToolForMCPAsync( + name: "mcp.tools.list", arguments: .object(["server": .string("cursor-fixture")]), + context: .empty) + } + func discover(gateway selected: GatewayRuntime? = nil) async throws { + let firstOwnership = base.observations.ownerships.count + let result = try await catalog(gateway: selected) + if result.objectValue?["isError"] == .bool(true) { + await reportLaunchFailure(since: 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.callToolForMCPAsync( + name: name, arguments: .object(["prompt": .string(prompt)]), context: .empty) + if result.objectValue?["isError"] == .bool(true) { + await reportLaunchFailure(since: 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(since firstOwnership: Int, operation: String) async { + for ownership in base.observations.ownerships.dropFirst(firstOwnership) { + 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: GatewayRuntime? = 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) + } + return try await (selected ?? gateway!).callToolForMCPAsync( + name: "mcp.tools.call", arguments: .object(arguments), context: .empty) + } + func requestReceipt(_ id: String) async throws -> [String: JSONValue] { + try cursorValue( + try await gateway.callToolForMCPAsync( + name: "mcp.requests.read", + arguments: .object(["server": .string("cursor-fixture"), "request_id": .string(id)]), + context: .empty)) + } + #if DEBUG + var vendorLaunches: [ExecutionObservations.Launch] { + base.observations.launches.filter { $0.executable != base.platform.gitExecutable } + } + func withStartupBarrier( + _ barrier: CursorStartupBarrier, body: () async throws -> Void + ) async throws { + let observation = CursorVendorStartupObservation.shared + await observation.set({ await barrier.park($0) }, projectID: projectID) + do { + try await body() + } catch { + barrier.release() + await observation.set(nil, projectID: projectID) + throw error + } + await observation.set(nil, projectID: projectID) + } + func withVendorReplyObserver( + _ observe: @escaping @Sendable (CursorStartupReply) async -> Bool, + release: () -> Void, + body: () async throws -> Void + ) async throws { + let observation = CursorVendorStartupObservation.shared + await observation.setReplyObserver(observe, projectID: projectID) + do { + try await body() + } catch { + release() + await observation.setReplyObserver(nil, projectID: projectID) + throw error + } + release() + await observation.setReplyObserver(nil, projectID: projectID) + } + 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 workloadJournal(_ boundary: CursorStartupBoundary) throws -> ExecutionRecoveryJournal.Entry + { + let path = base.database.permissionExecutionRoot.appendingPathComponent("ownership") + .appendingPathComponent(boundary.workloadID.uuidString + ".json") + let entry = try JSONDecoder().decode( + ExecutionRecoveryJournal.Entry.self, from: Data(contentsOf: path)) + try #require(entry.child == boundary.workloadID && entry.execution == boundary.executionID) + try #require(entry.recovery.sandboxed) + return entry + } + func waitForNewWorkload(since index: Int) async throws -> Int32 { + let deadline = ContinuousClock.now + .seconds(5) + repeat { + if let launch = vendorLaunches.dropFirst(index).first(where: { $0.arguments == ["acp"] }) { + let pid = launch.member.processID + if try vendorEffects().contains(where: { + $0["phase"] == .string("workload") && $0["pid"]?.intValue == Int(pid) + }) { + try #require(launch.sandboxed) + return pid + } + } + try await Task.sleep(for: .milliseconds(20)) + } while ContinuousClock.now < deadline + throw CursorFixtureError.deadline + } + 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 gateway.callToolForMCPAsync( + 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 gateway.callToolForMCPAsync( + 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 waitForStartupDrain(_ boundary: CursorStartupBoundary) async throws { + let deadline = ContinuousClock.now + .seconds(7) + repeat { + if await boundary.channelClosed(), boundary.receipts().workload == "never_dispatched" { + return + } + try await Task.sleep(for: .milliseconds(20)) + } while ContinuousClock.now < deadline + throw CursorFixtureError.deadline + } + #endif + 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() async throws -> String { + try #require( + try cursorValue( + try await call("cursor.acp.session.open", ["permission_policy": .string("manual")]))[ + "session"]?.stringValue) + } + 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 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: [ExecutionObservations.Launch], second: [ExecutionObservations.Launch], adapterPID: Int32 + ) 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 pids = Set(pair.map { $0.member.processID }) + 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 { pids.contains($0.root.processID) } ?? 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) + } + if rows.isEmpty { + try #require( + record.children.values.contains { $0.recovery?.root.processID == adapterPID }) + } else { + try #require(record.children.count == 2) + } + let phaseIDs = try pair.map { launch in + try #require(slots.first(where: { $0.value.recovery?.root == launch.member })?.key) + } + rows.append([ + "execution": execution.id.uuidString, + "authorization_ids": execution.authorizationIDs.map(\.uuidString).sorted(), + "adapter_pid": adapterPID, + "probe_pid": pair[0].member.processID, + "probe_child": phaseIDs[0].uuidString, + "workload_pid": pair[1].member.processID, + "workload_child": phaseIDs[1].uuidString, + ]) + } + try #require(matched) + } + return rows + } + } + 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) async throws -> [String: JSONValue] { + for _ in 0..<200 { + let value = try cursorValue( + try await call( + "cursor.acp.session.prompt.result", + ["session": .string(session), "prompt_id": .string(prompt)])) + 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.callToolForMCPAsync( + 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 gateway.permissionRuntime.coordinator.reconcile() + var live = false + for ownership in base.observations.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 gateway?.shutdown() + await other?.shutdown() + if !removed { try await removeWorktree() } + try await requireJoined() + try await base.requireNoScratch() + await lifecycle.shutdown() + base.session.end() + await base.runtime.shutdown() + 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/vendor.py b/tests/Fixtures/vendor.py index cddefd7..ba7d912 100755 --- a/tests/Fixtures/vendor.py +++ b/tests/Fixtures/vendor.py @@ -7,14 +7,56 @@ 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') 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 +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}) @@ -27,14 +69,17 @@ def finish(identifier,reason='end_turn'):reply(identifier,{'stopReason':reason}) reply(identifier,{'protocolVersion':1,'agentCapabilities':{'loadSession':True},'authMethods':[{'id':'cursor_login','name':'Existing CLI login'}]}) elif method=='authenticate':reply(identifier,{}) 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': + observe('prompt', prompt=prompt, acp_id=identifier, native_session=session) + if prompt in ('permission','permission-on-cancel','question','plan'): + if prompt in ('permission','permission-on-cancel'): 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'}]} 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}]} @@ -42,7 +87,7 @@ def finish(identifier,reason='end_turn'):reply(identifier,{'stopReason':reason}) 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 +98,29 @@ 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.startswith('boundaries:'): + update(json.dumps(boundaries(json.loads(prompt[len('boundaries:'):])))) + 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) + update(json.dumps({'received_response':response})) + cancelled = prompt == 'permission-on-cancel' and response == {'outcome': {'outcome': 'cancelled'}} + finish(waiting.pop(identifier), '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/support.py b/tests/support.py index 91fc915..bb3592e 100644 --- a/tests/support.py +++ b/tests/support.py @@ -12,15 +12,15 @@ VENDOR = tomllib.loads((ROOT / 'computer-mcp-plugin.toml').read_text())['id'] class Client: - def __init__(self, directory, environment=None, command=None): + def __init__(self, directory, environment=None, command=None, pass_fds=()): env = dict(os.environ) if command is None else {} 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) + 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,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':'2025-06-18','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..0ce5bc9 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -62,16 +62,78 @@ 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_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_declarations.py b/tests/test_declarations.py new file mode 100644 index 0000000..69004c5 --- /dev/null +++ b/tests/test_declarations.py @@ -0,0 +1,30 @@ +import tempfile +import tomllib +import unittest +from support import Client, 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): + (ROOT / '.agent/host6').mkdir(parents=True, exist_ok=True) + manifest = tomllib.loads((ROOT / 'computer-mcp-plugin.toml').read_text()) + self.assertEqual(manifest['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.'}]) + self.assertNotIn('sandbox', manifest) + 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(dir=ROOT / '.agent/host6') 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']) + +if __name__ == '__main__': unittest.main() diff --git a/tests/test_host_source.py b/tests/test_host_source.py new file mode 100644 index 0000000..fbe171f --- /dev/null +++ b/tests/test_host_source.py @@ -0,0 +1,106 @@ +"""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().parent.parent +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): + @classmethod + def setUpClass(cls): + (ROOT / '.agent/host6').mkdir(parents=True, exist_ok=True) + + 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_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_ignored_run_outputs(self): + host = Path('/separate/host') + with self.assertRaises(ValueError): driver.validate_locations(host, ROOT, ROOT / 'output') + with self.assertRaises(ValueError): driver.validate_locations(ROOT, ROOT, ROOT / '.agent/host6/run') + driver.validate_locations(host, ROOT, ROOT / '.agent/host6/not-created') + + def test_snapshot_rejects_links_and_path_escape(self): + for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)): + with tempfile.TemporaryDirectory(dir=ROOT / '.agent/host6') 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(dir=ROOT / '.agent/host6') as temp: + output = Path(temp) / 'run' + args = SimpleNamespace(host_source=Path('/separate/host'), plugin_source=ROOT, suite='source', + 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): + self.assertEqual(cwd, output / 'host-source') + self.assertEqual(command[-1], 'CursorSourceIntegrationTests/sourceConsumer') + self.assertTrue((cwd / 'Tests/ComputerMCPMacOSTests' / driver.FIXTURE).is_file()) + self.assertEqual(environment['COMPUTER_MCP_CURSOR_PLUGIN'], str(output / 'plugin-source')) + (output / 'build').mkdir() + Path(environment['COMPUTER_MCP_CURSOR_CASES']).write_text(json.dumps({ + 'kind': 'deterministic', 'run_id': environment['COMPUTER_MCP_CURSOR_RUN_ID'], + 'tests_executed': 1, 'cases': sorted(driver.CASES)})) + with patch.object(driver, 'verify_source'), patch.object(driver, 'export_source', side_effect=export), patch.object(driver, 'run_process', side_effect=execute): + driver.run(args) + receipt = json.loads((output / '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']) + for name in ('host-source', 'plugin-source', 'build'): self.assertFalse((output / name).exists()) + + def test_bounded_command_failure_and_timeout(self): + with tempfile.TemporaryDirectory(dir=ROOT / '.agent/host6') 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/test_managed_adapter.py b/tests/test_managed_adapter.py new file mode 100644 index 0000000..bcc53d2 --- /dev/null +++ b/tests/test_managed_adapter.py @@ -0,0 +1,248 @@ +"""Exercise the packaged Cursor adapter on its private carrier and ordinary MCP.""" + +import base64 +import io +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 +import zipfile + +from support import Client, ROOT +from test_package import builder + +CAPABILITY = 'io.github.computer-mcp/vendor-execution-v1' +METADATA = 'io.github.computer-mcp/work-invocation' +PEER = ROOT / 'tests/Fixtures/vendor.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): + self.socket, self.adapter_socket = socket.socketpair() + self.home = home + self.answer_error = answer_error + self.thread = threading.Thread(target=self.serve, daemon=True) + self.vendor = None + self.turn = None + self.answers = [] + self.retirements = 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'], 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.vendor = subprocess.Popen( + [sys.executable, str(PEER), 'acp'], cwd=self.home, + env={'HOME': str(self.home), 'CURSOR_SOURCE_FIXTURE': '1'}, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + elif op == 'read': + if self.vendor is None: + return {'error': 'vendor_effect_stale'} + 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'] + if kind == 'answer' and self.answer_error == REFUSAL: + return {'error': REFUSAL} + if kind in ('answer', 'housekeeping'): + self.answers.append(message) + 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': + result = {'turn': self.turn, 'dispatched': True, 'sent': False} + elif op == 'retire': + self.retire() + self.retirements += 1 + result = {'retired': True, 'probe_settled': True, 'workload_settled': True} + 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): + @classmethod + def setUpClass(cls): + stage = tempfile.TemporaryDirectory() + cls.addClassCleanup(stage.cleanup) + cls.root = Path(stage.name) + with zipfile.ZipFile(io.BytesIO(builder.package_bytes(ROOT)[0])) as archive: + archive.extractall(cls.root) + cls.adapter = cls.root / 'bin/cursor-mcp-adapter' + + def setUp(self): + self.home = Path(self.enterContext(tempfile.TemporaryDirectory())) + + def managed(self, answer_error): + host = VendorFixture(self.home, answer_error) + 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:]])' + ) + client = Client(self.home, { + 'COMPUTER_MCP_HOST_CONTEXT': CAPABILITY, 'COMPUTER_MCP_HOST_FD': '3', + }, [sys.executable, '-B', '-c', bootstrap, str(fd), str(self.adapter), + '--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_standalone_and_missing_managed_negotiation(self): + environment = {'HOME': str(self.home), 'PATH': os.environ['PATH'], '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()) + client = Client(self.home, environment, [sys.executable, '-B', str(self.adapter)]) + self.addCleanup(client.close) + self.assertNotIn('experimental', client.initialization['result']['capabilities']) + result = self.value(client.call('cursor.acp.prompt', {'prompt': 'hello'})) + self.assertEqual(result['stop_reason'], 'end_turn') + self.assertEqual(result['text'], 'hello') + self.assertTrue(result['closed']) diff --git a/tests/test_package.py b/tests/test_package.py index c43c5f6..0dff832 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -27,6 +27,23 @@ 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', + 'acquire': ['cursor.acp.session.open', 'cursor.acp.prompt'], + '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')) + for name in ('cursor-vendor-execution.json', 'bin/cursor_vendor_execution.py', + 'bin/plugin_runtime.py', acp['executable']['path']): + self.assertEqual(archive.read(name), (ROOT / name).read_bytes()) 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: From 525e829f6bb9129a56e8c608e5827d2edf450c27 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:50:17 +0800 Subject: [PATCH 02/29] test: verify managed Cursor lifecycle through installed package --- computer-mcp-plugin.toml | 11 + cursor-vendor-execution.json | 23 +- scripts/validate_host_source.py | 27 +- .../CursorSourceIntegrationTests.swift.txt | 1227 +++++++++-------- tests/Fixtures/vendor.py | 6 + tests/Fixtures/vendor_start_transport.py | 172 +++ tests/test_managed_adapter.py | 49 +- tests/test_package.py | 29 +- 8 files changed, 946 insertions(+), 598 deletions(-) create mode 100644 tests/Fixtures/vendor_start_transport.py diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index 88b83ce..d37699a 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -37,6 +37,17 @@ 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" = "451c89ad1cd2301a1d897710fbbbdd15e98e68d87769d8146bf1a4f8729cb924" +"bin/cursor_vendor_execution.py" = "27478badaaf35e9c2499efdb4858ebeae048e7117b7d07377452b5d7e52bd2b3" +"bin/plugin_runtime.py" = "5a9f797bfca4b6ab31a9a648017fb1d09400593a9aab0d2250d426efa51f97cf" +"cli-tree.json" = "cc52c0bc7662f93d8596f715625d2ed274d05d95c681bac4d32c0faf273b64a3" +"cursor-vendor-execution.json" = "b50a088d4db85f42f2c4b9bd78fd26ee8b84e3009bdec0867beb60df2c738d2f" + [[skills]] id = "cursor-agent" path = "skills/cursor-agent" diff --git a/cursor-vendor-execution.json b/cursor-vendor-execution.json index 91e54da..e9e44a4 100644 --- a/cursor-vendor-execution.json +++ b/cursor-vendor-execution.json @@ -1,8 +1,25 @@ { "capability": "io.github.computer-mcp/vendor-execution-v1", "dependency": "cursor-agent", - "acquire": ["cursor.acp.session.open", "cursor.acp.prompt"], - "probe": ["--version"], - "workload": ["acp"], + "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/scripts/validate_host_source.py b/scripts/validate_host_source.py index 4fe8fce..4ef3e5c 100644 --- a/scripts/validate_host_source.py +++ b/scripts/validate_host_source.py @@ -34,7 +34,8 @@ } INPUTS = ( "computer-mcp-plugin.toml", "tests/Fixtures/" + FIXTURE + ".txt", - "tests/Fixtures/vendor.py", "scripts/validate_host_source.py", + "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", ) @@ -197,28 +198,32 @@ def validate_startup_cancellation(evidence): def validate_start_recovery(lost, closure): - for record in (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") - phases = [record.get(key) for key in ("acquisition", "execution", "probe", "workload")] + 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 phases) or len(set(phases)) != len(phases) + 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("charged_at_lookup") is not True - or lost.get("charged_after_retirement") is not False + 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") - if (type(closure.get("workload_starts")) is not int or closure["workload_starts"] != 0 - or closure.get("probe_state") != "retired" - or closure.get("workload_state") != "never_dispatched" - or closure.get("result") != "outcome_unknown" or closure.get("cleanup") != "confirmed"): - raise ValueError("Private channel closure did not confirm pending start cleanup") + 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 run(args): diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index 5c5db29..dd3632e 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -1,5 +1,6 @@ import ComputerMCPMacOS import ComputerMCPPermissions +import ComputerMCPSandbox import ComputerMCPTestSupport import Foundation import Testing @@ -30,13 +31,13 @@ struct CursorSourceIntegrationTests { for (caller, provider) in [(1, true), (2, false)] { try await withCursor(package, caller: caller, provider: provider) { h in try await h.discover() - let before = h.base.observations.launches.count + let before = 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.base.observations.launches.count == before) + try #require(h.base.observations.members.count == before) print( "Cursor gate denial preserved (caller write: \(caller == 2), provider write: \(provider))" ) @@ -45,41 +46,29 @@ struct CursorSourceIntegrationTests { var measured: [[String: Any]] = [] try await withCursor(package) { h in - func providerLaunches() -> [ExecutionObservations.Launch] { - h.base.observations.launches.filter { $0.executable != h.base.platform.gitExecutable } - } try await h.discover() - let cold = providerLaunches().count + let baseline = h.base.observations.members.count let a = try await h.open() - let warm = providerLaunches().count + let warm = h.base.observations.members.count let b = try await h.open() - let launches = providerLaunches() - let first = Array(launches.dropFirst(cold).prefix(warm - cold)) - let second = Array(launches.dropFirst(warm)) - try #require(first.count == 3, "\(first)") - try #require(second.count == 2, "\(second)") - let adapter = try #require(first.first) - try #require(adapter.arguments.last == "--host-vendor-execution") - try #require(first.dropFirst().map(\.arguments) == [["--version"], ["acp"]]) - try #require(second.map(\.arguments) == [["--version"], ["acp"]]) - let allLaunchesSandboxed = (first + second).allSatisfy { $0.sandboxed } - try #require(allLaunchesSandboxed) + 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) } + let launches = Array(h.base.observations.members.dropFirst(baseline)) + try #require(Set(launches.suffix(from: warm - baseline)) == Set(roots.suffix(2))) + let adapter = try #require(Set(launches).subtracting(roots).first) + try #require(Set(launches) == Set(roots + [adapter])) + try #require(launches.count == 5) measured = try h.verifyAcquisitions( - first: Array(first.dropFirst()), second: second, adapterPID: adapter.member.processID) - let aPID = try #require(first.last?.member.processID) - let bPID = try #require(second.last?.member.processID) - print("Cursor gate acquired A \(aPID) and B \(bPID) in adapter \(adapter.member.processID)") - print( - "Cursor gate binaries \(adapter.executable) / \(first[1].executable) / \(second[0].executable)" - ) - let aOwner = try #require( - h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == aPID - }) - let bOwner = try #require( - h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == bPID - }) + first: Array(roots.prefix(2)), second: Array(roots.suffix(2)), adapter: adapter) + 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)") let noFD = try cursorValue(try await h.prompt(a, "env")) try #require(noFD["text"] == .string("[]")) let outside = String( @@ -184,7 +173,7 @@ struct CursorSourceIntegrationTests { started: isolationStarted) if !siblingAlive { let adapterOwner = h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == adapter.member.processID + (try? $0.recoveryState().root.processID) == adapter.processID } let adapterMembers = try? await adapterOwner?.members() h.reportIsolation( @@ -218,11 +207,7 @@ struct CursorSourceIntegrationTests { 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"]) - let freshB = "fresh B prompt after A retirement" - let freshReply = try cursorValue(try await h.prompt(b, freshB)) - try #require(freshReply["session"] == .string(b)) - try #require(freshReply["stop_reason"] == .string("end_turn")) - try await h.waitVendorPrompt(pid: bPID, prompt: freshB) + 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) @@ -237,23 +222,21 @@ struct CursorSourceIntegrationTests { $0["pid"]?.intValue == Int(bPID) && $0["phase"]?.stringValue == "cancel" }.count == 1) try #require(try h.nativeStarts == 2) - try #require(providerLaunches().count == launches.count) + try #require(h.base.observations.members.count == baseline + launches.count) _ = try cursorValue( try await h.call("cursor.acp.session.close", ["session": .string(b)])) try #require(try await bOwner.members().isEmpty) } let evidence = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_CASES"])) - var cases = [ + 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", ] var details: [String: Any] = ["acquisitions": measured] - #if DEBUG - details["startup_cancellation"] = try await registeredStartupCancellation(package) - details["lost_start_reply"] = try await registeredLostStartReply(package) - details["pending_start_closure"] = try await registeredPendingStartClosure(package) - cases += ["startup-cancellation", "lost-start-reply", "pending-start-closure"] - #endif + details["startup_cancellation"] = try await registeredStartupCancellation(package) + details["lost_start_reply"] = try await registeredLostStartReply(package) + details["pending_start_closure"] = try await registeredPendingStartClosure(package) details["kind"] = "deterministic" details["tests_executed"] = 1 let runID = try #require(env["COMPUTER_MCP_CURSOR_RUN_ID"]) @@ -262,376 +245,295 @@ struct CursorSourceIntegrationTests { try JSONSerialization.data(withJSONObject: details).write(to: evidence, options: .atomic) } - #if DEBUG - private func registeredStartupCancellation(_ package: PluginPackage) async throws - -> [String: Any] - { - var evidence: [String: Any] = [:] - try await withCursor(package) { h in + private func registeredStartupCancellation(_ package: PluginPackage) async throws + -> [String: Any] + { + var evidence: [String: Any] = [:] + for withdraw in [false, true] { + try await withCursor(package, observeStartup: true) { h in try await h.discover() - // Discovery and delegated execution use separate pool authority. - let executionBaseline = h.vendorLaunches.count let b = try await h.open() - let launches = Array(h.vendorLaunches.dropFirst(executionBaseline)) - try #require(launches.count == 3) - try #require(launches.dropFirst().map(\.arguments) == [["--version"], ["acp"]]) - let bPID = try #require(launches.last?.member.processID) - let adapter = try #require(launches.first) - try #require(adapter.arguments.last == "--host-vendor-execution") - let adapterPID = adapter.member.processID - let bOwner = try #require( - h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == bPID - }) + let bRoot = try h.lastWorkload() let bPrompt = "complete-on-cancel" - let bRequest = "startup-sibling" + let bRequestID = "startup-sibling" let bStarted = try cursorValue( try await h.call( "cursor.acp.session.prompt", ["session": .string(b), "prompt": .string(bPrompt)], - startRequestID: bRequest)) + startRequestID: bRequestID)) try #require(bStarted["state"] == .string("running")) let bDownstream = try #require(bStarted["downstream_request_id"]) - try await h.waitVendorPrompt(pid: bPID, prompt: bPrompt) - let bPending = try h.vendorTurn(pid: bPID, prompt: bPrompt) - try #require(bPending.map { $0["phase"]?.stringValue } == ["prompt"]) - let bNative = try #require(bPending.first?["acp_id"]) - - for withdraw in [false, true] { - let requestID = withdraw ? "startup-withdraw" : "startup-control" - let gate = CursorStartupBarrier() - let launchCount = h.vendorLaunches.count - let startCount = try h.nativeStarts - try await h.withStartupBarrier(gate) { - let started = try cursorValue( - try await h.call( - "cursor.acp.session.open", ["permission_policy": .string("manual")], - startRequestID: requestID)) - try #require(started["request_id"] == .string(requestID)) - try #require(started["state"] == .string("running")) - let downstream = try #require(started["downstream_request_id"]?.stringValue) - let boundary = try await gate.wait() - let initialReceipts = boundary.receipts() - try #require(initialReceipts.probe == "retired") - try #require(initialReceipts.workload == "pending") - let before = try h.startupChildren(boundary) - let probePID = try #require(before.probe.recovery?.root.processID) - try #require(before.probe.completed) - try #require(before.workload.recovery == nil && !before.workload.completed) - let atBoundary = Array(h.vendorLaunches.dropFirst(launchCount)) - try #require(atBoundary.map(\.arguments) == [["--version"]]) - try #require(atBoundary.first?.member.processID == probePID) - try #require(atBoundary.first?.sandboxed == true) - var trial: [String: Any] = [ - "acquisition": boundary.acquisitionID.uuidString, - "execution": boundary.executionID.uuidString, - "probe": boundary.probeID.uuidString, - "workload": boundary.workloadID.uuidString, - "probe_pid": Int(probePID), - "probe_state": initialReceipts.probe, - "request_id": requestID, - "downstream_request_id": downstream, - ] - - if withdraw { - let cancellation = try cursorValue( - try await h.gateway.callToolForMCPAsync( - name: "mcp.requests.cancel", - arguments: .object([ - "server": .string("cursor-fixture"), "request_id": .string(requestID), - ]), context: .empty)) - try #require(cancellation["cancellation_requested"] == .bool(true)) - try #require(cancellation["request_id"] == .string(requestID)) - let sealed = try h.startupChildren(boundary) - let receipts = boundary.receipts() - try #require(receipts.probe == "retired") - try #require(receipts.workload == "never_dispatched") - try #require(sealed.probe.completed) - try #require(sealed.probe.recovery?.root.processID == probePID) - try #require(sealed.workload.completed && sealed.workload.recovery == nil) - try #require(h.vendorLaunches.count == launchCount + 1) - trial["workload_state"] = receipts.workload - print("Cursor startup sealed \(boundary.acquisitionID) before workload bootstrap") - } + 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.base.observations.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 #require(Array(h.base.observations.members.dropFirst(before)) == [probeRoot]) + try h.requirePeerEvidence(probeRoot, phase: "probe") - gate.release() - let receipt = try await h.waitRequestReceipt(requestID) - try #require(receipt["request_id"] == .string(requestID)) - try #require(receipt["downstream_request_id"] == .string(downstream)) - let reply = try #require(receipt["result"]) - if withdraw { - try #require(receipt["state"] == .string("failed"), "\(receipt)") - try #require(receipt["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 #require(h.vendorLaunches.count == launchCount + 1) - try #require(try h.nativeStarts == startCount) - trial["workload_starts"] = 0 - trial["result"] = "cancelled" - } else { - try #require(receipt["state"] == .string("succeeded"), "\(receipt)") - let opened = try cursorValue(reply) - let session = try #require(opened["session"]?.stringValue) - let live = try h.startupChildren(boundary) - let workloadPID = try #require(live.workload.recovery?.root.processID) - try #require(!live.workload.completed) - let launches = Array(h.vendorLaunches.dropFirst(launchCount)) - try #require(launches.map(\.arguments) == [["--version"], ["acp"]]) - try #require(launches.last?.member.processID == workloadPID) - try #require(launches.last?.sandboxed == true) - try #require(try h.nativeStarts == startCount + 1) - let owner = try #require( - h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == workloadPID - }) - _ = try cursorValue( - try await h.call("cursor.acp.session.close", ["session": .string(session)])) - try #require(try await owner.members().isEmpty) - trial["workload_pid"] = Int(workloadPID) - trial["workload_starts"] = 1 - trial["result"] = "opened" - print("Cursor startup control \(boundary.acquisitionID) launched \(workloadPID)") - } - evidence[withdraw ? "cancelled" : "control"] = trial - } + 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.gateway.callToolForMCPAsync( + 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 #require(try await bOwner.members().contains(where: { $0.processID == bPID })) - let stillPending = try h.vendorTurn(pid: bPID, prompt: bPrompt) - try #require(stillPending.map { $0["phase"]?.stringValue } == ["prompt"]) - try #require(stillPending.first?["acp_id"] == bNative) - let stop = try cursorValue(try await h.stop(b)) - try #require(stop["cancel_requested"] == .bool(true)) - let completed = try await h.waitRequestReceipt(bRequest) - try #require(completed["state"] == .string("succeeded"), "\(completed)") - try #require(completed["downstream_request_id"] == bDownstream) - let result = try cursorValue(try #require(completed["result"])) + 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 #require(Array(h.base.observations.members.dropFirst(before)) == [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) + 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 #require(Array(h.base.observations.members.dropFirst(before)) == [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( - result["session"] == .string(b) && result["stop_reason"] == .string("end_turn")) - let settled = try h.vendorTurn(pid: bPID, prompt: bPrompt) - try #require(settled.map { $0["phase"]?.stringValue } == ["prompt", "cancel", "terminal"]) - try #require(settled.last?["acp_id"] == bNative) - try #require(settled.last?["outcome"]?.objectValue?["result"] == result["native_result"]) - let fresh = "fresh B after startup cancellation" - let reply = try cursorValue(try await h.prompt(b, fresh)) - try #require(reply["session"] == .string(b) && reply["stop_reason"] == .string("end_turn")) - try await h.waitVendorPrompt(pid: bPID, prompt: fresh) - let freshTurn = try h.vendorTurn(pid: bPID, prompt: fresh) - let freshID = try #require(freshTurn.first?["acp_id"]?.intValue) - let originalID = try #require(bNative.intValue) - try #require(freshID > originalID) + 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) - let adapters = h.vendorLaunches.dropFirst(executionBaseline).filter { - $0.arguments.last == "--host-vendor-execution" - } - try #require(adapters.map(\.member.processID) == [adapterPID]) - evidence["sibling_pid"] = Int(bPID) - evidence["adapter_pid"] = Int(adapterPID) + evidence[withdraw ? "cancelled" : "control"] = trial } - return evidence } + return evidence + } - private func registeredLostStartReply(_ package: PluginPackage) async throws -> [String: Any] { - var evidence: [String: Any] = [:] - try await withCursor(package) { h in - try await h.discover() - let b = try await h.open() - let bPID = try #require(h.vendorLaunches.last?.member.processID) - let before = h.vendorLaunches.count - let launch = CursorStartupBarrier() - let lookup = CursorStartupBarrier() - let retire = CursorStartupBarrier() - try await h.withVendorReplyObserver( - { reply in - switch reply.operation { - case .launch: - await launch.park(reply) - return true - case .receipt: - await lookup.park(reply) - return false - case .retire: - await retire.park(reply) - return false - } - }, - release: { - launch.release() - lookup.release() - retire.release() - } - ) { - let requestID = "startup-lost-reply" - let arguments: [String: JSONValue] = ["permission_policy": .string("manual")] - let started = try cursorValue( - try await h.call("cursor.acp.session.open", arguments, startRequestID: requestID)) - try #require(started["state"] == .string("running")) - try #require(started["request_id"] == .string(requestID)) - let downstream = try #require(started["downstream_request_id"]?.stringValue) - let withheld = try await launch.wait() - let boundary = withheld.boundary - let probeID = JSONValue.string(boundary.probeID.uuidString.lowercased()) - let workloadID = JSONValue.string(boundary.workloadID.uuidString.lowercased()) - let pid = try await h.waitForNewWorkload(since: before) - let live = try h.startupChildren(boundary) - let member = try #require(live.workload.recovery?.root) - try #require(member.processID == pid) - try #require(withheld.requestedWorkloadID == boundary.workloadID) - let durable = try h.workloadJournal(boundary) - try #require(durable.recovery.root == member && !durable.completed) - try #require(withheld.charged) - print("Cursor startup reply dropped for \(boundary.workloadID) after peer \(pid) started") - launch.release() - - let recovered = try await lookup.wait(timeout: .seconds(15)) - try #require(recovered.boundary.acquisitionID == boundary.acquisitionID) - try #require(recovered.boundary.executionID == boundary.executionID) - try #require(recovered.requestedWorkloadID == boundary.workloadID) - try #require(recovered.payload["probe"] == probeID) - try #require(recovered.payload["workload"] == workloadID) - try #require(recovered.payload["probe_state"] == .string("retired")) - try #require(recovered.payload["workload_state"] == .string("pending")) - try #require(recovered.payload["retired"] == .bool(false)) - try #require(recovered.charged) - print("Cursor startup lookup recovered \(boundary.workloadID) while still charged") - let pending = try h.workloadJournal(boundary) - try #require(pending.recovery.root == member && !pending.completed) - let during = "B while A start receipt is pending" - let bReply = try cursorValue(try await h.prompt(b, during)) - try #require( - bReply["session"] == .string(b) && bReply["stop_reason"] == .string("end_turn")) - try await h.waitVendorPrompt(pid: bPID, prompt: during) - lookup.release() - - let settled = try await retire.wait() - try #require(settled.boundary.acquisitionID == boundary.acquisitionID) - try #require(settled.requestedWorkloadID == boundary.workloadID) - try #require(settled.payload["probe"] == probeID) - try #require(settled.payload["workload"] == workloadID) - try #require(settled.payload["workload_state"] == .string("retired")) - try #require(settled.payload["retired"] == .bool(true) && !settled.charged) - let complete = try h.workloadJournal(boundary) - try #require(complete.completed && complete.recovery.root == member) - let owner = try #require( - h.base.observations.ownerships.first { - (try? $0.recoveryState().root) == member - }) - try #require(try await owner.members().isEmpty) - print("Cursor startup retired \(boundary.workloadID) and released its capacity") - retire.release() + private func registeredLostStartReply(_ package: PluginPackage) async throws -> [String: Any] { + var evidence: [String: Any] = [:] + try await withCursor(package, observeStartup: true) { h in + try await h.discover() + let b = try await h.open() + let bRoot = try h.lastWorkload() + let before = h.base.observations.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 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", arguments, startRequestID: requestID)) - try #require(repeated["state"] == .string("failed")) - try #require(repeated["downstream_request_id"] == .string(downstream)) - try #require(repeated["result"] == reply) - try #require(repeated["replayed"] == .bool(false)) + 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 fresh = "B after lost start reply settlement" - let bFresh = try cursorValue(try await h.prompt(b, fresh)) - try #require( - bFresh["session"] == .string(b) && bFresh["stop_reason"] == .string("end_turn")) - try await h.waitVendorPrompt(pid: bPID, prompt: fresh) - let measured = Array(h.vendorLaunches.dropFirst(before)) - try #require(measured.map(\.arguments) == [["--version"], ["acp"]]) - let peers = try h.vendorEffects().filter { $0["phase"] == .string("workload") } - try #require(peers.compactMap { $0["pid"]?.intValue } == [Int(bPID), Int(pid)]) - try #require(try h.nativeStarts == 1) - evidence = [ - "request_id": requestID, "downstream_request_id": downstream, - "acquisition": boundary.acquisitionID.uuidString, - "execution": boundary.executionID.uuidString, "probe": boundary.probeID.uuidString, - "workload": boundary.workloadID.uuidString, "workload_pid": Int(pid), - "sibling_pid": Int(bPID), "charged_at_lookup": recovered.charged, - "charged_after_retirement": settled.charged, "workload_starts": peers.count - 1, - "workload_state": "retired", "result": "timeout", - ] - } - _ = try cursorValue(try await h.call("cursor.acp.session.close", ["session": .string(b)])) - } - return evidence + 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 #require(Array(h.base.observations.members.dropFirst(before)) == [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] = [:] - try await withCursor(package) { h in + private func registeredPendingStartClosure(_ package: PluginPackage) async throws -> [String: Any] + { + var evidence: [String: Any] = [:] + for dispatched in [false, true] { + try await withCursor(package, observeStartup: true) { h in try await h.discover() _ = try await h.open() - let bPID = try #require(h.vendorLaunches.last?.member.processID) - let bOwner = try #require( - h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == bPID - }) - let before = h.vendorLaunches.count - let gate = CursorStartupBarrier() - try await h.withStartupBarrier(gate) { - let requestID = "startup-connection-closure" - let started = try cursorValue( - try await h.call( - "cursor.acp.session.open", ["permission_policy": .string("manual")], - startRequestID: requestID)) - try #require(started["state"] == .string("running")) - let downstream = try #require(started["downstream_request_id"]?.stringValue) - let boundary = try await gate.wait() - let beforeClosure = try h.startupChildren(boundary) - let probeRoot = try #require(beforeClosure.probe.recovery?.root) - try #require(beforeClosure.probe.completed && !beforeClosure.workload.completed) - try #require(beforeClosure.workload.recovery == nil) - let owner = try await h.vendorRequestOwner(requestID) - async let close = h.closeVendorConnection(owner) - do { - try await h.waitForStartupDrain(boundary) - } catch { - gate.release() - _ = try? await close - throw error + let sibling = try h.lastWorkload() + let siblingOwner = try h.processOwner(sibling) + let before = h.base.observations.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) } - gate.release() - - let result = try await close - 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)") - print("Cursor private channel close joined pending startup \(boundary.acquisitionID)") - let after = try h.startupChildren(boundary) - try #require(after.probe.completed && after.workload.completed) - try #require(after.probe.recovery?.root == probeRoot) - try #require(after.workload.recovery == nil) - try #require(try await bOwner.members().isEmpty) - let measured = Array(h.vendorLaunches.dropFirst(before)) - try #require(measured.map(\.arguments) == [["--version"]]) - 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) - evidence = [ - "request_id": requestID, "downstream_request_id": downstream, - "acquisition": boundary.acquisitionID.uuidString, - "execution": boundary.executionID.uuidString, "probe": boundary.probeID.uuidString, - "workload": boundary.workloadID.uuidString, "workload_starts": measured.count - 1, - "probe_state": boundary.receipts().probe, - "workload_state": boundary.receipts().workload, - "result": "outcome_unknown", "cleanup": "confirmed", - ] + } 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 #require(Array(h.base.observations.members.dropFirst(before)) == 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 } - #endif + return evidence + } @Test func sourceConsumer() async throws { let env = ProcessInfo.processInfo.environment @@ -914,9 +816,10 @@ private func cursorDenied(_ value: JSONValue) throws { } private func withCursor( _ package: PluginPackage, caller: Int = 2, provider: Bool = true, - use: Bool = true, body: (CursorHarness) async throws -> Void + use: Bool = true, observeStartup: Bool = false, body: (CursorHarness) async throws -> Void ) async throws { - let h = try await CursorHarness.make(package, caller: caller, provider: provider, use: use) + let h = try await CursorHarness.make( + package, caller: caller, provider: provider, use: use, observeStartup: observeStartup) do { try await body(h) } catch { do { try await h.close() } catch { Issue.record("Cursor cleanup failed: \(error)") } throw error @@ -924,41 +827,26 @@ private func withCursor( try await h.close() } -#if DEBUG - private typealias CursorStartupBoundary = CursorVendorStartupObservation.Boundary - private typealias CursorStartupReply = CursorVendorStartupObservation.Reply - - private final class CursorStartupBarrier: Sendable { - private let arrival = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) - private let permission = AsyncStream.makeStream() - - func park(_ boundary: Value) async { - arrival.continuation.yield(boundary) - arrival.continuation.finish() - var permit = permission.stream.makeAsyncIterator() - _ = await permit.next() - } +private struct CursorStartupBoundary { + let acquisitionID: UUID + let executionID: UUID + let probeID: UUID + let workloadID: UUID + let adapter: ExecutionMember +} - func wait(timeout: Duration = .seconds(10)) async throws -> Value { - try await withThrowingTaskGroup(of: Value.self) { group in - group.addTask { - var events = self.arrival.stream.makeAsyncIterator() - guard let boundary = await events.next() else { throw CursorFixtureError.deadline } - return boundary - } - group.addTask { - try await Task.sleep(for: timeout) - throw CursorFixtureError.deadline - } - defer { group.cancelAll() } - guard let boundary = try await group.next() else { throw CursorFixtureError.deadline } - return boundary - } - } +private struct CursorTransportEvent: Decodable { + let adapterPID: Int32 + let request: [String: JSONValue] + let reply: [String: JSONValue]? - func release() { permission.continuation.finish() } + enum CodingKeys: String, CodingKey { + case adapterPID = "adapter_pid" + case request, reply } -#endif + + var result: [String: JSONValue]? { reply?["result"]?.objectValue } +} private final class CursorHarness: @unchecked Sendable { let base: FixedHostFixture @@ -988,13 +876,14 @@ private final class CursorHarness: @unchecked Sendable { self.outside = outside self.owner = owner } - static func make(_ package: PluginPackage, caller: Int, provider: Bool, use: Bool) async throws - -> CursorHarness - { + static func make( + _ package: PluginPackage, caller: Int, provider: Bool, use: 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 { try await base.initializeRepository() let value = try cursorValue( @@ -1017,6 +906,19 @@ private final class CursorHarness: @unchecked Sendable { 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 """ @@ -1090,14 +992,14 @@ private final class CursorHarness: @unchecked Sendable { uniqueKeysWithValues: cursorReadTools.map { ($0, CapabilityRisk.readOnly) })) ], cli: ["agent": .init(registrationID: "cursor-cli")], - dependencyExecutables: ["cursor-agent": peer.path, "python-runtime": python]) + 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: python), + "cursor-agent": peer, "python-runtime": URL(fileURLWithPath: adapterPython), ], hostVersion: PluginVersion(ComputerMCPCLI.version), architecture: PluginHost.architecture) try #require( @@ -1118,9 +1020,12 @@ private final class CursorHarness: @unchecked Sendable { let adapterCommand = try #require(adapter.command) try #require( URL(fileURLWithPath: adapterCommand).resolvingSymlinksInPath() - == URL(fileURLWithPath: python).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( - adapter.args == [runtimePackage.root.appendingPathComponent("bin/cursor-mcp-adapter").path]) + adapterPath.resolvingSymlinksInPath() == installedAdapter.resolvingSymlinksInPath()) print( "Cursor fixture adapter launch: \(adapterCommand) \(adapter.args); native peer interpreter: \(python)" ) @@ -1135,6 +1040,7 @@ private final class CursorHarness: @unchecked Sendable { pending = h let lifecycleProfile = try #require( base.database.profiles().first { $0.id == base.configuration.runtime.profileID }) + stage = "consumer generation" h.gateway = try h.makeConsumer("cursor-consumer", caller: caller, use: use) try #require( base.database.profiles().first { $0.id == lifecycleProfile.id } == lifecycleProfile) @@ -1143,6 +1049,7 @@ private final class CursorHarness: @unchecked Sendable { 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)])) @@ -1152,22 +1059,33 @@ private final class CursorHarness: @unchecked Sendable { }) try #require(approval.enabled && approval.fullAccessConsent == nil) return h - } catch { - if let pending { - try await pending.close() - } else { - if let created { - _ = try await lifecycle.callToolForMCPAsync( - name: "git.worktree_remove", - arguments: .object(["project_id": .string(created), "force": .bool(true)]), - context: .init(session: base.session)) + } 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.callToolForMCPAsync( + 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) } - 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 error + throw setupError } } var nativeStarts: Int { @@ -1277,137 +1195,276 @@ private final class CursorHarness: @unchecked Sendable { arguments: .object(["server": .string("cursor-fixture"), "request_id": .string(id)]), context: .empty)) } - #if DEBUG - var vendorLaunches: [ExecutionObservations.Launch] { - base.observations.launches.filter { $0.executable != base.platform.gitExecutable } + func processOwner(_ member: ExecutionMember) throws -> any ExecutionOwnership { + try #require(base.observations.ownerships.first { (try? $0.recoveryState().root) == member }) + } + + func processMember(pid: Int32) throws -> ExecutionMember { + let matches = base.observations.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 requirePeerEvidence(_ root: ExecutionMember, phase: String) throws { + let matching = try vendorEffects().filter { + $0["phase"] == .string(phase) && $0["pid"] == .integer(Int64(root.processID)) } - func withStartupBarrier( - _ barrier: CursorStartupBarrier, body: () async throws -> Void - ) async throws { - let observation = CursorVendorStartupObservation.shared - await observation.set({ await barrier.park($0) }, projectID: projectID) - do { - try await body() - } catch { - barrier.release() - await observation.set(nil, projectID: projectID) - throw error + 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 } - await observation.set(nil, projectID: projectID) + 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 withVendorReplyObserver( - _ observe: @escaping @Sendable (CursorStartupReply) async -> Bool, - release: () -> Void, - body: () async throws -> Void - ) async throws { - let observation = CursorVendorStartupObservation.shared - await observation.setReplyObserver(observe, projectID: projectID) - do { - try await body() - } catch { - release() - await observation.setReplyObserver(nil, projectID: projectID) - throw error + } + + 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 } - release() - await observation.setReplyObserver(nil, projectID: projectID) + 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"]) } - 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]) + 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 (probe, workload) + return execution.id } } - func workloadJournal(_ boundary: CursorStartupBoundary) throws -> ExecutionRecoveryJournal.Entry - { - let path = base.database.permissionExecutionRoot.appendingPathComponent("ownership") - .appendingPathComponent(boundary.workloadID.uuidString + ".json") - let entry = try JSONDecoder().decode( - ExecutionRecoveryJournal.Entry.self, from: Data(contentsOf: path)) - try #require(entry.child == boundary.workloadID && entry.execution == boundary.executionID) - try #require(entry.recovery.sandboxed) - return entry - } - func waitForNewWorkload(since index: Int) async throws -> Int32 { - let deadline = ContinuousClock.now + .seconds(5) - repeat { - if let launch = vendorLaunches.dropFirst(index).first(where: { $0.arguments == ["acp"] }) { - let pid = launch.member.processID - if try vendorEffects().contains(where: { - $0["phase"] == .string("workload") && $0["pid"]?.intValue == Int(pid) - }) { - try #require(launch.sandboxed) - return pid - } - } - try await Task.sleep(for: .milliseconds(20)) - } while ContinuousClock.now < deadline - throw CursorFixtureError.deadline + 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 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 gateway.callToolForMCPAsync( - 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 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 closeVendorConnection(_ owner: (locator: JSONValue, connectionID: UUID)) async throws - -> [String: JSONValue] - { - try cursorValue( - try await gateway.callToolForMCPAsync( - 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 phaseJournal(_ child: UUID, boundary: CursorStartupBoundary) 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 == boundary.executionID) + 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 gateway.callToolForMCPAsync( + 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) } - func waitForStartupDrain(_ boundary: CursorStartupBoundary) async throws { - let deadline = ContinuousClock.now + .seconds(7) - repeat { - if await boundary.channelClosed(), boundary.receipts().workload == "never_dispatched" { - return - } - try await Task.sleep(for: .milliseconds(20)) - } while ContinuousClock.now < deadline - throw CursorFixtureError.deadline + let visible = owners.prefix(8).compactMap(\.objectValue).map { + [$0["kind"], $0["resource_id"], $0["connection_id"]] } - #endif + 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 gateway.callToolForMCPAsync( + 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 { @@ -1541,7 +1598,7 @@ private final class CursorHarness: @unchecked Sendable { } } func verifyAcquisitions( - first: [ExecutionObservations.Launch], second: [ExecutionObservations.Launch], adapterPID: Int32 + first: [ExecutionMember], second: [ExecutionMember], adapter: ExecutionMember ) throws -> [[String: Any]] { try gateway.permissionRuntime.store.readWithDatabase { database, ledger in var rows: [[String: Any]] = [] @@ -1549,7 +1606,7 @@ private final class CursorHarness: @unchecked Sendable { var proofs: Set = [] var children: Set = [] for pair in [first, second] { - let pids = Set(pair.map { $0.member.processID }) + let pids = Set(pair) var matched = false for execution in ledger.executions.values where execution.delegatedTo == .package("cursor") { @@ -1557,7 +1614,7 @@ private final class CursorHarness: @unchecked Sendable { continue } let slots = record.children.filter { _, record in - record.recovery.map { pids.contains($0.root.processID) } ?? false + record.recovery.map { pids.contains($0.root) } ?? false } guard slots.count == 2 else { continue } let newExecution = executions.insert(execution.id).inserted @@ -1574,20 +1631,27 @@ private final class CursorHarness: @unchecked Sendable { } if rows.isEmpty { try #require( - record.children.values.contains { $0.recovery?.root.processID == adapterPID }) + record.children.values.count == 3 + && record.children.values.contains { + $0.recovery?.root == adapter && $0.recovery?.sandboxed == true + }) } else { try #require(record.children.count == 2) } - let phaseIDs = try pair.map { launch in - try #require(slots.first(where: { $0.value.recovery?.root == launch.member })?.key) + let phaseIDs = try pair.map { root in + let pair = try #require(slots.first { $0.value.recovery?.root == root }) + try #require(pair.value.recovery?.sandboxed == true) + return pair.key } + try #require(slots[phaseIDs[0]]?.completed == true) + try #require(slots[phaseIDs[1]]?.completed == false) rows.append([ "execution": execution.id.uuidString, "authorization_ids": execution.authorizationIDs.map(\.uuidString).sorted(), - "adapter_pid": adapterPID, - "probe_pid": pair[0].member.processID, + "adapter_pid": adapter.processID, + "probe_pid": pair[0].processID, "probe_child": phaseIDs[0].uuidString, - "workload_pid": pair[1].member.processID, + "workload_pid": pair[1].processID, "workload_child": phaseIDs[1].uuidString, ]) } @@ -1642,7 +1706,7 @@ private final class CursorHarness: @unchecked Sendable { } func requireJoined() async throws { for _ in 0..<200 { - try await gateway.permissionRuntime.coordinator.reconcile() + try await (gateway ?? base.runtime).permissionRuntime.coordinator.reconcile() var live = false for ownership in base.observations.ownerships { if try await ownership.members().isEmpty == false { live = true } @@ -1655,12 +1719,19 @@ private final class CursorHarness: @unchecked Sendable { func close() async throws { await gateway?.shutdown() await other?.shutdown() - if !removed { try await removeWorktree() } - try await requireJoined() - try await base.requireNoScratch() + 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)) } diff --git a/tests/Fixtures/vendor.py b/tests/Fixtures/vendor.py index ba7d912..c7b90a2 100755 --- a/tests/Fixtures/vendor.py +++ b/tests/Fixtures/vendor.py @@ -101,6 +101,12 @@ def finish(identifier,reason='end_turn'):reply(identifier,{'stopReason':reason}) 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) 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/test_managed_adapter.py b/tests/test_managed_adapter.py index bcc53d2..01f3391 100644 --- a/tests/test_managed_adapter.py +++ b/tests/test_managed_adapter.py @@ -22,6 +22,7 @@ CAPABILITY = 'io.github.computer-mcp/vendor-execution-v1' METADATA = 'io.github.computer-mcp/work-invocation' PEER = ROOT / 'tests/Fixtures/vendor.py' +START_TRANSPORT = ROOT / 'tests/Fixtures/vendor_start_transport.py' REFUSAL = 'vendor_effect_denied' @@ -37,6 +38,7 @@ def __init__(self, home, answer_error): self.turn = None self.answers = [] self.retirements = 0 + self.launches = 0 self.error = None self.thread.start() @@ -69,6 +71,7 @@ def respond(self, request): 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={'HOME': str(self.home), 'CURSOR_SOURCE_FIXTURE': '1'}, @@ -97,6 +100,8 @@ def respond(self, request): return {'error': self.answer_error} elif op == 'stop': result = {'turn': self.turn, 'dispatched': True, 'sent': False} + elif op == 'receipt': + result = {'retired': self.vendor is None, 'probe': 'probe', 'workload': 'workload'} elif op == 'retire': self.retire() self.retirements += 1 @@ -144,7 +149,7 @@ def setUpClass(cls): def setUp(self): self.home = Path(self.enterContext(tempfile.TemporaryDirectory())) - def managed(self, answer_error): + def managed(self, answer_error, *, transport=False): host = VendorFixture(self.home, answer_error) self.addCleanup(host.close) fd = host.adapter_socket.fileno() @@ -153,10 +158,12 @@ def managed(self, answer_error): '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', - }, [sys.executable, '-B', '-c', bootstrap, str(fd), str(self.adapter), - '--host-vendor-execution'], pass_fds=(fd,)) + '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) @@ -231,6 +238,42 @@ def test_unknown_answer_delivery_retires_without_replaying_answer(self): 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_packaged_standalone_and_missing_managed_negotiation(self): environment = {'HOME': str(self.home), 'PATH': os.environ['PATH'], 'CURSOR_SOURCE_FIXTURE': '1'} missing = subprocess.run( diff --git a/tests/test_package.py b/tests/test_package.py index 0dff832..10fea82 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -1,3 +1,4 @@ +import hashlib import importlib.util import io import json @@ -32,7 +33,20 @@ def test_reproducible_archive_and_executable_mode(self): self.assertEqual(signature, { 'capability': 'io.github.computer-mcp/vendor-execution-v1', 'dependency': 'cursor-agent', - 'acquire': ['cursor.acp.session.open', 'cursor.acp.prompt'], + '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'] @@ -41,9 +55,18 @@ def test_reproducible_archive_and_executable_mode(self): self.assertIn(signature['dependency'], {dependency['id'] for dependency in manifest['dependencies']}) [acp] = manifest['mcp'] self.assertEqual((acp['id'], acp['transport']), ('acp', 'stdio')) - for name in ('cursor-vendor-execution.json', 'bin/cursor_vendor_execution.py', - 'bin/plugin_runtime.py', acp['executable']['path']): + 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: From 576afc1fa7c180b4173d3f4c86ae55af00d33eb4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:16:53 +0800 Subject: [PATCH 03/29] test: verify registered adapter launch ownership --- scripts/validate_host_source.py | 36 +++- .../CursorSourceIntegrationTests.swift.txt | 161 ++++++++++++------ tests/test_host_source.py | 23 +++ 3 files changed, 162 insertions(+), 58 deletions(-) diff --git a/scripts/validate_host_source.py b/scripts/validate_host_source.py index 4ef3e5c..a339097 100644 --- a/scripts/validate_host_source.py +++ b/scripts/validate_host_source.py @@ -174,6 +174,39 @@ def validate_evidence(observed, run_id, expected_cases=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_startup_cancellation(evidence): if not isinstance(evidence, dict): raise ValueError("Host did not record startup cancellation") @@ -284,8 +317,7 @@ def run(args): validate_evidence(observed, run_id, VENDOR_CASES if suite == "vendor-stop" else CASES) if suite == "vendor-stop": acquisitions = observed.get("acquisitions") - if not isinstance(acquisitions, list) or len(acquisitions) != 2: - raise ValueError("Host did not record the two acquired vendor workloads") + validate_acquisitions(acquisitions) result["acquisitions"] = acquisitions result["startup_cancellation"] = observed.get("startup_cancellation") validate_startup_cancellation(result["startup_cancellation"]) diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index dd3632e..886fd87 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -1,3 +1,4 @@ +import ComputerMCPDarwinTestSupport import ComputerMCPMacOS import ComputerMCPPermissions import ComputerMCPSandbox @@ -31,13 +32,15 @@ struct CursorSourceIntegrationTests { for (caller, provider) in [(1, true), (2, false)] { try await withCursor(package, caller: caller, provider: provider) { h in try await h.discover() - let before = h.base.observations.members.count + 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.base.observations.members.count == before) + 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))" ) @@ -47,21 +50,29 @@ struct CursorSourceIntegrationTests { var measured: [[String: Any]] = [] try await withCursor(package) { h in try await h.discover() - let baseline = h.base.observations.members.count + let baseline = h.mcpObservations.members.count + let hostBaseline = h.base.observations.members.count let a = try await h.open() - let warm = h.base.observations.members.count + let warm = h.mcpObservations.members.count let b = try await h.open() 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) } - let launches = Array(h.base.observations.members.dropFirst(baseline)) - try #require(Set(launches.suffix(from: warm - baseline)) == Set(roots.suffix(2))) - let adapter = try #require(Set(launches).subtracting(roots).first) - try #require(Set(launches) == Set(roots + [adapter])) - try #require(launches.count == 5) - measured = try h.verifyAcquisitions( - first: Array(roots.prefix(2)), second: Array(roots.suffix(2)), adapter: adapter) + 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 @@ -172,9 +183,7 @@ struct CursorSourceIntegrationTests { "A settled; A members \(aMembers.map(\.processID)), B members \(bMembers.map(\.processID))", started: isolationStarted) if !siblingAlive { - let adapterOwner = h.base.observations.ownerships.first { - (try? $0.recoveryState().root.processID) == adapter.processID - } + let adapterOwner = try? h.processOwner(adapter) let adapterMembers = try? await adapterOwner?.members() h.reportIsolation( "adapter members \(adapterMembers?.map(\.processID) ?? [])", @@ -222,7 +231,7 @@ struct CursorSourceIntegrationTests { $0["pid"]?.intValue == Int(bPID) && $0["phase"]?.stringValue == "cancel" }.count == 1) try #require(try h.nativeStarts == 2) - try #require(h.base.observations.members.count == baseline + launches.count) + 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) @@ -266,7 +275,7 @@ struct CursorSourceIntegrationTests { 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.base.observations.members.count + let before = h.mcpObservations.members.count let startCount = try h.nativeStarts try h.armStartupFault("hold-launch") let started = try await h.startOpen(requestID) @@ -277,7 +286,7 @@ struct CursorSourceIntegrationTests { 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 #require(Array(h.base.observations.members.dropFirst(before)) == [probeRoot]) + try h.requireMCPLaunches(since: before, exactly: [probeRoot]) try h.requirePeerEvidence(probeRoot, phase: "probe") var trial = h.startupEvidence(boundary, requestID: requestID, downstream: downstream) @@ -308,7 +317,7 @@ struct CursorSourceIntegrationTests { let payload = reply.objectValue?["structuredContent"]?.objectValue?["result"] try #require(payload?.objectValue?["error"]?.objectValue?["code"] == .string("cancelled")) try await h.requireNeverLaunched(boundary, probe: probeRoot) - try #require(Array(h.base.observations.members.dropFirst(before)) == [probeRoot]) + try h.requireMCPLaunches(since: before, exactly: [probeRoot]) try #require(try h.nativeStarts == startCount) trial["workload_state"] = "never_dispatched" trial["workload_starts"] = 0 @@ -325,7 +334,7 @@ struct CursorSourceIntegrationTests { 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 #require(Array(h.base.observations.members.dropFirst(before)) == [probeRoot, root]) + try h.requireMCPLaunches(since: before, exactly: [probeRoot, root]) try h.requirePeerEvidence(root, phase: "workload") try #require(try h.nativeStarts == startCount + 1) _ = try cursorValue( @@ -371,7 +380,7 @@ struct CursorSourceIntegrationTests { try await h.discover() let b = try await h.open() let bRoot = try h.lastWorkload() - let before = h.base.observations.members.count + let before = h.mcpObservations.members.count try h.armStartupFault("lose-reply") let requestID = "startup-lost-reply" let started = try await h.startOpen(requestID) @@ -437,7 +446,7 @@ struct CursorSourceIntegrationTests { 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 #require(Array(h.base.observations.members.dropFirst(before)) == [probe, root]) + 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)]) @@ -464,7 +473,7 @@ struct CursorSourceIntegrationTests { _ = try await h.open() let sibling = try h.lastWorkload() let siblingOwner = try h.processOwner(sibling) - let before = h.base.observations.members.count + 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" @@ -517,7 +526,7 @@ struct CursorSourceIntegrationTests { try #require(try await siblingOwner.members().isEmpty) let adapter = try h.processOwner(boundary.adapter) try #require(try await adapter.members().isEmpty) - try #require(Array(h.base.observations.members.dropFirst(before)) == roots) + 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")) @@ -723,7 +732,7 @@ struct CursorSourceIntegrationTests { try #require(cancelled["is_error"] == .bool(true)) try #require(try h.nativeStarts == nativeStarts) // Client B uses a separate authority and kill domain in the same provider container. - let firstOwnerships = h.base.observations.ownerships + let firstOwnerships = h.mcpObservations.ownerships var retained = false for ownership in firstOwnerships { if try await ownership.members().isEmpty == false { retained = true } @@ -850,6 +859,9 @@ private struct CursorTransportEvent: Decodable { 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 @@ -1045,6 +1057,7 @@ private final class CursorHarness: @unchecked Sendable { 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) } @@ -1115,7 +1128,9 @@ private final class CursorHarness: @unchecked Sendable { context: .init( caller: .localMCP, profileID: id, projectID: projectID, trustedPrincipalID: name), database: base.database, registeredProjects: base.database.projects(), - platform: base.platform, plugins: [plugin], bundledPlugins: .init(packages: [], issues: [])) + platform: base.platform, + mcpClient: MCPProxyClient(launcher: testExecutionLauncher(observations: mcpObservations)), + plugins: [plugin], bundledPlugins: .init(packages: [], issues: [])) _ = try gateway.makeControlSession() return gateway } @@ -1125,10 +1140,11 @@ private final class CursorHarness: @unchecked Sendable { context: .empty) } func discover(gateway selected: GatewayRuntime? = nil) async throws { - let firstOwnership = base.observations.ownerships.count + let firstOwnership = mcpObservations.ownerships.count let result = try await catalog(gateway: selected) if result.objectValue?["isError"] == .bool(true) { - await reportLaunchFailure(since: firstOwnership, operation: "discovery") + await reportLaunchFailure( + mcpObservations.ownerships.dropFirst(firstOwnership), operation: "discovery") } try #require(result.objectValue?["isError"] != .bool(true), "\(result)") let tools = try #require( @@ -1141,7 +1157,9 @@ private final class CursorHarness: @unchecked Sendable { let result = try await gateway.callToolForMCPAsync( name: name, arguments: .object(["prompt": .string(prompt)]), context: .empty) if result.objectValue?["isError"] == .bool(true) { - await reportLaunchFailure(since: firstOwnership, operation: "CLI compatibility/target") + 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") @@ -1157,8 +1175,10 @@ private final class CursorHarness: @unchecked Sendable { } return result } - func reportLaunchFailure(since firstOwnership: Int, operation: String) async { - for ownership in base.observations.ownerships.dropFirst(firstOwnership) { + 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( @@ -1195,12 +1215,24 @@ private final class CursorHarness: @unchecked Sendable { 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 { - try #require(base.observations.ownerships.first { (try? $0.recoveryState().root) == member }) + 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 = base.observations.members.filter { $0.processID == pid } + let matches = mcpObservations.members.filter { $0.processID == pid } try #require(matches.count == 1) return try #require(matches.first) } @@ -1384,11 +1416,15 @@ private final class CursorHarness: @unchecked Sendable { 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 == boundary.executionID) + try #require(entry.child == child && entry.execution == execution) try #require(entry.recovery.sandboxed) return entry } @@ -1606,7 +1642,7 @@ private final class CursorHarness: @unchecked Sendable { var proofs: Set = [] var children: Set = [] for pair in [first, second] { - let pids = Set(pair) + let roots = Set(pair) var matched = false for execution in ledger.executions.values where execution.delegatedTo == .package("cursor") { @@ -1614,7 +1650,7 @@ private final class CursorHarness: @unchecked Sendable { continue } let slots = record.children.filter { _, record in - record.recovery.map { pids.contains($0.root) } ?? false + record.recovery.map { roots.contains($0.root) } ?? false } guard slots.count == 2 else { continue } let newExecution = executions.insert(execution.id).inserted @@ -1629,37 +1665,50 @@ private final class CursorHarness: @unchecked Sendable { 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.values.count == 3 - && record.children.values.contains { - $0.recovery?.root == adapter && $0.recovery?.sandboxed == true - }) + 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"] } - let phaseIDs = try pair.map { root in - let pair = try #require(slots.first { $0.value.recovery?.root == root }) - try #require(pair.value.recovery?.sandboxed == true) - return pair.key + 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) } - try #require(slots[phaseIDs[0]]?.completed == true) - try #require(slots[phaseIDs[1]]?.completed == false) - rows.append([ - "execution": execution.id.uuidString, - "authorization_ids": execution.authorizationIDs.map(\.uuidString).sorted(), - "adapter_pid": adapter.processID, - "probe_pid": pair[0].processID, - "probe_child": phaseIDs[0].uuidString, - "workload_pid": pair[1].processID, - "workload_child": phaseIDs[1].uuidString, - ]) + 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( @@ -1708,7 +1757,7 @@ private final class CursorHarness: @unchecked Sendable { for _ in 0..<200 { try await (gateway ?? base.runtime).permissionRuntime.coordinator.reconcile() var live = false - for ownership in base.observations.ownerships { + for ownership in base.observations.ownerships + mcpObservations.ownerships { if try await ownership.members().isEmpty == false { live = true } } if !live { return } diff --git a/tests/test_host_source.py b/tests/test_host_source.py index fbe171f..df0ec21 100644 --- a/tests/test_host_source.py +++ b/tests/test_host_source.py @@ -36,6 +36,29 @@ def test_evidence_must_be_fresh_complete_and_nonzero(self): 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_source_identity_and_dirt_are_rejected(self): sha = 'a' * 40 with patch.object(driver, 'git', side_effect=[str(ROOT), sha, '']): From 580659542e0bb29a715f7bb187748acee2f86023 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:40:37 +0800 Subject: [PATCH 04/29] test: verify retained sessions through the registered host router --- .github/computer-mcp-host.sha | 1 + .github/workflows/ci.yml | 50 +++++++- CONTRIBUTING.md | 4 +- docs/Reference/Installation.md | 6 +- .../CursorSourceIntegrationTests.swift.txt | 111 +++++++++++++----- 5 files changed, 141 insertions(+), 31 deletions(-) create mode 100644 .github/computer-mcp-host.sha diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha new file mode 100644 index 0000000..16fd2b2 --- /dev/null +++ b/.github/computer-mcp-host.sha @@ -0,0 +1 @@ +1ab29e3f7097c335f2b5429da3c708ca8a307db1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bb141ef..0715fac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,9 +53,57 @@ jobs: - run: python3 tests/check_runtime_rejection.py runtime: uses: computer-mcp/github-workflows/.github/workflows/plugin-runtime.yml@fd25fcface41732fda099017c6945912366fc7c1 + host-consumer: + runs-on: macos-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + with: + python-version: '3.14' + - name: Verify the registered Cursor consumer against pinned Host source + shell: bash + env: + PLUGIN_SHA: ${{ github.sha }} + 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 ]] + test "$(git rev-parse HEAD)" = "$PLUGIN_SHA" + 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" + python3 -B scripts/validate_host_source.py --suite vendor-stop \ + --host-source "$host_source" --host-sha "$host_sha" \ + --plugin-source "$PWD" --plugin-sha "$PLUGIN_SHA" \ + --output "$PWD/.agent/host6/ci-registered-consumer" --timeout 1200 + - name: Retain registered consumer evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: cursor-host-consumer-${{ github.sha }} + path: | + .agent/host6/ci-registered-consumer/receipt.json + .agent/host6/ci-registered-consumer/cases.json + .agent/host6/ci-registered-consumer/*-export.log + .agent/host6/ci-registered-consumer/package-build.log + .agent/host6/ci-registered-consumer/swift-test.log + if-no-files-found: ignore + include-hidden-files: true + retention-days: 14 validate: if: always() - needs: [package, unsupported-runtime, runtime] + needs: [package, unsupported-runtime, runtime, host-consumer] uses: computer-mcp/github-workflows/.github/workflows/result.yml@fd25fcface41732fda099017c6945912366fc7c1 with: needs-json: ${{ toJSON(needs) }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 623afea..fec6998 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,4 +23,6 @@ The exact-source consumer and separate archive identity check are documented in [installation guide](docs/Reference/Installation.md). Use only clean reviewed full-SHA pairs; never direct plugin commands to an implicit App control socket. The deterministic fixture preserves native permission choices and does not establish authentication or -real-model sandbox suitability. CI host acquisition awaits the reviewed host pin. +real-model sandbox suitability. The required CI job runs the registered Cursor suite +at the candidate revision and fetches [the pinned Host SHA](.github/computer-mcp-host.sha) +from the public Host repository. diff --git a/docs/Reference/Installation.md b/docs/Reference/Installation.md index 63e9ca8..864460c 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -54,8 +54,10 @@ python3 scripts/validate_host_source.py \ --output /absolute/path/to/plugin-cursor/.agent/host6/source-run ``` -Both SHA placeholders must be replaced with reviewed commits. The final host pin and CI -acquisition remain integration-owner decisions. Python is the driver's current interpreter +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. +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. diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index 886fd87..90e22f2 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -55,6 +55,11 @@ struct CursorSourceIntegrationTests { 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"]) @@ -102,8 +107,18 @@ struct CursorSourceIntegrationTests { try #require(stopped["stop_reason"] == .string("cancelled")) try #require( stopped["native_result"]?.objectValue?["usage"]?.objectValue?["tokens"] == .integer(3)) - try #require(try await aOwner.members().contains(where: { $0.processID == aPID })) - _ = try cursorValue(try await h.prompt(a, "hello after cancellation")) + 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 resumed = try cursorValue(try await h.prompt(a, "hello after cancellation")) + try #require( + resumed["session"] == .string(a) && resumed["stop_reason"] == .string("end_turn")) + try await h.waitVendorPrompt(pid: aPID, prompt: "hello after cancellation") + 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) @@ -216,6 +231,7 @@ struct CursorSourceIntegrationTests { 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) @@ -294,7 +310,7 @@ struct CursorSourceIntegrationTests { trial["probe_pid"] = Int(probeRoot.processID) if withdraw { let cancelled = try cursorValue( - try await h.gateway.callToolForMCPAsync( + try await h.consumer.generations.callToolForMCPAsync( name: "mcp.requests.cancel", arguments: .object([ "server": .string("cursor-fixture"), "request_id": .string(requestID), @@ -331,6 +347,7 @@ struct CursorSourceIntegrationTests { 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) @@ -741,9 +758,7 @@ struct CursorSourceIntegrationTests { let second = try h.makeConsumer("cursor-second", caller: 2, use: true) h.other = second try await h.discover(gateway: second) - let secondSession = try #require( - try cursorValue(try await h.call("cursor.acp.session.open", gateway: second))["session"]? - .stringValue) + let secondSession = try await h.open(gateway: second) let service = h.gateway.permissionRuntime.service _ = try service.revokePermission( .plugin("cursor"), profileID: h.consumerID, owner: h.owner, @@ -857,6 +872,11 @@ private struct CursorTransportEvent: Decodable { 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 @@ -870,8 +890,9 @@ private final class CursorHarness: @unchecked Sendable { let outside: [URL] let owner: GatewayPermissionOwner let consumerID = GatewayProfileID(rawValue: "cursor-consumer")! - var gateway: GatewayRuntime! - var other: GatewayRuntime? + var consumer: CursorConsumer! + var gateway: GatewayRuntime { consumer.runtime } + var other: CursorConsumer? var removed = false init( @@ -1053,7 +1074,7 @@ private final class CursorHarness: @unchecked Sendable { let lifecycleProfile = try #require( base.database.profiles().first { $0.id == base.configuration.runtime.profileID }) stage = "consumer generation" - h.gateway = try h.makeConsumer("cursor-consumer", caller: caller, use: use) + 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) @@ -1109,7 +1130,7 @@ private final class CursorHarness: @unchecked Sendable { return (try? String(contentsOf: path, encoding: .utf8).split(separator: "\n").count) ?? 0 } } - func makeConsumer(_ name: String, caller: Int, use: Bool) throws -> GatewayRuntime { + 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([ @@ -1132,14 +1153,14 @@ private final class CursorHarness: @unchecked Sendable { mcpClient: MCPProxyClient(launcher: testExecutionLauncher(observations: mcpObservations)), plugins: [plugin], bundledPlugins: .init(packages: [], issues: [])) _ = try gateway.makeControlSession() - return gateway + return .init(runtime: gateway, generations: GatewayStandaloneGenerations(gateway)) } - func catalog(gateway selected: GatewayRuntime? = nil) async throws -> JSONValue { - try await (selected ?? gateway!).callToolForMCPAsync( + func catalog(gateway selected: CursorConsumer? = nil) async throws -> JSONValue { + try await (selected ?? consumer!).generations.callToolForMCPAsync( name: "mcp.tools.list", arguments: .object(["server": .string("cursor-fixture")]), context: .empty) } - func discover(gateway selected: GatewayRuntime? = nil) async throws { + 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) { @@ -1195,7 +1216,7 @@ private final class CursorHarness: @unchecked Sendable { } } func call( - _ name: String, _ args: [String: JSONValue] = [:], gateway selected: GatewayRuntime? = nil, + _ name: String, _ args: [String: JSONValue] = [:], gateway selected: CursorConsumer? = nil, startRequestID: String? = nil ) async throws -> JSONValue { var arguments: [String: JSONValue] = [ @@ -1205,12 +1226,18 @@ private final class CursorHarness: @unchecked Sendable { arguments["request_id"] = .string(startRequestID) arguments["wait_for_result"] = .bool(false) } - return try await (selected ?? gateway!).callToolForMCPAsync( - name: "mcp.tools.call", arguments: .object(arguments), context: .empty) + let client = selected ?? consumer! + do { + return try await client.generations.callToolForMCPAsync( + 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 gateway.callToolForMCPAsync( + try await consumer.generations.callToolForMCPAsync( name: "mcp.requests.read", arguments: .object(["server": .string("cursor-fixture"), "request_id": .string(id)]), context: .empty)) @@ -1463,7 +1490,7 @@ private final class CursorHarness: @unchecked Sendable { try #require(request.projectID == projectID && request.registrationID == "cursor-fixture") let connectionID = try #require(request.connectionID) let report = try cursorValue( - try await gateway.callToolForMCPAsync( + try await consumer.generations.callToolForMCPAsync( name: "runtime.owners.list", arguments: .object([ "project_id": .string(projectID), "server": .string("cursor-fixture"), @@ -1493,7 +1520,7 @@ private final class CursorHarness: @unchecked Sendable { -> [String: JSONValue] { try cursorValue( - try await gateway.callToolForMCPAsync( + try await consumer.generations.callToolForMCPAsync( name: "runtime.owners.call", arguments: .object([ "project_id": .string(projectID), "owner": owner.locator, @@ -1510,12 +1537,42 @@ private final class CursorHarness: @unchecked Sendable { } while ContinuousClock.now < deadline throw CursorFixtureError.deadline } - func open() async throws -> String { - try #require( + 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")]))[ - "session"]?.stringValue) + 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)]) @@ -1755,7 +1812,7 @@ private final class CursorHarness: @unchecked Sendable { } func requireJoined() async throws { for _ in 0..<200 { - try await (gateway ?? base.runtime).permissionRuntime.coordinator.reconcile() + 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 } @@ -1766,8 +1823,8 @@ private final class CursorHarness: @unchecked Sendable { throw CursorFixtureError.deadline } func close() async throws { - await gateway?.shutdown() - await other?.shutdown() + await consumer?.generations.shutdown() + await other?.generations.shutdown() let cleanupError: (any Error)? do { if !removed { try await removeWorktree() } From 40693242b3d58a9e4a4e830c8125e240859c241e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:14:01 +0800 Subject: [PATCH 05/29] test: correlate native cancellation with each addressed turn --- scripts/validate_host_source.py | 26 +++++++ .../CursorSourceIntegrationTests.swift.txt | 77 +++++++++++++++---- tests/test_host_source.py | 19 +++++ 3 files changed, 105 insertions(+), 17 deletions(-) diff --git a/scripts/validate_host_source.py b/scripts/validate_host_source.py index a339097..be35ae8 100644 --- a/scripts/validate_host_source.py +++ b/scripts/validate_host_source.py @@ -207,6 +207,30 @@ def root(row, phase): 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") @@ -319,6 +343,8 @@ def run(args): acquisitions = observed.get("acquisitions") validate_acquisitions(acquisitions) result["acquisitions"] = acquisitions + result["native_stops"] = observed.get("native_stops") + validate_native_stops(result["native_stops"], acquisitions) result["startup_cancellation"] = observed.get("startup_cancellation") validate_startup_cancellation(result["startup_cancellation"]) result["lost_start_reply"] = observed.get("lost_start_reply") diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index 90e22f2..6902e16 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -21,9 +21,9 @@ private let cursorWriteTools: Set = [ "cursor.acp.session.cancel", "cursor.acp.session.close", ] -@Suite(.nativeIntegration, .serialized, .timeLimit(.minutes(5))) +@Suite(.nativeIntegration, .serialized) struct CursorSourceIntegrationTests { - @Test func registeredVendorStop() async throws { + @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"]) @@ -48,6 +48,7 @@ struct CursorSourceIntegrationTests { } var measured: [[String: Any]] = [] + var nativeStops: [[String: Any]] = [] try await withCursor(package) { h in try await h.discover() let baseline = h.mcpObservations.members.count @@ -123,9 +124,12 @@ struct CursorSourceIntegrationTests { async let interactive = h.prompt(a, "permission-on-cancel") _ = try await h.waitPending(a) let beforeAnswer = try h.vendorEffects().count - let interactiveStop = try cursorValue(try await h.stop(a)) - try #require(interactiveStop["cancel_requested"] == .bool(true)) - let interactiveResult = try cursorNativeValue(try await interactive) + 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) @@ -236,21 +240,32 @@ struct CursorSourceIntegrationTests { let freshTurn = try h.vendorTurn(pid: bPID, prompt: freshB) let freshNativeID = try #require(freshTurn.first?["acp_id"]?.intValue) try #require(freshNativeID > bNativeID) - let effects = try h.vendorEffects() - try #require(effects.filter { $0["phase"]?.stringValue == "probe" }.count == 2) - try #require( - effects.filter { - $0["pid"]?.intValue == Int(aPID) && $0["phase"]?.stringValue == "cancel" - }.count == 3) - try #require( - effects.filter { - $0["pid"]?.intValue == Int(bPID) && $0["phase"]?.stringValue == "cancel" - }.count == 1) 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) } let evidence = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_CASES"])) let cases = [ @@ -258,7 +273,7 @@ struct CursorSourceIntegrationTests { "native-result-races", "pending-answer-cancel", "forced-stop-isolation", "cleanup", "startup-cancellation", "lost-start-reply", "pending-start-closure", ] - var details: [String: Any] = ["acquisitions": measured] + var details: [String: Any] = ["acquisitions": measured, "native_stops": nativeStops] details["startup_cancellation"] = try await registeredStartupCancellation(package) details["lost_start_reply"] = try await registeredLostStartReply(package) details["pending_start_closure"] = try await registeredPendingStartClosure(package) @@ -561,7 +576,7 @@ struct CursorSourceIntegrationTests { return evidence } - @Test func sourceConsumer() async throws { + @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) @@ -1677,6 +1692,34 @@ private final class CursorHarness: @unchecked Sendable { 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([ diff --git a/tests/test_host_source.py b/tests/test_host_source.py index df0ec21..cd77158 100644 --- a/tests/test_host_source.py +++ b/tests/test_host_source.py @@ -59,6 +59,25 @@ def acquisition(offset): 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, '']): From 49bf7e357974fb9afc6d138abafd4818ca09f8eb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:16:05 +0800 Subject: [PATCH 06/29] test: verify registered project access in Cursor worktrees --- tests/Fixtures/CursorSourceIntegrationTests.swift.txt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index 6902e16..f2cf4ad 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -713,8 +713,9 @@ struct CursorSourceIntegrationTests { 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]] == Array(repeating: ["r", "a"], count: h.outside.count)) + 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( @@ -933,6 +934,10 @@ private final class CursorHarness: @unchecked Sendable { 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.callToolForMCPAsync( @@ -944,7 +949,7 @@ private final class CursorHarness: @unchecked Sendable { let foreign = try base.database.prepareProviderContainer(.package("foreign")).sandbox let outside = [ base.project.appendingPathComponent("source-main"), - base.root.appendingPathComponent("unrelated"), + unrelated.appendingPathComponent("value.txt"), base.database.permissionExecutionRoot.appendingPathComponent("host-secret"), URL(fileURLWithPath: foreign.state.value).appendingPathComponent("foreign-secret"), ] From c7e031efd9a2df2b0275d3f08024d490ec0fdc5c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:36:11 +0800 Subject: [PATCH 07/29] ci: verify Cursor source and registered session workflows --- .github/workflows/ci.yml | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0715fac..2927042 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,6 +54,10 @@ jobs: runtime: uses: computer-mcp/github-workflows/.github/workflows/plugin-runtime.yml@fd25fcface41732fda099017c6945912366fc7c1 host-consumer: + strategy: + fail-fast: false + matrix: + suite: [source, vendor-stop] runs-on: macos-latest timeout-minutes: 25 steps: @@ -64,10 +68,11 @@ jobs: - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 with: python-version: '3.14' - - name: Verify the registered Cursor consumer against pinned Host source + - name: Verify the consumer against pinned Host source shell: bash env: PLUGIN_SHA: ${{ github.sha }} + SUITE: ${{ matrix.suite }} GIT_TERMINAL_PROMPT: '0' GIT_ASKPASS: /usr/bin/false GIT_CONFIG_GLOBAL: /dev/null @@ -83,21 +88,21 @@ jobs: 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" - python3 -B scripts/validate_host_source.py --suite vendor-stop \ + python3 -B scripts/validate_host_source.py --suite "$SUITE" \ --host-source "$host_source" --host-sha "$host_sha" \ --plugin-source "$PWD" --plugin-sha "$PLUGIN_SHA" \ - --output "$PWD/.agent/host6/ci-registered-consumer" --timeout 1200 - - name: Retain registered consumer evidence + --output "$PWD/.agent/host6/host-consumer" --timeout 1200 + - name: Retain consumer evidence if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - name: cursor-host-consumer-${{ github.sha }} + name: cursor-host-consumer-${{ matrix.suite }}-${{ github.sha }} path: | - .agent/host6/ci-registered-consumer/receipt.json - .agent/host6/ci-registered-consumer/cases.json - .agent/host6/ci-registered-consumer/*-export.log - .agent/host6/ci-registered-consumer/package-build.log - .agent/host6/ci-registered-consumer/swift-test.log + .agent/host6/host-consumer/receipt.json + .agent/host6/host-consumer/cases.json + .agent/host6/host-consumer/*-export.log + .agent/host6/host-consumer/package-build.log + .agent/host6/host-consumer/swift-test.log if-no-files-found: ignore include-hidden-files: true retention-days: 14 From 40265c11699dcef36679fbde24f8288becc2f001 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:44:04 +0800 Subject: [PATCH 08/29] test: verify retained Cursor cancellation results --- .../CursorSourceIntegrationTests.swift.txt | 41 +++++++++++++++---- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index f2cf4ad..04bcd56 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -761,8 +761,9 @@ struct CursorSourceIntegrationTests { 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)) - try #require(cancelled["is_error"] == .bool(true)) + session, prompt: try #require(slow["prompt_id"]?.stringValue), + expectingCancellation: true) + try #require(cancelled["closed"] == .bool(false)) try #require(try h.nativeStarts == nativeStarts) // Client B uses a separate authority and kill domain in the same provider container. let firstOwnerships = h.mcpObservations.ownerships @@ -846,6 +847,29 @@ private func cursorNativeValue(_ value: JSONValue) throws -> [String: JSONValue] 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( @@ -1838,12 +1862,15 @@ private final class CursorHarness: @unchecked Sendable { } throw CursorFixtureError.deadline } - func waitResult(_ session: String, prompt: String) async throws -> [String: JSONValue] { + func waitResult(_ session: String, prompt: String, expectingCancellation: Bool = false) + async throws -> [String: JSONValue] + { for _ in 0..<200 { - let value = try cursorValue( - try await call( - "cursor.acp.session.prompt.result", - ["session": .string(session), "prompt_id": .string(prompt)])) + 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)) } From 46e0de62ad16bbfb2e381850f32d38462fb1a9a2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:03:34 +0800 Subject: [PATCH 09/29] test: verify Cursor revocation against its owned worktree processes --- .../CursorSourceIntegrationTests.swift.txt | 103 ++++++++++++++---- 1 file changed, 83 insertions(+), 20 deletions(-) diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index 04bcd56..63af383 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -765,46 +765,61 @@ struct CursorSourceIntegrationTests { 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 firstOwnerships = h.mcpObservations.ownerships - var retained = false - for ownership in firstOwnerships { - if try await ownership.members().isEmpty == false { retained = true } - } - try #require(retained) - let second = try h.makeConsumer("cursor-second", caller: 2, use: true) + 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 - _ = try service.revokePermission( + 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 cursorValue( + 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("hello")], gateway: second)) - for _ in 0..<200 { - var live = false - for ownership in firstOwnerships { - if try await ownership.members().isEmpty == false { live = true } - } - if !live { break } - try await Task.sleep(for: .milliseconds(10)) - } - for ownership in firstOwnerships { try #require(try await ownership.members().isEmpty) } + ["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.requireJoined() + try await h.requireWorktreeRootsJoined(Array(remainingExecutions.keys)) } let evidence = URL(fileURLWithPath: try #require(env["COMPUTER_MCP_CURSOR_CASES"])) try JSONSerialization.data(withJSONObject: [ @@ -1317,6 +1332,54 @@ private final class CursorHarness: @unchecked Sendable { 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)) From 0905e7ea808b04d531494cba7835e3c277d14709 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:09:30 +0800 Subject: [PATCH 10/29] ci: pin the reviewed host for consumer acceptance --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 16fd2b2..15264bc 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -1ab29e3f7097c335f2b5429da3c708ca8a307db1 +f6de5e0c003af87722868d5c38aebb12ee656e3b From 629851fba92fb334c7e216bbfd73688524520470 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:15:32 +0800 Subject: [PATCH 11/29] fix: isolate Cursor source validation evidence --- .github/workflows/ci.yml | 14 +++++----- docs/Reference/Installation.md | 9 ++++--- scripts/validate_host_source.py | 29 +++++++++++---------- tests/test_declarations.py | 3 +-- tests/test_host_source.py | 46 +++++++++++++++++++++++---------- 5 files changed, 61 insertions(+), 40 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2927042..5938aaf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,20 +91,20 @@ jobs: python3 -B scripts/validate_host_source.py --suite "$SUITE" \ --host-source "$host_source" --host-sha "$host_sha" \ --plugin-source "$PWD" --plugin-sha "$PLUGIN_SHA" \ - --output "$PWD/.agent/host6/host-consumer" --timeout 1200 + --output "$RUNNER_TEMP/host-consumer" --timeout 1200 - name: Retain consumer evidence if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: cursor-host-consumer-${{ matrix.suite }}-${{ github.sha }} path: | - .agent/host6/host-consumer/receipt.json - .agent/host6/host-consumer/cases.json - .agent/host6/host-consumer/*-export.log - .agent/host6/host-consumer/package-build.log - .agent/host6/host-consumer/swift-test.log + ${{ runner.temp }}/host-consumer/receipt.json + ${{ runner.temp }}/host-consumer/cases.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 if-no-files-found: ignore - include-hidden-files: true retention-days: 14 validate: if: always() diff --git a/docs/Reference/Installation.md b/docs/Reference/Installation.md index 864460c..d06cdaa 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -40,8 +40,9 @@ CI runs deterministic fixture tests and packaging; it does not install a vendor ## Deterministic source consumer Use explicit clean host and plugin repository roots and full lowercase 40-character -commit SHAs. The driver verifies both HEADs and clean status, exports committed sources -into a fresh ignored run directory, and injects the companion fixture into the isolated +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 @@ -51,12 +52,14 @@ committed `FixedHostFixture`, permission fixtures and standalone generation API. python3 scripts/validate_host_source.py \ --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/plugin-cursor/.agent/host6/source-run + --output /absolute/path/to/validation-runs/cursor-source-run ``` 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 writes the run to the runner's temporary directory and uploads its receipt, case +evidence and logs. 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. diff --git a/scripts/validate_host_source.py b/scripts/validate_host_source.py index be35ae8..f4561d7 100644 --- a/scripts/validate_host_source.py +++ b/scripts/validate_host_source.py @@ -1,6 +1,6 @@ """Run the deterministic Cursor companion against explicit clean source commits. -The driver exports both commits into an ignored run directory. It never edits +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. """ @@ -81,15 +81,16 @@ def contains(parent, child): def validate_locations(host, plugin, output): if contains(host, plugin) or contains(plugin, host): raise ValueError("Host and plugin must be separate, non-nested source checkouts") - owned = plugin / ".agent/host6" - if not contains(owned, output) or output == owned: - raise ValueError("Output must be a new run directory under plugin .agent/host6") - if contains(host, output): - raise ValueError("Output must be outside the host source") - if not git(plugin, "check-ignore", str(output / "receipt.json")): - raise ValueError("Run output must be ignored") - if output.exists() or output.is_symlink(): - raise ValueError("Output must be a new directory") + 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(contains(root, output) or 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): @@ -284,13 +285,12 @@ def validate_start_recovery(lost, closure): def run(args): - validate_locations(args.host_source, args.plugin_source, args.output) + 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) suite = args.suite before = {name: digest(args.plugin_source / name) for name in INPUTS} - args.output.mkdir(parents=True) - output = args.output + output.mkdir(parents=True) host = output / "host-source" plugin = output / "plugin-source" evidence = output / "cases.json" @@ -381,7 +381,8 @@ def main(argv=None): 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=absolute) + 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, default="source") parser.add_argument("--timeout", type=int, default=900) args = parser.parse_args(argv) diff --git a/tests/test_declarations.py b/tests/test_declarations.py index 69004c5..2f43847 100644 --- a/tests/test_declarations.py +++ b/tests/test_declarations.py @@ -7,7 +7,6 @@ class DeclarationTests(unittest.TestCase): def test_manifest_matches_actual_catalog(self): - (ROOT / '.agent/host6').mkdir(parents=True, exist_ok=True) manifest = tomllib.loads((ROOT / 'computer-mcp-plugin.toml').read_text()) self.assertEqual(manifest['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.'}]) self.assertNotIn('sandbox', manifest) @@ -15,7 +14,7 @@ def test_manifest_matches_actual_catalog(self): 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(dir=ROOT / '.agent/host6') as temp: + with tempfile.TemporaryDirectory() as temp: client = Client(temp) try: tools = client.request('tools/list')['result']['tools'] diff --git a/tests/test_host_source.py b/tests/test_host_source.py index cd77158..93afd7f 100644 --- a/tests/test_host_source.py +++ b/tests/test_host_source.py @@ -18,10 +18,6 @@ class HostSourceTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - (ROOT / '.agent/host6').mkdir(parents=True, exist_ok=True) - 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) @@ -87,15 +83,36 @@ def test_source_identity_and_dirt_are_rejected(self): with patch.object(driver, 'git', side_effect=[str(ROOT), sha, '?? untracked']): with self.assertRaises(ValueError): driver.verify_source(ROOT, sha) - def test_only_ignored_run_outputs(self): - host = Path('/separate/host') - with self.assertRaises(ValueError): driver.validate_locations(host, ROOT, ROOT / 'output') - with self.assertRaises(ValueError): driver.validate_locations(ROOT, ROOT, ROOT / '.agent/host6/run') - driver.validate_locations(host, ROOT, ROOT / '.agent/host6/not-created') + 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_snapshot_rejects_links_and_path_escape(self): for name, kind in (('../escape', tarfile.REGTYPE), ('link', tarfile.SYMTYPE)): - with tempfile.TemporaryDirectory(dir=ROOT / '.agent/host6') as temp: + 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) @@ -105,9 +122,10 @@ def test_snapshot_rejects_links_and_path_escape(self): def test_staged_run_records_pair_and_removes_owned_snapshots(self): import shutil from types import SimpleNamespace - with tempfile.TemporaryDirectory(dir=ROOT / '.agent/host6') as temp: - output = Path(temp) / 'run' - args = SimpleNamespace(host_source=Path('/separate/host'), plugin_source=ROOT, suite='source', + with tempfile.TemporaryDirectory() as temp: + root = Path(temp).resolve() + output = root / 'run' + args = SimpleNamespace(host_source=root / 'host', plugin_source=ROOT, suite='source', host_sha='a' * 40, plugin_sha='b' * 40, output=output, timeout=3) def export(root, sha, destination, environment, work): destination.mkdir() @@ -138,7 +156,7 @@ def execute(command, cwd, environment, log, timeout): for name in ('host-source', 'plugin-source', 'build'): self.assertFalse((output / name).exists()) def test_bounded_command_failure_and_timeout(self): - with tempfile.TemporaryDirectory(dir=ROOT / '.agent/host6') as temp: + 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') From 8432be3bb909d7963c2708f5dc7d59297b42322e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:26:23 +0800 Subject: [PATCH 12/29] fix: check Cursor validation paths by filesystem identity --- scripts/validate_host_source.py | 22 ++++++++++++++++++-- tests/test_host_source.py | 36 +++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/scripts/validate_host_source.py b/scripts/validate_host_source.py index f4561d7..ff98222 100644 --- a/scripts/validate_host_source.py +++ b/scripts/validate_host_source.py @@ -78,15 +78,33 @@ 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 contains(host, plugin) or contains(plugin, host): + 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(contains(root, output) or contains(output, root) for root in (host, plugin)): + 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") diff --git a/tests/test_host_source.py b/tests/test_host_source.py index 93afd7f..5a776d5 100644 --- a/tests/test_host_source.py +++ b/tests/test_host_source.py @@ -110,6 +110,42 @@ def test_only_fresh_external_run_outputs(self): 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: From 8392aa2b960b4e1bf1f25d43641859092dd80287 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:22:26 +0800 Subject: [PATCH 13/29] ci: pin Host with reviewed Computer Use declarations --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 15264bc..f8d746f 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -f6de5e0c003af87722868d5c38aebb12ee656e3b +f1d29a58573ee97e5bfe7392e9c6852a508a706f From 04a83f20f4209b4fa56ff848788911ae41cd5d5d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:37:30 +0800 Subject: [PATCH 14/29] feat: declare Cursor service access and report ACP sign-in requirements --- README.md | 12 +++++++----- bin/cursor-mcp-adapter | 14 ++++++++++++-- computer-mcp-plugin.toml | 10 +++++++--- docs/Reference/Installation.md | 8 +++++++- docs/Reference/Interface.md | 32 +++++++++++++++++++++++++------- tests/Fixtures/vendor.py | 12 +++++++++++- tests/test_adapter.py | 30 ++++++++++++++++++++++++++++++ tests/test_declarations.py | 10 +++++++++- 8 files changed, 108 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index abb8744..07ec069 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,9 @@ 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 and run `agent login` in the vendor context selected for + the plugin. Provide Python 3.13 or newer on the Computer MCP launch `PATH`. + [Cursor CLI authentication](https://cursor.com/docs/cli/reference/authentication) 2. Build the archive: ```sh @@ -64,9 +65,10 @@ from `Examples/settings.json`. through the same UI or `plugins configure`. The `cursor-agent` dependency selects the executable for the CLI and Host-managed ACP contributions. -Review the provider Project-write purpose and MCP caller requirements in the manifest. -The offline draft uses sandbox mode with network none and no user-config read exceptions; -native login/network/config and execution-mode acceptance remain pending owner decisions. +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. diff --git a/bin/cursor-mcp-adapter b/bin/cursor-mcp-adapter index bc277b4..33ce92e 100755 --- a/bin/cursor-mcp-adapter +++ b/bin/cursor-mcp-adapter @@ -21,6 +21,7 @@ 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)} @@ -291,9 +292,18 @@ class Session: if 'error' in message and (not isinstance(message['error'],dict) or type(message['error'].get('code')) is not int or not isinstance(message['error'].get('message'),str)): raise Failure('invalid_vendor_response','ACP error has invalid fields') if 'error' in message: - error = message['error'] - code = error.get('code') if isinstance(error,dict) else None + code = message['error']['code'] settled_rpc_error = kind == 'prompt' and self.managed is not None + if method == 'authenticate': + hint = 'Run `agent login` in the same Cursor Agent context.' + detail = message['error']['message'] + # Cursor's browser login failures use Invalid Params in the pinned CLI. + if code == ACP_AUTH_REQUIRED or (code == -32602 and ( + detail == 'Login failed or timed out. Please try again.' + or detail.startswith('Failed to open browser for login. Please visit: ') + )): + raise Failure('authentication_required', f'Cursor sign-in required (RPC code {code}). {hint}') + raise Failure('vendor_error', f'Cursor rejected authenticate (RPC code {code}). {hint}') raise Failure('vendor_error',f'Cursor rejected {method} (RPC code {code}); no request was replayed') value = message['result'] if not isinstance(value,dict): diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index d37699a..8f47e1b 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 run agent login in the same Cursor Agent context selected for this plugin." +documentation = "https://cursor.com/docs/cli/reference/authentication" [[dependencies]] id = "python-runtime" @@ -22,6 +22,10 @@ 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" } @@ -42,7 +46,7 @@ dependency = "cursor-agent" signature = "cursor-vendor-execution.json" [mcp.vendor_execution.files] -"bin/cursor-mcp-adapter" = "451c89ad1cd2301a1d897710fbbbdd15e98e68d87769d8146bf1a4f8729cb924" +"bin/cursor-mcp-adapter" = "3110f1cb6a203f3d2b2d8e7be8b7f8783ac30dd0215eac37b6d7928b353170ac" "bin/cursor_vendor_execution.py" = "27478badaaf35e9c2499efdb4858ebeae048e7117b7d07377452b5d7e52bd2b3" "bin/plugin_runtime.py" = "5a9f797bfca4b6ab31a9a648017fb1d09400593a9aab0d2250d426efa51f97cf" "cli-tree.json" = "cc52c0bc7662f93d8596f715625d2ed274d05d95c681bac4d32c0faf273b64a3" diff --git a/docs/Reference/Installation.md b/docs/Reference/Installation.md index d06cdaa..9e310db 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -4,7 +4,13 @@ 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. +Install Cursor Agent separately. In the vendor context selected for this plugin, +run `agent login` and complete the sign-in in your browser. Cursor manages the +credentials used by that context. The adapter's ACP authentication uses the +existing vendor credentials. [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 diff --git a/docs/Reference/Interface.md b/docs/Reference/Interface.md index b6fa707..64e30a7 100644 --- a/docs/Reference/Interface.md +++ b/docs/Reference/Interface.md @@ -21,13 +21,23 @@ does not authorize project execution. Runtime metadata never sets caller require 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 offline draft omits sandbox declarations: sandbox mode, network none and no existing -user-config read exceptions. Provider HOME/cache/state are host-provisioned persistent -container paths; temporary storage is execution-local. The host selects the worktree, -protects unrelated projects/host data/other containers and retires writers before removal. -This adapter does not request `projects-v1` or perform host lifecycle calls. Native login, -config reads, network and any Full access choice require measured facts and an owner -decision. The deterministic fixture does not establish real-model suitability. +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 owner initiates browser sign-in via `agent login` in the selected Cursor +Agent context. The plugin network request covers only the agent/API hosts +listed above. Provider HOME, cache and state use host-provisioned persistent +container paths. Temporary storage is execution-local. +[Cursor CLI authentication](https://cursor.com/docs/cli/reference/authentication) + +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 @@ -88,6 +98,14 @@ 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 before creating or loading a session. An authentication +RPC rejection stops setup. The adapter reports `authentication_required` when +ACP requires authentication or the pinned Cursor CLI reports that its browser +sign-in could not complete. Other authentication rejections report +`vendor_error`. Both include the original RPC code and a fixed login hint. +[Cursor ACP](https://cursor.com/docs/cli/acp) + ## Tools | Native MCP tool | Behavior | diff --git a/tests/Fixtures/vendor.py b/tests/Fixtures/vendor.py index c7b90a2..a8b81ba 100755 --- a/tests/Fixtures/vendor.py +++ b/tests/Fixtures/vendor.py @@ -67,7 +67,17 @@ 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: diff --git a/tests/test_adapter.py b/tests/test_adapter.py index 0ce5bc9..84ec55c 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -1,4 +1,5 @@ import json +from pathlib import Path import tempfile import time import unittest @@ -26,6 +27,35 @@ 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.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'), + (-32602, 'Failed to open browser for login. Please visit: https://example.test/fixture-sensitive-url', + 'authentication_required'), + (-32602, 'Unknown authentication method: fixture-sensitive-message', 'vendor_error'), + ] + for rpc_code, message, expected in cases: + with self.subTest(rpc_code=rpc_code, expected=expected), tempfile.TemporaryDirectory() as directory: + client = Client(directory, { + 'HOME': directory, 'CURSOR_SOURCE_FIXTURE': '1', + 'FIXTURE_AUTH_ERROR_CODE': str(rpc_code), + 'FIXTURE_AUTH_ERROR_MESSAGE': message, + }) + try: + response = client.call('cursor.acp.session.open') + self.assertTrue(response['result']['isError']) + error = Client.value(response)['error'] + self.assertEqual(error['code'], expected) + self.assertIn(f'RPC code {rpc_code}', error['message']) + self.assertIn('Run `agent login` in the same Cursor Agent context.', error['message']) + self.assertNotIn('fixture-sensitive', 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']: diff --git a/tests/test_declarations.py b/tests/test_declarations.py index 2f43847..feb3532 100644 --- a/tests/test_declarations.py +++ b/tests/test_declarations.py @@ -9,7 +9,6 @@ class DeclarationTests(unittest.TestCase): def test_manifest_matches_actual_catalog(self): manifest = tomllib.loads((ROOT / 'computer-mcp-plugin.toml').read_text()) self.assertEqual(manifest['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.'}]) - self.assertNotIn('sandbox', manifest) self.assertNotIn('host_service_contract', manifest['mcp'][0]) mcp = manifest['mcp'][0] self.assertEqual(mcp['requirements'], {'project': 'write'}) @@ -26,4 +25,13 @@ def test_manifest_matches_actual_catalog(self): 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((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() From 5b6c9a9b08410a4ba64f5bd8965216fe1cf0f479 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:39:14 +0800 Subject: [PATCH 15/29] fix: classify Cursor ACP authentication by RPC code --- bin/cursor-mcp-adapter | 7 +------ computer-mcp-plugin.toml | 2 +- docs/Reference/Interface.md | 10 +++++----- tests/test_adapter.py | 5 +++-- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/bin/cursor-mcp-adapter b/bin/cursor-mcp-adapter index 33ce92e..7a8b03e 100755 --- a/bin/cursor-mcp-adapter +++ b/bin/cursor-mcp-adapter @@ -296,12 +296,7 @@ class Session: settled_rpc_error = kind == 'prompt' and self.managed is not None if method == 'authenticate': hint = 'Run `agent login` in the same Cursor Agent context.' - detail = message['error']['message'] - # Cursor's browser login failures use Invalid Params in the pinned CLI. - if code == ACP_AUTH_REQUIRED or (code == -32602 and ( - detail == 'Login failed or timed out. Please try again.' - or detail.startswith('Failed to open browser for login. Please visit: ') - )): + if code == ACP_AUTH_REQUIRED: raise Failure('authentication_required', f'Cursor sign-in required (RPC code {code}). {hint}') raise Failure('vendor_error', f'Cursor rejected authenticate (RPC code {code}). {hint}') raise Failure('vendor_error',f'Cursor rejected {method} (RPC code {code}); no request was replayed') diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index 8f47e1b..c27c1ef 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -46,7 +46,7 @@ dependency = "cursor-agent" signature = "cursor-vendor-execution.json" [mcp.vendor_execution.files] -"bin/cursor-mcp-adapter" = "3110f1cb6a203f3d2b2d8e7be8b7f8783ac30dd0215eac37b6d7928b353170ac" +"bin/cursor-mcp-adapter" = "ac3e61776722990fe3823ed10b58f30e617733b1f242cefc0c9f20ae20a0a77a" "bin/cursor_vendor_execution.py" = "27478badaaf35e9c2499efdb4858ebeae048e7117b7d07377452b5d7e52bd2b3" "bin/plugin_runtime.py" = "5a9f797bfca4b6ab31a9a648017fb1d09400593a9aab0d2250d426efa51f97cf" "cli-tree.json" = "cc52c0bc7662f93d8596f715625d2ed274d05d95c681bac4d32c0faf273b64a3" diff --git a/docs/Reference/Interface.md b/docs/Reference/Interface.md index 64e30a7..ca45f58 100644 --- a/docs/Reference/Interface.md +++ b/docs/Reference/Interface.md @@ -100,11 +100,11 @@ stdio clients use the local supervisor and select the executable through The adapter initializes ACP and calls `authenticate` with the advertised `cursor_login` method before creating or loading a session. An authentication -RPC rejection stops setup. The adapter reports `authentication_required` when -ACP requires authentication or the pinned Cursor CLI reports that its browser -sign-in could not complete. Other authentication rejections report -`vendor_error`. Both include the original RPC code and a fixed login hint. -[Cursor ACP](https://cursor.com/docs/cli/acp) +RPC rejection stops setup. The adapter reports `authentication_required` for +ACP Authentication Required (`-32000`) and `vendor_error` for other +authentication rejections. Both include the original RPC code and a fixed +login hint. [Cursor ACP](https://cursor.com/docs/cli/acp) · +[ACP error codes](https://agentclientprotocol.com/protocol/v1/schema#errorcode) ## Tools diff --git a/tests/test_adapter.py b/tests/test_adapter.py index 84ec55c..b941d48 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -31,8 +31,8 @@ def test_authentication_rejection_stops_before_native_session_setup(self): cases = [ (-32000, 'fixture-sensitive-message', 'authentication_required'), (-32602, 'Failed to open browser for login. Please visit: https://example.test/fixture-sensitive-url', - 'authentication_required'), - (-32602, 'Unknown authentication method: fixture-sensitive-message', 'vendor_error'), + 'vendor_error'), + (-32603, 'fixture-sensitive-message', 'vendor_error'), ] for rpc_code, message, expected in cases: with self.subTest(rpc_code=rpc_code, expected=expected), tempfile.TemporaryDirectory() as directory: @@ -49,6 +49,7 @@ def test_authentication_rejection_stops_before_native_session_setup(self): self.assertIn(f'RPC code {rpc_code}', error['message']) self.assertIn('Run `agent login` in the same Cursor Agent context.', error['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() From f803ed2a4fdc46ee0c09aeb48cb180ef4492f7d9 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:56:57 +0800 Subject: [PATCH 16/29] test: verify Cursor service access in Host registration --- tests/Fixtures/CursorSourceIntegrationTests.swift.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt index 63af383..1f20987 100644 --- a/tests/Fixtures/CursorSourceIntegrationTests.swift.txt +++ b/tests/Fixtures/CursorSourceIntegrationTests.swift.txt @@ -583,7 +583,10 @@ struct CursorSourceIntegrationTests { try #require(package.manifest.id == "cursor") try #require(package.manifest.permissions?.map(\.id) == [.project]) try #require(package.manifest.permissions?.first?.access == .write) - try #require(package.manifest.sandbox == nil) + 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") From 0f48bb629d82e4e4e019442dd588a2fa8065a87f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:14:20 +0800 Subject: [PATCH 17/29] ci: run consumer checks against the corrected host fixtures --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index f8d746f..7631746 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -f1d29a58573ee97e5bfe7392e9c6852a508a706f +93b228f4ccc628848e7f892f8044f51444bed746 From 2ba842bf4880c09b7b566588400b654a03098ee4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:21:38 +0800 Subject: [PATCH 18/29] fix: limit ACP sign-in hints to authentication required --- README.md | 6 +++--- bin/cursor-mcp-adapter | 5 +++-- computer-mcp-plugin.toml | 4 ++-- docs/Reference/Installation.md | 10 ++++++---- docs/Reference/Interface.md | 14 +++++++------- tests/test_adapter.py | 5 ++++- tests/test_managed_adapter.py | 25 +++++++++++++++++++++---- 7 files changed, 46 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 07ec069..ed9890e 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,9 @@ from `Examples/settings.json`. ## Install -1. Install Cursor Agent and run `agent login` in the vendor context selected for - the plugin. Provide Python 3.13 or newer on the Computer MCP launch `PATH`. - [Cursor CLI authentication](https://cursor.com/docs/cli/reference/authentication) +1. Install Cursor Agent separately. Provide Python 3.13 or newer on the Computer + MCP launch `PATH`. See the [installation guide](docs/Reference/Installation.md#dependencies-and-configuration) + for the sign-in requirements of installed and standalone use. 2. Build the archive: ```sh diff --git a/bin/cursor-mcp-adapter b/bin/cursor-mcp-adapter index 7a8b03e..a5670f7 100755 --- a/bin/cursor-mcp-adapter +++ b/bin/cursor-mcp-adapter @@ -295,10 +295,11 @@ class Session: code = message['error']['code'] settled_rpc_error = kind == 'prompt' and self.managed is not None if method == 'authenticate': - hint = 'Run `agent login` in the same Cursor Agent context.' if code == ACP_AUTH_REQUIRED: + hint = ('Check sign-in for this installed Cursor provider.' if self.managed else + 'Run `agent login` in the standalone Cursor Agent context.') raise Failure('authentication_required', f'Cursor sign-in required (RPC code {code}). {hint}') - raise Failure('vendor_error', f'Cursor rejected authenticate (RPC code {code}). {hint}') + raise Failure('vendor_error', f'Cursor rejected authenticate (RPC code {code}).') raise Failure('vendor_error',f'Cursor rejected {method} (RPC code {code}); no request was replayed') value = message['result'] if not isinstance(value,dict): diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index c27c1ef..70cd5cb 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -8,7 +8,7 @@ description = "Cursor Agent CLI automation plus an ACP-to-MCP adapter." [[dependencies]] id = "cursor-agent" commands = ["agent"] -instructions = "Install Cursor Agent separately and run agent login in the same Cursor Agent context selected for this plugin." +instructions = "Install Cursor Agent separately. The installed provider requires existing Cursor sign-in in its host-provisioned context." documentation = "https://cursor.com/docs/cli/reference/authentication" [[dependencies]] @@ -46,7 +46,7 @@ dependency = "cursor-agent" signature = "cursor-vendor-execution.json" [mcp.vendor_execution.files] -"bin/cursor-mcp-adapter" = "ac3e61776722990fe3823ed10b58f30e617733b1f242cefc0c9f20ae20a0a77a" +"bin/cursor-mcp-adapter" = "8b9e841dc5a0f19b790ab4e42fa280971f9d7465175289ca0d08397bd50deb09" "bin/cursor_vendor_execution.py" = "27478badaaf35e9c2499efdb4858ebeae048e7117b7d07377452b5d7e52bd2b3" "bin/plugin_runtime.py" = "5a9f797bfca4b6ab31a9a648017fb1d09400593a9aab0d2250d426efa51f97cf" "cli-tree.json" = "cc52c0bc7662f93d8596f715625d2ed274d05d95c681bac4d32c0faf273b64a3" diff --git a/docs/Reference/Installation.md b/docs/Reference/Installation.md index 9e310db..81f4bcb 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -4,10 +4,12 @@ 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 Cursor Agent separately. In the vendor context selected for this plugin, -run `agent login` and complete the sign-in in your browser. Cursor manages the -credentials used by that context. The adapter's ACP authentication uses the -existing vendor credentials. [Cursor CLI authentication](https://cursor.com/docs/cli/reference/authentication) +Install Cursor Agent separately. Standalone adapter clients can run `agent login` +in the Cursor Agent context used to launch the adapter and complete sign-in in +the browser. An installed provider requires existing Cursor sign-in in its +host-provisioned context, which has its own HOME, cache and state. The plugin +provides no sign-in flow for an installed provider. +[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. diff --git a/docs/Reference/Interface.md b/docs/Reference/Interface.md index ca45f58..b999e32 100644 --- a/docs/Reference/Interface.md +++ b/docs/Reference/Interface.md @@ -29,11 +29,10 @@ 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 owner initiates browser sign-in via `agent login` in the selected Cursor -Agent context. The plugin network request covers only the agent/API hosts -listed above. Provider HOME, cache and state use host-provisioned persistent -container paths. Temporary storage is execution-local. -[Cursor CLI authentication](https://cursor.com/docs/cli/reference/authentication) +The installed provider uses host-provisioned persistent container paths for +HOME, cache and state. Temporary storage is execution-local. See the +[installation guide](Installation.md#dependencies-and-configuration) for sign-in +requirements. The host selects the worktree, protects unrelated projects, host data and other containers, and retires writers before removal. This adapter does not @@ -102,8 +101,9 @@ The adapter initializes ACP and calls `authenticate` with the advertised `cursor_login` method before creating or loading 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 original RPC code and a fixed -login hint. [Cursor ACP](https://cursor.com/docs/cli/acp) · +authentication rejections. Both include the numeric RPC code and omit the +vendor message and data. Only `authentication_required` includes a sign-in +hint appropriate to installed or standalone use. [Cursor ACP](https://cursor.com/docs/cli/acp) · [ACP error codes](https://agentclientprotocol.com/protocol/v1/schema#errorcode) ## Tools diff --git a/tests/test_adapter.py b/tests/test_adapter.py index b941d48..48b7bb6 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -47,7 +47,10 @@ def test_authentication_rejection_stops_before_native_session_setup(self): error = Client.value(response)['error'] self.assertEqual(error['code'], expected) self.assertIn(f'RPC code {rpc_code}', error['message']) - self.assertIn('Run `agent login` in the same Cursor Agent context.', error['message']) + if rpc_code == -32000: + self.assertIn('Run `agent login` in the standalone Cursor Agent context.', error['message']) + else: + self.assertEqual(error['message'], f'Cursor rejected authenticate (RPC code {rpc_code}).') 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'], []) diff --git a/tests/test_managed_adapter.py b/tests/test_managed_adapter.py index 01f3391..6df27fa 100644 --- a/tests/test_managed_adapter.py +++ b/tests/test_managed_adapter.py @@ -29,10 +29,11 @@ class VendorFixture: """Drive the adapter contract with a local socket and a deterministic ACP peer.""" - def __init__(self, home, answer_error): + def __init__(self, home, answer_error, vendor_env=None): self.socket, self.adapter_socket = socket.socketpair() self.home = home self.answer_error = answer_error + self.vendor_env = {'HOME': str(home), 'CURSOR_SOURCE_FIXTURE': '1', **(vendor_env or {})} self.thread = threading.Thread(target=self.serve, daemon=True) self.vendor = None self.turn = None @@ -74,7 +75,7 @@ def respond(self, request): self.launches += 1 self.vendor = subprocess.Popen( [sys.executable, str(PEER), 'acp'], cwd=self.home, - env={'HOME': str(self.home), 'CURSOR_SOURCE_FIXTURE': '1'}, + env=self.vendor_env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) elif op == 'read': if self.vendor is None: @@ -149,8 +150,8 @@ def setUpClass(cls): def setUp(self): self.home = Path(self.enterContext(tempfile.TemporaryDirectory())) - def managed(self, answer_error, *, transport=False): - host = VendorFixture(self.home, answer_error) + def managed(self, answer_error, *, transport=False, vendor_env=None): + host = VendorFixture(self.home, answer_error, vendor_env) self.addCleanup(host.close) fd = host.adapter_socket.fileno() bootstrap = ( @@ -274,6 +275,22 @@ def event(name, timeout=3): 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). Check sign-in for this installed Cursor provider.', + }) + 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_packaged_standalone_and_missing_managed_negotiation(self): environment = {'HOME': str(self.home), 'PATH': os.environ['PATH'], 'CURSOR_SOURCE_FIXTURE': '1'} missing = subprocess.run( From e297829e9eada575196c91fa00abf1a82056dfa1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:52:41 +0800 Subject: [PATCH 19/29] ci: verify the consumer against the mounted-project fix --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 7631746..a0f9b77 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -93b228f4ccc628848e7f892f8044f51444bed746 +45ac094f2f5f9c2d1c37e67acb59e9975465695e From 3d465204565e593a41736d2cfae873838c032ef8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:26:02 +0800 Subject: [PATCH 20/29] fix: keep sign-in with the vendor --- README.md | 8 +++----- bin/cursor-mcp-adapter | 6 ++---- computer-mcp-plugin.toml | 4 ++-- docs/Reference/Installation.md | 9 ++++----- docs/Reference/Interface.md | 15 ++++++--------- skills/cursor-agent/SKILL.md | 2 +- tests/test_adapter.py | 22 +++++++++------------- tests/test_managed_adapter.py | 2 +- 8 files changed, 28 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index ed9890e..f0f1ce4 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,8 @@ from `Examples/settings.json`. ## Install -1. Install Cursor Agent separately. Provide Python 3.13 or newer on the Computer - MCP launch `PATH`. See the [installation guide](docs/Reference/Installation.md#dependencies-and-configuration) - for the sign-in requirements of installed and standalone use. +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 @@ -97,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 diff --git a/bin/cursor-mcp-adapter b/bin/cursor-mcp-adapter index a5670f7..dc1d2f5 100755 --- a/bin/cursor-mcp-adapter +++ b/bin/cursor-mcp-adapter @@ -296,9 +296,7 @@ class Session: settled_rpc_error = kind == 'prompt' and self.managed is not None if method == 'authenticate': if code == ACP_AUTH_REQUIRED: - hint = ('Check sign-in for this installed Cursor provider.' if self.managed else - 'Run `agent login` in the standalone Cursor Agent context.') - raise Failure('authentication_required', f'Cursor sign-in required (RPC code {code}). {hint}') + raise Failure('authentication_required', f'Cursor sign-in required (RPC code {code}).') raise Failure('vendor_error', f'Cursor rejected authenticate (RPC code {code}).') raise Failure('vendor_error',f'Cursor rejected {method} (RPC code {code}); no request was replayed') value = message['result'] @@ -581,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')), diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index 70cd5cb..7cc5d65 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -8,7 +8,7 @@ description = "Cursor Agent CLI automation plus an ACP-to-MCP adapter." [[dependencies]] id = "cursor-agent" commands = ["agent"] -instructions = "Install Cursor Agent separately. The installed provider requires existing Cursor sign-in in its host-provisioned context." +instructions = "Install Cursor Agent separately and sign in on your computer using Cursor." documentation = "https://cursor.com/docs/cli/reference/authentication" [[dependencies]] @@ -46,7 +46,7 @@ dependency = "cursor-agent" signature = "cursor-vendor-execution.json" [mcp.vendor_execution.files] -"bin/cursor-mcp-adapter" = "8b9e841dc5a0f19b790ab4e42fa280971f9d7465175289ca0d08397bd50deb09" +"bin/cursor-mcp-adapter" = "c2d54c86d558c9abc02062d2235e35435670aa7588206f46b8203de92aa57fa4" "bin/cursor_vendor_execution.py" = "27478badaaf35e9c2499efdb4858ebeae048e7117b7d07377452b5d7e52bd2b3" "bin/plugin_runtime.py" = "5a9f797bfca4b6ab31a9a648017fb1d09400593a9aab0d2250d426efa51f97cf" "cli-tree.json" = "cc52c0bc7662f93d8596f715625d2ed274d05d95c681bac4d32c0faf273b64a3" diff --git a/docs/Reference/Installation.md b/docs/Reference/Installation.md index 81f4bcb..a18ad57 100644 --- a/docs/Reference/Installation.md +++ b/docs/Reference/Installation.md @@ -4,11 +4,10 @@ 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 Cursor Agent separately. Standalone adapter clients can run `agent login` -in the Cursor Agent context used to launch the adapter and complete sign-in in -the browser. An installed provider requires existing Cursor sign-in in its -host-provisioned context, which has its own HOME, cache and state. The plugin -provides no sign-in flow for an installed provider. +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` diff --git a/docs/Reference/Interface.md b/docs/Reference/Interface.md index b999e32..d2bf965 100644 --- a/docs/Reference/Interface.md +++ b/docs/Reference/Interface.md @@ -30,9 +30,7 @@ hosts are excluded and Full access defaults to off. [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. See the -[installation guide](Installation.md#dependencies-and-configuration) for sign-in -requirements. +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 @@ -98,12 +96,11 @@ 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 before creating or loading 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. Only `authentication_required` includes a sign-in -hint appropriate to installed or standalone use. [Cursor ACP](https://cursor.com/docs/cli/acp) · +`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 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/test_adapter.py b/tests/test_adapter.py index 48b7bb6..98f70b4 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -29,28 +29,24 @@ def test_acp_prompt_through_mcp(self): 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'), + (-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'), - (-32603, 'fixture-sensitive-message', 'vendor_error'), + 'vendor_error', 'Cursor rejected authenticate (RPC code -32602).'), + (-32603, 'fixture-sensitive-message', 'vendor_error', + 'Cursor rejected authenticate (RPC code -32603).'), ] - for rpc_code, message, expected in cases: - with self.subTest(rpc_code=rpc_code, expected=expected), tempfile.TemporaryDirectory() as directory: + 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': message, + 'FIXTURE_AUTH_ERROR_MESSAGE': vendor_message, }) try: response = client.call('cursor.acp.session.open') self.assertTrue(response['result']['isError']) - error = Client.value(response)['error'] - self.assertEqual(error['code'], expected) - self.assertIn(f'RPC code {rpc_code}', error['message']) - if rpc_code == -32000: - self.assertIn('Run `agent login` in the standalone Cursor Agent context.', error['message']) - else: - self.assertEqual(error['message'], f'Cursor rejected authenticate (RPC code {rpc_code}).') + 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'], []) diff --git a/tests/test_managed_adapter.py b/tests/test_managed_adapter.py index 6df27fa..53eadd3 100644 --- a/tests/test_managed_adapter.py +++ b/tests/test_managed_adapter.py @@ -284,7 +284,7 @@ def test_managed_authentication_required_stops_before_session_load(self): self.assertTrue(response['result']['isError']) self.assertEqual(Client.value(response)['error'], { 'code': 'authentication_required', - 'message': 'Cursor sign-in required (RPC code -32000). Check sign-in for this installed Cursor provider.', + 'message': 'Cursor sign-in required (RPC code -32000).', }) self.assertNotIn('fixture-sensitive', json.dumps(response)) self.assertFalse((self.home / 'cursor-native-starts.jsonl').exists()) From 2afb37c21b75ffa9572ffec0ea57b1a3d5768bf3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:05:35 +0800 Subject: [PATCH 21/29] ci: validate against the integrated Host candidate --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index a0f9b77..4d53469 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -45ac094f2f5f9c2d1c37e67acb59e9975465695e +feafb1088e88e45563a95bbf9a996998d2fa7180 From ba4f8c344364742b95734deb41d50c2f01e9fbee Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:24:41 +0800 Subject: [PATCH 22/29] ci: test against the reviewed Host revision --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 4d53469..da31c2d 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -feafb1088e88e45563a95bbf9a996998d2fa7180 +a34a17ca6ec24d8810002deb224a6d2e469ff282 From b2c0c170e26ddd0eac891d6f4c56cea49c5aabc0 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:31:12 +0800 Subject: [PATCH 23/29] ci: verify against the updated host diagnostics contract --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index da31c2d..cb42063 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -a34a17ca6ec24d8810002deb224a6d2e469ff282 +504d1d434a192a2d7c4595f8888ebb63f728f228 From ab36e7453d69abfd82570c21f90a12b63a445179 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:40:42 +0800 Subject: [PATCH 24/29] ci: pin Host for integrated candidate checks --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index cb42063..1614582 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -504d1d434a192a2d7c4595f8888ebb63f728f228 +d73d6b522520896fc041a22bb30fe04f4f81beaf From 8ebbb42a11b103bf44554b61473950c077515fbe Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:36:08 +0800 Subject: [PATCH 25/29] ci: allow more time for the Cursor source suite --- .github/workflows/ci.yml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5938aaf..83743db 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,9 +57,15 @@ jobs: strategy: fail-fast: false matrix: - suite: [source, vendor-stop] + include: + - suite: source + swift-timeout-seconds: 1800 + job-timeout-minutes: 35 + - suite: vendor-stop + swift-timeout-seconds: 1200 + job-timeout-minutes: 25 runs-on: macos-latest - timeout-minutes: 25 + timeout-minutes: ${{ matrix.job-timeout-minutes }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -73,6 +79,7 @@ jobs: env: PLUGIN_SHA: ${{ github.sha }} SUITE: ${{ matrix.suite }} + SWIFT_TIMEOUT_SECONDS: ${{ matrix.swift-timeout-seconds }} GIT_TERMINAL_PROMPT: '0' GIT_ASKPASS: /usr/bin/false GIT_CONFIG_GLOBAL: /dev/null @@ -91,7 +98,7 @@ jobs: python3 -B scripts/validate_host_source.py --suite "$SUITE" \ --host-source "$host_source" --host-sha "$host_sha" \ --plugin-source "$PWD" --plugin-sha "$PLUGIN_SHA" \ - --output "$RUNNER_TEMP/host-consumer" --timeout 1200 + --output "$RUNNER_TEMP/host-consumer" --timeout "$SWIFT_TIMEOUT_SECONDS" - name: Retain consumer evidence if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 From f6a35b857ba8e7f2ac0cf354bcdb9cf77bcd55b3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:03:27 +0800 Subject: [PATCH 26/29] ci: verify against the parallel Host candidate --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 1614582..d42a787 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -d73d6b522520896fc041a22bb30fe04f4f81beaf +c2a81115dee819122c7368bd266bc74136011ceb From bbddefa0ab6ef49f3c988d77a87efd38247251f6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:20:14 +0800 Subject: [PATCH 27/29] ci: verify the accepted Host candidate --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index d42a787..44dda92 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -c2a81115dee819122c7368bd266bc74136011ceb +bb0c029778a7d5e44670606abfc2261f841beea7 From 54a21c552c396421b809feca9704dea81eb9566a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:16:40 +0800 Subject: [PATCH 28/29] docs: prepare 0.1.0 release notes --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) 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. From cac39d52581e307a429c5c66f159bd7169e814be Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:09 +0800 Subject: [PATCH 29/29] ci: pin Computer MCP 0.1.0 for plugin validation --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 44dda92..58d2856 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -bb0c029778a7d5e44670606abfc2261f841beea7 +bee91275a6301e56c64f677125f5d7f38ba7fe0e