diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 58d2856..7bb883c 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -bee91275a6301e56c64f677125f5d7f38ba7fe0e +941999d411e2a0f1626cc124a3679748804ce2f2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5bdde58..f30afee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,9 +14,15 @@ jobs: package: runs-on: macos-latest 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 @@ -24,50 +30,70 @@ jobs: python-version: '3.13' - name: Install dependency gate tooling run: brew install jq ripgrep - - name: Validate Swift package + - 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: host + persist-credentials: false + - 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 }} 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: | + plugin/dist/codex-plugin-macos-arm64.zip + plugin/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) @@ -76,9 +102,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: | @@ -86,18 +110,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@d1235cc8d2d86df99770c30b5a0b64469085e931 with: needs-json: ${{ toJSON(needs) }} + optional-jobs: ${{ needs.package.outputs.interop == 'false' && '["interop"]' || '[]' }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 66bb202..d8f22e4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,25 +6,25 @@ 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`, `ripgrep`, and the provisioned +Host fixture for the commit in [the Host pin](.github/computer-mcp-host.sha). ```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 +COMPUTER_MCP_TEST_HOST=/absolute/path/to/fixture 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. 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 96291f9..71f3951 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -89,17 +89,28 @@ 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 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 +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: @@ -113,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/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/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift index f6cb21c..f3c8566 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() @@ -561,10 +574,9 @@ 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. - let runtime = fixture.makeRuntime(requestTimeoutSeconds: 10) + try Data().write(to: fixture.holdLoadedThreadsFile) + defer { try? FileManager.default.removeItem(at: fixture.holdLoadedThreadsFile) } + let runtime = fixture.makeRuntime() async let first = runtime.call(method: "thread/loaded/list", params: .object([:])) try await waitUntilRuntimeCondition { @@ -578,6 +590,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")) @@ -663,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 ) @@ -701,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 ) @@ -722,9 +733,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 +1533,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 +1552,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( @@ -1613,12 +1623,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" @@ -1634,14 +1652,11 @@ 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 - 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 @@ -1731,6 +1746,7 @@ struct AppServerProcessFixture { func makeRuntime( requestTimeoutSeconds: Int = CodexConfig().appServerRequestTimeoutSeconds, + appListTimeoutSeconds: Int = CodexConfig().appServerAppListTimeoutSeconds, approvalTimeoutSeconds: Int = 300, database: CodexDatabase? = nil, workspaceID: String? = "fixture-workspace", @@ -1743,6 +1759,7 @@ struct AppServerProcessFixture { executable: executable.path, execEnabled: false, appServerRequestTimeoutSeconds: requestTimeoutSeconds, + appServerAppListTimeoutSeconds: appListTimeoutSeconds, appServerTerminationGraceMilliseconds: 200, appServerKillGraceMilliseconds: 1_000, appServerApprovalTimeoutSeconds: approvalTimeoutSeconds, 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/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/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 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/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 { diff --git a/Tests/PackagedAdapter.py b/Tests/PackagedAdapter.py new file mode 100644 index 0000000..86ff79b --- /dev/null +++ b/Tests/PackagedAdapter.py @@ -0,0 +1,342 @@ +"""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] +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 + 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, smoke_case): + 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") + 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) + 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, 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) + 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()) + 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"]), smoke_case) + + +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 b271613..4991004 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -6,12 +6,15 @@ import json from pathlib import Path import subprocess +import sys import tempfile +import threading from types import SimpleNamespace import unittest 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) @@ -58,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) @@ -70,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: @@ -203,6 +226,57 @@ 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", + "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/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/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/check-host.py b/scripts/check-host.py index efea077..b47acd7 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -9,7 +9,7 @@ """ import argparse -from contextlib import closing +from concurrent.futures import ThreadPoolExecutor import hashlib import json import os @@ -18,7 +18,6 @@ import re import shutil import signal -import sqlite3 import subprocess import sys import tarfile @@ -28,18 +27,15 @@ 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 - - -def require(condition, detail): - if not condition: - raise AssertionError(detail) +STEP_OUTPUT_LOCK = threading.Lock() def executable(value): @@ -81,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") @@ -97,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": @@ -139,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") @@ -166,6 +166,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 +182,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)} @@ -216,20 +215,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 ( @@ -328,74 +313,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"] @@ -496,7 +413,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 +757,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) @@ -859,116 +777,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" @@ -1499,13 +1307,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 +1333,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 +1421,51 @@ 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" diff --git a/scripts/mcp_client.py b/scripts/mcp_client.py new file mode 100644 index 0000000..3a1f2e8 --- /dev/null +++ b/scripts/mcp_client.py @@ -0,0 +1,81 @@ +"""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/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 diff --git a/scripts/test-interop.sh b/scripts/test-interop.sh new file mode 100644 index 0000000..65f90e9 --- /dev/null +++ b/scripts/test-interop.sh @@ -0,0 +1,17 @@ +#!/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" + /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" \ + --plugin-revision "$(git rev-parse HEAD)" --archive "$package/codex-plugin-macos-arm64.zip" \ + --receipt "$package/receipt.json" --output-directory "$evidence" 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 new file mode 100755 index 0000000..6d529e3 --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# 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 [--plugin-only] NEW_OUTPUT_DIRECTORY" >&2 + exit 2 +fi +output=$1 +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 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' +# Keep SwiftPM's test plan separate from the release packaging build. +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" +( + 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" +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"