From 69b9f212dd6ba234c10447a22439caffd06749d8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:55:13 +0800 Subject: [PATCH 01/16] perf: shorten Codex consumer validation --- .../CodexAppServerRuntimeTests.swift | 17 ++-- Tests/test_host_acceptance.py | 53 +++++++++++ scripts/check-host.py | 88 +++++++++++++------ 3 files changed, 122 insertions(+), 36 deletions(-) diff --git a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift index f6cb21c..7fb7ec8 100644 --- a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift @@ -561,9 +561,8 @@ final class CodexAppServerRuntimeTests { func testConcurrentRequestsRemainRunningUntilEveryRequestCompletes() async throws { let fixture = try AppServerProcessFixture() defer { fixture.remove() } - try Data().write(to: fixture.delayLoadedThreadsFile) - // Keep the retry boundary above the fixture's two serialized one-second replies; - // this test observes request accounting rather than timeout retirement. + try Data().write(to: fixture.holdLoadedThreadsFile) + defer { try? FileManager.default.removeItem(at: fixture.holdLoadedThreadsFile) } let runtime = fixture.makeRuntime(requestTimeoutSeconds: 10) async let first = runtime.call(method: "thread/loaded/list", params: .object([:])) @@ -578,6 +577,7 @@ final class CodexAppServerRuntimeTests { let concurrentStatus = await runtime.status().objectValue #expect(concurrentStatus?["current_request_state"] == .string("running")) #expect(concurrentStatus?["current_request_count"] == .number(2)) + try FileManager.default.removeItem(at: fixture.holdLoadedThreadsFile) _ = try await (first, second) let completedStatus = await runtime.status().objectValue #expect(completedStatus?["current_request_state"] == .string("idle")) @@ -722,9 +722,8 @@ final class CodexAppServerRuntimeTests { try await runtime.approvals(state: CodexApprovalState.pending.rawValue, limit: 10) .objectValue?["approvals"] == .array([]) ) - _ = await requestTask.value - await runtime.shutdown() + _ = await requestTask.value } @Test @@ -1523,7 +1522,7 @@ struct AppServerProcessFixture { let hangRequestReceivedFile: URL let hangTurnStartFile: URL let hangInitializeFile: URL - let delayLoadedThreadsFile: URL + let holdLoadedThreadsFile: URL let approvalRequestFile: URL let approvalResponseLog: URL let closeInputAfterApprovalRequestFile: URL @@ -1542,7 +1541,7 @@ struct AppServerProcessFixture { hangRequestReceivedFile = directory.appendingPathComponent("hang-request-received") hangTurnStartFile = directory.appendingPathComponent("hang-turn-start") hangInitializeFile = directory.appendingPathComponent("hang-initialize") - delayLoadedThreadsFile = directory.appendingPathComponent("delay-loaded-threads") + holdLoadedThreadsFile = directory.appendingPathComponent("hold-loaded-threads") approvalRequestFile = directory.appendingPathComponent("approval-request.json") approvalResponseLog = directory.appendingPathComponent("approval-response.log") closeInputAfterApprovalRequestFile = directory.appendingPathComponent( @@ -1639,9 +1638,7 @@ struct AppServerProcessFixture { : > "$fixture_dir/hang-request-received" continue fi - if [ -f "$fixture_dir/delay-loaded-threads" ]; then - /bin/sleep 1 - fi + while [ -f "$fixture_dir/hold-loaded-threads" ]; do /bin/sleep 0.01; done if [ -f "$fixture_dir/loaded-threads.json" ]; then loaded=$(/bin/cat "$fixture_dir/loaded-threads.json") else diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index b271613..74f26ac 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -7,6 +7,7 @@ from pathlib import Path import subprocess import tempfile +import threading from types import SimpleNamespace import unittest from unittest.mock import Mock, call, patch @@ -203,6 +204,58 @@ def cleanup(): else: self.assertNotIn("last_tool_call", report) + def test_registered_cases_overlap_in_private_roots_and_report_the_failing_call(self): + options = acceptance.parse_arguments(self.container_arguments("a" * 40)) + fixture = acceptance.Fixture(options) + scoped_started = threading.Event() + restart_started = threading.Event() + calls = { + "catalog_permissions": "catalog", + "plugin_use_permissions": "plugin-use", + "cold_catalog_and_reads": "cold", + "callbacks_disabled": "callbacks-disabled", + "wildcard_fallback": "wildcard", + } + + def finish(case): + self.assertEqual(case.root.parent, fixture.root / "registered-scenarios") + self.assertEqual(case.environment["HOME"], str(case.root)) + self.assertEqual(case.projects["primary"], case.root / "primary") + case.steps.append(case.root.name) + + def scoped(case): + scoped_started.set() + self.assertTrue(restart_started.wait(5)) + case.last_tool_call = {"tool": "codex.worktree.managed.read", "project_id": "primary"} + raise RuntimeError("observation failed") + + def restart(): + restart_started.set() + self.assertTrue(scoped_started.wait(5)) + fixture.steps.append("restart") + + def select(case): + self.assertEqual(case.project_count, int(case.root.name == "single-project")) + finish(case) + + with contextlib.ExitStack() as stack: + for check in calls: + stack.enter_context(patch.object(acceptance.Fixture, check, finish)) + setup = stack.enter_context(patch.object(acceptance.Fixture, "setup", autospec=True)) + cleanup = stack.enter_context(patch.object(acceptance.Fixture, "cleanup", autospec=True, return_value=[])) + stack.enter_context(patch.object(acceptance.Fixture, "scoped_worktree_permissions", scoped)) + stack.enter_context(patch.object(acceptance.Fixture, "project_selection", select)) + stack.enter_context(patch.object(fixture, "registered_restart_and_revocation", restart)) + with self.assertRaisesRegex(RuntimeError, "^scoped: observation failed$"): + fixture.registered_container() + expected = {*calls.values(), "single-project", "no-project", "scoped"} + self.assertEqual({args[0].root.name for args, _ in setup.call_args_list}, expected) + self.assertEqual({args[0].root.name for args, _ in cleanup.call_args_list}, expected) + self.assertCountEqual(fixture.steps, (expected - {"scoped"}) | {"restart"}) + self.assertEqual(fixture.last_tool_call, { + "tool": "codex.worktree.managed.read", "project_id": "primary", + }) + def test_directory_errors_with_expected_cwd_stop_before_apps(self): fixture = acceptance.Fixture(acceptance.parse_arguments(self.arguments + ["--mode", "fixture"])) cwd = str(fixture.root / "primary") diff --git a/scripts/check-host.py b/scripts/check-host.py index efea077..6088c2b 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -9,6 +9,7 @@ """ import argparse +from concurrent.futures import ThreadPoolExecutor from contextlib import closing import hashlib import json @@ -35,6 +36,7 @@ MANIFEST = REPOSITORY / "computer-mcp-plugin.toml" ADAPTER_PATH = Path("bin/codex-mcp-adapter") MAX_MESSAGE = 8_388_608 +STEP_OUTPUT_LOCK = threading.Lock() def require(condition, detail): @@ -166,6 +168,7 @@ def prepare_pinned_host(options): dependencies: [ "ComputerMCPConfiguration", "ComputerMCPCore", "ComputerMCPGateway", "ComputerMCPMacOS", "ComputerMCPPermissions", "ComputerMCPPlatform", "ComputerMCPPlugins", "ComputerMCPTransport", + "computer-mcp-execution-bootstrap", .product(name: "MCP", package: "swift-sdk"), ], path: "Tests/CodexRegisteredHost" @@ -181,14 +184,12 @@ def prepare_pinned_host(options): options.adapter = executable(str(options.package / ADAPTER_PATH)) build = ["/usr/bin/swift", "build", "--package-path", str(source), "--build-system", "native", "--disable-swift-testing", "--disable-automatic-resolution"] - products = ("CodexRegisteredHost", "computer-mcp-execution-bootstrap") lock = (source / "Package.resolved").read_bytes() - for product in products: - subprocess.run([*build, "--product", product], check=True) + subprocess.run([*build, "--product", "CodexRegisteredHost"], check=True) require((source / "Package.resolved").read_bytes() == lock, "Host dependency lock changed") binary_directory = Path(subprocess.check_output([*build, "--show-bin-path"], text=True).strip()) - options.host = executable(str(binary_directory / products[0])) - bootstrap = executable(str(binary_directory / products[1])) + options.host = executable(str(binary_directory / "CodexRegisteredHost")) + bootstrap = executable(str(binary_directory / "computer-mcp-execution-bootstrap")) options.output_directory = stage / "runtime" return {"host_revision": host_revision, "plugin_revision": plugin_revision, "archive": archive, "execution_bootstrap_sha256": digest(bootstrap)} @@ -496,7 +497,7 @@ def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None, downstream_catalog = self.project_catalog() # An unbound multi-project connection resolves direct names in the # requested project's registry even when the global catalog omits them. - self.catalog = downstream_catalog if indirect else downstream_catalog | self.client.list_tools() + self.catalog = downstream_catalog if indirect else downstream_catalog | gateway_catalog require(set(fixture.risks) <= self.catalog.keys(), {"missing_tools": sorted(set(fixture.risks) - self.catalog.keys())}) require(gateway_catalog["mcp.tools.call"]["inputSchema"]["properties"]["project_id"]["type"] == "string", @@ -840,7 +841,8 @@ def thread(self, host, params=None): def record(self, name): self.steps.append(name) - print(json.dumps({"passed": name}), flush=True) + with STEP_OUTPUT_LOCK: + print(json.dumps({"passed": name}), flush=True) def catalog_and_diagnostics(self): host = Host(self) @@ -1499,13 +1501,22 @@ def remove_worktree(self, host, worktree, parent): if not reply_lost: removed = unwrap(response, indirect=True) host.select_project("primary") + writers = [peer["pid"], *child_pids[:2]] + source_observed_after_exit = False + + def writers_exited(): + return all(exited(pid) for pid in writers) + if reply_lost: removal_id = None def observe_removal(): - nonlocal removal_id + nonlocal removal_id, source_observed_after_exit + # Only a read started after writer exit can also serve as the final source readback. + stopped = writers_exited() observation = host.raw("codex.worktree.managed.read", selector, gateway_envelope=True) removal_id, completed = observe_worktree_removal(observation, worktree_id, project, removal_id) + source_observed_after_exit = stopped and completed is not None return completed removed = wait_until(observe_removal, self.options.timeout_seconds, "Host removal observation") @@ -1516,10 +1527,10 @@ def observe_removal(): require(operation["project_id"] == project and operation["result"]["oid"] == tip and operation["result"]["worktree_id"] == worktree["resolved"]["worktree_id"], operation) require(not path.exists(), f"Host still has the removed checkout: {path}") - wait_until(lambda: all(exited(pid) for pid in [peer["pid"], *child_pids[:2]]), 15, - "Removed worktree still has its vendor or supervisor") - source = host.call("codex.worktree.managed.read", selector) - require(source["state"] == "removed" and source["operation_id"] == removed["operation_id"], source) + wait_until(writers_exited, 15, "Removed worktree still has its vendor or supervisor") + if not source_observed_after_exit: + source = host.call("codex.worktree.managed.read", selector) + require(source["state"] == "removed" and source["operation_id"] == removed["operation_id"], source) recovery = self.root / "worktree-recovery" repositories = [entry.parent for entry in recovery.rglob("HEAD") if (entry.parent / "objects").is_dir()] require(any(subprocess.run( @@ -1604,27 +1615,52 @@ def registered_revocation(self, caller, worktree): self.record("caller-revocation-isolated-and-durable-provider-revocation-terminated-peer") def registered_container(self): - self.catalog_permissions() - self.scoped_worktree_permissions() - for name, check, settings in ( + cases = ( + ("scoped", "scoped_worktree_permissions", {}), + ("catalog", "catalog_permissions", {}), ("plugin-use", "plugin_use_permissions", {}), ("cold", "cold_catalog_and_reads", {}), ("single-project", "project_selection", {"project_count": 1}), ("no-project", "project_selection", {"project_count": 0}), ("callbacks-disabled", "callbacks_disabled", {"host_services": False}), ("wildcard", "wildcard_fallback", {"wildcard": True}), - ): - options = SimpleNamespace(**vars(self.options)) - options.output_directory = self.root / "registered-scenarios" / name - scenario = Fixture(options, **settings) - scenario.steps = self.steps + ) + # Each case owns a Host database, authorization state, Git repositories and processes. + failure = None + with ThreadPoolExecutor(max_workers=3) as executor: + pending = [ + (name, executor.submit(self.registered_scenario, name, check, settings)) + for name, check, settings in cases + ] try: - scenario.setup() - getattr(scenario, check)() - finally: - self.last_tool_call = scenario.last_tool_call - require(not (errors := scenario.cleanup()), errors) - self.registered_restart_and_revocation() + self.registered_restart_and_revocation() + except Exception as error: + failure = error + for name, future in pending: + steps, last_tool_call, error, cleanup_errors = future.result() + self.steps.extend(steps) + if failure is None and (error or cleanup_errors): + self.last_tool_call = last_tool_call + detail = f"{name}: {error}" if error else name + if cleanup_errors: + detail += f" (cleanup: {cleanup_errors})" + failure = RuntimeError(detail) + if failure is not None: + raise failure + + def registered_scenario(self, name, check, settings): + options = SimpleNamespace(**vars(self.options)) + options.output_directory = self.root / "registered-scenarios" / name + scenario = Fixture(options, **settings) + failure = None + try: + scenario.setup() + getattr(scenario, check)() + except Exception as error: + failure = error + finally: + cleanup_errors = scenario.cleanup() + return scenario.steps, scenario.last_tool_call, failure, cleanup_errors def registered_restart_and_revocation(self): marker = "caller project fixture\n" From 83d4df38bc5cfc9a79ad5687ca92d863146f4f5f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:38:24 +0800 Subject: [PATCH 02/16] test: separate packaged adapter checks from Host interop --- .github/workflows/ci.yml | 90 ++--- CONTRIBUTING.md | 23 +- Documentation/Reference/Release.md | 24 +- .../CodexManagedWorktreeTests.swift | 65 ++-- Tests/PackagedAdapter.py | 328 ++++++++++++++++++ Tests/test_host_acceptance.py | 3 +- scripts/check-host.py | 203 +---------- scripts/mcp_client.py | 82 +++++ scripts/test.sh | 27 ++ 9 files changed, 547 insertions(+), 298 deletions(-) create mode 100644 Tests/PackagedAdapter.py create mode 100644 scripts/mcp_client.py create mode 100755 scripts/test.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 03fce09..7a54979 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,8 @@ jobs: package: runs-on: macos-latest timeout-minutes: 60 + outputs: + interop: ${{ steps.interop.outputs.required }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -24,50 +26,57 @@ jobs: python-version: '3.13' - name: Install dependency gate tooling run: brew install jq ripgrep - - name: Validate Swift package + - name: Validate and package the plugin env: BASE_COMMIT: ${{ github.event.pull_request.base.sha || github.event.before }} run: | - python3 scripts/version.py check if [[ "$BASE_COMMIT" =~ ^[0-9a-f]{40}$ && "$BASE_COMMIT" != 0000000000000000000000000000000000000000 ]]; then python3 scripts/version.py check --base "$BASE_COMMIT" fi - /usr/bin/swift --version - /usr/bin/swift package resolve - git diff --exit-code -- Package.resolved - scripts/verify-swift-codex-release-gate.sh - node --test Tests/schema-import.test.mjs - node scripts/import-schema.mjs --check - /usr/bin/swift format lint --strict --recursive Package.swift Sources Tests - /usr/bin/swift build --build-tests --disable-automatic-resolution - - name: Run Swift tests - timeout-minutes: 10 + scripts/test.sh dist + - name: Determine whether exact-pair interop is required + id: interop + env: + PR_BASE: ${{ github.event.pull_request.base.sha }} run: | - /usr/bin/sw_vers - /usr/sbin/sysctl -n hw.logicalcpu - /usr/bin/swift test --skip-build --disable-automatic-resolution --no-parallel & - test_pid=$! - for ((elapsed = 0; elapsed < 60; elapsed++)); do - if ! /bin/kill -0 "$test_pid" 2>/dev/null; then break; fi - /bin/sleep 1 - done - if /bin/kill -0 "$test_pid" 2>/dev/null; then - /bin/ps -p "$test_pid" -o pid=,ppid=,etime=,comm= || true - for process_id in $(/usr/bin/pgrep -P "$test_pid" || true); do - process_command=$(/bin/ps -p "$process_id" -o comm= || true) - case "$process_command" in - *swiftpm-testing*) /usr/bin/sample "$process_id" 1 || true ;; + required=true + if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then + required=false + git diff --no-renames --name-only -z "$PR_BASE" "$GITHUB_SHA" > .build/interop-paths + while IFS= read -r -d '' path; do + case "$path" in + Documentation/*|README.md|CONTRIBUTING.md|CHANGELOG.md) ;; + *) required=true; break ;; esac - done + done < .build/interop-paths fi - wait "$test_pid" - - name: Validate package ownership and publication - run: | - python3 scripts/check-host.py --help - python3 -m unittest discover -s Tests -p 'test_*.py' -v - python3 scripts/check-workflow.py --check-release-workflow - - name: Build relocatable adapter and receipt - run: python3 scripts/package.py --output dist --configuration release + echo "Exact-pair interop required: $required" + echo "required=$required" >> "$GITHUB_OUTPUT" + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: codex-plugin-macos-arm64-${{ github.sha }} + path: | + dist/codex-plugin-macos-arm64.zip + dist/receipt.json + if-no-files-found: error + retention-days: 14 + + interop: + needs: package + if: needs.package.outputs.interop == 'true' + runs-on: macos-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + with: + python-version: '3.13' + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: codex-plugin-macos-arm64-${{ github.sha }} + path: dist - name: Accept the release archive against the pinned Host source run: | host_revision=$(cat .github/computer-mcp-host.sha) @@ -86,18 +95,11 @@ jobs: if [[ -f "$report" ]]; then cat "$report" fi - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: codex-plugin-macos-arm64-${{ github.sha }} - path: | - dist/codex-plugin-macos-arm64.zip - dist/receipt.json - if-no-files-found: error - retention-days: 14 validate: if: always() - needs: [package] + needs: [package, interop] uses: computer-mcp/github-workflows/.github/workflows/result.yml@fd25fcface41732fda099017c6945912366fc7c1 with: needs-json: ${{ toJSON(needs) }} + optional-jobs: ${{ needs.package.outputs.interop == 'false' && '["interop"]' || '[]' }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 66bb202..50782b9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,25 +6,18 @@ external dependencies and credentials. ## Validation -CI runs these checks on macOS; run them before opening a pull request. They need -Node.js, `jq` and `ripgrep`: +Run the same macOS plugin suite as CI before opening a pull request. It needs +Swift, Python 3.12 or newer, Node.js, `jq` and `ripgrep`. ```sh -python3 scripts/version.py check -swift package resolve && git diff --exit-code -- Package.resolved -scripts/verify-swift-codex-release-gate.sh -node --test Tests/schema-import.test.mjs -node scripts/import-schema.mjs --check -swift format lint --strict --recursive Package.swift Sources Tests -swift build --build-tests --disable-automatic-resolution -swift test --skip-build --disable-automatic-resolution --no-parallel -python3 -m unittest discover -s Tests -p 'test_*.py' -python3 scripts/package.py --output OUTPUT_DIRECTORY --configuration release +scripts/test.sh .build/plugin-validation ``` -Exercise help, valid input and invalid input -from outside the checkout. Keep command output contracts and generated resources -covered by tests. +Use a new output directory for each run. The suite builds a release ZIP, +verifies its receipt, and exercises the relocated adapter over MCP with private +Host-service and vendor fixtures. It needs no installed Host or vendor account. +Use [the exact-pair gate](Documentation/Reference/Release.md#runtime-acceptance) +when changing the Host-facing contract or implementation. ## Documentation diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index 96291f9..dcbfc50 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -89,17 +89,25 @@ checks the relocated bytes before runtime acceptance. ## Candidate, Acceptance and Publication -CI runs source checks and `scripts/package.py`, then verifies and relocates the -archive with `scripts/check-package.py`. It uploads the ZIP and native build -receipt as the commit-named candidate artifact. `release.yml` promotes those -accepted CI bytes and receipts without rebuilding. Verification, publication -and catalog notification are separate jobs. +The CI package job runs `scripts/test.sh dist`. This is the same suite +contributors run locally. It checks the source, builds and verifies the release +ZIP and receipt, then exercises the relocated manifest's stdio contribution +with a deterministic App Server and an inherited Host-service MCP fixture. +These cases cover cold discovery, scoped storage, historical migration, lazy +approval recovery, and startup and shutdown of an owned vendor process. + +The package job uploads the release ZIP and native receipt as the commit-named +candidate artifact. The interop job downloads those same bytes. It runs on +default-branch pushes, workflow dispatches and pull requests with changes +outside the documentation files. A successful default-branch CI run requires +both jobs. `release.yml` promotes those accepted bytes and receipts without +rebuilding. Verification, publication and catalog notification are separate jobs. ### Runtime acceptance -Use macOS, Swift, Python 3.12 or newer and Git. CI builds the release archive -and runs registered Host acceptance before it uploads the candidate. To run -the same check locally, use a clean Computer MCP checkout at the full commit +Use macOS, Swift, Python 3.12 or newer and Git. CI's interop job exercises +the release archive through registered Host acceptance. To run the same check +locally, use a clean Computer MCP checkout at the full commit in [the Host pin](../../.github/computer-mcp-host.sha), a clean plugin checkout, and the ZIP and receipt from that plugin candidate: diff --git a/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift b/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift index 9362440..e43d430 100644 --- a/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift +++ b/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift @@ -215,35 +215,40 @@ struct CodexManagedWorktreeTests { let leaseID = try #require(created["lease"]?.objectValue?["lease_id"]?.stringValue) let lease = try #require(try fixture.child.codexWorktreeLease(id: leaseID)) try fixture.release(lease, in: fixture.child) - #expect(throws: CodexManagedWorktreeError.self) { - try fixture.manager.planRemoval(id: id, force: true) - } - let plan = try fixture.childManager.planRemoval(id: id, force: true) - let arguments = try #require(plan.objectValue?["perform_arguments"]?.objectValue) - let revision = try #require(arguments["expected_revision"]?.intValue) + let selector: [String: JSONValue] = ["managed_worktree_id": .string(id)] + let planInputs = selector.merging(["force": .bool(true)]) { _, force in force } let ids = newIDs() - var changed = arguments - changed["force"] = .bool(false) - await #expect(throws: CodexManagedWorktreeError.self) { - try await fixture.childManager.perform( - id: id, action: .remove, revision: revision, arguments: changed, invocation: metadata(ids)) + try await withMCPClient(fixture.provider()) { client in + let refused = try await call(client, "codex.worktree.remove.plan", planInputs) + #expect(refused.isError == true) } - #expect(throws: CodexWorktreeLeaseError.self) { - try fixture.acquire( - in: fixture.child, scope: fixture.childScope, agent: "racer", parent: fixture.parent.id) + try await withMCPClient(fixture.provider(child: true)) { client in + let plan = try result(await call(client, "codex.worktree.remove.plan", planInputs)) + let arguments = try #require(plan["perform_arguments"]?.objectValue) + var changed = arguments + changed["force"] = .bool(false) + let altered = try await call(client, "codex.worktree.remove.perform", changed, ids: ids) + #expect(altered.isError == true) + let competing = try await call( + client, "codex.worktree.leases.acquire", + [ + "agent_id": .string("racer"), "parent_lease_id": .string(fixture.parent.id), + "mode": .string("isolated_worktree"), + ]) + #expect(competing.isError == true) + await fixture.host.capture(try CodexHostInvocation.digest(arguments), action: .remove) + await fixture.host.loseNextRemovalReply() + let removal = try await call(client, "codex.worktree.remove.perform", arguments, ids: ids) + #expect(removal.isError == true) + let pending = try result(removal) + #expect(pending["state"] == .string("removing")) + #expect(pending["operation_id"] == .string(ids.operationID.uuidString)) + } + try await withMCPClient(fixture.provider()) { client in + let settled = try result(await call(client, "codex.worktree.managed.read", selector)) + #expect(settled["state"] == .string("removed")) + #expect(settled["operation_id"] == .string(ids.operationID.uuidString)) } - let digest = try CodexHostInvocation.digest(arguments) - await fixture.host.capture(digest, action: .remove) - await fixture.host.loseNextRemovalReply() - let removal = try await fixture.childManager.perform( - id: id, action: .remove, revision: revision, arguments: arguments, invocation: metadata(ids)) - #expect(removal.isError == true) - #expect(try result(removal)["state"] == .string("removing")) - let recovered = try #require(try fixture.source.hostWorktree(id: id, in: fixture.sourceScope)) - #expect(recovered.1?.ids == ids) - let settled = try result(await fixture.manager.read(recovered.0, operation: recovered.1)) - #expect(settled["state"] == .string("removed")) - #expect(settled["operation_id"] == .string(ids.operationID.uuidString)) #expect( await fixture.host.callbacks.suffix(3) == [ "inspect-invocation", "remove", "inspect-operation", @@ -311,10 +316,12 @@ private final class WorktreeFixture: Sendable { worktreeOwner(project: project, principal: principal) } - func provider() -> CodexAppServerProvider { + func provider(child: Bool = false) -> CodexAppServerProvider { .init( - appServer: FakeAppServerRuntime(), owner: owner(project: "source"), database: source, - workspaceURL: root, recentThreadReader: nil, localControlAllowed: true, projectServices: host) + appServer: FakeAppServerRuntime(), owner: owner(project: child ? "child" : "source"), + database: child ? self.child : source, + workspaceURL: child ? URL(fileURLWithPath: childPath) : root, + recentThreadReader: nil, localControlAllowed: true, projectServices: host) } func plan() throws -> (String, [String: JSONValue]) { diff --git a/Tests/PackagedAdapter.py b/Tests/PackagedAdapter.py new file mode 100644 index 0000000..6fb4dde --- /dev/null +++ b/Tests/PackagedAdapter.py @@ -0,0 +1,328 @@ +"""Exercise the relocated release adapter at its MCP, Host-service and vendor boundaries.""" + +from contextlib import closing, contextmanager +import errno +import hashlib +import json +import os +from pathlib import Path +import shlex +import shutil +import socket +import sqlite3 +import subprocess +import sys +import threading +import tomllib +import uuid + +REPOSITORY = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPOSITORY / "scripts")) +from mcp_client import MCPClient, require + + +class PackagedAdapter: + def __init__(self, root, executable, contract): + self.root, self.executable, self.contract = root, executable, contract + self.workspace = self.root / "workspace" + home = self.root / "home" + self.vendor_home = home / ".codex" + self.state = self.root / "state" + for directory in (self.workspace, self.vendor_home, self.state): + directory.mkdir(parents=True, mode=0o700) + self.environment = {"HOME": str(home), "PATH": "/usr/bin:/bin", "XDG_STATE_HOME": str(self.state)} + vendor = self.root / "vendor" + vendor.write_text("#!/bin/sh\nexec " + shlex.join([sys.executable, __file__]) + ' "$@"\n') + vendor.chmod(0o700) + self.config = self.root / "adapter.json" + self.config.write_text(json.dumps({ + "enabled": True, "app_server_enabled": True, "exec_enabled": False, "executable": str(vendor), + })) + self.generation = 0 + + @contextmanager + def connect(self, *, alternate=False): + principal = "package-codex-alternate" if alternate else "package-codex-fixture" + owner = {"project_id": "primary", "profile_id": "acceptance", "caller": "local-mcp", + "principal_id": principal} + host_context = { + "formatVersion": 1, "hostServiceContract": self.contract, "runtimeID": str(uuid.uuid4()), + "caller": owner["caller"], "profileID": owner["profile_id"], "principalID": principal, + "project": {"id": owner["project_id"], "rootPath": str(self.workspace)}, + } + self.generation += 1 + stem = self.root / f"adapter-{self.generation}" + errors = [] + expected_inventory = [] + + def host_service(stream): + try: + for line in stream: + request = json.loads(line) + method = request["method"] + params = request.get("params", {}) + if method == "notifications/initialized": + continue + if method == "initialize": + result = { + "protocolVersion": params["protocolVersion"], + "serverInfo": {"name": "fixture-host-service", "version": "1"}, + "capabilities": {"tools": {}, "experimental": { + "io.github.computer-mcp/host-service-contract": self.contract, + }}, + } + else: + require(method == "tools/call", request) + arguments = params["arguments"] + if params["name"] == "host.diagnostics.snapshot": + require(arguments["limit"] > 0, request) + value = {"owner": owner, "recent_tool_audits": []} + else: + require(params["name"] == "host.projects.worktree_list" + and uuid.UUID(arguments["invocation_id"]) == expected_inventory.pop(0), request) + value = {"worktrees": []} + result = {"content": [], "structuredContent": {"result": value}, "isError": False} + response = {"jsonrpc": "2.0", "id": request["id"], "result": result} + stream.write(json.dumps(response).encode() + b"\n") + stream.flush() + except Exception as error: + errors.append(error) + + peer, inherited = socket.socketpair() + with peer, inherited, stem.with_suffix(".log").open("w+") as stderr, \ + stem.with_suffix(".jsonl").open("w") as evidence: + fd = inherited.fileno() + require(3 <= fd <= 9, "Fixture requires a Host descriptor between 3 and 9") + environment = self.environment | {"COMPUTER_MCP_HOST_CONTEXT": json.dumps(host_context), + "COMPUTER_MCP_HOST_FD": str(fd)} + with subprocess.Popen( + [str(self.executable), "--config", str(self.config)], cwd=self.workspace, env=environment, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, text=True, pass_fds=(fd,), + ) as process: + inherited.close() + with peer.makefile("rwb") as stream: + worker = threading.Thread(target=host_service, args=(stream,), daemon=True) + worker.start() + client = MCPClient(process, evidence, 10) + try: + catalog = client.initialize() + + def call(name, arguments=None, *, invocation=False): + require(name in catalog, f"Packaged adapter did not advertise {name}") + params = {"name": name, "arguments": arguments or {}} + if invocation: + identifier = uuid.uuid4() + expected_inventory.append(identifier) + params["_meta"] = {"io.github.computer-mcp/host-invocation": str(identifier)} + result = client.send("tools/call", params) + require(not result.get("isError"), result) + structured = result["structuredContent"] + return structured if name.startswith("codex.protocol.") else structured["result"] + + yield call + finally: + process.stdin.close() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + raise + finally: + try: + peer.shutdown(socket.SHUT_RDWR) + except OSError as error: + if error.errno != errno.ENOTCONN: + raise + worker.join(timeout=2) + client.reader.join(timeout=2) + stderr.seek(0) + require(process.returncode == 0, stderr.read()) + require(not worker.is_alive() and isinstance(client.failure, EOFError), "Missing MCP EOF") + require(not errors and not expected_inventory, (errors, expected_inventory)) + + +def vendor_peer(): + home = Path(os.environ["CODEX_HOME"]) + receipt = {"pid": os.getpid(), "workspace": os.getcwd(), + "host_context": "COMPUTER_MCP_HOST_CONTEXT" in os.environ, + "host_descriptor": "COMPUTER_MCP_HOST_FD" in os.environ} + (home / "vendor.json").write_text(json.dumps(receipt)) + for line in sys.stdin: + request = json.loads(line) + if "id" not in request: + continue + if request["method"] == "initialize": + result = {"codexHome": str(home), "platformFamily": "unix", "platformOs": "macos", + "userAgent": "packaged-codex-fixture"} + else: + require(request["method"] == "thread/loaded/list", request) + result = {"data": ["packaged-vendor-thread"], "nextCursor": None} + print(json.dumps({"id": request["id"], "result": result}), flush=True) + + +def domain_rows(*paths, exclude=()): + rows = {} + for path in paths: + with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as database: + tables = database.execute( + "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name" + ).fetchall() + rows[path] = { + table: database.execute(f'SELECT * FROM "{table}" ORDER BY rowid').fetchall() + for (table,) in tables if table not in exclude and table != "grdb_migrations" + } + return rows + + +def cold_catalog_and_reads(adapter): + primary, alternate = "package-codex-fixture", "package-codex-alternate" + state = adapter.state / "codex-adapter" + + def subjects(): + return set(state.glob("subjects/*/codex.sqlite")) + + with adapter.connect() as host: + require(host("codex.diagnostics.snapshot")["scope"]["principal_id"] == primary, + "The adapter did not use the bound caller") + lease = host("codex.worktree.leases.acquire", {"agent_id": "cold-fixture-owner"}) + own, = subjects() + with adapter.connect(alternate=True) as host: + require(host("codex.diagnostics.snapshot")["scope"]["principal_id"] == alternate, + "The adapter did not use the alternate caller") + host("codex.worktree.leases.acquire", {"agent_id": "cold-fixture-owner"}) + foreign, = subjects() - {own} + + # Seed records from persisted state layouts that predate the current migration. + legacy = state / "codex.sqlite" + shutil.copy2(foreign, legacy) + index = state / "thread-owners.sqlite" + paths = [own, foreign, legacy, index, *sorted((state / "worktree-leases").glob("*.sqlite"))] + require(len(paths) == 6, paths) + created_at = "2026-01-01 00:00:00.000" + expires_at = "2099-01-01 00:00:00.000" + for path, principal, records in ( + (own, primary, {"orphan": "absent-runtime", "live": "fixture-live-runtime"}), + (foreign, alternate, {"foreign-canary": "foreign-runtime"}), + (legacy, None, {"unbound-canary": "unbound-runtime"}), + ): + owner = {"workspace_id": "primary", "profile_id": "acceptance", "principal_id": principal} + with closing(sqlite3.connect(path)) as database, database: + for approval_id, runtime_id in records.items(): + database.execute(""" + INSERT INTO codexApprovals ( + id, upstreamRequestID, kind, risk, state, workspaceID, workspacePath, + runtimeID, correlationID, detailsJSON, proposedActionJSON, createdAt, + expiresAt, ownerJSON + ) VALUES (?, 'n:42', 'file_change', 'workspace-write', 'pending', 'primary', + ?, ?, 'fixture-approval', '{}', '{}', ?, ?, ?) + """, (approval_id, str(adapter.workspace), runtime_id, created_at, + expires_at, json.dumps(owner))) + if path == own: + live = {"id": records["live"], "owner": owner, "workspacePath": str(adapter.workspace), + "state": "running", "createdAt": 0, "updatedAt": 0, + "process": {"state": "running", "process_id": os.getpid(), + "parent_process_id": os.getppid(), "termination_escalated": False}} + database.execute("INSERT INTO codexRuntimeLeases VALUES (?, 'primary', 'running', ?, ?)", + (live["id"], created_at, json.dumps(live))) + database.execute( + "INSERT INTO codexThreadOwnership (threadID, workspaceID, workspacePath, runtimeID, " + "state, createdAt, updatedAt, ownerJSON) VALUES (?, 'primary', ?, ?, 'loaded', ?, ?, ?)", + ("fixture-owned-thread", str(adapter.workspace), live["id"], + created_at, created_at, json.dumps(owner))) + history = {"id": "history-fixture", "state": "active", "principal_id": primary, + "profile_id": "acceptance"} + database.execute("INSERT INTO codexManagedWorktrees VALUES (?, 'primary', ?, 'active', ?, ?)", + (history["id"], "history-project", created_at, json.dumps(history))) + database.execute("DELETE FROM grdb_migrations WHERE identifier = 'codex-projects-v1-history'") + with closing(sqlite3.connect(index)) as database, database: + database.execute("INSERT INTO threadOwners VALUES (?, ?, ?)", + (hashlib.sha256(json.dumps([str(adapter.vendor_home)]).encode()).hexdigest(), + "fixture-owned-thread", own.parent.name)) + + before = domain_rows(*paths, exclude=("codexManagedWorktrees",)) + history_rows = domain_rows(own, foreign, legacy) + prior_history = history_rows[own]["codexManagedWorktrees"] + for _ in range(2): + with adapter.connect() as host: + for prefix in ("codex.protocol", "codex.app"): + host(prefix + ".methods.list") + host(prefix + ".methods.describe", {"method": "thread/loaded/list"}) + snapshot = host("codex.diagnostics.snapshot") + require(snapshot["host_diagnostics_available"] and snapshot["state_storage"]["unbound_history_available"], + snapshot) + require({row["id"] for row in snapshot["pending_approvals"]} == {"orphan", "live"}, snapshot) + require(snapshot["unmanaged_history"] == [history | {"state": "unmanaged", "previous_state": "active"}], + snapshot["unmanaged_history"]) + require(host("codex.worktree.managed.list", invocation=True)["unmanaged_history"] == snapshot["unmanaged_history"], + "Worktree inventory did not retain migrated history") + require(host("codex.worktree.leases.read", {"lease_id": lease["id"]}) == lease, lease) + host("codex.worktree.leases.cleanup.preview") + require(domain_rows(*paths, exclude=("codexManagedWorktrees",)) == before, + "Cold catalog, read or disconnect changed domain rows") + migrated = domain_rows(*paths)[own]["codexManagedWorktrees"] + require(migrated[0][:5] == (*prior_history[0][:3], "unmanaged", prior_history[0][4]), migrated) + require(json.loads(migrated[0][5]) == snapshot["unmanaged_history"][0], migrated) + prior_history = migrated + require(domain_rows(foreign, legacy) == {path: history_rows[path] for path in (foreign, legacy)}, + "Cold history migration changed an unrelated partition") + require(not (adapter.vendor_home / "vendor.json").exists(), "Cold observation started the peer") + + with adapter.connect() as host: + result = host("codex.app.approvals.list") + require({row["id"]: row["state"] for row in result["approvals"]} == + {"orphan": "interrupted", "live": "pending"}, result) + after = domain_rows(*paths, exclude=("codexManagedWorktrees",)) + require({path: after[path] for path in paths if path != own} == + {path: before[path] for path in paths if path != own}, "Recovery changed a separate partition") + require({table: rows for table, rows in after[own].items() if table != "codexApprovals"} == + {table: rows for table, rows in before[own].items() if table != "codexApprovals"}, + "Recovery changed unrelated records") + live_before, = [row for row in before[own]["codexApprovals"] if row[0] == "live"] + live_after, = [row for row in after[own]["codexApprovals"] if row[0] == "live"] + require(live_after == live_before, "Recovery changed the live approval") + require(not (adapter.vendor_home / "vendor.json").exists(), "Approval recovery started the peer") + print("Packaged adapter preserved cold state and recovered only the orphan approval.") + + + +def check_adapter(adapter): + cold_catalog_and_reads(adapter) + with adapter.connect() as call: + loaded = call("codex.app.thread.loaded.list") + require(loaded["data"] == ["packaged-vendor-thread"], loaded) + vendor = json.loads((adapter.vendor_home / "vendor.json").read_text()) + require(vendor["workspace"] == str(adapter.workspace) + and not vendor["host_context"] and not vendor["host_descriptor"], vendor) + try: + os.kill(vendor["pid"], 0) + except ProcessLookupError: + print("Packaged adapter bound and reaped its private vendor.") + else: + raise AssertionError("The vendor process survived adapter EOF") + + +def check_archive(output): + root = output / "adapter-contract" + root.mkdir(mode=0o700) + receipt_path = output / "receipt.json" + receipt = json.loads(receipt_path.read_text()) + require(receipt["configuration"] == "release", "Packaged tests require the release build") + package = root / "relocated" + subprocess.run([ + sys.executable, str(REPOSITORY / "scripts/check-package.py"), + "--archive", str(output / receipt["archive"]), "--receipt", str(receipt_path), + "--destination", str(package), + ], check=True, timeout=30) + manifest = tomllib.loads((package / "computer-mcp-plugin.toml").read_text()) + contribution, = [item for item in manifest["mcp"] if item["id"] == "app-server"] + require(contribution["transport"] == "stdio", contribution) + executable = package / contribution["executable"]["platform_paths"]["macos"] + check_adapter(PackagedAdapter(root, executable, contribution["host_service_contract"])) + + +if __name__ == "__main__": + if sys.argv[1] == "app-server": + vendor_peer() + else: + check_archive(Path(sys.argv[1]).resolve()) diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index 74f26ac..5134c32 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -6,6 +6,7 @@ import json from pathlib import Path import subprocess +import sys import tempfile import threading from types import SimpleNamespace @@ -13,6 +14,7 @@ from unittest.mock import Mock, call, patch SCRIPT = Path(__file__).resolve().parents[1] / "scripts/check-host.py" +sys.path.insert(0, str(SCRIPT.parent)) spec = importlib.util.spec_from_file_location("host_acceptance", SCRIPT) acceptance = importlib.util.module_from_spec(spec) spec.loader.exec_module(acceptance) @@ -212,7 +214,6 @@ def test_registered_cases_overlap_in_private_roots_and_report_the_failing_call(s calls = { "catalog_permissions": "catalog", "plugin_use_permissions": "plugin-use", - "cold_catalog_and_reads": "cold", "callbacks_disabled": "callbacks-disabled", "wildcard_fallback": "wildcard", } diff --git a/scripts/check-host.py b/scripts/check-host.py index 6088c2b..8960b95 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -10,7 +10,6 @@ import argparse from concurrent.futures import ThreadPoolExecutor -from contextlib import closing import hashlib import json import os @@ -19,7 +18,6 @@ import re import shutil import signal -import sqlite3 import subprocess import sys import tarfile @@ -29,21 +27,17 @@ from types import SimpleNamespace import uuid +from mcp_client import MCPClient, require + REPOSITORY = Path(__file__).resolve().parents[1] MODEL_SOURCE = REPOSITORY / "Tests/Fixtures/NativeCodex/ModelServer.py" REGISTERED_HOST_SOURCE = REPOSITORY / "Tests/Fixtures/RegisteredHost/RegisteredHost.swift" HOST_PIN = REPOSITORY / ".github/computer-mcp-host.sha" MANIFEST = REPOSITORY / "computer-mcp-plugin.toml" ADAPTER_PATH = Path("bin/codex-mcp-adapter") -MAX_MESSAGE = 8_388_608 STEP_OUTPUT_LOCK = threading.Lock() -def require(condition, detail): - if not condition: - raise AssertionError(detail) - - def executable(value): path = Path(value) if not path.is_absolute() or not path.is_file() or not os.access(path, os.X_OK): @@ -217,20 +211,6 @@ def require_admission_refusal(result): } and error.get("call_dispatched", False) is False, result) -def domain_rows(*paths, exclude=()): - rows = {} - for path in paths: - with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as database: - tables = database.execute( - "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name" - ).fetchall() - rows[path] = { - table: database.execute(f'SELECT * FROM "{table}" ORDER BY rowid').fetchall() - for (table,) in tables if table not in exclude and table != "grdb_migrations" - } - return rows - - def interrupted_mcp_call(error): message = error.get("message") return error.get("code") == "gateway.execution_failed" and isinstance(message, str) and ( @@ -329,74 +309,6 @@ def process_parent(pid): return int(result.stdout.strip()) if result.returncode == 0 and result.stdout.strip().isdigit() else None -class MCPClient: - def __init__(self, process, evidence, timeout): - self.process, self.evidence, self.timeout = process, evidence, timeout - self.sequence = 0 - self.queue = queue.Queue(maxsize=1024) - self.failure = None - self.reader = threading.Thread(target=self.read, daemon=True) - self.reader.start() - - def read(self): - try: - while True: - line = self.process.stdout.readline(MAX_MESSAGE + 1) - if not line: - raise EOFError("Host MCP stdout closed") - require(len(line.encode()) <= MAX_MESSAGE, "MCP message exceeded acceptance bound") - self.queue.put_nowait(json.loads(line)) - except Exception as error: - self.failure = error - - def send(self, method, params, notification=False, timeout=None): - self.sequence += 1 - message = {"jsonrpc": "2.0", "method": method, "params": params} - if not notification: - message["id"] = self.sequence - self.process.stdin.write(json.dumps(message) + "\n") - self.process.stdin.flush() - if notification: - return - deadline = time.monotonic() + (timeout or self.timeout) - while time.monotonic() < deadline: - try: - response = self.queue.get(timeout=min(0.1, max(0.01, deadline - time.monotonic()))) - except queue.Empty: - if self.failure: - raise self.failure - continue - if response.get("id") != message["id"]: - require("method" in response and "id" not in response, "Unexpected MCP response/request") - continue - self.evidence.write(json.dumps({"request": message, "response": response}) + "\n") - self.evidence.flush() - require(self.evidence.tell() <= 32 * 1024 * 1024, "Protocol evidence exceeded acceptance bound") - require("error" not in response, response) - return response["result"] - raise TimeoutError(method + "; result unknown, no write retry") - - def initialize(self): - self.send("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, - "clientInfo": {"name": "codex-host-acceptance", "version": "1"}}) - self.send("notifications/initialized", {}, notification=True) - return self.list_tools() - - def list_tools(self): - catalog, cursor, seen = {}, None, set() - for _ in range(100): - page = self.send("tools/list", {"cursor": cursor} if cursor else {}) - for tool in page["tools"]: - require(tool["name"] not in catalog, "Duplicate catalog tool") - catalog[tool["name"]] = tool - cursor = page.get("nextCursor") - if not cursor: - return catalog - require(cursor not in seen, "Cyclic tool catalog") - seen.add(cursor) - raise RuntimeError("Unbounded tool catalog") - - APP_READ = ["status", "methods.list", "models.list", "skills.list", "apps.list", "events.read", "thread.list", "thread.loaded.list", "thread.read", "thread.recent", "goal.get", "approvals.list", "requests.list", "handoff.diagnose", "runtimes.history"] @@ -861,116 +773,6 @@ def catalog_and_diagnostics(self): host.close() self.record("catalog-diagnostics-domain-leases-lazy-start") - def cold_catalog_and_reads(self): - primary, alternate = "registered-codex-fixture", "registered-codex-alternate" - lease = None - for distinct in (False, True): - host = Host(self, alternate_principal=distinct) - diagnostic = host.call("codex.diagnostics.snapshot") - require(diagnostic["scope"]["principal_id"] == (alternate if distinct else primary), - diagnostic["scope"]) - current = host.call("codex.worktree.leases.acquire", {"agent_id": "cold-fixture-owner"}) - if not distinct: - lease = current - host.close() - - state = Path(self.container["state"]) / "codex-adapter" - def scope(*fields): - return hashlib.sha256(json.dumps(fields, separators=(",", ":")).encode()).hexdigest() - - own = state / "subjects" / scope(primary, "acceptance", "primary") / "codex.sqlite" - foreign = state / "subjects" / scope(alternate, "acceptance", "primary") / "codex.sqlite" - legacy = state / "codex.sqlite" - shutil.copy2(foreign, legacy) - index = state / "thread-owners.sqlite" - paths = [own, foreign, legacy, index, *sorted((state / "worktree-leases").glob("*.sqlite"))] - require(len(paths) == 6, paths) - created_at = "2026-01-01 00:00:00.000" - expires_at = "2099-01-01 00:00:00.000" - for path, principal, records in ( - (own, primary, {"orphan": "absent-runtime", "live": "fixture-live-runtime"}), - (foreign, alternate, {"foreign-canary": "foreign-runtime"}), - (legacy, None, {"unbound-canary": "unbound-runtime"}), - ): - owner = {"workspace_id": "primary", "profile_id": "acceptance", "principal_id": principal} - with closing(sqlite3.connect(path)) as database, database: - for approval_id, runtime_id in records.items(): - database.execute(""" - INSERT INTO codexApprovals ( - id, upstreamRequestID, kind, risk, state, workspaceID, workspacePath, - runtimeID, correlationID, detailsJSON, proposedActionJSON, createdAt, - expiresAt, ownerJSON - ) VALUES (?, 'n:42', 'file_change', 'workspace-write', 'pending', 'primary', - ?, ?, 'fixture-approval', '{}', '{}', ?, ?, ?) - """, (approval_id, str(self.projects["primary"]), runtime_id, created_at, - expires_at, json.dumps(owner))) - if path == own: - live = {"id": records["live"], "owner": owner, "workspacePath": str(self.projects["primary"]), - "state": "running", "createdAt": 0, "updatedAt": 0, - "process": {"state": "running", "process_id": os.getpid(), - "parent_process_id": os.getppid(), "termination_escalated": False}} - database.execute("INSERT INTO codexRuntimeLeases VALUES (?, 'primary', 'running', ?, ?)", - (live["id"], created_at, json.dumps(live))) - database.execute( - "INSERT INTO codexThreadOwnership (threadID, workspaceID, workspacePath, runtimeID, " - "state, createdAt, updatedAt, ownerJSON) VALUES (?, 'primary', ?, ?, 'loaded', ?, ?, ?)", - ("fixture-owned-thread", str(self.projects["primary"]), live["id"], - created_at, created_at, json.dumps(owner))) - history = {"id": "history-fixture", "state": "active", "principal_id": primary, - "profile_id": "acceptance"} - database.execute("INSERT INTO codexManagedWorktrees VALUES (?, 'primary', ?, 'active', ?, ?)", - (history["id"], "history-project", created_at, json.dumps(history))) - database.execute("DELETE FROM grdb_migrations WHERE identifier = 'codex-projects-v1-history'") - with closing(sqlite3.connect(index)) as database, database: - database.execute("INSERT INTO threadOwners VALUES (?, ?, ?)", - (scope(str(self.home)), "fixture-owned-thread", scope(primary, "acceptance", "primary"))) - - before = domain_rows(*paths, exclude=("codexManagedWorktrees",)) - history_rows = domain_rows(own, foreign, legacy) - prior_history = history_rows[own]["codexManagedWorktrees"] - for indirect in (False, True): - host = Host(self, indirect=indirect) - for prefix in ("codex.protocol", "codex.app"): - host.call(prefix + ".methods.list") - host.call(prefix + ".methods.describe", {"method": "thread/loaded/list"}) - snapshot = host.call("codex.diagnostics.snapshot") - require(snapshot["host_diagnostics_available"] and snapshot["state_storage"]["unbound_history_available"], - snapshot) - require({row["id"] for row in snapshot["pending_approvals"]} == {"orphan", "live"}, snapshot) - require(snapshot["unmanaged_history"] == [history | {"state": "unmanaged", "previous_state": "active"}], - snapshot["unmanaged_history"]) - host.call("codex.worktree.managed.list") - require(host.call("codex.worktree.leases.read", {"lease_id": lease["id"]}) == lease, lease) - host.call("codex.worktree.leases.cleanup.preview") - host.close() - require(domain_rows(*paths, exclude=("codexManagedWorktrees",)) == before, - "Cold catalog, read or disconnect changed domain rows") - migrated = domain_rows(*paths)[own]["codexManagedWorktrees"] - require(migrated[0][:5] == (*prior_history[0][:3], "unmanaged", prior_history[0][4]), migrated) - require(json.loads(migrated[0][5]) == snapshot["unmanaged_history"][0], migrated) - prior_history = migrated - require(domain_rows(foreign, legacy) == {path: history_rows[path] for path in (foreign, legacy)}, - "Cold history migration changed an unrelated partition") - require(not (self.home / "vendor.json").exists(), "Cold observation started the peer") - - host = Host(self) - result = host.call("approvals.list") - require({row["id"]: row["state"] for row in result["approvals"]} == - {"orphan": "interrupted", "live": "pending"}, result) - # The response endpoint may carry a stronger Host floor. The runtime test - # exercises its broker after reconciliation with the same interrupted state. - host.close() - after = domain_rows(*paths, exclude=("codexManagedWorktrees",)) - require({path: after[path] for path in paths if path != own} == - {path: before[path] for path in paths if path != own}, "Recovery changed a separate partition") - require({table: rows for table, rows in after[own].items() if table != "codexApprovals"} == - {table: rows for table, rows in before[own].items() if table != "codexApprovals"}, - "Recovery changed unrelated records") - require(after[own]["codexApprovals"][1] == before[own]["codexApprovals"][1], - "Recovery changed the live approval") - require(not (self.home / "vendor.json").exists(), "Approval recovery started the peer") - self.record("cold-discovery-scoped-history-migration-and-lazy-approval-recovery") - def catalog_permissions(self): catalog = "codex.protocol.methods.list" read = "codex.diagnostics.snapshot" @@ -1619,7 +1421,6 @@ def registered_container(self): ("scoped", "scoped_worktree_permissions", {}), ("catalog", "catalog_permissions", {}), ("plugin-use", "plugin_use_permissions", {}), - ("cold", "cold_catalog_and_reads", {}), ("single-project", "project_selection", {"project_count": 1}), ("no-project", "project_selection", {"project_count": 0}), ("callbacks-disabled", "callbacks_disabled", {"host_services": False}), diff --git a/scripts/mcp_client.py b/scripts/mcp_client.py new file mode 100644 index 0000000..476714d --- /dev/null +++ b/scripts/mcp_client.py @@ -0,0 +1,82 @@ +"""Bounded JSON-RPC client shared by the adapter acceptance tests.""" + +import json +import queue +import threading +import time + +MAX_MESSAGE = 8_388_608 + + +def require(condition, detail): + if not condition: + raise AssertionError(detail) + + +class MCPClient: + def __init__(self, process, evidence, timeout): + self.process, self.evidence, self.timeout = process, evidence, timeout + self.sequence = 0 + self.queue = queue.Queue(maxsize=1024) + self.failure = None + self.reader = threading.Thread(target=self.read, daemon=True) + self.reader.start() + + def read(self): + try: + while True: + line = self.process.stdout.readline(MAX_MESSAGE + 1) + if not line: + raise EOFError("MCP server stdout closed") + require(len(line.encode()) <= MAX_MESSAGE, "MCP message exceeded acceptance bound") + self.queue.put_nowait(json.loads(line)) + except Exception as error: + self.failure = error + + def send(self, method, params, notification=False, timeout=None): + self.sequence += 1 + message = {"jsonrpc": "2.0", "method": method, "params": params} + if not notification: + message["id"] = self.sequence + self.process.stdin.write(json.dumps(message) + "\n") + self.process.stdin.flush() + if notification: + return + deadline = time.monotonic() + (timeout or self.timeout) + while time.monotonic() < deadline: + try: + response = self.queue.get(timeout=min(0.1, max(0.01, deadline - time.monotonic()))) + except queue.Empty: + if self.failure: + raise self.failure + continue + if response.get("id") != message["id"]: + require("method" in response and "id" not in response, "Unexpected MCP response/request") + continue + self.evidence.write(json.dumps({"request": message, "response": response}) + "\n") + self.evidence.flush() + require(self.evidence.tell() <= 32 * 1024 * 1024, "Protocol evidence exceeded acceptance bound") + require("error" not in response, response) + return response["result"] + raise TimeoutError(method + "; result unknown, no write retry") + + def initialize(self): + self.send("initialize", {"protocolVersion": "2025-11-25", "capabilities": {}, + "clientInfo": {"name": "codex-acceptance", "version": "1"}}) + self.send("notifications/initialized", {}, notification=True) + return self.list_tools() + + def list_tools(self): + catalog, cursor, seen = {}, None, set() + for _ in range(100): + page = self.send("tools/list", {"cursor": cursor} if cursor else {}) + for tool in page["tools"]: + require(tool["name"] not in catalog, "Duplicate catalog tool") + catalog[tool["name"]] = tool + cursor = page.get("nextCursor") + if not cursor: + return catalog + require(cursor not in seen, "Cyclic tool catalog") + seen.add(cursor) + raise RuntimeError("Unbounded tool catalog") + diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..3efeaa3 --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# Run the plugin-owned checks and produce the release archive used by CI. +set -euo pipefail +cd "$(dirname "$0")/.." +if [[ $# != 1 ]]; then + echo "Usage: scripts/test.sh NEW_OUTPUT_DIRECTORY" >&2 + exit 2 +fi +output=$1 +python3 scripts/version.py check +/usr/bin/swift package resolve +git diff --exit-code -- Package.resolved +scripts/verify-swift-codex-release-gate.sh +node --test Tests/schema-import.test.mjs +node scripts/import-schema.mjs --check +/usr/bin/swift format lint --strict --recursive Package.swift Sources Tests +# These assertions measure wall-clock behavior on the current machine. +timing_tests='incompleteHostStartupHasABoundedAndJoinedExit|testLargePersistedThreadReadIsBoundedAndPaginatesWithoutOverlap' +/usr/bin/swift test --disable-automatic-resolution --no-parallel --filter "$timing_tests" +/usr/bin/swift test --skip-build --disable-automatic-resolution --skip "$timing_tests" +python3 scripts/check-host.py --help >/dev/null +python3 -m unittest discover -s Tests -p 'test_*.py' +python3 scripts/check-workflow.py --check-release-workflow +echo "Release ZIP build and packaging" +time -p python3 scripts/package.py --output "$output" --configuration release +echo "Relocated adapter contract tests" +time -p python3 Tests/PackagedAdapter.py "$output" From c4046a25d56442e275793b8e9464468310c8dc17 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:40:04 +0800 Subject: [PATCH 03/16] perf: isolate Swift test and release build plans --- scripts/mcp_client.py | 1 - scripts/test.sh | 6 ++++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/mcp_client.py b/scripts/mcp_client.py index 476714d..3a1f2e8 100644 --- a/scripts/mcp_client.py +++ b/scripts/mcp_client.py @@ -79,4 +79,3 @@ def list_tools(self): require(cursor not in seen, "Cyclic tool catalog") seen.add(cursor) raise RuntimeError("Unbounded tool catalog") - diff --git a/scripts/test.sh b/scripts/test.sh index 3efeaa3..fe02c38 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -16,8 +16,10 @@ node scripts/import-schema.mjs --check /usr/bin/swift format lint --strict --recursive Package.swift Sources Tests # These assertions measure wall-clock behavior on the current machine. timing_tests='incompleteHostStartupHasABoundedAndJoinedExit|testLargePersistedThreadReadIsBoundedAndPaginatesWithoutOverlap' -/usr/bin/swift test --disable-automatic-resolution --no-parallel --filter "$timing_tests" -/usr/bin/swift test --skip-build --disable-automatic-resolution --skip "$timing_tests" +# Keep SwiftPM's test plan separate from the release packaging build. +unit_build="$PWD/.build/plugin-tests" +/usr/bin/swift test --scratch-path "$unit_build" --disable-automatic-resolution --no-parallel --filter "$timing_tests" +/usr/bin/swift test --scratch-path "$unit_build" --skip-build --disable-automatic-resolution --skip "$timing_tests" python3 scripts/check-host.py --help >/dev/null python3 -m unittest discover -s Tests -p 'test_*.py' python3 scripts/check-workflow.py --check-release-workflow From 6653c6afd42f92a079995b0220fb0cdfaf2cc849 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:42:52 +0800 Subject: [PATCH 04/16] test: gate survivor exit and overlap independent packaging --- .../CodexAppServerProcessTransportTests.swift | 17 +++++++++++++-- scripts/test.sh | 21 +++++++++++++------ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift b/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift index d12d6e2..007996b 100644 --- a/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift @@ -8,14 +8,26 @@ import Testing struct CodexAppServerProcessTransportTests { @Test(.timeLimit(.minutes(1))) func supervisorExitDoesNotProveChildGroupCleanup() async throws { + let workspace = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: workspace) } + let hold = workspace.appendingPathComponent("hold") + try Data().write(to: hold) let transport = try ManagedLineProcess( configuration: .init( executable: "/usr/bin/python3", arguments: [ "-c", - "import os,time; print(os.getpid(),flush=True); os.close(1); os.close(2); time.sleep(3)", + """ + import os, time + print(os.getpid(), flush=True) + os.close(1) + os.close(2) + while os.path.exists("hold"): + time.sleep(0.01) + """, ], - workingDirectory: FileManager.default.temporaryDirectory, + workingDirectory: workspace, terminationGraceMilliseconds: 10, killGraceMilliseconds: 100)) var lines = transport.inboundLines.makeAsyncIterator() let ready = try #require(try await lines.next()) @@ -34,6 +46,7 @@ struct CodexAppServerProcessTransportTests { await transport.close() #expect(Darwin.kill(child, 0) == 0) #expect(await transport.snapshot().cleanupConfirmed == false) + try FileManager.default.removeItem(at: hold) let cleanupDeadline = ContinuousClock.now + .seconds(4) while await transport.snapshot().cleanupConfirmed != true, ContinuousClock.now < cleanupDeadline { diff --git a/scripts/test.sh b/scripts/test.sh index fe02c38..016069d 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -18,12 +18,21 @@ node scripts/import-schema.mjs --check timing_tests='incompleteHostStartupHasABoundedAndJoinedExit|testLargePersistedThreadReadIsBoundedAndPaginatesWithoutOverlap' # Keep SwiftPM's test plan separate from the release packaging build. unit_build="$PWD/.build/plugin-tests" -/usr/bin/swift test --scratch-path "$unit_build" --disable-automatic-resolution --no-parallel --filter "$timing_tests" -/usr/bin/swift test --scratch-path "$unit_build" --skip-build --disable-automatic-resolution --skip "$timing_tests" +echo "Swift test build and wall-clock assertions" +time -p /usr/bin/swift test --scratch-path "$unit_build" --disable-automatic-resolution --no-parallel --filter "$timing_tests" python3 scripts/check-host.py --help >/dev/null python3 -m unittest discover -s Tests -p 'test_*.py' python3 scripts/check-workflow.py --check-release-workflow -echo "Release ZIP build and packaging" -time -p python3 scripts/package.py --output "$output" --configuration release -echo "Relocated adapter contract tests" -time -p python3 Tests/PackagedAdapter.py "$output" + +( + echo "Release ZIP build and packaging" + time -p python3 scripts/package.py --output "$output" --configuration release + echo "Relocated adapter contract tests" + time -p python3 Tests/PackagedAdapter.py "$output" +) & +packaging=$! +echo "Remaining Swift tests" +test_status=0 +time -p /usr/bin/swift test --scratch-path "$unit_build" --skip-build --disable-automatic-resolution --skip "$timing_tests" || test_status=$? +wait "$packaging" +exit "$test_status" From f268878ac16543f75562e0b470c2145636634dae Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:55:22 +0800 Subject: [PATCH 05/16] test: wire the shared Host package smoke gate --- .github/workflows/ci.yml | 13 ++++++++++++ CONTRIBUTING.md | 15 +++++++++---- Documentation/Reference/Release.md | 7 ++++++ Tests/Fixtures/HostSmoke.json | 30 ++++++++++++++++++++++++++ Tests/PackagedAdapter.py | 26 +++++++++++++++++------ Tests/test_host_acceptance.py | 20 ++++++++++++++++++ Tests/test_package.py | 3 +++ Tests/test_package_archive.py | 2 ++ scripts/check-host.py | 12 +++++++---- scripts/test-portable.sh | 9 ++++++++ scripts/test.sh | 34 +++++++++++++++++++++++------- 11 files changed, 149 insertions(+), 22 deletions(-) create mode 100644 Tests/Fixtures/HostSmoke.json create mode 100755 scripts/test-portable.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a54979..6b3da47 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,19 @@ jobs: python-version: '3.13' - name: Install dependency gate tooling run: brew install jq ripgrep + - name: Read the pinned Host revision + id: smoke-host + run: | + revision=$(cat .github/computer-mcp-host.sha) + [[ "$revision" =~ ^[0-9a-f]{40}$ && "$revision" != 0000000000000000000000000000000000000000 ]] + echo "revision=$revision" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + repository: computer-mcp/computer-mcp + ref: ${{ steps.smoke-host.outputs.revision }} + path: .agent/smoke-host + persist-credentials: false + - uses: ./.agent/smoke-host/.github/actions/provision-plugin-smoke - name: Validate and package the plugin env: BASE_COMMIT: ${{ github.event.pull_request.base.sha || github.event.before }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 50782b9..d8f22e4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,16 +7,23 @@ external dependencies and credentials. ## Validation Run the same macOS plugin suite as CI before opening a pull request. It needs -Swift, Python 3.12 or newer, Node.js, `jq` and `ripgrep`. +Swift, Python 3.12 or newer, Node.js, `jq`, `ripgrep`, and the provisioned +Host fixture for the commit in [the Host pin](.github/computer-mcp-host.sha). ```sh -scripts/test.sh .build/plugin-validation +COMPUTER_MCP_TEST_HOST=/absolute/path/to/fixture scripts/test.sh .build/plugin-validation ``` Use a new output directory for each run. The suite builds a release ZIP, verifies its receipt, and exercises the relocated adapter over MCP with private -Host-service and vendor fixtures. It needs no installed Host or vendor account. -Use [the exact-pair gate](Documentation/Reference/Release.md#runtime-acceptance) +Host-service and vendor fixtures. The prebuilt Host then installs the same ZIP +and checks a public catalog call. The tests use no vendor account. + +Use `scripts/test.sh --plugin-only .build/plugin-validation` for macOS native +checks while developing without the Host fixture. On Linux or with the +minimum Python 3.11 interpreter, `scripts/test-portable.sh` runs the source +and script checks. The portable checks need Bash, zsh, Git, Node.js, +`jq` and `ripgrep`. Use [the exact-pair gate](Documentation/Reference/Release.md#runtime-acceptance) when changing the Host-facing contract or implementation. ## Documentation diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index dcbfc50..71f3951 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -95,6 +95,9 @@ ZIP and receipt, then exercises the relocated manifest's stdio contribution with a deterministic App Server and an inherited Host-service MCP fixture. These cases cover cold discovery, scoped storage, historical migration, lazy approval recovery, and startup and shutdown of an owned vendor process. +The same suite uses the prebuilt Host at the committed pin to install the ZIP, +enable its stdio contribution and check the public response defined in +[`HostSmoke.json`](../../Tests/Fixtures/HostSmoke.json). The package job uploads the release ZIP and native receipt as the commit-named candidate artifact. The interop job downloads those same bytes. It runs on @@ -121,6 +124,10 @@ python3 scripts/check-host.py \ --output-directory "$PWD/.build/host-acceptance" ``` +Host CI can pass `--host-revision FULL_SHA` to test its exact candidate against +this plugin. The driver still requires a clean Host checkout at that SHA and +a clean plugin checkout at `--plugin-revision`. + The driver checks both Git checkouts, exports Host source into the new output directory, and builds the registered fixture and execution bootstrap against the committed Host dependency lock. It verifies and relocates the ZIP before diff --git a/Tests/Fixtures/HostSmoke.json b/Tests/Fixtures/HostSmoke.json new file mode 100644 index 0000000..afb618b --- /dev/null +++ b/Tests/Fixtures/HostSmoke.json @@ -0,0 +1,30 @@ +{ + "call": { + "kind": "mcp", + "component": "app-server", + "tool": "codex.protocol.methods.describe", + "arguments": { + "method": "thread/loaded/list" + } + }, + "expected": { + "isError": false, + "structuredContent": { + "result": { + "isError": false, + "structuredContent": { + "method": "thread/loaded/list", + "channel": "stable", + "direction": "ClientRequest", + "requires_params": true, + "request_schema": { + "type": "object" + } + } + }, + "gateway_execution": { + "capability_id": "mcp.tools.call" + } + } + } +} diff --git a/Tests/PackagedAdapter.py b/Tests/PackagedAdapter.py index 6fb4dde..86ff79b 100644 --- a/Tests/PackagedAdapter.py +++ b/Tests/PackagedAdapter.py @@ -17,10 +17,22 @@ import uuid REPOSITORY = Path(__file__).resolve().parents[1] +HOST_SMOKE_CASE = REPOSITORY / "Tests/Fixtures/HostSmoke.json" sys.path.insert(0, str(REPOSITORY / "scripts")) from mcp_client import MCPClient, require +def check_protocol_description(host, scenario): + call = scenario["call"] + actual = host(call["tool"], call["arguments"]) + expected = scenario["expected"]["structuredContent"]["result"]["structuredContent"] + for key, value in expected.items(): + if key == "request_schema": + require(value.items() <= actual[key].items(), actual[key]) + else: + require(actual[key] == value, {key: actual[key]}) + + class PackagedAdapter: def __init__(self, root, executable, contract): self.root, self.executable, self.contract = root, executable, contract @@ -175,7 +187,7 @@ def domain_rows(*paths, exclude=()): return rows -def cold_catalog_and_reads(adapter): +def cold_catalog_and_reads(adapter, smoke_case): primary, alternate = "package-codex-fixture", "package-codex-alternate" state = adapter.state / "codex-adapter" @@ -247,7 +259,8 @@ def subjects(): with adapter.connect() as host: for prefix in ("codex.protocol", "codex.app"): host(prefix + ".methods.list") - host(prefix + ".methods.describe", {"method": "thread/loaded/list"}) + check_protocol_description(host, smoke_case) + host("codex.app.methods.describe", smoke_case["call"]["arguments"]) snapshot = host("codex.diagnostics.snapshot") require(snapshot["host_diagnostics_available"] and snapshot["state_storage"]["unbound_history_available"], snapshot) @@ -286,8 +299,8 @@ def subjects(): -def check_adapter(adapter): - cold_catalog_and_reads(adapter) +def check_adapter(adapter, smoke_case): + cold_catalog_and_reads(adapter, smoke_case) with adapter.connect() as call: loaded = call("codex.app.thread.loaded.list") require(loaded["data"] == ["packaged-vendor-thread"], loaded) @@ -315,10 +328,11 @@ def check_archive(output): "--destination", str(package), ], check=True, timeout=30) manifest = tomllib.loads((package / "computer-mcp-plugin.toml").read_text()) - contribution, = [item for item in manifest["mcp"] if item["id"] == "app-server"] + smoke_case = json.loads(HOST_SMOKE_CASE.read_text(encoding="utf-8")) + contribution, = [item for item in manifest["mcp"] if item["id"] == smoke_case["call"]["component"]] require(contribution["transport"] == "stdio", contribution) executable = package / contribution["executable"]["platform_paths"]["macos"] - check_adapter(PackagedAdapter(root, executable, contribution["host_service_contract"])) + check_adapter(PackagedAdapter(root, executable, contribution["host_service_contract"]), smoke_case) if __name__ == "__main__": diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index 5134c32..4991004 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -61,6 +61,7 @@ def test_container_mode_requires_pinned_source_and_release_archive(self): arguments = self.container_arguments("a" * 40) options = acceptance.parse_arguments(arguments) self.assertEqual(options.host_source, self.root) + self.assertIsNone(options.host_revision) self.assertIsNone(options.host) self.assertIsNone(options.adapter) self.assertIsNone(options.codex) @@ -73,6 +74,25 @@ def test_container_mode_requires_pinned_source_and_release_archive(self): self.invalid(self.container_arguments("a" * 39)) self.invalid(self.container_arguments("0" * 40)) + def test_explicit_host_revision_is_container_only_and_replaces_the_default_pin(self): + plugin = "a" * 40 + host = "b" * 40 + for invalid in ("master", "", "B" * 40, "0" * 40): + self.invalid(self.container_arguments(plugin) + ["--host-revision", invalid]) + self.invalid(self.arguments + ["--mode", "fixture", "--host-revision", host]) + source = self.arguments[:4] + self.arguments[6:] + self.invalid(source + ["--mode", "source", "--host-revision", host]) + options = acceptance.parse_arguments(self.container_arguments(plugin) + ["--host-revision", host]) + with patch.object(acceptance, "HOST_PIN", self.root / "absent-pin"), \ + patch.object(acceptance, "checked_revision", side_effect=[host, plugin]) as checkout: + with self.assertRaises(json.JSONDecodeError): + acceptance.prepare_pinned_host(options) + self.assertEqual(checkout.call_args_list, [ + call(self.root, host, "Host"), + call(acceptance.REPOSITORY, plugin, "Plugin"), + ]) + self.assertFalse(options.output_directory.exists()) + def test_pin_rejects_missing_malformed_or_mismatched_source_before_build(self): with patch.object(acceptance, "HOST_PIN", self.root / "host.sha"), \ patch.object(acceptance, "checked_revision") as checkout: diff --git a/Tests/test_package.py b/Tests/test_package.py index ff201d1..cc771cf 100644 --- a/Tests/test_package.py +++ b/Tests/test_package.py @@ -67,6 +67,7 @@ def test_version_drift_is_rejected_before_building(self): command.assert_not_called() self.assertFalse((root / "output").exists()) + @unittest.skipUnless(sys.platform == "darwin", "Requires macOS exclusive publication") def test_package_preserves_manifest_bytes_in_archive_and_receipt(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -204,6 +205,7 @@ def test_package_rejects_links_before_signing_or_running_payload(self): self.assertEqual(list(root.glob("codex-package-*")), []) self.assertEqual(outside.read_bytes(), b"user owned") + @unittest.skipUnless(sys.platform == "darwin", "Requires macOS exclusive publication") def test_package_does_not_replace_destination_created_during_build(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -287,6 +289,7 @@ def test_linked_tree_root_is_rejected(self): package.copy_tree(source, root / "target") self.assertFalse((root / "target").exists()) + @unittest.skipUnless(sys.platform == "darwin", "Requires macOS exclusive publication") def test_exclusive_publication_preserves_every_existing_destination(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/Tests/test_package_archive.py b/Tests/test_package_archive.py index 201f92c..76ff961 100644 --- a/Tests/test_package_archive.py +++ b/Tests/test_package_archive.py @@ -38,6 +38,7 @@ def fixture(self, root, additions=()): "archive_sha256": hashlib.sha256(archive.read_bytes()).hexdigest()})) return archive, receipt, manifest + @unittest.skipUnless(sys.platform == "darwin", "Requires macOS exclusive publication") def test_exact_archive_relocates_with_manifest_bytes_and_executable_mode(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -88,6 +89,7 @@ def test_archive_inventory_and_manifest_tampering_are_detected(self): checker.verify(archive, receipt, manifest, root / "relocated") self.assertFalse((root / "relocated").exists()) + @unittest.skipUnless(sys.platform == "darwin", "Requires macOS exclusive publication") def test_relocation_preserves_destination_created_during_verification(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/scripts/check-host.py b/scripts/check-host.py index 8960b95..b47acd7 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -77,7 +77,8 @@ def timeout_seconds(value): def parse_arguments(arguments=None): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--host-source", type=checkout_directory, help="Container mode: clean checkout at the committed Host pin") + parser.add_argument("--host-source", type=checkout_directory, help="Container mode: clean Host checkout") + parser.add_argument("--host-revision", help="Container mode: full Host checkout SHA (defaults to the committed Host pin)") parser.add_argument("--plugin-revision", help="Container mode: full plugin checkout SHA") parser.add_argument("--archive", type=absolute_file, help="Container mode: plugin release ZIP") parser.add_argument("--receipt", type=absolute_file, help="Container mode: release ZIP receipt") @@ -93,12 +94,15 @@ def parse_arguments(arguments=None): root = options.output_directory if not root.is_absolute() or root.exists() or root.is_symlink(): parser.error("--output-directory must be a new absolute path") - source_inputs = (options.host_source, options.plugin_revision, options.archive, options.receipt) + required_source = (options.host_source, options.plugin_revision, options.archive, options.receipt) + source_inputs = (*required_source, options.host_revision is not None) if options.mode == "container": - if not all(source_inputs) or any((options.host, options.adapter, options.codex)): + if not all(required_source) or any((options.host, options.adapter, options.codex)): parser.error("Container mode requires --host-source, --plugin-revision, --archive and --receipt") try: full_revision(options.plugin_revision) + if options.host_revision is not None: + full_revision(options.host_revision) except ValueError as error: parser.error(str(error)) elif options.mode == "source": @@ -135,7 +139,7 @@ def read(*arguments): def prepare_pinned_host(options): - pin = full_revision(HOST_PIN.read_text(encoding="ascii").strip()) + pin = options.host_revision or full_revision(HOST_PIN.read_text(encoding="ascii").strip()) require(options.host_source != REPOSITORY, "Host and plugin require separate checkouts") host_revision = checked_revision(options.host_source, pin, "Host") plugin_revision = checked_revision(REPOSITORY, options.plugin_revision, "Plugin") diff --git a/scripts/test-portable.sh b/scripts/test-portable.sh new file mode 100755 index 0000000..9d8259a --- /dev/null +++ b/scripts/test-portable.sh @@ -0,0 +1,9 @@ +#!/bin/bash +# Run source and script checks on macOS and Linux. +set -euo pipefail +cd "$(dirname "$0")/.." +python3 scripts/version.py check +node --test Tests/schema-import.test.mjs +python3 scripts/check-host.py --help >/dev/null +python3 -m unittest discover -s Tests -p 'test_*.py' +python3 scripts/check-workflow.py --check-release-workflow diff --git a/scripts/test.sh b/scripts/test.sh index 016069d..6d529e3 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -1,17 +1,33 @@ #!/bin/bash -# Run the plugin-owned checks and produce the release archive used by CI. +# Build and validate the native release archive used by CI. set -euo pipefail cd "$(dirname "$0")/.." +smoke=true +if [[ ${1:-} == --plugin-only ]]; then + smoke=false + shift +fi if [[ $# != 1 ]]; then - echo "Usage: scripts/test.sh NEW_OUTPUT_DIRECTORY" >&2 + echo "Usage: scripts/test.sh [--plugin-only] NEW_OUTPUT_DIRECTORY" >&2 exit 2 fi output=$1 -python3 scripts/version.py check +if "$smoke"; then + fixture=${COMPUTER_MCP_TEST_HOST:?Set COMPUTER_MCP_TEST_HOST to the provisioned Host fixture directory.} + if [[ ! -f "$fixture/verify-package.py" || ! -x "$fixture/computer-mcp-plugin-smoke" ]]; then + echo "Missing provisioned Host smoke runner in $fixture" >&2 + exit 1 + fi + host_revision=$(cat .github/computer-mcp-host.sha) + if [[ ! "$host_revision" =~ ^[0-9a-f]{40}$ || "$host_revision" == 0000000000000000000000000000000000000000 ]]; then + echo "The Host pin must contain a full Git commit SHA." >&2 + exit 1 + fi +fi +scripts/test-portable.sh /usr/bin/swift package resolve git diff --exit-code -- Package.resolved scripts/verify-swift-codex-release-gate.sh -node --test Tests/schema-import.test.mjs node scripts/import-schema.mjs --check /usr/bin/swift format lint --strict --recursive Package.swift Sources Tests # These assertions measure wall-clock behavior on the current machine. @@ -20,15 +36,17 @@ timing_tests='incompleteHostStartupHasABoundedAndJoinedExit|testLargePersistedTh unit_build="$PWD/.build/plugin-tests" echo "Swift test build and wall-clock assertions" time -p /usr/bin/swift test --scratch-path "$unit_build" --disable-automatic-resolution --no-parallel --filter "$timing_tests" -python3 scripts/check-host.py --help >/dev/null -python3 -m unittest discover -s Tests -p 'test_*.py' -python3 scripts/check-workflow.py --check-release-workflow - ( echo "Release ZIP build and packaging" time -p python3 scripts/package.py --output "$output" --configuration release echo "Relocated adapter contract tests" time -p python3 Tests/PackagedAdapter.py "$output" + if "$smoke"; then + echo "Installed package smoke through the pinned Host" + archive=$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["archive"])' "$output/receipt.json") + time -p python3 "$fixture/verify-package.py" --host-revision "$host_revision" \ + --archive "$output/$archive" --case Tests/Fixtures/HostSmoke.json + fi ) & packaging=$! echo "Remaining Swift tests" From 22c7da5d3beac9bcd2ace8df4d489519b1845cf2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:02:57 +0800 Subject: [PATCH 06/16] ci: pin the Host with registered-package smoke support --- .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 58d2856..c3f902a 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -bee91275a6301e56c64f677125f5d7f38ba7fe0e +627ae1d0982446c4cd0c48f49d5689d8573359fd From 6b7e76b8770adf3039d7346f177f9983854b43cb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:13:38 +0800 Subject: [PATCH 07/16] test: share exact-pair interoperability with the Host gate --- .github/workflows/ci.yml | 4 +--- scripts/test-interop.sh | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 scripts/test-interop.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b3da47..4172222 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -98,9 +98,7 @@ jobs: git init "$host_checkout" git -C "$host_checkout" fetch --no-tags --depth=1 https://github.com/computer-mcp/computer-mcp.git "$host_revision" git -C "$host_checkout" checkout --detach FETCH_HEAD - python3 scripts/check-host.py --mode container --host-source "$host_checkout" \ - --plugin-revision "$GITHUB_SHA" --archive "$PWD/dist/codex-plugin-macos-arm64.zip" \ - --receipt "$PWD/dist/receipt.json" --output-directory "$PWD/.build/host-acceptance" + bash scripts/test-interop.sh "$host_checkout" "$host_revision" "$PWD/.build/host-acceptance" "$PWD/dist" - name: Record registered Host acceptance if: always() run: | diff --git a/scripts/test-interop.sh b/scripts/test-interop.sh new file mode 100644 index 0000000..4a0e40e --- /dev/null +++ b/scripts/test-interop.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +host=${1:?Host checkout} +revision=${2:?Host commit} +evidence=${3:?Evidence directory} +if [[ $# == 4 ]]; then + package=$4 +else + package="$evidence-package" + python3 scripts/package.py --output "$package" --configuration release +fi +exec python3 scripts/check-host.py --mode container --host-source "$host" --host-revision "$revision" \ + --plugin-revision "$(git rev-parse HEAD)" --archive "$package/codex-plugin-macos-arm64.zip" \ + --receipt "$package/receipt.json" --output-directory "$evidence" From 1bf7dc4e6909209cefc4596d3e880ea9ee38bb85 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:14:59 +0800 Subject: [PATCH 08/16] test: resolve locked dependencies for standalone interop builds --- scripts/test-interop.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/test-interop.sh b/scripts/test-interop.sh index 4a0e40e..65f90e9 100644 --- a/scripts/test-interop.sh +++ b/scripts/test-interop.sh @@ -8,6 +8,8 @@ if [[ $# == 4 ]]; then package=$4 else package="$evidence-package" + /usr/bin/swift package resolve + git diff --exit-code -- Package.resolved python3 scripts/package.py --output "$package" --configuration release fi exec python3 scripts/check-host.py --mode container --host-source "$host" --host-revision "$revision" \ From d0e48cacd5cfac0f7e498079af4a446d0072376a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 00:22:35 +0800 Subject: [PATCH 09/16] ci: verify packages with 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 c3f902a..3595d7a 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -627ae1d0982446c4cd0c48f49d5689d8573359fd +c31a32a95512cbce3f610ed9877abd1a619c3909 From 61d6e3f880717891bb4da29096d9d08f8aa7b8e9 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:01:06 +0800 Subject: [PATCH 10/16] ci: validate plugins with the reviewed 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 3595d7a..afadd47 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -c31a32a95512cbce3f610ed9877abd1a619c3909 +27dbd8223c19699435beec76786a5219389c852b From 22af74498986236f1d57f9bf488c1b802e441135 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:38:12 +0800 Subject: [PATCH 11/16] ci: isolate plugin and Host checkouts in the runner workspace --- .github/workflows/ci.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4172222..ca53639 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,9 +16,13 @@ jobs: timeout-minutes: 60 outputs: interop: ${{ steps.interop.outputs.required }} + defaults: + run: + working-directory: plugin steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + path: plugin persist-credentials: false fetch-depth: 0 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 @@ -36,9 +40,9 @@ jobs: with: repository: computer-mcp/computer-mcp ref: ${{ steps.smoke-host.outputs.revision }} - path: .agent/smoke-host + path: host persist-credentials: false - - uses: ./.agent/smoke-host/.github/actions/provision-plugin-smoke + - uses: ./host/.github/actions/provision-plugin-smoke - name: Validate and package the plugin env: BASE_COMMIT: ${{ github.event.pull_request.base.sha || github.event.before }} @@ -69,8 +73,8 @@ jobs: with: name: codex-plugin-macos-arm64-${{ github.sha }} path: | - dist/codex-plugin-macos-arm64.zip - dist/receipt.json + plugin/dist/codex-plugin-macos-arm64.zip + plugin/dist/receipt.json if-no-files-found: error retention-days: 14 From c2cdad5c119046ae78cd9347423ca91af0333782 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:31:20 +0800 Subject: [PATCH 12/16] test: scope the retirement deadline to the stalled request --- .../CodexAppServerRuntimeTests.swift | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift index 7fb7ec8..6b55f78 100644 --- a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift @@ -91,21 +91,28 @@ final class CodexAppServerRuntimeTests { func confirmedRetirementReleasesLoadedAndActiveThreadOwnership(timeout: Bool) async throws { let fixture = try AppServerProcessFixture() defer { fixture.remove() } - let runtime = fixture.makeRuntime(requestTimeoutSeconds: 1) + // Keep the short deadline on the deliberately stalled call, including after a reconnect. + let runtime = fixture.makeRuntime(appListTimeoutSeconds: 1) do { _ = try await runtime.call(method: "thread/start", params: .object([:])) - _ = try await runtime.call( + let turn = try await runtime.call( method: "turn/start", params: .object([ "threadId": .string("thread_native"), "input": .array([.object(["type": .string("text"), "text": .string("fixture")])]), ])) + #expect(turn.objectValue?["turn"]?.objectValue?["status"] == .string("inProgress")) #expect(await runtime.hasLiveOwnership(of: "thread_native")) let pid = try await fixture.waitForLatestPID(count: 1) if timeout { try Data().write(to: fixture.hangRequestsFile) - await assertThrowsErrorAsync( - try await runtime.call(method: "thread/loaded/list", params: .object([:]))) + do { + _ = try await runtime.call(method: "app/list", params: .object([:])) + Issue.record("The fixture withheld the app/list response.") + } catch { + try #require(error.localizedDescription.contains("1-second deadline")) + } + try #require(FileManager.default.fileExists(atPath: fixture.hangRequestReceivedFile.path)) } else { #expect(Darwin.kill(pid, SIGTERM) == 0) try await waitUntilRuntimeCondition { @@ -115,6 +122,11 @@ final class CodexAppServerRuntimeTests { } } let status = await runtime.status() + if timeout { + let failure = status.objectValue?["last_request_failure"]?.objectValue + #expect(failure?["kind"] == .string("request_timeout")) + #expect(failure?["message"]?.stringValue?.contains("'app/list'") == true) + } #expect(status.objectValue?["process"]?.objectValue?["cleanup_confirmed"] == .bool(true)) #expect(await waitForProcessExit(pid)) #expect(!(await runtime.hasLiveOwnership(of: "thread_native"))) @@ -124,6 +136,7 @@ final class CodexAppServerRuntimeTests { ).isEmpty) if timeout { try FileManager.default.removeItem(at: fixture.hangRequestsFile) } _ = try await runtime.call(method: "thread/loaded/list", params: .object([:])) + #expect(try await fixture.waitForLatestPID(count: 2) != pid) #expect(await runtime.hasLiveOwnership(of: "thread_fixture")) #expect(!(await runtime.hasLiveOwnership(of: "thread_native"))) await runtime.shutdown() @@ -1612,12 +1625,20 @@ struct AppServerProcessFixture { continue ;; esac - id=$(printf '%s\n' "$line" | /usr/bin/sed -E 's/.*"id":("[^"]*"|[0-9]+).*/\\1/') if [ -f "$fixture_dir/notifications-next.jsonl" ]; then /bin/cat "$fixture_dir/notifications-next.jsonl" /bin/rm "$fixture_dir/notifications-next.jsonl" while [ -f "$fixture_dir/hold-notification-response" ]; do /bin/sleep 0.01; done fi + if [ -f "$fixture_dir/hang-requests" ]; then + case "$line" in + *'"app'*'/list"'*|*thread*loaded*list*) + : > "$fixture_dir/hang-request-received" + continue + ;; + esac + fi + id=$(printf '%s\n' "$line" | /usr/bin/sed -E 's/.*"id":("[^"]*"|[0-9]+).*/\\1/') case "$line" in *remoteControl*enable*|*remoteControl*disable*) printf '{"id":%s,"result":{"status":"disabled","installationId":"fixture-installation","serverName":"fixture"}}\n' "$id" @@ -1633,11 +1654,10 @@ struct AppServerProcessFixture { *mcpServer*oauth*login*) printf '{"id":%s,"result":{"authorizationUrl":"https://example.invalid/oauth"}}\\n' "$id" ;; + *'"app'*'/list"'*) + printf '{"id":%s,"result":{"data":[],"nextCursor":null}}\\n' "$id" + ;; *thread*loaded*list*) - if [ -f "$fixture_dir/hang-requests" ]; then - : > "$fixture_dir/hang-request-received" - continue - fi while [ -f "$fixture_dir/hold-loaded-threads" ]; do /bin/sleep 0.01; done if [ -f "$fixture_dir/loaded-threads.json" ]; then loaded=$(/bin/cat "$fixture_dir/loaded-threads.json") @@ -1728,6 +1748,7 @@ struct AppServerProcessFixture { func makeRuntime( requestTimeoutSeconds: Int = CodexConfig().appServerRequestTimeoutSeconds, + appListTimeoutSeconds: Int = CodexConfig().appServerAppListTimeoutSeconds, approvalTimeoutSeconds: Int = 300, database: CodexDatabase? = nil, workspaceID: String? = "fixture-workspace", @@ -1740,6 +1761,7 @@ struct AppServerProcessFixture { executable: executable.path, execEnabled: false, appServerRequestTimeoutSeconds: requestTimeoutSeconds, + appServerAppListTimeoutSeconds: appListTimeoutSeconds, appServerTerminationGraceMilliseconds: 200, appServerKillGraceMilliseconds: 1_000, appServerApprovalTimeoutSeconds: approvalTimeoutSeconds, From d54ec7d301ced42ff4e511c1fe234cece5f03d56 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:27:25 +0800 Subject: [PATCH 13/16] test: keep setup off short App Server deadlines --- .../CodexAppServerRuntimeTests.swift | 4 +-- .../CodexAppWorkOwnershipTests.swift | 3 +- .../CodexValidationCleanupTests.swift | 34 +++++++++++-------- 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift index 6b55f78..f3c8566 100644 --- a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift @@ -576,7 +576,7 @@ final class CodexAppServerRuntimeTests { defer { fixture.remove() } try Data().write(to: fixture.holdLoadedThreadsFile) defer { try? FileManager.default.removeItem(at: fixture.holdLoadedThreadsFile) } - let runtime = fixture.makeRuntime(requestTimeoutSeconds: 10) + let runtime = fixture.makeRuntime() async let first = runtime.call(method: "thread/loaded/list", params: .object([:])) try await waitUntilRuntimeCondition { @@ -676,7 +676,6 @@ final class CodexAppServerRuntimeTests { try fixture.configureFileApproval(grantRoot: fixture.directory.path) let database = try CodexDatabase(inMemory: ()) let runtime = fixture.makeRuntime( - requestTimeoutSeconds: 3, approvalTimeoutSeconds: 1, database: database ) @@ -714,7 +713,6 @@ final class CodexAppServerRuntimeTests { try Data().write(to: fixture.closeInputAfterApprovalRequestFile) let database = try CodexDatabase(inMemory: ()) let runtime = fixture.makeRuntime( - requestTimeoutSeconds: 10, approvalTimeoutSeconds: 1, database: database ) diff --git a/Tests/CodexAdapterTests/CodexAppWorkOwnershipTests.swift b/Tests/CodexAdapterTests/CodexAppWorkOwnershipTests.swift index 3fc4c90..ceead2e 100644 --- a/Tests/CodexAdapterTests/CodexAppWorkOwnershipTests.swift +++ b/Tests/CodexAdapterTests/CodexAppWorkOwnershipTests.swift @@ -1028,8 +1028,7 @@ struct CodexAppWorkOwnershipTests { ) async throws { let fixture = try AppServerProcessFixture() defer { fixture.remove() } - let runtime = fixture.makeRuntime( - requestTimeoutSeconds: 10, workspaceID: fixture.directory.lastPathComponent) + let runtime = fixture.makeRuntime(workspaceID: fixture.directory.lastPathComponent) do { try await body(fixture, runtime) await runtime.shutdown() diff --git a/Tests/CodexAdapterTests/CodexValidationCleanupTests.swift b/Tests/CodexAdapterTests/CodexValidationCleanupTests.swift index 0ab343e..bcfcfba 100644 --- a/Tests/CodexAdapterTests/CodexValidationCleanupTests.swift +++ b/Tests/CodexAdapterTests/CodexValidationCleanupTests.swift @@ -113,22 +113,29 @@ final class CodexValidationCleanupTests { func testValidationCleanupStopsOnlyTheExactOwnedRuntime() async throws { let fixture = try ValidationRuntimeFixture() defer { fixture.remove() } - let owner = validationOwner(connectionID: "validation-owned-runtime") - let runtime = fixture.makeRuntime(owner: owner) - _ = try await runtime.call(method: "thread/loaded/list", params: .object([:])) - let status = await runtime.status() - let ownedProcessID = try #require( - status.objectValue?["process"]?.objectValue?["process_id"]?.intValue.flatMap(Int32.init) - ) + let sentinelInput = Pipe() let unrelated = Process() - unrelated.executableURL = URL(fileURLWithPath: "/bin/sleep") - unrelated.arguments = ["10"] + unrelated.executableURL = URL(fileURLWithPath: "/bin/cat") + unrelated.standardInput = sentinelInput try unrelated.run() let unrelatedProcessID = unrelated.processIdentifier defer { - if unrelated.isRunning { - unrelated.terminate() - } + try? sentinelInput.fileHandleForWriting.close() + unrelated.waitUntilExit() + } + + let owner = validationOwner(connectionID: "validation-owned-runtime") + let runtime = fixture.makeRuntime(owner: owner) + let ownedProcessID: Int32 + do { + _ = try await runtime.call(method: "thread/loaded/list", params: .object([:])) + let status = await runtime.status() + ownedProcessID = try #require( + status.objectValue?["process"]?.objectValue?["process_id"]?.intValue.flatMap(Int32.init) + ) + } catch { + await runtime.shutdown() + throw error } let target = CodexValidationCleanupTarget( owner: owner, @@ -167,7 +174,7 @@ final class CodexValidationCleanupTests { #expect(outcome.value == "primary-passed") #expect(outcome.cleanup.warnings.isEmpty) #expect(!validationProcessExists(ownedProcessID)) - #expect(validationProcessExists(unrelatedProcessID)) + #expect(unrelated.isRunning && validationProcessExists(unrelatedProcessID)) } } @@ -229,7 +236,6 @@ private struct ValidationRuntimeFixture { enabled: true, executable: executable.path, execEnabled: false, - appServerRequestTimeoutSeconds: 2, appServerTerminationGraceMilliseconds: 200, appServerKillGraceMilliseconds: 1_000, approvalPolicy: .never From eb64f4af43fabaff5eb901d18d7176301e72ceb6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:44:12 +0800 Subject: [PATCH 14/16] test: keep fixture registration synchronous --- .../RegisteredHost/RegisteredHost.swift | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift index 620efef..39b3f47 100644 --- a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift +++ b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift @@ -50,7 +50,7 @@ struct RegisteredHost { private static func run(root: URL, command: String, observer: StdioTransport?) async throws { let database = try GatewayDatabase(path: root.appendingPathComponent("host.sqlite").path) - _ = database.permissionStore( + let permissionStore = database.permissionStore( counter: FixtureEpochCounter(file: root.appendingPathComponent("fixture-epoch.json"))) var services = MacOSPlatform.services services.permissionPolicyReader = FixturePolicySources() @@ -62,14 +62,17 @@ struct RegisteredHost { try database.bootstrapPermissionProfiles( configuration.profiles.map(\.grant), declarations: configuration.profiles.map(\.grant)) try database.registerManifestProjectsForStartup(configuration.manifestProjects) + if command == "register" { + // Registration owns no executions and exits after its authoring transactions commit. + let permissionService = GatewayPermissionService( + store: permissionStore, policyReader: platform.permissionPolicyReader) + try await registerPlugin( + root: root, database: database, store: store, permissionService: permissionService) + return + } let permissionRuntime = try database.permissionRuntime(platform: platform) try await permissionRuntime.ready() switch command { - case "register": - try await registerPlugin( - root: root, database: database, store: store, permissionRuntime: permissionRuntime, - configuration: configuration) - return case "deny-source", "restore-source": try await setSourceAccess( root: root, database: database, permissionRuntime: permissionRuntime, @@ -211,7 +214,7 @@ struct RegisteredHost { private static func registerPlugin( root: URL, database: GatewayDatabase, store: PluginStore, - permissionRuntime: GatewayPermissionRuntime, configuration: GatewayConfiguration + permissionService: GatewayPermissionService ) async throws { let source = root.appendingPathComponent("plugin", isDirectory: true) let package = try PluginPackage.load(at: source) @@ -233,7 +236,7 @@ struct RegisteredHost { _ = try await store.setSettings(settings, for: "codex", expectedRevision: registered.revision) let owner = try owner() - let view = try permissionRuntime.service.view(owner: owner) + let view = try permissionService.view(owner: owner) guard let epoch = view.epoch else { throw FixtureError.missingEpoch } let review = try GatewayProviderReview( package: package, configuration: database.configurationState()) @@ -243,7 +246,7 @@ struct RegisteredHost { for id in projectIDs { try permissions.set(.granted(.write), for: .project(id)) } - let approval = try permissionRuntime.service.approveProvider( + let approval = try permissionService.approveProvider( review, permissions: permissions, fullAccess: false, owner: owner, expectedProviderRevision: nil, expectedRevision: view.revision, expectedEpoch: epoch) guard approval.enabled, approval.sourceDigest == review.sourceDigest else { From b213800a27307f3ae04bc8c338a15329e4c25a96 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:18:02 +0800 Subject: [PATCH 15/16] ci: pin interoperability to the merged 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 afadd47..7bb883c 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -27dbd8223c19699435beec76786a5219389c852b +941999d411e2a0f1626cc124a3679748804ce2f2 From 526a4e5da118ec4665b9a801bb2882747ba385d8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:47:57 +0800 Subject: [PATCH 16/16] fix: request the correct media type for release downloads --- Tests/test_plugin_release.py | 24 ++++++++++++++++++++++-- scripts/plugin_release.py | 13 +++++++------ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/Tests/test_plugin_release.py b/Tests/test_plugin_release.py index d5e7f00..519384f 100644 --- a/Tests/test_plugin_release.py +++ b/Tests/test_plugin_release.py @@ -176,7 +176,7 @@ def list(self, path, key=None): raise AssertionError(("LIST", route)) return copy.deepcopy(result) - def download(self, path): + def download(self, path, *, accept): route = self._record("DOWNLOAD", path) if route.startswith("/actions/artifacts/"): return self.artifact_bytes[int(route.split("/")[3])] @@ -530,6 +530,25 @@ def test_artifact_id_digest_ownership_and_download_bytes_are_checked(self): self.api.artifact_bytes[20] += b"tampered" self.assert_no_writes(self.verify, "Downloaded CI artifact digest mismatch") + def test_downloads_use_endpoint_media_types_and_preserve_bytes(self): + transport = release.GitHub("fake") + self.api.add_draft() + payload = b"\x00\xffrelease asset\r\n" + asset = self.api.add_asset(ARCHIVE, payload) + responses = [io.BytesIO(self.api.artifact_bytes[20]), io.BytesIO(payload)] + ci = {"run_id": 10, "run_attempt": 1, + "artifacts": [{"id": 20, "digest": self.api.artifacts[20]["digest"]}]} + with patch.object(transport.opener, "open", side_effect=responses) as open_request, \ + patch.object(self.api, "download", transport.download): + self.assertEqual(release.get_ci_files(self.api, REPOSITORY, COMMIT, ci, [ARCHIVE]), self.native) + self.assertEqual(release.read_asset(self.api, API_ROOT, asset), payload) + + requests = [call.args[0] for call in open_request.call_args_list] + self.assertEqual([(request.full_url, request.get_header("Accept")) for request in requests], [ + (f"https://api.github.com{API_ROOT}/actions/artifacts/20/zip", "application/vnd.github+json"), + (f"https://api.github.com{API_ROOT}/releases/assets/{asset['id']}", "application/octet-stream"), + ]) + def test_native_receipt_inventory_and_manifest_are_checked_as_data(self): for change in ("inventory", "manifest", "receipt", "name"): with self.subTest(change=change): @@ -679,7 +698,8 @@ def test_publish_only_retry_uses_original_artifact_id_and_digests(self): runner = case.root / ("publisher-" + str(attempt)) bundle = runner / "plugin-release" bundle.mkdir(parents=True) - data = case.api.download(API_ROOT + "/actions/artifacts/" + artifact_id + "/zip") + data = case.api.download(API_ROOT + "/actions/artifacts/" + artifact_id + "/zip", + accept="application/vnd.github+json") for name, content in release.zip_entries(data).items(): path = bundle / name path.parent.mkdir(parents=True, exist_ok=True) diff --git a/scripts/plugin_release.py b/scripts/plugin_release.py index 3ebd97a..8ad83a5 100644 --- a/scripts/plugin_release.py +++ b/scripts/plugin_release.py @@ -82,11 +82,12 @@ def __init__(self, token): self.token = token self.opener = build_opener(SafeRedirect()) - def _request(self, method, path, data=None, content_type="application/json", binary=False): + def _request(self, method, path, data=None, content_type="application/json", *, + accept="application/vnd.github+json", binary=False): host = "https://uploads.github.com" if method == "POST" and "/assets?" in path else "https://api.github.com" require(path.startswith("/repos/") and not path.startswith("//"), "Invalid GitHub API path") headers = {"Authorization": f"Bearer {self.token}", "X-GitHub-Api-Version": "2022-11-28", - "Accept": "application/octet-stream" if binary else "application/vnd.github+json", + "Accept": accept, "Content-Type": content_type} body = data if isinstance(data, bytes) else json.dumps(data).encode() if data is not None else None try: @@ -111,8 +112,8 @@ def list(self, path, key=None): return result raise ReleaseError("GitHub pagination exceeded its limit") - def download(self, path): - return self._request("GET", path, binary=True) + def download(self, path, *, accept): + return self._request("GET", path, accept=accept, binary=True) def send(self, method, path, data=None, content_type="application/json"): return self._request(method, path, data, content_type) @@ -258,7 +259,7 @@ def get_ci_files(api, repository, commit, ci, declared, recovering=False): names = [name for name in declared if artifact.get("name") == name[:-4] + "-" + commit] require(len(names) == 1, "CI artifact name differs from the manifest") name = names[0] - data = api.download(f"{root}/actions/artifacts/{source['id']}/zip") + data = api.download(f"{root}/actions/artifacts/{source['id']}/zip", accept="application/vnd.github+json") except APIError as error: if recovering and error.status in (404, 410): raise ReleaseError(recovery) from None @@ -296,7 +297,7 @@ def release_assets(api, root, release): def read_asset(api, root, asset): require(asset.get("state") == "uploaded", "Release asset is incomplete") - data = api.download(f"{root}/releases/assets/{asset['id']}") + data = api.download(f"{root}/releases/assets/{asset['id']}", accept="application/octet-stream") require(sha256(data) == digest_value(asset.get("digest")) and len(data) == asset.get("size"), "Release asset download differs from its API digest or size") return data