From 505958bf7c99e22d49af7526292b37fe26525be6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:21:40 +0800 Subject: [PATCH 01/25] feat(worktrees): delegate Codex project lifecycle to host services --- Documentation/Architecture/Package.md | 98 +- Documentation/Reference/HostIntegration.md | 128 +- Documentation/Reference/Workflows.md | 51 +- README.md | 9 +- Sources/CodexAdapter/CodexAdapterServer.swift | 9 +- .../CodexAppServerMethodCatalog.swift | 2 +- .../CodexAdapter/CodexAppServerProvider.swift | 224 ++-- .../CodexDatabase+HostWorktrees.swift | 352 +++++ Sources/CodexAdapter/CodexDatabase.swift | 258 ++-- .../CodexAdapter/CodexExecutionProvider.swift | 2 +- Sources/CodexAdapter/CodexHostMCPClient.swift | 128 +- Sources/CodexAdapter/CodexHostServices.swift | 33 +- Sources/CodexAdapter/CodexHostWorktree.swift | 261 ++++ .../CodexHostWorktreeManager.swift | 178 +++ Sources/CodexAdapter/CodexLaunchContext.swift | 41 +- .../CodexManagedWorkspaceHost.swift | 12 - .../CodexAdapter/CodexManagedWorktree.swift | 806 +---------- Sources/CodexAdapter/CodexOperationRisk.swift | 12 + .../CodexOperationalDiagnostics.swift | 33 +- .../CodexAdapter/CodexProjectServices.swift | 148 ++ .../CodexWorktreeFileSystem.swift | 93 -- Sources/CodexAdapter/CodexWorktreeLease.swift | 47 +- .../MCPInheritedSocketTransport.swift | 23 +- .../CodexAppServerProviderTests.swift | 2 +- .../CodexDatabaseSchemaTests.swift | 90 +- .../CodexHostMCPClientTests.swift | 84 +- .../CodexLaunchContextTests.swift | 20 +- .../CodexManagedWorktreeTests.swift | 1189 +++++++---------- .../CodexOperationalDiagnosticsTests.swift | 8 +- .../CodexWorkContinuationTests.swift | 2 +- computer-mcp-plugin.toml | 1 + scripts/check-workflow.py | 8 +- 32 files changed, 2184 insertions(+), 2168 deletions(-) create mode 100644 Sources/CodexAdapter/CodexDatabase+HostWorktrees.swift create mode 100644 Sources/CodexAdapter/CodexHostWorktree.swift create mode 100644 Sources/CodexAdapter/CodexHostWorktreeManager.swift delete mode 100644 Sources/CodexAdapter/CodexManagedWorkspaceHost.swift create mode 100644 Sources/CodexAdapter/CodexProjectServices.swift delete mode 100644 Sources/CodexAdapter/CodexWorktreeFileSystem.swift diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 7d4ca81..826e7ef 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -218,55 +218,43 @@ events, native approvals, user input, connection generations, cancellation, shutdown and handoff. Lease-based reconciliation checks the exact receipted processes before declaring an uncoordinated owner gone. -`CodexDatabase` stores approvals, runtime leases, thread ownership, -reconciliation receipts, acceptance runs, worktree leases and managed-worktree receipts using their -existing row and JSON representations. -It uses one initial domain schema and GRDB transactions; it does -not store host profiles, credentials, workspace registrations or audit. -Unknown migration identifiers fail before either the domain or shared-lease -store is initialized. Use a fresh adapter state directory for an incompatible -schema. The separate shared-lease database initializes only its lease table and -index. -Host-launched storage is partitioned by verified subject, profile and registered -workspace, not a transient connection or channel. Reconnection retains this -identity. Worktree lease facts use one transactional store per subject and -profile, so a registered child workspace and its source observe the same lease -revision. Tool access remains workspace-bound; cross-workspace lineage requires -a managed-worktree receipt created by the source's verified host registration. -Other domain records remain workspace-partitioned. -Existing unbound storage is preserved and reported for local review; -it is never silently assigned to a new subject. A shared, transactional native -thread-owner index prevents concurrent claims or reads by another subject. -Read-only history lookup does not claim a thread. - -`CodexHostTools` requires host preflight plus per-execution authorization and -audit. Native Codex approvals retain official decisions and scopes; host-tool -approvals remain under the host's own authority. -`CodexHostMCPClient` uses the explicitly delegated standard MCP connection. -Its verified subject is fixed, while the host checks current grants for each -call. Tool arguments cannot select authority or an administrator socket. - -`CodexManagedWorktreeManager` owns Git planning, creation, ownership checks and -removal, preserving the stored revision and source-workspace scope. -`CodexManagedWorkspaceHost` owns derived-workspace registration and grants, -registration rollback, and destructive-operation authorization. Removal requires -that authorization before changing either Git or the lifecycle receipt. - -`CodexOperationalDiagnostics` correlates adapter-owned state with a bounded, -scope-matched `CodexHostDiagnostics` snapshot. Host audit data stays host-owned; -missing host data produces explicit unknown values. Audit projection -retains identifiers and digests, redacts strings, and excludes command bodies. -The executable's launch factory supplies these interfaces when the host provides -its inherited MCP descriptor. Without it, managed-worktree mutations remain -unavailable and host diagnostic fields remain unknown. Vendor subprocesses do -not receive the host descriptor or reserved context. The host chooses the -managed root separately from adapter-domain persistence. - -Removal preserves a `removing` receipt when Git succeeded but host cleanup did -not. A new reviewed operation validates path absence and Git state before -retrying metadata only. Provision rollback preserves Git content when host -cleanup is unconfirmed; it never represents that case as a complete rollback. -See [Host integration](../Reference/HostIntegration.md) for the operator contract. +`CodexDatabase` stores approvals, native runtime and thread ownership, +reconciliation receipts, acceptance runs and worktree history. The primary +database is partitioned by verified principal, profile and selected project. +The native thread-owner index coordinates claims independently. + +The principal/profile lease database also owns new host-backed worktree +associations and operations. Source and child projections use the same +transactional writer, scoped to their host-returned association. Separate +transactions validate primary run references and persist worktree state. +Worktree migrations run before the provider is published. Legacy worktree +rows retain their original identities and lifecycle states as unmanaged +history in the primary database. Unbound history stays in its original store. +Unknown migrations fail before either required database is migrated. + +`CodexHostTools` preflights dynamic callbacks and rechecks authorization at +execution. Native Codex approvals retain official decisions and scopes. +`CodexHostMCPClient` uses the inherited MCP connection with its immutable +verified subject and selected project. Its typed project service methods +preserve complete host responses. Both peers advertise `projects-v1`. + +`CodexHostWorktreeManager` records plans and commits the invocation and +operation IDs before private lifecycle calls. On creation, the shared writer +settles the host association and the lease disposition in one transaction. +A competing lease can coexist with a completed creation. Computer MCP +executes Git operations and controls project registration and removal. + +Pending operations survive adapter restart. A fresh, authorized managed +worktree read inspects the retained operation ID and can settle its observed +state. The source remains available for this read after the child is removed. +Host recovery owns unresolved effects. + +`CodexOperationalDiagnostics` combines adapter records with bounded, +scope-matched host audit observations. It projects identifiers and digests and +redacts diagnostic strings. The launch factory supplies host interfaces only +with the inherited descriptor. Vendor subprocesses receive their own execution +context. See [Host integration](../Reference/HostIntegration.md) for the +operator contract. ## Runtime generations and teardown @@ -317,11 +305,11 @@ Standard-MCP dispatch tests use controlled execution doubles and an isolated protocol process with a durable database. These fixtures do not prove native model authentication or host-to-adapter integration. -Managed-worktree tests also use private Git repositories and two workspace-bound -MCP connections. They verify lease scope, active/dirty worktree protection, -host denial without mutation, durable removal and branch preservation. -The workspace and diagnostic host implementations in these tests are test -doubles, not evidence of a connected Computer MCP control plane. +Worktree tests use typed host doubles, separate source and child database +connections, and standard MCP dispatch. They exercise reviewed argument +presence, durable operation binding, lease contention, migration and +inspection after a lost reply. Paired acceptance uses the actual adapter +and host with an isolated deterministic vendor peer. The exposed execution surface includes App Server and Exec. Version-specific schemas remain separate inspection tools. The package exports an executable, not a @@ -345,7 +333,7 @@ acceptance before promoting an artifact to a public release. ## Inherited host channel -The host binds callbacks to its own immutable caller/workspace scope over an +The host binds callbacks to its own immutable caller and project scope over an inherited connected Unix socket. `COMPUTER_MCP_HOST_FD` selects a canonical descriptor from 3 through 9 alongside the host context. The transport requires a connected stream socket, sets close-on-exec and nonblocking mode, and bounds diff --git a/Documentation/Reference/HostIntegration.md b/Documentation/Reference/HostIntegration.md index c58588e..2794d0e 100644 --- a/Documentation/Reference/HostIntegration.md +++ b/Documentation/Reference/HostIntegration.md @@ -3,14 +3,14 @@ Set `hostServices: true` in the Computer MCP host's local settings for this plugin's `app-server` MCP contribution. The App exposes the same choice as **Allow scoped host services**. It is separate from enabling the plugin, -selecting its tools and granting a profile access to the workspace. A plugin +selecting its tools and granting a profile access to the project. A plugin manifest cannot turn it on. A direct stdio registration uses `host_services`. The host starts the adapter with a connected Unix descriptor and immutable scope. `CodexHostMCPClient` uses standard MCP to call the host; it does not open the control socket, read the host database or start another service. Standalone launches without that descriptor retain ordinary configured Codex -execution but cannot perform host-owned registration operations. +execution but cannot perform host-owned worktree operations. `codex.app.ownership.reconcile.perform` is a local-control operation. A remote-bound adapter omits it from its MCP tool catalog and rejects attempts @@ -19,9 +19,8 @@ to invoke it directly. The host-established caller scope determines visibility. ## Approval and execution Dynamic vendor tools are preflighted against the current host scope, then -executed with a fresh check. Destructive operations retain host-issued -prepare/commit tickets. A changed classification requires a new approval rather -than converting an earlier read-only decision into a mutation. +executed with a fresh check. Host callbacks carry the selected `project_id`. +A changed classification requires a fresh approval. Native Codex Full Access follows the user's Codex configuration or explicit native request. The host decides whether the caller may invoke Codex; it does @@ -43,14 +42,18 @@ minimum risk, never to reduce a configured restriction or grant access. `codex.app.methods.list` provides the same per-method classification for configuration review. MCP annotations remain advisory. -The three private host-service consumers also declare -`io.github.computer-mcp/host-action`: diagnostics uses `diagnostics.snapshot`, -provisioning uses `workspaces.provision`, and removal uses `workspaces.remove`. -The host binds the recognized effect to the admitted invocation and operation -ticket together with the exact arguments. The declaration grants no authority; -the host enforces its minimum risk and rejects a changed effect before dispatch. -Released hosts that recognize the original Codex method names remain compatible. -Codex's persisted worktree IDs retain their existing identity on either host. +The package contribution and both MCP initialization responses identify the +`projects-v1` contract. The adapter also checks the host launch context before +sending lifecycle requests. A missing or mismatched contract produces +`host.unsupported_contract`. Update Computer MCP and the Codex plugin together +and restart the provider. + +Tool metadata declares `io.github.computer-mcp/host-action` for diagnostics +(`diagnostics.snapshot`) and the worktree effects (`projects.provision`, +`projects.list`, `projects.remove`). The host binds each effect to the admitted +invocation and supplies the operation ID for a mutation. Narrow project +mutations declare `project-write`. Native Codex sandbox values keep their vendor +meaning. Metadata/history/event inspection declares `read-only`. Narrow filesystem and metadata mutations retain their effect classification. Exec cancellation and @@ -59,50 +62,50 @@ than submit new model input. Native turn interruption differs because Codex can run an Interrupt command hook. A host emergency-revocation action is a separate host-owned control, not a promise that a vendor cancellation RPC has no hooks. -Native approval responses use official response objects, including session -scope, amendments, refusal and cancellation. Responses bind to their original -SDK server request and can be consumed only once. Host destructive operations -use explicit `operations.prepare`, local confirmation and `operations.commit`; -the adapter never manufactures approval by automatically consuming a ticket. - -## Managed workspaces - -The host supplies the managed root beside its file-backed state. The plugin -plans and executes Git operations; the host validates exact repository/path -identity before transactionally adding its registration and profile grant. -The plugin's database holds the plan, lease and lifecycle receipt, not host -workspace authority. Each receipt binds the verified principal, profile and -source workspace; channel names are audit metadata. Unbound historical receipts -remain inspectable but cannot authorize mutations. A new child connection must resolve the newly registered -workspace before releasing its child lease. Lease revisions are shared across -that subject's profile-bound workspace connections and survive adapter restart; -the source observes the child's release before approving removal. Lease tools -cannot read or mutate a different workspace's lease, and unrelated workspaces -cannot claim managed parent lineage. - -Use the existing `provision.plan` / `provision.perform` and `remove.plan` / -`remove.perform` workflows. Removal requires a released lease, no live owner, -a reviewed clean worktree and an executing host ticket. Independent registration -edits or another profile's grants are not silently deleted. Branches survive -ordinary removal. - -When Git has already removed the directory but registration cleanup fails, -`managed.read` reports `removing` with the error. Run `remove.plan` again, -review the current receipt, and obtain a new host prepare/commit ticket for -`remove.perform` with its new revision. Both sides verify absence of the path -and Git registration before metadata-only cleanup. It never repeats the Git -delete, and it refuses a new path that appeared at the old location. - -When a failed provision cannot confirm host rollback, its failed receipt reports -incomplete recovery and preserves remaining worktree/branch content. Inspect -both domain and host records before manual reconciliation. An uncertain result, -plugin uninstall, or failed test does not authorize deleting independently -changed content. +Native approval responses bind to the original SDK server request and can be +consumed once. The host applies its own authorization and confirmation to +callbacks. + +## Host worktrees + +Codex stores reviewed selections and writer leases. Computer MCP owns creation, +repository topology, verified project registration, Git recovery and removal. +The source and child adapters share only their associated worktree and its +operations within the verified principal and profile. Other Codex records stay +in the selected project's state directory. + +Plan and provision in the source project. Copy the returned `perform_arguments`, +including any explicit nulls. Omitted or null `branch` selects +`worktree/`. Omitted or null `base` selects the source main checkout's +current branch when the host reserves the perform call. Supply an explicit base +branch for a detached source. The resolved result includes the child project, +worktree ID, checkout path, branch, base and warnings. Lease disposition is +reported separately. If the child has a conflicting writer lease, settle that +lease before acquiring one explicitly in the child. + +Select the returned child project to release its Codex writer lease and plan +removal. The review binds `force`, which defaults to false. The host drains +writers, retains recoverable Git roots, publishes the committed result, then +removes the checkout and unregisters the child. Force authorizes discarding +uncommitted changes. The branch remains available in the source. + +The adapter records the invocation and operation IDs before requesting an +effect. If a reply is lost, or removal terminates the child adapter, read the +record with `codex.worktree.managed.read` from the source project. The same +operation ID is inspected under current host authorization. A pending or +recovery-required outcome stays attached to that operation until the host +resolves it. A terminal refusal needs a fresh plan and invocation. A subsequent +owner permission answer does not resume the original call. + +`codex.worktree.managed.list` includes host inventory, Codex records and +unmanaged history. Foreign inventory is visible without a Codex association. +Existing plugin-created records remain unmanaged across upgrade and expiry. +Lease expiry changes metadata only. ## Diagnostics `codex.diagnostics.snapshot` combines adapter state with host records only when -this callback service is available. The host filters records by workspace, +this callback service is available. The host filters records by project, verified subject and profile before limiting the result. Connection and channel identifiers remain audit metadata, not new authorization subjects. It exposes receipt IDs and digests rather than command bodies or secrets. Native configuration overrides and actual resolved configuration remain @@ -116,22 +119,21 @@ separate checks from the host callback protocol. Use the host's generic tool command with the exported name. The examples assume an empty MCP registration prefix; prepend the configured prefix when present. -IDs come from the registered workspace and returned native thread: +Use the registered project ID and returned native thread ID. ```sh computer-mcp tools call codex.app.handoff.diagnose --arguments-json \ - '{"workspace_id":"","thread_id":"","observed_error":""}' + '{"project_id":"","thread_id":"","observed_error":""}' computer-mcp tools call codex.diagnostics.snapshot --arguments-json \ - '{"workspace_id":"","limit":100}' + '{"project_id":"","limit":100}' computer-mcp tools call codex.app.thread.release --arguments-json \ - '{"workspace_id":"","thread_id":""}' + '{"project_id":"","thread_id":""}' computer-mcp tools call codex.app.thread.recent --arguments-json \ - '{"workspace_id":"","thread_id":""}' + '{"project_id":"","thread_id":""}' ``` -When calling indirectly with `mcp.tools.call`, put `workspace_id` beside -`server`, `tool` and `arguments`; only native plugin arguments go inside -`arguments`. Native names and exported host names need not be identical. +When calling indirectly with `mcp.tools.call`, put `project_id` beside +`server`, `tool` and `arguments`. Put plugin arguments inside `arguments`. Native names and exported host names need not be identical. The handoff diagnosis distinguishes these classifications: @@ -166,8 +168,8 @@ Thread and turn responses report applied native permissions. Omitted settings inherit Codex configuration; an explicit override can change the sandbox or approval policy. A host profile name is not evidence of effective Full Access. A host denial prevents invocation; it never silently chooses a narrower native -mode. Full Access cannot grant host callbacks extra capabilities, workspace -access, tickets or macOS privacy permissions. +mode. Full Access cannot grant host callbacks extra capabilities, project +access or macOS privacy permissions. The installed vendor must support the requested stable or explicitly enabled experimental API. Incompatible methods fail explicitly. App Server failure diff --git a/Documentation/Reference/Workflows.md b/Documentation/Reference/Workflows.md index 00a09b7..d2d3df1 100644 --- a/Documentation/Reference/Workflows.md +++ b/Documentation/Reference/Workflows.md @@ -11,7 +11,7 @@ by the runtime; do not substitute upstream thread IDs for local handles. | App Server approval | `codex.app.approvals.list` / `read` → `respond` with the exact approval ID | | App Server input and events | `codex.app.requests.list` / `respond`; `codex.app.events.read` | | Acceptance and writer ownership | `codex.run.*` and `codex.worktree.leases.*`, with durable revisions | -| Managed worktrees | `codex.worktree.provision.plan` / `perform`, `managed.list` / `read`, and `remove.plan` / `perform`; mutations require the host workspace service | +| Managed worktrees | `codex.worktree.provision.plan` / `perform`, `managed.list` / `read`, and `remove.plan` / `perform` through the host project service | | Operational diagnostics | `codex.diagnostics.snapshot`, with optional bounded `limit` | | Exec | `codex.exec.start` / `resume`; inspect `list` / `events` / `result`; `cancel` while running; `release` after cleanup | @@ -142,18 +142,12 @@ and are not repaired by reconnecting or force-stopping another client. Native tools also expose `thread/read`, `thread/turns/list` and `thread/items/list` with the SDK's complete schemas and parameter names. -## Workspace and diagnostic availability +## Project and diagnostic availability -Managed-worktree plans are bound to the source workspace and a live parent -lease. A child lease must be released through its own workspace-bound connection. -Removal requires a fresh reviewed plan, a clean owned worktree, no active lease -or live runtime, and host authorization. Removal preserves the branch. - -An explicitly enabled host-services connection supplies registration, removal -authorization and diagnostics. Without that connection, `provision.perform` and -`remove.perform` fail before Git mutation; planning and receipt inspection remain -available. See [host integration](HostIntegration.md) for exact scope and -metadata-only recovery after a partially completed removal. +Worktree provisioning, inventory and removal use the host's scoped +`projects-v1` channel. Standalone adapters can read their local unmanaged +history and use ordinary Codex execution. See [host integration](HostIntegration.md) +for authorization and recovery. Diagnostics read adapter state without starting Codex. `host_diagnostics_available: false` means `recent_tool_audits` is unavailable, @@ -223,20 +217,25 @@ selected child reconciliation. It may reference a native Goal without treating its own state as native Goal state. Turn completion can leave both active. `codex.worktree.leases.*` records mutation ownership, heartbeat, release and -conflicts. Receipt cleanup does not delete a worktree. Managed provisioning is -two steps: `provision.plan` validates the source repository, active parent lease, -branch, start commit, derived path, profile and lineage; `provision.perform` -consumes the reviewed revision before the five-minute plan expires. It creates -the child, requests host registration and the profile grant, and acquires the -isolated lease. Reconnect to select the newly registered child before starting -a leased turn there. - -Removal planning binds the receipt, Git common directory and HEAD. Perform -requires the current revision, explicit confirmation and the host's executing -operation ticket. The child lease must be inactive and the worktree clean with -no live child runtime. Paths must be real current-user-owned directories under -the canonical managed root. A replacement symlink or independently created -worktree is not a cleanup target. Ordinary removal preserves the branch. +conflicts. Expiry updates lease metadata. + +1. In the source project, acquire a parent lease and call + `codex.worktree.provision.plan` with the lease ID, agent and worktree + `name`. Include the desired branch or base branch if you want an explicit + selection. Absent and null values both request host defaults. +2. Copy the returned `perform_arguments` into + `codex.worktree.provision.perform` within five minutes. The host selects + `worktree/` for a defaulted branch and captures a defaulted base + from the source's main checkout at perform admission. +3. Select the returned child `project_id` for leased work. If creation + succeeds with a lease conflict or unavailable lease, use the child + lease-acquire flow once a writer lease is available. +4. Release the child's writer lease, then call `codex.worktree.remove.plan` + in the child project. Review `force` before copying the removal + `perform_arguments` into `codex.worktree.remove.perform`. +5. If a mutation reply is lost, call `codex.worktree.managed.read` in + the source project to inspect the recorded operation. Wait for a + confirmed host disposition before taking further lifecycle action. ## Runtime inspection and handoff diff --git a/README.md b/README.md index 18be425..334c499 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ vendor process, and neither launch mode grants host administration. Standalone c process working directory as the initial directory. A host that enables `hostServices` supplies the scoped MCP callback connection for dynamic tools, -managed-workspace registration and diagnostics. See +project worktree services and diagnostics. See [host integration](Documentation/Reference/HostIntegration.md) for approval ownership, recovery and availability boundaries. @@ -112,9 +112,10 @@ and availability boundaries. App Server, Exec, native Goals, acceptance runs, thread handoff and managed worktrees are experimental and opt-in. A completed turn does not imply Goal completion or acceptance. The -adapter cannot inspect or terminate another client's connection or processes. Managed-worktree -planning and receipts use the adapter's database; provisioning and removal require a connected -host workspace service. +adapter cannot inspect or terminate another client's connection or processes. Codex stores +worktree plans, writer leases, and operation IDs. The connected `projects-v1` host service +creates and removes worktrees. Existing plugin-created worktree records remain available as +unmanaged history. Native tools preserve request extensions, response fields and exact signed 64-bit integers. `codex.app.methods.call` accepts experimental methods with `experimental: true` when the runtime diff --git a/Sources/CodexAdapter/CodexAdapterServer.swift b/Sources/CodexAdapter/CodexAdapterServer.swift index 55135bd..5c33ca0 100644 --- a/Sources/CodexAdapter/CodexAdapterServer.swift +++ b/Sources/CodexAdapter/CodexAdapterServer.swift @@ -83,10 +83,15 @@ package enum CodexAdapterServer { do { return try await CodexWorkInvocation.$current.withValue(invocation) { if let appServer, appServer.tools.contains(where: { $0.name == params.name }) { - return try await appServer.call(name: params.name, arguments: arguments) + return try await appServer.call( + name: params.name, arguments: arguments, + hostInvocation: CodexHostInvocation(params._meta)) } return try await execution.call(name: params.name, arguments: arguments) } + } catch let error as CodexProjectContract.Unsupported { + return try .init( + structuredContent: JSONValue.object(["error": error.fields]), isError: true) } catch CodexToolError.unknownTool { throw MCPError.invalidParams("Unknown tool: \(params.name)") } catch { @@ -100,7 +105,7 @@ package enum CodexAdapterServer { } } do { - try await server.start(transport: transport) + try await server.start(transport: CodexProjectHandshakeTransport(transport)) await server.waitUntilCompleted() } catch { await server.stop() diff --git a/Sources/CodexAdapter/CodexAppServerMethodCatalog.swift b/Sources/CodexAdapter/CodexAppServerMethodCatalog.swift index 39ae24a..d63722b 100644 --- a/Sources/CodexAdapter/CodexAppServerMethodCatalog.swift +++ b/Sources/CodexAdapter/CodexAppServerMethodCatalog.swift @@ -57,7 +57,7 @@ struct CodexAppServerMethod: Equatable, Sendable { "type": .string("object"), "properties": .object(["result": .object([:])]), "required": .array([.string("result")]), "additionalProperties": .bool(false), ]), - _meta: .init(additionalFields: ["io.github.computer-mcp/risk": .string(risk.rawValue)])) + _meta: .init(additionalFields: ["io.github.computer-mcp/risk": .string(risk.hostValue)])) } } diff --git a/Sources/CodexAdapter/CodexAppServerProvider.swift b/Sources/CodexAdapter/CodexAppServerProvider.swift index 4b8673c..a86a572 100644 --- a/Sources/CodexAdapter/CodexAppServerProvider.swift +++ b/Sources/CodexAdapter/CodexAppServerProvider.swift @@ -8,8 +8,7 @@ struct CodexAppServerProvider: Sendable { let workspaceURL: URL let recentThreadReader: CodexRecentThreadReader? let localControlAllowed: Bool - let workspaceHost: (any CodexManagedWorkspaceHost)? - let managedWorktreeRoot: URL? + let projectServices: (any CodexProjectServices)? let configuredSandbox: CodexSandboxMode? let hostDiagnostics: (any CodexHostDiagnostics)? let unboundStateAvailable: Bool @@ -19,7 +18,7 @@ struct CodexAppServerProvider: Sendable { appServer: any CodexAppServerRuntimeProtocol, owner: CodexRuntimeOwner?, database: CodexDatabase?, workspaceURL: URL, recentThreadReader: CodexRecentThreadReader?, localControlAllowed: Bool, - workspaceHost: (any CodexManagedWorkspaceHost)? = nil, managedWorktreeRoot: URL? = nil, + projectServices: (any CodexProjectServices)? = nil, configuredSandbox: CodexSandboxMode? = CodexConfig().sandbox, hostDiagnostics: (any CodexHostDiagnostics)? = nil, unboundStateAvailable: Bool = false, threadOwnerIndex: CodexThreadOwnerIndex? = nil @@ -30,8 +29,7 @@ struct CodexAppServerProvider: Sendable { self.workspaceURL = workspaceURL self.recentThreadReader = recentThreadReader self.localControlAllowed = localControlAllowed - self.workspaceHost = workspaceHost - self.managedWorktreeRoot = managedWorktreeRoot + self.projectServices = projectServices self.configuredSandbox = configuredSandbox self.hostDiagnostics = hostDiagnostics self.unboundStateAvailable = unboundStateAvailable @@ -44,7 +42,9 @@ struct CodexAppServerProvider: Sendable { } + CodexAppServerMethodCatalog.methods.filter { $0.channel == .stable }.map(\.tool) } - func call(name: String, arguments: JSONValue?) async throws -> MCP.CallTool.Result { + func call( + name: String, arguments: JSONValue?, hostInvocation: CodexHostInvocation? = nil + ) async throws -> MCP.CallTool.Result { try CodexAppServerMethodCatalog.validate() if let method = CodexAppServerMethodCatalog.methods.first(where: { $0.channel == .stable && $0.toolName == name @@ -463,7 +463,8 @@ struct CodexAppServerProvider: Sendable { ), liveRuntimeStatus: await CodexRuntimeDirectory.shared.statuses( workspaceID: owner?.workspaceID - ) + ), + scope: CodexProjectScope(owner) ).json case "codex.worktree.leases.list": result = .object([ @@ -513,78 +514,52 @@ struct CodexAppServerProvider: Sendable { ) case "codex.worktree.managed.list": - result = .object([ - "worktrees": .array( - try database?.codexManagedWorktrees( - sourceWorkspaceID: owner?.workspaceID, - limit: try Self.boundedInt("limit", in: object, default: 100, range: 1...1_000) - ).map(\.json) ?? [] - ) - ]) + let limit = try Self.boundedInt("limit", in: object, default: 100, range: 1...1_000) + let history = + try owner.flatMap { try database?.unmanagedWorktrees(owner: $0, limit: limit) } ?? [] + if CodexProjectScope(owner) != nil { + return try await worktreeManager().list( + history: history, limit: limit, invocation: hostInvocation) + } + result = .object(["worktrees": .array([]), "unmanaged_history": .array(history)]) case "codex.worktree.managed.read": - result = try selectedManagedWorktree( - id: Self.requiredString("managed_worktree_id", in: object) - ).json + let id = try Self.requiredIdentifier("managed_worktree_id", in: object) + if let scope = CodexProjectScope(owner), + let (worktree, operation) = try database?.hostWorktree(id: id, in: scope) + { + if let operation, operation.observedState?.isTerminal != true { + return try await worktreeManager().read(worktree, operation: operation) + } + result = + operation?.projection(in: scope, worktree: worktree) + ?? .object(worktree.projection(in: scope)) + } else if let owner, let history = try database?.unmanagedWorktree(id: id, owner: owner) { + result = history + } else { + throw CodexManagedWorktreeError.unknown(id) + } case "codex.worktree.provision.plan": - result = try CodexManagedWorktreeManager.planProvision( - database: database, - sourceWorkspaceID: owner?.workspaceID, - sourceWorkspaceURL: workspaceURL, - profileID: owner?.profileID, - caller: owner?.caller, - principalID: owner?.principalID, + result = try worktreeManager().planProvision( + selection: CodexWorktreeSelection(object), agentID: Self.requiredString("agent_id", in: object), threadID: try Self.optionalString("thread_id", in: object), runID: try Self.optionalString("run_id", in: object), parentLeaseID: Self.requiredString("parent_lease_id", in: object), - branch: Self.requiredString("branch", in: object), - startPoint: try Self.optionalString("start_point", in: object) ?? "HEAD", - ttlSeconds: try Self.boundedInt( - "ttl_seconds", in: object, default: 900, range: 30...86_400 - ), - managedRoot: managedWorktreeRoot - ).json + ttlSeconds: Self.boundedInt("ttl_seconds", in: object, default: 900, range: 30...86_400)) case "codex.worktree.provision.perform": - _ = try selectedManagedWorktree( - id: Self.requiredString("plan_id", in: object), requiresOwnership: true) - result = try await CodexManagedWorktreeManager.performProvision( - database: database, - sourceWorkspaceID: owner?.workspaceID, - planID: Self.requiredString("plan_id", in: object), - expectedRevision: try Self.requiredInt("expected_revision", in: object), - confirmProvision: try Self.requiredBool("confirm_provision", in: object), - workspaceHost: try requireWorkspaceHost(), - managedRoot: managedWorktreeRoot - ).json + return try await worktreeManager().perform( + id: Self.requiredIdentifier("plan_id", in: object), action: .provision, + revision: Self.requiredInt("expected_revision", in: object), + arguments: object, invocation: hostInvocation) case "codex.worktree.remove.plan": - let managed = try selectedManagedWorktree( - id: Self.requiredString("managed_worktree_id", in: object), requiresOwnership: true - ) - result = try CodexManagedWorktreeManager.planRemoval( - database: database, - sourceWorkspaceID: owner?.workspaceID, - managedWorktreeID: managed.id, - liveRuntimeStatus: await CodexRuntimeDirectory.shared.statuses( - workspaceID: managed.workspaceID - ), - managedRoot: managedWorktreeRoot - ).json + result = try worktreeManager().planRemoval( + id: Self.requiredIdentifier("managed_worktree_id", in: object), + force: object["force"] == nil ? false : Self.requiredBool("force", in: object)) case "codex.worktree.remove.perform": - let managed = try selectedManagedWorktree( - id: Self.requiredString("managed_worktree_id", in: object), requiresOwnership: true - ) - result = try await CodexManagedWorktreeManager.performRemoval( - database: database, - sourceWorkspaceID: owner?.workspaceID, - managedWorktreeID: managed.id, - expectedRevision: try Self.requiredInt("expected_revision", in: object), - confirmRemoval: try Self.requiredBool("confirm_remove", in: object), - workspaceHost: try requireWorkspaceHost(), - liveRuntimeStatus: await CodexRuntimeDirectory.shared.statuses( - workspaceID: managed.workspaceID - ), - managedRoot: managedWorktreeRoot - ).json + return try await worktreeManager().perform( + id: Self.requiredIdentifier("managed_worktree_id", in: object), action: .remove, + revision: Self.requiredInt("expected_revision", in: object), + arguments: object, invocation: hostInvocation) default: throw CodexToolError.unknownTool(name) } @@ -618,32 +593,12 @@ struct CodexAppServerProvider: Sendable { private func tryAppServer() throws -> any CodexAppServerRuntimeProtocol { appServer } private func selectedWorkspacePath() throws -> String { workspaceURL.path } - private func requireWorkspaceHost() throws -> any CodexManagedWorkspaceHost { - guard let workspaceHost else { - throw CodexToolError.disabled( - "Managed workspace mutation requires the owning host's registration and operation-ticket service." - ) - } - return workspaceHost - } - - private func selectedManagedWorktree(id: String, requiresOwnership: Bool = false) throws - -> CodexManagedWorktree - { - guard let worktree = try database?.codexManagedWorktree(id: id), - worktree.sourceWorkspaceID == owner?.workspaceID - else { - throw CodexManagedWorktreeError.unknown(id) - } - if requiresOwnership { - guard let principalID = owner?.principalID, worktree.principalID == principalID, - worktree.profileID == owner?.profileID - else { - throw CodexManagedWorktreeError.invalid( - "Managed worktree ownership is unbound or belongs to another authorization subject.") - } + private func worktreeManager() throws -> CodexHostWorktreeManager { + guard let scope = CodexProjectScope(owner), let projectServices else { + throw CodexProjectContract.Unsupported(observed: nil) } - return worktree + guard let database else { throw CodexManagedWorktreeError.unavailable } + return CodexHostWorktreeManager(database: database, scope: scope, services: projectServices) } private func selectedRun(id: String) throws -> CodexOrchestrationRun { @@ -1279,6 +1234,14 @@ struct CodexAppServerProvider: Sendable { return value } + private static let worktreeNameSchema: JSONValue = .object([ + "type": .string("string"), "pattern": .string("^[a-z0-9]+(-[a-z0-9]+)*$"), + "minLength": .integer(1), "maxLength": .integer(48), + ]) + private static let optionalBranchSchema: JSONValue = .object([ + "type": .array([.string("string"), .string("null")]), + "minLength": .integer(1), "maxLength": .integer(1024), + ]) private static let emptySchema = objectSchema() private static let cursorSchema = objectSchema(properties: [ "after_cursor": integerSchema(minimum: 0), @@ -1287,74 +1250,81 @@ struct CodexAppServerProvider: Sendable { private static let definitions: [MCP.Tool] = [ tool( "codex.diagnostics.snapshot", - "Read one redacted, workspace-scoped operational snapshot that correlates Codex runtimes, process and connection ownership, approvals, acceptance runs, worktree leases, cleanup state, and recent tool or Git audit receipts.", + "Read one redacted, project-scoped operational snapshot that correlates Codex runtimes, process and connection ownership, approvals, acceptance runs, worktree leases, cleanup state, and recent tool or Git audit receipts.", objectSchema(properties: ["limit": integerSchema(minimum: 1, maximum: 1_000)]), hostAction: "diagnostics.snapshot" ), tool( "codex.worktree.managed.list", - "List Computer MCP-owned worktree plans and lifecycle receipts rooted in the selected source workspace.", - objectSchema(properties: ["limit": integerSchema(minimum: 1, maximum: 1_000)]) + "List Codex worktree plans, unmanaged history, and host project inventory for the selected project.", + objectSchema(properties: ["limit": integerSchema(minimum: 1, maximum: 1_000)]), + hostAction: "projects.list", reportsHostResponse: true ), tool( "codex.worktree.managed.read", - "Read one Computer MCP-owned worktree plan or lifecycle receipt.", + "Read a worktree record and inspect any unresolved operation through the selected source or child project.", objectSchema( properties: ["managed_worktree_id": stringSchema()], required: ["managed_worktree_id"] - ) + ), + reportsHostResponse: true ), tool( "codex.worktree.provision.plan", - "Persist and validate a five-minute plan for a new isolated Git worktree under the Computer MCP-managed root. This does not create a branch or directory.", + "Review and persist a five-minute plan for a host worktree in the selected source project.", objectSchema( properties: [ "agent_id": stringSchema(), "thread_id": stringSchema(), "run_id": stringSchema(), "parent_lease_id": stringSchema(), - "branch": stringSchema(), - "start_point": stringSchema(), + "name": worktreeNameSchema, + "branch": optionalBranchSchema, + "base": optionalBranchSchema, "ttl_seconds": integerSchema(minimum: 30, maximum: 86_400), ], - required: ["agent_id", "parent_lease_id", "branch"] + required: ["agent_id", "parent_lease_id", "name"] ), - risk: .workspaceWrite + risk: .workspaceWrite, reportsHostResponse: true ), tool( "codex.worktree.provision.perform", - "Create exactly one reviewed managed worktree, register it as a child workspace, inherit the current profile's workspace grant, and acquire an isolated writer lease.", + "Ask the host to create the reviewed worktree and report the host result and Codex lease disposition.", objectSchema( properties: [ "plan_id": stringSchema(), "expected_revision": integerSchema(minimum: 1), "confirm_provision": booleanSchema(), + "name": worktreeNameSchema, + "branch": optionalBranchSchema, + "base": optionalBranchSchema, ], - required: ["plan_id", "expected_revision", "confirm_provision"] + required: ["plan_id", "expected_revision", "confirm_provision", "name"] ), - risk: .workspaceWrite, hostAction: "workspaces.provision" + risk: .workspaceWrite, hostAction: "projects.provision", reportsHostResponse: true ), tool( "codex.worktree.remove.plan", - "Verify Computer MCP ownership, an inactive writer lease, no live runtime, exact Git linkage, and a clean worktree before persisting a five-minute removal plan.", + "Review a five-minute removal plan in the child project after releasing its writer lease.", objectSchema( - properties: ["managed_worktree_id": stringSchema()], + properties: ["managed_worktree_id": stringSchema(), "force": booleanSchema()], required: ["managed_worktree_id"] ), - risk: .workspaceWrite + risk: .workspaceWrite, reportsHostResponse: true ), tool( "codex.worktree.remove.perform", - "Remove exactly the reviewed clean Computer MCP-owned worktree and its managed workspace registration. The local branch is preserved. This destructive operation also requires a gateway operation ticket.", + "Ask the host to retain recoverable Git data and remove the selected child project using the reviewed force setting.", objectSchema( properties: [ "managed_worktree_id": stringSchema(), "expected_revision": integerSchema(minimum: 1), "confirm_remove": booleanSchema(), + "force": booleanSchema(), ], required: ["managed_worktree_id", "expected_revision", "confirm_remove"] ), - risk: .destructive, hostAction: "workspaces.remove" + risk: .destructive, hostAction: "projects.remove", reportsHostResponse: true ), tool( "codex.app.status", "Read the persistent Codex App Server connection status.", emptySchema), @@ -1948,13 +1918,14 @@ struct CodexAppServerProvider: Sendable { ] private static func tool( _ name: String, _ description: String, _ inputSchema: JSONValue, - risk: CodexOperationRisk = .readOnly, hostAction: String? = nil + risk: CodexOperationRisk = .readOnly, hostAction: String? = nil, + reportsHostResponse: Bool = false ) -> MCP.Tool { let title = name.split(whereSeparator: { $0 == "." || $0 == "_" || $0 == "-" }) .map { String($0.prefix(1)).uppercased() + $0.dropFirst() }.joined(separator: " ") let input = try! JSONDecoder().decode( MCP.Value.self, from: JSONEncoder().encode(inputSchema)) - var metadata: [String: MCP.Value] = ["io.github.computer-mcp/risk": .string(risk.rawValue)] + var metadata: [String: MCP.Value] = ["io.github.computer-mcp/risk": .string(risk.hostValue)] if let hostAction { metadata["io.github.computer-mcp/host-action"] = .string(hostAction) } return .init( name: name, title: title, description: description, inputSchema: input, @@ -1962,13 +1933,28 @@ struct CodexAppServerProvider: Sendable { readOnlyHint: risk == .readOnly, destructiveHint: risk == .destructive || risk == .fullShell, idempotentHint: risk == .readOnly, openWorldHint: risk != .readOnly), - outputSchema: .object([ - "type": .string("object"), "properties": .object(["result": .object([:])]), - "required": .array([.string("result")]), "additionalProperties": .bool(false), - ]), + outputSchema: reportsHostResponse + ? worktreeOutputSchema + : .object([ + "type": .string("object"), "properties": .object(["result": .object([:])]), + "required": .array([.string("result")]), "additionalProperties": .bool(false), + ]), _meta: .init(additionalFields: metadata)) } + private static let worktreeOutputSchema: MCP.Value = .object([ + "type": .string("object"), + "properties": .object([ + "result": .object(["type": .string("object")]), + "error": .object(["type": .string("object")]), + ]), + "oneOf": .array([ + .object(["required": .array([.string("result")])]), + .object(["required": .array([.string("error")])]), + ]), + "additionalProperties": .bool(false), + ]) + private static func objectSchema( properties: [String: JSONValue] = [:], required: [String] = [] diff --git a/Sources/CodexAdapter/CodexDatabase+HostWorktrees.swift b/Sources/CodexAdapter/CodexDatabase+HostWorktrees.swift new file mode 100644 index 0000000..42e9eef --- /dev/null +++ b/Sources/CodexAdapter/CodexDatabase+HostWorktrees.swift @@ -0,0 +1,352 @@ +import Foundation +import GRDB + +extension CodexDatabase { + static func createHostWorktreeTables(_ database: Database) throws { + try database.create(table: "codexHostWorktrees") { table in + table.column("id", .text).primaryKey() + table.column("principalID", .text).notNull() + table.column("profileID", .text).notNull() + table.column("sourceProjectID", .text).notNull() + table.column("childProjectID", .text) + table.column("updatedAt", .datetime).notNull() + table.column("payloadJSON", .text).notNull() + table.uniqueKey(["principalID", "profileID", "childProjectID"]) + } + try database.create( + index: "codexHostWorktrees_on_source", + on: "codexHostWorktrees", + columns: ["principalID", "profileID", "sourceProjectID", "updatedAt"]) + try database.create(table: "codexWorktreeOperations") { table in + table.column("id", .text).primaryKey() + table.column("invocationID", .text).notNull().unique() + table.column("domainID", .text).notNull().references("codexHostWorktrees") + table.column("payloadJSON", .text).notNull() + } + } + + func hostWorktrees(in scope: CodexProjectScope, limit: Int) throws -> [CodexHostWorktree] { + try worktreeLeaseWriter.read { database in + try CodexHostWorktreeRow.visible(in: scope) + .order(Column("updatedAt").desc, Column("id").desc) + .limit(limit).fetchAll(database).map { try $0.value() } + } + } + + func hostWorktree(id: String, in scope: CodexProjectScope) throws + -> (CodexHostWorktree, CodexWorktreeOperation?)? + { + try worktreeLeaseWriter.read { database in + guard let worktree = try Self.visibleWorktree(id: id, scope: scope, in: database) + else { return nil } + let operation = try worktree.currentOperationID.map { + try Self.operation(id: $0, worktree: worktree, in: database) + } + return (worktree, operation) + } + } + + func saveProvisionPlan(_ worktree: CodexHostWorktree, in scope: CodexProjectScope, now: Date) + throws + { + try worktreeLeaseWriter.write { database in + guard try Self.boundHostChild(in: database, scope: scope) == nil else { + throw CodexManagedWorktreeError.invalid("Select the source project to plan creation.") + } + guard worktree.source == scope, + try Self.hasActiveParent(worktree, in: database, now: now) + else { throw CodexManagedWorktreeError.invalid("An active source parent lease is required.") } + try CodexHostWorktreeRow(worktree).insert(database) + } + } + + func saveRemovalPlan( + id: String, in scope: CodexProjectScope, force: Bool, now: Date + ) throws -> CodexHostWorktree { + try worktreeLeaseWriter.write { database in + guard var worktree = try Self.visibleWorktree(id: id, scope: scope, in: database), + worktree.creation?.projectID == scope.projectID + else { throw CodexManagedWorktreeError.unknown(id) } + guard + worktree.state == .active + || (worktree.state == .removalPlanned + && worktree.planExpiresAt.map({ $0 <= now }) == true) + else { + throw CodexManagedWorktreeError.state("the worktree is unavailable for removal planning") + } + try Self.requireNoActiveLeases(in: database, scope: scope, now: now) + worktree.state = .removalPlanned + worktree.currentOperationID = nil + worktree.force = force + worktree.planExpiresAt = now.addingTimeInterval(300) + worktree.revision += 1 + worktree.updatedAt = now + try Self.saveHostWorktree(worktree, in: database) + return worktree + } + } + + func beginWorktreeOperation( + id: String, in scope: CodexProjectScope, action: CodexWorktreeAction, + revision: Int, arguments: [String: JSONValue], ids: CodexHostOperationIDs, now: Date + ) throws -> (CodexHostWorktree, CodexWorktreeOperation) { + let digest = try CodexHostInvocation.digest(arguments) + return try worktreeLeaseWriter.write { database in + guard var worktree = try Self.visibleWorktree(id: id, scope: scope, in: database), + action == .provision + ? worktree.source == scope : worktree.creation?.projectID == scope.projectID + else { throw CodexManagedWorktreeError.unknown(id) } + guard worktree.revision == revision else { + throw CodexManagedWorktreeError.revisionConflict( + expected: revision, actual: worktree.revision) + } + guard worktree.state == (action == .provision ? .planned : .removalPlanned), + worktree.planExpiresAt.map({ $0 > now }) == true + else { throw CodexManagedWorktreeError.state("the plan is not current") } + var reviewed = arguments + if action == .remove, reviewed["force"] == nil { reviewed["force"] = .bool(false) } + guard reviewed == worktree.performArguments else { + throw CodexManagedWorktreeError.invalid( + "perform arguments must match the reviewed plan, including optional creation fields") + } + if action == .provision { + guard try Self.hasActiveParent(worktree, in: database, now: now) else { + throw CodexManagedWorktreeError.state("the source parent lease is inactive") + } + } else { + try Self.requireNoActiveLeases(in: database, scope: scope, now: now) + } + let operation = CodexWorktreeOperation( + ids: ids, domainID: worktree.id, action: action, source: worktree.source, + selectedProjectID: scope.projectID, arguments: arguments, argumentsDigest: digest) + try CodexWorktreeOperationRow(operation).insert(database) + worktree.currentOperationID = ids.operationID + worktree.state = action.pendingState + worktree.planExpiresAt = nil + worktree.revision += 1 + worktree.updatedAt = now + try Self.saveHostWorktree(worktree, in: database) + return (worktree, operation) + } + } + + func settleWorktreeOperation( + id: String, in scope: CodexProjectScope, operationID: UUID, envelope: JSONValue, + response: CodexHostToolResponse, now: Date + ) throws -> (CodexHostWorktree, CodexWorktreeOperation) { + try worktreeLeaseWriter.write { database in + guard var worktree = try Self.visibleWorktree(id: id, scope: scope, in: database) + else { throw CodexManagedWorktreeError.unknown(id) } + var operation = try Self.operation(id: operationID, worktree: worktree, in: database) + let state = try operation.state(of: envelope) + if operation.observedState?.isTerminal == true { + guard + !state.isTerminal + || (operation.observedState == state + && operation.envelope == envelope) + else { throw CodexWorktreeObservationError.conflictingTerminalState } + return (worktree, operation) + } + guard worktree.currentOperationID == operationID, + worktree.state == operation.action.pendingState + else { throw CodexWorktreeObservationError.invalidEnvelope } + if (state == .reserved && operation.observedState == .running) + || ((state == .reserved || state == .running) + && operation.observedState == .recoveryRequired) + { + return (worktree, operation) + } + operation.observedState = state + operation.envelope = envelope + operation.response = response + operation.observationError = nil + operation.uncertainResponse = nil + if state == .completed { + let result = envelope.objectValue?["result"] ?? .null + switch operation.action { + case .provision: + let creation = try CodexWorktreeCreation(result, worktree: worktree) + worktree.creation = creation + worktree.creationOperationID = operationID + worktree.lease = try Self.settleCreationLease( + worktree, creation: creation, in: database, now: now) + worktree.state = .active + case .remove: + try Self.validateRemoval(result, worktree: worktree) + worktree.state = .removed + worktree.force = nil + } + } else if state == .failed { + worktree.state = operation.action == .provision ? .failed : .active + worktree.force = nil + } + if state.isTerminal { + worktree.revision += 1 + worktree.updatedAt = now + try Self.saveHostWorktree(worktree, in: database) + } + try CodexWorktreeOperationRow(operation).update(database) + return (worktree, operation) + } + } + + func recordWorktreeObservationFailure( + id: String, in scope: CodexProjectScope, operationID: UUID, + response: CodexHostToolResponse?, message: String + ) throws -> (CodexHostWorktree, CodexWorktreeOperation) { + try worktreeLeaseWriter.write { database in + guard let worktree = try Self.visibleWorktree(id: id, scope: scope, in: database) + else { throw CodexManagedWorktreeError.unknown(id) } + var operation = try Self.operation(id: operationID, worktree: worktree, in: database) + if worktree.currentOperationID == operationID, operation.observedState?.isTerminal != true { + operation.observationError = message + if let response { operation.uncertainResponse = response } + try CodexWorktreeOperationRow(operation).update(database) + } + return (worktree, operation) + } + } + + static func boundHostChild(in database: Database, scope: CodexProjectScope) throws + -> CodexHostWorktree? + { + guard + let worktree = try CodexHostWorktreeRow.subject(in: scope) + .filter(Column("childProjectID") == scope.projectID).fetchOne(database)?.value() + else { return nil } + guard let id = worktree.creationOperationID, + let creation = worktree.creation, creation.projectID == scope.projectID + else { throw CodexWorktreeObservationError.invalidCompletion } + let operation = try operation(id: id, worktree: worktree, in: database) + guard operation.action == .provision, operation.observedState == .completed, + operation.selectedProjectID == worktree.source.projectID, + try operation.state(of: operation.envelope) == .completed, + operation.envelope?.objectValue?["result"] == creation.result + else { throw CodexWorktreeObservationError.invalidCompletion } + return worktree + } + + static func saveHostWorktree(_ worktree: CodexHostWorktree, in database: Database) throws { + try CodexHostWorktreeRow(worktree).update(database) + } + + private static func visibleWorktree( + id: String, scope: CodexProjectScope, in database: Database + ) throws -> CodexHostWorktree? { + try CodexHostWorktreeRow.visible(in: scope) + .filter(Column("id") == id).fetchOne(database)?.value() + } + + private static func operation(id: UUID, worktree: CodexHostWorktree, in database: Database) throws + -> CodexWorktreeOperation + { + guard let record = try CodexWorktreeOperationRow.fetchOne(database, key: id.uuidString), + record.domainID == worktree.id + else { throw CodexWorktreeObservationError.invalidEnvelope } + let operation = try record.value() + guard operation.domainID == worktree.id, operation.source == worktree.source, + operation.ids.operationID == id + else { throw CodexWorktreeObservationError.invalidEnvelope } + return operation + } + + private static func hasActiveParent( + _ worktree: CodexHostWorktree, in database: Database, now: Date + ) throws -> Bool { + guard let parent = try worktreeLease(in: database, id: worktree.parentLeaseID) + else { return false } + return parent.workspaceID == worktree.source.projectID && parent.state == .active + && parent.expiresAt > now + } + + private static func requireNoActiveLeases( + in database: Database, scope: CodexProjectScope, now: Date + ) throws { + guard try activeWorktreeLeases(in: database, projectID: scope.projectID, now: now).isEmpty + else { throw CodexManagedWorktreeError.state("the child has an active writer lease") } + } + + private static func settleCreationLease( + _ worktree: CodexHostWorktree, creation: CodexWorktreeCreation, in database: Database, now: Date + ) throws -> CodexWorktreeLeaseOutcome { + guard try hasActiveParent(worktree, in: database, now: now) + else { return .unavailable("source_parent_inactive") } + let lease = CodexWorktreeLease( + workspaceID: creation.projectID, workspacePath: creation.path, mode: .isolatedWorktree, + agentID: worktree.agentID, threadID: worktree.threadID, runID: worktree.runID, + parentLeaseID: worktree.parentLeaseID, branch: creation.branch, + ttlSeconds: worktree.ttlSeconds, now: now, association: worktree) + do { + return .acquired(try acquireWorktreeLease(in: database, proposed: lease, now: now).id) + } catch CodexWorktreeLeaseError.conflict { + return .conflict + } + } + + private static func validateRemoval(_ result: JSONValue, worktree: CodexHostWorktree) throws { + guard let creation = worktree.creation, let fields = result.objectValue, + fields["worktree_id"]?.stringValue.flatMap(UUID.init(uuidString:)) == creation.worktreeID, + fields["project_id"] == .string(creation.projectID), + fields["branch"] == .string(creation.branch), + let oid = fields["oid"]?.stringValue, [40, 64].contains(oid.utf8.count), + oid.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }), + let warnings = fields["termination_warnings"]?.arrayValue, + warnings.allSatisfy({ $0.stringValue != nil }) + else { throw CodexWorktreeObservationError.invalidCompletion } + } +} + +private struct CodexHostWorktreeRow: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "codexHostWorktrees" + + let id: String + let principalID: String + let profileID: String + let sourceProjectID: String + let childProjectID: String? + let updatedAt: Date + let payloadJSON: String + + init(_ value: CodexHostWorktree) throws { + id = value.id + principalID = value.source.principalID + profileID = value.source.profileID + sourceProjectID = value.source.projectID + childProjectID = value.creation?.projectID + updatedAt = value.updatedAt + payloadJSON = String(decoding: try JSONEncoder().encode(value), as: UTF8.self) + } + + static func subject(in scope: CodexProjectScope) -> QueryInterfaceRequest { + filter(Column("principalID") == scope.principalID && Column("profileID") == scope.profileID) + } + + static func visible(in scope: CodexProjectScope) -> QueryInterfaceRequest { + subject(in: scope).filter( + Column("sourceProjectID") == scope.projectID || Column("childProjectID") == scope.projectID) + } + + func value() throws -> CodexHostWorktree { + try JSONDecoder().decode(CodexHostWorktree.self, from: Data(payloadJSON.utf8)) + } +} + +private struct CodexWorktreeOperationRow: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "codexWorktreeOperations" + + let id: String + let invocationID: String + let domainID: String + let payloadJSON: String + + init(_ value: CodexWorktreeOperation) throws { + id = value.ids.operationID.uuidString + invocationID = value.ids.invocationID.uuidString + domainID = value.domainID + payloadJSON = String(decoding: try JSONEncoder().encode(value), as: UTF8.self) + } + + func value() throws -> CodexWorktreeOperation { + try JSONDecoder().decode(CodexWorktreeOperation.self, from: Data(payloadJSON.utf8)) + } +} diff --git a/Sources/CodexAdapter/CodexDatabase.swift b/Sources/CodexAdapter/CodexDatabase.swift index a888273..79685dc 100644 --- a/Sources/CodexAdapter/CodexDatabase.swift +++ b/Sources/CodexAdapter/CodexDatabase.swift @@ -4,7 +4,7 @@ import GRDB /// Adapter-owned domain records. Host grants, credentials, workspaces and audit stay with the host. final class CodexDatabase: @unchecked Sendable { private let writer: any DatabaseWriter - private let worktreeLeaseWriter: any DatabaseWriter + let worktreeLeaseWriter: any DatabaseWriter let sharesWorktreeLeases: Bool let fileURL: URL? @@ -19,12 +19,13 @@ final class CodexDatabase: @unchecked Sendable { } else { worktreeLeaseWriter = writer } - try Self.validateMigrations(Self.migrator, in: writer) + let primaryMigrator = Self.primaryMigrator(includesLocalWorktrees: !sharesWorktreeLeases) + try Self.validateMigrations(primaryMigrator, in: writer) if sharesWorktreeLeases { try Self.validateMigrations(Self.worktreeLeaseMigrator, in: worktreeLeaseWriter) try Self.worktreeLeaseMigrator.migrate(worktreeLeaseWriter) } - try Self.migrator.migrate(writer) + try primaryMigrator.migrate(writer) } init(inMemory: Void) throws { @@ -245,55 +246,116 @@ final class CodexDatabase: @unchecked Sendable { branch: String?, ttlSeconds: Int, now: Date, - managedWorktreeID: String? = nil + scope: CodexProjectScope? ) throws -> CodexWorktreeLease { try worktreeLeaseWriter.write { database in - let rows = - try CodexWorktreeLeaseRow - .filter(Column("workspaceID") == workspaceID) - .filter(Column("state") == CodexWorktreeLeaseState.active.rawValue) - .fetchAll(database) - for row in rows { - var existing = try row.value() - if existing.expiresAt <= now { - existing.state = .expired - existing.releasedAt = now - existing.releaseReason = "lease_ttl_expired" - existing.revision += 1 - try CodexWorktreeLeaseRow(existing).save(database) - continue + guard scope == nil || scope?.projectID == workspaceID else { + throw CodexWorktreeLeaseError.invalid("The lease must use the selected project.") + } + let association = try scope.flatMap { try Self.boundHostChild(in: database, scope: $0) } + let parent = try parentLeaseID.flatMap { try Self.worktreeLease(in: database, id: $0) } + if parentLeaseID != nil { + guard let parent, parent.state == .active, parent.expiresAt > now else { + throw CodexWorktreeLeaseError.invalid("parent_lease_id must identify an active lease") } - if existing.agentID == agentID, existing.threadID == threadID, - existing.runID == runID - { - return existing + guard parent.workspaceID != workspaceID || parent.mode == .exclusive else { + throw CodexWorktreeLeaseError.invalid( + "an isolated child must use a separately registered worktree project") + } + if sharesWorktreeLeases, parent.workspaceID != workspaceID, association == nil { + throw CodexWorktreeLeaseError.invalid( + "The parent lease requires a completed host worktree association.") } - throw CodexWorktreeLeaseError.conflict(existing) } - let lease = CodexWorktreeLease( - id: UUID().uuidString, - workspaceID: workspaceID, - workspacePath: workspacePath, - mode: mode, - agentID: agentID, - threadID: threadID, - runID: runID, - parentLeaseID: parentLeaseID, - branch: branch, - state: .active, - createdAt: now, - heartbeatAt: now, - expiresAt: now.addingTimeInterval(TimeInterval(ttlSeconds)), - releasedAt: nil, - releaseReason: nil, - revision: 1, - managedWorktreeID: managedWorktreeID - ) - try CodexWorktreeLeaseRow(lease).save(database) - return lease + + if let association { + guard + association.state == .active + || (association.state == .removalPlanned + && association.planExpiresAt.map({ $0 <= now }) == true) + else { + throw CodexWorktreeLeaseError.invalid("The host worktree is pending removal or removed.") + } + guard let host = association.creation, association.creationOperationID != nil, + let parent, + parent.workspaceID == association.source.projectID, host.path == workspacePath, + branch == nil || branch == host.branch + else { + throw CodexWorktreeLeaseError.invalid( + "The lease must use the selected host worktree and its source parent.") + } + } + + let proposed = CodexWorktreeLease( + workspaceID: workspaceID, workspacePath: workspacePath, mode: mode, agentID: agentID, + threadID: threadID, runID: runID, parentLeaseID: parentLeaseID, + branch: association?.creation?.branch ?? branch, ttlSeconds: ttlSeconds, now: now, + association: association) + let acquired = try Self.acquireWorktreeLease(in: database, proposed: proposed, now: now) + if var association, + association.lease != .acquired(acquired.id) || association.state == .removalPlanned + { + association.lease = .acquired(acquired.id) + association.state = .active + association.force = nil + association.planExpiresAt = nil + association.revision += 1 + association.updatedAt = now + try Self.saveHostWorktree(association, in: database) + } + return acquired } } + static func worktreeLease(in database: Database, id: String) throws -> CodexWorktreeLease? { + try CodexWorktreeLeaseRow.fetchOne(database, key: id)?.value() + } + + static func activeWorktreeLeases(in database: Database, projectID: String, now: Date) throws + -> [CodexWorktreeLease] + { + let rows = + try CodexWorktreeLeaseRow + .filter(Column("workspaceID") == projectID) + .filter(Column("state") == CodexWorktreeLeaseState.active.rawValue) + .fetchAll(database) + var active: [CodexWorktreeLease] = [] + for row in rows { + var lease = try row.value() + if lease.expiresAt > now { + active.append(lease) + } else { + lease.state = .expired + lease.releasedAt = now + lease.releaseReason = "lease_ttl_expired" + lease.revision += 1 + try CodexWorktreeLeaseRow(lease).save(database) + } + } + return active + } + + static func acquireWorktreeLease( + in database: Database, proposed: CodexWorktreeLease, now: Date + ) throws -> CodexWorktreeLease { + let active = try activeWorktreeLeases(in: database, projectID: proposed.workspaceID, now: now) + if let existing = active.first { + guard active.count == 1, existing.agentID == proposed.agentID, + existing.threadID == proposed.threadID, existing.runID == proposed.runID, + proposed.hostWorktreeID == nil + || (existing.hostWorktreeID == proposed.hostWorktreeID + && existing.creationOperationID == proposed.creationOperationID + && existing.managedWorktreeID == proposed.managedWorktreeID + && existing.parentLeaseID == proposed.parentLeaseID + && existing.workspacePath == proposed.workspacePath + && existing.mode == proposed.mode && existing.branch == proposed.branch) + else { throw CodexWorktreeLeaseError.conflict(existing) } + return existing + } + try CodexWorktreeLeaseRow(proposed).insert(database) + return proposed + } + func updateCodexWorktreeLease( id: String, workspaceID: String?, @@ -321,63 +383,32 @@ final class CodexDatabase: @unchecked Sendable { } } - func saveCodexManagedWorktree(_ worktree: CodexManagedWorktree) throws { - try writer.write { database in - try CodexManagedWorktreeRow(worktree).save(database) - } - } - - func codexManagedWorktree(id: String) throws -> CodexManagedWorktree? { - try writer.read { database in - try CodexManagedWorktreeRow.fetchOne(database, key: id)?.value() - } - } - - func codexManagedWorktrees( - sourceWorkspaceID: String? = nil, - limit: Int = 100 - ) throws -> [CodexManagedWorktree] { - try writer.read { database in - var request = - CodexManagedWorktreeRow + func unmanagedWorktrees(owner: CodexRuntimeOwner, limit: Int) throws -> [JSONValue] { + guard let project = owner.workspaceID else { return [] } + return try writer.read { database in + let rows = + try CodexManagedWorktreeRow + .filter(Column("sourceWorkspaceID") == project) + .filter(Column("state") == CodexManagedWorktreeState.unmanaged.rawValue) .order(Column("updatedAt").desc, Column("id").desc) - if let sourceWorkspaceID { - request = request.filter(Column("sourceWorkspaceID") == sourceWorkspaceID) - } - return try request.limit(max(1, min(limit, 5_000))).fetchAll(database).map { - try $0.value() + .fetchCursor(database) + var history: [JSONValue] = [] + while history.count < limit, let row = try rows.next() { + if let item = try row.history(for: owner) { history.append(item) } } + return history } } - func updateCodexManagedWorktree( - id: String, - sourceWorkspaceID: String?, - expectedRevision: Int, - mutate: (inout CodexManagedWorktree) throws -> Void - ) throws -> CodexManagedWorktree { - try writer.write { database in - guard let row = try CodexManagedWorktreeRow.fetchOne(database, key: id) else { - throw CodexManagedWorktreeError.unknown(id) - } - var worktree = try row.value() - guard sourceWorkspaceID == nil || worktree.sourceWorkspaceID == sourceWorkspaceID else { - throw CodexManagedWorktreeError.unknown(id) - } - guard worktree.revision == expectedRevision else { - throw CodexManagedWorktreeError.revisionConflict( - expected: expectedRevision, - actual: worktree.revision - ) - } - try mutate(&worktree) - worktree.revision += 1 - try CodexManagedWorktreeRow(worktree).save(database) - return worktree + func unmanagedWorktree(id: String, owner: CodexRuntimeOwner) throws -> JSONValue? { + try writer.read { database in + try CodexManagedWorktreeRow.fetchOne(database, key: id)?.history(for: owner) } } - static var migrator: DatabaseMigrator { + static var migrator: DatabaseMigrator { primaryMigrator(includesLocalWorktrees: true) } + + private static func primaryMigrator(includesLocalWorktrees: Bool) -> DatabaseMigrator { var migrator = DatabaseMigrator() migrator.registerMigration("codex-initial") { database in try database.create(table: "codexApprovals") { table in @@ -481,12 +512,28 @@ final class CodexDatabase: @unchecked Sendable { columns: ["sourceWorkspaceID", "state", "updatedAt"] ) } + migrator.registerMigration("codex-projects-v1-history") { database in + for var row in try CodexManagedWorktreeRow.fetchAll(database) { + var payload = try row.payload() + payload["previous_state"] = payload["state"] ?? .string(row.state) + payload["state"] = .string(CodexManagedWorktreeState.unmanaged.rawValue) + row.state = CodexManagedWorktreeState.unmanaged.rawValue + row.payloadJSON = String(decoding: try JSONEncoder().encode(payload), as: UTF8.self) + try row.update(database) + } + } + if includesLocalWorktrees { + migrator.registerMigration( + "codex-projects-v1-local-worktrees", migrate: createHostWorktreeTables) + } return migrator } private static var worktreeLeaseMigrator: DatabaseMigrator { var migrator = DatabaseMigrator() migrator.registerMigration("codex-worktree-leases-initial", migrate: createWorktreeLeaseTable) + migrator.registerMigration( + "codex-projects-v1-shared-worktrees", migrate: createHostWorktreeTables) return migrator } @@ -531,22 +578,19 @@ private struct CodexManagedWorktreeRow: Codable, FetchableRecord, PersistableRec var updatedAt: Date var payloadJSON: String - init(_ value: CodexManagedWorktree) throws { - id = value.id - sourceWorkspaceID = value.sourceWorkspaceID - workspaceID = value.workspaceID - state = value.state.rawValue - updatedAt = value.updatedAt - let encoder = JSONEncoder() - encoder.outputFormatting = [.sortedKeys] - payloadJSON = String(decoding: try encoder.encode(value), as: UTF8.self) + func payload() throws -> [String: JSONValue] { + try JSONDecoder().decode([String: JSONValue].self, from: Data(payloadJSON.utf8)) } - func value() throws -> CodexManagedWorktree { - guard let data = payloadJSON.data(using: .utf8) else { - throw CodexDatabaseError.invalidStoredValue("Codex managed worktree is not UTF-8.") - } - return try JSONDecoder().decode(CodexManagedWorktree.self, from: data) + func history(for owner: CodexRuntimeOwner) throws -> JSONValue? { + guard state == CodexManagedWorktreeState.unmanaged.rawValue, + sourceWorkspaceID == owner.workspaceID + else { return nil } + let fields = try payload() + guard fields["principal_id"]?.stringValue == owner.principalID, + owner.principalID == nil || fields["profile_id"]?.stringValue == owner.profileID + else { return nil } + return .object(fields) } } diff --git a/Sources/CodexAdapter/CodexExecutionProvider.swift b/Sources/CodexAdapter/CodexExecutionProvider.swift index 62f6d30..f58be56 100644 --- a/Sources/CodexAdapter/CodexExecutionProvider.swift +++ b/Sources/CodexAdapter/CodexExecutionProvider.swift @@ -271,7 +271,7 @@ struct CodexExecutionProvider: Sendable { "type": .string("object"), "properties": .object(["result": .object([:])]), "required": .array([.string("result")]), "additionalProperties": .bool(false), ]), - _meta: .init(additionalFields: ["io.github.computer-mcp/risk": .string(risk.rawValue)])) + _meta: .init(additionalFields: ["io.github.computer-mcp/risk": .string(risk.hostValue)])) } private static func objectSchema( diff --git a/Sources/CodexAdapter/CodexHostMCPClient.swift b/Sources/CodexAdapter/CodexHostMCPClient.swift index f6d79fe..6dc0858 100644 --- a/Sources/CodexAdapter/CodexHostMCPClient.swift +++ b/Sources/CodexAdapter/CodexHostMCPClient.swift @@ -2,17 +2,18 @@ import CryptoKit import Foundation import MCP -/// Host tools use standard MCP and the existing gateway policy/ticket tool surface. +/// Host tools use standard MCP and the existing gateway project tool surface. /// Caller-provided tool arguments cannot select this connection or its authority. -actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, +actor CodexHostMCPClient: CodexHostTools, CodexProjectServices, CodexHostDiagnostics { static let descriptorEnvironmentKey = "COMPUTER_MCP_HOST_FD" private let owner: CodexRuntimeOwner - private let workspaceID: String + private let projectID: String private let client = MCP.Client(name: "codex-host-tools", version: CodexAdapterBuildInfo.version) private let transport: MCPInheritedSocketTransport private let requestTimeout: Duration + private let launchContract: String? private var startup: Task? private var connected = false private var closed = false @@ -32,23 +33,25 @@ actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, else { throw ConfigurationError.invalid("Invalid inherited host MCP descriptor.") } return try Self( takingOwnershipOf: FileHandle(fileDescriptor: descriptor, closeOnDealloc: true), - owner: context.owner) + owner: context.owner, launchContract: context.hostServiceContract) } init( takingOwnershipOf handle: FileHandle, owner: CodexRuntimeOwner, - requestTimeout: Duration = .seconds(30) + requestTimeout: Duration = .seconds(30), launchContract: String? = nil ) throws { guard requestTimeout > .zero else { throw ConfigurationError.invalid("Invalid host request timeout.") } - guard let workspaceID = owner.workspaceID, !workspaceID.isEmpty else { - throw ConfigurationError.invalid("Host MCP requires a bound workspace identity.") + guard let projectID = owner.workspaceID, !projectID.isEmpty else { + throw ConfigurationError.invalid("Host MCP requires a bound project identity.") } self.owner = owner - self.workspaceID = workspaceID + self.projectID = projectID self.requestTimeout = requestTimeout - transport = try MCPInheritedSocketTransport(takingOwnershipOf: handle) + self.launchContract = launchContract + transport = try MCPInheritedSocketTransport( + takingOwnershipOf: handle, observesProjectContract: true) } func risk(named name: String, arguments: JSONValue, requestID: String, workspaceID: String?) @@ -105,9 +108,9 @@ actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, guard !closed, arguments.objectValue != nil, !name.hasPrefix("codex."), !name.hasPrefix("host."), !name.isEmpty, name.utf8.count <= 512, !requestID.isEmpty, requestID.utf8.count <= 512, - workspaceID == nil || workspaceID == self.workspaceID, - arguments.objectValue?["workspace_id"] == nil - || arguments.objectValue?["workspace_id"] == .string(self.workspaceID) + workspaceID == nil || workspaceID == self.projectID, + arguments.objectValue?["project_id"] == nil + || arguments.objectValue?["project_id"] == .string(self.projectID) else { throw CodexToolError.executionFailed( "Host tool call does not match the bound connection scope.") @@ -116,7 +119,7 @@ actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, private func scoped(_ arguments: [String: JSONValue]) -> [String: JSONValue] { var arguments = arguments - arguments["workspace_id"] = .string(self.workspaceID) + arguments["project_id"] = .string(self.projectID) return arguments } @@ -125,14 +128,14 @@ actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, name: "policy.probe", arguments: [ "capability_id": .string(name), "arguments": .object(scoped(arguments.objectValue ?? [:])), - "workspace_id": .string(self.workspaceID), + "project_id": .string(self.projectID), ]) guard let value = result.objectValue?["structuredContent"]?.objectValue?["result"]?.objectValue, value["decision"] == .string("allowed"), value["capability_id"] == .string(name), - value["workspace_id"] == .string(self.workspaceID), - let declared = value["risk"]?.stringValue.flatMap(CodexOperationRisk.init(rawValue:)), + value["project_id"] == .string(self.projectID), + let declared = value["risk"]?.stringValue.flatMap(CodexOperationRisk.init(hostValue:)), let effective = value["effective_risk"]?.stringValue.flatMap( - CodexOperationRisk.init(rawValue:)) + CodexOperationRisk.init(hostValue:)) else { throw CodexToolError.executionFailed( "Host preflight returned an invalid or unsupported decision.") @@ -141,9 +144,7 @@ actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, name: name, digest: try Self.digest(arguments), declared: declared, effective: effective) } - private func call( - name: String, arguments: [String: JSONValue], preserveToolError: Bool = false - ) async throws -> JSONValue { + private func connect() async throws { try Task.checkCancellation() guard !closed else { throw MCPError.connectionClosed } if !connected { @@ -168,18 +169,30 @@ actor CodexHostMCPClient: CodexHostTools, CodexManagedWorkspaceHost, guard !closed else { throw MCPError.connectionClosed } connected = true } + } + + private enum RawToolCall: MCP.Method { + static let name = MCP.CallTool.name + typealias Parameters = MCP.CallTool.Parameters + typealias Result = MCP.Value + } + + private func call( + name: String, arguments: [String: JSONValue], preserveToolError: Bool = false + ) async throws -> JSONValue { + try await connect() let client = client let parameters = try JSONDecoder().decode( [String: MCP.Value].self, from: JSONEncoder().encode(arguments)) - let result: MCP.CallTool.Result = try await Self.bounded( + let result: MCP.Value = try await Self.bounded( client: client, transport: transport, timeout: requestTimeout ) { - let request: RequestContext = try await client.callTool( - name: name, arguments: parameters) + let request = try await client.send( + RawToolCall.request(.init(name: name, arguments: parameters))) return try await request.value } let value = try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(result)) - guard preserveToolError || result.isError != true else { + guard preserveToolError || value.objectValue?["isError"] != .bool(true) else { let error = value.objectValue?["structuredContent"]?.objectValue?["error"]?.objectValue throw CodexToolError.executionFailed( CodexApprovalRedactor.redactString( @@ -243,14 +256,15 @@ extension CodexHostMCPClient { let value = try await service("host.diagnostics.snapshot", ["limit": .integer(Int64(limit))]) guard let object = value.objectValue, let returnedOwner = object["owner"], - try JSONDecoder().decode(CodexRuntimeOwner.self, from: JSONEncoder().encode(returnedOwner)) - == owner, + try JSONDecoder().decode( + CodexHostDiagnosticOwner.self, from: JSONEncoder().encode(returnedOwner) + ).runtimeOwner == owner, let audits = object["recent_tool_audits"]?.arrayValue, audits.count <= limit else { throw CodexToolError.executionFailed( "Host diagnostic response differs from the connection scope or limit.") } - guard audits.allSatisfy({ $0.objectValue?["workspace_id"] == .string(workspaceID) }) + guard audits.allSatisfy({ $0.objectValue?["project_id"] == .string(projectID) }) else { throw CodexToolError.executionFailed("Host diagnostics included a different owner.") } @@ -258,39 +272,49 @@ extension CodexHostMCPClient { owner: owner, recentToolAudits: audits) } - func registerDerivedWorkspace(_ worktree: CodexManagedWorktree, now: Date) async throws { - try validateDerived(worktree) - let result = try await service("host.workspaces.register", ["worktree": worktree.json]) - guard result.objectValue?["registered"] == .bool(true), - result.objectValue?["workspace_id"] == .string(worktree.workspaceID) - else { - throw CodexToolError.executionFailed("Host did not confirm the exact derived registration.") + func validateContract() async throws { + guard launchContract == CodexProjectContract.identifier else { + throw CodexProjectContract.Unsupported(observed: launchContract) + } + try await connect() + let observed = await transport.observedProjectContract + guard observed == CodexProjectContract.identifier else { + throw CodexProjectContract.Unsupported(observed: observed) } } - func unregisterDerivedWorkspace(_ worktree: CodexManagedWorktree, now: Date) async throws { - try validateDerived(worktree) - let result = try await service("host.workspaces.unregister", ["worktree": worktree.json]) - guard result.objectValue?["unregistered"] == .bool(true) else { - throw CodexToolError.executionFailed("Host did not confirm registration removal.") + func describe(_ inspection: CodexProjectInspection) async throws -> CodexHostToolResponse { + let arguments: [String: JSONValue] + switch inspection { + case .invocation(let id): arguments = ["invocation_id": .string(id.uuidString)] + case .operation(let id): arguments = ["operation_id": .string(id.uuidString)] } + return try await projectService("host.invocations.describe", arguments) } - func authorizeRemoval(_ worktree: CodexManagedWorktree) async throws { - try validateDerived(worktree) - let result = try await service("host.workspaces.authorize_removal", ["worktree": worktree.json]) - guard result.objectValue?["authorized"] == .bool(true) else { - throw CodexToolError.executionFailed("Host did not authorize this removal.") - } + func add(_ selection: CodexWorktreeSelection, ids: CodexHostOperationIDs) async throws + -> CodexHostToolResponse + { + try await projectService( + "host.projects.worktree_add", ids.arguments.merging(selection.arguments) { id, _ in id }) } - private func validateDerived(_ worktree: CodexManagedWorktree) throws { - guard let principalID = owner.principalID, worktree.principalID == principalID, - worktree.sourceWorkspaceID == workspaceID, worktree.profileID == owner.profileID - else { - throw CodexToolError.executionFailed( - "Derived workspace receipt belongs to a different scope.") - } + func list(invocationID: UUID) async throws -> CodexHostToolResponse { + try await projectService( + "host.projects.worktree_list", ["invocation_id": .string(invocationID.uuidString)]) + } + + func remove(force: Bool, ids: CodexHostOperationIDs) async throws -> CodexHostToolResponse { + var arguments = ids.arguments + arguments["force"] = .bool(force) + return try await projectService("host.projects.worktree_remove", arguments) + } + + private func projectService(_ name: String, _ arguments: [String: JSONValue]) async throws + -> CodexHostToolResponse + { + try await validateContract() + return .init(raw: try await call(name: name, arguments: arguments, preserveToolError: true)) } private func service(_ name: String, _ arguments: [String: JSONValue]) async throws -> JSONValue { diff --git a/Sources/CodexAdapter/CodexHostServices.swift b/Sources/CodexAdapter/CodexHostServices.swift index 652a331..d39feab 100644 --- a/Sources/CodexAdapter/CodexHostServices.swift +++ b/Sources/CodexAdapter/CodexHostServices.swift @@ -13,7 +13,38 @@ struct CodexHostDiagnosticSnapshot: Sendable { let recentToolAudits: [JSONValue] } -/// The host preflights and authorizes using the connection's immutable caller and workspace. +/// Private host diagnostics use project vocabulary. Native ownership receipts +/// retain their persisted workspace representation. +struct CodexHostDiagnosticOwner: Decodable { + let projectID: String? + let profileID: String? + let caller: String? + let transport: String? + let socketConnectionID: String? + let tunnelInstanceID: String? + let tunnelProfileID: String? + let principalID: String? + + private enum CodingKeys: String, CodingKey { + case projectID = "project_id" + case profileID = "profile_id" + case caller + case transport + case socketConnectionID = "socket_connection_id" + case tunnelInstanceID = "tunnel_instance_id" + case tunnelProfileID = "tunnel_profile_id" + case principalID = "principal_id" + } + + var runtimeOwner: CodexRuntimeOwner { + .init( + workspaceID: projectID, profileID: profileID, caller: caller, transport: transport, + socketConnectionID: socketConnectionID, tunnelInstanceID: tunnelInstanceID, + tunnelProfileID: tunnelProfileID, principalID: principalID) + } +} + +/// The host preflights and authorizes using the connection's immutable caller and selected project. /// It must recheck current policy and audit each execution; a risk hint alone grants nothing. protocol CodexHostTools: Sendable { func discard(requestID: String) async diff --git a/Sources/CodexAdapter/CodexHostWorktree.swift b/Sources/CodexAdapter/CodexHostWorktree.swift new file mode 100644 index 0000000..f6dd336 --- /dev/null +++ b/Sources/CodexAdapter/CodexHostWorktree.swift @@ -0,0 +1,261 @@ +import Foundation + +struct CodexWorktreeSelection: Codable, Equatable, Sendable { + // Dictionary membership preserves explicit JSON null independently of omission. + let name: String + private let fields: [String: JSONValue] + + init(_ arguments: [String: JSONValue]) throws { + guard let name = arguments["name"]?.stringValue, name.utf8.count <= 48, + name.wholeMatch(of: #/[a-z0-9]+(-[a-z0-9]+)*/#) != nil + else { throw CodexManagedWorktreeError.invalid("name must be a lowercase worktree slug") } + var fields: [String: JSONValue] = [:] + for key in ["branch", "base"] { + guard let value = arguments[key] else { continue } + if value != .null { + guard let text = value.stringValue, !text.isEmpty, text.utf8.count <= 1024, + text.unicodeScalars.allSatisfy({ !CharacterSet.controlCharacters.contains($0) }) + else { + throw CodexManagedWorktreeError.invalid("\(key) must be a bounded branch name or null") + } + } + fields[key] = value + } + self.name = name + self.fields = fields + } + + var arguments: [String: JSONValue] { + var arguments = fields + arguments["name"] = .string(name) + return arguments + } + var expectedBranch: String { fields["branch"]?.stringValue ?? "worktree/\(name)" } + var explicitBase: String? { fields["base"]?.stringValue } +} + +struct CodexProjectScope: Codable, Equatable, Sendable { + let principalID: String + let profileID: String + let projectID: String + + init?(_ owner: CodexRuntimeOwner?) { + guard let principalID = owner?.principalID, !principalID.isEmpty, + let profileID = owner?.profileID, !profileID.isEmpty, + let projectID = owner?.workspaceID, !projectID.isEmpty + else { return nil } + self.principalID = principalID + self.profileID = profileID + self.projectID = projectID + } +} + +struct CodexHostWorktree: Codable, Equatable, Sendable, Identifiable { + let id: String + let source: CodexProjectScope + let selection: CodexWorktreeSelection + let agentID: String + let threadID: String? + let runID: String? + let parentLeaseID: String + let ttlSeconds: Int + let createdAt: Date + var updatedAt: Date + var revision = 1 + var state = CodexManagedWorktreeState.planned + var planExpiresAt: Date? + var force: Bool? + var creation: CodexWorktreeCreation? + var creationOperationID: UUID? + var currentOperationID: UUID? + var lease: CodexWorktreeLeaseOutcome? + + func projection(in scope: CodexProjectScope) -> [String: JSONValue] { + var fields: [String: JSONValue] = [ + "id": .string(id), "source_project_id": .string(source.projectID), + "project_id": creation.map { .string($0.projectID) } ?? .null, + "requested": .object(selection.arguments), + "resolved": creation?.result ?? .null, + "state": .string(state.rawValue), "revision": .integer(Int64(revision)), + "plan_expires_at": planExpiresAt.map { .string($0.ISO8601Format()) } ?? .null, + "lease": lease?.json ?? .null, + "operation_id": currentOperationID.map { .string($0.uuidString) } ?? .null, + ] + if scope == source { + fields["agent_id"] = .string(agentID) + fields["thread_id"] = threadID.map(JSONValue.string) ?? .null + fields["run_id"] = runID.map(JSONValue.string) ?? .null + fields["parent_lease_id"] = .string(parentLeaseID) + } + fields["perform_arguments"] = performArguments.map(JSONValue.object) + return fields + } + + var performArguments: [String: JSONValue]? { + let revision = JSONValue.integer(Int64(revision)) + switch state { + case .planned: + return selection.arguments.merging([ + "plan_id": .string(id), "expected_revision": revision, "confirm_provision": .bool(true), + ]) { value, _ in value } + case .removalPlanned: + return [ + "managed_worktree_id": .string(id), "expected_revision": revision, + "confirm_remove": .bool(true), "force": .bool(force == true), + ] + default: + return nil + } + } +} + +struct CodexWorktreeCreation: Codable, Equatable, Sendable { + let worktreeID: UUID + let projectID: String + let path: String + let branch: String + let result: JSONValue + + init(_ result: JSONValue, worktree: CodexHostWorktree) throws { + guard let object = result.objectValue, + let rawID = object["worktree_id"]?.stringValue, let id = UUID(uuidString: rawID), + let projectID = object["project_id"]?.stringValue, !projectID.isEmpty, + projectID != worktree.source.projectID, + let path = object["path"]?.stringValue, path.hasPrefix("/"), !path.contains("\0"), + let branch = object["branch"]?.stringValue, branch == worktree.selection.expectedBranch, + let base = object["base"]?.stringValue, !base.isEmpty, + worktree.selection.explicitBase.map({ $0 == base }) ?? true, + let warnings = object["warnings"]?.arrayValue, warnings.allSatisfy({ $0.stringValue != nil }) + else { throw CodexWorktreeObservationError.invalidCompletion } + self.worktreeID = id + self.projectID = projectID + self.path = path + self.branch = branch + self.result = result + } +} + +enum CodexWorktreeLeaseOutcome: Codable, Equatable, Sendable { + case acquired(String) + case conflict + case unavailable(String) + + var json: JSONValue { + switch self { + case .acquired(let id): .object(["state": .string("acquired"), "lease_id": .string(id)]) + case .conflict: .object(["state": .string("conflict")]) + case .unavailable(let reason): + .object(["state": .string("unavailable"), "reason": .string(reason)]) + } + } +} + +enum CodexWorktreeAction: String, Codable, Sendable { + case provision = "projects.provision" + case remove = "projects.remove" + + var tool: String { + switch self { + case .provision: "codex.worktree.provision.perform" + case .remove: "codex.worktree.remove.perform" + } + } + + var pendingState: CodexManagedWorktreeState { + switch self { + case .provision: .provisioning + case .remove: .removing + } + } +} + +enum CodexHostWorktreeState: String, Codable, Sendable { + case reserved + case running + case completed + case failed + case recoveryRequired = "recovery_required" + + var isTerminal: Bool { self == .completed || self == .failed } +} + +enum CodexWorktreeObservationError: LocalizedError { + case invalidInvocation + case invalidEnvelope + case invalidCompletion + case refusal + case conflictingTerminalState + + var errorDescription: String? { + switch self { + case .invalidInvocation: "Host invocation does not match the committed worktree operation." + case .invalidEnvelope: "Host operation envelope is missing or does not match its binding." + case .invalidCompletion: "Host completion does not match the reviewed worktree selection." + case .refusal: "Host returned a refusal without a worktree operation outcome." + case .conflictingTerminalState: "Host observation differs from the stored terminal outcome." + } + } +} + +struct CodexWorktreeOperation: Codable, Equatable, Sendable { + let ids: CodexHostOperationIDs + let domainID: String + let action: CodexWorktreeAction + let source: CodexProjectScope + let selectedProjectID: String + let arguments: [String: JSONValue] + let argumentsDigest: String + var observedState: CodexHostWorktreeState? + var envelope: JSONValue? + var response: CodexHostToolResponse? + var observationError: String? + var uncertainResponse: CodexHostToolResponse? + + func validateInvocation(_ response: CodexHostToolResponse) throws -> JSONValue { + guard response.refusal == nil else { throw CodexWorktreeObservationError.refusal } + guard response.isError != true, + let live = response.result?.objectValue, live["format_version"] == .integer(1), + live["invocation_id"]?.stringValue.flatMap(UUID.init(uuidString:)) == ids.invocationID, + live["principal_id"] == .string(source.principalID), + live["profile_id"] == .string(source.profileID), + live["project_id"] == .string(selectedProjectID), + live["tool"] == .string(action.tool), live["host_action"] == .string(action.rawValue), + live["arguments_digest"] == .string(argumentsDigest), let operation = live["operation"] + else { throw CodexWorktreeObservationError.invalidInvocation } + _ = try state(of: operation) + return operation + } + + func state(of envelope: JSONValue?) throws -> CodexHostWorktreeState { + let fields = envelope?.objectValue + guard fields?["operation_id"]?.stringValue.flatMap(UUID.init(uuidString:)) == ids.operationID, + fields?["invocation_id"]?.stringValue.flatMap(UUID.init(uuidString:)) == ids.invocationID, + fields?["action"] == .string(action.rawValue), + fields?["source_project_id"] == .string(source.projectID), + fields?["project_id"] == .string(selectedProjectID), + let state = fields?["state"]?.stringValue.flatMap(CodexHostWorktreeState.init(rawValue:)), + state == .completed ? fields?["result"]?.objectValue != nil : fields?["result"] == .null + else { throw CodexWorktreeObservationError.invalidEnvelope } + let error = fields?["error"] + switch state { + case .failed, .recoveryRequired: + guard let details = error?.objectValue, + let code = details["code"]?.stringValue, !code.isEmpty, + details["message"]?.stringValue != nil + else { throw CodexWorktreeObservationError.invalidEnvelope } + case .reserved, .running, .completed: + guard error == .null else { throw CodexWorktreeObservationError.invalidEnvelope } + } + return state + } + + func projection(in scope: CodexProjectScope, worktree: CodexHostWorktree) -> JSONValue { + var result = worktree.projection(in: scope) + result["invocation_id"] = .string(ids.invocationID.uuidString) + result["host_state"] = observedState.map { .string($0.rawValue) } ?? .null + result["host_response"] = response?.raw + result["observation_error"] = observationError.map(JSONValue.string) + result["uncertain_host_response"] = uncertainResponse?.raw + return .object(result) + } +} diff --git a/Sources/CodexAdapter/CodexHostWorktreeManager.swift b/Sources/CodexAdapter/CodexHostWorktreeManager.swift new file mode 100644 index 0000000..d2018be --- /dev/null +++ b/Sources/CodexAdapter/CodexHostWorktreeManager.swift @@ -0,0 +1,178 @@ +import Foundation +import MCP + +struct CodexHostWorktreeManager: Sendable { + let database: CodexDatabase + let scope: CodexProjectScope + let services: any CodexProjectServices + + func planProvision( + selection: CodexWorktreeSelection, agentID: String, threadID: String?, runID: String?, + parentLeaseID: String, ttlSeconds: Int, now: Date = Date() + ) throws -> JSONValue { + try Self.validateIdentifier(agentID, maximum: 256, name: "agent_id") + try Self.validateIdentifier(parentLeaseID, maximum: 256, name: "parent_lease_id") + if let threadID { try Self.validateIdentifier(threadID, maximum: 1024, name: "thread_id") } + if let runID { + try Self.validateIdentifier(runID, maximum: 256, name: "run_id") + guard let run = try database.codexOrchestrationRun(id: runID), + run.workspaceID == scope.projectID + else { throw CodexManagedWorktreeError.invalid("run_id must identify a source-local run") } + } + guard (30...86_400).contains(ttlSeconds) else { + throw CodexManagedWorktreeError.invalid("ttl_seconds must be between 30 and 86400") + } + let worktree = CodexHostWorktree( + id: UUID().uuidString.lowercased(), source: scope, selection: selection, + agentID: agentID, threadID: threadID, runID: runID, parentLeaseID: parentLeaseID, + ttlSeconds: ttlSeconds, createdAt: now, updatedAt: now, + planExpiresAt: now.addingTimeInterval(300)) + try database.saveProvisionPlan(worktree, in: scope, now: now) + return .object(worktree.projection(in: scope)) + } + + func planRemoval(id: String, force: Bool, now: Date = Date()) throws -> JSONValue { + let worktree = try database.saveRemovalPlan(id: id, in: scope, force: force, now: now) + return .object(worktree.projection(in: scope)) + } + + func perform( + id: String, action: CodexWorktreeAction, revision: Int, + arguments: [String: JSONValue], invocation: CodexHostInvocation?, now: Date = Date() + ) async throws -> MCP.CallTool.Result { + guard let invocationID = invocation?.invocationID, let operationID = invocation?.operationID, + invocationID != operationID + else { + throw CodexManagedWorktreeError.invalid("Host invocation and operation IDs are required.") + } + try await services.validateContract() + let (worktree, operation) = try database.beginWorktreeOperation( + id: id, in: scope, action: action, revision: revision, arguments: arguments, + ids: .init(invocationID: invocationID, operationID: operationID), now: now) + + var response: CodexHostToolResponse? + do { + let inspection = try await services.describe(.invocation(invocationID)) + response = inspection + let envelope = try operation.validateInvocation(inspection) + let (current, observed) = try database.settleWorktreeOperation( + id: worktree.id, in: scope, operationID: operationID, envelope: envelope, + response: inspection, now: Date()) + guard observed.observedState == .reserved else { return try projected(current, observed) } + response = nil + let effect: CodexHostToolResponse + switch action { + case .provision: + effect = try await services.add(worktree.selection, ids: operation.ids) + case .remove: + effect = try await services.remove(force: worktree.force == true, ids: operation.ids) + } + response = effect + return try settle(worktree, operation, envelope: Self.envelope(effect), response: effect) + } catch { + return try uncertain(worktree, operation, response: response, error: error) + } + } + + func read(_ worktree: CodexHostWorktree, operation: CodexWorktreeOperation?) async throws + -> MCP.CallTool.Result + { + guard let operation else { return try result(.object(worktree.projection(in: scope))) } + guard operation.observedState?.isTerminal != true else { + return try projected(worktree, operation) + } + var response: CodexHostToolResponse? + do { + let inspection = try await services.describe(.operation(operation.ids.operationID)) + response = inspection + return try settle( + worktree, operation, envelope: Self.envelope(inspection), response: inspection) + } catch let error as CodexProjectContract.Unsupported { + throw error + } catch { + return try uncertain(worktree, operation, response: response, error: error) + } + } + + func list(history: [JSONValue], limit: Int, invocation: CodexHostInvocation?) async throws + -> MCP.CallTool.Result + { + guard let id = invocation?.invocationID, invocation?.operationID == nil else { + throw CodexManagedWorktreeError.invalid("A host inventory invocation ID is required.") + } + let records = try database.hostWorktrees(in: scope, limit: limit) + let response = try await services.list(invocationID: id) + var payload: [String: JSONValue] = [ + "worktrees": .array(records.map { .object($0.projection(in: scope)) }), + "unmanaged_history": .array(history), "host_response": response.raw, + ] + if response.result?.objectValue?["worktrees"]?.arrayValue == nil + || response.isError == true || response.refusal != nil + { + payload["observation_error"] = .string("Host inventory was unavailable.") + } + return try response.toolResult(.object(payload)) + } + + private func settle( + _ worktree: CodexHostWorktree, _ operation: CodexWorktreeOperation, + envelope: JSONValue, response: CodexHostToolResponse + ) throws -> MCP.CallTool.Result { + let (current, observed) = try database.settleWorktreeOperation( + id: worktree.id, in: scope, operationID: operation.ids.operationID, + envelope: envelope, response: response, now: Date()) + return try projected(current, observed) + } + + private func uncertain( + _ worktree: CodexHostWorktree, _ operation: CodexWorktreeOperation, + response: CodexHostToolResponse?, error: Error + ) throws -> MCP.CallTool.Result { + let message = CodexApprovalRedactor.redactString( + error.localizedDescription, maximumCharacters: 4096) + if let (current, observed) = try? database.recordWorktreeObservationFailure( + id: worktree.id, in: scope, operationID: operation.ids.operationID, + response: response, message: message), + observed.observationError == message + { + return try projected(current, observed) + } + // The earlier ID transaction has committed. An observation that could not be + // stored must still be visible to the caller without claiming settlement. + let latest = try? database.hostWorktree(id: worktree.id, in: scope) + var observed = latest?.1 ?? operation + observed.observationError = message + if let response { observed.uncertainResponse = response } + return try projected(latest?.0 ?? worktree, observed) + } + + private func projected(_ worktree: CodexHostWorktree, _ operation: CodexWorktreeOperation) + throws -> MCP.CallTool.Result + { + let payload = operation.projection(in: scope, worktree: worktree) + if let response = operation.uncertainResponse ?? operation.response { + return try response.toolResult(payload) + } + return try result(payload, isError: operation.observationError != nil) + } + + private func result(_ payload: JSONValue, isError: Bool = false) throws -> MCP.CallTool.Result { + try MCP.CallTool.Result( + structuredContent: JSONValue.object(["result": payload]), isError: isError) + } + + private static func envelope(_ response: CodexHostToolResponse) throws -> JSONValue { + if response.refusal != nil { throw CodexWorktreeObservationError.refusal } + guard let envelope = response.result else { + throw CodexWorktreeObservationError.invalidEnvelope + } + return envelope + } + + private static func validateIdentifier(_ value: String, maximum: Int, name: String) throws { + guard !value.isEmpty, value.utf8.count <= maximum, + value.unicodeScalars.allSatisfy({ !CharacterSet.controlCharacters.contains($0) }), + CodexApprovalRedactor.redactString(value, maximumCharacters: maximum) == value + else { throw CodexManagedWorktreeError.invalid("\(name) must be a bounded identifier") } + } +} diff --git a/Sources/CodexAdapter/CodexLaunchContext.swift b/Sources/CodexAdapter/CodexLaunchContext.swift index 914165c..b2b372f 100644 --- a/Sources/CodexAdapter/CodexLaunchContext.swift +++ b/Sources/CodexAdapter/CodexLaunchContext.swift @@ -6,29 +6,41 @@ struct CodexLaunchContext: Sendable { let workspaceURL: URL let owner: CodexRuntimeOwner let localControlAllowed: Bool - let managedWorktreeRoot: URL? + let managedProjectRoot: URL? + let hostServiceContract: String? init(environment: [String: String], currentDirectory: URL) throws { if let text = environment["COMPUTER_MCP_HOST_CONTEXT"] { guard text.utf8.count <= 16_384, + let fields = try? JSONDecoder().decode([String: JSONValue].self, from: Data(text.utf8)), + fields["formatVersion"] == .integer(1) + else { + throw ConfigurationError.invalid("Invalid Computer MCP launch context.") + } + let marker = fields["hostServiceContract"]?.stringValue + guard marker == CodexProjectContract.identifier else { + throw CodexProjectContract.Unsupported(observed: marker) + } + guard let host = try? JSONDecoder().decode(Host.self, from: Data(text.utf8)), host.formatVersion == 1, - !host.workspace.id.isEmpty, !host.profileID.isEmpty, !host.caller.isEmpty, - Self.isAbsolutePath(host.workspace.rootPath), !host.workspace.rootPath.contains("\0") + !host.project.id.isEmpty, !host.profileID.isEmpty, !host.caller.isEmpty, + Self.isAbsolutePath(host.project.rootPath), !host.project.rootPath.contains("\0") else { throw ConfigurationError.invalid("Invalid Computer MCP launch context.") } - workspaceURL = URL(fileURLWithPath: host.workspace.rootPath).standardizedFileURL - if let root = host.managedWorkspaceRoot { + hostServiceContract = marker + workspaceURL = URL(fileURLWithPath: host.project.rootPath).standardizedFileURL + if let root = host.managedProjectRoot { guard Self.isAbsolutePath(root), root.utf8.count <= 16_384, !root.contains("\0") else { - throw ConfigurationError.invalid("Invalid host-owned managed workspace root.") + throw ConfigurationError.invalid("Invalid host-owned managed project root.") } - managedWorktreeRoot = URL(fileURLWithPath: root, isDirectory: true).standardizedFileURL + managedProjectRoot = URL(fileURLWithPath: root, isDirectory: true).standardizedFileURL } else { - managedWorktreeRoot = nil + managedProjectRoot = nil } owner = CodexRuntimeOwner( - workspaceID: host.workspace.id, profileID: host.profileID, caller: host.caller, + workspaceID: host.project.id, profileID: host.profileID, caller: host.caller, transport: host.transportTrace?.transport, socketConnectionID: host.transportTrace?.socketConnectionID, tunnelInstanceID: host.transportTrace?.tunnelInstanceID, @@ -36,7 +48,8 @@ struct CodexLaunchContext: Sendable { localControlAllowed = ["local-app", "local-cli", "local-mcp"].contains(host.caller) } else { workspaceURL = currentDirectory.standardizedFileURL - managedWorktreeRoot = nil + managedProjectRoot = nil + hostServiceContract = nil let identity = SHA256.hash(data: Data(workspaceURL.path.utf8)) .map { String(format: "%02x", $0) }.joined() owner = CodexRuntimeOwner( @@ -112,7 +125,7 @@ struct CodexLaunchContext: Sendable { owner: owner, database: database, workspaceURL: workspaceURL, recentThreadReader: .live(), localControlAllowed: localControlAllowed, - workspaceHost: hostServices, managedWorktreeRoot: managedWorktreeRoot, + projectServices: hostServices, configuredSandbox: configuration.sandbox, hostDiagnostics: hostServices, unboundStateAvailable: unboundStateAvailable, threadOwnerIndex: threadOwnerIndex) } @@ -143,7 +156,7 @@ struct CodexLaunchContext: Sendable { } private struct Host: Decodable { - struct Workspace: Decodable { + struct Project: Decodable { let id: String let rootPath: String } @@ -152,8 +165,8 @@ struct CodexLaunchContext: Sendable { let caller: String let profileID: String let principalID: String? - let workspace: Workspace - let managedWorkspaceRoot: String? + let project: Project + let managedProjectRoot: String? let transportTrace: TransportTrace? struct TransportTrace: Decodable { let transport: String diff --git a/Sources/CodexAdapter/CodexManagedWorkspaceHost.swift b/Sources/CodexAdapter/CodexManagedWorkspaceHost.swift deleted file mode 100644 index 112cf5f..0000000 --- a/Sources/CodexAdapter/CodexManagedWorkspaceHost.swift +++ /dev/null @@ -1,12 +0,0 @@ -import Foundation - -/// The host rechecks the bound source workspace, caller and profile before registering -/// a derived workspace. It owns registration, grants and their rollback; the adapter -/// supplies the exact persisted worktree receipt, never a caller-selected profile. -/// Removal is idempotent and must reject registrations not owned by that receipt. -protocol CodexManagedWorkspaceHost: Sendable { - func registerDerivedWorkspace(_ worktree: CodexManagedWorktree, now: Date) async throws - func unregisterDerivedWorkspace(_ worktree: CodexManagedWorktree, now: Date) async throws - /// Validates the current invocation's host-owned destructive-operation ticket. - func authorizeRemoval(_ worktree: CodexManagedWorktree) async throws -} diff --git a/Sources/CodexAdapter/CodexManagedWorktree.swift b/Sources/CodexAdapter/CodexManagedWorktree.swift index e1f0134..9d59f4f 100644 --- a/Sources/CodexAdapter/CodexManagedWorktree.swift +++ b/Sources/CodexAdapter/CodexManagedWorktree.swift @@ -1,4 +1,3 @@ -import CryptoKit import Foundation enum CodexManagedWorktreeState: String, Codable, Equatable, Sendable { @@ -9,66 +8,7 @@ enum CodexManagedWorktreeState: String, Codable, Equatable, Sendable { case removing case removed case failed -} - -struct CodexManagedWorktree: Codable, Equatable, Sendable, Identifiable { - let id: String - let sourceWorkspaceID: String - let workspaceID: String - let sourceRepositoryRoot: String - let gitCommonDirectory: String - let path: String - let branch: String - let startPoint: String - var headOID: String - let agentID: String - let threadID: String? - let runID: String? - let parentLeaseID: String - let profileID: String - let caller: String - let ttlSeconds: Int - var leaseID: String? - var state: CodexManagedWorktreeState - let createdAt: Date - var updatedAt: Date - var planExpiresAt: Date? - var removedAt: Date? - var lastError: String? - var revision: Int - var principalID: String? = nil - - private enum CodingKeys: String, CodingKey { - case id - case sourceWorkspaceID = "source_workspace_id" - case workspaceID = "workspace_id" - case sourceRepositoryRoot = "source_repository_root" - case gitCommonDirectory = "git_common_directory" - case path - case branch - case startPoint = "start_point" - case headOID = "head_oid" - case agentID = "agent_id" - case threadID = "thread_id" - case runID = "run_id" - case parentLeaseID = "parent_lease_id" - case profileID = "profile_id" - case principalID = "principal_id" - case caller - case ttlSeconds = "ttl_seconds" - case leaseID = "lease_id" - case state - case createdAt = "created_at" - case updatedAt = "updated_at" - case planExpiresAt = "plan_expires_at" - case removedAt = "removed_at" - case lastError = "last_error" - case revision - } - - var json: JSONValue { - (try? JSONValue.encoded(self)) ?? .object([:]) - } + case unmanaged } enum CodexManagedWorktreeError: Error, LocalizedError, Sendable { @@ -77,7 +17,6 @@ enum CodexManagedWorktreeError: Error, LocalizedError, Sendable { case unknown(String) case revisionConflict(expected: Int, actual: Int) case state(String) - case command(String) var errorDescription: String? { switch self { @@ -91,749 +30,6 @@ enum CodexManagedWorktreeError: Error, LocalizedError, Sendable { return "Managed worktree revision conflict: expected \(expected), current \(actual)." case .state(let detail): return "Managed worktree state does not allow this operation: \(detail)" - case .command(let detail): - return "Managed worktree Git operation failed: \(detail)" - } - } -} - -enum CodexManagedWorktreeManager { - private typealias FileSystem = CodexWorktreeFileSystem - static func planProvision( - database: CodexDatabase?, - sourceWorkspaceID: String?, - sourceWorkspaceURL: URL, - profileID: String?, - caller: String?, - principalID: String? = nil, - agentID: String, - threadID: String?, - runID: String?, - parentLeaseID: String, - branch: String, - startPoint: String, - ttlSeconds: Int, - commandRunner: any CommandRunning = ProcessCommandRunner(), - managedRoot: URL? = nil, - now: Date = Date() - ) throws -> CodexManagedWorktree { - guard let database else { throw CodexManagedWorktreeError.unavailable } - guard let sourceWorkspaceID, !sourceWorkspaceID.isEmpty else { - throw CodexManagedWorktreeError.invalid("the source workspace is not registered") - } - guard let profileID, !profileID.isEmpty else { - throw CodexManagedWorktreeError.invalid("the gateway profile is unavailable") - } - guard let caller, !caller.isEmpty else { - throw CodexManagedWorktreeError.invalid("the gateway caller is unavailable") - } - try validateText(agentID, name: "agent_id", maximum: 256) - try validateText(branch, name: "branch", maximum: 256) - try validateText(startPoint, name: "start_point", maximum: 256) - if let threadID { - try validateOpaqueIdentifier(threadID, name: "thread_id", maximum: 1_024) - } - guard (30...86_400).contains(ttlSeconds) else { - throw CodexManagedWorktreeError.invalid("ttl_seconds must be between 30 and 86400") - } - guard let parent = try database.codexWorktreeLease(id: parentLeaseID), - parent.workspaceID == sourceWorkspaceID, - parent.state == .active, - parent.expiresAt > now - else { - throw CodexManagedWorktreeError.invalid( - "parent_lease_id must identify an active lease for the source workspace" - ) - } - if let runID { - guard let run = try database.codexOrchestrationRun(id: runID), - run.workspaceID == sourceWorkspaceID - else { - throw CodexManagedWorktreeError.invalid( - "run_id must identify a run in the source workspace" - ) - } - } - let sourceRoot = try canonicalURL(sourceWorkspaceURL.path, relativeTo: sourceWorkspaceURL) - let repositoryRoot = try gitPath( - ["rev-parse", "--show-toplevel"], - workingDirectory: sourceRoot, - runner: commandRunner - ) - guard - try FileSystem.sameDirectory(canonicalURL(repositoryRoot, relativeTo: sourceRoot), sourceRoot) - else { - throw CodexManagedWorktreeError.invalid( - "the registered source workspace must be the Git repository root" - ) - } - _ = try git( - ["check-ref-format", "--branch", branch], - workingDirectory: sourceRoot, - runner: commandRunner - ) - let branchLookup = try gitResult( - ["show-ref", "--verify", "--quiet", "refs/heads/\(branch)"], - workingDirectory: sourceRoot, - runner: commandRunner - ) - guard branchLookup.exitCode == 1 else { - if branchLookup.exitCode == 0 { - throw CodexManagedWorktreeError.invalid("branch already exists") - } - throw commandError(branchLookup) - } - let headOID = try gitText( - ["rev-parse", "--verify", "\(startPoint)^{commit}"], - workingDirectory: sourceRoot, - runner: commandRunner - ) - guard isObjectID(headOID) else { - throw CodexManagedWorktreeError.command("Git returned an invalid start commit.") - } - let commonDirectory = try canonicalURL( - try gitPath( - ["rev-parse", "--git-common-dir"], - workingDirectory: sourceRoot, - runner: commandRunner - ), - relativeTo: sourceRoot - ) - let id = UUID().uuidString.lowercased() - let workspaceID = "codex-worktree-\(id)" - let root = managedRootURL(database: database, override: managedRoot) - let sourceComponent = SHA256.hash(data: Data(sourceWorkspaceID.utf8)) - .prefix(12).map { String(format: "%02x", $0) }.joined() - let target = - root - .appendingPathComponent(sourceComponent, isDirectory: true) - .appendingPathComponent(id, isDirectory: true) - .standardizedFileURL - guard try FileSystem.isDescendant(target, of: root) else { - throw CodexManagedWorktreeError.invalid("derived worktree path escaped the managed root") - } - guard try FileSystem.provisionPathIsAvailable(target) else { - throw CodexManagedWorktreeError.invalid("derived worktree path already exists") - } - guard - !(try database.codexManagedWorktrees(sourceWorkspaceID: sourceWorkspaceID, limit: 5_000)) - .contains(where: { - $0.branch == branch - && [.planned, .provisioning, .active, .removalPlanned, .removing].contains($0.state) - }) - else { - throw CodexManagedWorktreeError.invalid( - "branch is already reserved by a Computer MCP-managed worktree" - ) - } - let record = CodexManagedWorktree( - id: id, - sourceWorkspaceID: sourceWorkspaceID, - workspaceID: workspaceID, - sourceRepositoryRoot: sourceRoot.path, - gitCommonDirectory: commonDirectory.path, - path: target.path, - branch: branch, - startPoint: startPoint, - headOID: headOID, - agentID: agentID, - threadID: threadID, - runID: runID, - parentLeaseID: parentLeaseID, - profileID: profileID, - caller: caller, - ttlSeconds: ttlSeconds, - leaseID: nil, - state: .planned, - createdAt: now, - updatedAt: now, - planExpiresAt: now.addingTimeInterval(300), - removedAt: nil, - lastError: nil, - revision: 1, principalID: principalID - ) - try database.saveCodexManagedWorktree(record) - return record - } - - static func performProvision( - database: CodexDatabase?, - sourceWorkspaceID: String?, - planID: String, - expectedRevision: Int, - confirmProvision: Bool, - workspaceHost: any CodexManagedWorkspaceHost, - commandRunner: any CommandRunning = ProcessCommandRunner(), - managedRoot: URL? = nil, - now: Date = Date() - ) async throws -> CodexManagedWorktree { - guard let database else { throw CodexManagedWorktreeError.unavailable } - guard confirmProvision else { - throw CodexManagedWorktreeError.invalid( - "confirm_provision must be true after reviewing the persisted plan" - ) - } - guard var record = try database.codexManagedWorktree(id: planID), - record.sourceWorkspaceID == sourceWorkspaceID - else { - throw CodexManagedWorktreeError.unknown(planID) - } - guard record.revision == expectedRevision else { - throw CodexManagedWorktreeError.revisionConflict( - expected: expectedRevision, - actual: record.revision - ) - } - guard record.state == .planned, record.planExpiresAt.map({ $0 > now }) == true else { - throw CodexManagedWorktreeError.state("the provision plan is not current") - } - guard let parent = try database.codexWorktreeLease(id: record.parentLeaseID), - parent.workspaceID == record.sourceWorkspaceID, - parent.state == .active, - parent.expiresAt > now - else { - throw CodexManagedWorktreeError.state("the parent lease is no longer active") - } - let sourceRoot = URL(fileURLWithPath: record.sourceRepositoryRoot, isDirectory: true) - let expectedRoot = managedRootURL(database: database, override: managedRoot) - let target = URL(fileURLWithPath: record.path, isDirectory: true).standardizedFileURL - guard try FileSystem.isDescendant(target, of: expectedRoot) else { - throw CodexManagedWorktreeError.invalid("persisted path is outside the managed root") - } - guard try FileSystem.provisionPathIsAvailable(target) else { - throw CodexManagedWorktreeError.state("the planned worktree path already exists") - } - let resolvedOID = try gitText( - ["rev-parse", "--verify", "\(record.startPoint)^{commit}"], - workingDirectory: sourceRoot, - runner: commandRunner - ) - guard resolvedOID == record.headOID else { - throw CodexManagedWorktreeError.state("the planned start point changed") - } - let branchLookup = try gitResult( - ["show-ref", "--verify", "--quiet", "refs/heads/\(record.branch)"], - workingDirectory: sourceRoot, - runner: commandRunner - ) - guard branchLookup.exitCode == 1 else { - throw CodexManagedWorktreeError.state("the planned branch is no longer available") - } - record = try database.updateCodexManagedWorktree( - id: record.id, - sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - value.state = .provisioning - value.updatedAt = now - value.lastError = nil - } - var createdLease: CodexWorktreeLease? - var createdGitWorktree = false - do { - try FileSystem.prepareRoot(expectedRoot) - try FileSystem.prepareParent(target.deletingLastPathComponent(), containedIn: expectedRoot) - _ = try git( - ["worktree", "add", "-b", record.branch, target.path, record.headOID], - workingDirectory: sourceRoot, - runner: commandRunner - ) - createdGitWorktree = true - let actualRoot = try canonicalURL( - try gitPath( - ["rev-parse", "--show-toplevel"], - workingDirectory: target, - runner: commandRunner - ), - relativeTo: target - ) - let actualCommon = try canonicalURL( - try gitPath( - ["rev-parse", "--git-common-dir"], - workingDirectory: target, - runner: commandRunner - ), - relativeTo: target - ) - try validateManagedDirectory(target, containedIn: expectedRoot) - guard try FileSystem.sameDirectory(actualRoot, target.resolvingSymlinksInPath()), - try FileSystem.sameDirectory(actualCommon, URL(fileURLWithPath: record.gitCommonDirectory)) - else { - throw CodexManagedWorktreeError.state( - "Git did not create the exact planned worktree in the source repository" - ) - } - try await workspaceHost.registerDerivedWorkspace(record, now: now) - let lease = try database.acquireCodexWorktreeLease( - workspaceID: record.workspaceID, - workspacePath: target.path, - mode: .isolatedWorktree, - agentID: record.agentID, - threadID: record.threadID, - runID: record.runID, - parentLeaseID: record.parentLeaseID, - branch: record.branch, - ttlSeconds: record.ttlSeconds, - now: now, - managedWorktreeID: record.id - ) - createdLease = lease - let actualHead = try gitText( - ["rev-parse", "HEAD"], - workingDirectory: target, - runner: commandRunner - ) - return try database.updateCodexManagedWorktree( - id: record.id, - sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - value.state = .active - value.headOID = actualHead - value.leaseID = lease.id - value.updatedAt = now - value.planExpiresAt = nil - } - } catch { - var recoveryErrors: [String] = [] - if let createdLease { - do { - _ = try CodexWorktreeLeaseManager.release( - database: database, - workspaceID: createdLease.workspaceID, leaseID: createdLease.id, - expectedRevision: createdLease.revision, - reason: "managed_worktree_provision_rolled_back", now: now) - } catch { recoveryErrors.append("The created writer lease could not be released.") } - } - var hostRemovalConfirmed = false - do { - try await workspaceHost.unregisterDerivedWorkspace(record, now: now) - hostRemovalConfirmed = true - } catch { - recoveryErrors.append( - "Host registration removal is unconfirmed; the owned worktree was preserved.") - } - if createdGitWorktree && hostRemovalConfirmed && recoveryErrors.isEmpty { - do { - _ = try git( - ["worktree", "remove", target.path], workingDirectory: sourceRoot, runner: commandRunner - ) - guard try FileSystem.isAbsent(target) else { - throw CodexManagedWorktreeError.state("Git rollback did not remove the exact target") - } - // Delete only the exact branch value created by this operation; an independently - // advanced reference must not be lost to unconditional branch deletion. - let removed = try gitResult( - ["update-ref", "-d", "refs/heads/" + record.branch, record.headOID], - workingDirectory: sourceRoot, runner: commandRunner) - if removed.exitCode != 0 { - recoveryErrors.append("The branch changed independently and was preserved.") - } - } catch { - recoveryErrors.append( - "Git rollback is incomplete; remaining owned content was preserved.") - } - } - let message = - safeError(error) - + (recoveryErrors.isEmpty - ? "" : " Recovery incomplete: " + recoveryErrors.joined(separator: " ")) - _ = try? database.updateCodexManagedWorktree( - id: record.id, sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - value.state = .failed - value.updatedAt = now - value.planExpiresAt = nil - value.lastError = message - } - throw error - } - } - - static func planRemoval( - database: CodexDatabase?, - sourceWorkspaceID: String?, - managedWorktreeID: String, - liveRuntimeStatus: JSONValue, - commandRunner: any CommandRunning = ProcessCommandRunner(), - managedRoot: URL? = nil, - now: Date = Date() - ) throws -> CodexManagedWorktree { - guard let database else { throw CodexManagedWorktreeError.unavailable } - guard let record = try database.codexManagedWorktree(id: managedWorktreeID), - record.sourceWorkspaceID == sourceWorkspaceID - else { - throw CodexManagedWorktreeError.unknown(managedWorktreeID) - } - if record.state == .removing { - try validateRemovedWorktree( - record, database: database, liveRuntimeStatus: liveRuntimeStatus, - commandRunner: commandRunner, managedRoot: managedRoot, now: now) - // This preview describes cleanup of already-removed content. It does not create a - // fresh destructive plan or authorize touching a path that has reappeared. - return record - } - guard record.state == .active else { - throw CodexManagedWorktreeError.state( - "only an active or incompletely removed managed worktree can be reviewed") - } - try validateRemoval( - record, - database: database, - liveRuntimeStatus: liveRuntimeStatus, - commandRunner: commandRunner, - managedRoot: managedRoot, - expectedHeadOID: nil, - now: now - ) - let target = URL(fileURLWithPath: record.path, isDirectory: true) - let headOID = try gitText( - ["rev-parse", "HEAD"], - workingDirectory: target, - runner: commandRunner - ) - return try database.updateCodexManagedWorktree( - id: record.id, - sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - value.state = .removalPlanned - value.headOID = headOID - value.updatedAt = now - value.planExpiresAt = now.addingTimeInterval(300) - value.lastError = nil - } - } - - static func performRemoval( - database: CodexDatabase?, - sourceWorkspaceID: String?, - managedWorktreeID: String, - expectedRevision: Int, - confirmRemoval: Bool, - workspaceHost: any CodexManagedWorkspaceHost, - liveRuntimeStatus: JSONValue, - commandRunner: any CommandRunning = ProcessCommandRunner(), - managedRoot: URL? = nil, - now: Date = Date() - ) async throws -> CodexManagedWorktree { - guard let database else { throw CodexManagedWorktreeError.unavailable } - guard confirmRemoval else { - throw CodexManagedWorktreeError.invalid( - "confirm_remove must be true after reviewing the removal plan" - ) - } - guard var record = try database.codexManagedWorktree(id: managedWorktreeID), - record.sourceWorkspaceID == sourceWorkspaceID - else { - throw CodexManagedWorktreeError.unknown(managedWorktreeID) - } - guard record.revision == expectedRevision else { - throw CodexManagedWorktreeError.revisionConflict( - expected: expectedRevision, - actual: record.revision - ) - } - let cleanupOnly = record.state == .removing - guard - cleanupOnly - || (record.state == .removalPlanned && record.planExpiresAt.map({ $0 > now }) == true) - else { throw CodexManagedWorktreeError.state("the removal plan is not current") } - if cleanupOnly { - try validateRemovedWorktree( - record, database: database, liveRuntimeStatus: liveRuntimeStatus, - commandRunner: commandRunner, managedRoot: managedRoot, now: now) - } else { - try validateRemoval( - record, database: database, liveRuntimeStatus: liveRuntimeStatus, - commandRunner: commandRunner, managedRoot: managedRoot, expectedHeadOID: record.headOID, - now: now) - } - try await workspaceHost.authorizeRemoval(record) - record = try database.updateCodexManagedWorktree( - id: record.id, - sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - value.state = .removing - value.updatedAt = now - value.lastError = nil } - let sourceRoot = URL(fileURLWithPath: record.sourceRepositoryRoot, isDirectory: true) - do { - if !cleanupOnly { - _ = try git( - ["worktree", "remove", record.path], workingDirectory: sourceRoot, runner: commandRunner) - } - try validateRemovedWorktree( - record, database: database, liveRuntimeStatus: liveRuntimeStatus, - commandRunner: commandRunner, managedRoot: managedRoot, now: now) - try await workspaceHost.unregisterDerivedWorkspace(record, now: now) - return try database.updateCodexManagedWorktree( - id: record.id, - sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - value.state = .removed - value.updatedAt = now - value.removedAt = now - value.planExpiresAt = nil - } - } catch { - let message = safeError(error) - _ = try? database.updateCodexManagedWorktree( - id: record.id, - sourceWorkspaceID: sourceWorkspaceID, - expectedRevision: record.revision - ) { value in - // Filesystem deletion cannot be rolled back by restoring an "active" enum. - // Keep the pending cleanup receipt until a new review verifies Git and path absence. - value.state = .removing - value.updatedAt = now - value.planExpiresAt = nil - value.lastError = message - } - throw error - } - } - - static func managedRootURL(database: CodexDatabase, override: URL?) -> URL { - if let override { - return override.standardizedFileURL - } - if let databaseURL = database.fileURL { - return databaseURL.deletingLastPathComponent() - .appendingPathComponent("Managed Worktrees", isDirectory: true) - .standardizedFileURL - } - return FileManager.default.temporaryDirectory - .appendingPathComponent("Computer MCP Managed Worktrees", isDirectory: true) - .standardizedFileURL - } - - private static func validateRemoval( - _ record: CodexManagedWorktree, - database: CodexDatabase, - liveRuntimeStatus: JSONValue, - commandRunner: any CommandRunning, - managedRoot: URL?, - expectedHeadOID: String?, - now: Date - ) throws { - guard let leaseID = record.leaseID, - let lease = try database.codexWorktreeLease(id: leaseID), - lease.workspaceID == record.workspaceID, - !database.sharesWorktreeLeases || lease.managedWorktreeID == record.id - else { - throw CodexManagedWorktreeError.state("the managed writer lease receipt is missing") - } - guard lease.state != .active else { - let suffix = lease.expiresAt <= now ? "run lease cleanup first" : "release it first" - throw CodexManagedWorktreeError.state("the managed writer lease is active; \(suffix)") - } - guard (liveRuntimeStatus.objectValue?["runtimes"]?.arrayValue ?? []).isEmpty else { - throw CodexManagedWorktreeError.state( - "a live Computer MCP runtime still owns the managed workspace" - ) - } - let root = managedRootURL(database: database, override: managedRoot).standardizedFileURL - let target = URL(fileURLWithPath: record.path, isDirectory: true).standardizedFileURL - try validateManagedDirectory(root, containedIn: root) - guard try FileSystem.isDescendant(target, of: root), - FileManager.default.fileExists(atPath: target.path) - else { - throw CodexManagedWorktreeError.state( - "the ownership receipt does not identify an existing path under the managed root" - ) - } - try validateManagedDirectory(target, containedIn: root) - let actualRoot = try canonicalURL( - try gitPath( - ["rev-parse", "--show-toplevel"], - workingDirectory: target, - runner: commandRunner - ), - relativeTo: target - ) - let actualCommon = try canonicalURL( - try gitPath( - ["rev-parse", "--git-common-dir"], - workingDirectory: target, - runner: commandRunner - ), - relativeTo: target - ) - guard try FileSystem.sameDirectory(actualRoot, target.resolvingSymlinksInPath()), - try FileSystem.sameDirectory(actualCommon, URL(fileURLWithPath: record.gitCommonDirectory)) - else { - throw CodexManagedWorktreeError.state( - "the path is not the exact worktree recorded by Computer MCP" - ) - } - let status = try gitResult( - ["status", "--porcelain=v1", "-z"], - workingDirectory: target, - runner: commandRunner - ) - guard status.exitCode == 0, status.stdout.isEmpty else { - throw CodexManagedWorktreeError.state("the managed worktree is not clean") - } - if let expectedHeadOID { - let head = try gitText( - ["rev-parse", "HEAD"], - workingDirectory: target, - runner: commandRunner - ) - guard head == expectedHeadOID else { - throw CodexManagedWorktreeError.state("the managed worktree HEAD changed after review") - } - } - } - - private static func validateRemovedWorktree( - _ record: CodexManagedWorktree, database: CodexDatabase, liveRuntimeStatus: JSONValue, - commandRunner: any CommandRunning, managedRoot: URL?, now: Date - ) throws { - guard let leaseID = record.leaseID, let lease = try database.codexWorktreeLease(id: leaseID), - lease.workspaceID == record.workspaceID, lease.state != .active, - !database.sharesWorktreeLeases || lease.managedWorktreeID == record.id, - (liveRuntimeStatus.objectValue?["runtimes"]?.arrayValue ?? []).isEmpty - else { - throw CodexManagedWorktreeError.state( - "metadata cleanup requires a released owned lease and no live runtime") - } - let root = managedRootURL(database: database, override: managedRoot).standardizedFileURL - let target = URL(fileURLWithPath: record.path).standardizedFileURL - guard try FileSystem.isDescendant(target, of: root) else { - throw CodexManagedWorktreeError.state("metadata cleanup path escaped the managed root") - } - try validateManagedDirectory(root, containedIn: root) - try validateManagedDirectory(target.deletingLastPathComponent(), containedIn: root) - guard try FileSystem.isAbsent(target) else { - throw CodexManagedWorktreeError.state( - "metadata cleanup refuses an existing or unverified path") - } - let source = URL(fileURLWithPath: record.sourceRepositoryRoot) - let common = try canonicalURL( - try gitPath( - ["rev-parse", "--git-common-dir"], workingDirectory: source, runner: commandRunner), - relativeTo: source) - guard try FileSystem.sameDirectory(common, URL(fileURLWithPath: record.gitCommonDirectory)) - else { - throw CodexManagedWorktreeError.state("metadata cleanup source repository identity changed") - } - let inventory = try git( - ["worktree", "list", "--porcelain", "-z"], workingDirectory: source, runner: commandRunner) - let paths = inventory.stdout.split(separator: "\0").compactMap { entry -> String? in - guard entry.hasPrefix("worktree ") else { return nil } - return String(entry.dropFirst("worktree ".count)) - } - guard - try !paths.contains(where: { try FileSystem.samePath(URL(fileURLWithPath: $0), target) }) - else { - throw CodexManagedWorktreeError.state( - "Git still records the worktree; metadata-only cleanup is unsafe") - } - } - - private static func validateManagedDirectory(_ directory: URL, containedIn root: URL) throws { - try FileSystem.validateDirectory(directory, containedIn: root) - } - - private static func validateText(_ value: String, name: String, maximum: Int) throws { - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty, trimmed.utf8.count <= maximum, trimmed == value else { - throw CodexManagedWorktreeError.invalid( - "\(name) must contain 1...\(maximum) bytes without surrounding whitespace" - ) - } - guard CodexApprovalRedactor.redactString(value, maximumCharacters: maximum) == value else { - throw CodexManagedWorktreeError.invalid( - "\(name) must not contain credential-like text" - ) - } - } - - private static func validateOpaqueIdentifier( - _ value: String, - name: String, - maximum: Int - ) throws { - let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty, trimmed == value, value.utf8.count <= maximum else { - throw CodexManagedWorktreeError.invalid( - "\(name) must contain 1...\(maximum) bytes without surrounding whitespace" - ) - } - } - - private static func git( - _ arguments: [String], - workingDirectory: URL, - runner: any CommandRunning - ) throws -> CommandResult { - let result = try gitResult(arguments, workingDirectory: workingDirectory, runner: runner) - guard result.exitCode == 0, !result.timedOut else { throw commandError(result) } - return result - } - - private static func gitText( - _ arguments: [String], - workingDirectory: URL, - runner: any CommandRunning - ) throws -> String { - try git(arguments, workingDirectory: workingDirectory, runner: runner) - .stdout.trimmingCharacters(in: .whitespacesAndNewlines) - } - - private static func gitPath( - _ arguments: [String], - workingDirectory: URL, - runner: any CommandRunning - ) throws -> String { - let value = try gitText(arguments, workingDirectory: workingDirectory, runner: runner) - guard !value.isEmpty, value.utf8.count <= 16_384 else { - throw CodexManagedWorktreeError.command("Git returned an invalid path.") - } - return value - } - - private static func gitResult( - _ arguments: [String], - workingDirectory: URL, - runner: any CommandRunning - ) throws -> CommandResult { - try runner.run( - executable: FileSystem.gitExecutable, - arguments: arguments, - workingDirectory: workingDirectory, - environment: ["GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C"], - timeoutMilliseconds: 30_000, - maxOutputBytes: 1_048_576 - ) - } - - private static func commandError(_ result: CommandResult) -> CodexManagedWorktreeError { - let detail = - result.timedOut - ? "command timed out" - : (result.stderr.isEmpty ? "exit \(result.exitCode ?? -1)" : result.stderr) - return .command(CodexApprovalRedactor.redactString(detail, maximumCharacters: 4_096)) - } - - private static func canonicalURL(_ path: String, relativeTo base: URL) throws -> URL { - try FileSystem.canonicalDirectory(path, relativeTo: base) - } - - private static func isObjectID(_ value: String) -> Bool { - value.utf8.count == 40 - && value.utf8.allSatisfy { - ($0 >= 48 && $0 <= 57) || ($0 >= 97 && $0 <= 102) - } - } - - private static func safeError(_ error: Error) -> String { - CodexApprovalRedactor.redactString(error.localizedDescription, maximumCharacters: 4_096) } } diff --git a/Sources/CodexAdapter/CodexOperationRisk.swift b/Sources/CodexAdapter/CodexOperationRisk.swift index d05f079..3997b44 100644 --- a/Sources/CodexAdapter/CodexOperationRisk.swift +++ b/Sources/CodexAdapter/CodexOperationRisk.swift @@ -4,4 +4,16 @@ enum CodexOperationRisk: String, Codable, Equatable, Sendable { case externalWrite = "external-write" case destructive case fullShell = "full-shell" + + var hostValue: String { self == .workspaceWrite ? "project-write" : rawValue } + + init?(hostValue: String) { + if hostValue == "project-write" { + self = .workspaceWrite + } else if hostValue == Self.workspaceWrite.rawValue { + return nil + } else { + self.init(rawValue: hostValue) + } + } } diff --git a/Sources/CodexAdapter/CodexOperationalDiagnostics.swift b/Sources/CodexAdapter/CodexOperationalDiagnostics.swift index 0272957..3abddc9 100644 --- a/Sources/CodexAdapter/CodexOperationalDiagnostics.swift +++ b/Sources/CodexAdapter/CodexOperationalDiagnostics.swift @@ -15,7 +15,7 @@ enum CodexOperationalDiagnostics { guard let owner, hostSnapshot.owner == owner, hostSnapshot.recentToolAudits.count <= limit, hostSnapshot.recentToolAudits.allSatisfy({ - $0.objectValue?["workspace_id"]?.stringValue == owner.workspaceID + $0.objectValue?["project_id"]?.stringValue == owner.workspaceID }) else { throw CodexToolError.executionFailed( @@ -32,11 +32,19 @@ enum CodexOperationalDiagnostics { let approvals = try database?.codexApprovals(workspaceID: workspaceID, limit: limit) ?? [] let runs = try database?.codexOrchestrationRuns(workspaceID: workspaceID, limit: limit) ?? [] let leases = try database?.codexWorktreeLeases(workspaceID: workspaceID, limit: limit) ?? [] - let managedWorktrees = Array( - try database?.codexManagedWorktrees(limit: max(limit * 4, limit)) - .filter { $0.sourceWorkspaceID == workspaceID || $0.workspaceID == workspaceID } - .prefix(limit) ?? [] - ) + let projectScope = CodexProjectScope(owner) + let managedWorktrees = + try projectScope.flatMap { + try database?.hostWorktrees(in: $0, limit: limit) + } ?? [] + let unmanagedHistory = + try owner.flatMap { + try database?.unmanagedWorktrees(owner: $0, limit: limit) + } ?? [] + let worktreeProjections = + projectScope.map { scope in + managedWorktrees.map { JSONValue.object($0.projection(in: scope)) } + } ?? [] let audits = hostSnapshot?.recentToolAudits ?? [] let cleanup = try CodexRuntimeMaintenance.preview( database: database, @@ -67,7 +75,7 @@ enum CodexOperationalDiagnostics { return .object([ "generated_at": .string(timestamp(now)), "scope": .object([ - "workspace_id": diagnosticIdentifier(workspaceID), + "project_id": diagnosticIdentifier(workspaceID), "principal_id": diagnosticIdentifier(owner?.principalID), "profile_id": diagnosticIdentifier(owner?.profileID), "caller": diagnosticIdentifier(owner?.caller), @@ -110,7 +118,8 @@ enum CodexOperationalDiagnostics { "active_runs": .array(activeRuns.map(\.json)), "active_worktree_leases": .array(activeLeases.map(\.json)), "expired_worktree_lease_receipts": .array(expiredLeaseReceipts.map(\.json)), - "managed_worktrees": .array(managedWorktrees.map(\.json)), + "managed_worktrees": .array(worktreeProjections), + "unmanaged_history": .array(unmanagedHistory), "recent_tool_audits": hostSnapshot == nil ? .null : .array(audits.map(auditJSON)), "safety": .object([ "secrets_redacted": .bool(true), @@ -126,7 +135,7 @@ enum CodexOperationalDiagnostics { pendingApprovals: [CodexApprovalRecord], activeRuns: [CodexOrchestrationRun], expiredLeaseReceipts: [CodexWorktreeLease], - managedWorktrees: [CodexManagedWorktree], + managedWorktrees: [CodexHostWorktree], threadOwnership: [CodexThreadOwnershipRecord], now: Date ) -> [JSONValue] { @@ -210,7 +219,7 @@ enum CodexOperationalDiagnostics { code: "managed_worktree_failed", summary: "A Computer MCP-managed worktree lifecycle operation failed.", recovery: - "Inspect the managed worktree receipt and verify Git ownership before retrying or cleaning up.", + "Read the host operation outcome before making a fresh request.", subjectID: worktree.id ) ) @@ -224,7 +233,7 @@ enum CodexOperationalDiagnostics { severity: "info", code: "managed_worktree_plan_expired", summary: "A reviewed managed worktree plan expired without execution.", - recovery: "Create a fresh plan so Git and ownership state are validated again.", + recovery: "Create a fresh worktree plan.", subjectID: worktree.id ) ) @@ -274,7 +283,7 @@ enum CodexOperationalDiagnostics { for key in [ "id", "occurred_at", "request_id", "mcp_request_id", "invocation_id", "parent_request_id", "ticket_id", "transport", "socket_connection_id", - "tunnel_instance_id", "tunnel_profile_id", "profile_id", "workspace_id", + "tunnel_instance_id", "tunnel_profile_id", "profile_id", "project_id", "capability_id", "decision", "error_code", "input_digest", "output_digest", ] { result[key] = diagnosticIdentifier(object[key]?.stringValue) diff --git a/Sources/CodexAdapter/CodexProjectServices.swift b/Sources/CodexAdapter/CodexProjectServices.swift new file mode 100644 index 0000000..a0a7d14 --- /dev/null +++ b/Sources/CodexAdapter/CodexProjectServices.swift @@ -0,0 +1,148 @@ +import CryptoKit +import Foundation +import Logging +import MCP + +enum CodexProjectContract { + static let identifier = "projects-v1" + static let capabilityKey = "io.github.computer-mcp/host-service-contract" + + struct Unsupported: LocalizedError { + let observed: String? + + var errorDescription: String? { + "[host.unsupported_contract] Required projects-v1, observed \(observed ?? "none"). " + + "Update Computer MCP and the Codex plugin together, then restart the provider." + } + + var fields: JSONValue { + .object([ + "code": .string("host.unsupported_contract"), + "message": .string(errorDescription ?? ""), + "required_contract": .string(CodexProjectContract.identifier), + "observed_contract": observed.map(JSONValue.string) ?? .null, + ]) + } + } +} + +/// The pinned SDK models standard capabilities only. Add the contract to the wire +/// result while retaining the SDK's initialize handler and protocol negotiation. +actor CodexProjectHandshakeTransport: MCP.Transport { + private let transport: any MCP.Transport + + private let contract: String + init(_ transport: any MCP.Transport, contract: String = CodexProjectContract.identifier) { + self.transport = transport + self.contract = contract + } + + nonisolated let logger = Logger( + label: "codex.project-handshake", factory: { _ in SwiftLogNoOpLogHandler() }) + private var frames: AsyncThrowingStream? + private var advertised = false + + func connect() async throws { + try await transport.connect() + frames = await transport.receive() + } + + func disconnect() async { await transport.disconnect() } + + func receive() -> AsyncThrowingStream { + frames ?? AsyncThrowingStream { $0.finish(throwing: MCPError.connectionClosed) } + } + + func send(_ data: Data) async throws { + guard !advertised, + var message = try? JSONDecoder().decode([String: JSONValue].self, from: data), + var result = message["result"]?.objectValue, + result["serverInfo"] != nil, result["protocolVersion"] != nil, + var capabilities = result["capabilities"]?.objectValue + else { + try await transport.send(data) + return + } + var experimental = capabilities["experimental"]?.objectValue ?? [:] + experimental[CodexProjectContract.capabilityKey] = .string(contract) + capabilities["experimental"] = .object(experimental) + result["capabilities"] = .object(capabilities) + message["result"] = .object(result) + try await transport.send(JSONEncoder().encode(message)) + advertised = true + } +} + +struct CodexHostInvocation: Sendable { + static let invocationKey = "io.github.computer-mcp/host-invocation" + static let operationKey = "io.github.computer-mcp/host-operation" + + let invocationID: UUID? + let operationID: UUID? + + init(_ metadata: MCP.Metadata?) throws { + func uuid(_ key: String) throws -> UUID? { + guard let value = metadata?[key] else { return nil } + guard let raw = value.stringValue, let id = UUID(uuidString: raw), + id.uuidString.lowercased() == raw.lowercased() + else { throw MCPError.invalidParams("Host lifecycle metadata must contain UUIDs.") } + return id + } + invocationID = try uuid(Self.invocationKey) + operationID = try uuid(Self.operationKey) + } + + static func digest(_ arguments: [String: JSONValue]) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return SHA256.hash(data: try encoder.encode(JSONValue.object(arguments))) + .map { String(format: "%02x", $0) }.joined() + } +} + +struct CodexHostOperationIDs: Codable, Equatable, Sendable { + let invocationID: UUID + let operationID: UUID + + var arguments: [String: JSONValue] { + [ + "invocation_id": .string(invocationID.uuidString), + "operation_id": .string(operationID.uuidString), + ] + } +} + +enum CodexProjectInspection: Sendable { + case invocation(UUID) + case operation(UUID) +} + +struct CodexHostToolResponse: Codable, Equatable, Sendable { + let raw: JSONValue + + var structured: [String: JSONValue]? { + raw.objectValue?["structuredContent"]?.objectValue + } + var result: JSONValue? { structured?["result"] } + var refusal: JSONValue? { structured?["error"] } + var isError: Bool? { raw.objectValue?["isError"]?.boolValue } + + func toolResult(_ result: JSONValue) throws -> MCP.CallTool.Result { + let original = try? JSONDecoder().decode( + MCP.CallTool.Result.self, from: JSONEncoder().encode(raw)) + return try MCP.CallTool.Result( + content: original?.content ?? [], + structuredContent: JSONValue.object(["result": result]), + isError: result.objectValue?["observation_error"] != nil || isError == true, + _meta: original?._meta) + } +} + +protocol CodexProjectServices: Sendable { + func validateContract() async throws + func describe(_ inspection: CodexProjectInspection) async throws -> CodexHostToolResponse + func add(_ selection: CodexWorktreeSelection, ids: CodexHostOperationIDs) async throws + -> CodexHostToolResponse + func list(invocationID: UUID) async throws -> CodexHostToolResponse + func remove(force: Bool, ids: CodexHostOperationIDs) async throws -> CodexHostToolResponse +} diff --git a/Sources/CodexAdapter/CodexWorktreeFileSystem.swift b/Sources/CodexAdapter/CodexWorktreeFileSystem.swift deleted file mode 100644 index 9a9ff71..0000000 --- a/Sources/CodexAdapter/CodexWorktreeFileSystem.swift +++ /dev/null @@ -1,93 +0,0 @@ -import Darwin -import Foundation - -/// Filesystem ownership for managed Git operations; host authorization remains with the manager. -enum CodexWorktreeFileSystem { - static let gitExecutable = "/usr/bin/git" - - static func prepareRoot(_ root: URL) throws { - let fileManager = FileManager.default - if fileManager.fileExists(atPath: root.path) { - let values = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) - guard values.isDirectory == true, values.isSymbolicLink != true else { - throw CodexManagedWorktreeError.invalid( - "the managed worktree root must be a real directory" - ) - } - let attributes = try fileManager.attributesOfItem(atPath: root.path) - if let owner = attributes[.ownerAccountID] as? NSNumber, owner.uint32Value != getuid() { - throw CodexManagedWorktreeError.invalid( - "the managed worktree root is owned by another user" - ) - } - } else { - try fileManager.createDirectory( - at: root, - withIntermediateDirectories: true, - attributes: [.posixPermissions: NSNumber(value: Int16(0o700))] - ) - } - try fileManager.setAttributes( - [.posixPermissions: NSNumber(value: Int16(0o700))], - ofItemAtPath: root.path - ) - } - - static func prepareParent(_ parent: URL, containedIn root: URL) throws { - try FileManager.default.createDirectory( - at: parent, withIntermediateDirectories: true, - attributes: [.posixPermissions: NSNumber(value: Int16(0o700))]) - try validateDirectory(parent, containedIn: root) - } - - /// Inspection never creates a missing directory or changes an existing directory's permissions. - static func validateDirectory(_ directory: URL, containedIn root: URL) throws { - let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) - guard values.isDirectory == true, values.isSymbolicLink != true else { - throw CodexManagedWorktreeError.invalid( - "managed worktree paths must be real directories, not symbolic links" - ) - } - let resolvedDirectory = directory.standardizedFileURL.resolvingSymlinksInPath() - let resolvedRoot = root.standardizedFileURL.resolvingSymlinksInPath() - guard - resolvedDirectory == resolvedRoot - || resolvedDirectory.path.hasPrefix(resolvedRoot.path + "/") - else { - throw CodexManagedWorktreeError.invalid( - "managed worktree path escaped the canonical managed root" - ) - } - } - - /// A lexical precheck only. Existing directory containment requires canonical path validation. - static func isDescendant(_ directory: URL, of root: URL) throws -> Bool { - return directory.standardizedFileURL.path.hasPrefix(root.standardizedFileURL.path + "/") - } - - static func samePath(_ lhs: URL, _ rhs: URL) throws -> Bool { - return lhs.standardizedFileURL.path == rhs.standardizedFileURL.path - } - - static func sameDirectory(_ lhs: URL, _ rhs: URL) throws -> Bool { - return lhs.path == rhs.path - } - - static func canonicalDirectory(_ path: String, relativeTo base: URL) throws -> URL { - let url = - path.hasPrefix("/") - ? URL(fileURLWithPath: path, isDirectory: true) - : base.appendingPathComponent(path, isDirectory: true) - return url.standardizedFileURL.resolvingSymlinksInPath() - } - - static func isAbsent(_ url: URL) throws -> Bool { - var info = stat() - return lstat(url.path, &info) != 0 && errno == ENOENT - } - - static func provisionPathIsAvailable(_ url: URL) throws -> Bool { - return !FileManager.default.fileExists(atPath: url.path) - } - -} diff --git a/Sources/CodexAdapter/CodexWorktreeLease.swift b/Sources/CodexAdapter/CodexWorktreeLease.swift index 5d0ae94..616cdce 100644 --- a/Sources/CodexAdapter/CodexWorktreeLease.swift +++ b/Sources/CodexAdapter/CodexWorktreeLease.swift @@ -30,12 +30,31 @@ struct CodexWorktreeLease: Codable, Equatable, Sendable, Identifiable { var releaseReason: String? var revision: Int var managedWorktreeID: String? = nil + var hostWorktreeID: UUID? = nil + var creationOperationID: UUID? = nil var json: JSONValue { (try? JSONValue.encoded(self)) ?? .object([:]) } } +extension CodexWorktreeLease { + init( + workspaceID: String, workspacePath: String, mode: CodexWorktreeLeaseMode, agentID: String, + threadID: String?, runID: String?, parentLeaseID: String?, branch: String?, ttlSeconds: Int, + now: Date, association: CodexHostWorktree? + ) { + self.init( + id: UUID().uuidString, workspaceID: workspaceID, workspacePath: workspacePath, + mode: mode, agentID: agentID, threadID: threadID, runID: runID, + parentLeaseID: parentLeaseID, branch: branch, state: .active, createdAt: now, + heartbeatAt: now, expiresAt: now.addingTimeInterval(TimeInterval(ttlSeconds)), + releasedAt: nil, releaseReason: nil, revision: 1, managedWorktreeID: association?.id, + hostWorktreeID: association?.creation?.worktreeID, + creationOperationID: association?.creationOperationID) + } +} + enum CodexWorktreeLeaseError: Error, LocalizedError, Sendable { case unavailable case invalid(String) @@ -76,6 +95,7 @@ enum CodexWorktreeLeaseManager { mode: CodexWorktreeLeaseMode, ttlSeconds: Int, liveRuntimeStatus: JSONValue, + scope: CodexProjectScope? = nil, now: Date = Date() ) throws -> CodexWorktreeLease { guard let database else { throw CodexWorktreeLeaseError.unavailable } @@ -101,31 +121,6 @@ enum CodexWorktreeLeaseManager { ) } } - var managedWorktreeID: String? - if let parentLeaseID { - guard let parent = try database.codexWorktreeLease(id: parentLeaseID), - parent.state == .active, parent.expiresAt > now - else { - throw CodexWorktreeLeaseError.invalid("parent_lease_id must identify an active lease") - } - guard parent.workspaceID != workspaceID || parent.mode == .exclusive else { - throw CodexWorktreeLeaseError.invalid( - "an isolated child must use a separately registered worktree workspace" - ) - } - if database.sharesWorktreeLeases, parent.workspaceID != workspaceID { - let lineage = try database.codexWorktreeLeases(workspaceID: workspaceID, limit: 5_000) - .first { - $0.parentLeaseID == parentLeaseID && $0.managedWorktreeID != nil - && $0.workspacePath == workspaceURL.standardizedFileURL.path - } - guard let lineage else { - throw CodexWorktreeLeaseError.invalid( - "The parent lease must belong to this workspace's registered managed-worktree lineage.") - } - managedWorktreeID = lineage.managedWorktreeID - } - } if mode == .isolatedWorktree, parentLeaseID == nil { throw CodexWorktreeLeaseError.invalid( "isolated_worktree requires parent_lease_id to preserve task lineage" @@ -148,7 +143,7 @@ enum CodexWorktreeLeaseManager { branch: safeBranch, ttlSeconds: ttlSeconds, now: now, - managedWorktreeID: managedWorktreeID + scope: scope ) } diff --git a/Sources/CodexAdapter/MCPInheritedSocketTransport.swift b/Sources/CodexAdapter/MCPInheritedSocketTransport.swift index 62f5eca..dec3b24 100644 --- a/Sources/CodexAdapter/MCPInheritedSocketTransport.swift +++ b/Sources/CodexAdapter/MCPInheritedSocketTransport.swift @@ -12,6 +12,9 @@ actor MCPInheritedSocketTransport: Transport { private let maximumMessageBytes: Int private let maximumQueuedMessages: Int private let writeTimeout: Duration + private let observesProjectContract: Bool + private var initializeID: JSONValue? + private(set) var observedProjectContract: String? private let stream: AsyncThrowingStream private let continuation: AsyncThrowingStream.Continuation private var connected = false @@ -23,7 +26,8 @@ actor MCPInheritedSocketTransport: Transport { init( takingOwnershipOf handle: FileHandle, maximumMessageBytes: Int = 1_048_576, - maximumQueuedMessages: Int = 32, writeTimeout: Duration = .seconds(30) + maximumQueuedMessages: Int = 32, writeTimeout: Duration = .seconds(30), + observesProjectContract: Bool = false ) throws { guard (1...16_777_216).contains(maximumMessageBytes), (1...256).contains(maximumQueuedMessages), writeTimeout > .zero @@ -58,6 +62,7 @@ actor MCPInheritedSocketTransport: Transport { self.maximumMessageBytes = maximumMessageBytes self.maximumQueuedMessages = maximumQueuedMessages self.writeTimeout = writeTimeout + self.observesProjectContract = observesProjectContract (stream, continuation) = AsyncThrowingStream.makeStream( bufferingPolicy: .bufferingOldest(maximumQueuedMessages)) } @@ -106,6 +111,12 @@ actor MCPInheritedSocketTransport: Transport { finish(throwing: MCPError.transportError(POSIXError(.ENOBUFS))) throw MCPError.connectionClosed } + if observesProjectContract, + let request = try? JSONDecoder().decode(JSONValue.self, from: message).objectValue, + request["method"] == .string("initialize") + { + initializeID = request["id"] + } queuedWrites += 1 defer { queuedWrites -= 1 } let predecessor = writer @@ -188,6 +199,16 @@ actor MCPInheritedSocketTransport: Transport { finish(throwing: MCPError.parseError("Invalid inherited MCP frame.")) return false } + if let initializeID, + let reply = try? JSONDecoder().decode(JSONValue.self, from: message).objectValue, + reply["id"] == initializeID + { + observedProjectContract = + reply["result"]?.objectValue?["capabilities"]?.objectValue?[ + "experimental" + ]?.objectValue?[CodexProjectContract.capabilityKey]?.stringValue + self.initializeID = nil + } switch continuation.yield(message) { case .enqueued: break case .dropped, .terminated: diff --git a/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift b/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift index ed61774..b68abb6 100644 --- a/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift @@ -51,7 +51,7 @@ struct CodexAppServerProviderTests { } let goal = try #require(tools.first { $0.name == "codex.app.goal.clear" }) #expect( - goal._meta?["io.github.computer-mcp/risk"] == .string("workspace-write")) + goal._meta?["io.github.computer-mcp/risk"] == .string("project-write")) } @Test diff --git a/Tests/CodexAdapterTests/CodexDatabaseSchemaTests.swift b/Tests/CodexAdapterTests/CodexDatabaseSchemaTests.swift index 22e49f4..dae8907 100644 --- a/Tests/CodexAdapterTests/CodexDatabaseSchemaTests.swift +++ b/Tests/CodexAdapterTests/CodexDatabaseSchemaTests.swift @@ -5,13 +5,13 @@ import Testing @testable import CodexAdapter struct CodexDatabaseSchemaTests { - @Test func initialSchemaMatchesCapturedFinalSchema() throws { + @Test func originalMigrationMatchesCapturedSchema() throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: directory) } let path = directory.appendingPathComponent("codex.sqlite").path - _ = try CodexDatabase(path: path) let queue = try DatabaseQueue(path: path) + try CodexDatabase.migrator.migrate(queue, upTo: "codex-initial") let fixture = try #require( Bundle.module.url( forResource: "codex-schema", withExtension: "json", subdirectory: "Fixtures")) @@ -20,7 +20,14 @@ struct CodexDatabaseSchemaTests { #expect( try queue.read { try CodexDatabase.migrator.appliedIdentifiers($0) } == ["codex-initial"]) _ = try CodexDatabase(path: path) - #expect(try schema(queue) == expected) + let upgraded = try schema(queue) + #expect( + upgraded.filter { !["codexHostWorktrees", "codexWorktreeOperations"].contains($0.table) } + == expected) + #expect(upgraded.contains { $0.name == "codexHostWorktrees" }) + #expect(upgraded.contains { $0.name == "codexWorktreeOperations" }) + _ = try CodexDatabase(path: path) + #expect(try schema(queue) == upgraded) } @Test(arguments: [false, true]) @@ -70,6 +77,83 @@ struct CodexDatabaseSchemaTests { _ = try CodexDatabase(path: path, worktreeLeasePath: leases) } + @Test(arguments: [false, true]) + func historicalRowsAreUnmanagedAcrossIndependentStoreMigrations(splitStore: Bool) throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let path = directory.appendingPathComponent("codex.sqlite").path + let leases = directory.appendingPathComponent("leases.sqlite").path + let checkout = directory.appendingPathComponent("historical-checkout") + let original = Data("historical checkout data".utf8) + try original.write(to: checkout) + let primary = try DatabaseQueue(path: path) + try CodexDatabase.migrator.migrate(primary, upTo: "codex-initial") + let states = [ + "planned", "provisioning", "active", "removal_planned", "removing", "removed", "failed", + ] + try primary.write { database in + for state in states { + let payload: [String: JSONValue] = [ + "id": .string(state), "state": .string(state), "path": .string(checkout.path), + "principal_id": .string("principal"), "profile_id": .string("profile"), + "source_workspace_id": .string("source"), + "workspace_id": .string("codex-worktree-\(state)"), + "retained_extension": .integer(42), + ] + try database.execute( + sql: "INSERT INTO codexManagedWorktrees VALUES (?, ?, ?, ?, ?, ?)", + arguments: [ + state, "source", "codex-worktree-\(state)", state, Date(), + String(decoding: try JSONEncoder().encode(payload), as: UTF8.self), + ]) + } + } + if splitStore { + try primary.write { database in + try database.execute( + sql: """ + CREATE TRIGGER reject_history_update BEFORE UPDATE ON codexManagedWorktrees + BEGIN SELECT RAISE(ABORT, 'fixture interrupted migration'); END + """) + } + #expect(throws: DatabaseError.self) { + try CodexDatabase(path: path, worktreeLeasePath: leases) + } + #expect( + try schema(DatabaseQueue(path: leases)).contains { $0.name == "codexWorktreeOperations" }) + #expect( + try primary.read { + try String.fetchAll($0, sql: "SELECT state FROM codexManagedWorktrees").sorted() + } + == states.sorted()) + try primary.write { try $0.execute(sql: "DROP TRIGGER reject_history_update") } + } + let database = try CodexDatabase(path: path, worktreeLeasePath: splitStore ? leases : nil) + let owner = CodexRuntimeOwner( + workspaceID: "source", profileID: "profile", caller: "local-mcp", transport: nil, + socketConnectionID: nil, tunnelInstanceID: nil, tunnelProfileID: nil, principalID: "principal" + ) + let history = try database.unmanagedWorktrees(owner: owner, limit: 20) + #expect(history.count == states.count) + for item in history { + let row = try #require(item.objectValue) + #expect(row["state"] == .string("unmanaged")) + #expect(row["previous_state"] == row["id"]) + #expect(row["path"] == .string(checkout.path)) + #expect(row["retained_extension"] == .integer(42)) + } + let sqlStates = try primary.read { + try String.fetchAll($0, sql: "SELECT DISTINCT state FROM codexManagedWorktrees") + } + #expect(sqlStates == ["unmanaged"]) + let scope = try #require(CodexProjectScope(owner)) + #expect(try database.hostWorktrees(in: scope, limit: 20).isEmpty) + #expect(try Data(contentsOf: checkout) == original) + let reopened = try CodexDatabase(path: path, worktreeLeasePath: splitStore ? leases : nil) + #expect(try reopened.unmanagedWorktrees(owner: owner, limit: 20) == history) + } + private struct SchemaObject: Codable, Equatable { let type: String let name: String diff --git a/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift b/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift index 968a6c9..e23a1ab 100644 --- a/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift +++ b/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift @@ -6,8 +6,8 @@ import Testing @Suite(.timeLimit(.minutes(1))) struct CodexHostMCPClientTests { - @Test(arguments: ["read-only", "destructive"]) - func executionUsesFreshHostAuthorizationWithoutImplicitTickets(risk: String) async throws { + @Test(arguments: ["read-only", "project-write", "destructive"]) + func executionUsesFreshHostAuthorization(risk: String) async throws { let fixture = try HostClientFixture() await fixture.state.setRisk(risk) try await fixture.start() @@ -15,13 +15,13 @@ struct CodexHostMCPClientTests { let arguments: JSONValue = .object(["path": .string("fixture.txt")]) let decision = try await fixture.client.risk( named: "file.test", arguments: arguments, requestID: "call", workspaceID: "fixture") - #expect(decision.rawValue == risk) + #expect(decision.hostValue == risk) let result = try await fixture.client.execute( name: "file.test", arguments: arguments, requestID: "call", workspaceID: "fixture") #expect(result.objectValue?["isError"] == .bool(false)) let calls = await fixture.state.calls #expect(calls.map(\.0) == ["policy.probe", "policy.probe", "file.test"]) - #expect(calls.allSatisfy { $0.1["workspace_id"] == .string("fixture") }) + #expect(calls.allSatisfy { $0.1["project_id"] == .string("fixture") }) await fixture.close() } catch { await fixture.close() @@ -61,7 +61,7 @@ struct CodexHostMCPClientTests { let arguments: JSONValue = change == "arguments" ? .object(["extra": .bool(true)]) - : change == "nested-workspace" ? .object(["workspace_id": .string("other")]) : .object([:]) + : change == "nested-workspace" ? .object(["project_id": .string("other")]) : .object([:]) await #expect(throws: (any Error).self) { try await fixture.client.execute( name: change == "name" ? "file.other" : "file.test", arguments: arguments, @@ -156,39 +156,34 @@ struct CodexHostMCPClientTests { } } - @Test(arguments: ["same", "different", "unbound"]) - func managedWorkspaceOwnershipUsesSubjectNotChannel(_ binding: String) async throws { - let fixture = try HostClientFixture(principalID: "subject-a") + @Test(arguments: [nil, "projects-v0", "projects-v1"] as [String?]) + func lifecycleRequiresObservedHostContract(_ marker: String?) async throws { + let fixture = try HostClientFixture(peerContract: marker, launchContract: "projects-v1") try await fixture.start() - var worktree = CodexManagedWorktree( - id: "worktree", sourceWorkspaceID: "fixture", workspaceID: "child", - sourceRepositoryRoot: "/tmp/source", gitCommonDirectory: "/tmp/source/.git", - path: "/tmp/child", branch: "codex/fixture", startPoint: "HEAD", headOID: "head", - agentID: "agent", threadID: nil, runID: nil, parentLeaseID: "lease", profileID: "fixture", - caller: "local-mcp", ttlSeconds: 60, leaseID: nil, state: .active, createdAt: Date(), - updatedAt: Date(), planExpiresAt: nil, removedAt: nil, lastError: nil, revision: 1) - worktree.principalID = - binding == "unbound" ? nil : (binding == "same" ? "subject-a" : "subject-b") do { - if binding == "same" { - try await fixture.client.authorizeRemoval(worktree) - let calls = await fixture.state.calls - #expect(calls.count == 1) - #expect(calls.first?.1["worktree"]?.objectValue?["principal_id"] == .string("subject-a")) - } else { - await #expect(throws: CodexToolError.self) { - try await fixture.client.authorizeRemoval(worktree) - } - #expect(await fixture.state.calls.isEmpty) - } - let decoded = try JSONDecoder().decode( - CodexManagedWorktree.self, from: JSONEncoder().encode(worktree)) - #expect(decoded.principalID == worktree.principalID) - await fixture.close() + let response = try await fixture.client.add( + CodexWorktreeSelection(["name": .string("change"), "base": .null]), + ids: .init(invocationID: UUID(), operationID: UUID())) + #expect(marker == "projects-v1") + #expect(response.isError == true) + #expect(response.refusal?.objectValue?["extra"] == .integer(9)) + #expect(response.raw.objectValue?["content"]?.arrayValue?.count == 1) + } catch let error as CodexProjectContract.Unsupported { + #expect(marker != "projects-v1") + #expect(error.observed == marker) } catch { await fixture.close() throw error } + let calls = await fixture.state.calls + if marker == "projects-v1" { + #expect(calls.map(\.0) == ["host.projects.worktree_add"]) + #expect(calls.first?.1["base"] == .null) + #expect(calls.first?.1["branch"] == nil) + } else { + #expect(calls.isEmpty) + } + await fixture.close() } @Test @@ -218,7 +213,9 @@ private final class HostClientFixture: Sendable { let transport: MCPInheritedSocketTransport let client: CodexHostMCPClient let server = MCP.Server(name: "host-fixture", version: "1", capabilities: .init(tools: .init())) - init(principalID: String? = nil) throws { + let peerContract: String? + init(peerContract: String? = nil, launchContract: String? = nil) throws { + self.peerContract = peerContract let pair = try MCPInheritedSocketTransport.makePair() transport = try MCPInheritedSocketTransport(takingOwnershipOf: pair.0) client = try CodexHostMCPClient( @@ -226,13 +223,18 @@ private final class HostClientFixture: Sendable { owner: .init( workspaceID: "fixture", profileID: "fixture", caller: "secure-tunnel", transport: "gateway_socket", socketConnectionID: "fixture-socket", tunnelInstanceID: nil, - tunnelProfileID: nil, principalID: principalID)) + tunnelProfileID: nil, principalID: "subject-a"), launchContract: launchContract) } func start() async throws { await server.withMethodHandler(MCP.CallTool.self) { [state] params in await state.respond(params) } - try await server.start(transport: transport) + if let peerContract { + try await server.start( + transport: CodexProjectHandshakeTransport(transport, contract: peerContract)) + } else { + try await server.start(transport: transport) + } } func close() async { await client.shutdown() @@ -254,12 +256,14 @@ private actor HostClientState { if params.name == "policy.probe" { result = .object([ "decision": .string("allowed"), "capability_id": arguments["capability_id"]!, - "workspace_id": .string("fixture"), "risk": .string(risk), "effective_risk": .string(risk), + "project_id": .string("fixture"), "risk": .string(risk), "effective_risk": .string(risk), ]) - } else if params.name == "host.workspaces.authorize_removal" { - result = .object(["authorized": .bool(true)]) - } else if params.name == "operations.prepare" { - result = .object(["ticket_id": .string("host-ticket")]) + } else if params.name == "host.projects.worktree_add" { + return .init( + content: [.text(text: "fixture refusal", annotations: nil, _meta: nil)], + structuredContent: .object([ + "error": .object(["code": .string("host.service_denied"), "extra": .int(9)]) + ]), isError: true) } else if failExecution { return .init( content: [], diff --git a/Tests/CodexAdapterTests/CodexLaunchContextTests.swift b/Tests/CodexAdapterTests/CodexLaunchContextTests.swift index d01bb9f..c55e3b9 100644 --- a/Tests/CodexAdapterTests/CodexLaunchContextTests.swift +++ b/Tests/CodexAdapterTests/CodexLaunchContextTests.swift @@ -101,6 +101,24 @@ struct CodexLaunchContextTests { } } + @Test(arguments: [nil, "projects-v0"] as [String?]) + func launchRejectsUnsupportedContracts(marker: String?) throws { + var host = try JSONDecoder().decode([String: JSONValue].self, from: Data(validHost.utf8)) + host["hostServiceContract"] = marker.map(JSONValue.string) + if marker == nil { host["workspace"] = host.removeValue(forKey: "project") } + do { + _ = try CodexLaunchContext( + environment: [ + "COMPUTER_MCP_HOST_CONTEXT": String( + decoding: try JSONEncoder().encode(host), as: UTF8.self) + ], currentDirectory: URL(fileURLWithPath: "/tmp")) + Issue.record("Expected the obsolete host launch context to be refused.") + } catch let error as CodexProjectContract.Unsupported { + #expect(error.observed == marker) + #expect(error.fields.objectValue?["required_contract"] == .string("projects-v1")) + } + } + @Test func existingConfigurationDefaultsAndValidationArePreserved() throws { let config = try JSONDecoder().decode(CodexConfig.self, from: Data("{}".utf8)) #expect(config == CodexConfig()) @@ -162,6 +180,6 @@ struct CodexLaunchContextTests { } private var validHost: String { - #"{"formatVersion":1,"runtimeID":"B66E26EE-53AF-4455-A25D-E2BDD219798C","caller":"local-mcp","profileID":"observe","workspace":{"id":"fixture","rootPath":"/tmp/bound-workspace"},"readOnly":true}"# + #"{"formatVersion":1,"runtimeID":"B66E26EE-53AF-4455-A25D-E2BDD219798C","caller":"local-mcp","profileID":"observe","hostServiceContract":"projects-v1","project":{"id":"fixture","rootPath":"/tmp/bound-workspace"},"readOnly":true}"# } } diff --git a/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift b/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift index af80779..9362440 100644 --- a/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift +++ b/Tests/CodexAdapterTests/CodexManagedWorktreeTests.swift @@ -1,775 +1,536 @@ import Foundation +import GRDB import MCP import Testing @testable import CodexAdapter -@Suite(.serialized) -final class CodexManagedWorktreeTests { - @Test(.timeLimit(.minutes(1))) - func mcpWorktreeLifecyclePreservesHostDenialAndWorkspaceScope() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString, isDirectory: true) - let repository = directory.appendingPathComponent("repository", isDirectory: true) - let managedRoot = directory.appendingPathComponent("managed", isDirectory: true) - try FileManager.default.createDirectory(at: repository, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try runGit(["init", "-q"], in: repository) - try runGit(["config", "user.name", "Computer MCP Test"], in: repository) - try runGit(["config", "user.email", "computer-mcp@example.invalid"], in: repository) - try Data("baseline\n".utf8).write(to: repository.appendingPathComponent("README.md")) - try runGit(["add", "README.md"], in: repository) - try runGit(["commit", "-q", "-m", "test: baseline"], in: repository) - let host = RecordingManagedWorkspaceHost() - func provider( - workspaceID: String, path: URL, hostConnected: Bool = true, - principalID: String = "fixture-principal", profileID: String = "local-admin" - ) throws -> CodexAppServerProvider { - let launch: [String: Any] = [ - "formatVersion": 1, "runtimeID": UUID().uuidString, "caller": "local-mcp", - "principalID": principalID, "profileID": profileID, - "workspace": ["id": workspaceID, "rootPath": path.path], +@Suite(.timeLimit(.minutes(1))) +struct CodexManagedWorktreeTests { + @Test(arguments: [nil, .null, .string("reviewed-base")] as [JSONValue?]) + func mcpPreservesReviewedSelectionAndCommitsHostIDsBeforeInspection(base: JSONValue?) async throws + { + let fixture = try WorktreeFixture() + let provider = fixture.provider() + try await withMCPClient(provider) { client in + var planArguments: [String: JSONValue] = [ + "name": .string("example"), "agent_id": .string("child-agent"), + "parent_lease_id": .string(fixture.parent.id), ] - let context = try CodexLaunchContext( - environment: [ - "COMPUTER_MCP_HOST_CONTEXT": String( - decoding: JSONSerialization.data(withJSONObject: launch), as: UTF8.self) - ], - currentDirectory: path) - let scoped = try #require( - try context.appServerProvider( - configuration: .init(enabled: true, executable: "/missing/codex"), - stateDirectory: directory.appendingPathComponent("state"))) - return CodexAppServerProvider( - appServer: FakeAppServerRuntime(), - owner: context.owner, - database: scoped.database, workspaceURL: path, recentThreadReader: nil, - localControlAllowed: true, - workspaceHost: hostConnected ? host : nil, managedWorktreeRoot: managedRoot) - } - let source = try provider(workspaceID: "source-workspace", path: repository) - let database = try #require(source.database) - try await withMCPClient(provider: source) { - client in - let parent = try await invoke( - client, "codex.worktree.leases.acquire", - [ - "agent_id": .string("parent"), "mode": .string("exclusive"), - ]) - let plan = try await invoke( - client, "codex.worktree.provision.plan", - [ - "agent_id": .string("child"), - "parent_lease_id": try #require(parent.objectValue?["id"]), - "branch": .string("codex/mcp-worktree"), - ]) - let planID = try #require(plan.objectValue?["id"]) - try await withMCPClient( - provider: provider(workspaceID: "source-workspace", path: repository, hostConnected: false) - ) { unconnected in - let unavailable = try await unconnected.callTool( - name: "codex.worktree.provision.perform", - arguments: [ - "plan_id": planID, "expected_revision": try #require(plan.objectValue?["revision"]), - "confirm_provision": .bool(true), - ]) - #expect(unavailable.isError == true) - let plannedPath = try #require(plan.objectValue?["path"]?.stringValue) - #expect(!FileManager.default.fileExists(atPath: plannedPath)) - #expect( - try database.codexManagedWorktree(id: try #require(planID.stringValue))?.state == .planned - ) - } - let active = try await invoke( - client, "codex.worktree.provision.perform", - [ - "plan_id": planID, "expected_revision": try #require(plan.objectValue?["revision"]), - "confirm_provision": .bool(true), - ]) - let worktreeID = try #require(active.objectValue?["id"]?.stringValue) - let record = try #require(try database.codexManagedWorktree(id: worktreeID)) - #expect(record.state == .active) - #expect(await host.record(id: record.workspaceID)?.id == worktreeID) - let listed = try await invoke(client, "codex.worktree.managed.list") - #expect(listed.objectValue?["worktrees"]?.arrayValue?.count == 1) - let read = try await invoke( - client, "codex.worktree.managed.read", - [ - "managed_worktree_id": .string(worktreeID) - ]) - #expect(read == active) - let sourceDiagnostic = try await invoke(client, "codex.diagnostics.snapshot") + let branch: JSONValue? = base?.stringValue == nil ? base : .string("explicit-branch") + planArguments["base"] = base + planArguments["branch"] = branch + let plan = try result(await call(client, "codex.worktree.provision.plan", planArguments)) + let performArguments = try #require(plan["perform_arguments"]?.objectValue) + #expect(performArguments["base"] == base) + #expect(performArguments["branch"] == branch) + let ids = newIDs() + var altered = performArguments + altered["branch"] = .string("worktree/example") + let substituted = try await call( + client, "codex.worktree.provision.perform", altered, ids: ids) + #expect(substituted.isError == true) + let missing = try await call(client, "codex.worktree.provision.perform", performArguments) + #expect(missing.isError == true) + var spoofed = performArguments + spoofed["operation_id"] = .string(ids.operationID.uuidString) + let spoof = try await call(client, "codex.worktree.provision.perform", spoofed, ids: ids) + #expect(spoof.isError == true) + #expect(await fixture.host.callbacks.isEmpty) + let digest = try CodexHostInvocation.digest(performArguments) + await fixture.host.capture(digest, action: .provision) + let completed = try result( + await call(client, "codex.worktree.provision.perform", performArguments, ids: ids)) + #expect(completed["state"] == .string("active")) + #expect(completed["host_state"] == .string("completed")) + #expect(completed["requested"]?.objectValue?["base"] == base) #expect( - sourceDiagnostic.objectValue?["summary"]?.objectValue?["active_managed_worktree_count"] - == .int(1)) - let leaseID = try #require(record.leaseID) - let lease = try #require(try database.codexWorktreeLease(id: leaseID)) - let releaseArguments: [String: MCP.Value] = [ - "lease_id": .string(leaseID), "expected_revision": .int(lease.revision), - "reason": .string("Child work accepted."), - ] - let wrongScope = try await client.callTool( - name: "codex.worktree.leases.release", arguments: releaseArguments) - #expect(wrongScope.isError == true) - #expect(try database.codexWorktreeLease(id: leaseID)?.state == .active) - let busy = try await client.callTool( - name: "codex.worktree.remove.plan", - arguments: [ - "managed_worktree_id": .string(worktreeID) - ]) - #expect(busy.isError == true) - for (workspace, principal, profile) in [ - ("unrelated-workspace", "fixture-principal", "local-admin"), - (record.workspaceID, "foreign-principal", "local-admin"), - (record.workspaceID, "fixture-principal", "foreign-profile"), - ] { - try await withMCPClient( - provider: provider( - workspaceID: workspace, path: URL(fileURLWithPath: record.path), - principalID: principal, profileID: profile) - ) { unauthorized in - for name in [ - "codex.worktree.leases.read", "codex.worktree.leases.heartbeat", - "codex.worktree.leases.release", - ] { - let arguments: [String: MCP.Value] - if name.hasSuffix(".read") { - arguments = ["lease_id": .string(leaseID)] - } else if name.hasSuffix(".heartbeat") { - arguments = ["lease_id": .string(leaseID), "expected_revision": .int(lease.revision)] - } else { - arguments = releaseArguments - } - #expect( - try await unauthorized.callTool(name: name, arguments: arguments).isError == true) - } - let hidden = try await invoke(unauthorized, "codex.worktree.leases.list") - #expect(hidden.objectValue?["leases"]?.arrayValue?.isEmpty == true) - let invalidLineage = try await unauthorized.callTool( - name: "codex.worktree.leases.acquire", - arguments: [ - "agent_id": .string("unrelated"), "mode": .string("isolated_worktree"), - "parent_lease_id": try #require(parent.objectValue?["id"]), - ]) - #expect(invalidLineage.isError == true) - } - } - #expect(try database.codexWorktreeLease(id: leaseID)?.state == .active) - try await withMCPClient( - provider: provider(workspaceID: record.workspaceID, path: URL(fileURLWithPath: record.path)) - ) { child in - let hidden = try await child.callTool( - name: "codex.worktree.managed.read", - arguments: [ - "managed_worktree_id": .string(worktreeID) - ]) - #expect(hidden.isError == true) - let childDiagnostic = try await invoke(child, "codex.diagnostics.snapshot") - #expect( - childDiagnostic.objectValue?["active_worktree_leases"]?.arrayValue?.first?.objectValue?[ - "managedWorktreeID"] - == .string(worktreeID)) - #expect( - childDiagnostic.objectValue?["summary"]?.objectValue?["active_worktree_lease_count"] - == .int(1)) - let childLease = try await invoke( - child, "codex.worktree.leases.read", ["lease_id": .string(leaseID)]) - #expect(childLease.objectValue?["managedWorktreeID"] == .string(worktreeID)) - let renewed = try await invoke( - child, "codex.worktree.leases.heartbeat", - ["lease_id": .string(leaseID), "expected_revision": .int(lease.revision)]) - var currentRelease = releaseArguments - currentRelease["expected_revision"] = try #require(renewed.objectValue?["revision"]) - _ = try await invoke(child, "codex.worktree.leases.release", currentRelease) - } - #expect(try database.codexWorktreeLease(id: leaseID)?.state == .released) - let restartedChild = try provider( - workspaceID: record.workspaceID, path: URL(fileURLWithPath: record.path)) - #expect(restartedChild.database?.fileURL != database.fileURL) - #expect(try restartedChild.database?.codexWorktreeLease(id: leaseID)?.state == .released) - let dirty = URL(fileURLWithPath: record.path).appendingPathComponent("unaccepted.txt") - try Data("keep until reviewed\n".utf8).write(to: dirty) - let dirtyRemoval = try await client.callTool( - name: "codex.worktree.remove.plan", - arguments: [ - "managed_worktree_id": .string(worktreeID) - ]) - #expect(dirtyRemoval.isError == true) - #expect(try Data(contentsOf: dirty) == Data("keep until reviewed\n".utf8)) - try FileManager.default.removeItem(at: dirty) - let removal = try await invoke( - client, "codex.worktree.remove.plan", - [ - "managed_worktree_id": .string(worktreeID) - ]) - let removeArguments: [String: MCP.Value] = [ - "managed_worktree_id": .string(worktreeID), - "expected_revision": try #require(removal.objectValue?["revision"]), - "confirm_remove": .bool(true), - ] - await host.setRemovalAllowed(false) - let denied = try await client.callTool( - name: "codex.worktree.remove.perform", arguments: removeArguments) - #expect(denied.isError == true) - #expect(try database.codexManagedWorktree(id: worktreeID)?.state == .removalPlanned) + completed["resolved"]?.objectValue?["branch"] + == (branch?.stringValue.map(JSONValue.string) ?? .string("worktree/example"))) #expect( - try database.codexManagedWorktree(id: worktreeID)?.json - == JSONDecoder().decode( - JSONValue.self, from: JSONEncoder().encode(removal))) - #expect(FileManager.default.fileExists(atPath: record.path)) - #expect(await host.record(id: record.workspaceID)?.id == worktreeID) - await host.setRemovalAllowed(true) - let removed = try await invoke(client, "codex.worktree.remove.perform", removeArguments) - #expect(removed.objectValue?["state"] == .string("removed")) - #expect(!FileManager.default.fileExists(atPath: record.path)) - #expect(await host.record(id: record.workspaceID) == nil) - let removedDiagnostic = try await invoke(client, "codex.diagnostics.snapshot") + completed["resolved"]?.objectValue?["base"] + == (base?.stringValue.map(JSONValue.string) ?? .string("captured-main"))) + #expect(completed["lease"]?.objectValue?["state"] == .string("acquired")) + #expect(await fixture.host.callbacks == ["inspect-invocation", "add"]) + #expect(await fixture.host.selection?.arguments["base"] == base) + let id = try #require(completed["id"]?.stringValue) + let child = try #require(try fixture.child.hostWorktree(id: id, in: fixture.childScope)?.0) + #expect(child.projection(in: fixture.childScope)["run_id"] == nil) #expect( - removedDiagnostic.objectValue?["summary"]?.objectValue?["active_managed_worktree_count"] - == .int(0)) - let reopened = try #require( - try provider(workspaceID: "source-workspace", path: repository).database) - #expect(try reopened.codexManagedWorktree(id: worktreeID)?.state == .removed) - #expect(try reopened.codexWorktreeLease(id: leaseID)?.state == .released) + try fixture.child.hostWorktree( + id: id, in: #require(CodexProjectScope(fixture.owner(project: "sibling")))) == nil) #expect( - try gitResult( - ["show-ref", "--verify", "--quiet", "refs/heads/codex/mcp-worktree"], in: repository - ).exitCode == 0) + try fixture.child.hostWorktree( + id: id, + in: #require(CodexProjectScope(fixture.owner(project: "child", principal: "other")))) + == nil) } } - @Test(arguments: [false, true]) - func testManagedWorktreeProvisionAndRemovalRequireOwnedCleanLifecycle(retryHostFailure: Bool) - async throws - { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString, isDirectory: true) - let repository = directory.appendingPathComponent("repository", isDirectory: true) - let managedRoot = directory.appendingPathComponent("managed", isDirectory: true) - try FileManager.default.createDirectory(at: repository, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try runGit(["init", "-q"], in: repository) - try runGit(["config", "user.name", "Computer MCP Test"], in: repository) - try runGit(["config", "user.email", "computer-mcp@example.invalid"], in: repository) - try Data("baseline\n".utf8).write(to: repository.appendingPathComponent("README.md")) - try runGit(["add", "README.md"], in: repository) - try runGit(["commit", "-q", "-m", "test: baseline"], in: repository) - - let database = try CodexDatabase(inMemory: ()) - let sourceWorkspaceID = "source-workspace" - let workspaceHost = RecordingManagedWorkspaceHost() - let parent = try CodexWorktreeLeaseManager.acquire( - database: database, - workspaceID: sourceWorkspaceID, - workspaceURL: repository, - agentID: "parent-agent", - threadID: "parent-thread", - runID: nil, - parentLeaseID: nil, - branch: nil, - mode: .exclusive, - ttlSeconds: 900, - liveRuntimeStatus: .object(["runtimes": .array([])]) - ) + @Test + func hostDigestMismatchPreservesPendingOperationWithoutCallingEffect() async throws { + let fixture = try WorktreeFixture() + let (id, request) = try fixture.plan() + let ids = newIDs() + await fixture.host.capture("mismatched-complete-digest", action: .provision) + let reply = try await fixture.manager.perform( + id: id, action: .provision, revision: 1, arguments: request, invocation: metadata(ids)) + #expect(reply.isError == true) + let projection = try result(reply) + #expect(projection["operation_id"] == .string(ids.operationID.uuidString)) + #expect(projection["uncertain_host_response"]?.objectValue?["structuredContent"] != nil) + #expect(await fixture.host.callbacks == ["inspect-invocation"]) + let stored = try #require(try fixture.source.hostWorktree(id: id, in: fixture.sourceScope)) + #expect(stored.0.state == .provisioning) + #expect(stored.1?.ids == ids) + } - let plan = try CodexManagedWorktreeManager.planProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - sourceWorkspaceURL: repository, - profileID: "local-admin", - caller: "local-mcp", - agentID: "child-agent", - threadID: "child-thread", - runID: nil, - parentLeaseID: parent.id, - branch: "codex/managed-child", - startPoint: "HEAD", - ttlSeconds: 900, - managedRoot: managedRoot - ) - #expect(plan.state == .planned) - #expect(!FileManager.default.fileExists(atPath: plan.path)) - - let active = try await CodexManagedWorktreeManager.performProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - planID: plan.id, - expectedRevision: plan.revision, - confirmProvision: true, - workspaceHost: workspaceHost, - managedRoot: managedRoot - ) - #expect(active.state == .active) - #expect(FileManager.default.fileExists(atPath: active.path)) - #expect(await workspaceHost.record(id: active.workspaceID)?.path == active.path) - let childLeaseID = try #require(active.leaseID) - var childLease = try #require(try database.codexWorktreeLease(id: childLeaseID)) - #expect(childLease.mode == .isolatedWorktree) - #expect(childLease.parentLeaseID == parent.id) - #expect(childLease.workspaceID == active.workspaceID) - - let dirtyFile = URL(fileURLWithPath: active.path).appendingPathComponent("dirty.txt") - try Data("not accepted\n".utf8).write(to: dirtyFile) + @Test + func conflictingLeaseLeavesCompletedAssociationAndAllowsLaterChildAcquisition() async throws { + let fixture = try WorktreeFixture() + let conflict = try fixture.acquire( + in: fixture.child, scope: fixture.childScope, agent: "other-agent") + let (id, request) = try fixture.plan() + let created = try await fixture.performProvision(id, request: request) + #expect(created["host_state"] == .string("completed")) + #expect(created["lease"]?.objectValue?["state"] == .string("conflict")) + #expect(try fixture.child.codexWorktreeLease(id: conflict.id) == conflict) #expect(throws: CodexManagedWorktreeError.self) { - try CodexManagedWorktreeManager.planRemoval( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - managedWorktreeID: active.id, - liveRuntimeStatus: .object(["runtimes": .array([])]), - managedRoot: managedRoot - ) - } - try FileManager.default.removeItem(at: dirtyFile) - childLease = try CodexWorktreeLeaseManager.release( - database: database, - workspaceID: childLease.workspaceID, - leaseID: childLease.id, - expectedRevision: childLease.revision, - reason: "Child evidence reconciled." - ) - #expect(childLease.state == .released) - - var removalPlan = try CodexManagedWorktreeManager.planRemoval( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - managedWorktreeID: active.id, - liveRuntimeStatus: .object(["runtimes": .array([])]), - managedRoot: managedRoot - ) - if retryHostFailure { - await workspaceHost.setUnregisterAllowed(false) - await #expect(throws: (any Error).self) { - try await CodexManagedWorktreeManager.performRemoval( - database: database, - sourceWorkspaceID: sourceWorkspaceID, managedWorktreeID: active.id, - expectedRevision: removalPlan.revision, confirmRemoval: true, - workspaceHost: workspaceHost, - liveRuntimeStatus: .object(["runtimes": .array([])]), managedRoot: managedRoot) - } - let unfinished = try #require(try database.codexManagedWorktree(id: active.id)) - #expect(unfinished.state == .removing) - #expect(!FileManager.default.fileExists(atPath: active.path)) - #expect(await workspaceHost.record(id: active.workspaceID) != nil) - // A replacement path must never be treated as the already-removed worktree. - try FileManager.default.createDirectory( - atPath: active.path, withIntermediateDirectories: false) - #expect(throws: (any Error).self) { - try CodexManagedWorktreeManager.planRemoval( - database: database, sourceWorkspaceID: sourceWorkspaceID, - managedWorktreeID: active.id, liveRuntimeStatus: .object(["runtimes": .array([])]), - managedRoot: managedRoot) - } - try FileManager.default.removeItem(atPath: active.path) - await workspaceHost.setUnregisterAllowed(true) - removalPlan = try CodexManagedWorktreeManager.planRemoval( - database: database, - sourceWorkspaceID: sourceWorkspaceID, managedWorktreeID: active.id, - liveRuntimeStatus: .object(["runtimes": .array([])]), managedRoot: managedRoot) + try fixture.childManager.planRemoval(id: id, force: false) } - let removed = try await CodexManagedWorktreeManager.performRemoval( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - managedWorktreeID: active.id, - expectedRevision: removalPlan.revision, - confirmRemoval: true, - workspaceHost: workspaceHost, - liveRuntimeStatus: .object(["runtimes": .array([])]), - managedRoot: managedRoot - ) - #expect(removed.state == .removed) - #expect(!FileManager.default.fileExists(atPath: active.path)) - #expect(await workspaceHost.record(id: active.workspaceID) == nil) - let preservedBranch = try gitResult( - ["show-ref", "--verify", "--quiet", "refs/heads/codex/managed-child"], - in: repository - ) - #expect(preservedBranch.exitCode == 0) + try fixture.release(conflict, in: fixture.child) + let original = try #require(try fixture.child.hostWorktree(id: id, in: fixture.childScope)) + let operation = try #require(original.1) + let envelope = try #require(operation.envelope) + let response = try #require(operation.response) + _ = try fixture.child.settleWorktreeOperation( + id: id, in: fixture.childScope, operationID: operation.ids.operationID, + envelope: envelope, response: response, now: Date()) + #expect(try fixture.child.hostWorktree(id: id, in: fixture.childScope)?.0.lease == .conflict) + let acquired = try fixture.acquire( + in: fixture.child, scope: fixture.childScope, agent: "child-agent", parent: fixture.parent.id) + #expect(acquired.hostWorktreeID == fixture.host.worktreeID) + #expect(acquired.creationOperationID == operation.ids.operationID) + #expect(acquired.managedWorktreeID == id) } @Test - func failedHostRollbackPreservesTheOwnedGitWorktreeAndBranch() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString, isDirectory: true) - let repository = directory.appendingPathComponent("repository", isDirectory: true) - let managedRoot = directory.appendingPathComponent("managed", isDirectory: true) - try FileManager.default.createDirectory(at: repository, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try runGit(["init", "-q"], in: repository) - try runGit(["config", "user.name", "Computer MCP Test"], in: repository) - try runGit(["config", "user.email", "computer-mcp@example.invalid"], in: repository) - try Data("baseline\n".utf8).write(to: repository.appendingPathComponent("README.md")) - try runGit(["add", "README.md"], in: repository) - try runGit(["commit", "-q", "-m", "test: baseline"], in: repository) - - let database = try CodexDatabase(inMemory: ()) - let sourceWorkspaceID = "source-workspace" - let workspaceHost = RecordingManagedWorkspaceHost() - let parent = try CodexWorktreeLeaseManager.acquire( - database: database, - workspaceID: sourceWorkspaceID, - workspaceURL: repository, - agentID: "parent-agent", - threadID: "parent-thread", - runID: nil, - parentLeaseID: nil, - branch: nil, - mode: .exclusive, - ttlSeconds: 900, - liveRuntimeStatus: .object(["runtimes": .array([])]) - ) + func concurrentSourceConnectionsCommitOnlyOneOperation() async throws { + let fixture = try WorktreeFixture() + let another = try CodexDatabase(path: fixture.sourcePath, worktreeLeasePath: fixture.sharedPath) + let (id, request) = try fixture.plan() + let digest = try CodexHostInvocation.digest(request) + await fixture.host.capture(digest, action: .provision) + + let successes = await withTaskGroup(of: Bool.self, returning: Int.self) { tasks in + for database in [fixture.source, another] { + tasks.addTask { + let manager = CodexHostWorktreeManager( + database: database, scope: fixture.sourceScope, services: fixture.host) + do { + _ = try await manager.perform( + id: id, action: .provision, revision: 1, arguments: request, + invocation: metadata(newIDs())) + return true + } catch CodexManagedWorktreeError.revisionConflict { + return false + } catch { + Issue.record("Unexpected admission failure: \(error)") + return false + } + } + } + var successes = 0 + for await admitted in tasks where admitted { successes += 1 } + return successes + } + #expect(successes == 1) + #expect(await fixture.host.callbacks == ["inspect-invocation", "add"]) + } - let plan = try CodexManagedWorktreeManager.planProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - sourceWorkspaceURL: repository, - profileID: "local-admin", - caller: "local-mcp", - agentID: "child-agent", - threadID: "child-thread", - runID: nil, - parentLeaseID: parent.id, - branch: "codex/managed-child", - startPoint: "HEAD", - ttlSeconds: 900, - managedRoot: managedRoot - ) - #expect(plan.state == .planned) - #expect(!FileManager.default.fileExists(atPath: plan.path)) - - await workspaceHost.setRegisterFailureAfterSaving(true) - await workspaceHost.setUnregisterAllowed(false) - await #expect(throws: (any Error).self) { - try await CodexManagedWorktreeManager.performProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, planID: plan.id, expectedRevision: plan.revision, - confirmProvision: true, workspaceHost: workspaceHost, managedRoot: managedRoot) + @Test(arguments: [CodexHostWorktreeState.failed, .recoveryRequired]) + func structuredHostErrorsRetainTheirEnvelopeAndNeverReplay(state: CodexHostWorktreeState) + async throws + { + let fixture = try WorktreeFixture() + let (id, request) = try fixture.plan() + await fixture.host.failCreation(as: state) + let outcome = try await fixture.performProvision(id, request: request) + #expect(outcome["state"] == .string(state == .failed ? "failed" : "provisioning")) + #expect(outcome["host_state"] == .string(state.rawValue)) + let raw = try #require(outcome["host_response"]?.objectValue) + #expect(raw["isError"] == .bool(true)) + #expect(raw["content"]?.arrayValue?.count == 1) + let envelope = raw["structuredContent"]?.objectValue?["result"]?.objectValue + #expect(envelope?["extension"] == .integer(9)) + #expect(envelope?["error"]?.objectValue?["code"] == .string("permission.required")) + let pending = try #require(try fixture.source.hostWorktree(id: id, in: fixture.sourceScope)) + #expect(pending.1?.response?.raw == .object(raw)) + let revision = pending.0.revision + await #expect(throws: CodexManagedWorktreeError.self) { + try await fixture.manager.perform( + id: id, action: .provision, revision: revision, arguments: request, + invocation: metadata(newIDs())) } - let failed = try #require(try database.codexManagedWorktree(id: plan.id)) - #expect(failed.state == .failed) - #expect(failed.lastError?.contains("Recovery incomplete") == true) - #expect(FileManager.default.fileExists(atPath: plan.path)) - #expect(await workspaceHost.record(id: plan.workspaceID) != nil) - let branch = try gitResult( - ["show-ref", "--verify", "refs/heads/" + plan.branch], in: repository) - #expect(branch.exitCode == 0) + #expect(await fixture.host.callbacks == ["inspect-invocation", "add"]) } @Test - func testRemovalNeverTargetsAnUnownedUserWorktree() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString, isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - let database = try CodexDatabase(inMemory: ()) - - #expect(throws: CodexManagedWorktreeError.self) { - try CodexManagedWorktreeManager.planRemoval( - database: database, - sourceWorkspaceID: "source-workspace", - managedWorktreeID: "user-owned-worktree", - liveRuntimeStatus: .object(["runtimes": .array([])]), - managedRoot: directory.appendingPathComponent("managed", isDirectory: true) - ) + func sqlSettlementFailureRecoversSameCreationWithoutRepeatingHostEffect() async throws { + let fixture = try WorktreeFixture() + let (id, request) = try fixture.plan() + let queue = try DatabaseQueue(path: fixture.sharedPath) + try await queue.write { database in + try database.execute( + sql: """ + CREATE TRIGGER reject_child_settlement BEFORE UPDATE ON codexHostWorktrees + WHEN NEW.childProjectID IS NOT NULL + BEGIN SELECT RAISE(ABORT, 'fixture settlement failure'); END + """) } - #expect(FileManager.default.fileExists(atPath: directory.path)) + let uncertain = try await fixture.performProvision(id, request: request) + #expect(uncertain["state"] == .string("provisioning")) + #expect(uncertain["host_state"] == .string("reserved")) + #expect(uncertain["uncertain_host_response"] != nil) + let pending = try #require(try fixture.source.hostWorktree(id: id, in: fixture.sourceScope)) + let operation = try #require(pending.1) + #expect(operation.observedState == .reserved) + #expect(try fixture.child.hostWorktree(id: id, in: fixture.childScope) == nil) + try await queue.write { try $0.execute(sql: "DROP TRIGGER reject_child_settlement") } + let reopened = try CodexDatabase( + path: fixture.sourcePath, worktreeLeasePath: fixture.sharedPath) + let source = CodexHostWorktreeManager( + database: reopened, scope: fixture.sourceScope, services: fixture.host) + let resolved = try result(await source.read(pending.0, operation: operation)) + #expect(resolved["state"] == .string("active")) + #expect(resolved["operation_id"] == .string(operation.ids.operationID.uuidString)) + #expect(await fixture.host.callbacks == ["inspect-invocation", "add", "inspect-operation"]) } @Test - func testRemovalRejectsAReceiptedPathReplacedBySymbolicLink() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString, isDirectory: true) - let repository = directory.appendingPathComponent("repository", isDirectory: true) - let managedRoot = directory.appendingPathComponent("managed", isDirectory: true) - try FileManager.default.createDirectory(at: repository, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try runGit(["init", "-q"], in: repository) - try runGit(["config", "user.name", "Computer MCP Test"], in: repository) - try runGit(["config", "user.email", "computer-mcp@example.invalid"], in: repository) - try Data("baseline\n".utf8).write(to: repository.appendingPathComponent("README.md")) - try runGit(["add", "README.md"], in: repository) - try runGit(["commit", "-q", "-m", "test: baseline"], in: repository) - - let database = try CodexDatabase(inMemory: ()) - let sourceWorkspaceID = "source-workspace" - let workspaceHost = RecordingManagedWorkspaceHost() - let parent = try CodexWorktreeLeaseManager.acquire( - database: database, - workspaceID: sourceWorkspaceID, - workspaceURL: repository, - agentID: "parent-agent", - threadID: "parent-thread", - runID: nil, - parentLeaseID: nil, - branch: nil, - mode: .exclusive, - ttlSeconds: 900, - liveRuntimeStatus: .object(["runtimes": .array([])]) - ) - let plan = try CodexManagedWorktreeManager.planProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - sourceWorkspaceURL: repository, - profileID: "local-admin", - caller: "local-mcp", - agentID: "child-agent", - threadID: "child-thread", - runID: nil, - parentLeaseID: parent.id, - branch: "codex/symlink-boundary", - startPoint: "HEAD", - ttlSeconds: 900, - managedRoot: managedRoot - ) - let active = try await CodexManagedWorktreeManager.performProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - planID: plan.id, - expectedRevision: plan.revision, - confirmProvision: true, - workspaceHost: workspaceHost, - managedRoot: managedRoot - ) - let childLeaseID = try #require(active.leaseID) - var childLease = try #require(try database.codexWorktreeLease(id: childLeaseID)) - childLease = try CodexWorktreeLeaseManager.release( - database: database, - workspaceID: childLease.workspaceID, - leaseID: childLease.id, - expectedRevision: childLease.revision, - reason: "Ready for removal validation." - ) - #expect(childLease.state == .released) - - let original = URL(fileURLWithPath: active.path, isDirectory: true) - let moved = directory.appendingPathComponent("moved-worktree", isDirectory: true) - try FileManager.default.moveItem(at: original, to: moved) - try FileManager.default.createSymbolicLink(at: original, withDestinationURL: moved) - + func lostChildRemovalReplyIsRecoverableFromTheSource() async throws { + let fixture = try WorktreeFixture() + let (id, request) = try fixture.plan() + let created = try await fixture.performProvision(id, request: request) + 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 CodexManagedWorktreeManager.planRemoval( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - managedWorktreeID: active.id, - liveRuntimeStatus: .object(["runtimes": .array([])]), - managedRoot: managedRoot - ) + try fixture.manager.planRemoval(id: id, force: true) } - #expect(FileManager.default.fileExists(atPath: moved.path)) + 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 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)) + } + #expect(throws: CodexWorktreeLeaseError.self) { + try fixture.acquire( + in: fixture.child, scope: fixture.childScope, agent: "racer", parent: fixture.parent.id) + } + 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", + ]) } @Test - func testProvisionRollbackDoesNotDeleteBranchCreatedByAnotherWriter() async throws { - let directory = FileManager.default.temporaryDirectory - .appendingPathComponent(UUID().uuidString, isDirectory: true) - let repository = directory.appendingPathComponent("repository", isDirectory: true) - let managedRoot = directory.appendingPathComponent("managed", isDirectory: true) - try FileManager.default.createDirectory(at: repository, withIntermediateDirectories: true) - defer { try? FileManager.default.removeItem(at: directory) } - try runGit(["init", "-q"], in: repository) - try runGit(["config", "user.name", "Computer MCP Test"], in: repository) - try runGit(["config", "user.email", "computer-mcp@example.invalid"], in: repository) - try Data("baseline\n".utf8).write(to: repository.appendingPathComponent("README.md")) - try runGit(["add", "README.md"], in: repository) - try runGit(["commit", "-q", "-m", "test: baseline"], in: repository) - - let database = try CodexDatabase(inMemory: ()) - let sourceWorkspaceID = "source-workspace" - let workspaceHost = RecordingManagedWorkspaceHost() - let parent = try CodexWorktreeLeaseManager.acquire( - database: database, - workspaceID: sourceWorkspaceID, - workspaceURL: repository, - agentID: "parent-agent", - threadID: "parent-thread", - runID: nil, - parentLeaseID: nil, - branch: nil, - mode: .exclusive, - ttlSeconds: 900, - liveRuntimeStatus: .object(["runtimes": .array([])]) - ) - let branch = "codex/concurrent-owner" - let plan = try CodexManagedWorktreeManager.planProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - sourceWorkspaceURL: repository, - profileID: "local-admin", - caller: "local-mcp", - agentID: "child-agent", - threadID: "child-thread", - runID: nil, - parentLeaseID: parent.id, - branch: branch, - startPoint: "HEAD", - ttlSeconds: 900, - commandRunner: BranchRaceCommandRunner(branch: branch), - managedRoot: managedRoot - ) - - await #expect(throws: CodexManagedWorktreeError.self) { - try await CodexManagedWorktreeManager.performProvision( - database: database, - sourceWorkspaceID: sourceWorkspaceID, - planID: plan.id, - expectedRevision: plan.revision, - confirmProvision: true, - workspaceHost: workspaceHost, - commandRunner: BranchRaceCommandRunner(branch: branch), - managedRoot: managedRoot - ) + func foreignInventoryDoesNotCreateLineage() async throws { + let fixture = try WorktreeFixture() + let listed = try await fixture.manager.list( + history: [], limit: 10, invocation: metadata(newIDs(), list: true)) + let payload = try result(listed) + let inventory = payload["host_response"]?.objectValue?["structuredContent"]? + .objectValue?["result"]?.objectValue?["worktrees"]?.arrayValue + #expect(inventory?.count == 1) + #expect(payload["worktrees"] == .array([])) + #expect(throws: CodexWorktreeLeaseError.self) { + try fixture.acquire( + in: fixture.child, scope: fixture.childScope, agent: "child", parent: fixture.parent.id) } - let branchResult = try gitResult( - ["show-ref", "--verify", "--quiet", "refs/heads/\(branch)"], - in: repository - ) - #expect(branchResult.exitCode == 0) } +} - private func runGit(_ arguments: [String], in directory: URL) throws { - let result = try gitResult(arguments, in: directory) - guard result.exitCode == 0 else { - throw CodexManagedWorktreeError.command(result.stderr) - } +private final class WorktreeFixture: Sendable { + let root: URL + let sourcePath: String + let sharedPath: String + let source: CodexDatabase + let child: CodexDatabase + let sourceScope: CodexProjectScope + let childScope: CodexProjectScope + let host: FixtureProjectServices + let parent: CodexWorktreeLease + let childPath: String + + init() throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + self.root = root + sourcePath = root.appendingPathComponent("source.sqlite").path + sharedPath = root.appendingPathComponent("leases.sqlite").path + source = try CodexDatabase(path: sourcePath, worktreeLeasePath: sharedPath) + child = try CodexDatabase( + path: root.appendingPathComponent("child.sqlite").path, worktreeLeasePath: sharedPath) + sourceScope = try #require(CodexProjectScope(worktreeOwner(project: "source"))) + childScope = try #require(CodexProjectScope(worktreeOwner(project: "child"))) + childPath = root.appendingPathComponent("checkout").path + host = FixtureProjectServices(db: source, source: sourceScope, childPath: childPath) + parent = try CodexWorktreeLeaseManager.acquire( + database: source, workspaceID: sourceScope.projectID, workspaceURL: root, + agentID: "source-agent", threadID: nil, runID: nil, parentLeaseID: nil, branch: nil, + mode: .exclusive, ttlSeconds: 900, liveRuntimeStatus: .object([:]), scope: sourceScope) } - private func gitResult(_ arguments: [String], in directory: URL) throws -> CommandResult { - try ProcessCommandRunner().run( - executable: "/usr/bin/git", - arguments: arguments, - workingDirectory: directory, - environment: ["GIT_TERMINAL_PROMPT": "0", "LC_ALL": "C"], - timeoutMilliseconds: 10_000, - maxOutputBytes: 1_048_576 - ) + deinit { try? FileManager.default.removeItem(at: root) } + + var manager: CodexHostWorktreeManager { + .init(database: source, scope: sourceScope, services: host) + } + var childManager: CodexHostWorktreeManager { + .init(database: child, scope: childScope, services: host) } -} -private final class BranchRaceCommandRunner: CommandRunning, @unchecked Sendable { - private let branch: String - private let runner = ProcessCommandRunner() - private let lock = NSLock() - private var injected = false + func owner(project: String, principal: String = "principal") -> CodexRuntimeOwner { + worktreeOwner(project: project, principal: principal) + } - init(branch: String) { - self.branch = branch + func provider() -> CodexAppServerProvider { + .init( + appServer: FakeAppServerRuntime(), owner: owner(project: "source"), database: source, + workspaceURL: root, recentThreadReader: nil, localControlAllowed: true, projectServices: host) } - func run( - executable: String, - arguments: [String], - workingDirectory: URL?, - environment: [String: String], - timeoutMilliseconds: Int, - maxOutputBytes: Int - ) throws -> CommandResult { - lock.lock() - let shouldInject = - !injected && executable == "/usr/bin/git" && arguments.starts(with: ["worktree", "add"]) - if shouldInject { - injected = true - } - lock.unlock() - - if shouldInject, let workingDirectory { - let create = try runner.run( - executable: executable, - arguments: ["branch", branch, "HEAD"], - workingDirectory: workingDirectory, - environment: environment, - timeoutMilliseconds: timeoutMilliseconds, - maxOutputBytes: maxOutputBytes - ) - guard create.exitCode == 0 else { return create } - return CommandResult( - executable: executable, - arguments: arguments, - exitCode: 128, - timedOut: false, - stdout: "", - stderr: "fatal: a concurrent writer created the branch", - stdoutTruncated: false, - stderrTruncated: false - ) - } - return try runner.run( - executable: executable, - arguments: arguments, - workingDirectory: workingDirectory, - environment: environment, - timeoutMilliseconds: timeoutMilliseconds, - maxOutputBytes: maxOutputBytes + func plan() throws -> (String, [String: JSONValue]) { + let plan = try manager.planProvision( + selection: .init(["name": .string("example"), "base": .null]), + agentID: "child-agent", threadID: nil, runID: nil, parentLeaseID: parent.id, ttlSeconds: 900) + return ( + try #require(plan.objectValue?["id"]?.stringValue), + try #require(plan.objectValue?["perform_arguments"]?.objectValue) ) } - func runData( - executable: String, - arguments: [String], - workingDirectory: URL?, - environment: [String: String], - timeoutMilliseconds: Int, - maxOutputBytes: Int - ) throws -> CommandDataResult { - try runner.runData( - executable: executable, - arguments: arguments, - workingDirectory: workingDirectory, - environment: environment, - timeoutMilliseconds: timeoutMilliseconds, - maxOutputBytes: maxOutputBytes + func performProvision(_ id: String, request: [String: JSONValue]) async throws + -> [String: JSONValue] + { + let digest = try CodexHostInvocation.digest(request) + await host.capture(digest, action: .provision) + return try result( + await manager.perform( + id: id, action: .provision, revision: 1, arguments: request, invocation: metadata(newIDs())) ) } + + func acquire( + in database: CodexDatabase, scope: CodexProjectScope, agent: String, parent: String? = nil + ) + throws -> CodexWorktreeLease + { + try CodexWorktreeLeaseManager.acquire( + database: database, workspaceID: scope.projectID, + workspaceURL: URL(fileURLWithPath: childPath), + agentID: agent, threadID: nil, runID: nil, parentLeaseID: parent, branch: nil, + mode: parent == nil ? .exclusive : .isolatedWorktree, + ttlSeconds: 900, liveRuntimeStatus: .object([:]), scope: scope) + } + + func release(_ lease: CodexWorktreeLease, in database: CodexDatabase) throws { + _ = try CodexWorktreeLeaseManager.release( + database: database, workspaceID: lease.workspaceID, leaseID: lease.id, + expectedRevision: lease.revision, reason: "reviewed") + } } -private actor RecordingManagedWorkspaceHost: CodexManagedWorkspaceHost { - private var records: [String: CodexManagedWorktree] = [:] - private var removalAllowed = true - private var unregisterAllowed = true - private var registerFailureAfterSaving = false - func setRegisterFailureAfterSaving(_ value: Bool) { registerFailureAfterSaving = value } - func setUnregisterAllowed(_ value: Bool) { unregisterAllowed = value } +private actor FixtureProjectServices: CodexProjectServices { + private let db: CodexDatabase + private let source: CodexProjectScope + private let childPath: String + nonisolated let worktreeID = UUID() + private var digest = "" + private var action: CodexWorktreeAction = .provision + private var lostRemovalReply = false + private var creationFailure: CodexHostWorktreeState? + private var outcomes: [UUID: JSONValue] = [:] + private(set) var callbacks: [String] = [] + private(set) var selection: CodexWorktreeSelection? + + init(db: CodexDatabase, source: CodexProjectScope, childPath: String) { + self.db = db + self.source = source + self.childPath = childPath + } + + func capture(_ digest: String, action: CodexWorktreeAction) { + self.digest = digest + self.action = action + } - func setRemovalAllowed(_ allowed: Bool) { removalAllowed = allowed } + func loseNextRemovalReply() { lostRemovalReply = true } + func failCreation(as state: CodexHostWorktreeState) { creationFailure = state } - func authorizeRemoval(_ worktree: CodexManagedWorktree) throws { - guard removalAllowed else { - throw CodexManagedWorktreeError.state("Fixture host denied removal.") - } - guard records[worktree.workspaceID]?.id == worktree.id else { - throw CodexManagedWorktreeError.state("Fixture removal ownership mismatch.") + func validateContract() {} + + func describe(_ inspection: CodexProjectInspection) throws -> CodexHostToolResponse { + switch inspection { + case .invocation(let id): + callbacks.append("inspect-invocation") + let pending = try db.hostWorktrees(in: source, limit: 20).first { + $0.state == action.pendingState + } + let worktree = try #require(pending) + let operation = try #require(try db.hostWorktree(id: worktree.id, in: source)?.1) + #expect(operation.ids.invocationID == id) + return reply( + .object([ + "format_version": .integer(1), "invocation_id": .string(id.uuidString), + "principal_id": .string(source.principalID), "profile_id": .string(source.profileID), + "project_id": .string(operation.selectedProjectID), + "tool": .string(action.tool), "host_action": .string(action.rawValue), + "arguments_digest": .string(digest), + "operation": envelope(operation.ids, result: .null, state: "reserved"), + ])) + case .operation(let id): + callbacks.append("inspect-operation") + return reply(try #require(outcomes[id])) } } - func registerDerivedWorkspace(_ worktree: CodexManagedWorktree, now: Date) throws { - guard worktree.sourceWorkspaceID == "source-workspace", - worktree.profileID == "local-admin", worktree.caller == "local-mcp" - else { - throw CodexManagedWorktreeError.state("Fixture source binding mismatch.") - } - records[worktree.workspaceID] = worktree - if registerFailureAfterSaving { - throw CodexManagedWorktreeError.state("Fixture registration acknowledgement failed.") + func add(_ selection: CodexWorktreeSelection, ids: CodexHostOperationIDs) + -> CodexHostToolResponse + { + callbacks.append("add") + self.selection = selection + if let creationFailure { + let error: JSONValue = .object([ + "code": .string("permission.required"), "message": .string("fixture host refused"), + ]) + let failed = envelope(ids, result: .null, state: creationFailure.rawValue, error: error) + outcomes[ids.operationID] = failed + return .init( + raw: .object([ + "content": .array([ + .object(["type": .string("text"), "text": .string("fixture refusal")]) + ]), + "structuredContent": .object(["result": failed]), "isError": .bool(true), + ])) } + return complete( + ids, + [ + "worktree_id": .string(worktreeID.uuidString), "project_id": .string("child"), + "path": .string(childPath), "branch": .string(selection.expectedBranch), + "base": .string(selection.explicitBase ?? "captured-main"), "warnings": .array([]), + ]) } - func unregisterDerivedWorkspace(_ worktree: CodexManagedWorktree, now: Date) throws { - guard unregisterAllowed else { - throw CodexManagedWorktreeError.state("Fixture unregister failed after Git removal.") - } - guard let registered = records[worktree.workspaceID] else { return } - guard registered.id == worktree.id, registered.path == worktree.path, - registered.sourceWorkspaceID == worktree.sourceWorkspaceID - else { - throw CodexManagedWorktreeError.state("Fixture registration ownership mismatch.") + func remove(force: Bool, ids: CodexHostOperationIDs) throws -> CodexHostToolResponse { + callbacks.append("remove") + #expect(force) + let result = complete( + ids, + [ + "worktree_id": .string(worktreeID.uuidString), "project_id": .string("child"), + "branch": .string("worktree/example"), "oid": .string(String(repeating: "a", count: 40)), + "termination_warnings": .array([]), + ]) + if lostRemovalReply { + lostRemovalReply = false + throw MCPError.connectionClosed } - records.removeValue(forKey: worktree.workspaceID) + return result + } + + func list(invocationID: UUID) -> CodexHostToolResponse { + reply(.object(["worktrees": .array([.object(["owner": .string("foreign")])])])) + } + + private func complete(_ ids: CodexHostOperationIDs, _ fields: [String: JSONValue]) + -> CodexHostToolResponse + { + let completed = envelope(ids, result: .object(fields), state: "completed") + outcomes[ids.operationID] = completed + return reply(completed) + } + + private func envelope( + _ ids: CodexHostOperationIDs, result: JSONValue, state: String, error: JSONValue = .null + ) -> JSONValue { + .object( + ids.arguments.merging([ + "action": .string(action.rawValue), "source_project_id": .string(source.projectID), + "project_id": .string(action == .provision ? source.projectID : "child"), + "state": .string(state), "result": result, "error": error, "extension": .integer(9), + ]) { current, _ in current }) } - func record(id: String) -> CodexManagedWorktree? { records[id] } + private func reply(_ fields: JSONValue) -> CodexHostToolResponse { + .init( + raw: .object([ + "content": .array([]), "isError": .bool(false), + "structuredContent": .object(["result": fields]), + ])) + } +} + +private func worktreeOwner(project: String, principal: String = "principal") -> CodexRuntimeOwner { + .init( + workspaceID: project, profileID: "profile", caller: "local-mcp", transport: nil, + socketConnectionID: nil, tunnelInstanceID: nil, tunnelProfileID: nil, principalID: principal) +} + +private func newIDs() -> CodexHostOperationIDs { .init(invocationID: UUID(), operationID: UUID()) } + +private func metadata(_ ids: CodexHostOperationIDs, list: Bool = false) throws + -> CodexHostInvocation +{ + var fields: [String: MCP.Value] = [ + CodexHostInvocation.invocationKey: .string(ids.invocationID.uuidString) + ] + if !list { fields[CodexHostInvocation.operationKey] = .string(ids.operationID.uuidString) } + return try CodexHostInvocation(.init(additionalFields: fields)) +} + +private func call( + _ client: MCP.Client, _ tool: String, _ args: [String: JSONValue], + ids: CodexHostOperationIDs? = nil +) async throws -> MCP.CallTool.Result { + let args = try JSONDecoder().decode([String: MCP.Value].self, from: JSONEncoder().encode(args)) + let meta = ids.map { + MCP.Metadata(additionalFields: [ + CodexHostInvocation.invocationKey: .string($0.invocationID.uuidString), + CodexHostInvocation.operationKey: .string($0.operationID.uuidString), + ]) + } + let request: RequestContext = try await client.callTool( + name: tool, arguments: args, meta: meta) + return try await request.value +} + +private func result(_ reply: MCP.CallTool.Result) throws -> [String: JSONValue] { + let value = try JSONDecoder().decode( + JSONValue.self, from: JSONEncoder().encode(reply.structuredContent)) + return try #require(value.objectValue?["result"]?.objectValue) } private func withMCPClient( - provider: CodexAppServerProvider, - body: (MCP.Client) async throws -> Void + _ provider: CodexAppServerProvider, body: (MCP.Client) async throws -> Void ) async throws { let pair = await InMemoryTransport.createConnectedPair() try await pair.server.connect() @@ -789,17 +550,3 @@ private func withMCPClient( throw error } } - -private func invoke( - _ client: MCP.Client, _ name: String, _ arguments: [String: MCP.Value] = [:] -) async throws -> MCP.Value { - let pending = try await client.send(MCP.CallTool.request(.init(name: name, arguments: arguments))) - let response = try await pending.value - try #require(response.isError == false, "\(name): \(response.content)") - let result = try #require(response.structuredContent?.objectValue?["result"]) - guard case .text(let text, _, _) = response.content.first else { - throw CodexToolError.executionFailed("Missing MCP text result.") - } - #expect(try JSONDecoder().decode(MCP.Value.self, from: Data(text.utf8)) == result) - return result -} diff --git a/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift b/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift index 95841f2..b40fff9 100644 --- a/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift +++ b/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift @@ -73,7 +73,7 @@ final class CodexOperationalDiagnosticsTests { owner: owner(profileID: mismatch == "owner" ? "profile-2" : "profile-1"), recentToolAudits: Array( repeating: .object([ - "workspace_id": .string(mismatch == "workspace" ? "workspace-2" : "workspace-1") + "project_id": .string(mismatch == "workspace" ? "workspace-2" : "workspace-1") ]), count: mismatch == "limit" ? 2 : 1)) await #expect(throws: CodexToolError.self) { @@ -218,7 +218,7 @@ final class CodexOperationalDiagnosticsTests { "tunnel_instance_id": .string("tunnel-1"), "tunnel_profile_id": .string("tunnel-profile-1"), "profile_id": .string("profile-1"), - "workspace_id": .string("workspace-1"), + "project_id": .string("workspace-1"), "capability_id": .string("git.commit"), "output_byte_count": .integer(9_007_199_254_740_993), "decision": .string("allowed"), @@ -231,7 +231,7 @@ final class CodexOperationalDiagnosticsTests { "request_id": .string("token=diagnostic-secret"), "mcp_request_id": .string(String(repeating: "m", count: 2_048)), "profile_id": .string("profile-1"), - "workspace_id": .string("workspace-1"), + "project_id": .string("workspace-1"), "capability_id": .string("tools.list"), "decision": .string("allowed"), "input": .string("unprojected command input"), @@ -258,7 +258,7 @@ final class CodexOperationalDiagnosticsTests { #expect( object["codex_configuration"]?.objectValue?["sandbox_override"] == .string("workspace-write")) - #expect(object["scope"]?.objectValue?["workspace_id"] == .string("workspace-1")) + #expect(object["scope"]?.objectValue?["project_id"] == .string("workspace-1")) #expect(summary["persisted_runtime_count"] == .number(1)) #expect(summary["thread_ownership_receipt_count"] == .number(1)) #expect(summary["pending_approval_count"] == .number(1)) diff --git a/Tests/CodexAdapterTests/CodexWorkContinuationTests.swift b/Tests/CodexAdapterTests/CodexWorkContinuationTests.swift index f94a83f..4258c54 100644 --- a/Tests/CodexAdapterTests/CodexWorkContinuationTests.swift +++ b/Tests/CodexAdapterTests/CodexWorkContinuationTests.swift @@ -22,7 +22,7 @@ struct CodexWorkContinuationTests { } let tool = try CodexWorkSnapshot.declaring(method.tool) #expect(tool.inputSchema == method.tool.inputSchema) - #expect(tool._meta?["io.github.computer-mcp/risk"] == .string(method.risk.rawValue)) + #expect(tool._meta?["io.github.computer-mcp/risk"] == .string(method.risk.hostValue)) } } diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index 6c6db4b..0b66289 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -7,6 +7,7 @@ description = 'Codex execution and protocol inspection through standard MCP.' [[mcp]] id = 'app-server' transport = 'stdio' +host_service_contract = "projects-v1" executable = { platform_paths = { macos = 'bin/codex-mcp-adapter' } } capabilities = ['tools'] diff --git a/scripts/check-workflow.py b/scripts/check-workflow.py index 421a216..910d1cb 100644 --- a/scripts/check-workflow.py +++ b/scripts/check-workflow.py @@ -264,9 +264,11 @@ def run(adapter, codex, gateway=None, database=None, control_socket=None, regist metrics_exporter = "none" ''' (state / "config.toml").write_text(config) - context = {"formatVersion": 1, "runtimeID": str(uuid.uuid4()), "caller": "local-mcp", - "profileID": "local-admin", "principalID": "workflow-fixture", - "workspace": {"id": "workflow-fixture", "rootPath": str(workspace)}} + context = { + "formatVersion": 1, "hostServiceContract": "projects-v1", "runtimeID": str(uuid.uuid4()), + "caller": "local-mcp", "profileID": "local-admin", "principalID": "workflow-fixture", + "project": {"id": "workflow-fixture", "rootPath": str(workspace)}, + } environment = {"PATH": runtime_path, "CODEX_HOME": str(state), "COMPUTER_MCP_HOST_CONTEXT": json.dumps(context)} adapter_config = root / "adapter.json" From 5b7a5610f37bd13a02d805d1a06d30694a46a878 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:35:05 +0800 Subject: [PATCH 02/25] fix(plugin): declare project writes for host worktree operations --- .../CodexAppServerProviderTests.swift | 16 +++++++++++----- computer-mcp-plugin.toml | 5 +++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift b/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift index b68abb6..bb8e95e 100644 --- a/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerProviderTests.swift @@ -10,10 +10,15 @@ struct CodexAppServerProviderTests { func hostServiceConsumersDeclareTheirExactSemanticEffect() { let expected = [ "codex.diagnostics.snapshot": "diagnostics.snapshot", - "codex.worktree.provision.perform": "workspaces.provision", - "codex.worktree.remove.perform": "workspaces.remove", + "codex.worktree.managed.list": "projects.list", + "codex.worktree.provision.perform": "projects.provision", + "codex.worktree.remove.perform": "projects.remove", ] - for tool in makeProvider().tools { + let consumers = makeProvider().tools.filter { + $0._meta?["io.github.computer-mcp/host-action"] != nil + } + #expect(consumers.map(\.name).sorted() == expected.keys.sorted()) + for tool in consumers { #expect(tool._meta?["io.github.computer-mcp/host-action"]?.stringValue == expected[tool.name]) } } @@ -33,8 +38,9 @@ struct CodexAppServerProviderTests { for tool in tools { let raw = try #require( tool._meta?["io.github.computer-mcp/risk"]?.stringValue) - #expect(CodexOperationRisk(rawValue: raw) != nil) - #expect(tool.annotations.readOnlyHint == (raw == "read-only")) + let risk = try #require( + CodexOperationRisk(hostValue: raw), "Invalid host risk for \(tool.name)") + #expect(tool.annotations.readOnlyHint == (risk == .readOnly)) } for name in [ "codex.app.methods.call", "codex.app.thread.start", "codex.app.thread.reclaim", diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index 0b66289..fd24108 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -4,6 +4,11 @@ version = "0.1.0" plugin_api = 1 description = 'Codex execution and protocol inspection through standard MCP.' +[[permissions]] +id = "project" +access = "write" +purpose = "Create and remove managed worktrees in projects you approve for Codex." + [[mcp]] id = 'app-server' transport = 'stdio' From dc0abdd862792b27c56da91150b617efa4c41650 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:38:21 +0800 Subject: [PATCH 03/25] test(transport): wait for child readiness before ending the owner --- .../CodexAppServerProcessTransportTests.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift b/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift index 257029b..d12d6e2 100644 --- a/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerProcessTransportTests.swift @@ -421,8 +421,9 @@ struct CodexAppServerProcessTransportTests { defer { try? FileManager.default.removeItem(at: directory) } let owner = Process() owner.executableURL = URL(fileURLWithPath: "/bin/sleep") - owner.arguments = ["0.3"] + owner.arguments = ["30"] try owner.run() + defer { if owner.isRunning { owner.terminate() } } let descendantPIDFile = directory.appendingPathComponent("descendant.pid") let script = directory.appendingPathComponent("app-server.sh") @@ -457,6 +458,7 @@ struct CodexAppServerProcessTransportTests { let supervisorPID = try #require(running.supervisorProcessID) let descendantPID = try await waitForPID(at: descendantPIDFile) + owner.terminate() let ownerExited = await waitForProcessExit(owner) #expect(ownerExited) if !ownerExited { From e03d34831d9047204cd58a76bdffb3a43f56e284 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:54:06 +0800 Subject: [PATCH 04/25] fix(plugin): use host-managed runtime storage --- Documentation/Reference/Installation.md | 9 +- Documentation/Reference/Release.md | 91 +++-- README.md | 18 +- Sources/CodexAdapter/CodexHostMCPClient.swift | 14 +- Sources/CodexAdapter/CodexLaunchContext.swift | 13 +- .../CodexProcessEnvironment.swift | 29 ++ .../CodexRecentThreadReader.swift | 10 +- .../CodexHostMCPClientTests.swift | 2 +- .../CodexLaunchContextTests.swift | 31 ++ .../CodexProcessEnvironmentTests.swift | 20 + Tests/Fixtures/NativeCodex/HostToolVendor.py | 67 ---- Tests/Fixtures/NativeCodex/README.md | 8 - .../RegisteredHost/RegisteredHost.swift | 240 ++++++++++++ Tests/test_host_acceptance.py | 11 +- scripts/check-host.py | 347 ++++++++++-------- 15 files changed, 601 insertions(+), 309 deletions(-) delete mode 100644 Tests/Fixtures/NativeCodex/HostToolVendor.py create mode 100644 Tests/Fixtures/RegisteredHost/RegisteredHost.swift diff --git a/Documentation/Reference/Installation.md b/Documentation/Reference/Installation.md index 8ae15a6..5a0f38d 100644 --- a/Documentation/Reference/Installation.md +++ b/Documentation/Reference/Installation.md @@ -79,8 +79,7 @@ and set startup arguments to individual values: "allowAnyTool": true, "hostServices": true, "args": [ - "--config", "/absolute/path/to/codex.json", - "--state-directory", "/absolute/path/to/adapter-state" + "--config", "/absolute/path/to/codex.json" ] } } @@ -93,8 +92,10 @@ remain separate host decisions. `hostServices` delegates the current connection' scope over a private inherited MCP endpoint, not local-admin authority; leave it false for an adapter that does not require callbacks. See [host integration](HostIntegration.md). The configuration file contains the existing -Codex settings described in the root manual; `CODEX_HOME` selects vendor state -through the registered environment. Never put credentials in arguments. +Codex settings described in the root manual. The host must allow the adapter +to read the configuration file. The provider container holds adapter records +under `$XDG_STATE_HOME/codex-adapter` and vendor state under `$HOME/.codex` by +default. Never put credentials in arguments. For the CLI, save the settings JSON and use `plugins configure codex --settings-file /absolute/path/settings.json --expected-revision REVISION`. diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index ad1c1b1..9581790 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -97,12 +97,9 @@ and catalog notification are separate jobs. ### Runtime acceptance -Use macOS with the selected installed `computer-mcp` CLI, a separately installed -vendor Codex, Python 3.11 or newer, Git and the verified release archive. The -adapter must be the executable extracted from that archive. Record the host, -plugin and vendor combination; a package doctor proves configuration and files, -not model execution. Run the ordinary checks in [Contributing](../../CONTRIBUTING.md) -first. +Use macOS, Python 3.11 or newer, Git and the verified release archive. Record +both source revisions and the executable digests. Run the ordinary checks in +[Contributing](../../CONTRIBUTING.md) first. ```sh python3 scripts/check-package.py --archive --receipt \ @@ -111,11 +108,10 @@ python3 scripts/check-workflow.py \ --adapter "$PWD/.build/accepted-package/bin/codex-mcp-adapter" \ --codex /absolute/path/to/codex python3 scripts/check-host.py \ - --host /absolute/path/to/computer-mcp \ + --host /absolute/path/to/CodexRegisteredHost \ --adapter "$PWD/.build/accepted-package/bin/codex-mcp-adapter" \ - --codex /absolute/path/to/codex \ - --output-directory "$PWD/.build/host-acceptance" \ - --mode full --auth-file /absolute/path/to/vendor/auth.json --model + --output-directory "$PWD/.build/host-container-acceptance" \ + --mode container ``` `check-workflow.py` exercises the relocated adapter through standard MCP with @@ -123,15 +119,15 @@ an isolated home and fixed loopback model, covering native approvals, turns, cancellation, reconnection and owned-process cleanup. It does not establish real model authentication. -`check-host.py` uses only the host's public `serve stdio` command and standard -MCP. It starts private host instances with explicit workspace selection, host -configuration and databases. It does not contact the normal App control socket -or an existing App Server. The model fixture and all native generations are -owned by the run. The selected output directory must be new; after inspecting -its receipt and confirming cleanup, remove its disposable state before reusing -that location. +`check-host.py` registers the package in a disposable host database and approves +the selected provider and caller permissions before serving standard MCP over +stdio. Use a new output directory. Container mode verifies injected storage +across two host and adapter launches, an allowed project file callback, refusal +to redirect a callback to a sibling project, and peer descriptor isolation. +It uses a deterministic vendor peer and omits authentication and model calls. -Full mode needs a vendor file-store login authorized for the selected model. +Full mode additionally takes `--codex`, `--auth-file` and `--model`. It needs a +vendor file-store login authorized for the selected model. The supplied `auth.json` is copied with mode `0600` into the private vendor home and deleted on exit; the original is never changed. Keychain-only credentials are not imported. The real-model checks make bounded text-only App Server and @@ -140,21 +136,10 @@ Model use may incur the account's ordinary usage charges. Keep the output private because native histories and diagnostic evidence can include account metadata. Never publish the authentication file or raw runtime state. -For a deterministic native check without credentials, use `--mode fixture` and -omit `--auth-file` and `--model`. This still needs the installed host and real -vendor executable. It tests catalog/diagnostic laziness, explicit Skills -directories and app-list deadlines, inherited and explicit Full Access, a native -read-only override, Git hooks, loopback and outside-workspace access, workspace -process isolation, three-connection thread/Goal handoff, vendor/adapter crash -recovery without replay, native approval, fork/review/steer/interruption, Exec -options/events/results/resume/cancellation/release, and exact thread archiving. -A separate disposable App Server protocol peer exercises native host callbacks: -workspace/recursion denial, Git dry-run index preservation, prepare without -mutation, exact single-use host tickets, a complete hooked file/Git commit, and -rejection of a pending local-approval ticket. The standalone host's configured -policy authorizes the successful ticket path; local App approval resolution is -verified by the host's generic tests, not simulated as an App UI check here. -It cannot prove real authentication or model availability. +Use `--mode fixture` with `--codex` to select the native loopback recipes. The +enclosing host sandbox applies to native commands in both native modes. Run +native and authenticated acceptance for the exact reviewed host and vendor +configuration before release. The driver writes `report.json` with step results, binary versions/digests, fixture digest, authentication status and cleanup errors. It separately records @@ -168,8 +153,8 @@ owned thread; unrelated errors remain failures. The release candidate requires the full report to pass for its exact executable bytes, in addition to source tests and archive verification. Host plugin installation, grants, local approval and uninstall remain the host's generic -acceptance responsibility; this driver validates the native runtime through a -public host registration. Keep those host checks with the accepted combination. +acceptance responsibility; this driver validates the runtime through a +disposable host registration. Keep those host checks with the accepted combination. Pure driver logic and argument validation run without a host or vendor: @@ -177,6 +162,42 @@ Pure driver logic and argument validation run without a host or vendor: python3 -m unittest discover -s Tests -p 'test_host_acceptance.py' -v ``` +#### Build the registered host fixture + +Build this fixture with the selected Computer MCP source revision on macOS. +The fixture uses the host's plugin store, provider review, permission service, +sandbox launcher and standard MCP gateway. Its authorization watermark and +managed policy source are confined to the fixture. It also serves the +deterministic App Server peer used by `check-host.py --mode container`. + +From the plugin checkout, set `host_source` to the selected host checkout, +`host_revision` to its full commit SHA, and `stage` to a new absolute path in +ignored build output. Record the host and plugin commit SHAs with the report. + +```sh +test "$(git -C "$host_source" rev-parse HEAD)" = "$host_revision" +mkdir -p "$stage/registered-host" +git -C "$host_source" archive "$host_revision" | tar -xf - -C "$stage/registered-host" +mkdir "$stage/registered-host/Tests/CodexRegisteredHost" +cp Tests/Fixtures/RegisteredHost/RegisteredHost.swift "$stage/registered-host/Tests/CodexRegisteredHost/" +cat >>"$stage/registered-host/Package.swift" <<'SWIFT' + +package.targets.append(.executableTarget( + name: "CodexRegisteredHost", + dependencies: [ + "ComputerMCPConfiguration", "ComputerMCPCore", "ComputerMCPGateway", "ComputerMCPMacOS", + "ComputerMCPPermissions", "ComputerMCPPlatform", "ComputerMCPPlugins", + ], + path: "Tests/CodexRegisteredHost" +)) +SWIFT +swift build --package-path "$stage/registered-host" --product CodexRegisteredHost +swift build --package-path "$stage/registered-host" --product computer-mcp-execution-bootstrap +``` + +Pass the resulting `CodexRegisteredHost` executable to `check-host.py --host`. +Keep the SwiftPM build output alongside it until the fixture has finished. + ### Publish 1. Select the reviewed `master` commit with successful `push` CI from diff --git a/README.md b/README.md index 334c499..8f9df7f 100644 --- a/README.md +++ b/README.md @@ -32,10 +32,10 @@ fork of the MCP Swift SDK. The host owns registration, caller grants, project au audit; the plugin does not link Computer MCP Core or install the vendor Codex binary. Computer MCP supplies the initial directory and a stable authorization subject, and admits each -invocation using its current permissions. Codex controls its own sandbox and approvals: explicit -native directories and Full Access selections are preserved, and native Full Access uses the -executing user's operating-system authority. The initial directory is task ownership metadata, -not an operating-system sandbox. Host callbacks still require their own grants. +invocation using its current permissions. Codex controls its own sandbox and approvals, including +explicit native directories and Full Access selections. The enclosing host sandbox also applies +to native Full Access. The initial directory identifies task ownership. Host callbacks require +their own grants. ## Quick look @@ -90,10 +90,12 @@ configuration fields as a local JSON file and launch with } ``` -For App Server execution, set `app_server_enabled` to `true` and pass -`--state-directory /absolute/path/adapter-state`. The directory holds the adapter's `codex.sqlite` -records, separate from the vendor's `CODEX_HOME` and the Computer MCP host database; host-bound -Exec also uses it for shared native thread ownership. Keep it across restarts and updates. +For App Server execution, set `app_server_enabled` to `true`. A registered host launch +stores adapter records under `$XDG_STATE_HOME/codex-adapter` and defaults the vendor's +`CODEX_HOME` to `$HOME/.codex` inside the provider container. Host-bound Exec also uses +the adapter state for native thread ownership. Standalone App Server clients pass +`--state-directory /absolute/path/adapter-state`. An explicit state directory or +`CODEX_HOME` takes precedence, subject to the host's filesystem policy. The configuration file is limited to 64 KiB, and no executable starts for catalog discovery. Omitted sandbox and approval settings follow native Codex configuration, including a diff --git a/Sources/CodexAdapter/CodexHostMCPClient.swift b/Sources/CodexAdapter/CodexHostMCPClient.swift index 6dc0858..1de76b6 100644 --- a/Sources/CodexAdapter/CodexHostMCPClient.swift +++ b/Sources/CodexAdapter/CodexHostMCPClient.swift @@ -20,8 +20,8 @@ actor CodexHostMCPClient: CodexHostTools, CodexProjectServices, private struct Decision: Equatable { let name: String let digest: String - let declared: CodexOperationRisk - let effective: CodexOperationRisk + let risk: CodexOperationRisk + let requirements: JSONValue } private var decisions: [String: Decision] = [:] @@ -68,7 +68,7 @@ actor CodexHostMCPClient: CodexHostTools, CodexProjectServices, "The host decision changed while its preflight was pending.") } decisions[requestID] = decision - return decision.effective + return decision.risk } func discard(requestID: String) { decisions.removeValue(forKey: requestID) } @@ -132,16 +132,14 @@ actor CodexHostMCPClient: CodexHostTools, CodexProjectServices, ]) guard let value = result.objectValue?["structuredContent"]?.objectValue?["result"]?.objectValue, value["decision"] == .string("allowed"), value["capability_id"] == .string(name), - value["project_id"] == .string(self.projectID), - let declared = value["risk"]?.stringValue.flatMap(CodexOperationRisk.init(hostValue:)), - let effective = value["effective_risk"]?.stringValue.flatMap( - CodexOperationRisk.init(hostValue:)) + let risk = value["risk"]?.stringValue.flatMap(CodexOperationRisk.init(hostValue:)), + let requirements = value["requirements"], requirements.objectValue != nil else { throw CodexToolError.executionFailed( "Host preflight returned an invalid or unsupported decision.") } return Decision( - name: name, digest: try Self.digest(arguments), declared: declared, effective: effective) + name: name, digest: try Self.digest(arguments), risk: risk, requirements: requirements) } private func connect() async throws { diff --git a/Sources/CodexAdapter/CodexLaunchContext.swift b/Sources/CodexAdapter/CodexLaunchContext.swift index b2b372f..3d82dfd 100644 --- a/Sources/CodexAdapter/CodexLaunchContext.swift +++ b/Sources/CodexAdapter/CodexLaunchContext.swift @@ -8,6 +8,7 @@ struct CodexLaunchContext: Sendable { let localControlAllowed: Bool let managedProjectRoot: URL? let hostServiceContract: String? + private let hostStateDirectory: URL? init(environment: [String: String], currentDirectory: URL) throws { if let text = environment["COMPUTER_MCP_HOST_CONTEXT"] { @@ -30,6 +31,8 @@ struct CodexLaunchContext: Sendable { throw ConfigurationError.invalid("Invalid Computer MCP launch context.") } hostServiceContract = marker + hostStateDirectory = CodexProcessEnvironment.hostStateRoot(in: environment)? + .appendingPathComponent("codex-adapter", isDirectory: true) workspaceURL = URL(fileURLWithPath: host.project.rootPath).standardizedFileURL if let root = host.managedProjectRoot { guard Self.isAbsolutePath(root), root.utf8.count <= 16_384, !root.contains("\0") else { @@ -50,6 +53,7 @@ struct CodexLaunchContext: Sendable { workspaceURL = currentDirectory.standardizedFileURL managedProjectRoot = nil hostServiceContract = nil + hostStateDirectory = nil let identity = SHA256.hash(data: Data(workspaceURL.path.utf8)) .map { String(format: "%02x", $0) }.joined() owner = CodexRuntimeOwner( @@ -80,7 +84,7 @@ struct CodexLaunchContext: Sendable { ) throws -> CodexAppServerProvider? { try configuration.validate() guard configuration.enabled, configuration.appServerEnabled else { return nil } - guard let stateDirectory else { + guard let stateDirectory = stateDirectory ?? hostStateDirectory else { throw ConfigurationError.invalid( "App Server execution requires --state-directory for adapter-owned records.") } @@ -132,7 +136,7 @@ struct CodexLaunchContext: Sendable { private func makeThreadOwnerIndex(stateDirectory: URL?) throws -> CodexThreadOwnerIndex? { guard let principalID = owner.principalID else { return nil } - guard let stateDirectory else { + guard let stateDirectory = stateDirectory ?? hostStateDirectory else { throw ConfigurationError.invalid( "Host-bound Codex execution requires --state-directory for thread ownership.") } @@ -143,12 +147,9 @@ struct CodexLaunchContext: Sendable { try FileManager.default.createDirectory( at: stateDirectory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) - let codexHome = - ProcessInfo.processInfo.environment["CODEX_HOME"].map { URL(fileURLWithPath: $0) } - ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".codex") return try CodexThreadOwnerIndex( path: stateDirectory.appendingPathComponent("thread-owners.sqlite").path, subject: scope, - codexHome: codexHome) + codexHome: CodexProcessEnvironment.vendorHome()) } private static func isAbsolutePath(_ path: String) -> Bool { diff --git a/Sources/CodexAdapter/CodexProcessEnvironment.swift b/Sources/CodexAdapter/CodexProcessEnvironment.swift index 333afe4..df64f1e 100644 --- a/Sources/CodexAdapter/CodexProcessEnvironment.swift +++ b/Sources/CodexAdapter/CodexProcessEnvironment.swift @@ -100,6 +100,9 @@ internal enum CodexProcessEnvironment { systemProxy: SystemNetworkProxySettings = .current() ) -> [String: String] { var environment = base + if base["CODEX_HOME"] == nil, let home = managedVendorHome(in: base) { + environment["CODEX_HOME"] = home.path + } for key in base.keys where parentSessionKeys.contains(key) { environment.removeValue(forKey: key) } @@ -132,6 +135,32 @@ internal enum CodexProcessEnvironment { return environment } + static func hostStateRoot(in environment: [String: String]) -> URL? { + guard environment["COMPUTER_MCP_HOST_CONTEXT"] != nil, + let state = environment["XDG_STATE_HOME"], state.hasPrefix("/"), !state.contains("\0") + else { return nil } + return URL(fileURLWithPath: state, isDirectory: true).standardizedFileURL + } + + static func vendorHome( + in environment: [String: String] = ProcessInfo.processInfo.environment + ) -> URL { + if let explicit = environment["CODEX_HOME"] { + return URL(fileURLWithPath: explicit, isDirectory: true) + } + return managedVendorHome(in: environment) + ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent( + ".codex", isDirectory: true) + } + + private static func managedVendorHome(in environment: [String: String]) -> URL? { + guard hostStateRoot(in: environment) != nil, + let home = environment["HOME"], home.hasPrefix("/"), !home.contains("\0") + else { return nil } + return URL(fileURLWithPath: home, isDirectory: true).appendingPathComponent( + ".codex", isDirectory: true) + } + private static func mirrorExistingValue( for keys: [String], in environment: inout [String: String] diff --git a/Sources/CodexAdapter/CodexRecentThreadReader.swift b/Sources/CodexAdapter/CodexRecentThreadReader.swift index 85203a7..703559b 100644 --- a/Sources/CodexAdapter/CodexRecentThreadReader.swift +++ b/Sources/CodexAdapter/CodexRecentThreadReader.swift @@ -95,15 +95,7 @@ struct CodexRecentThreadReader: Sendable { } static func live() -> CodexRecentThreadReader { - let environment = ProcessInfo.processInfo.environment - let codexHome = - environment["CODEX_HOME"].map { - URL(fileURLWithPath: $0, isDirectory: true) - } - ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent( - ".codex", - isDirectory: true - ) + let codexHome = CodexProcessEnvironment.vendorHome() return CodexRecentThreadReader( stateDatabaseURL: newestStateDatabase(in: codexHome), allowedRolloutRoot: codexHome diff --git a/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift b/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift index e23a1ab..76f38e4 100644 --- a/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift +++ b/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift @@ -256,7 +256,7 @@ private actor HostClientState { if params.name == "policy.probe" { result = .object([ "decision": .string("allowed"), "capability_id": arguments["capability_id"]!, - "project_id": .string("fixture"), "risk": .string(risk), "effective_risk": .string(risk), + "risk": .string(risk), "requirements": .object([:]), ]) } else if params.name == "host.projects.worktree_add" { return .init( diff --git a/Tests/CodexAdapterTests/CodexLaunchContextTests.swift b/Tests/CodexAdapterTests/CodexLaunchContextTests.swift index c55e3b9..d1eaffc 100644 --- a/Tests/CodexAdapterTests/CodexLaunchContextTests.swift +++ b/Tests/CodexAdapterTests/CodexLaunchContextTests.swift @@ -179,6 +179,37 @@ struct CodexLaunchContextTests { await other.shutdown() } + @Test func hostStateDefaultPreservesExplicitAndStandaloneOptions() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let configuration = CodexConfig(enabled: true, executable: "/missing/codex") + let host = try CodexLaunchContext( + environment: [ + "COMPUTER_MCP_HOST_CONTEXT": validHost, "XDG_STATE_HOME": root.path, + ], currentDirectory: root) + let managed = try #require( + try host.appServerProvider(configuration: configuration, stateDirectory: nil)) + #expect( + managed.database?.fileURL?.path + == root.appendingPathComponent("codex-adapter/codex.sqlite").path) + await managed.shutdown() + + let explicit = root.appendingPathComponent("explicit") + let standalone = try CodexLaunchContext( + environment: ["XDG_STATE_HOME": root.path], currentDirectory: root) + #expect(throws: ConfigurationError.self) { + try standalone.appServerProvider(configuration: configuration, stateDirectory: nil) + } + for context in [host, standalone] { + let provider = try #require( + try context.appServerProvider(configuration: configuration, stateDirectory: explicit)) + #expect( + provider.database?.fileURL?.path == explicit.appendingPathComponent("codex.sqlite").path) + await provider.shutdown() + } + } + private var validHost: String { #"{"formatVersion":1,"runtimeID":"B66E26EE-53AF-4455-A25D-E2BDD219798C","caller":"local-mcp","profileID":"observe","hostServiceContract":"projects-v1","project":{"id":"fixture","rootPath":"/tmp/bound-workspace"},"readOnly":true}"# } diff --git a/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift b/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift index 52851e1..b898279 100644 --- a/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift +++ b/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift @@ -33,6 +33,26 @@ final class CodexProcessEnvironmentTests { #expect(environment["PATH"] == "/usr/bin") } + @Test + func managedVendorHomeMatchesReaderAndChildEnvironment() { + var base = [ + "COMPUTER_MCP_HOST_CONTEXT": "fixture", + "HOME": "/tmp/container/home", + "XDG_STATE_HOME": "/tmp/container/state", + ] + for explicit in [nil, "/tmp/configured-codex-home"] as [String?] { + base["CODEX_HOME"] = explicit + let expected = explicit ?? "/tmp/container/home/.codex" + let child = CodexProcessEnvironment.resolved(base: base, systemProxy: .init()) + #expect(child["CODEX_HOME"] == expected) + #expect(CodexProcessEnvironment.vendorHome(in: base).path == expected) + #expect(child["COMPUTER_MCP_HOST_CONTEXT"] == nil) + } + base["COMPUTER_MCP_HOST_CONTEXT"] = nil + base["CODEX_HOME"] = nil + #expect(CodexProcessEnvironment.resolved(base: base, systemProxy: .init())["CODEX_HOME"] == nil) + } + @Test func testFixedMacOSProxiesAreMappedToConventionalCodexEnvironment() { let environment = CodexProcessEnvironment.resolved( diff --git a/Tests/Fixtures/NativeCodex/HostToolVendor.py b/Tests/Fixtures/NativeCodex/HostToolVendor.py deleted file mode 100644 index 4891549..0000000 --- a/Tests/Fixtures/NativeCodex/HostToolVendor.py +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env python3 -"""Disposable App Server protocol peer for exact native-to-host callback acceptance.""" - -import json -import os -from pathlib import Path -import stat -import sys -import threading -import time - -root = Path(os.environ["CODEX_HOME"]) -lock = threading.Lock() - - -def save(name, value): - temporary = root / (name + ".tmp") - temporary.write_text(json.dumps(value)) - temporary.replace(root / name) - - -def emit(value): - with lock: - print(json.dumps(value), flush=True) - - -def queued_callbacks(): - while True: - for path in sorted(root.glob("queued-*.json")): - value = json.loads(path.read_text()) - path.unlink() - emit(value) - time.sleep(0.01) - - -sockets = [] -for descriptor in range(3, 10): - try: - if stat.S_ISSOCK(os.fstat(descriptor).st_mode): - sockets.append(descriptor) - except OSError: - pass -save("vendor.json", {"pid": os.getpid(), "inherited_host_socket": bool(sockets), - "inherited_host_env": any(key in os.environ for key in - ("COMPUTER_MCP_HOST_FD", "COMPUTER_MCP_HOST_CONTEXT", "CODEX_THREAD_ID"))}) -for line in sys.stdin: - request = json.loads(line) - method = request.get("method") - if method == "initialize": - result = {"codexHome": str(root), "platformFamily": "unix", "platformOs": "macos", - "userAgent": "isolated-callback-fixture"} - elif method == "initialized": - threading.Thread(target=queued_callbacks, daemon=True).start() - continue - elif method == "thread/loaded/list": - result = {"data": [], "nextCursor": None} - elif method is None and isinstance(request.get("id"), int) and request["id"] >= 900: - save("callback-" + str(request["id"]) + ".json", request) - continue - elif method == "thread/unsubscribe": - result = {"status": "unsubscribed"} - elif "id" not in request: - continue - else: - emit({"id": request["id"], "error": {"code": -32601, "message": "Fixture method not implemented"}}) - continue - emit({"id": request["id"], "result": result}) diff --git a/Tests/Fixtures/NativeCodex/README.md b/Tests/Fixtures/NativeCodex/README.md index 897d981..e1a63cd 100644 --- a/Tests/Fixtures/NativeCodex/README.md +++ b/Tests/Fixtures/NativeCodex/README.md @@ -17,11 +17,3 @@ for full and fixture-only acceptance. Fixture provenance: Computer MCP commit `65921cd298783003895106b293fa6dd540e47313`, `Tests/ComputerMCPTests/Fixtures/NativeCodex/ModelServer.py`. - -`HostToolVendor.py` is a disposable protocol peer for native `item/tool/call` -forwarding. It reads queued requests from its private vendor home and records -exact replies and descriptor/environment isolation. It exercises the real -adapter and public host MCP; it does not impersonate an authenticated model. -The driver owns the Git repository and verifies tickets, side effects and -native callback results separately. This peer adapts the `vendorSource` in the -same source commit's `CodexPluginHostIntegrationTests.swift`. diff --git a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift new file mode 100644 index 0000000..b30a1b4 --- /dev/null +++ b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift @@ -0,0 +1,240 @@ +import ComputerMCPConfiguration +import ComputerMCPCore +import ComputerMCPGateway +import ComputerMCPMacOS +import ComputerMCPPermissions +import ComputerMCPPlatform +import ComputerMCPPlugins +import Darwin +import Foundation + +@main +struct RegisteredHost { + private enum FixtureError: Error { + case invalidArguments, invalidRegistration, missingEpoch, invalidPeerMessage + } + + static func main() async throws { + let arguments = Array(CommandLine.arguments.dropFirst()) + switch arguments.first { + case "--version": + print(ComputerMCPCLI.version) + case "app-server": + try runPeer() + case "register", "serve": + guard arguments.count == 2 else { throw FixtureError.invalidArguments } + let root = URL(fileURLWithPath: arguments[1], isDirectory: true).resolvingSymlinksInPath() + try await run(root: root, register: arguments[0] == "register") + default: + throw FixtureError.invalidArguments + } + } + + private static func run(root: URL, register: Bool) async throws { + let database = try GatewayDatabase(path: root.appendingPathComponent("host.sqlite").path) + _ = database.permissionStore( + counter: FixtureEpochCounter(file: root.appendingPathComponent("fixture-epoch.json"))) + var platform = MacOSPlatform.services + platform.permissionPolicyReader = FixturePolicySources() + let store = PluginStore(database: database, platform: platform) + let configuration = try GatewayConfiguration.load( + path: root.appendingPathComponent("host.toml").path, + knownPluginMCPServerIDs: database.pluginStoreSnapshot().knownMCPRegistrationIDs) + try database.bootstrapPermissionProfiles( + configuration.profiles.map(\.grant), declarations: configuration.profiles.map(\.grant)) + try database.registerManifestProjectsForStartup(configuration.manifestProjects) + let permissionRuntime = try database.permissionRuntime(platform: platform) + try await permissionRuntime.ready() + if register { + try await registerPlugin( + root: root, database: database, store: store, permissionRuntime: permissionRuntime, + configuration: configuration) + return + } + let context = ExecutionContext( + caller: configuration.runtime.caller, profileID: configuration.runtime.profileID, + projectID: configuration.runtime.defaultProjectID, + transportTrace: .init(transport: "stdio", socketConnectionID: UUID().uuidString), + trustedPrincipalID: "registered-codex-fixture") + let gateway = try await GatewayRuntime.make( + configuration: configuration, context: context, database: database, platform: platform, + bundledPlugins: .init(packages: [], issues: [])) + try await MCPRuntimeAdapter.runStdioGateway(configuration: configuration, registry: gateway) + } + + private static func registerPlugin( + root: URL, database: GatewayDatabase, store: PluginStore, + permissionRuntime: GatewayPermissionRuntime, configuration: GatewayConfiguration + ) async throws { + let source = root.appendingPathComponent("plugin", isDirectory: true) + let package = try PluginPackage.load(at: source) + let registered = try await store.registerDevelopment( + at: source, expectedRevision: store.snapshot().revision) + guard package.manifest.id == "codex", var settings = registered.settings["codex"], + !settings.enabled + else { throw FixtureError.invalidRegistration } + + let identity = PluginIdentity.package("codex") + let container = try database.prepareProviderContainer(identity).sandbox + let configFile = URL(fileURLWithPath: container.home.value, isDirectory: true) + .appendingPathComponent("adapter.json") + let contribution = try JSONDecoder().decode( + PluginMCPSettings.self, + from: Data(contentsOf: root.appendingPathComponent("contribution.json"))) + settings.mcp["app-server"] = contribution + settings.mcp["app-server"]?.args = ["--config", configFile.path] + _ = try await store.setSettings(settings, for: "codex", expectedRevision: registered.revision) + + let owner = try GatewayPermissionOwner( + context: .init( + caller: .localApp, profileID: .localAdmin, trustedPrincipalID: "fixture-owner"), + validate: {}) + let view = try permissionRuntime.service.view(owner: owner) + guard let epoch = view.epoch else { throw FixtureError.missingEpoch } + let review = try GatewayProviderReview( + package: package, configuration: database.configurationState()) + var permissions = Permissions() + let reviewedProjects = configuration.profileGrant(for: configuration.runtime.profileID) + .permissions + for id in ["primary", "other"] { + let project = Permission.project(id) + guard let level = reviewedProjects.entries[project] else { + throw FixtureError.invalidRegistration + } + try permissions.set(level, for: project) + } + let approval = try permissionRuntime.service.approveProvider( + review, permissions: permissions, fullAccess: false, owner: owner, + expectedProviderRevision: nil, expectedRevision: view.revision, expectedEpoch: epoch) + guard approval.enabled, approval.sourceDigest == review.sourceDigest else { + throw FixtureError.invalidRegistration + } + let receipt = [ + "home": container.home.value, "cache": container.cache.value, "state": container.state.value, + "config": configFile.path, "manifest_digest": review.sourceDigest, + ] + print(String(decoding: try JSONEncoder().encode(receipt), as: UTF8.self)) + } + + private static func runPeer() throws { + let environment = ProcessInfo.processInfo.environment + guard let path = environment["CODEX_HOME"] else { throw FixtureError.invalidPeerMessage } + let home = URL(fileURLWithPath: path, isDirectory: true) + let marker = home.appendingPathComponent("peer-count") + let count = + FileManager.default.fileExists(atPath: marker.path) + ? Int(try String(contentsOf: marker, encoding: .utf8)) : 0 + guard let count else { throw FixtureError.invalidPeerMessage } + try String(count + 1).write(to: marker, atomically: true, encoding: .utf8) + + func save(_ value: [String: Any], to name: String) throws { + try JSONSerialization.data(withJSONObject: value).write( + to: home.appendingPathComponent(name), options: .atomic) + } + func emit(_ value: [String: Any]) throws { + let data = try JSONSerialization.data(withJSONObject: value) + try FileHandle.standardOutput.write(contentsOf: data + Data([0x0A])) + } + let inherited = [ + "COMPUTER_MCP_HOST_CONTEXT", "COMPUTER_MCP_HOST_FD", + "COMPUTER_MCP_HOST_READ_HANDLE", "COMPUTER_MCP_HOST_WRITE_HANDLE", "CODEX_THREAD_ID", + ].contains { environment[$0] != nil } + let sockets = (3..<32).contains { fd in + var info = stat() + return fstat(Int32(fd), &info) == 0 && info.st_mode & S_IFMT == S_IFSOCK + } + try save( + [ + "pid": ProcessInfo.processInfo.processIdentifier, "count": count + 1, + "home": environment["HOME"] ?? "", "cache": environment["XDG_CACHE_HOME"] ?? "", + "state": environment["XDG_STATE_HOME"] ?? "", "codex_home": path, + "inherited_host_env": inherited, "inherited_host_socket": sockets, + ], to: "vendor.json") + + var awaiting: (callbackID: Int, requestID: Any)? + let loaded: [String: Any] = ["data": [], "nextCursor": NSNull()] + while let line = readLine() { + guard let request = try JSONSerialization.jsonObject(with: Data(line.utf8)) as? [String: Any] + else { throw FixtureError.invalidPeerMessage } + guard let id = request["id"] else { continue } + switch request["method"] as? String { + case "initialize": + try emit([ + "id": id, + "result": [ + "codexHome": path, "platformFamily": "unix", "platformOs": "macos", + "userAgent": "registered-codex-fixture", + ], + ]) + case "thread/loaded/list": + let queued = home.appendingPathComponent("queued.json") + if FileManager.default.fileExists(atPath: queued.path), + let callback = try JSONSerialization.jsonObject(with: Data(contentsOf: queued)) + as? [String: Any], let callbackID = callback["id"] as? Int + { + try FileManager.default.removeItem(at: queued) + awaiting = (callbackID, id) + try emit(callback) + } else { + try emit(["id": id, "result": loaded]) + } + case nil: + guard let pending = awaiting, id as? Int == pending.callbackID else { + throw FixtureError.invalidPeerMessage + } + try save(request, to: "callback-\(pending.callbackID).json") + awaiting = nil + try emit(["id": pending.requestID, "result": loaded]) + default: + try emit(["id": id, "error": ["code": -32601, "message": "Unsupported fixture method"]]) + } + } + } +} + +private struct FixtureEpochCounter: AuthorizationEpochCounter { + private let access: Access + + init(file: URL) { access = Access(file: file) } + + func withExclusiveAccess( + _ body: (any AuthorizationEpochCounterAccess) throws -> Result + ) throws -> Result { + let fd = open(access.file.path + ".lock", O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_RDWR, 0o600) + guard fd >= 0 else { throw AuthorizationEpochCounterError.unavailable } + defer { close(fd) } + guard flock(fd, LOCK_EX) == 0 else { throw AuthorizationEpochCounterError.unavailable } + return try body(access) + } + + private struct Access: AuthorizationEpochCounterAccess { + let file: URL + + func read() throws -> AuthorizationEpochWatermark? { + guard FileManager.default.fileExists(atPath: file.path) else { return nil } + return try JSONDecoder().decode( + AuthorizationEpochWatermark.self, from: Data(contentsOf: file)) + } + + func advance(to watermark: AuthorizationEpochWatermark) throws { + if let previous = try read(), + previous.databaseID != watermark.databaseID || previous.revision >= watermark.revision + { + throw AuthorizationEpochCounterError.nonMonotonicWrite + } + try JSONEncoder().encode(watermark).write(to: file, options: .atomic) + } + } +} + +private struct FixturePolicySources: ManagedPolicyReading { + func canonicalPolicyPath(_ path: String) throws -> String { + URL(fileURLWithPath: path).resolvingSymlinksInPath().path + } + + func readSources() -> [ManagedPolicySourceSnapshot] { + ManagedPolicySourceID.allCases.map { + .init(source: $0, location: "fixture/" + $0.rawValue, status: .absent) + } + } +} diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index 1d64b1b..daf3fe3 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -38,6 +38,15 @@ def test_fixture_arguments_do_not_launch_or_create_state(self): self.assertEqual(parsed.mode, "fixture") self.assertFalse(parsed.output_directory.exists()) + def test_container_mode_requires_only_the_registered_fixture_and_adapter(self): + arguments = self.arguments[:-4] + self.arguments[-2:] + ["--mode", "container"] + options = acceptance.parse_arguments(arguments) + self.assertIsNone(options.codex) + self.assertFalse(options.output_directory.exists()) + self.invalid(self.arguments + ["--mode", "container"]) + self.invalid(arguments + ["--model", "unused"]) + self.invalid(arguments[:-2] + ["--mode", "fixture"]) + def test_full_requires_explicit_authentication_and_model(self): self.invalid(self.arguments) auth = self.root / "auth.json" @@ -145,7 +154,7 @@ def fail_configuration(*args, **kwargs): launch = stack.enter_context(patch.object(acceptance.subprocess, "Popen", side_effect=AssertionError("Unexpected process launch"))) for phase in ("setup", "catalog_and_diagnostics", "directories", "native_permissions", "handoff", - "sibling_workspace", "recovery", "app_lifecycle", "exec_lifecycle", "host_callbacks"): + "sibling_workspace", "recovery", "app_lifecycle", "exec_lifecycle"): stack.enter_context(patch.object(fixture, phase)) configure = stack.enter_context(patch.object(fixture, "configure", side_effect=fail_configuration)) stack.enter_context(contextlib.redirect_stdout(output)) diff --git a/scripts/check-host.py b/scripts/check-host.py index 1b3e30e..c04e65a 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 -"""Accept a packaged adapter through an installed Computer MCP CLI's public MCP surface. +"""Accept a packaged adapter through a source-built registered Computer MCP gateway. -Fixture mode uses real native Codex with a private loopback Responses server. +Container mode uses a deterministic protocol peer. Fixture mode uses native +Codex with a private loopback Responses server. Full mode additionally requires authenticated model execution. All host instances, workspaces, runtime homes and failure injection targets are private to this run. """ @@ -13,6 +14,7 @@ from pathlib import Path import queue import re +import shutil import signal import subprocess import sys @@ -20,7 +22,9 @@ import time import uuid -MODEL_SOURCE = Path(__file__).resolve().parents[1] / "Tests/Fixtures/NativeCodex/ModelServer.py" +REPOSITORY = Path(__file__).resolve().parents[1] +MODEL_SOURCE = REPOSITORY / "Tests/Fixtures/NativeCodex/ModelServer.py" +REGISTERED_HOST_SOURCE = REPOSITORY / "Tests/Fixtures/RegisteredHost/RegisteredHost.swift" MAX_MESSAGE = 8_388_608 @@ -55,11 +59,11 @@ def timeout_seconds(value): def parse_arguments(arguments=None): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--host", required=True, type=executable, help="Installed computer-mcp CLI") + parser.add_argument("--host", required=True, type=executable, help="Source-built CodexRegisteredHost fixture") parser.add_argument("--adapter", required=True, type=executable, help="Adapter from the verified, relocated archive") - parser.add_argument("--codex", required=True, type=executable, help="User-installed vendor Codex") + parser.add_argument("--codex", type=executable, help="Native modes: user-installed vendor Codex") parser.add_argument("--output-directory", required=True, type=Path, help="New private directory in ignored build output") - parser.add_argument("--mode", choices=("fixture", "full"), default="full") + parser.add_argument("--mode", choices=("container", "fixture", "full"), default="full") parser.add_argument("--auth-file", type=absolute_file, help="Full mode: existing vendor auth.json; copied privately and deleted on exit") parser.add_argument("--model", help="Full mode: authenticated model ID") parser.add_argument("--timeout-seconds", type=timeout_seconds, default=180) @@ -67,9 +71,13 @@ 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") + if options.mode == "container" and options.codex: + parser.error("Container mode uses only the disposable protocol peer") + if options.mode != "container" and not options.codex: + parser.error("Native modes require --codex") if options.mode == "full" and (not options.auth_file or not options.model or not options.model.strip()): parser.error("Full mode requires --auth-file and --model") - if options.mode == "fixture" and (options.auth_file or options.model): + if options.mode != "full" and (options.auth_file or options.model): parser.error("Authentication inputs require full mode") if options.model and any(c in options.model for c in "\0\r\n"): parser.error("Model ID must be a single nonempty line") @@ -239,16 +247,19 @@ def __init__(self, fixture, indirect=True): fixture.generation += 1 self.log = (fixture.root / f"host-{fixture.generation}.log").open("w") self.evidence = (fixture.root / f"protocol-{fixture.generation}.jsonl").open("w") - self.process = subprocess.Popen([str(fixture.options.host), "serve", "stdio", "--config", - str(fixture.root / "host.toml"), "--database", str(fixture.root / "host.sqlite")], + self.process = subprocess.Popen([str(fixture.options.host), "serve", str(fixture.root)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, text=True, bufsize=1, env=fixture.environment, cwd=fixture.root) fixture.hosts.append(self) self.client = MCPClient(self.process, self.evidence, fixture.options.timeout_seconds) - self.catalog = self.client.initialize() - require(set(RISKS) <= self.catalog.keys(), {"missing_tools": sorted(set(RISKS) - self.catalog.keys())}) - require(self.catalog["mcp.tools.call"]["inputSchema"]["properties"]["workspace_id"]["type"] == "string", - "Generic dispatch lacks workspace selection") + gateway_catalog = self.client.initialize() + tools = unwrap(self.client.send("tools/call", { + "name": "mcp.tools.list", "arguments": {"server": "codex"}, + })) + self.catalog = {tool["name"]: tool for tool in tools} if indirect else 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", + "Generic dispatch lacks project selection") def raw(self, name, arguments=None, timeout=None): name = name if name.startswith("codex.") else "codex.app." + name @@ -256,9 +267,9 @@ def raw(self, name, arguments=None, timeout=None): require(set(arguments) <= self.catalog[name]["inputSchema"]["properties"].keys(), {"tool": name, "undeclared_inputs": sorted(set(arguments) - self.catalog[name]["inputSchema"]["properties"].keys())}) if self.indirect: params = {"name": "mcp.tools.call", "arguments": {"server": "codex", "tool": name, - "workspace_id": self.workspace, "arguments": arguments}} + "project_id": self.workspace, "arguments": arguments}} else: - params = {"name": name, "arguments": dict(arguments, workspace_id=self.workspace)} + params = {"name": name, "arguments": dict(arguments, project_id=self.workspace)} result = self.client.send("tools/call", params, timeout=timeout) return unwrap(result) if self.indirect else result @@ -344,10 +355,17 @@ def __init__(self, options): self.generation = 0 self.model = None self.model_log = None + self.container = None + self.adapter_config = self.root / "adapter.json" + self.launches = self.root / "launches.jsonl" + self.risks = RISKS + if options.mode == "container": + self.risks = {name: RISKS[name] for name in ( + "codex.app.status", "codex.app.thread.loaded.list", "codex.diagnostics.snapshot")} self.home = self.root / "codex-home" self.home.mkdir(mode=0o700) # Private HOME also isolates Git, native skills, hooks and host configuration. - self.environment = {"HOME": str(self.root), "PATH": str(options.codex.parent) + ":/usr/bin:/bin", + self.environment = {"HOME": str(self.root), "PATH": "/usr/bin:/bin", "TMPDIR": str(self.root / "tmp"), "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"} (self.root / "tmp").mkdir(mode=0o700) @@ -355,17 +373,23 @@ def __init__(self, options): def setup(self): for name in ("primary", "other"): (self.root / name).mkdir() + if self.options.mode == "container": + continue self.git(["init", "--quiet"], name) for key, value in (("user.name", "Acceptance"), ("user.email", "acceptance@example.invalid"), ("commit.gpgsign", "false"), ("core.hooksPath", str(self.root / name / ".git/hooks"))): self.git(["config", key, value], name) - wrapper = self.root / "configured-codex" + self.register() + if self.options.mode == "container": + self.configure_adapter(self.peer, exec_enabled=False) + return + wrapper = self.package / "bin/configured-codex" wrapper.write_text(f'''#!{sys.executable} import json, os, sys keys = ("COMPUTER_MCP_HOST_CONTEXT", "COMPUTER_MCP_HOST_FD", "CODEX_THREAD_ID") assert not any(key in os.environ for key in keys), "Parent authority leaked" -assert os.environ.get("COMPUTER_MCP_FIXTURE_VALUE") == "preserved", "Ordinary environment lost" -with open({str(self.root / 'launches.jsonl')!r}, "a") as receipt: +assert os.environ.get("CODEX_HOME") == {str(self.home)!r}, "Wrong vendor container" +with open({str(self.launches)!r}, "a") as receipt: receipt.write(json.dumps({{"mode": sys.argv[1], "cwd": os.getcwd(), "argv": sys.argv[1:], "pid": os.getpid()}}) + "\\n") os.execv({str(self.options.codex)!r}, [{str(self.options.codex)!r}] + sys.argv[1:]) ''') @@ -402,50 +426,79 @@ def configure(self, sandbox="danger-full-access", approval="never", authenticate ''' config += '[analytics]\nenabled = false\n[otel]\nmetrics_exporter = "none"\n' (self.home / "config.toml").write_text(config) - (self.root / "adapter.json").write_text(json.dumps({ - "enabled": True, "executable": "configured-codex", "app_server_enabled": True, - "exec_enabled": True, "app_server_request_timeout_seconds": 30, + self.configure_adapter(self.package / "bin/configured-codex", exec_enabled=True) + + def configure_adapter(self, vendor, exec_enabled): + self.adapter_config.write_text(json.dumps({ + "enabled": True, "executable": str(vendor), "app_server_enabled": True, + "exec_enabled": exec_enabled, "app_server_request_timeout_seconds": 30, "app_server_app_list_timeout_seconds": 120, })) - policies = ", ".join(q(name) + " = " + q(risk) for name, risk in RISKS.items()) + + def register(self): + q = json.dumps + self.package = self.root / "plugin" + bin_directory = self.package / "bin" + bin_directory.mkdir(parents=True) + manifest = REPOSITORY / "computer-mcp-plugin.toml" + shutil.copy2(manifest, self.package / manifest.name) + shutil.copy2(self.options.adapter, bin_directory / "codex-mcp-adapter") + resources = self.options.adapter.with_name("codex-plugin_CodexAdapter.bundle") + shutil.copytree(resources, bin_directory / resources.name) + self.peer = bin_directory / "fixture-vendor" + if self.options.mode == "container": + shutil.copy2(self.options.host, self.peer) + + access = "read" if self.options.mode == "container" else "write" config = f'''schema_version = 1 [runtime] caller = "local-mcp" profile = "acceptance" +project_id = "primary" + [[profiles]] id = "acceptance" -mode = "local-full-access" -confirmation_policy = "never" -full_shell_enabled = true -capabilities = ["mcp.tools.call", "workspace.list"] -workspaces = ["primary", "other"] allowed_callers = ["local-mcp"] +full_access = false + +[profiles.projects] +primary = {{ access = "{access}", network = "none" }} +other = {{ access = "{access}", network = "none" }} + +[profiles.plugins] +codex = "use" + +[builtin] +enabled = ["file.read"] ''' for name in ("primary", "other"): - config += f'''[[workspaces]] + config += f'''[[projects]] id = {q(name)} display_name = {q(name)} path = {q(str(self.root / name))} -''' - config += f'''[[mcp.servers]] -id = "codex" -transport = "stdio" -command = {q(str(self.options.adapter))} -args = ["--config", {q(str(self.root / 'adapter.json'))}, "--state-directory", {q(str(self.root / 'adapter-state'))}] -exposure = "reexport" -prefix = "" -allowed_tools = {q(list(RISKS))} -host_services = true -tool_risks = {{ {policies} }} -startup_timeout_ms = 10000 -request_timeout_ms = {max(130, self.options.timeout_seconds) * 1000} -[mcp.servers.env] -CODEX_HOME = {q(str(self.home))} -PATH = {q(str(self.root) + os.pathsep + self.environment['PATH'])} -CODEX_THREAD_ID = "acceptance-parent-session" -COMPUTER_MCP_FIXTURE_VALUE = "preserved" ''' (self.root / "host.toml").write_text(config) + (self.root / "contribution.json").write_text(json.dumps({ + "registrationID": "codex", "exposure": "gateway" if self.options.mode == "container" else "reexport", + "prefix": "", + "hostServices": True, "allowedTools": list(self.risks), + "toolRisks": {name: "project-write" if risk == "workspace-write" else risk + for name, risk in self.risks.items()}, + })) + result = subprocess.run([str(self.options.host), "register", str(self.root)], + env=self.environment, cwd=self.root, capture_output=True, text=True, + timeout=self.options.timeout_seconds) + (self.root / "registration.log").write_text(result.stderr) + require(result.returncode == 0, {"registration_exit": result.returncode, "stderr": result.stderr}) + self.container = json.loads(result.stdout) + for key in ("home", "cache", "state", "config"): + require(Path(self.container[key]).is_relative_to(self.root / "host.sqlite.providers"), + {"invalid_container_path": key}) + (self.root / "registration.json").write_text(json.dumps(self.container, indent=2) + "\n") + self.home = Path(self.container["home"]) / ".codex" + self.home.mkdir(mode=0o700) + self.adapter_config = Path(self.container["config"]) + self.launches = self.home / "launches.jsonl" def git(self, args, workspace="primary"): return subprocess.run(["/usr/bin/git", *args], cwd=self.root / workspace, env=self.environment, @@ -475,18 +528,18 @@ def record(self, name): def catalog_and_diagnostics(self): host = Host(self) - require(not (self.root / "launches.jsonl").exists(), "Discovery started the vendor") + require(not self.launches.exists(), "Discovery started the vendor") diagnostic = host.call("codex.diagnostics.snapshot", {"limit": 10}) require(diagnostic["persistence_available"] and diagnostic["host_diagnostics_available"], diagnostic) require(diagnostic["state_storage"]["scope"] == "authorization_subject", diagnostic) - require(not (self.root / "launches.jsonl").exists(), "Diagnostics started the vendor") + require(not self.launches.exists(), "Diagnostics started the vendor") host.call("codex.run.list") host.call("codex.worktree.managed.list") host.call("codex.worktree.leases.list") lease = host.call("codex.worktree.leases.acquire", {"agent_id": "acceptance"}) host.call("codex.worktree.leases.release", {"lease_id": lease["id"], "expected_revision": lease["revision"], "reason": "Acceptance complete"}) - require(not (self.root / "launches.jsonl").exists(), "Domain lease operations started the vendor") + require(not self.launches.exists(), "Domain lease operations started the vendor") host.close() self.record("catalog-diagnostics-domain-leases-lazy-start") @@ -630,7 +683,7 @@ def retired(): def app_lifecycle(self): self.configure(sandbox="workspace-write", approval="on-request") - config = self.root / "adapter.json" + config = self.adapter_config settings = json.loads(config.read_text()) settings.update(sandbox="workspace-write", approval_policy="untrusted") config.write_text(json.dumps(settings)) @@ -682,7 +735,7 @@ def exec_lifecycle(self): page = host.call("codex.exec.events", {"session_id": session, "after_cursor": 0, "max_results": 1000}) require(page["missed_events"] == 0 and page["events"], page) host.call("codex.exec.release", {"session_id": session}) - launches = [json.loads(line) for line in (self.root / "launches.jsonl").read_text().splitlines()] + launches = [json.loads(line) for line in self.launches.read_text().splitlines()] exec_launches = [entry for entry in launches if entry["mode"] == "exec"] require(len(exec_launches) == 2, exec_launches) inherited, explicit = (entry["argv"] for entry in exec_launches) @@ -708,102 +761,70 @@ def exec_lifecycle(self): self.response("cleanup") self.record("exec-defaults-overrides-events-result-resume-cancel-release") - def host_callbacks(self): - source = MODEL_SOURCE.with_name("HostToolVendor.py") - vendor = self.root / "host-tool-vendor" - vendor.write_text("#!" + sys.executable + "\n" + source.read_text().split("\n", 1)[1]) - vendor.chmod(0o700) - sequence = 900 - - def callback(name, arguments, success=True, request_error=None): - nonlocal sequence - sequence += 1 - request = {"id": sequence, "method": "item/tool/call", "params": { - "namespace": "computer-mcp", "tool": name, "arguments": arguments, - "callId": f"callback-{sequence}", "threadId": "callback-thread", "turnId": "callback-turn"}} - temporary = self.home / "queued.tmp" - temporary.write_text(json.dumps(request)) - temporary.replace(self.home / f"queued-{sequence}.json") - response = self.home / f"callback-{sequence}.json" - wait_until(response.exists, 15, "Native host callback") - value = json.loads(response.read_text()) - if request_error: - require(value.get("error") == request_error, value) - return value - require(value.get("result", {}).get("success") is success, value) - if not success: - return value - text = value["result"]["contentItems"][0]["text"] - return unwrap(json.loads(text)) - - for confirmation in ("never", "all-writes"): - self.configure() - config = self.root / "adapter.json" - settings = json.loads(config.read_text()) - settings["executable"] = str(vendor) - config.write_text(json.dumps(settings)) - host_config = self.root / "host.toml" - text = host_config.read_text().replace('confirmation_policy = "never"', - 'confirmation_policy = "' + confirmation + '"') - text = text.replace('capabilities = ["mcp.tools.call", "workspace.list"]', - 'capabilities = ["mcp.tools.call", "workspace.list", "policy.probe", ' - '"operations.prepare", "operations.commit", "file.read", "file.write", "git.add", "git.commit"]') - text += '\n[[cli.commands]]\nid = "git"\nexecutable = "/usr/bin/git"\n' - text += '\n[builtin]\nenabled = ["file.read", "file.write", "git.add", "git.commit"]\n' - host_config.write_text(text) + def registered_container(self): + marker = "caller project fixture\n" + sibling = "sibling project fixture\n" + (self.root / "primary/product.txt").write_text(marker) + (self.root / "other/product.txt").write_text(sibling) + vendor_receipt = self.home / "vendor.json" + prior_vendor = prior_runtime = None + for generation in (1, 2): host = Host(self) - host.call("thread.loaded.list") - receipt = json.loads((self.home / "vendor.json").read_text()) - require(not receipt["inherited_host_env"] and not receipt["inherited_host_socket"], receipt) - self.pids.add(receipt["pid"]) - callback("file.read", {"workspace_id": "other", "path": "product.txt"}, success=False) - callback("codex.app.status", {}, request_error={"code": -32001, - "message": "This App Server request is not part of the supported coding contract."}) - if confirmation == "never": - (self.root / "primary/product.txt").write_text("governed-native\n") - index = self.root / "primary/.git/index" - before = index.read_bytes() - staged = self.git(["diff", "--cached", "--name-only"]) - callback("git.add", {"paths": ["product.txt"], "dry_run": True}) - require(index.read_bytes() == before and self.git(["diff", "--cached", "--name-only"]) == staged, - "Native dry-run callback changed the index") - require(host.call("approvals.list", {"state": "pending"})["approvals"] == [], - "Host dry-run created native approval") - (self.root / "primary/product.txt").unlink() - # Keep all acceptance artifacts out of this exact Git workflow's status. - (self.root / "primary/.git/info/exclude").write_text("*\n!product.txt\n") - hook = self.root / "primary/.git/hooks/pre-commit" - hook.write_text("#!/bin/sh\n/usr/bin/touch .git/callback-hook-ran\n") - hook.chmod(0o700) - steps = [("file.write", {"path": "product.txt", "content": "governed-native\n"}), - ("git.add", {"paths": ["product.txt"]}), - ("git.commit", {"message": "Governed native callback acceptance"})] - for tool, arguments in steps: - ticket = callback("operations.prepare", {"tool": tool, "arguments": arguments})["ticket_id"] - if tool == "file.write": - require(not (self.root / "primary/product.txt").exists(), "Prepare executed the write") - elif tool == "git.add": - require(not self.git(["diff", "--cached", "--name-only"]), "Prepare staged files") - else: - require(not (self.root / "primary/.git/callback-hook-ran").exists(), "Prepare committed") - commit = {"tool": tool, "arguments": arguments, "ticket_id": ticket} - callback("operations.commit", dict(commit, ticket_id="unrelated-ticket"), success=False) - callback("operations.commit", commit) - callback("operations.commit", commit, success=False) - require((self.root / "primary/.git/callback-hook-ran").exists(), "Callback Git hook did not run") - require(self.git(["show", "HEAD:product.txt"]) == "governed-native\n", "Callback commit content differs") - require(not self.git(["status", "--porcelain"]), "Callback worktree is not clean") + initial = host.call("codex.diagnostics.snapshot") + require(initial["host_diagnostics_available"] and initial["persistence_available"], initial) + require(initial["state_storage"]["scope"] == "authorization_subject", initial) + require(initial["scope"]["project_id"] == "primary" + and initial["scope"]["principal_id"] == "registered-codex-fixture", initial) + if prior_runtime: + require(any(row["id"] == prior_runtime for row in initial["persisted_runtimes"]), initial) + require(not vendor_receipt.exists() or json.loads(vendor_receipt.read_text()) == prior_vendor, + "Catalog or diagnostics launched the peer") + + request_id = 900 + generation + arguments = {"path": "product.txt"} + if generation == 2: + arguments["project_id"] = "other" + request = {"id": request_id, "method": "item/tool/call", "params": { + "namespace": "computer-mcp", "tool": "file.read", "arguments": arguments, + "callId": f"fixture-read-{generation}", "threadId": "fixture-thread", "turnId": "fixture-turn"}} + (self.home / "queued.json").write_text(json.dumps(request)) + loaded = host.call("thread.loaded.list") + require(loaded["data"] == [], loaded) + vendor = json.loads(vendor_receipt.read_text()) + self.pids.add(vendor["pid"]) + response = json.loads((self.home / f"callback-{request_id}.json").read_text()) + require(response["id"] == request_id and "error" not in response, response) + callback = response["result"] + require(callback["success"] is (generation == 1), callback) + content = json.loads(callback["contentItems"][0]["text"]) + if generation == 1: + require(unwrap(content)["content"] == marker, content) + execution = content["structuredContent"]["gateway_execution"] + require(all(execution[key] == initial["scope"][key] + for key in ("project_id", "profile_id", "caller", "socket_connection_id")), execution) else: - arguments = {"path": "pending.txt", "content": "must require local approval"} - prepared = callback("operations.prepare", {"tool": "file.write", "arguments": arguments}) - require("pending_approval" in json.dumps(prepared), prepared) - callback("operations.commit", {"tool": "file.write", "arguments": arguments, - "ticket_id": prepared["ticket_id"]}, success=False) - require(not (self.root / "primary/pending.txt").exists(), "Pending host ticket was consumed") + require("bound connection scope" in content["error"] and sibling not in json.dumps(content), content) + + require(vendor["count"] == generation and vendor["codex_home"] == str(self.home), vendor) + require(all(vendor[key] == self.container[key] for key in ("home", "cache", "state")), vendor) + require(not vendor["inherited_host_env"] and not vendor["inherited_host_socket"], vendor) + require(prior_vendor is None or vendor["pid"] != prior_vendor["pid"], vendor) host.processes() + snapshot = host.call("codex.diagnostics.snapshot") + if generation == 1: + reads = [row for row in snapshot["recent_tool_audits"] + if row["capability_id"] == "file.read" and row["request_id"] == execution["request_id"]] + require(any(row["decision"] == "allowed" + and row["socket_connection_id"] == execution["socket_connection_id"] + for row in reads), reads) + prior_runtime = host.call("status")["runtime_id"] + prior_vendor = vendor + (self.root / f"vendor-{generation}.json").write_text(json.dumps(vendor, indent=2) + "\n") host.close() - self.configure() - self.record("native-host-callback-scope-dry-run-exact-tickets-hooked-git-and-pending-approval") + wait_until(lambda: exited(vendor["pid"]), 15, "Fixture peer exit") + require(list(Path(self.container["state"]).glob("codex-adapter/subjects/*/codex.sqlite")), + "Adapter records are missing in the injected state directory") + self.record("registered-container-vendor-and-adapter-persistence-and-caller-scoped-read") def authenticated(self): with self.options.auth_file.open("rb") as source: @@ -894,7 +915,7 @@ def cleanup(self): except Exception as error: errors.append(f"Model log cleanup: {error}") try: - launches = self.root / "launches.jsonl" + launches = self.launches if launches.exists(): entries = [json.loads(line) for line in launches.read_text().splitlines()] self.pids.update(entry["pid"] for entry in entries) @@ -923,28 +944,30 @@ def run(options): report = {"schema_version": 1, "mode": options.mode, "passed": False, "authenticated_model_verified": False, "steps": fixture.steps, "binaries": {key: {"path": str(getattr(options, key)), "sha256": digest(getattr(options, key))} - for key in ("host", "adapter", "codex")}, - "fixture_sha256": {source.name: digest(source) for source in - (MODEL_SOURCE, MODEL_SOURCE.with_name("HostToolVendor.py"))}} + for key in ("host", "adapter", "codex") if getattr(options, key)}, + "fixture_sha256": {source.name: digest(source) for source in ( + MODEL_SOURCE, REGISTERED_HOST_SOURCE)}} try: fixture.setup() - for key in ("host", "adapter", "codex"): + for key in report["binaries"]: result = subprocess.run([str(getattr(options, key)), "--version"], text=True, capture_output=True, timeout=10, check=True, env=fixture.environment) report["binaries"][key]["version"] = result.stdout.strip() - fixture.catalog_and_diagnostics() - fixture.directories() - fixture.native_permissions() - fixture.handoff() - fixture.sibling_workspace() - fixture.recovery() - fixture.app_lifecycle() - fixture.exec_lifecycle() - fixture.host_callbacks() - if options.mode == "full": - fixture.authenticated() - report["authenticated_model_verified"] = True - fixture.archive_threads() + if options.mode == "container": + fixture.registered_container() + else: + fixture.catalog_and_diagnostics() + fixture.directories() + fixture.native_permissions() + fixture.handoff() + fixture.sibling_workspace() + fixture.recovery() + fixture.app_lifecycle() + fixture.exec_lifecycle() + if options.mode == "full": + fixture.authenticated() + report["authenticated_model_verified"] = True + fixture.archive_threads() report["passed"] = True except Exception as error: report["failure"] = str(error) From 2a2efda6f3a0f1b993eba9dddbad15c9a56443a8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:05:06 +0800 Subject: [PATCH 05/25] test(integration): accept Codex against pinned Host sources --- .github/computer-mcp-host.sha | 1 + .github/workflows/ci.yml | 23 +- Documentation/Reference/Release.md | 96 ++-- .../RegisteredHost/RegisteredHost.swift | 152 +++++- Tests/test_host_acceptance.py | 80 ++- scripts/check-host.py | 493 ++++++++++++++++-- 6 files changed, 713 insertions(+), 132 deletions(-) create mode 100644 .github/computer-mcp-host.sha diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha new file mode 100644 index 0000000..fc0ed8c --- /dev/null +++ b/.github/computer-mcp-host.sha @@ -0,0 +1 @@ +42eb815c4be435f3f4f9d191fc6ac0927f23fe83 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 38bf356..03fce09 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ concurrency: jobs: package: runs-on: macos-latest - timeout-minutes: 30 + timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -63,12 +63,29 @@ jobs: 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 + - name: Accept the release archive against the pinned Host source run: | - python3 scripts/package.py --output dist --configuration release - python3 scripts/check-package.py --archive dist/codex-plugin-macos-arm64.zip --receipt dist/receipt.json --destination .build/accepted-package + host_revision=$(cat .github/computer-mcp-host.sha) + [[ "$host_revision" =~ ^[0-9a-f]{40}$ && "$host_revision" != 0000000000000000000000000000000000000000 ]] + host_checkout="$PWD/.build/computer-mcp-host" + 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" + - name: Record registered Host acceptance + if: always() + run: | + report=.build/host-acceptance/runtime/report.json + if [[ -f "$report" ]]; then + cat "$report" + fi - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: codex-plugin-macos-arm64-${{ github.sha }} diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index 9581790..abfcd79 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -97,37 +97,49 @@ and catalog notification are separate jobs. ### Runtime acceptance -Use macOS, Python 3.11 or newer, Git and the verified release archive. Record -both source revisions and the executable digests. Run the ordinary checks in -[Contributing](../../CONTRIBUTING.md) first. +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 +in [the Host pin](../../.github/computer-mcp-host.sha), a clean plugin checkout, +and the ZIP and receipt from that plugin candidate: ```sh -python3 scripts/check-package.py --archive --receipt \ - --destination .build/accepted-package -python3 scripts/check-workflow.py \ - --adapter "$PWD/.build/accepted-package/bin/codex-mcp-adapter" \ - --codex /absolute/path/to/codex python3 scripts/check-host.py \ - --host /absolute/path/to/CodexRegisteredHost \ - --adapter "$PWD/.build/accepted-package/bin/codex-mcp-adapter" \ - --output-directory "$PWD/.build/host-container-acceptance" \ - --mode container + --mode container \ + --host-source /absolute/path/to/computer-mcp \ + --plugin-revision "$(git rev-parse HEAD)" \ + --archive "$PWD/dist/codex-plugin-macos-arm64.zip" \ + --receipt "$PWD/dist/receipt.json" \ + --output-directory "$PWD/.build/host-acceptance" ``` -`check-workflow.py` exercises the relocated adapter through standard MCP with -an isolated home and fixed loopback model, covering native approvals, turns, -cancellation, reconnection and owned-process cleanup. It does not establish -real model authentication. +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 +registering it in the disposable Host database. The report in +`runtime/report.json` identifies both source commits, the archive, the +executables and the authorization revisions. The driver uses a deterministic vendor peer with network access +disabled. Through standard MCP it verifies project and caller binding, Host +worktree creation and removal, persisted state across restart, and caller and +provider revocation. The restart check confirms that a dead runtime receipt +grants no live authority and uses the adapter's stale-record cleanup when +needed. Rerun the gate after changing either source revision. + +`check-workflow.py` can separately exercise native approvals, turns, +cancellation, reconnection and owned-process cleanup through standard MCP +using an isolated home and a fixed loopback response: -`check-host.py` registers the package in a disposable host database and approves -the selected provider and caller permissions before serving standard MCP over -stdio. Use a new output directory. Container mode verifies injected storage -across two host and adapter launches, an allowed project file callback, refusal -to redirect a callback to a sibling project, and peer descriptor isolation. -It uses a deterministic vendor peer and omits authentication and model calls. +```sh +python3 scripts/check-workflow.py \ + --adapter "$PWD/.build/host-acceptance/relocated/bin/codex-mcp-adapter" \ + --codex /absolute/path/to/codex +``` -Full mode additionally takes `--codex`, `--auth-file` and `--model`. It needs a -vendor file-store login authorized for the selected model. +Native modes take the relocated adapter via `--adapter`, the fixture executable +produced by container mode via `--host`, and installed Codex via `--codex`. +Keep the adjacent execution bootstrap and SwiftPM build output available until +the fixture finishes. Full mode additionally takes `--auth-file` and `--model`. +It needs a vendor file-store login authorized for the selected model. The supplied `auth.json` is copied with mode `0600` into the private vendor home and deleted on exit; the original is never changed. Keychain-only credentials are not imported. The real-model checks make bounded text-only App Server and @@ -162,42 +174,6 @@ Pure driver logic and argument validation run without a host or vendor: python3 -m unittest discover -s Tests -p 'test_host_acceptance.py' -v ``` -#### Build the registered host fixture - -Build this fixture with the selected Computer MCP source revision on macOS. -The fixture uses the host's plugin store, provider review, permission service, -sandbox launcher and standard MCP gateway. Its authorization watermark and -managed policy source are confined to the fixture. It also serves the -deterministic App Server peer used by `check-host.py --mode container`. - -From the plugin checkout, set `host_source` to the selected host checkout, -`host_revision` to its full commit SHA, and `stage` to a new absolute path in -ignored build output. Record the host and plugin commit SHAs with the report. - -```sh -test "$(git -C "$host_source" rev-parse HEAD)" = "$host_revision" -mkdir -p "$stage/registered-host" -git -C "$host_source" archive "$host_revision" | tar -xf - -C "$stage/registered-host" -mkdir "$stage/registered-host/Tests/CodexRegisteredHost" -cp Tests/Fixtures/RegisteredHost/RegisteredHost.swift "$stage/registered-host/Tests/CodexRegisteredHost/" -cat >>"$stage/registered-host/Package.swift" <<'SWIFT' - -package.targets.append(.executableTarget( - name: "CodexRegisteredHost", - dependencies: [ - "ComputerMCPConfiguration", "ComputerMCPCore", "ComputerMCPGateway", "ComputerMCPMacOS", - "ComputerMCPPermissions", "ComputerMCPPlatform", "ComputerMCPPlugins", - ], - path: "Tests/CodexRegisteredHost" -)) -SWIFT -swift build --package-path "$stage/registered-host" --product CodexRegisteredHost -swift build --package-path "$stage/registered-host" --product computer-mcp-execution-bootstrap -``` - -Pass the resulting `CodexRegisteredHost` executable to `check-host.py --host`. -Keep the SwiftPM build output alongside it until the fixture has finished. - ### Publish 1. Select the reviewed `master` commit with successful `push` CI from diff --git a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift index b30a1b4..5c80fc3 100644 --- a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift +++ b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift @@ -5,8 +5,10 @@ import ComputerMCPMacOS import ComputerMCPPermissions import ComputerMCPPlatform import ComputerMCPPlugins +import ComputerMCPTransport import Darwin import Foundation +import MCP @main struct RegisteredHost { @@ -22,20 +24,32 @@ struct RegisteredHost { case "app-server": try runPeer() case "register", "serve": - guard arguments.count == 2 else { throw FixtureError.invalidArguments } + guard arguments.count == 2 || (arguments.count == 4 && arguments[0] == "serve") + else { throw FixtureError.invalidArguments } let root = URL(fileURLWithPath: arguments[1], isDirectory: true).resolvingSymlinksInPath() - try await run(root: root, register: arguments[0] == "register") + let observer: StdioTransport? + if arguments.count == 4 { + guard let input = Int32(arguments[2]), let output = Int32(arguments[3]), + input > STDERR_FILENO, output > STDERR_FILENO, input != output, + fcntl(input, F_SETFD, FD_CLOEXEC) == 0, fcntl(output, F_SETFD, FD_CLOEXEC) == 0 + else { throw FixtureError.invalidArguments } + observer = StdioTransport(input: .init(rawValue: input), output: .init(rawValue: output)) + } else { + observer = nil + } + try await run(root: root, register: arguments[0] == "register", observer: observer) default: throw FixtureError.invalidArguments } } - private static func run(root: URL, register: Bool) async throws { + private static func run(root: URL, register: Bool, observer: StdioTransport?) async throws { let database = try GatewayDatabase(path: root.appendingPathComponent("host.sqlite").path) _ = database.permissionStore( counter: FixtureEpochCounter(file: root.appendingPathComponent("fixture-epoch.json"))) - var platform = MacOSPlatform.services - platform.permissionPolicyReader = FixturePolicySources() + var services = MacOSPlatform.services + services.permissionPolicyReader = FixturePolicySources() + let platform = services let store = PluginStore(database: database, platform: platform) let configuration = try GatewayConfiguration.load( path: root.appendingPathComponent("host.toml").path, @@ -51,15 +65,122 @@ struct RegisteredHost { configuration: configuration) return } + let primary = try await makeGateway( + database: database, platform: platform, configuration: configuration) + if let observer { + let secondaryGateway = try await makeGateway( + database: database, platform: platform, configuration: configuration, role: "observer") + async let secondary: Void = serve( + secondaryGateway, root: root, configuration: configuration, + permissionRuntime: permissionRuntime, role: "observer", transport: observer) + try await serve( + primary, root: root, configuration: configuration, + permissionRuntime: permissionRuntime, role: "acceptance") + try await secondary + } else { + try await serve( + primary, root: root, configuration: configuration, permissionRuntime: permissionRuntime) + } + } + + private static func makeGateway( + database: GatewayDatabase, platform: PlatformServices, configuration: GatewayConfiguration, + role: String? = nil + ) async throws -> GatewayRuntime { + let profile = role.flatMap { GatewayProfileID(rawValue: $0) } ?? configuration.runtime.profileID let context = ExecutionContext( - caller: configuration.runtime.caller, profileID: configuration.runtime.profileID, + caller: configuration.runtime.caller, profileID: profile, projectID: configuration.runtime.defaultProjectID, transportTrace: .init(transport: "stdio", socketConnectionID: UUID().uuidString), - trustedPrincipalID: "registered-codex-fixture") - let gateway = try await GatewayRuntime.make( + trustedPrincipalID: role == "observer" + ? "registered-codex-observer" : "registered-codex-fixture") + return try await GatewayRuntime.make( configuration: configuration, context: context, database: database, platform: platform, bundledPlugins: .init(packages: [], issues: [])) - try await MCPRuntimeAdapter.runStdioGateway(configuration: configuration, registry: gateway) + } + + private static func serve( + _ gateway: GatewayRuntime, root: URL, configuration: GatewayConfiguration, + permissionRuntime: GatewayPermissionRuntime, role: String? = nil, + transport: StdioTransport? = nil + ) async throws { + let control = role.map { role in + Task { + do { + guard let profile = GatewayProfileID(rawValue: role) + else { throw FixtureError.invalidArguments } + try await waitForRevocation( + root: root, role: role, profile: profile, permissionRuntime: permissionRuntime) + } catch is CancellationError { + } catch { + let receipt = root.appendingPathComponent("revoke-\(role).json") + let details = try JSONSerialization.data(withJSONObject: [ + "error": String(describing: error) + ]) + try details.write(to: receipt, options: .atomic) + } + } + } + defer { control?.cancel() } + if let transport { + let server = await MCPRuntimeAdapter.makeGatewayServer( + configuration: configuration, registry: gateway) + do { + try await server.start(transport: MCPInitializeNormalizationTransport(wrapping: transport)) + await server.waitUntilCompleted() + } catch { + await gateway.shutdown() + throw error + } + await gateway.shutdown() + } else { + try await MCPRuntimeAdapter.runStdioGateway(configuration: configuration, registry: gateway) + } + } + + private static func owner() throws -> GatewayPermissionOwner { + try GatewayPermissionOwner( + context: .init( + caller: .localApp, profileID: .localAdmin, trustedPrincipalID: "fixture-owner"), + validate: {}) + } + + private static func waitForRevocation( + root: URL, role: String, profile: GatewayProfileID, permissionRuntime: GatewayPermissionRuntime + ) async throws { + let trigger = root.appendingPathComponent("revoke-\(role)") + while !FileManager.default.fileExists(atPath: trigger.path) { + try await Task.sleep(for: .milliseconds(50)) + } + try Task.checkCancellation() + let owner = try owner() + let service = permissionRuntime.service + let before = try service.view(owner: owner) + let revoked: RevocationResult + if role == "acceptance" { + revoked = try service.revokePermission( + .plugin("codex"), profileID: profile, owner: owner, expectedRevision: before.revision) + } else { + let identity = PluginIdentity.package("codex") + guard let approval = before.providers.first(where: { $0.identity == identity }) + else { throw FixtureError.invalidRegistration } + revoked = try service.revokeProvider( + identity, owner: owner, expectedProviderRevision: approval.revision, + expectedRevision: before.revision) + } + try await permissionRuntime.coordinator.reconcile() + let after = try service.view(owner: owner) + let disabled = + role == "acceptance" + ? after.profiles.first(where: { $0.id == profile })?.permissions.entries[.plugin("codex")] + == .denied + : after.providers.first(where: { $0.identity == .package("codex") })?.enabled == false + guard disabled else { throw FixtureError.invalidRegistration } + try JSONSerialization.data(withJSONObject: [ + "epoch": after.epoch?.uuidString ?? "", "before_revision": before.revision, + "after_revision": after.revision, + "executions": revoked.executionsToTerminate.map(\.uuidString).sorted(), + ]).write(to: trigger.appendingPathExtension("json"), options: .atomic) } private static func registerPlugin( @@ -85,10 +206,7 @@ struct RegisteredHost { settings.mcp["app-server"]?.args = ["--config", configFile.path] _ = try await store.setSettings(settings, for: "codex", expectedRevision: registered.revision) - let owner = try GatewayPermissionOwner( - context: .init( - caller: .localApp, profileID: .localAdmin, trustedPrincipalID: "fixture-owner"), - validate: {}) + let owner = try owner() let view = try permissionRuntime.service.view(owner: owner) guard let epoch = view.epoch else { throw FixtureError.missingEpoch } let review = try GatewayProviderReview( @@ -112,6 +230,7 @@ struct RegisteredHost { let receipt = [ "home": container.home.value, "cache": container.cache.value, "state": container.state.value, "config": configFile.path, "manifest_digest": review.sourceDigest, + "provider_revision": String(approval.revision), "authorization_epoch": epoch.uuidString, ] print(String(decoding: try JSONEncoder().encode(receipt), as: UTF8.self)) } @@ -167,6 +286,13 @@ struct RegisteredHost { ], ]) case "thread/loaded/list": + let directory = URL(fileURLWithPath: FileManager.default.currentDirectoryPath) + let edit = directory.appendingPathComponent("fixture-edit-request") + if FileManager.default.fileExists(atPath: edit.path) { + try "edited by the registered peer\n".write( + to: directory.appendingPathComponent("fixture-edit.txt"), atomically: true, + encoding: .utf8) + } let queued = home.appendingPathComponent("queued.json") if FileManager.default.fileExists(atPath: queued.path), let callback = try JSONSerialization.jsonObject(with: Data(contentsOf: queued)) diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index daf3fe3..f4b8d5f 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -5,6 +5,7 @@ import io import json from pathlib import Path +import subprocess import tempfile import unittest from unittest.mock import Mock, patch @@ -38,14 +39,67 @@ def test_fixture_arguments_do_not_launch_or_create_state(self): self.assertEqual(parsed.mode, "fixture") self.assertFalse(parsed.output_directory.exists()) - def test_container_mode_requires_only_the_registered_fixture_and_adapter(self): - arguments = self.arguments[:-4] + self.arguments[-2:] + ["--mode", "container"] + def container_arguments(self, revision): + return ["--mode", "container", "--host-source", str(self.root), + "--plugin-revision", revision, "--archive", str(self.executable), + "--receipt", str(self.executable), "--output-directory", str(self.root / "output")] + + 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) + self.assertIsNone(options.adapter) self.assertIsNone(options.codex) self.assertFalse(options.output_directory.exists()) self.invalid(self.arguments + ["--mode", "container"]) self.invalid(arguments + ["--model", "unused"]) - self.invalid(arguments[:-2] + ["--mode", "fixture"]) + self.invalid(arguments + ["--host", str(self.executable)]) + self.invalid(arguments[0:2] + arguments[4:]) + self.invalid(self.container_arguments("main")) + self.invalid(self.container_arguments("a" * 39)) + self.invalid(self.container_arguments("0" * 40)) + + 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: + options = acceptance.parse_arguments(self.container_arguments("a" * 40)) + with self.assertRaises(FileNotFoundError): + acceptance.prepare_pinned_host(options) + acceptance.HOST_PIN.write_text("master\n") + with self.assertRaisesRegex(ValueError, "full 40-character"): + acceptance.prepare_pinned_host(options) + checkout.assert_not_called() + acceptance.HOST_PIN.write_text("b" * 40 + "\n") + checkout.side_effect = AssertionError("mismatched Host") + with self.assertRaisesRegex(AssertionError, "mismatched Host"): + acceptance.prepare_pinned_host(options) + checkout.assert_called_once_with(self.root, "b" * 40, "Host") + self.assertFalse(options.output_directory.exists()) + + def test_host_revision_checks_actual_clean_checkout(self): + checkout = self.root / "host" + checkout.mkdir() + + def git(*arguments): + return subprocess.check_output(["/usr/bin/git", "-C", str(checkout), *arguments], text=True).strip() + + git("init", "-q") + manifest = checkout / "Package.swift" + manifest.write_text("Host source") + git("add", ".") + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", + "-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null", "commit", "-qm", "Fixture") + revision = git("rev-parse", "HEAD") + self.assertEqual(acceptance.checked_revision(checkout, revision, "Host"), revision) + with self.assertRaisesRegex(AssertionError, "differs from required"): + acceptance.checked_revision(checkout, "f" * 40, "Host") + for dirty_file in (checkout / "untracked", manifest): + dirty_file.write_text("Changed source") + with self.assertRaisesRegex(AssertionError, "checkout must be clean"): + acceptance.checked_revision(checkout, revision, "Host") + if dirty_file != manifest: + dirty_file.unlink() def test_full_requires_explicit_authentication_and_model(self): self.invalid(self.arguments) @@ -94,6 +148,26 @@ def test_nested_tool_errors_cannot_be_success(self): with self.assertRaises(RuntimeError): acceptance.unwrap(failure, indirect="structuredContent" in failure) + def test_removal_observations_wait_on_the_same_bound_pending_operation(self): + pending = {"id": "fixture", "project_id": "child", "source_project_id": "primary", + "operation_id": "91807494-d50c-4d89-9e0a-d17b608ecf66", + "state": "removing", "host_state": "reserved", "observation_error": "Temporarily unavailable"} + + def reply(payload, error=False): + return {"isError": error, "structuredContent": {"result": payload}} + + operation, completed = acceptance.observe_worktree_removal(reply(pending, True), "fixture", "child", None) + self.assertIsNone(completed) + removed = dict(pending, state="removed", host_state="completed", observation_error=None) + self.assertEqual(acceptance.observe_worktree_removal(reply(removed), "fixture", "child", operation), + (operation, removed)) + for change in ({"project_id": "sibling"}, {"host_state": "recovery_required"}, + {"operation_id": "0447fad0-a4cb-4c82-9bcd-357be8f3d37b"}): + with self.assertRaises(AssertionError): + acceptance.observe_worktree_removal(reply(dict(pending, **change), True), "fixture", "child", operation) + with self.assertRaises(RuntimeError): + acceptance.observe_worktree_removal(reply(removed, True), "fixture", "child", operation) + def test_archive_requires_success_or_exact_missing_rollout_identity(self): success = {"structuredContent": {"result": {}}} self.assertEqual(acceptance.archive_disposition(success, "thread-1"), "archived") diff --git a/scripts/check-host.py b/scripts/check-host.py index c04e65a..b83346b 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -18,13 +18,18 @@ import signal import subprocess import sys +import tarfile import threading import time +from types import SimpleNamespace import uuid 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 @@ -47,6 +52,19 @@ def absolute_file(value): return path.resolve() +def checkout_directory(value): + path = Path(value) + if not path.is_absolute() or not path.is_dir(): + raise argparse.ArgumentTypeError("Expected an existing absolute Git checkout directory") + return path.resolve() + + +def full_revision(value): + if not re.fullmatch(r"[0-9a-f]{40}", value) or value == "0" * 40: + raise ValueError("A full 40-character Git commit SHA is required") + return value + + def timeout_seconds(value): try: number = int(value) @@ -59,8 +77,12 @@ def timeout_seconds(value): def parse_arguments(arguments=None): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--host", required=True, type=executable, help="Source-built CodexRegisteredHost fixture") - parser.add_argument("--adapter", required=True, type=executable, help="Adapter from the verified, relocated archive") + parser.add_argument("--host-source", type=checkout_directory, help="Container mode: clean checkout at 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") + parser.add_argument("--host", type=executable, help="Native modes: source-built CodexRegisteredHost fixture") + parser.add_argument("--adapter", type=executable, help="Native modes: adapter from the verified, relocated archive") parser.add_argument("--codex", type=executable, help="Native modes: user-installed vendor Codex") parser.add_argument("--output-directory", required=True, type=Path, help="New private directory in ignored build output") parser.add_argument("--mode", choices=("container", "fixture", "full"), default="full") @@ -71,10 +93,16 @@ 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") - if options.mode == "container" and options.codex: - parser.error("Container mode uses only the disposable protocol peer") - if options.mode != "container" and not options.codex: - parser.error("Native modes require --codex") + source_inputs = (options.host_source, options.plugin_revision, options.archive, options.receipt) + if options.mode == "container": + if not all(source_inputs) 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) + except ValueError as error: + parser.error(str(error)) + elif any(source_inputs) or not all((options.host, options.adapter, options.codex)): + parser.error("Native modes require --host, --adapter and --codex") if options.mode == "full" and (not options.auth_file or not options.model or not options.model.strip()): parser.error("Full mode requires --auth-file and --model") if options.mode != "full" and (options.auth_file or options.model): @@ -84,6 +112,81 @@ def parse_arguments(arguments=None): return options +def git_at(directory, *arguments): + return ["/usr/bin/git", "--no-optional-locks", "--no-replace-objects", "-C", str(directory), *arguments] + + +def checked_revision(directory, expected, label): + def read(*arguments): + return subprocess.run(git_at(directory, *arguments), text=True, check=True, + stdout=subprocess.PIPE, timeout=30).stdout.strip() + + expected = full_revision(expected) + require(Path(read("rev-parse", "--show-toplevel")).resolve() == directory, + f"{label} must be a separate Git checkout root: {directory}") + actual = read("rev-parse", "--verify", "HEAD^{commit}") + require(actual == expected, f"{label} HEAD {actual} differs from required {expected}") + require(not read("status", "--porcelain=v1", "--untracked-files=all", "--ignore-submodules=none"), + f"{label} checkout must be clean: {directory}") + return actual + + +def prepare_pinned_host(options): + pin = 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") + receipt = json.loads(options.receipt.read_text()) + require(isinstance(receipt, dict) and receipt.get("configuration") == "release", + "Pinned Host acceptance requires a release archive") + stage = options.output_directory.resolve() + require(not stage.is_relative_to(options.host_source), "Build output must be outside the Host checkout") + stage.mkdir(mode=0o700, parents=True) + source = stage / "host-source" + source.mkdir() + with subprocess.Popen(git_at(options.host_source, "archive", host_revision), + stdout=subprocess.PIPE) as archive: + with archive.stdout, tarfile.open(fileobj=archive.stdout, mode="r|") as tar: + tar.extractall(source, filter="data") + require(archive.wait(timeout=30) == 0, "Failed to export pinned Host source") + target = source / "Tests/CodexRegisteredHost" + target.mkdir() + shutil.copy2(REGISTERED_HOST_SOURCE, target / REGISTERED_HOST_SOURCE.name) + with (source / "Package.swift").open("a") as manifest: + manifest.write(""" +package.targets.append(.executableTarget( + name: "CodexRegisteredHost", + dependencies: [ + "ComputerMCPConfiguration", "ComputerMCPCore", "ComputerMCPGateway", "ComputerMCPMacOS", + "ComputerMCPPermissions", "ComputerMCPPlatform", "ComputerMCPPlugins", "ComputerMCPTransport", + .product(name: "MCP", package: "swift-sdk"), + ], + path: "Tests/CodexRegisteredHost" +)) +""") + options.package = stage / "relocated" + verified = subprocess.run([ + sys.executable, str(REPOSITORY / "scripts/check-package.py"), + "--archive", str(options.archive), "--receipt", str(options.receipt), + "--destination", str(options.package), + ], text=True, check=True, stdout=subprocess.PIPE, timeout=120) + archive = json.loads(verified.stdout) + 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) + 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.output_directory = stage / "runtime" + return {"host_revision": host_revision, "plugin_revision": plugin_revision, + "archive": archive, "execution_bootstrap_sha256": digest(bootstrap)} + + def unwrap(result, indirect=False): for _ in range(2 if indirect else 1): require(isinstance(result, dict), "Malformed MCP tool result") @@ -93,6 +196,18 @@ def unwrap(result, indirect=False): return result +def observe_worktree_removal(result, worktree_id, project, operation_id): + current = result.get("structuredContent", {}).get("result") + require(isinstance(current, dict) and current["id"] == worktree_id + and current["project_id"] == project and current["source_project_id"] == "primary", result) + observed_id = uuid.UUID(current["operation_id"]) + require(operation_id is None or operation_id == observed_id, current) + if current["state"] == "removed": + return observed_id, unwrap(result) + require(current["state"] == "removing" and current["host_state"] in {"reserved", "running"}, current) + return observed_id, None + + def archive_disposition(result, thread_id): if not isinstance(thread_id, str) or not thread_id or any(c.isspace() for c in thread_id): return "failed" @@ -240,38 +355,91 @@ def initialize(self): "codex.worktree.leases.acquire": "workspace-write", "codex.worktree.leases.release": "workspace-write"} +CONTAINER_RISKS = { + "codex.app.status": "read-only", + "codex.app.thread.loaded.list": "read-only", + "codex.app.runtimes.cleanup.preview": "read-only", + "codex.app.runtimes.cleanup.perform": "workspace-write", + "codex.diagnostics.snapshot": "read-only", + "codex.worktree.managed.list": "read-only", + "codex.worktree.managed.read": "read-only", + "codex.worktree.leases.list": "read-only", + "codex.worktree.leases.acquire": "workspace-write", + "codex.worktree.leases.release": "workspace-write", + "codex.worktree.provision.plan": "workspace-write", + "codex.worktree.provision.perform": "workspace-write", + "codex.worktree.remove.plan": "workspace-write", + "codex.worktree.remove.perform": "destructive", +} + + class Host: - def __init__(self, fixture, indirect=True): + def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None): self.fixture, self.indirect = fixture, indirect self.workspace = "primary" fixture.generation += 1 self.log = (fixture.root / f"host-{fixture.generation}.log").open("w") self.evidence = (fixture.root / f"protocol-{fixture.generation}.jsonl").open("w") - self.process = subprocess.Popen([str(fixture.options.host), "serve", str(fixture.root)], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, - text=True, bufsize=1, env=fixture.environment, cwd=fixture.root) + self.process = self.observer_streams = None + if streams is None: + command = [str(fixture.options.host), "serve", str(fixture.root)] + child_fds = () + if with_observer: + input_fd, writer = os.pipe() + reader, output_fd = os.pipe() + child_fds = (input_fd, output_fd) + command.extend(str(fd) for fd in child_fds) + self.observer_streams = SimpleNamespace( + stdin=os.fdopen(writer, "w"), stdout=os.fdopen(reader)) + try: + self.process = subprocess.Popen( + command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, + text=True, bufsize=1, env=fixture.environment, cwd=fixture.root, pass_fds=child_fds) + except OSError: + if self.observer_streams: + self.observer_streams.stdin.close() + self.observer_streams.stdout.close() + self.log.close() + self.evidence.close() + raise + finally: + for fd in child_fds: + os.close(fd) + streams = self.process fixture.hosts.append(self) - self.client = MCPClient(self.process, self.evidence, fixture.options.timeout_seconds) + self.client = MCPClient(streams, self.evidence, fixture.options.timeout_seconds) gateway_catalog = self.client.initialize() - tools = unwrap(self.client.send("tools/call", { - "name": "mcp.tools.list", "arguments": {"server": "codex"}, - })) - self.catalog = {tool["name"]: tool for tool in tools} if indirect else gateway_catalog + downstream_catalog = self.project_catalog() + self.catalog = downstream_catalog if indirect else 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", "Generic dispatch lacks project selection") + def project_catalog(self): + tools = unwrap(self.client.send("tools/call", { + "name": "mcp.tools.list", "arguments": {"server": "codex", "project_id": self.workspace}, + })) + return {tool["name"]: tool for tool in tools} + + def select_project(self, project): + self.workspace = project + self.catalog = self.project_catalog() + def raw(self, name, arguments=None, timeout=None): name = name if name.startswith("codex.") else "codex.app." + name arguments = arguments or {} require(set(arguments) <= self.catalog[name]["inputSchema"]["properties"].keys(), {"tool": name, "undeclared_inputs": sorted(set(arguments) - self.catalog[name]["inputSchema"]["properties"].keys())}) + result = self.dispatch(name, arguments, timeout) + return unwrap(result) if self.indirect else result + + def dispatch(self, name, arguments=None, timeout=None): + arguments = arguments or {} if self.indirect: params = {"name": "mcp.tools.call", "arguments": {"server": "codex", "tool": name, "project_id": self.workspace, "arguments": arguments}} else: params = {"name": name, "arguments": dict(arguments, project_id=self.workspace)} - result = self.client.send("tools/call", params, timeout=timeout) - return unwrap(result) if self.indirect else result + return self.client.send("tools/call", params, timeout=timeout) def call(self, name, arguments=None, timeout=None): return unwrap(self.raw(name, arguments, timeout)) @@ -280,6 +448,13 @@ def method(self, name, params=None, timeout=None): return self.call("methods.call", {"method": name, "params": params or {}}, timeout) def close(self): + if self.process is None: + self.client.process.stdin.close() + self.log.close() + self.evidence.close() + return + if self.observer_streams: + self.observer_streams.stdin.close() if self.process.poll() is None: self.process.stdin.close() try: @@ -293,13 +468,15 @@ def close(self): self.process.wait(timeout=5) raise RuntimeError("Host did not exit after MCP EOF") self.client.reader.join(timeout=2) + if self.observer_streams: + self.observer_streams.stdout.close() self.log.close() self.evidence.close() require(self.process.returncode == 0, {"host_exit": self.process.returncode}) def processes(self): status = self.call("status") - require(Path(status["workspace"]).resolve() == (self.fixture.root / self.workspace).resolve(), status) + require(Path(status["workspace"]).resolve() == self.fixture.projects[self.workspace], status) pids = [status["process"][key] for key in ("process_id", "supervisor_process_id", "parent_process_id")] require(all(isinstance(pid, int) and pid > 1 for pid in pids), status) self.fixture.pids.update(pids) @@ -356,12 +533,11 @@ def __init__(self, options): self.model = None self.model_log = None self.container = None + self.authorization = {} self.adapter_config = self.root / "adapter.json" self.launches = self.root / "launches.jsonl" - self.risks = RISKS - if options.mode == "container": - self.risks = {name: RISKS[name] for name in ( - "codex.app.status", "codex.app.thread.loaded.list", "codex.diagnostics.snapshot")} + self.risks = CONTAINER_RISKS if options.mode == "container" else RISKS + self.projects = {name: self.root / name for name in ("primary", "other")} self.home = self.root / "codex-home" self.home.mkdir(mode=0o700) # Private HOME also isolates Git, native skills, hooks and host configuration. @@ -371,14 +547,16 @@ def __init__(self, options): (self.root / "tmp").mkdir(mode=0o700) def setup(self): - for name in ("primary", "other"): - (self.root / name).mkdir() - if self.options.mode == "container": - continue - self.git(["init", "--quiet"], name) + for name, path in self.projects.items(): + path.mkdir() + self.git(["init", "--quiet", "--initial-branch=main"], name) for key, value in (("user.name", "Acceptance"), ("user.email", "acceptance@example.invalid"), ("commit.gpgsign", "false"), ("core.hooksPath", str(self.root / name / ".git/hooks"))): self.git(["config", key, value], name) + if self.options.mode == "container": + (self.projects["primary"] / "product.txt").write_text("caller project fixture\n") + self.git(["add", "product.txt"]) + self.git(["commit", "--quiet", "-m", "Fixture base"]) self.register() if self.options.mode == "container": self.configure_adapter(self.peer, exec_enabled=False) @@ -439,18 +617,16 @@ def register(self): q = json.dumps self.package = self.root / "plugin" bin_directory = self.package / "bin" - bin_directory.mkdir(parents=True) - manifest = REPOSITORY / "computer-mcp-plugin.toml" - shutil.copy2(manifest, self.package / manifest.name) - shutil.copy2(self.options.adapter, bin_directory / "codex-mcp-adapter") - resources = self.options.adapter.with_name("codex-plugin_CodexAdapter.bundle") - shutil.copytree(resources, bin_directory / resources.name) - self.peer = bin_directory / "fixture-vendor" if self.options.mode == "container": - shutil.copy2(self.options.host, self.peer) + shutil.copytree(self.options.package, self.package) + else: + bin_directory.mkdir(parents=True) + shutil.copy2(MANIFEST, self.package / MANIFEST.name) + shutil.copy2(self.options.adapter, bin_directory / "codex-mcp-adapter") + resources = self.options.adapter.with_name("codex-plugin_CodexAdapter.bundle") + shutil.copytree(resources, bin_directory / resources.name) - access = "read" if self.options.mode == "container" else "write" - config = f'''schema_version = 1 + config = '''schema_version = 1 [runtime] caller = "local-mcp" profile = "acceptance" @@ -462,12 +638,27 @@ def register(self): full_access = false [profiles.projects] -primary = {{ access = "{access}", network = "none" }} -other = {{ access = "{access}", network = "none" }} +primary = { access = "write", network = "none" } +other = { access = "write", network = "none" } [profiles.plugins] codex = "use" +''' + if self.options.mode == "container": + config += ''' +[[profiles]] +id = "observer" +allowed_callers = ["local-mcp"] +full_access = false + +[profiles.projects] +primary = { access = "write", network = "none" } +other = { access = "write", network = "none" } +[profiles.plugins] +codex = "use" +''' + config += ''' [builtin] enabled = ["file.read"] ''' @@ -497,11 +688,17 @@ def register(self): (self.root / "registration.json").write_text(json.dumps(self.container, indent=2) + "\n") self.home = Path(self.container["home"]) / ".codex" self.home.mkdir(mode=0o700) + if self.options.mode == "container": + self.authorization["registration"] = { + key: self.container[key] for key in ("manifest_digest", "provider_revision", "authorization_epoch") + } + self.peer = Path(self.container["home"]) / "fixture-vendor" + shutil.copy2(self.options.host, self.peer) self.adapter_config = Path(self.container["config"]) self.launches = self.home / "launches.jsonl" def git(self, args, workspace="primary"): - return subprocess.run(["/usr/bin/git", *args], cwd=self.root / workspace, env=self.environment, + return subprocess.run(["/usr/bin/git", *args], cwd=self.projects[workspace], env=self.environment, text=True, capture_output=True, timeout=10, check=True).stdout def response(self, phase, command=None, hold=False): @@ -761,13 +958,178 @@ def exec_lifecycle(self): self.response("cleanup") self.record("exec-defaults-overrides-events-result-resume-cancel-release") + def provision_worktree(self, host): + parent = host.call("codex.worktree.leases.acquire", {"agent_id": "acceptance-parent"}) + plan = host.call("codex.worktree.provision.plan", { + "name": "fixture", "agent_id": "acceptance-child", "parent_lease_id": parent["id"], + }) + require(plan["state"] == "planned" and plan["source_project_id"] == "primary", plan) + worktree = host.call("codex.worktree.provision.perform", plan["perform_arguments"]) + require(worktree["id"] == plan["id"] and worktree["state"] == "active" + and worktree["host_state"] == "completed" and worktree["lease"]["state"] == "acquired", worktree) + operation = worktree["host_response"]["structuredContent"]["result"] + require(operation["source_project_id"] == "primary" and operation["project_id"] == "primary" + and uuid.UUID(operation["operation_id"]) == uuid.UUID(worktree["operation_id"]), operation) + child = worktree["project_id"] + path = Path(worktree["resolved"]["path"]).resolve(strict=True) + require(path.is_relative_to(self.root / "worktrees") and child not in self.projects, worktree) + self.projects[child] = path + require(self.git(["rev-parse", "HEAD"], child) == self.git(["rev-parse", "HEAD"]), worktree) + inventory = host.call("codex.worktree.managed.list") + require(worktree["resolved"]["worktree_id"] in json.dumps(inventory), inventory) + self.record("host-created-associated-worktree") + return worktree, parent + + def remove_worktree(self, host, worktree, parent): + worktree_id, project = worktree["id"], worktree["project_id"] + selector = {"managed_worktree_id": worktree_id} + observed = host.call("codex.worktree.managed.read", selector) + require(observed["state"] == "active" and observed["operation_id"] == worktree["operation_id"], observed) + host.select_project("other") + refused = host.raw("codex.worktree.managed.read", selector) + require(refused.get("isError") is True and "Unknown Computer MCP-managed worktree" in json.dumps(refused), + refused) + host.select_project(project) + require(host.call("codex.worktree.managed.read", selector)["project_id"] == project, + "Caller did not resolve its derived project") + path = self.projects[project] + trigger = path / "fixture-edit-request" + trigger.touch() + require(host.call("thread.loaded.list")["data"] == [], "Unexpected fixture threads") + peer = self.vendor_receipt() + child_pids = host.processes() + require((path / "fixture-edit.txt").read_text() == "edited by the registered peer\n" + and not (self.projects["primary"] / "fixture-edit.txt").exists(), path) + trigger.unlink() + self.git(["add", "fixture-edit.txt"], project) + self.git(["-c", "user.name=Acceptance", "-c", "user.email=acceptance@example.invalid", + "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "Fixture edit"], project) + tip = self.git(["rev-parse", "HEAD"], project).strip() + lease = next(row for row in host.call("codex.worktree.leases.list")["leases"] + if row["id"] == worktree["lease"]["lease_id"]) + host.call("codex.worktree.leases.release", {"lease_id": lease["id"], + "expected_revision": lease["revision"], "reason": "Fixture edit committed"}) + plan = host.call("codex.worktree.remove.plan", selector) + require(plan["state"] == "removal_planned", plan) + response = host.dispatch("codex.worktree.remove.perform", plan["perform_arguments"]) + error = response.get("structuredContent", {}).get("error", {}) + message = error.get("message", "") + reply_lost = (response.get("isError") and error.get("code") == "gateway.execution_failed" + and (message.startswith("[mcp.request_cancelled]") + or message == "MCP server 'codex' request timed out.")) + if not reply_lost: + removed = unwrap(response, indirect=True) + host.select_project("primary") + if reply_lost: + removal_id = None + + def observe_removal(): + nonlocal removal_id + observation = host.raw("codex.worktree.managed.read", selector) + removal_id, completed = observe_worktree_removal(observation, worktree_id, project, removal_id) + return completed + + removed = wait_until(observe_removal, self.options.timeout_seconds, "Host removal observation") + self.record("interrupted-removal-reply-recovered-without-replaying") + require(removed["state"] == "removed" and removed["host_state"] == "completed" + and removed["operation_id"] != worktree["operation_id"], removed) + operation = removed["host_response"]["structuredContent"]["result"] + 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) + recovery = self.root / "worktree-recovery" + repositories = [entry.parent for entry in recovery.rglob("HEAD") if (entry.parent / "objects").is_dir()] + require(any(subprocess.run( + ["/usr/bin/git", "--git-dir", str(repository), "cat-file", "-e", tip + "^{commit}"], + env=self.environment, capture_output=True, timeout=10).returncode == 0 + for repository in repositories), "Host recovery storage lacks the removed commit") + require(not self.git(["status", "--porcelain"]), "Source checkout changed") + host.call("codex.worktree.leases.release", {"lease_id": parent["id"], + "expected_revision": parent["revision"], "reason": "Fixture worktree removed"}) + self.record("host-restarted-edited-retained-and-removed-worktree") + + def vendor_receipt(self): + receipt = json.loads((self.home / "vendor.json").read_text()) + self.pids.add(receipt["pid"]) + return receipt + + def clear_stale_runtime(self, host, snapshot, prior_runtime, prior_pids): + persisted = next(row for row in snapshot["persisted_runtimes"] if row["id"] == prior_runtime) + require(all(exited(pid) for pid in prior_pids), "Previous fixture process still exists") + require(not any(snapshot[key] for key in ("active_runs", "pending_approvals", "thread_ownership_receipts")) + and all(row["runtime_id"] != prior_runtime and row["process"] is None + and row["connection_id"] is None and row["current_request_count"] == 0 + and not row["threads"] for row in snapshot["live_runtimes"]["runtimes"]), + "Restart reported a live peer, request, thread, run or approval") + preview = host.call("runtimes.cleanup.preview") + require(persisted["state"] == "running", persisted) + candidates = preview["candidates"] + require(preview["signals_sent"] is False and len(candidates) == 1 + and candidates[0]["runtime"]["id"] == prior_runtime + and candidates[0]["classification"] == "stale_record" + and candidates[0]["cleanup_ready"] and not candidates[0]["directory_active"] + and not candidates[0]["process_active"], preview) + cleanup = host.call("runtimes.cleanup.perform", {"confirm_cleanup": True}) + require(cleanup["signals_sent"] is False and cleanup["watchdog_pending"] == [] + and [(row["id"], row["state"], row["currentRequestState"]) for row in cleanup["cleaned"]] + == [(prior_runtime, "cleaned", "idle")], cleanup) + require(host.call("runtimes.cleanup.preview")["candidates"] == [], "Stale runtime remained actionable") + self.record("restarted-without-live-runtime-authority-or-reported-work") + + def revoke(self, role): + trigger = self.root / f"revoke-{role}" + trigger.touch() + receipt_path = trigger.with_suffix(".json") + wait_until(receipt_path.exists, self.options.timeout_seconds, f"{role} revocation receipt") + receipt = json.loads(receipt_path.read_text()) + require("error" not in receipt, receipt) + require(receipt["before_revision"] < receipt["after_revision"] and receipt["executions"] + and receipt["epoch"] == self.container["authorization_epoch"], receipt) + self.authorization[role] = receipt + + def assert_revoked(self, host, code, message=None): + result = host.dispatch("codex.app.thread.loaded.list") + error = result.get("structuredContent", {}).get("error", {}) + require(result.get("isError") is True and error.get("code") == code + and (message is None or error.get("message") == message), result) + + def registered_revocation(self, caller, worktree): + require(caller.call("thread.loaded.list")["data"] == [], "Unexpected fixture threads") + caller_pids = caller.processes() + observer = Host(self, streams=caller.observer_streams) + scope = observer.call("codex.diagnostics.snapshot")["scope"] + require(scope["principal_id"] == "registered-codex-observer" + and scope["profile_id"] == "observer" and scope["project_id"] == "primary", scope) + refused = observer.raw("codex.worktree.managed.read", {"managed_worktree_id": worktree["id"]}) + require(refused.get("isError") is True and "Unknown Computer MCP-managed worktree" in json.dumps(refused), + refused) + require(observer.call("thread.loaded.list")["data"] == [], "Unexpected fixture threads") + observer_peer = self.vendor_receipt() + observer_pids = observer.processes() + require(caller_pids[0] != observer_pids[0] == observer_peer["pid"], observer_peer) + self.revoke("acceptance") + wait_until(lambda: all(exited(pid) for pid in caller_pids[:2]), 15, "Revoked caller process exit") + self.assert_revoked(caller, "permission.denied") + require(observer.call("thread.loaded.list")["data"] == [] and not exited(observer_pids[0]) + and observer.processes() == observer_pids, "Unrelated caller lost its live runtime") + self.revoke("observer") + wait_until(lambda: all(exited(pid) for pid in observer_pids[:2]), 15, "Revoked provider process exit") + self.assert_revoked(observer, "permission.unavailable", "invalidBinding") + observer.close() + caller.close() + require(self.vendor_receipt() == observer_peer, "Revocation relaunched the vendor") + self.record("caller-revocation-isolated-and-durable-provider-revocation-terminated-peer") + def registered_container(self): marker = "caller project fixture\n" sibling = "sibling project fixture\n" - (self.root / "primary/product.txt").write_text(marker) (self.root / "other/product.txt").write_text(sibling) vendor_receipt = self.home / "vendor.json" - prior_vendor = prior_runtime = None + prior_vendor = None for generation in (1, 2): host = Host(self) initial = host.call("codex.diagnostics.snapshot") @@ -775,8 +1137,8 @@ def registered_container(self): require(initial["state_storage"]["scope"] == "authorization_subject", initial) require(initial["scope"]["project_id"] == "primary" and initial["scope"]["principal_id"] == "registered-codex-fixture", initial) - if prior_runtime: - require(any(row["id"] == prior_runtime for row in initial["persisted_runtimes"]), initial) + if prior_vendor: + self.clear_stale_runtime(host, initial, prior_runtime, prior_pids) require(not vendor_receipt.exists() or json.loads(vendor_receipt.read_text()) == prior_vendor, "Catalog or diagnostics launched the peer") @@ -790,8 +1152,7 @@ def registered_container(self): (self.home / "queued.json").write_text(json.dumps(request)) loaded = host.call("thread.loaded.list") require(loaded["data"] == [], loaded) - vendor = json.loads(vendor_receipt.read_text()) - self.pids.add(vendor["pid"]) + vendor = self.vendor_receipt() response = json.loads((self.home / f"callback-{request_id}.json").read_text()) require(response["id"] == request_id and "error" not in response, response) callback = response["result"] @@ -809,7 +1170,7 @@ def registered_container(self): require(all(vendor[key] == self.container[key] for key in ("home", "cache", "state")), vendor) require(not vendor["inherited_host_env"] and not vendor["inherited_host_socket"], vendor) require(prior_vendor is None or vendor["pid"] != prior_vendor["pid"], vendor) - host.processes() + pids = host.processes() snapshot = host.call("codex.diagnostics.snapshot") if generation == 1: reads = [row for row in snapshot["recent_tool_audits"] @@ -817,11 +1178,22 @@ def registered_container(self): require(any(row["decision"] == "allowed" and row["socket_connection_id"] == execution["socket_connection_id"] for row in reads), reads) - prior_runtime = host.call("status")["runtime_id"] - prior_vendor = vendor (self.root / f"vendor-{generation}.json").write_text(json.dumps(vendor, indent=2) + "\n") - host.close() - wait_until(lambda: exited(vendor["pid"]), 15, "Fixture peer exit") + if generation == 1: + worktree, parent = self.provision_worktree(host) + prior_runtime = host.call("status")["runtime_id"] + prior_vendor, prior_pids = vendor, pids + adapter_pid = pids[2] + require(descendant(adapter_pid, host.process.pid, process_parent) + and descendant(vendor["pid"], adapter_pid, process_parent), + "Crash target is not the fixture's adapter and vendor lineage") + os.kill(adapter_pid, signal.SIGKILL) + host.close() + wait_until(lambda: all(exited(pid) for pid in prior_pids), 15, "Previous fixture process exit") + else: + self.remove_worktree(host, worktree, parent) + host.close() + self.registered_revocation(Host(self, with_observer=True), worktree) require(list(Path(self.container["state"]).glob("codex-adapter/subjects/*/codex.sqlite")), "Adapter records are missing in the injected state directory") self.record("registered-container-vendor-and-adapter-persistence-and-caller-scoped-read") @@ -922,6 +1294,8 @@ def cleanup(self): roots = {str((self.root / name).resolve()) for name in ("primary", "other")} if not all(str(Path(entry["cwd"]).resolve()) in roots for entry in entries): errors.append("Vendor launched outside selected workspaces") + if self.options.mode == "container" and (self.home / "vendor.json").is_file(): + self.vendor_receipt() except Exception as error: errors.append(f"Launch receipts: {error}") try: @@ -939,7 +1313,7 @@ def digest(path): return value.hexdigest() -def run(options): +def run(options, provenance=None): fixture = Fixture(options) report = {"schema_version": 1, "mode": options.mode, "passed": False, "authenticated_model_verified": False, "steps": fixture.steps, @@ -947,6 +1321,9 @@ def run(options): for key in ("host", "adapter", "codex") if getattr(options, key)}, "fixture_sha256": {source.name: digest(source) for source in ( MODEL_SOURCE, REGISTERED_HOST_SOURCE)}} + if provenance: + report["source_acceptance"] = provenance + report["authorization"] = fixture.authorization try: fixture.setup() for key in report["binaries"]: @@ -1001,5 +1378,15 @@ def run(options): return 0 if report["passed"] else 1 +def main(): + options = parse_arguments() + try: + provenance = prepare_pinned_host(options) if options.mode == "container" else None + return run(options, provenance) + except (AssertionError, OSError, ValueError, subprocess.SubprocessError, tarfile.TarError) as error: + print(f"Host acceptance failed: {error}", file=sys.stderr) + return 1 + + if __name__ == "__main__": - raise SystemExit(run(parse_arguments())) + raise SystemExit(main()) From ff7821fac39c2208ea1bccd5adbfa8a82ac06568 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:09:30 +0800 Subject: [PATCH 06/25] ci: pin the reviewed host for consumer acceptance --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index fc0ed8c..15264bc 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -42eb815c4be435f3f4f9d191fc6ac0927f23fe83 +f6de5e0c003af87722868d5c38aebb12ee656e3b From a209f044e031ea05d06e47357776d24436547d76 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:26:04 +0800 Subject: [PATCH 07/25] fix(test): retry removal reads after a Host configuration change --- Tests/test_host_acceptance.py | 41 ++++++++++++++++++++++++++++++++++- scripts/check-host.py | 17 ++++++++++++--- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index f4b8d5f..14e622d 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -154,7 +154,8 @@ def test_removal_observations_wait_on_the_same_bound_pending_operation(self): "state": "removing", "host_state": "reserved", "observation_error": "Temporarily unavailable"} def reply(payload, error=False): - return {"isError": error, "structuredContent": {"result": payload}} + plugin = {"isError": error, "structuredContent": {"result": payload}} + return {"isError": False, "structuredContent": {"result": plugin}} operation, completed = acceptance.observe_worktree_removal(reply(pending, True), "fixture", "child", None) self.assertIsNone(completed) @@ -168,6 +169,44 @@ def reply(payload, error=False): with self.assertRaises(RuntimeError): acceptance.observe_worktree_removal(reply(removed, True), "fixture", "child", operation) + def test_removal_observation_retries_only_source_gateway_configuration_change(self): + operation = acceptance.uuid.UUID("91807494-d50c-4d89-9e0a-d17b608ecf66") + + def reply(code="configuration.changed", project="primary", capability="mcp.tools.call"): + return {"isError": True, "structuredContent": { + "error": {"code": code, "message": "The gateway configuration changed during preparation."}, + "gateway_execution": {"project_id": project, "capability_id": capability}, + }} + + host = object.__new__(acceptance.Host) + tool = "codex.worktree.managed.read" + selector = {"managed_worktree_id": "fixture"} + host.indirect, host.workspace = True, "primary" + host.catalog = {tool: {"inputSchema": {"properties": {"managed_worktree_id": {"type": "string"}}}}} + host.client = Mock() + host.client.send.return_value = reply() + observation = host.raw(tool, selector, gateway_envelope=True) + host.client.send.assert_called_once_with("tools/call", { + "name": "mcp.tools.call", "arguments": { + "server": "codex", "tool": tool, "project_id": "primary", "arguments": selector, + }, + }, timeout=None) + self.assertEqual(acceptance.observe_worktree_removal(observation, "fixture", "child", operation), + (operation, None)) + self.assertEqual(acceptance.observe_worktree_removal(observation, "fixture", "child", None), + (None, None)) + with self.assertRaises(RuntimeError): + host.raw(tool, selector) + + for rejected in (reply(code="permission.denied"), reply(code="gateway.execution_failed"), + reply(project="sibling"), reply(capability="mcp.tools.list"), + {"isError": True, "structuredContent": {"error": {"code": "configuration.changed"}}}): + with self.subTest(response=rejected), self.assertRaises(RuntimeError): + acceptance.observe_worktree_removal(rejected, "fixture", "child", operation) + nested = {"structuredContent": {"result": reply()}} + with self.assertRaises(AssertionError): + acceptance.observe_worktree_removal(nested, "fixture", "child", operation) + def test_archive_requires_success_or_exact_missing_rollout_identity(self): success = {"structuredContent": {"result": {}}} self.assertEqual(acceptance.archive_disposition(success, "thread-1"), "archived") diff --git a/scripts/check-host.py b/scripts/check-host.py index b83346b..117b2f4 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -197,6 +197,17 @@ def unwrap(result, indirect=False): def observe_worktree_removal(result, worktree_id, project, operation_id): + if isinstance(result, dict) and result.get("isError") is True: + structured = result.get("structuredContent") + if isinstance(structured, dict): + error = structured.get("error") + execution = structured.get("gateway_execution") + # The removal can invalidate the Host's project snapshot during read admission. + if (isinstance(error, dict) and error.get("code") == "configuration.changed" + and isinstance(execution, dict) and execution.get("capability_id") == "mcp.tools.call" + and execution.get("project_id") == "primary" and "result" not in structured): + return operation_id, None + result = unwrap(result) current = result.get("structuredContent", {}).get("result") require(isinstance(current, dict) and current["id"] == worktree_id and current["project_id"] == project and current["source_project_id"] == "primary", result) @@ -425,12 +436,12 @@ def select_project(self, project): self.workspace = project self.catalog = self.project_catalog() - def raw(self, name, arguments=None, timeout=None): + def raw(self, name, arguments=None, timeout=None, *, gateway_envelope=False): name = name if name.startswith("codex.") else "codex.app." + name arguments = arguments or {} require(set(arguments) <= self.catalog[name]["inputSchema"]["properties"].keys(), {"tool": name, "undeclared_inputs": sorted(set(arguments) - self.catalog[name]["inputSchema"]["properties"].keys())}) result = self.dispatch(name, arguments, timeout) - return unwrap(result) if self.indirect else result + return unwrap(result) if self.indirect and not gateway_envelope else result def dispatch(self, name, arguments=None, timeout=None): arguments = arguments or {} @@ -1025,7 +1036,7 @@ def remove_worktree(self, host, worktree, parent): def observe_removal(): nonlocal removal_id - observation = host.raw("codex.worktree.managed.read", selector) + observation = host.raw("codex.worktree.managed.read", selector, gateway_envelope=True) removal_id, completed = observe_worktree_removal(observation, worktree_id, project, removal_id) return completed From 39484fe030b4653fcbc0439e1607f042ea23c449 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:17:42 +0800 Subject: [PATCH 08/25] test: derive expected Codex location from the fixture home --- Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift b/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift index b898279..21ba65a 100644 --- a/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift +++ b/Tests/CodexAdapterTests/CodexProcessEnvironmentTests.swift @@ -35,14 +35,15 @@ final class CodexProcessEnvironmentTests { @Test func managedVendorHomeMatchesReaderAndChildEnvironment() { + let fixtureHome = "/tmp/container/home" var base = [ "COMPUTER_MCP_HOST_CONTEXT": "fixture", - "HOME": "/tmp/container/home", + "HOME": fixtureHome, "XDG_STATE_HOME": "/tmp/container/state", ] for explicit in [nil, "/tmp/configured-codex-home"] as [String?] { base["CODEX_HOME"] = explicit - let expected = explicit ?? "/tmp/container/home/.codex" + let expected = explicit ?? "\(fixtureHome)/.codex" let child = CodexProcessEnvironment.resolved(base: base, systemProxy: .init()) #expect(child["CODEX_HOME"] == expected) #expect(CodexProcessEnvironment.vendorHome(in: base).path == expected) From edb1c74e1ed1099076c3e117bc1d32b84fd4d029 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:22:26 +0800 Subject: [PATCH 09/25] ci: pin Host with reviewed Computer Use declarations --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 15264bc..f8d746f 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -f6de5e0c003af87722868d5c38aebb12ee656e3b +f1d29a58573ee97e5bfe7392e9c6852a508a706f From 900cab1c5ae534f0af4e40f66344cc9cf8738db7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:27:40 +0800 Subject: [PATCH 10/25] fix(test): fail registered acceptance on skills directory errors --- Tests/test_host_acceptance.py | 39 ++++++++++++++++++++++++++++++++++- scripts/check-host.py | 10 +++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index 14e622d..d62086a 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -8,7 +8,7 @@ import subprocess import tempfile import unittest -from unittest.mock import Mock, patch +from unittest.mock import Mock, call, patch SCRIPT = Path(__file__).resolve().parents[1] / "scripts/check-host.py" spec = importlib.util.spec_from_file_location("host_acceptance", SCRIPT) @@ -148,6 +148,43 @@ def test_nested_tool_errors_cannot_be_success(self): with self.assertRaises(RuntimeError): acceptance.unwrap(failure, indirect="structuredContent" in failure) + 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") + error = {"path": cwd + "/skills", "message": "Failed to synchronize managed preferences"} + with patch.object(acceptance, "Host") as host: + host.return_value.method.return_value = {"data": [{"cwd": cwd, "skills": [], "errors": [error]}]} + with self.assertRaisesRegex( + AssertionError, "skills/list.*Failed to synchronize managed preferences", + ) as failure: + fixture.directories() + self.assertIn(error["path"], str(failure.exception)) + host.return_value.method.assert_called_once_with( + "skills/list", {"cwds": [cwd], "forceReload": False}, timeout=35, + ) + self.assertEqual(fixture.steps, []) + + def test_directory_results_without_errors_continue_to_apps(self): + fixture = acceptance.Fixture(acceptance.parse_arguments(self.arguments + ["--mode", "fixture"])) + cwd = str(fixture.root / "primary") + skill = {"name": "fixture", "description": "Acceptance skill", "enabled": True, + "path": cwd + "/skills/fixture/SKILL.md", "scope": "user"} + for skills in ([], [skill]): + with self.subTest(skills=skills), patch.object(acceptance, "Host") as host, \ + contextlib.redirect_stdout(io.StringIO()): + host.return_value.method.side_effect = [ + {"data": [{"cwd": cwd, "skills": skills, "errors": []}]}, + {"data": []}, + ] + fixture.directories() + self.assertEqual(host.return_value.method.call_args_list, [ + call("skills/list", {"cwds": [cwd], "forceReload": False}, timeout=35), + call("app/list", {"limit": 1, "forceRefetch": False}, timeout=125), + ]) + host.return_value.processes.assert_called_once_with() + host.return_value.close.assert_called_once_with() + self.assertEqual(fixture.steps, ["skills-explicit-directory-and-app-list-deadlines"] * 2) + def test_removal_observations_wait_on_the_same_bound_pending_operation(self): pending = {"id": "fixture", "project_id": "child", "source_project_id": "primary", "operation_id": "91807494-d50c-4d89-9e0a-d17b608ecf66", diff --git a/scripts/check-host.py b/scripts/check-host.py index 117b2f4..4e0004a 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -753,10 +753,16 @@ def catalog_and_diagnostics(self): def directories(self): host = Host(self) + cwd = str(self.root / "primary") started = time.monotonic() - skills = host.method("skills/list", {"cwds": [str(self.root / "primary")], "forceReload": False}, timeout=35) + skills = host.method("skills/list", {"cwds": [cwd], "forceReload": False}, timeout=35) require(time.monotonic() - started < 30, "skills/list exceeded normal deadline") - require(len(skills["data"]) == 1 and skills["data"][0]["cwd"] == str(self.root / "primary"), skills) + require(len(skills["data"]) == 1 and skills["data"][0]["cwd"] == cwd, skills) + errors = skills["data"][0].get("errors") + require( + errors == [], + f"skills/list expected no directory errors for {cwd}, got {json.dumps(errors, ensure_ascii=False)}", + ) started = time.monotonic() apps = host.method("app/list", {"limit": 1, "forceRefetch": False}, timeout=125) require(time.monotonic() - started < 120 and len(apps["data"]) <= 1, apps) From c75060d4cfc9257b7b32d325054629e7001b41d8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:38:27 +0800 Subject: [PATCH 11/25] feat: declare Codex service access and document native sign-in --- Documentation/Reference/HostIntegration.md | 15 +++++++++++ Documentation/Reference/Workflows.md | 27 +++++++++++++++++++ .../CodexAppAsyncWorkTests.swift | 6 ++--- Tests/test_package.py | 12 +++++++++ computer-mcp-plugin.toml | 4 +++ 5 files changed, 61 insertions(+), 3 deletions(-) diff --git a/Documentation/Reference/HostIntegration.md b/Documentation/Reference/HostIntegration.md index 2794d0e..56aa0cf 100644 --- a/Documentation/Reference/HostIntegration.md +++ b/Documentation/Reference/HostIntegration.md @@ -66,6 +66,21 @@ Native approval responses bind to the original SDK server request and can be consumed once. The host applies its own authorization and confirmation to callbacks. +### Codex network access + +The package requests outbound access to `api.openai.com` and `chatgpt.com` for +the default Codex model endpoints and `auth.openai.com` for OpenAI sign-in. +The custom list uses exact hostnames and excludes the Host's trusted-host list. +Host Full access is off by default. + +The list is the maximum the package requests for sandboxed execution. At +enablement the owner reviews the declaration and can select less access within +the Host's policy limits. An update that adds network access requires fresh +owner approval before the added access applies. For an enterprise deployment +with a different provider or issuer, verify its endpoints against that +deployment's configuration and review any declaration change through the same +Host flow. + ## Host worktrees Codex stores reviewed selections and writer leases. Computer MCP owns creation, diff --git a/Documentation/Reference/Workflows.md b/Documentation/Reference/Workflows.md index d2d3df1..7acfb29 100644 --- a/Documentation/Reference/Workflows.md +++ b/Documentation/Reference/Workflows.md @@ -15,6 +15,33 @@ by the runtime; do not substitute upstream thread IDs for local handles. | Operational diagnostics | `codex.diagnostics.snapshot`, with optional bounded `limit` | | Exec | `codex.exec.start` / `resume`; inspect `list` / `events` / `result`; `cancel` while running; `release` after cleanup | +## Sign in to registered Codex + +Use the same registered App Server runtime for the account calls and events. +Prepend the registration's configured prefix to each tool name when present. + +1. Call `codex.app.native.account.read` to check the current account. +2. To sign in, call `codex.app.native.account.login.start` with + `{"params":{"type":"chatgpt"}}` for browser sign-in or + `{"params":{"type":"chatgptDeviceCode"}}` for device-code sign-in. Keep the + returned `loginId`. +3. The account owner completes the vendor confirmation. Open `authUrl` for + browser sign-in, or open `verificationUrl` and enter the returned `userCode` + for device-code sign-in. +4. Read `codex.app.events.read` for `account/login/completed` with the matching + `loginId`. Check `success` and any `error`, then call + `codex.app.native.account.read` again to verify the account. + +Codex stores the sign-in state in the registered provider's private vendor +home. Browser sign-in needs Codex to bind a local callback listener, which can +fail in the registered sandbox even with approved outbound access. Device-code +sign-in uses outbound requests and depends on the vendor making it available +for the account. If App Server rejects the start request, the adapter surfaces +the native error as `codex.app.request_failed`. After an accepted start, a +failed completion is reported in the matching notification. Use the vendor +error and the runtime's [reviewed network access](HostIntegration.md#codex-network-access) +to diagnose the failure on that installation. + ## Native coding configuration Exec start accepts `prompt` and optional `model` and `options`; resume accepts diff --git a/Tests/CodexAdapterTests/CodexAppAsyncWorkTests.swift b/Tests/CodexAdapterTests/CodexAppAsyncWorkTests.swift index b9ab59e..50f6a01 100644 --- a/Tests/CodexAdapterTests/CodexAppAsyncWorkTests.swift +++ b/Tests/CodexAdapterTests/CodexAppAsyncWorkTests.swift @@ -4,13 +4,13 @@ import Testing @testable import CodexAdapter struct CodexAppAsyncWorkTests { - @Test - func nativeLoginAcknowledgementEnrichesTheSameOwnedLifetime() throws { + @Test(arguments: ["chatgpt", "chatgptDeviceCode"]) + func nativeLoginAcknowledgementEnrichesTheSameOwnedLifetime(type: String) throws { var work = CodexAppAsyncWork() let creator = UUID() let ticket = try CodexWorkInvocation.$current.withValue(creator) { try work.prepare( - method: "account/login/start", params: .object(["type": .string("chatgpt")]), + method: "account/login/start", params: .object(["type": .string(type)]), generation: 1) } let pending = try #require(work.workResources().first) diff --git a/Tests/test_package.py b/Tests/test_package.py index 440664b..ff201d1 100644 --- a/Tests/test_package.py +++ b/Tests/test_package.py @@ -141,6 +141,18 @@ def test_named_archives_select_exact_platform_and_architecture_without_manifest_ package.validate_architectures(manifest, slices, platform) self.assertEqual(manifest.read_bytes(), original) + def test_manifest_requests_only_the_default_codex_network_hosts(self): + manifest = Path(__file__).resolve().parents[1] / "computer-mcp-plugin.toml" + with manifest.open("rb") as source: + sandbox = package.tomllib.load(source)["sandbox"] + network = sandbox["network"] + self.assertEqual(network["level"], "custom") + self.assertCountEqual(network["hosts"], ["api.openai.com", "chatgpt.com", "auth.openai.com"]) + self.assertNotIn("github.com", network["hosts"]) + self.assertIs(network["include_trusted"], False) + self.assertIs(sandbox.get("full_access", False), False) + self.assertFalse(sandbox.get("read_exceptions")) + def test_package_rejects_slice_mismatch_and_manifest_mutation_before_publication(self): for failure in ("slice_mismatch", "manifest_mutation", "version_mismatch"): with self.subTest(failure=failure), tempfile.TemporaryDirectory() as directory: diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index fd24108..654b0a0 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -9,6 +9,10 @@ id = "project" access = "write" purpose = "Create and remove managed worktrees in projects you approve for Codex." +[sandbox] +network = { level = "custom", hosts = ["api.openai.com", "chatgpt.com", "auth.openai.com"], include_trusted = false } +purpose = "Connect Codex to OpenAI model endpoints and the ChatGPT sign-in service." + [[mcp]] id = 'app-server' transport = 'stdio' From 979a3d9922d533a86bfa981617e46a538d725bd3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:14:20 +0800 Subject: [PATCH 12/25] ci: run consumer checks against the corrected host fixtures --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index f8d746f..7631746 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -f1d29a58573ee97e5bfe7392e9c6852a508a706f +93b228f4ccc628848e7f892f8044f51444bed746 From 3f6870f5cd48bc1c9703abd2b36949a068b25ad8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:24:20 +0800 Subject: [PATCH 13/25] test: identify the last registered tool call in failed CI reports --- Tests/test_host_acceptance.py | 47 +++++++++++++++++++++++++++++++++++ scripts/check-host.py | 6 +++++ 2 files changed, 53 insertions(+) diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index d62086a..6af7f01 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 +from types import SimpleNamespace import unittest from unittest.mock import Mock, call, patch @@ -148,6 +149,51 @@ def test_nested_tool_errors_cannot_be_success(self): with self.assertRaises(RuntimeError): acceptance.unwrap(failure, indirect="structuredContent" in failure) + def test_registered_report_keeps_last_tool_call_before_cleanup_on_failure(self): + project = "derived-fixture-project" + steps = ["host-created-associated-worktree", "restarted-without-live-runtime-authority-or-reported-work"] + failure = {"isError": True, "structuredContent": { + "error": {"code": "gateway.execution_failed", "message": "Client disconnected"}, + }} + cases = ( + ("codex.app.thread.loaded.list", failure, 1), + ("mcp.tools.list", failure, 1), + ("mcp.tools.list", {"structuredContent": {"result": []}}, 0), + ) + for index, (tool, response, status) in enumerate(cases): + with self.subTest(tool=tool, status=status): + arguments = self.container_arguments("a" * 40) + arguments[-1] = str(self.root / f"output-{index}") + options = acceptance.parse_arguments(arguments) + fixture = acceptance.Fixture(options) + fixture.steps.extend(steps) + host = object.__new__(acceptance.Host) + host.fixture, host.indirect, host.workspace = fixture, True, project + host.catalog = {tool: {"inputSchema": {"properties": {}}}} + host.client = Mock(send=Mock(side_effect=[response, {}])) + operation = host.project_catalog if tool == "mcp.tools.list" else lambda: host.call("thread.loaded.list") + + def cleanup(): + host.dispatch("codex.diagnostics.snapshot") + return [] + + with patch.object(acceptance, "Fixture", return_value=fixture), \ + patch.object(fixture, "setup"), \ + patch.object(fixture, "registered_container", side_effect=operation), \ + patch.object(fixture, "cleanup", side_effect=cleanup), \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(acceptance.run(options), status) + + report = json.loads((fixture.root / "report.json").read_text()) + self.assertEqual(fixture.last_tool_call["tool"], "codex.diagnostics.snapshot") + self.assertEqual(report["passed"], status == 0) + self.assertEqual(report["steps"], steps) + if status: + self.assertEqual(report["failure"], json.dumps(failure, ensure_ascii=False)) + self.assertEqual(report["last_tool_call"], {"tool": tool, "project_id": project}) + else: + self.assertNotIn("last_tool_call", report) + 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") @@ -216,6 +262,7 @@ def reply(code="configuration.changed", project="primary", capability="mcp.tools }} host = object.__new__(acceptance.Host) + host.fixture = SimpleNamespace() tool = "codex.worktree.managed.read" selector = {"managed_worktree_id": "fixture"} host.indirect, host.workspace = True, "primary" diff --git a/scripts/check-host.py b/scripts/check-host.py index 4e0004a..fef6621 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -427,6 +427,7 @@ def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None) "Generic dispatch lacks project selection") def project_catalog(self): + self.fixture.last_tool_call = {"tool": "mcp.tools.list", "project_id": self.workspace} tools = unwrap(self.client.send("tools/call", { "name": "mcp.tools.list", "arguments": {"server": "codex", "project_id": self.workspace}, })) @@ -450,6 +451,7 @@ def dispatch(self, name, arguments=None, timeout=None): "project_id": self.workspace, "arguments": arguments}} else: params = {"name": name, "arguments": dict(arguments, project_id=self.workspace)} + self.fixture.last_tool_call = {"tool": name, "project_id": self.workspace} return self.client.send("tools/call", params, timeout=timeout) def call(self, name, arguments=None, timeout=None): @@ -540,6 +542,7 @@ def __init__(self, options): self.options, self.root = options, options.output_directory.resolve() self.root.mkdir(mode=0o700, parents=True) self.hosts, self.pids, self.threads, self.steps = [], set(), set(), [] + self.last_tool_call = None self.generation = 0 self.model = None self.model_log = None @@ -1366,6 +1369,7 @@ def run(options, provenance=None): except Exception as error: report["failure"] = str(error) finally: + last_tool_call = fixture.last_tool_call report["cleanup_errors"] = [] try: (fixture.home / "auth.json").unlink(missing_ok=True) @@ -1387,6 +1391,8 @@ def run(options, provenance=None): report["binary_digests_unchanged"] = False report["cleanup_errors"].append(f"Binary digest verification: {error}") report["passed"] = report["passed"] and not report["cleanup_errors"] and report["binary_digests_unchanged"] + if options.mode == "container" and not report["passed"] and last_tool_call is not None: + report["last_tool_call"] = last_tool_call (fixture.root / "report.json").write_text(json.dumps(report, indent=2) + "\n") print(json.dumps({"passed": report["passed"], "mode": options.mode, "authenticated_model_verified": report["authenticated_model_verified"], From 08c170810548b3af4e1134c7689a6c5ae25b2dc7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:52:35 +0800 Subject: [PATCH 14/25] ci: verify the consumer against the mounted-project fix --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 7631746..a0f9b77 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -93b228f4ccc628848e7f892f8044f51444bed746 +45ac094f2f5f9c2d1c37e67acb59e9975465695e From 2b498c425ebb708933e99baa51684e22bd2e50ff Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:24:56 +0800 Subject: [PATCH 15/25] docs: describe sessions through the local Codex runtime --- Documentation/Reference/Workflows.md | 33 ++++++---------------------- 1 file changed, 7 insertions(+), 26 deletions(-) diff --git a/Documentation/Reference/Workflows.md b/Documentation/Reference/Workflows.md index 7acfb29..784c6c6 100644 --- a/Documentation/Reference/Workflows.md +++ b/Documentation/Reference/Workflows.md @@ -15,32 +15,13 @@ by the runtime; do not substitute upstream thread IDs for local handles. | Operational diagnostics | `codex.diagnostics.snapshot`, with optional bounded `limit` | | Exec | `codex.exec.start` / `resume`; inspect `list` / `events` / `result`; `cancel` while running; `release` after cleanup | -## Sign in to registered Codex - -Use the same registered App Server runtime for the account calls and events. -Prepend the registration's configured prefix to each tool name when present. - -1. Call `codex.app.native.account.read` to check the current account. -2. To sign in, call `codex.app.native.account.login.start` with - `{"params":{"type":"chatgpt"}}` for browser sign-in or - `{"params":{"type":"chatgptDeviceCode"}}` for device-code sign-in. Keep the - returned `loginId`. -3. The account owner completes the vendor confirmation. Open `authUrl` for - browser sign-in, or open `verificationUrl` and enter the returned `userCode` - for device-code sign-in. -4. Read `codex.app.events.read` for `account/login/completed` with the matching - `loginId`. Check `success` and any `error`, then call - `codex.app.native.account.read` again to verify the account. - -Codex stores the sign-in state in the registered provider's private vendor -home. Browser sign-in needs Codex to bind a local callback listener, which can -fail in the registered sandbox even with approved outbound access. Device-code -sign-in uses outbound requests and depends on the vendor making it available -for the account. If App Server rejects the start request, the adapter surfaces -the native error as `codex.app.request_failed`. After an accepted start, a -failed completion is reported in the matching notification. Use the vendor -error and the runtime's [reviewed network access](HostIntegration.md#codex-network-access) -to diagnose the failure on that installation. +## Codex session + +Sign in using Codex on your computer. The plugin sends requests to the bound +Codex runtime, which owns the account and reports its status. If a request +requires authentication, use the vendor result for that runtime. The Host +launches the registered provider with a private home, so a separate Codex +installation reporting a signed-in account does not verify this connection. ## Native coding configuration From 804586069d16f2ac14da9e3664e1e2d938effbff Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:05:34 +0800 Subject: [PATCH 16/25] ci: validate against the integrated Host candidate --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index a0f9b77..4d53469 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -45ac094f2f5f9c2d1c37e67acb59e9975465695e +feafb1088e88e45563a95bbf9a996998d2fa7180 From daad512f50454c30d7e55d88e33f9b9b1421ff36 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:24:41 +0800 Subject: [PATCH 17/25] ci: test against the reviewed Host revision --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 4d53469..da31c2d 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -feafb1088e88e45563a95bbf9a996998d2fa7180 +a34a17ca6ec24d8810002deb224a6d2e469ff282 From 8104b98160175f1780968a6e76e872e50b802c12 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 20:23:59 +0800 Subject: [PATCH 18/25] fix: correlate host diagnostics with the admitted invocation --- Documentation/Reference/HostIntegration.md | 41 +++++++----- Documentation/Reference/Installation.md | 13 ++-- .../CodexAdapter/CodexAppServerProvider.swift | 3 +- Sources/CodexAdapter/CodexHostMCPClient.swift | 8 ++- Sources/CodexAdapter/CodexHostServices.swift | 3 +- .../CodexHostMCPClientTests.swift | 67 +++++++++++++++++-- .../CodexOperationalDiagnosticsTests.swift | 3 +- scripts/check-host.py | 3 + 8 files changed, 110 insertions(+), 31 deletions(-) diff --git a/Documentation/Reference/HostIntegration.md b/Documentation/Reference/HostIntegration.md index 56aa0cf..2d4988e 100644 --- a/Documentation/Reference/HostIntegration.md +++ b/Documentation/Reference/HostIntegration.md @@ -93,10 +93,13 @@ Plan and provision in the source project. Copy the returned `perform_arguments`, including any explicit nulls. Omitted or null `branch` selects `worktree/`. Omitted or null `base` selects the source main checkout's current branch when the host reserves the perform call. Supply an explicit base -branch for a detached source. The resolved result includes the child project, -worktree ID, checkout path, branch, base and warnings. Lease disposition is -reported separately. If the child has a conflicting writer lease, settle that -lease before acquiring one explicitly in the child. +branch for a detached source. An adapter in a read-only source project sandbox +can request provisioning when the caller has the required host authorization. +Computer MCP performs the Git writes and registers the child project while the +source adapter stays within its read-only sandbox. The resolved result includes +the child project, worktree ID, checkout path, branch, base and warnings. Lease +disposition is reported separately. If the child has a conflicting writer lease, +settle that lease before acquiring one explicitly in the child. Select the returned child project to release its Codex writer lease and plan removal. The review binds `force`, which defaults to false. The host drains @@ -120,12 +123,19 @@ Lease expiry changes metadata only. ## Diagnostics `codex.diagnostics.snapshot` combines adapter state with host records only when -this callback service is available. The host filters records by project, -verified subject and profile before limiting the result. Connection and channel -identifiers remain audit metadata, not new authorization subjects. It exposes -receipt IDs and digests rather than command bodies or secrets. Native configuration overrides and actual resolved configuration remain -distinct. Use `config/read` through `codex.app.methods.call` for the vendor -configuration; diagnostics do not infer effective Full Access from host grants. +this callback service is available. Deploy the Codex adapter with a Computer MCP +host that supports the optional `invocation_id` on the private +`host.diagnostics.snapshot` callback, then restart the provider. Registered +dispatch forwards the admitted invocation UUID from host request metadata and +the requested limit. Callers can set `limit` on the public tool. Standalone +diagnostics report adapter state. + +The host filters records by project, verified subject and profile before limiting +the result. Connection and channel identifiers are audit metadata. The tool exposes +receipt IDs and digests, and the host keeps command bodies and secrets. Adapter +diagnostics report native configuration overrides. Use `config/read` through +`codex.app.methods.call` to see the resolved vendor configuration and check Full +Access. The host permits 1–1000 requested records and bounds the complete service result. Reduce `limit` when the response would exceed the byte limit. Inspection does not @@ -170,11 +180,12 @@ another client must be resolved through that client's controls. Never use ### Execution or permissions fail Inspect App Server with `codex.app.status` and Exec with `codex.exec.list` -independently. The host's provider/package doctor checks availability; it does -not prove model authentication. Verify the selected executable and native -configuration, including personal provider, MCP, Skills and hooks settings. -A slow or broken personal integration can delay startup. Diagnose credentials -in Codex's own store rather than copying them into host configuration. +independently. The host's `plugins doctor codex` checks package and adapter +availability. The Codex adapter resolves the vendor CLI when it needs to start +Codex. Verify the configured vendor executable, its model authentication, and +native configuration, including personal provider, MCP, Skills and hooks +settings. A slow or broken personal integration can delay startup. Diagnose +credentials in Codex's own store rather than copying them into host configuration. An unavailable custom program fails explicitly; it never falls back to a different executable. For a non-Git initial directory, select Exec's native `options.skip_git_repo_check` explicitly. diff --git a/Documentation/Reference/Installation.md b/Documentation/Reference/Installation.md index 5a0f38d..1c24bda 100644 --- a/Documentation/Reference/Installation.md +++ b/Documentation/Reference/Installation.md @@ -24,8 +24,9 @@ each file and archive SHA-256, platform, architecture and build configuration. It is not an official-source or publisher signature. No artifact is uploaded or installed automatically. -The repository manifest declares `codex-plugin-macos-arm64.zip`. Packaging -requires the built adapter to match the declared platform and architecture. +The distributed archive, `codex-plugin-macos-arm64.zip`, is for Apple silicon +(`arm64`) Macs. Packaging requires the built adapter to match the declared +platform and architecture. The archive carries the repository's exact manifest bytes; its `platform_paths` selects the executable. The manifest's `minimum_host` declares the required Computer MCP version. Official GitHub installation verifies the archive @@ -104,10 +105,10 @@ whole settings object. Setting `args` to null follows package defaults, while an empty array starts the adapter in protocol-inspection mode. App changes and CLI changes use the same host transaction and stale-revision protection. -Use `plugins doctor codex` for package/file checks. A successful report is not -a model-authentication or complete-workflow readiness claim. Discovery itself -does not launch Codex. Host launch metadata binds the workspace and read-only -boundary when serving through Computer MCP. +Use `plugins doctor codex` to check package files and adapter availability. +The adapter resolves the vendor CLI when starting Codex. Model authentication +and workflow readiness are separate checks. Host launch metadata binds the +workspace and read-only boundary when serving through Computer MCP. ## Stop, update, roll back and remove diff --git a/Sources/CodexAdapter/CodexAppServerProvider.swift b/Sources/CodexAdapter/CodexAppServerProvider.swift index a86a572..d59afbf 100644 --- a/Sources/CodexAdapter/CodexAppServerProvider.swift +++ b/Sources/CodexAdapter/CodexAppServerProvider.swift @@ -78,7 +78,8 @@ struct CodexAppServerProvider: Sendable { case "codex.diagnostics.snapshot": let limit = try Self.boundedInt("limit", in: object, default: 100, range: 1...1_000) let now = Date() - let hostSnapshot = try await hostDiagnostics?.snapshot(limit: limit, now: now) + let hostSnapshot = try await hostDiagnostics?.snapshot( + limit: limit, invocationID: hostInvocation?.invocationID, now: now) result = try await CodexOperationalDiagnostics.snapshot( database: database, owner: owner, configuredSandbox: configuredSandbox, limit: limit, hostSnapshot: hostSnapshot, unboundStateAvailable: unboundStateAvailable, diff --git a/Sources/CodexAdapter/CodexHostMCPClient.swift b/Sources/CodexAdapter/CodexHostMCPClient.swift index 1de76b6..ac84b41 100644 --- a/Sources/CodexAdapter/CodexHostMCPClient.swift +++ b/Sources/CodexAdapter/CodexHostMCPClient.swift @@ -247,11 +247,15 @@ actor CodexHostMCPClient: CodexHostTools, CodexProjectServices, } extension CodexHostMCPClient { - func snapshot(limit: Int, now: Date) async throws -> CodexHostDiagnosticSnapshot { + func snapshot(limit: Int, invocationID: UUID?, now: Date) async throws + -> CodexHostDiagnosticSnapshot + { guard (1...1000).contains(limit) else { throw CodexToolError.invalidArguments("Host diagnostic limit must be 1...1000.") } - let value = try await service("host.diagnostics.snapshot", ["limit": .integer(Int64(limit))]) + var arguments: [String: JSONValue] = ["limit": .integer(Int64(limit))] + if let invocationID { arguments["invocation_id"] = .string(invocationID.uuidString) } + let value = try await service("host.diagnostics.snapshot", arguments) guard let object = value.objectValue, let returnedOwner = object["owner"], try JSONDecoder().decode( diff --git a/Sources/CodexAdapter/CodexHostServices.swift b/Sources/CodexAdapter/CodexHostServices.swift index d39feab..ceab432 100644 --- a/Sources/CodexAdapter/CodexHostServices.swift +++ b/Sources/CodexAdapter/CodexHostServices.swift @@ -4,7 +4,8 @@ import Foundation /// visible, bounded audit receipts. /// This interface does not confer database access or approval authority. protocol CodexHostDiagnostics: Sendable { - func snapshot(limit: Int, now: Date) async throws -> CodexHostDiagnosticSnapshot + func snapshot(limit: Int, invocationID: UUID?, now: Date) async throws + -> CodexHostDiagnosticSnapshot } struct CodexHostDiagnosticSnapshot: Sendable { diff --git a/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift b/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift index 76f38e4..4c69a74 100644 --- a/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift +++ b/Tests/CodexAdapterTests/CodexHostMCPClientTests.swift @@ -156,6 +156,54 @@ struct CodexHostMCPClientTests { } } + @Test(arguments: [false, true]) + func diagnosticsDispatchForwardsLimitAndOptionalHostInvocation(_ admitted: Bool) async throws { + let host = try HostClientFixture( + peerContract: CodexProjectContract.identifier, + launchContract: CodexProjectContract.identifier) + let provider = CodexAppServerProvider( + appServer: FakeAppServerRuntime(), owner: host.owner, database: nil, + workspaceURL: URL(fileURLWithPath: "/tmp"), recentThreadReader: nil, + localControlAllowed: false, hostDiagnostics: host.client) + let pair = await InMemoryTransport.createConnectedPair() + try await pair.server.connect() + try await host.start() + let serving = Task { + try await CodexAdapterServer.serve(transport: pair.server, appServer: provider) + } + let client = MCP.Client(name: "diagnostics-dispatch-fixture", version: "1") + do { + _ = try await client.connect(transport: pair.client) + let invocationID = UUID() + let metadata = + admitted + ? MCP.Metadata(additionalFields: [ + CodexHostInvocation.invocationKey: .string(invocationID.uuidString) + ]) : nil + let request = try await client.send( + MCP.CallTool.request( + .init(name: "codex.diagnostics.snapshot", arguments: ["limit": .int(7)], meta: metadata))) + let response = try await request.value + #expect(response.isError == false) + let result = try #require(response.structuredContent?.objectValue?["result"]?.objectValue) + #expect(result["host_diagnostics_available"] == .bool(true)) + let calls = await host.state.calls + #expect(calls.map(\.0) == ["host.diagnostics.snapshot"]) + var expectedArguments: [String: MCP.Value] = ["limit": .int(7)] + if admitted { expectedArguments["invocation_id"] = .string(invocationID.uuidString) } + #expect(calls.first?.1 == expectedArguments) + await client.disconnect() + try await serving.value + await host.close() + } catch { + await client.disconnect() + await pair.server.disconnect() + await host.close() + _ = try? await serving.value + throw error + } + } + @Test(arguments: [nil, "projects-v0", "projects-v1"] as [String?]) func lifecycleRequiresObservedHostContract(_ marker: String?) async throws { let fixture = try HostClientFixture(peerContract: marker, launchContract: "projects-v1") @@ -210,6 +258,10 @@ struct CodexHostMCPClientTests { private final class HostClientFixture: Sendable { let state = HostClientState() + let owner = CodexRuntimeOwner( + workspaceID: "fixture", profileID: "fixture", caller: "secure-tunnel", + transport: "gateway_socket", socketConnectionID: "fixture-socket", tunnelInstanceID: nil, + tunnelProfileID: nil, principalID: "subject-a") let transport: MCPInheritedSocketTransport let client: CodexHostMCPClient let server = MCP.Server(name: "host-fixture", version: "1", capabilities: .init(tools: .init())) @@ -219,11 +271,7 @@ private final class HostClientFixture: Sendable { let pair = try MCPInheritedSocketTransport.makePair() transport = try MCPInheritedSocketTransport(takingOwnershipOf: pair.0) client = try CodexHostMCPClient( - takingOwnershipOf: pair.1, - owner: .init( - workspaceID: "fixture", profileID: "fixture", caller: "secure-tunnel", - transport: "gateway_socket", socketConnectionID: "fixture-socket", tunnelInstanceID: nil, - tunnelProfileID: nil, principalID: "subject-a"), launchContract: launchContract) + takingOwnershipOf: pair.1, owner: owner, launchContract: launchContract) } func start() async throws { await server.withMethodHandler(MCP.CallTool.self) { [state] params in @@ -258,6 +306,15 @@ private actor HostClientState { "decision": .string("allowed"), "capability_id": arguments["capability_id"]!, "risk": .string(risk), "requirements": .object([:]), ]) + } else if params.name == "host.diagnostics.snapshot" { + result = .object([ + "owner": .object([ + "project_id": .string("fixture"), "profile_id": .string("fixture"), + "caller": .string("secure-tunnel"), "transport": .string("gateway_socket"), + "socket_connection_id": .string("fixture-socket"), "principal_id": .string("subject-a"), + ]), + "recent_tool_audits": .array([]), + ]) } else if params.name == "host.projects.worktree_add" { return .init( content: [.text(text: "fixture refusal", annotations: nil, _meta: nil)], diff --git a/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift b/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift index b40fff9..55f8663 100644 --- a/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift +++ b/Tests/CodexAdapterTests/CodexOperationalDiagnosticsTests.swift @@ -348,8 +348,9 @@ private struct HostDiagnosticsStub: CodexHostDiagnostics { let value: CodexHostDiagnosticSnapshot let denied: Bool - func snapshot(limit: Int, now: Date) throws -> CodexHostDiagnosticSnapshot { + func snapshot(limit: Int, invocationID: UUID?, now: Date) throws -> CodexHostDiagnosticSnapshot { #expect(limit == 1) + #expect(invocationID == nil) if denied { throw CodexToolError.disabled("Fixture host denied audit access.") } return value } diff --git a/scripts/check-host.py b/scripts/check-host.py index fef6621..780882d 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -1198,6 +1198,9 @@ def registered_container(self): require(any(row["decision"] == "allowed" and row["socket_connection_id"] == execution["socket_connection_id"] for row in reads), reads) + bounded = host.call("codex.diagnostics.snapshot", {"limit": 1}) + require(bounded["host_diagnostics_available"] + and len(bounded["recent_tool_audits"]) == 1, bounded) (self.root / f"vendor-{generation}.json").write_text(json.dumps(vendor, indent=2) + "\n") if generation == 1: worktree, parent = self.provision_worktree(host) From ee4782350d9e3648707dea404fba4f8a16a99bc0 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:11:44 +0800 Subject: [PATCH 19/25] feat: declare scoped Codex tool requirements --- .github/computer-mcp-host.sha | 2 +- Documentation/Reference/HostIntegration.md | 21 +- Documentation/Reference/Installation.md | 9 +- Documentation/Reference/Release.md | 10 +- .../CodexAdapter/CodexAppServerRuntime.swift | 102 ++-- Sources/CodexAdapter/CodexDatabase.swift | 31 +- Sources/CodexAdapter/CodexLaunchContext.swift | 3 +- .../CodexThreadOwnershipReconciliation.swift | 2 +- .../CodexAppServerRuntimeTests.swift | 26 +- .../CodexDatabaseTests.swift | 29 +- .../RegisteredHost/RegisteredHost.swift | 79 ++- Tests/test_host_acceptance.py | 28 +- computer-mcp-plugin.toml | 22 +- scripts/check-host.py | 513 ++++++++++++++++-- 14 files changed, 759 insertions(+), 118 deletions(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index da31c2d..cb42063 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -a34a17ca6ec24d8810002deb224a6d2e469ff282 +504d1d434a192a2d7c4595f8888ebb63f728f228 diff --git a/Documentation/Reference/HostIntegration.md b/Documentation/Reference/HostIntegration.md index 2d4988e..3828ea2 100644 --- a/Documentation/Reference/HostIntegration.md +++ b/Documentation/Reference/HostIntegration.md @@ -42,6 +42,16 @@ minimum risk, never to reduce a configured restriction or grant access. `codex.app.methods.list` provides the same per-method classification for configuration review. MCP annotations remain advisory. +The caller needs Plugin use and the Host's project selection and risk checks. +The four protocol and App Server method catalog tools add no Project minimum +of their own. The diagnostics snapshot, managed-worktree list, lease list and +read, and lease cleanup preview require Project read. Worktree provision and +removal, lease changes, and managed-worktree read require Project write. +Managed-worktree read can settle a pending Host operation and acquire its +writer lease. A derived project inherits its source project's authority. +Other tools use the Host's conservative check against the provider's effective +sensitive grants, including grants on unrelated targets. + The package contribution and both MCP initialization responses identify the `projects-v1` contract. The adapter also checks the host launch context before sending lifecycle requests. A missing or mismatched contract produces @@ -139,8 +149,11 @@ Access. The host permits 1–1000 requested records and bounds the complete service result. Reduce `limit` when the response would exceed the byte limit. Inspection does not -start Codex or a model. Real vendor/model authentication and GUI permissions are -separate checks from the host callback protocol. +start Codex or a model. Cold discovery and reads can initialize adapter storage +and migrate older unmanaged worktree history. Approval recovery runs through the +approval tools or before native App Server startup. Real vendor/model +authentication and GUI permissions are separate checks from the host callback +protocol. Use the host's generic tool command with the exported name. The examples assume an empty MCP registration prefix; prepend the configured prefix when present. @@ -180,8 +193,8 @@ another client must be resolved through that client's controls. Never use ### Execution or permissions fail Inspect App Server with `codex.app.status` and Exec with `codex.exec.list` -independently. The host's `plugins doctor codex` checks package and adapter -availability. The Codex adapter resolves the vendor CLI when it needs to start +independently. The host's `plugins doctor codex` inspects configuration, package +files and adapter availability. The Codex adapter resolves the vendor CLI when it needs to start Codex. Verify the configured vendor executable, its model authentication, and native configuration, including personal provider, MCP, Skills and hooks settings. A slow or broken personal integration can delay startup. Diagnose diff --git a/Documentation/Reference/Installation.md b/Documentation/Reference/Installation.md index 1c24bda..6bb45a7 100644 --- a/Documentation/Reference/Installation.md +++ b/Documentation/Reference/Installation.md @@ -25,7 +25,9 @@ It is not an official-source or publisher signature. No artifact is uploaded or installed automatically. The distributed archive, `codex-plugin-macos-arm64.zip`, is for Apple silicon -(`arm64`) Macs. Packaging requires the built adapter to match the declared +(`arm64`) Macs. The manifest also declares Intel (`x86_64`) compatibility. +An Intel archive and runtime acceptance are separate from this distribution. +Packaging requires the built adapter to match the declared platform and architecture. The archive carries the repository's exact manifest bytes; its `platform_paths` selects the executable. The manifest's `minimum_host` declares the required @@ -105,8 +107,9 @@ whole settings object. Setting `args` to null follows package defaults, while an empty array starts the adapter in protocol-inspection mode. App changes and CLI changes use the same host transaction and stale-revision protection. -Use `plugins doctor codex` to check package files and adapter availability. -The adapter resolves the vendor CLI when starting Codex. Model authentication +Use `plugins doctor codex` to inspect saved configuration, package files and +adapter availability. The adapter resolves the vendor CLI when starting Codex. +Sign in through the vendor's own login flow. Model authentication and workflow readiness are separate checks. Host launch metadata binds the workspace and read-only boundary when serving through Computer MCP. diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index abfcd79..96291f9 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -121,10 +121,18 @@ registering it in the disposable Host database. The report in executables and the authorization revisions. The driver uses a deterministic vendor peer with network access disabled. Through standard MCP it verifies project and caller binding, Host worktree creation and removal, persisted state across restart, and caller and -provider revocation. The restart check confirms that a dead runtime receipt +provider revocation. It also checks exact tool requirements, cold discovery +and reads, and lease and worktree ownership across callers and derived +projects. The restart check confirms that a dead runtime receipt grants no live authority and uses the adapter's stale-record cleanup when needed. Rerun the gate after changing either source revision. +For local checks from source, run the same registered fixture with +`--mode source --host --adapter ` +and a new `--output-directory`. Build the fixture and adjacent execution +bootstrap from the pinned Host and use the adapter and its resource bundle +from the candidate build. CI verifies the relocated release archive. + `check-workflow.py` can separately exercise native approvals, turns, cancellation, reconnection and owned-process cleanup through standard MCP using an isolated home and a fixed loopback response: diff --git a/Sources/CodexAdapter/CodexAppServerRuntime.swift b/Sources/CodexAdapter/CodexAppServerRuntime.swift index 1b9b3d5..cb93e54 100644 --- a/Sources/CodexAdapter/CodexAppServerRuntime.swift +++ b/Sources/CodexAdapter/CodexAppServerRuntime.swift @@ -298,6 +298,7 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { private let createdAt = Date() nonisolated let owner: CodexRuntimeOwner? private let database: CodexDatabase? + private let hostBound: Bool private let dynamicToolDispatcher: (any CodexHostTools)? private var connection: CodexAppServerConnection? private var processTransport: ManagedCodexAppServerTransport? @@ -357,12 +358,14 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { database: CodexDatabase? = nil, dynamicToolDispatcher: (any CodexHostTools)? = nil, threadOwnerIndex: CodexThreadOwnerIndex? = nil, + hostBound: Bool = false, maxOutputBytes: Int = 1_048_576 ) { self.configuration = configuration self.workspaceURL = workspaceURL.standardizedFileURL self.owner = owner self.database = database + self.hostBound = hostBound self.dynamicToolDispatcher = dynamicToolDispatcher self.threadOwnerIndex = threadOwnerIndex self.outputBounds = CodexOutputBounds(maxOutputBytes: maxOutputBytes) @@ -370,15 +373,23 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { capacity: configuration.maxEventsPerSession, maxOutputBytes: maxOutputBytes ) - for var record in (try? database?.codexApprovals(limit: 5_000)) ?? [] + for record in (try? database?.codexApprovals(limit: 5_000)) ?? [] where Self.isApprovalVisible(record, to: owner) { - if record.state == .pending, Self.isApprovalOwnerGone(record, database: database) { - record.state = .interrupted - record.resolvedAt = Date() - record.resolutionReason = "The owning runtime is no longer active." - try? database?.saveCodexApproval(record) + if !hostBound, record.state == .pending, + Self.isApprovalOwnerGone(record, database: database), let database + { + do { + let current = try database.interruptPendingCodexApproval( + record, at: Date(), reason: "The owning runtime is no longer active.") + approvalRecords[record.id] = current.flatMap { + Self.isApprovalVisible($0, to: owner) ? $0 : nil + } + } catch { + approvalRecords[record.id] = record + } + } else { + approvalRecords[record.id] = record } - approvalRecords[record.id] = record } CodexRuntimeDirectory.shared.register(self, id: runtimeID) } @@ -1341,6 +1352,12 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { return } isShutdown = true + if hostBound, connectionState == "idle" { + connectionState = "stopped" + shutdownReason = reason + unregisterIfDrained() + return + } for work in serverRequestWork.values { work.task?.cancel() } let retiredGeneration = connectionGeneration shutdownReason = reason @@ -1412,11 +1429,16 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { return connection } await recheckProcessCleanup() + guard !isShutdown else { throw CancellationError() } + if let connection { return connection } guard unconfirmedTransport == nil, lastProcessSnapshot?.cleanupConfirmed != false else { throw CodexToolError.disabled( "codex.app.cleanup_unconfirmed: The previous owned process group has not been confirmed gone." ) } + if hostBound, connectionState == "idle" { + try reconcileOrphanedApprovals() + } connectionState = "starting" shutdownReason = nil lastError = nil @@ -1899,10 +1921,8 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { "codex.app.approval_owner_unavailable: The recorded owner is still alive or could not be verified. Respond through its owning adapter connection." ) } - record.state = .interrupted - record.resolvedAt = Date() - record.resolutionReason = "The live App Server request is no longer available." - try persistApproval(record) + try interruptApproval( + record, at: Date(), reason: "The live App Server request is no longer available.") throw CodexApprovalBrokerError.unavailableAfterRestart(id) } if record.expiresAt <= Date() { @@ -1980,6 +2000,17 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { } private func reconcileApprovalRecords() async throws { + try reconcileOrphanedApprovals() + let now = Date() + for (id, record) in approvalRecords + where record.runtimeID == runtimeID && record.state == .pending && record.expiresAt <= now { + if approvalTimeoutTasks[id]?.isCancelled != false { + await timeoutApproval(id: id) + } + } + } + + private func reconcileOrphanedApprovals() throws { if let database { for record in try database.codexApprovals(limit: 5_000) where Self.isApprovalVisible(record, to: owner) { @@ -1988,22 +2019,10 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { } let now = Date() for id in approvalRecords.keys.sorted() { - guard var record = approvalRecords[id], record.state == .pending else { continue } - if let task = approvalTimeoutTasks[id], !task.isCancelled { - continue - } - if record.runtimeID == runtimeID, pendingApprovalHandles[id] != nil { - if record.expiresAt <= now { - await timeoutApproval(id: id) - } - continue - } - if Self.isApprovalOwnerGone(record, database: database) { - record.state = .interrupted - record.resolvedAt = now - record.resolutionReason = "The owning runtime is no longer active." - try persistApproval(record) - } + guard let record = approvalRecords[id], record.state == .pending, + record.runtimeID != runtimeID, Self.isApprovalOwnerGone(record, database: database) + else { continue } + try interruptApproval(record, at: now, reason: "The owning runtime is no longer active.") } } @@ -2012,7 +2031,7 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { reason: String ) async { for id in pendingApprovalHandles.keys.sorted() { - guard var record = approvalRecords[id], let handle = pendingApprovalHandles[id] else { + guard let record = approvalRecords[id], let handle = pendingApprovalHandles[id] else { continue } try? await resolve( @@ -2020,16 +2039,30 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { timedOut: false, connection: connection ) - record.state = .interrupted - record.resolvedAt = Date() - record.decision = .string("cancel") - record.resolutionReason = reason - try? persistApproval(record) + try? interruptApproval(record, at: Date(), reason: reason, decision: .string("cancel")) approvalTimeoutTasks.removeValue(forKey: id)?.cancel() } pendingApprovalHandles.removeAll() } + private func interruptApproval( + _ approval: CodexApprovalRecord, at now: Date, reason: String, decision: JSONValue? = nil + ) throws { + if let database { + let current = try database.interruptPendingCodexApproval( + approval, at: now, reason: reason, decision: decision) + approvalRecords[approval.id] = current.flatMap { + Self.isApprovalVisible($0, to: owner) ? $0 : nil + } + } else if var current = approvalRecords[approval.id], current.state == .pending { + current.state = .interrupted + current.resolvedAt = now + current.resolutionReason = reason + if let decision { current.decision = decision } + approvalRecords[approval.id] = current + } + } + private func persistApproval(_ record: CodexApprovalRecord) throws { try database?.saveCodexApproval(record) approvalRecords[record.id] = record @@ -2494,8 +2527,7 @@ actor LiveCodexAppServerRuntime: CodexAppServerRuntimeProtocol { ) { guard let database else { return } let now = Date() - let previous = try? database.codexRuntimeLeases(limit: 5_000) - .first(where: { $0.id == runtimeID }) + let previous = try? database.codexRuntimeLease(id: runtimeID) let record = CodexRuntimeLeaseRecord( id: runtimeID, owner: owner, diff --git a/Sources/CodexAdapter/CodexDatabase.swift b/Sources/CodexAdapter/CodexDatabase.swift index 79685dc..27f0097 100644 --- a/Sources/CodexAdapter/CodexDatabase.swift +++ b/Sources/CodexAdapter/CodexDatabase.swift @@ -48,6 +48,29 @@ final class CodexDatabase: @unchecked Sendable { } } + func interruptPendingCodexApproval( + _ approval: CodexApprovalRecord, at now: Date, reason: String, decision: JSONValue? = nil + ) throws -> CodexApprovalRecord? { + try writer.write { database in + guard var row = try CodexApprovalRecordRow.fetchOne(database, key: approval.id) else { + return nil + } + let current = try row.value() + guard current.state == .pending, current.runtimeID == approval.runtimeID, + current.workspaceID == approval.workspaceID, current.owner == approval.owner + else { return current } + + row.state = CodexApprovalState.interrupted.rawValue + row.resolvedAt = now + row.resolutionReason = reason + if let decision { + row.decision = try CodexApprovalRecordRow.encode(decision) + } + try row.update(database) + return try row.value() + } + } + func codexApprovals( workspaceID: String? = nil, limit: Int = 500 @@ -71,6 +94,12 @@ final class CodexDatabase: @unchecked Sendable { } } + func codexRuntimeLease(id: String) throws -> CodexRuntimeLeaseRecord? { + try writer.read { database in + try CodexRuntimeLeaseRow.fetchOne(database, key: id)?.value() + } + } + func codexRuntimeLeases(limit: Int = 500) throws -> [CodexRuntimeLeaseRecord] { try writer.read { database in try CodexRuntimeLeaseRow @@ -701,7 +730,7 @@ private struct CodexApprovalRecordRow: Codable, FetchableRecord, PersistableReco ) } - private static func encode(_ value: JSONValue) throws -> String { + static func encode(_ value: JSONValue) throws -> String { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys] let data = try encoder.encode(value) diff --git a/Sources/CodexAdapter/CodexLaunchContext.swift b/Sources/CodexAdapter/CodexLaunchContext.swift index 3d82dfd..d0a6f29 100644 --- a/Sources/CodexAdapter/CodexLaunchContext.swift +++ b/Sources/CodexAdapter/CodexLaunchContext.swift @@ -125,7 +125,8 @@ struct CodexLaunchContext: Sendable { return CodexAppServerProvider( appServer: LiveCodexAppServerRuntime( configuration: configuration, workspaceURL: workspaceURL, owner: owner, database: database, - dynamicToolDispatcher: hostTools, threadOwnerIndex: threadOwnerIndex), + dynamicToolDispatcher: hostTools, threadOwnerIndex: threadOwnerIndex, + hostBound: hostServiceContract != nil), owner: owner, database: database, workspaceURL: workspaceURL, recentThreadReader: .live(), localControlAllowed: localControlAllowed, diff --git a/Sources/CodexAdapter/CodexThreadOwnershipReconciliation.swift b/Sources/CodexAdapter/CodexThreadOwnershipReconciliation.swift index dfee8f5..3696532 100644 --- a/Sources/CodexAdapter/CodexThreadOwnershipReconciliation.swift +++ b/Sources/CodexAdapter/CodexThreadOwnershipReconciliation.swift @@ -152,7 +152,7 @@ enum CodexThreadOwnershipReconciliation { runtimeID: String ) throws -> Bool { guard let database else { return false } - let lease = try database.codexRuntimeLeases(limit: 5_000).first { $0.id == runtimeID } + let lease = try database.codexRuntimeLease(id: runtimeID) return codexRuntimeProcessMayExist(lease?.process?.processID) || codexRuntimeProcessMayExist(lease?.process?.supervisorProcessID) } diff --git a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift index d1ac1dd..f6cb21c 100644 --- a/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift +++ b/Tests/CodexAdapterTests/CodexAppServerRuntimeTests.swift @@ -73,12 +73,16 @@ final class CodexAppServerRuntimeTests { try FileManager.default.setAttributes( [.posixPermissions: 0o700], ofItemAtPath: executable.path) } + let database = try CodexDatabase(inMemory: ()) let runtime = LiveCodexAppServerRuntime( - configuration: CodexConfig(enabled: true, executable: executable.path), workspaceURL: root) + configuration: CodexConfig(enabled: true, executable: executable.path), workspaceURL: root, + database: database, hostBound: true) await assertThrowsErrorAsync( try await runtime.call(method: "thread/loaded/list", params: .object([:]))) let status = await runtime.status() + #expect(try database.codexRuntimeLease(id: runtime.runtimeID)?.state == "failed") await runtime.shutdown() + #expect(try database.codexRuntimeLease(id: runtime.runtimeID)?.state == "stopped") #expect(status.objectValue?["connection_state"] == .string("failed")) #expect(status.objectValue?["last_error"]?.stringValue?.isEmpty == false) } @@ -908,8 +912,10 @@ final class CodexAppServerRuntimeTests { } } - @Test - func testPendingApprovalBecomesInterruptedAndCannotBeReplayedAfterRestart() async throws { + @Test(arguments: [false, true]) + func testPendingApprovalBecomesInterruptedAndCannotBeReplayedAfterRestart( + hostBound: Bool + ) async throws { let fixture = try AppServerProcessFixture() defer { fixture.remove() } try fixture.configureFileApproval(grantRoot: fixture.directory.path) @@ -924,7 +930,13 @@ final class CodexAppServerRuntimeTests { #expect(interrupted.state == .interrupted) #expect(interrupted.resolvedAt != nil) try? FileManager.default.removeItem(at: fixture.approvalRequestFile) - let replacement = fixture.makeRuntime(database: database) + try database.saveCodexApproval(pending) + let replacement = fixture.makeRuntime(database: database, hostBound: hostBound) + if hostBound { + #expect(try database.codexApproval(id: pending.id)?.state == .pending) + _ = try await replacement.call(method: "thread/loaded/list", params: .object([:])) + } + #expect(try database.codexApproval(id: pending.id)?.state == .interrupted) let record = try await replacement.approval(id: pending.id) .objectValue?["approval"]?.objectValue #expect(record?["state"] == .string("interrupted")) @@ -955,7 +967,7 @@ final class CodexAppServerRuntimeTests { // A different adapter process sees the durable lease, but not this process-local directory. CodexRuntimeDirectory.shared.unregister(id: owning.runtimeID) - let observer = fixture.makeRuntime(database: reopened) + let observer = fixture.makeRuntime(database: reopened, hostBound: true) do { #expect(try reopened.codexApproval(id: pending.id)?.state == .pending) let visible = try await observer.approval(id: pending.id) @@ -966,6 +978,7 @@ final class CodexAppServerRuntimeTests { #expect(try reopened.codexApproval(id: pending.id)?.state == .pending) #expect(!FileManager.default.fileExists(atPath: fixture.approvalResponseLog.path)) await observer.shutdown() + #expect(try reopened.codexRuntimeLease(id: observer.runtimeID) == nil) CodexRuntimeDirectory.shared.register(owning, id: owning.runtimeID) } catch { await observer.shutdown() @@ -1721,6 +1734,7 @@ struct AppServerProcessFixture { approvalTimeoutSeconds: Int = 300, database: CodexDatabase? = nil, workspaceID: String? = "fixture-workspace", + hostBound: Bool = false, dynamicToolDispatcher: (any CodexHostTools)? = nil ) -> LiveCodexAppServerRuntime { LiveCodexAppServerRuntime( @@ -1744,7 +1758,7 @@ struct AppServerProcessFixture { tunnelInstanceID: nil, tunnelProfileID: nil ), - database: database, dynamicToolDispatcher: dynamicToolDispatcher + database: database, dynamicToolDispatcher: dynamicToolDispatcher, hostBound: hostBound ) } diff --git a/Tests/CodexAdapterTests/CodexDatabaseTests.swift b/Tests/CodexAdapterTests/CodexDatabaseTests.swift index 9fe5e6b..491b0da 100644 --- a/Tests/CodexAdapterTests/CodexDatabaseTests.swift +++ b/Tests/CodexAdapterTests/CodexDatabaseTests.swift @@ -7,7 +7,11 @@ import Testing struct CodexDatabaseTests { @Test func testPersistsCodexApprovalAndRuntimeOwnershipReceipts() throws { - let database = try CodexDatabase(inMemory: ()) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let path = root.appendingPathComponent("codex.sqlite").path + let database = try CodexDatabase(path: path) let timestamp = Date(timeIntervalSince1970: 2_000) let owner = CodexRuntimeOwner( workspaceID: "workspace-1", @@ -85,6 +89,29 @@ struct CodexDatabaseTests { #expect(try database.codexRuntimeLeases() == [lease]) #expect(try database.codexThreadOwnership(threadID: ownership.threadID) == ownership) #expect(try database.codexThreadOwnerships(workspaceID: "workspace-1") == [ownership]) + + let otherConnection = try CodexDatabase(path: path) + let observed = try #require(try otherConnection.codexApproval(id: approval.id)) + var winner = approval + winner.state = .approved + winner.decision = .string("accept") + winner.response = .object(["decision": .string("accept")]) + try database.saveCodexApproval(winner) + #expect( + try otherConnection.interruptPendingCodexApproval( + observed, at: timestamp, reason: "Orphaned") == winner) + #expect(try database.codexApproval(id: winner.id) == winner) + + var reassigned = approval + reassigned.owner = owner + try database.saveCodexApproval(reassigned) + #expect( + try otherConnection.interruptPendingCodexApproval( + observed, at: timestamp, reason: "Orphaned") == reassigned) + #expect(try database.codexApproval(id: reassigned.id) == reassigned) + #expect( + try otherConnection.interruptPendingCodexApproval( + reassigned, at: timestamp, reason: "Orphaned")?.state == .interrupted) } @Test diff --git a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift index 5c80fc3..5ad132a 100644 --- a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift +++ b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift @@ -23,7 +23,7 @@ struct RegisteredHost { print(ComputerMCPCLI.version) case "app-server": try runPeer() - case "register", "serve": + case "register", "serve", "deny-source", "restore-source": guard arguments.count == 2 || (arguments.count == 4 && arguments[0] == "serve") else { throw FixtureError.invalidArguments } let root = URL(fileURLWithPath: arguments[1], isDirectory: true).resolvingSymlinksInPath() @@ -37,13 +37,13 @@ struct RegisteredHost { } else { observer = nil } - try await run(root: root, register: arguments[0] == "register", observer: observer) + try await run(root: root, command: arguments[0], observer: observer) default: throw FixtureError.invalidArguments } } - private static func run(root: URL, register: Bool, observer: StdioTransport?) async throws { + private static func run(root: URL, command: String, observer: StdioTransport?) async throws { let database = try GatewayDatabase(path: root.appendingPathComponent("host.sqlite").path) _ = database.permissionStore( counter: FixtureEpochCounter(file: root.appendingPathComponent("fixture-epoch.json"))) @@ -59,23 +59,34 @@ struct RegisteredHost { try database.registerManifestProjectsForStartup(configuration.manifestProjects) let permissionRuntime = try database.permissionRuntime(platform: platform) try await permissionRuntime.ready() - if register { + 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, + state: command == "deny-source" ? .denied : .granted(.write)) + return + default: + break } let primary = try await makeGateway( database: database, platform: platform, configuration: configuration) if let observer { + let alternate = ProcessInfo.processInfo.environment["CODEX_FIXTURE_SECONDARY"] == "alternate" let secondaryGateway = try await makeGateway( - database: database, platform: platform, configuration: configuration, role: "observer") + database: database, platform: platform, configuration: configuration, + role: alternate ? "alternate" : "observer") async let secondary: Void = serve( secondaryGateway, root: root, configuration: configuration, - permissionRuntime: permissionRuntime, role: "observer", transport: observer) + permissionRuntime: permissionRuntime, role: alternate ? nil : "observer", + transport: observer) try await serve( primary, root: root, configuration: configuration, - permissionRuntime: permissionRuntime, role: "acceptance") + permissionRuntime: permissionRuntime, role: alternate ? nil : "acceptance") try await secondary } else { try await serve( @@ -87,13 +98,23 @@ struct RegisteredHost { database: GatewayDatabase, platform: PlatformServices, configuration: GatewayConfiguration, role: String? = nil ) async throws -> GatewayRuntime { - let profile = role.flatMap { GatewayProfileID(rawValue: $0) } ?? configuration.runtime.profileID + let environment = ProcessInfo.processInfo.environment + let profileName = role == "observer" ? role : environment["CODEX_FIXTURE_PROFILE"] + let profile = + profileName.flatMap { GatewayProfileID(rawValue: $0) } + ?? configuration.runtime.profileID + let principal = + role == "observer" + ? "registered-codex-observer" + : role == "alternate" || environment["CODEX_FIXTURE_PRINCIPAL"] == "alternate" + ? "registered-codex-alternate" + : "registered-codex-fixture" let context = ExecutionContext( caller: configuration.runtime.caller, profileID: profile, - projectID: configuration.runtime.defaultProjectID, + projectID: environment["CODEX_FIXTURE_UNBOUND"] == "1" + ? nil : configuration.runtime.defaultProjectID, transportTrace: .init(transport: "stdio", socketConnectionID: UUID().uuidString), - trustedPrincipalID: role == "observer" - ? "registered-codex-observer" : "registered-codex-fixture") + trustedPrincipalID: principal) return try await GatewayRuntime.make( configuration: configuration, context: context, database: database, platform: platform, bundledPlugins: .init(packages: [], issues: [])) @@ -212,14 +233,10 @@ struct RegisteredHost { let review = try GatewayProviderReview( package: package, configuration: database.configurationState()) var permissions = Permissions() - let reviewedProjects = configuration.profileGrant(for: configuration.runtime.profileID) - .permissions - for id in ["primary", "other"] { - let project = Permission.project(id) - guard let level = reviewedProjects.entries[project] else { - throw FixtureError.invalidRegistration - } - try permissions.set(level, for: project) + let projectIDs = try JSONDecoder().decode( + [String].self, from: Data(contentsOf: root.appendingPathComponent("provider-projects.json"))) + for id in projectIDs { + try permissions.set(.granted(.write), for: .project(id)) } let approval = try permissionRuntime.service.approveProvider( review, permissions: permissions, fullAccess: false, owner: owner, @@ -235,6 +252,30 @@ struct RegisteredHost { print(String(decoding: try JSONEncoder().encode(receipt), as: UTF8.self)) } + private static func setSourceAccess( + root: URL, database: GatewayDatabase, permissionRuntime: GatewayPermissionRuntime, + state: PermissionState + ) async throws { + let service = permissionRuntime.service + let owner = try owner() + let view = try service.view(owner: owner) + guard let epoch = view.epoch, + let previous = view.providers.first(where: { $0.identity == .package("codex") }) + else { throw FixtureError.invalidRegistration } + let package = try PluginPackage.load(at: root.appendingPathComponent("plugin")) + let review = try GatewayProviderReview( + package: package, configuration: database.configurationState()) + var permissions = previous.permissions + try permissions.set(state, for: .project("primary")) + let approval = try service.approveProvider( + review, permissions: permissions, fullAccess: false, owner: owner, + expectedProviderRevision: previous.revision, expectedRevision: view.revision, + expectedEpoch: epoch, editingApproval: true) + guard approval.permissions.state(for: .project("primary")) == state + else { throw FixtureError.invalidRegistration } + try await permissionRuntime.coordinator.reconcile() + } + private static func runPeer() throws { let environment = ProcessInfo.processInfo.environment guard let path = environment["CODEX_HOME"] else { throw FixtureError.invalidPeerMessage } diff --git a/Tests/test_host_acceptance.py b/Tests/test_host_acceptance.py index 6af7f01..b271613 100644 --- a/Tests/test_host_acceptance.py +++ b/Tests/test_host_acceptance.py @@ -40,6 +40,15 @@ def test_fixture_arguments_do_not_launch_or_create_state(self): self.assertEqual(parsed.mode, "fixture") self.assertFalse(parsed.output_directory.exists()) + def test_source_mode_uses_a_built_adapter_and_fixture_without_archive_or_vendor(self): + built = self.arguments[:4] + self.arguments[6:] + parsed = acceptance.parse_arguments(built + ["--mode", "source"]) + self.assertEqual((parsed.host, parsed.adapter), (self.executable, self.executable)) + self.assertIsNone(parsed.codex) + self.assertFalse(parsed.output_directory.exists()) + self.invalid(self.arguments + ["--mode", "source"]) + self.invalid(built + ["--mode", "source", "--archive", str(self.executable)]) + def container_arguments(self, revision): return ["--mode", "container", "--host-source", str(self.root), "--plugin-revision", revision, "--archive", str(self.executable), @@ -252,12 +261,13 @@ def reply(payload, error=False): with self.assertRaises(RuntimeError): acceptance.observe_worktree_removal(reply(removed, True), "fixture", "child", operation) - def test_removal_observation_retries_only_source_gateway_configuration_change(self): + def test_removal_observation_retries_only_bound_transient_failures(self): operation = acceptance.uuid.UUID("91807494-d50c-4d89-9e0a-d17b608ecf66") - def reply(code="configuration.changed", project="primary", capability="mcp.tools.call"): + def reply(code="configuration.changed", project="primary", capability="mcp.tools.call", + message="The gateway configuration changed during preparation."): return {"isError": True, "structuredContent": { - "error": {"code": code, "message": "The gateway configuration changed during preparation."}, + "error": {"code": code, "message": message}, "gateway_execution": {"project_id": project, "capability_id": capability}, }} @@ -282,6 +292,18 @@ def reply(code="configuration.changed", project="primary", capability="mcp.tools with self.assertRaises(RuntimeError): host.raw(tool, selector) + for detail in ("[mcp.request_cancelled] Downstream request was cancelled.", + "MCP server 'codex' request timed out."): + interrupted = reply(code="gateway.execution_failed", message=detail) + self.assertEqual(acceptance.observe_worktree_removal(interrupted, "fixture", "child", operation), + (operation, None)) + with self.assertRaises(RuntimeError): + acceptance.observe_worktree_removal(interrupted, "fixture", "child", None) + with self.assertRaises(RuntimeError): + acceptance.observe_worktree_removal( + reply(code="gateway.execution_failed", message=detail, project="sibling"), + "fixture", "child", operation) + for rejected in (reply(code="permission.denied"), reply(code="gateway.execution_failed"), reply(project="sibling"), reply(capability="mcp.tools.list"), {"isError": True, "structuredContent": {"error": {"code": "configuration.changed"}}}): diff --git a/computer-mcp-plugin.toml b/computer-mcp-plugin.toml index 654b0a0..1029548 100644 --- a/computer-mcp-plugin.toml +++ b/computer-mcp-plugin.toml @@ -7,7 +7,7 @@ description = 'Codex execution and protocol inspection through standard MCP.' [[permissions]] id = "project" access = "write" -purpose = "Create and remove managed worktrees in projects you approve for Codex." +purpose = "Edit approved projects, manage writer leases, and create and remove Host-managed worktrees." [sandbox] network = { level = "custom", hosts = ["api.openai.com", "chatgpt.com", "auth.openai.com"], include_trusted = false } @@ -20,6 +20,26 @@ host_service_contract = "projects-v1" executable = { platform_paths = { macos = 'bin/codex-mcp-adapter' } } capabilities = ['tools'] +[mcp.tool_requirements] +"codex.protocol.methods.list" = { project = "none" } +"codex.protocol.methods.describe" = { project = "none" } +"codex.app.methods.list" = { project = "none" } +"codex.app.methods.describe" = { project = "none" } +"codex.diagnostics.snapshot" = { project = "read" } +"codex.worktree.managed.list" = { project = "read" } +"codex.worktree.leases.list" = { project = "read" } +"codex.worktree.leases.read" = { project = "read" } +"codex.worktree.leases.cleanup.preview" = { project = "read" } +"codex.worktree.provision.plan" = { project = "write" } +"codex.worktree.provision.perform" = { project = "write" } +"codex.worktree.remove.plan" = { project = "write" } +"codex.worktree.remove.perform" = { project = "write" } +"codex.worktree.managed.read" = { project = "write" } +"codex.worktree.leases.acquire" = { project = "write" } +"codex.worktree.leases.heartbeat" = { project = "write" } +"codex.worktree.leases.release" = { project = "write" } +"codex.worktree.leases.cleanup.perform" = { project = "write" } + [compatibility] minimum_host = '0.1.0' platforms = ['macos'] diff --git a/scripts/check-host.py b/scripts/check-host.py index 780882d..d53441d 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -2,12 +2,14 @@ """Accept a packaged adapter through a source-built registered Computer MCP gateway. Container mode uses a deterministic protocol peer. Fixture mode uses native -Codex with a private loopback Responses server. +Codex with a private loopback Responses server. Source mode runs the same +registered deterministic peer against built fixture and adapter executables. Full mode additionally requires authenticated model execution. All host instances, workspaces, runtime homes and failure injection targets are private to this run. """ import argparse +from contextlib import closing import hashlib import json import os @@ -16,6 +18,7 @@ import re import shutil import signal +import sqlite3 import subprocess import sys import tarfile @@ -81,11 +84,11 @@ def parse_arguments(arguments=None): 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") - parser.add_argument("--host", type=executable, help="Native modes: source-built CodexRegisteredHost fixture") - parser.add_argument("--adapter", type=executable, help="Native modes: adapter from the verified, relocated archive") + parser.add_argument("--host", type=executable, help="Source and native modes: source-built CodexRegisteredHost fixture") + parser.add_argument("--adapter", type=executable, help="Source and native modes: built adapter") parser.add_argument("--codex", type=executable, help="Native modes: user-installed vendor Codex") parser.add_argument("--output-directory", required=True, type=Path, help="New private directory in ignored build output") - parser.add_argument("--mode", choices=("container", "fixture", "full"), default="full") + parser.add_argument("--mode", choices=("container", "source", "fixture", "full"), default="full") parser.add_argument("--auth-file", type=absolute_file, help="Full mode: existing vendor auth.json; copied privately and deleted on exit") parser.add_argument("--model", help="Full mode: authenticated model ID") parser.add_argument("--timeout-seconds", type=timeout_seconds, default=180) @@ -101,6 +104,9 @@ def parse_arguments(arguments=None): full_revision(options.plugin_revision) except ValueError as error: parser.error(str(error)) + elif options.mode == "source": + if any(source_inputs) or options.codex or not all((options.host, options.adapter)): + parser.error("Source mode requires --host and --adapter") elif any(source_inputs) or not all((options.host, options.adapter, options.codex)): parser.error("Native modes require --host, --adapter and --codex") if options.mode == "full" and (not options.auth_file or not options.model or not options.model.strip()): @@ -196,16 +202,52 @@ def unwrap(result, indirect=False): return result +def require_refusal(result, detail): + if not result.get("isError"): + result = result.get("structuredContent", {}).get("result", result) + require(result.get("isError") is True and detail in json.dumps(result), result) + + +def require_admission_refusal(result): + error = result.get("structuredContent", {}).get("error", {}) + require(result.get("isError") is True and error.get("code") in { + "permission.required", "permission.denied", "policy.project_denied", + } 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 ( + message.startswith("[mcp.request_cancelled]") or message == "MCP server 'codex' request timed out." + ) + + def observe_worktree_removal(result, worktree_id, project, operation_id): if isinstance(result, dict) and result.get("isError") is True: structured = result.get("structuredContent") if isinstance(structured, dict): error = structured.get("error") execution = structured.get("gateway_execution") - # The removal can invalidate the Host's project snapshot during read admission. - if (isinstance(error, dict) and error.get("code") == "configuration.changed" + # Project refresh can interrupt an observation while the original removal settles. + if (isinstance(error, dict) and isinstance(execution, dict) and execution.get("capability_id") == "mcp.tools.call" - and execution.get("project_id") == "primary" and "result" not in structured): + and execution.get("project_id") == "primary" and "result" not in structured + and (error.get("code") == "configuration.changed" + or (operation_id is not None and interrupted_mcp_call(error)))): return operation_id, None result = unwrap(result) current = result.get("structuredContent", {}).get("result") @@ -336,6 +378,9 @@ 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 {}) @@ -367,6 +412,14 @@ def initialize(self): CONTAINER_RISKS = { + "codex.protocol.methods.list": "read-only", + "codex.protocol.methods.describe": "read-only", + "codex.app.methods.list": "read-only", + "codex.app.methods.describe": "read-only", + "codex.app.approvals.list": "read-only", + "codex.app.approvals.respond": "full-shell", + "codex.app.native.thread.loaded.list": "read-only", + "codex.exec.list": "read-only", "codex.app.status": "read-only", "codex.app.thread.loaded.list": "read-only", "codex.app.runtimes.cleanup.preview": "read-only", @@ -375,8 +428,12 @@ def initialize(self): "codex.worktree.managed.list": "read-only", "codex.worktree.managed.read": "read-only", "codex.worktree.leases.list": "read-only", + "codex.worktree.leases.read": "read-only", "codex.worktree.leases.acquire": "workspace-write", + "codex.worktree.leases.heartbeat": "workspace-write", "codex.worktree.leases.release": "workspace-write", + "codex.worktree.leases.cleanup.preview": "read-only", + "codex.worktree.leases.cleanup.perform": "workspace-write", "codex.worktree.provision.plan": "workspace-write", "codex.worktree.provision.perform": "workspace-write", "codex.worktree.remove.plan": "workspace-write", @@ -385,7 +442,8 @@ def initialize(self): class Host: - def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None): + def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None, + profile=None, alternate_principal=False, unbound=False): self.fixture, self.indirect = fixture, indirect self.workspace = "primary" fixture.generation += 1 @@ -403,9 +461,18 @@ def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None) self.observer_streams = SimpleNamespace( stdin=os.fdopen(writer, "w"), stdout=os.fdopen(reader)) try: + environment = fixture.environment.copy() + if profile: + environment["CODEX_FIXTURE_PROFILE"] = profile + if alternate_principal: + environment["CODEX_FIXTURE_PRINCIPAL"] = "alternate" + if unbound: + environment["CODEX_FIXTURE_UNBOUND"] = "1" + if with_observer == "alternate": + environment["CODEX_FIXTURE_SECONDARY"] = "alternate" self.process = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, - text=True, bufsize=1, env=fixture.environment, cwd=fixture.root, pass_fds=child_fds) + text=True, bufsize=1, env=environment, cwd=fixture.root, pass_fds=child_fds) except OSError: if self.observer_streams: self.observer_streams.stdin.close() @@ -420,9 +487,14 @@ def __init__(self, fixture, indirect=True, *, with_observer=False, streams=None) fixture.hosts.append(self) self.client = MCPClient(streams, self.evidence, fixture.options.timeout_seconds) gateway_catalog = self.client.initialize() - downstream_catalog = self.project_catalog() - self.catalog = downstream_catalog if indirect else gateway_catalog - require(set(fixture.risks) <= self.catalog.keys(), {"missing_tools": sorted(set(fixture.risks) - self.catalog.keys())}) + self.catalog = gateway_catalog + if fixture.project_count: + 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() + 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", "Generic dispatch lacks project selection") @@ -444,18 +516,22 @@ def raw(self, name, arguments=None, timeout=None, *, gateway_envelope=False): result = self.dispatch(name, arguments, timeout) return unwrap(result) if self.indirect and not gateway_envelope else result - def dispatch(self, name, arguments=None, timeout=None): - arguments = arguments or {} + def dispatch(self, name, arguments=None, timeout=None, *, select_project=True): + arguments = dict(arguments or {}) + project = {"project_id": self.workspace} if select_project else {} if self.indirect: params = {"name": "mcp.tools.call", "arguments": {"server": "codex", "tool": name, - "project_id": self.workspace, "arguments": arguments}} + **project, "arguments": arguments}} else: - params = {"name": name, "arguments": dict(arguments, project_id=self.workspace)} - self.fixture.last_tool_call = {"tool": name, "project_id": self.workspace} + params = {"name": name, "arguments": arguments | project} + self.fixture.last_tool_call = {"tool": name, "project_id": project.get("project_id")} return self.client.send("tools/call", params, timeout=timeout) def call(self, name, arguments=None, timeout=None): - return unwrap(self.raw(name, arguments, timeout)) + response = self.raw(name, arguments, timeout) + if name.startswith("codex.protocol.") and not response.get("isError"): + return response["structuredContent"] + return unwrap(response) def method(self, name, params=None, timeout=None): return self.call("methods.call", {"method": name, "params": params or {}}, timeout) @@ -538,7 +614,7 @@ def poll(): class Fixture: - def __init__(self, options): + def __init__(self, options, *, host_services=True, project_count=2, wildcard=False): self.options, self.root = options, options.output_directory.resolve() self.root.mkdir(mode=0o700, parents=True) self.hosts, self.pids, self.threads, self.steps = [], set(), set(), [] @@ -550,7 +626,11 @@ def __init__(self, options): self.authorization = {} self.adapter_config = self.root / "adapter.json" self.launches = self.root / "launches.jsonl" - self.risks = CONTAINER_RISKS if options.mode == "container" else RISKS + self.registered_peer = options.mode in {"container", "source"} + self.host_services = host_services + self.project_count = project_count + self.wildcard = wildcard + self.risks = CONTAINER_RISKS if self.registered_peer else RISKS self.projects = {name: self.root / name for name in ("primary", "other")} self.home = self.root / "codex-home" self.home.mkdir(mode=0o700) @@ -567,13 +647,14 @@ def setup(self): for key, value in (("user.name", "Acceptance"), ("user.email", "acceptance@example.invalid"), ("commit.gpgsign", "false"), ("core.hooksPath", str(self.root / name / ".git/hooks"))): self.git(["config", key, value], name) - if self.options.mode == "container": - (self.projects["primary"] / "product.txt").write_text("caller project fixture\n") - self.git(["add", "product.txt"]) - self.git(["commit", "--quiet", "-m", "Fixture base"]) + if self.registered_peer: + for name, marker in (("primary", "caller"), ("other", "sibling")): + (self.projects[name] / "product.txt").write_text(f"{marker} project fixture\n") + self.git(["add", "product.txt"], name) + self.git(["commit", "--quiet", "-m", "Fixture base"], name) self.register() - if self.options.mode == "container": - self.configure_adapter(self.peer, exec_enabled=False) + if self.registered_peer: + self.configure_adapter(self.peer, exec_enabled=True) return wrapper = self.package / "bin/configured-codex" wrapper.write_text(f'''#!{sys.executable} @@ -644,8 +725,10 @@ def register(self): [runtime] caller = "local-mcp" profile = "acceptance" -project_id = "primary" - +''' + if self.project_count: + config += 'project_id = "primary"\n' + config += ''' [[profiles]] id = "acceptance" allowed_callers = ["local-mcp"] @@ -658,7 +741,7 @@ def register(self): [profiles.plugins] codex = "use" ''' - if self.options.mode == "container": + if self.registered_peer: config += ''' [[profiles]] id = "observer" @@ -669,6 +752,17 @@ def register(self): primary = { access = "write", network = "none" } other = { access = "write", network = "none" } +[profiles.plugins] +codex = "use" +''' + for profile, access in (("scoped", "write"), ("reader", "read")): + config += f''' +[[profiles]] +id = "{profile}" +allowed_callers = ["local-mcp"] +full_access = false +[profiles.projects] +primary = {{ access = "{access}", network = "none" }} [profiles.plugins] codex = "use" ''' @@ -676,17 +770,24 @@ def register(self): [builtin] enabled = ["file.read"] ''' - for name in ("primary", "other"): + projects = list(self.projects)[:self.project_count] + if self.project_count < 2: + config = "\n".join( + line for line in config.splitlines() + if not any(line.startswith(f"{name} = ") for name in self.projects if name not in projects) + ) + "\n" + for name in projects: config += f'''[[projects]] id = {q(name)} display_name = {q(name)} path = {q(str(self.root / name))} ''' (self.root / "host.toml").write_text(config) + (self.root / "provider-projects.json").write_text(json.dumps(["*"] if self.wildcard else projects)) (self.root / "contribution.json").write_text(json.dumps({ - "registrationID": "codex", "exposure": "gateway" if self.options.mode == "container" else "reexport", + "registrationID": "codex", "exposure": "reexport", "prefix": "", - "hostServices": True, "allowedTools": list(self.risks), + "hostServices": self.host_services, "allowedTools": list(self.risks), "toolRisks": {name: "project-write" if risk == "workspace-write" else risk for name, risk in self.risks.items()}, })) @@ -702,7 +803,7 @@ def register(self): (self.root / "registration.json").write_text(json.dumps(self.container, indent=2) + "\n") self.home = Path(self.container["home"]) / ".codex" self.home.mkdir(mode=0o700) - if self.options.mode == "container": + if self.registered_peer: self.authorization["registration"] = { key: self.container[key] for key in ("manifest_digest", "provider_revision", "authorization_epoch") } @@ -754,6 +855,317 @@ 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" + write = "codex.worktree.leases.acquire" + for indirect in (False, True): + host = Host(self, indirect=indirect, profile="reader", unbound=True) + host.call(catalog) + require(host.call(read)["scope"]["project_id"] == "primary", "Wrong read scope") + require_admission_refusal(host.dispatch(write, {"agent_id": "reader"})) + require_refusal(host.dispatch(catalog, select_project=False), + "policy.project_required" if indirect else "gateway.tool_unknown") + host.close() + + host = Host(self, indirect=indirect, profile="scoped", unbound=True) + host.call(catalog) + for name in ("codex.app.status", "codex.app.native.thread.loaded.list", "codex.exec.list"): + require_admission_refusal(host.dispatch(name)) + if indirect: + host.select_project("other") + require_admission_refusal(host.dispatch(read)) + else: + host.workspace = "other" + require_refusal(host.dispatch(read), "gateway.tool_unknown") + host.close() + require(not (self.home / "vendor.json").exists(), "Catalog, read or refused call started the peer") + self.record("direct-and-forwarded-tool-requirements-and-conservative-fallback") + + def project_selection(self): + name = "codex.protocol.methods.list" + for indirect in (False, True): + host = Host(self, indirect=indirect, profile="scoped", unbound=True) + response = host.dispatch(name, select_project=False) + if self.project_count: + catalog = unwrap(response) if indirect else response + require(catalog["structuredContent"]["methods"], catalog) + require(response["structuredContent"]["gateway_execution"]["project_id"] == "primary", response) + else: + require_refusal(response, "policy.project_required" if indirect else "gateway.tool_unknown") + host.close() + require(not (self.home / "vendor.json").exists(), "Project selection started the peer") + self.record("catalog-single-project-inferred" if self.project_count else "catalog-no-project-refused") + + def callbacks_disabled(self): + host = Host(self, profile="scoped", unbound=True) + host.call("codex.protocol.methods.list") + snapshot = host.call("codex.diagnostics.snapshot") + require(snapshot["scope"]["principal_id"] == "registered-codex-fixture" + and snapshot["scope"]["profile_id"] == "scoped" + and snapshot["scope"]["project_id"] == "primary" + and snapshot["persistence_available"] + and snapshot["state_storage"]["scope"] == "authorization_subject" + and snapshot["host_diagnostics_available"] is False + and snapshot["recent_tool_audits"] is None, snapshot) + host.call("codex.worktree.leases.list") + host.close() + state = Path(self.container["state"]) / "codex-adapter" + require(len(list(state.glob("subjects/*/codex.sqlite"))) == 1 + and len(list(state.glob("worktree-leases/*.sqlite"))) == 1 + and not (state / "codex.sqlite").exists(), state) + require(not (self.home / "vendor.json").exists(), "Local reads started the peer") + self.record("callback-disabled-subject-storage-and-passive-local-reads") + + def wildcard_fallback(self): + # This profile holds concrete write grants for all currently registered projects. + host = Host(self) + host.call("codex.protocol.methods.list") + require(host.call("codex.diagnostics.snapshot")["host_diagnostics_available"], "Host callback unavailable") + require_admission_refusal(host.dispatch("codex.app.status")) + host.close() + require(not (self.home / "vendor.json").exists(), "Wildcard fallback started the peer") + self.record("concrete-caller-grants-do-not-cover-provider-wildcard") + + def scoped_worktree_permissions(self): + source_tool = "codex.worktree." + selector = lambda worktree: {"managed_worktree_id": worktree["id"]} + denied_path = self.projects["other"] / "sibling-inventory-canary" + path = str(denied_path) + self.git(["worktree", "add", "--detach", path]) + a = Host(self, profile="scoped", unbound=True, with_observer="alternate") + b = Host(self, streams=a.observer_streams) + a_scope = a.call("codex.diagnostics.snapshot")["scope"] + b_scope = b.call("codex.diagnostics.snapshot")["scope"] + require(a_scope["profile_id"] == b_scope["profile_id"] == "scoped" + and a_scope["principal_id"] != b_scope["principal_id"], [a_scope, b_scope]) + inventory = a.call(source_tool + "managed.list")["host_response"]["structuredContent"]["result"] + require(path not in json.dumps(inventory) + and any(row.get("unavailable") == "Path access denied." + and all(row.get(key) is None for key in ("path", "project_id", "worktree_id")) + for row in inventory["worktrees"]), inventory) + self.git(["worktree", "remove", path]) + require_admission_refusal(a.client.send("tools/call", { + "name": "file.read", "arguments": {"project_id": "other", "path": "product.txt"} + })) + require((self.projects["other"] / "product.txt").read_text() == "sibling project fixture\n", + "Sibling canary changed") + + parent = a.call(source_tool + "leases.acquire", {"agent_id": "scoped-parent"}) + provision = {"name": "scoped-child", "agent_id": "scoped-child", "parent_lease_id": parent["id"]} + plan = a.call(source_tool + "provision.plan", provision) + prior = self.git(["worktree", "list", "--porcelain"]) + require_refusal(b.dispatch(source_tool + "leases.read", {"lease_id": parent["id"]}), "Unknown Codex worktree lease") + require_refusal(b.dispatch(source_tool + "provision.plan", provision), "active source parent lease") + require_refusal(b.dispatch(source_tool + "provision.perform", plan["perform_arguments"]), "Unknown Computer MCP-managed worktree") + require(a.call(source_tool + "managed.read", selector(plan)) == plan + and self.git(["worktree", "list", "--porcelain"]) == prior, "Foreign call changed the source") + + worktree = a.call(source_tool + "provision.perform", plan["perform_arguments"]) + child = worktree["project_id"] + checkout = Path(worktree["resolved"]["path"]) + require(checkout.resolve().is_relative_to(self.root / "worktrees"), worktree) + self.projects[child] = checkout + b.close() + a.close() + a = Host(self, profile="scoped", unbound=True, with_observer="alternate") + b = Host(self, streams=a.observer_streams) + a.select_project(child) + b.select_project(child) + checked = a.call(source_tool + "managed.read", selector(worktree)) + reread = a.call(source_tool + "managed.read", selector(worktree)) + leases = a.call(source_tool + "leases.list")["leases"] + require(checked == reread and checked["operation_id"] == worktree["operation_id"] + and [row["id"] for row in leases] == [worktree["lease"]["lease_id"]], [checked, leases]) + lease = leases[0] + mutation = {"lease_id": lease["id"], "expected_revision": lease["revision"]} + prior = self.git(["worktree", "list", "--porcelain"]) + for name, arguments, detail in ( + ("managed.read", selector(worktree), "Unknown Computer MCP-managed worktree"), + ("remove.plan", selector(worktree), "Unknown Computer MCP-managed worktree"), + ("leases.heartbeat", mutation, "Unknown Codex worktree lease"), + ("leases.release", mutation | {"reason": "fixture"}, "Unknown Codex worktree lease"), + ("leases.acquire", {"agent_id": "alternate", "parent_lease_id": parent["id"], + "mode": "isolated_worktree"}, "parent_lease_id"), + ): + require_refusal(b.dispatch(source_tool + name, arguments), detail) + require(a.call(source_tool + "leases.read", {"lease_id": lease["id"]}) == lease + and self.git(["worktree", "list", "--porcelain"]) == prior, "Foreign call changed the child") + lease = a.call(source_tool + "leases.heartbeat", mutation) + a.call(source_tool + "leases.release", { + "lease_id": lease["id"], "expected_revision": lease["revision"], "reason": "scoped acceptance", + }) + linked = a.call(source_tool + "leases.acquire", { + "agent_id": "scoped-linked", "parent_lease_id": parent["id"], "mode": "isolated_worktree", + }) + require(linked["id"] != lease["id"] and linked["parentLeaseID"] == parent["id"] + and linked["managedWorktreeID"] == worktree["id"] + and linked["creationOperationID"] == worktree["operation_id"], linked) + a.call(source_tool + "leases.release", { + "lease_id": linked["id"], "expected_revision": linked["revision"], "reason": "linked lease verified", + }) + removal = a.call(source_tool + "remove.plan", selector(worktree)) + require_refusal(b.dispatch(source_tool + "remove.perform", removal["perform_arguments"]), + "Unknown Computer MCP-managed worktree") + require(a.call(source_tool + "managed.read", selector(worktree))["revision"] == removal["revision"] + and checkout.exists() and self.git(["worktree", "list", "--porcelain"]) == prior, + "Foreign removal changed the child or its plan") + b.close() + a.close() + + reader = Host(self, profile="reader", unbound=True) + reader.select_project(child) + require_admission_refusal(reader.dispatch(source_tool + "managed.read", selector(worktree))) + require_admission_refusal(reader.dispatch(source_tool + "remove.perform", removal["perform_arguments"])) + reader.close() + + def change_source_access(command): + subprocess.run([str(self.options.host), command, str(self.root)], check=True, + cwd=self.root, env=self.environment, timeout=self.options.timeout_seconds) + + change_source_access("deny-source") + try: + a = Host(self, profile="scoped", unbound=True) + a.select_project(child) + require_admission_refusal(a.dispatch(source_tool + "remove.perform", removal["perform_arguments"])) + a.close() + require(checkout.exists() and self.git(["worktree", "list", "--porcelain"]) == prior, + "Child selection substituted for provider source write") + finally: + change_source_access("restore-source") + + a = Host(self, profile="scoped", unbound=True) + a.select_project(child) + response = a.dispatch(source_tool + "remove.perform", removal["perform_arguments"]) + a.select_project("primary") + error = response.get("structuredContent", {}).get("error", {}) + if response.get("isError") and interrupted_mcp_call(error): + operation_id = None + def observe(): + nonlocal operation_id + result = a.dispatch(source_tool + "managed.read", selector(worktree)) + operation_id, completed = observe_worktree_removal(result, worktree["id"], child, operation_id) + return completed + removed = wait_until(observe, self.options.timeout_seconds, "Scoped removal settlement") + else: + removed = unwrap(response, indirect=True) + require(removed["state"] == "removed" and not checkout.exists(), removed) + a.call(source_tool + "leases.release", {"lease_id": parent["id"], + "expected_revision": parent["revision"], "reason": "scoped acceptance complete"}) + a.close() + require(not (self.home / "vendor.json").exists(), "Worktree domain operations started the peer") + self.record("scoped-source-child-lineage-and-independent-authority") + def directories(self): host = Host(self) cwd = str(self.root / "primary") @@ -1033,10 +1445,7 @@ def remove_worktree(self, host, worktree, parent): require(plan["state"] == "removal_planned", plan) response = host.dispatch("codex.worktree.remove.perform", plan["perform_arguments"]) error = response.get("structuredContent", {}).get("error", {}) - message = error.get("message", "") - reply_lost = (response.get("isError") and error.get("code") == "gateway.execution_failed" - and (message.startswith("[mcp.request_cancelled]") - or message == "MCP server 'codex' request timed out.")) + reply_lost = response.get("isError") and interrupted_mcp_call(error) if not reply_lost: removed = unwrap(response, indirect=True) host.select_project("primary") @@ -1145,9 +1554,30 @@ 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 ( + ("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 + 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() + + def registered_restart_and_revocation(self): marker = "caller project fixture\n" sibling = "sibling project fixture\n" - (self.root / "other/product.txt").write_text(sibling) vendor_receipt = self.home / "vendor.json" prior_vendor = None for generation in (1, 2): @@ -1317,7 +1747,7 @@ def cleanup(self): roots = {str((self.root / name).resolve()) for name in ("primary", "other")} if not all(str(Path(entry["cwd"]).resolve()) in roots for entry in entries): errors.append("Vendor launched outside selected workspaces") - if self.options.mode == "container" and (self.home / "vendor.json").is_file(): + if self.registered_peer and (self.home / "vendor.json").is_file(): self.vendor_receipt() except Exception as error: errors.append(f"Launch receipts: {error}") @@ -1346,6 +1776,7 @@ def run(options, provenance=None): MODEL_SOURCE, REGISTERED_HOST_SOURCE)}} if provenance: report["source_acceptance"] = provenance + if fixture.registered_peer: report["authorization"] = fixture.authorization try: fixture.setup() @@ -1353,7 +1784,7 @@ def run(options, provenance=None): result = subprocess.run([str(getattr(options, key)), "--version"], text=True, capture_output=True, timeout=10, check=True, env=fixture.environment) report["binaries"][key]["version"] = result.stdout.strip() - if options.mode == "container": + if fixture.registered_peer: fixture.registered_container() else: fixture.catalog_and_diagnostics() @@ -1394,7 +1825,7 @@ def run(options, provenance=None): report["binary_digests_unchanged"] = False report["cleanup_errors"].append(f"Binary digest verification: {error}") report["passed"] = report["passed"] and not report["cleanup_errors"] and report["binary_digests_unchanged"] - if options.mode == "container" and not report["passed"] and last_tool_call is not None: + if fixture.registered_peer and not report["passed"] and last_tool_call is not None: report["last_tool_call"] = last_tool_call (fixture.root / "report.json").write_text(json.dumps(report, indent=2) + "\n") print(json.dumps({"passed": report["passed"], "mode": options.mode, From a8c3011ca79b8d75c7332c2479044572cb98f987 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:22:51 +0800 Subject: [PATCH 20/25] test: verify registered Codex fallback and plugin use --- .../RegisteredHost/RegisteredHost.swift | 5 ++ scripts/check-host.py | 53 ++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift index 5ad132a..620efef 100644 --- a/Tests/Fixtures/RegisteredHost/RegisteredHost.swift +++ b/Tests/Fixtures/RegisteredHost/RegisteredHost.swift @@ -23,6 +23,11 @@ struct RegisteredHost { print(ComputerMCPCLI.version) case "app-server": try runPeer() + case "exec": + guard let path = ProcessInfo.processInfo.environment["CODEX_HOME"] + else { throw FixtureError.invalidPeerMessage } + try Data().write(to: URL(fileURLWithPath: path).appendingPathComponent("exec-started")) + throw FixtureError.invalidPeerMessage case "register", "serve", "deny-source", "restore-source": guard arguments.count == 2 || (arguments.count == 4 && arguments[0] == "serve") else { throw FixtureError.invalidArguments } diff --git a/scripts/check-host.py b/scripts/check-host.py index d53441d..efea077 100644 --- a/scripts/check-host.py +++ b/scripts/check-host.py @@ -24,6 +24,7 @@ import tarfile import threading import time +import tomllib from types import SimpleNamespace import uuid @@ -416,9 +417,12 @@ def list_tools(self): "codex.protocol.methods.describe": "read-only", "codex.app.methods.list": "read-only", "codex.app.methods.describe": "read-only", + "codex.app.methods.call": "full-shell", + "codex.app.events.read": "read-only", "codex.app.approvals.list": "read-only", "codex.app.approvals.respond": "full-shell", "codex.app.native.thread.loaded.list": "read-only", + "codex.exec.start": "full-shell", "codex.exec.list": "read-only", "codex.app.status": "read-only", "codex.app.thread.loaded.list": "read-only", @@ -969,6 +973,18 @@ def catalog_permissions(self): catalog = "codex.protocol.methods.list" read = "codex.diagnostics.snapshot" write = "codex.worktree.leases.acquire" + # The fixture now exposes the existing events reader without a manifest + # override, as it would for a newly surfaced read-only method. + unlisted_calls = { + "codex.app.methods.call": {"method": "thread/loaded/list", "params": {}}, + "codex.exec.start": {"prompt": "Reply with OK."}, + "codex.app.events.read": {"after_cursor": 0, "max_results": 1}, + } + with (self.package / MANIFEST.name).open("rb") as manifest: + contribution = next(item for item in tomllib.load(manifest)["mcp"] if item["id"] == "app-server") + require("requirements" not in contribution + and unlisted_calls.keys().isdisjoint(contribution.get("tool_requirements", {})), + "Fallback cases must be absent from the selected contribution's requirements") for indirect in (False, True): host = Host(self, indirect=indirect, profile="reader", unbound=True) host.call(catalog) @@ -982,6 +998,14 @@ def catalog_permissions(self): host.call(catalog) for name in ("codex.app.status", "codex.app.native.thread.loaded.list", "codex.exec.list"): require_admission_refusal(host.dispatch(name)) + for name, arguments in unlisted_calls.items(): + result = host.raw(name, arguments, gateway_envelope=True) + error = result.get("structuredContent", {}).get("error", {}) + require(result.get("isError") is True and error.get("code") == "permission.required" + and error.get("call_dispatched") is False + and [(request.get("permission"), request.get("object"), request.get("value")) + for request in error.get("requests", [])] == [("project", "other", "write")], + result) if indirect: host.select_project("other") require_admission_refusal(host.dispatch(read)) @@ -989,9 +1013,35 @@ def catalog_permissions(self): host.workspace = "other" require_refusal(host.dispatch(read), "gateway.tool_unknown") host.close() - require(not (self.home / "vendor.json").exists(), "Catalog, read or refused call started the peer") + require(not any((self.home / name).exists() for name in ("peer-count", "exec-started")), + "Catalog, read or refused call started the peer") self.record("direct-and-forwarded-tool-requirements-and-conservative-fallback") + def plugin_use_permissions(self): + host = Host(self, with_observer=True) + catalog = "codex.protocol.methods.list" + arguments = {"limit": 1} + for indirect in (False, True): + host.indirect = indirect + require(host.call("codex.app.events.read", {"after_cursor": 0, "max_results": 1})["events"] == [], + "Expected an empty event buffer for the newly exposed reader") + require(host.call(catalog, arguments)["methods"], "Expected a catalog entry") + self.revoke("acceptance") + for indirect in (False, True): + host.indirect = indirect + result = host.raw(catalog, arguments, gateway_envelope=True) + error = result.get("structuredContent", {}).get("error", {}) + require(result.get("isError") is True and error.get("code") == "permission.denied" + and error.get("reason") == 'permissionDenied(ComputerMCPPermissions.Permission.plugin("codex"))', + result) + project_read = host.client.send("tools/call", { + "name": "file.read", "arguments": {"project_id": "primary", "path": "product.txt"}, + }) + require(unwrap(project_read)["content"] == "caller project fixture\n", project_read) + host.close() + require(not (self.home / "peer-count").exists(), "Plugin use checks started the peer") + self.record("direct-and-forwarded-admission-requires-plugin-use") + def project_selection(self): name = "codex.protocol.methods.list" for indirect in (False, True): @@ -1557,6 +1607,7 @@ def registered_container(self): self.catalog_permissions() self.scoped_worktree_permissions() for name, check, settings in ( + ("plugin-use", "plugin_use_permissions", {}), ("cold", "cold_catalog_and_reads", {}), ("single-project", "project_selection", {"project_count": 1}), ("no-project", "project_selection", {"project_count": 0}), From f7d553ffd245bc93c7487a2e81ead7fc54d2aa7a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:40:42 +0800 Subject: [PATCH 21/25] ci: pin Host for integrated candidate checks --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index cb42063..1614582 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -504d1d434a192a2d7c4595f8888ebb63f728f228 +d73d6b522520896fc041a22bb30fe04f4f81beaf From 481d20afabd41142d3754b76ac60e5a0b63dc3bd Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:03:26 +0800 Subject: [PATCH 22/25] ci: verify against the parallel Host candidate --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 1614582..d42a787 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -d73d6b522520896fc041a22bb30fe04f4f81beaf +c2a81115dee819122c7368bd266bc74136011ceb From b42d2fdd44d00c9040916fb66aae0789986624d0 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:20:14 +0800 Subject: [PATCH 23/25] ci: verify the accepted Host candidate --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index d42a787..44dda92 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -c2a81115dee819122c7368bd266bc74136011ceb +bb0c029778a7d5e44670606abfc2261f841beea7 From 8826aa2512dbec436a67540768a9595fbf1f47c1 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 11:16:40 +0800 Subject: [PATCH 24/25] docs: prepare 0.1.0 release notes --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9149a7b..719c7f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,12 @@ ## Unreleased +## 0.1.0 — 2026-11-30 + ### Added +- Codex can use Host-managed project worktrees for isolated work. The adapter tracks writer leases and exposes diagnostics for managed operations. + - Public-host runtime acceptance for the packaged adapter and installed Codex, including native permissions, lifecycle recovery, thread handoff, authenticated model execution and exact owned-process cleanup. From e264517d0e18e63e3b9bc142c4227f46423396c3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:07 +0800 Subject: [PATCH 25/25] ci: pin Computer MCP 0.1.0 for plugin validation --- .github/computer-mcp-host.sha | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/computer-mcp-host.sha b/.github/computer-mcp-host.sha index 44dda92..58d2856 100644 --- a/.github/computer-mcp-host.sha +++ b/.github/computer-mcp-host.sha @@ -1 +1 @@ -bb0c029778a7d5e44670606abfc2261f841beea7 +bee91275a6301e56c64f677125f5d7f38ba7fe0e