From b283f08d3af93d884ff05a606d0a79b6285c58b3 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 04:06:13 -0500 Subject: [PATCH 1/7] Continue sessions on the current agent executable (#891) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every established session — ordinary Session/Prompt, held conversations, native launch, client-native attachment and incomplete replay — now uses the executable the current environment selects, reopens the exact retained conversation, and requires the provider's live assertion of the same native identity. Version and digest observations are diagnostic history: a change warns once per logical session per invocation on stderr and never refuses. Missing or different assertions and real resume failures still refuse without creating a replacement. - Generalize strict reopening (expectedAgentSessionId) beyond held Codex. - Select the host executable once, observe that same file, execute it. - Confirm client-native handoffs over ACP: before a native resume, and after a fresh creation once the child joins; exit status is never identity. - Retire build-drift admission and legacy refusals based only on missing historical observation; keep original-record agreement. - Add AcpxProviderDependencies.compatibilityWarnings, shared per CLI invocation; show held Sidekick stderr beside the reply. - Amend ACP, native launch, workflow and REPL specs, architecture, and decision records 004/005; proof fixtures record versions as evidence. --- architecture.md | 6 +- packages/acp/src/native-launch.ts | 101 +- packages/acp/src/provider.ts | 1171 ++++++++++++----- packages/acp/tests/certification-fixture.ts | 2 +- .../fixtures/claude-native-launch-proof.ts | 14 +- .../fixtures/claude-native-to-acp-proof.ts | 2 +- .../fixtures/codex-native-launch-proof.ts | 23 +- packages/acp/tests/helpers.ts | 465 ++++--- packages/acp/tests/host-conversation.test.ts | 448 ++++--- packages/acp/tests/native-launch.test.ts | 573 ++++++-- packages/acp/tests/released-peer.ts | 2 +- packages/agent/src/launch.ts | 22 +- packages/cli/src/agent-stack.ts | 14 + packages/cli/src/cli.ts | 22 +- packages/cli/src/compiled.ts | 2 +- packages/cli/src/deno-workflow.ts | 8 +- packages/cli/src/deno.ts | 2 +- packages/cli/src/repl/application.ts | 32 + packages/cli/src/repl/program.ts | 1 + packages/cli/src/repl/sidekick/assembly.ts | 3 + packages/cli/src/repl/sidekick/owner.ts | 39 + packages/cli/src/workflow-agent.ts | 20 +- packages/cli/src/workflow.ts | 5 +- .../adversarial-session-continuity.test.ts | 130 +- packages/cli/tests/fixtures/host-agent.ts | 4 +- packages/cli/tests/repl-agent-journey.test.ts | 67 + .../cli/tests/repl-sidekick-journey.test.ts | 61 + .../cli/tests/session-compatibility.test.ts | 485 +++++++ packages/cli/tests/support/mounted-repl.ts | 2 + .../cli/tests/workflow-agent-sessions.test.ts | 28 +- packages/runtime/apis.ts | 14 + packages/runtime/executable-observer.ts | 25 +- packages/runtime/mod.ts | 1 + .../runtime/tests/executable-observer.test.ts | 39 + specs/acp-client-spec.md | 153 ++- specs/decisions.md | 1 + .../decisions/004-host-installed-codex-cli.md | 8 +- ...current-executable-session-continuation.md | 81 ++ specs/decisions/README.md | 1 + specs/native-agent-session-launch-spec.md | 368 +++--- specs/repl-spec.md | 10 + specs/workflow-workspace-spec.md | 28 +- 42 files changed, 3321 insertions(+), 1162 deletions(-) create mode 100644 packages/cli/tests/session-compatibility.test.ts create mode 100644 specs/decisions/005-current-executable-session-continuation.md diff --git a/architecture.md b/architecture.md index beeeb340f..b8d6807ea 100644 --- a/architecture.md +++ b/architecture.md @@ -252,11 +252,13 @@ A storage lease belongs to the scope that opened it. The provider owns the under The workflow executor holds the run’s exclusive executor lock through execution, cleanup, and committed lifecycle settlement. Connection serialization alone does not permit another executor to advance the run. -Native Agent ownership separately protects a logical provider conversation. Construction provenance and executable compatibility do not replace live ownership; release requires evidence that the owner’s work can no longer act. +Native Agent ownership separately protects a logical provider conversation. Construction provenance and executable metadata do not replace live ownership; release requires evidence that the owner’s work can no longer act. + +A conversation continues on the executable the current environment selects. The provider's positive assertion of the retained native identity — not version or digest equality — decides whether it continues; a missing or different assertion refuses without creating a replacement. Executable observations are diagnostic history: kept with the records that first made them, never rewritten to name today's build, and reported once per logical session in an invocation when they differ or cannot be determined. That warning state belongs to the invocation's owning scope, and a held conversation's diagnostics are captured in the task that runs its work. A released operating-system lock proves a previous local workflow executor is gone. It does not, by itself, prove native Agent backend quiescence or clear an unresolved ownership record. -The [Workflow Workspace specification](specs/workflow-workspace-spec.md) owns executor and storage lifetimes. The [Native Agent session launch specification](specs/native-agent-session-launch-spec.md) owns handoff, build compatibility, and release proof. +The [Workflow Workspace specification](specs/workflow-workspace-spec.md) owns executor and storage lifetimes. The [Native Agent session launch specification](specs/native-agent-session-launch-spec.md) owns handoff, identity confirmation, and release proof; the [ACP client specification](specs/acp-client-spec.md#availability) owns executable selection and compatibility warnings. ### Cancellation and attachment diff --git a/packages/acp/src/native-launch.ts b/packages/acp/src/native-launch.ts index 7974bec19..cb8aaa138 100644 --- a/packages/acp/src/native-launch.ts +++ b/packages/acp/src/native-launch.ts @@ -9,36 +9,36 @@ * allocated identity, applies private instructions to the first user turn without * a bootstrap, and later resumes that conversation. * - * Until that contract is proven against the installed CLI, launch refuses before - * ACP detach, client identity allocation or private-file creation. Build pinning - * is an independent discriminator: either construction route may bind a session - * to the exact executable build that issued or accepted its identity. + * A launch refuses before ACP detach, client identity allocation or + * private-file creation for an adapter this host does not advertise. The + * executable each operation runs is the one the current environment selects; + * its observed version and digest are diagnostic history, recorded beside a + * session XMD constructs and compared only to warn. What continues a session is + * the provider's positive confirmation of its native identity. */ import { randomUUID } from "node:crypto"; import type { IdentityProvenance } from "@executablemd/agent/api"; /** - * What an adapter knows about the build behind its executable. + * What an adapter knows about the executable behind it. * - * A provider-native identity only means something while the build behind it can - * be recognized later: two builds of one provider accept the same identity and - * disagree silently about what it names, whether XMD chose that identity or the - * provider issued it. Everything here is - * that adapter's private dialect — which command to observe, what its version - * output looks like, and what the ACP adapter child needs in order to run the - * same build. None of it reaches a document. + * Everything here is that adapter's private dialect — which command a host + * resolves when it makes no selection of its own, what its version output + * looks like, and what the ACP adapter child needs in order to run the selected + * file. None of it reaches a document, and none of it admits or refuses a + * session: the version is reported, and the provider's live identity assertion + * decides whether a conversation continues. */ export interface NativeBinding { - /** The command whose build is observed, bound and retained. */ + /** The command a host without its own selection resolves and observes. */ command: string; /** The arguments that ask that exact file its version. */ versionArgs?: readonly string[]; /** * The canonical version from that output, or `undefined` when the output is - * not something this adapter recognizes. An unrecognized version is a - * refusal, not a value to retain — a build XMD cannot name is one it cannot - * later confirm. + * not something this adapter recognizes. An unrecognized version is reported + * as undetermined and never retained under a guess; it does not stop work. */ version(output: string): string | undefined; /** @@ -73,14 +73,14 @@ export interface NativeBinding { * * The whole line is retained rather than the number alone, because the number * alone is not a build: the same version string from a different product would - * compare equal. Anything that does not look like this is unrecognized, and an - * unrecognized build is refused rather than retained under a guess. + * compare equal. Anything that does not look like this is unrecognized, and is + * reported as undetermined rather than retained under a guess. * * Exactly one line may match. Zero is an output this adapter does not * recognize; two or more is output it cannot read as one answer, and taking * the first would be picking a build out of a list of them. Neither is - * repeated anywhere — the caller refuses with a stable class, and the output - * itself is provider-private. + * repeated anywhere — the caller reports the version as undetermined, and the + * output itself is provider-private. */ function claudeVersion(output: string): string | undefined { const canonical = output @@ -94,10 +94,10 @@ function claudeVersion(output: string): string | undefined { * Codex reports one line shaped `codex-cli x.y.z` — `codex-cli 0.153.2` at the * release this was proven against. * - * What is admitted is that shape, not that release: another canonical version - * passes here. Exactness belongs to the session instead — the string accepted - * here becomes its retained executable binding, and a later build that differs - * refuses against that binding rather than against a constant written down here. + * What is recognized is that shape, not that release: another canonical + * version passes here. The string recognized for a session XMD constructs is + * retained as its executable history, and a later different version is + * reported against that history; it is never compared with a constant here. * * The product word is retained with the number for the same reason Claude's * whole line is: a bare semver from another tool compares equal. The one-line @@ -109,7 +109,7 @@ function codexVersion(output: string): string | undefined { // second build's line ride along unnoticed: the answer would be "one // canonical line was in there somewhere" rather than "this is what the // executable reported". A wrapper that prints anything beside the version has - // not told us which build ran, so it is refused. + // not told us which build ran, so its version is undetermined. const lines = output .split("\n") .map((line) => line.trim()) @@ -170,12 +170,11 @@ export interface ClientAllocatedAdapter extends AdapterCommands { /** The argv that creates a session under `id` with that instruction layer. */ create(nativeSessionId: string, instructionFile: string): string[]; /** - * Which build of this adapter's executable a session is bound to. + * How this adapter's executable is reached and described. * - * Required, because an identity XMD chose is only meaningful beside the build - * that accepted it. The argv `create` and `resume` return still begins with - * the stable launcher name, which is what durable records carry; a run - * replaces that first member with the exact path it observed. + * The argv `create` and `resume` return still begins with the stable + * launcher name, which is what durable records carry; a run replaces that + * first member with the exact path the current environment selected. */ binding: NativeBinding; } @@ -185,17 +184,17 @@ export interface ProviderReturnedAdapter extends AdapterCommands { } /** - * A provider-returned adapter whose sessions are pinned to one observed build. + * A provider-returned adapter whose executable this host selects and describes. * * The provider still names the session, so nothing here chooses an identity. - * What the binding adds is the other half of what makes that name mean - * something: an identity a provider issued is only resumable by the build that - * issued it, and two builds of one provider accept the same string while - * disagreeing about which conversation it is. + * What the binding adds is which file runs and what version it reports, so a + * session's construction route can keep that as history and a later run can + * warn when it differs. * * It is a separate type rather than an optional member on the one above, - * because an adapter a host supplies for a provider that does not pin builds - * must not be able to reach a binding at all. Narrowing is the only way in. + * because an adapter a host supplies for a provider without a carried + * executable must not be able to reach a binding at all. Narrowing is the only + * way in. */ export interface BoundProviderReturnedAdapter extends ProviderReturnedAdapter { binding: NativeBinding; @@ -206,7 +205,7 @@ export type NativeAdapter = | BoundProviderReturnedAdapter | ClientAllocatedAdapter; -/** An adapter whose sessions are bound to the build that accepted them. */ +/** An adapter whose executable this host selects and describes. */ export type BuildBoundAdapter = BoundProviderReturnedAdapter | ClientAllocatedAdapter; /** Whether this adapter names its own sessions. */ @@ -215,12 +214,12 @@ export function allocatesIdentity(adapter: NativeAdapter): adapter is ClientAllo } /** - * Whether this adapter's sessions are bound to one observed executable build. + * Whether this adapter's executable is selected and described by this host. * * Independent of who names the session: `claude` allocates its identities and - * `codex` is handed them, and both are meaningless beside a build this run - * cannot recognize. An adapter without a binding keeps the released - * native-only behavior — it observes nothing and gains nothing. + * `codex` is handed them, and for both the current environment selects the + * executable and its version is reported. An adapter without a binding keeps + * the released native-only behavior — it observes nothing. */ export function bindsBuild(adapter: NativeAdapter): adapter is BuildBoundAdapter { return "binding" in adapter; @@ -287,8 +286,13 @@ const ADAPTERS: Readonly> = { }; /** - * The adapters whose native creation, instruction and resume contracts have - * been proven against the installed CLI. + * The adapters whose native creation, instruction and resume contracts XMD's + * integration supports. + * + * Recorded CLI, adapter and host versions describe the checks that ran. They + * are evidence, not an allowlist or a requirement to repeat certification for + * every release; the live documents below remain opt-in integration + * regressions. * * `claude` is here because `packages/acp/src/ClaudeNativeLaunch.test.md` and * `packages/acp/src/ClaudeZeroTurnExit.test.md` ran the production command @@ -321,8 +325,7 @@ const ADAPTERS: Readonly> = { export const ADVERTISED_NATIVE_LAUNCH: readonly string[] = ["claude", "codex"]; /** - * The adapters whose client-native ACP attachment has been proven against the - * installed CLI. + * The adapters whose client-native ACP attachment XMD's integration supports. * * A separate list from the one above, because they are separate capabilities: * handing a session to a native UI and later joining that same conversation @@ -332,8 +335,10 @@ export const ADVERTISED_NATIVE_LAUNCH: readonly string[] = ["claude", "codex"]; * `claude` is here because `packages/acp/src/ClaudeNativeToAcp.test.md` ran the * production command through the built binary: a native turn carrying a random * marker, then a marker-free ACP Prompt that recovered it under the same - * provider-native identity and the same observed build, and an independent - * absent identity that refused without taking a turn. + * provider-native identity, and an independent absent identity that refused + * without taking a turn. This attachment is also how a client-native session's + * identity is positively confirmed before a native resume and after a native + * creation. */ export const ADVERTISED_CLIENT_NATIVE_ATTACHMENT: readonly string[] = ["claude"]; diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index f9df5c7c9..d262a9265 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -140,6 +140,7 @@ import { ExecutableObservationError, nativeLaunch, notifyTerminal, + writeDiagnostic, } from "@executablemd/runtime"; import type { AgentSessionCoordinator, @@ -147,6 +148,7 @@ import type { AgentSessionOwnerKind, AgentSessionOwnership, ExecutableObserver, + ObservedExecutable, } from "@executablemd/runtime"; import { ADVERTISED_CLIENT_NATIVE_ATTACHMENT, @@ -324,13 +326,14 @@ export interface AcpxProviderDependencies { * How this host observes the build behind an executable. * * Supplied directly by the host that built it, like the coordinator and the - * route store beside it. It is deliberately not a contextual Api: executable - * validation decides which retained history may be accepted, and a decision - * document middleware could replace could point the observation at one binary - * while the run spawns another. + * route store beside it. What it reports is diagnostic: the version and + * digest of the executable this run selected, recorded beside a session it + * constructs and compared with that history to warn when they differ. It + * never decides whether a conversation may continue, and it is never asked + * to resolve a command the host has already selected. * - * Absent means this host cannot say which build it would run, so an agent - * whose sessions XMD names refuses before any provider effect. + * Absent means this host cannot say which version it runs. Work continues, + * with that reported once per logical session. */ executableObserver?: ExecutableObserver; /** @@ -410,21 +413,36 @@ export interface AcpxProviderDependencies { */ permissions?: "composable" | "strict"; sessions?: AcpxSessionPolicy; + /** + * Sessions already warned about in this host invocation. + * + * Share one set across its provider installations. Omission gives this + * installation its own set. Keys are private logical placements, and the + * set is never retained or used to admit execution. + */ + compatibilityWarnings?: Set; } /** - * One observed build, ready to be bound to a session. + * The executable one live operation selected, and what was observed about it. * - * `livePath` is the canonical path this run spawns and hands to the matching - * ACP child through `environment`. It appears in no record, route, diagnostic, - * result, or parent environment, and it does not outlive the operation that - * observed it. + * `livePath` is the file the current environment selected — the host's own + * selection for a carried adapter, or the observer's resolution on a host that + * makes none — and it is what this run spawns and hands to the matching ACP + * child through `environment`. It is absent for an opaque custom command, + * whose backend this provider does not guess at. It appears in no record, + * route, diagnostic, result, or parent environment, and it does not outlive the + * operation that selected it. + * + * `binding` is the complete current observation of that file, when one could + * be made. It is diagnostic: a fresh construction records it as history, and a + * later run compares it with that history only to warn. */ interface BoundBuild { agentName: string; agentCommand: string; - binding: ExecutableBuildBindingV1; - livePath: string; + binding: ExecutableBuildBindingV1 | undefined; + livePath: string | undefined; environment: Record; /** The exact ACP adapter command this binding was proven against, if pinned. */ adapterCommand: string | undefined; @@ -699,6 +717,14 @@ interface LaunchInvocation { * the other. Recording it is what keeps the check from running twice. */ readonly reconciled: Set; + /** + * Sessions whose native identity this invocation has positively confirmed. + * + * The live ACP load, or the accepted first turn, that reported the exact + * provider-native identity the handoff names. A resume reaches the native UI + * only after this, and a creation acknowledges success only after it. + */ + readonly confirmed: Set; } /** @@ -1176,6 +1202,7 @@ function* useAcpxProviderState( ? undefined : structuredClone(dependencies.newSessionOptions); const sessions = checkedSessionPolicy(dependencies?.sessions); + const compatibilityWarnings = dependencies?.compatibilityWarnings ?? new Set(); const strict = dependencies?.permissions === "strict"; const stateScope = yield* useScope(); const turns = yield* useSerialQueues(); @@ -1302,14 +1329,19 @@ function* useAcpxProviderState( return options; } - /** The `(agent command, build)` partition a bound runtime is kept under. */ + /** + * The `(agent command, selected environment)` partition a bound runtime is + * kept under. + * + * Keyed by what the child is actually started with, never by what was + * observed about it: two selections never share a child, and the same + * selection reached twice does, whatever its version reports. + */ function partitionOf(build: BoundBuild): string { - return [ - build.agentCommand, - build.binding.reportedVersion, - build.binding.executableDigest.algorithm, - build.binding.executableDigest.value, - ].join("\u0000"); + const environment = Object.entries(build.environment).sort(([a], [b]) => (a < b ? -1 : 1)); + return [build.agentCommand, build.adapterCommand ?? "", JSON.stringify(environment)].join( + "\u0000", + ); } /** @@ -1915,8 +1947,6 @@ function* useAcpxProviderState( */ build?: BoundBuild; attachment?: { resumeSessionId: string }; - /** Require the live Codex load to confirm a held conversation after a build change. */ - verifyReopening?: boolean; /** The session's state, as the caller resolved it. */ state: "new" | "existing"; /** @@ -1978,17 +2008,37 @@ function* useAcpxProviderState( const held = managed.get(prepared.details.sessionKey); const reopening = attachment === undefined && intent.state === "existing" - ? yield* reopeningOf(prepared) + ? yield* reopeningOf(agentName, prepared) : undefined; - let expectedAgentSessionId: string | undefined; - if (intent.verifyReopening) { - expectedAgentSessionId = reopening?.agentSessionId; - if (!expectedAgentSessionId) { - throw new AttachmentRefused({ - class: "identity-unavailable", - message: `session "${prepared.sessionKey}" has no retained native identity to verify after the Codex build changed`, - }); - } + // An established conversation is reopened only with the provider's live + // confirmation that it is the same native conversation, whichever + // executable the current environment selected. An adapter that owes a + // native identity and has none retained cannot be confirmed, so it refuses + // here rather than loading something it could not tell apart. + let expectedAgentSessionId = reopening?.agentSessionId; + if ( + reopening !== undefined && + expectedAgentSessionId === undefined && + owesIdentity(agentName) + ) { + throw new AttachmentRefused({ + class: "identity-unavailable", + message: + `session "${prepared.sessionKey}" has no retained native identity, so the provider ` + + `cannot confirm it is reopening the same conversation`, + }); + } + // An attachment to an identity XMD chose is strict once ACPX holds an + // established arrangement for it. Before one exists there is no record to + // verify against, so the exact load is checked against its returned + // assertion below instead. + const arranged = + attachment === undefined ? undefined : yield* until(store.load(prepared.sessionKey)); + const firstAttachment = + attachment !== undefined && + (arranged === undefined || arranged.sessionMaterialization?.state === "pending"); + if (attachment !== undefined && !firstAttachment) { + expectedAgentSessionId = attachment.resumeSessionId; } const resumeSessionId = attachment?.resumeSessionId ?? reopening?.acpSessionId; let managedEntry: ManagedSession; @@ -2049,6 +2099,13 @@ function* useAcpxProviderState( // conversation this session names is not reachable, and the adapter's own // message would carry provider-private detail — so the stable class is // what crosses, and nothing was created in its place. + if (firstAttachment) { + yield* withdrawRefusedArrangement(prepared.details.sessionKey); + } + const identity = nativeIdentityRefusal(error); + if (identity !== undefined) { + throw identity; + } throw new AttachmentRefused({ class: "identity-unavailable", message: @@ -2092,6 +2149,9 @@ function* useAcpxProviderState( // reconciles that, and a turn taken through this handle would land in // history that is not this session's, so it is given up before it is used. yield* abandonHandle(managedEntry, "attachment identity mismatch"); + if (firstAttachment) { + yield* withdrawRefusedArrangement(prepared.details.sessionKey); + } throw new AttachmentRefused({ class: "identity-unavailable", message: @@ -2127,28 +2187,31 @@ function* useAcpxProviderState( } /** - * The exact ACP session a held conversation's record names, and the record - * as it stood before this ensure. + * The exact ACP session an established record names, the native identity it + * must confirm, and the record as it stood before this ensure. * * ACPX reuses a persistent record in place only when it was built by the * same command string and the same argv. Anything else — another adapter, or * the same command given as a string where it was an array — would create a - * fresh conversation under the same key. So a held conversation always names - * the record's own ACP loading target: a record ACPX can reuse in place is - * reused, and any other is loaded through today's command against the + * fresh conversation under the same key. So an established session always + * names the record's own ACP loading target: a record ACPX can reuse in place + * is reused, and any other is loaded through today's command against the * history that already exists, never replaced. Read here, with the * session's queue and ownership held, so the record this answers from is the * one the ensure acts on. * - * A pending record asserts nothing and reopens nothing. + * Every supported adapter's established session is reopened this way, and so + * is every held conversation: the same continuation, whatever selected the + * executable today. A pending record asserts nothing and reopens nothing. */ function* reopeningOf( + agentName: string, prepared: Extract, ): Operation< { acpSessionId: string; agentSessionId?: string; record: AcpSessionRecord } | undefined > { const continuation = prepared.continuation; - if (continuation === undefined) { + if (continuation === undefined && adapterFor(agentName) === undefined) { return undefined; } const record = yield* until(store.load(prepared.details.sessionKey)); @@ -2157,7 +2220,7 @@ function* useAcpxProviderState( } // The history's own account first. Before the host acknowledged one, the // provider's promoted record is the only assertion there is. - const agentSessionId = continuation.agentSessionId ?? record.agentSessionId; + const agentSessionId = continuation?.agentSessionId ?? record.agentSessionId; return { acpSessionId: record.acpSessionId, ...(agentSessionId === undefined ? {} : { agentSessionId }), @@ -2166,6 +2229,47 @@ function* useAcpxProviderState( }; } + /** + * Whether this agent's established sessions owe a provider-native identity. + * + * An adapter that accepts a first turn explicitly asserts the conversation it + * made, so a session of it with no retained assertion is one nothing can + * confirm. A standard ACP integration asserts only its loading target. + */ + function owesIdentity(agentName: string): boolean { + return adapterFor(agentName)?.acceptance === "first-turn-acceptance"; + } + + /** + * Leave a refused first attachment asserting nothing. + * + * ACPX saves the arrangement an exact load answered with before the caller + * can refuse it. Before that load there was no record, so there is nothing to + * restore; what must not happen is for the refused answer to stand as this + * session's account and refuse every later exact retry. Marking it as + * occupancy is what a record no backend confirmed already means. + */ + function* withdrawRefusedArrangement(sessionKey: string): Operation { + try { + const left = yield* until(store.load(sessionKey)); + if (left === undefined || left.sessionMaterialization?.state === "pending") { + return; + } + const { agentSessionId: _refused, ...rest } = left; + yield* until( + store.save({ + ...rest, + sessionMaterialization: { + state: "pending", + contract: "executablemd.session-materialization/v1", + }, + }), + ); + } catch (error) { + cleanupErrors.push(toError(error)); + } + } + /** * The natural key one logical session is owned under. * @@ -2289,10 +2393,11 @@ function* useAcpxProviderState( * Refuse an advertised agent this host is not assembled to serve. * * Fail-closed, and closed means what the agent actually needs: every - * advertised session needs a coordinator to say who owns it, and one bound to - * a build also needs a route store to say how it was constructed and an - * observer to say which build that was. A host that can answer one question - * but not the other cannot act on a session a native UI may be in. + * advertised session needs a coordinator to say who owns it, and one whose + * adapter keeps construction history also needs a route store to say how it + * was constructed. A host that can answer one question but not the other + * cannot act on a session a native UI may be in. Observing an executable is + * diagnostic, so a host that cannot is not refused for it. */ function requireAssembly(agentName: string, sessionKey: string): void { if (!ownable(agentName)) { @@ -2306,9 +2411,6 @@ function* useAcpxProviderState( if (!routeStore) { missing.push("construction routes"); } - if (!executableObserver) { - missing.push("executable build observation"); - } } if (missing.length === 0) { return; @@ -2393,89 +2495,190 @@ function* useAcpxProviderState( } /** - * Publish or adopt `acp-first` for an agent whose sessions XMD would - * otherwise name, and refuse if this session already has an identity. + * Select the executable one live operation runs, and observe it. * - * Eager on purpose. Creating provider history first and writing down how it - * was constructed afterwards leaves a window in which a crash makes the - * session look unconstructed — and a client-native launch meeting that window - * would give a conversation that already exists a second identity. - */ - /** - * The exact live path of the build behind an adapter's command. + * Selection comes first and is the only thing that can refuse. A carried + * adapter's executable is chosen by the host's own selection — its explicit + * environment variable, then the host PATH — exactly once, and that same file + * is what is observed, spawned and handed to the matching child. A host that + * makes no selection of its own lets its observer resolve the command. A + * custom command is the host's to run as configured: nothing here guesses + * which backend an opaque wrapper starts, so its version is simply unknown. * - * Every way this can fail — no observer, resolution, canonicalization, an - * unreadable or non-executable file, a version this adapter does not - * recognize — ends in one stable class, because they are all the same - * question: is this the build that established the session. + * Observation is diagnostic. An executable whose version cannot be asked or + * read leaves no binding and keeps its selection; only a selected file that is + * missing or cannot be run is an availability failure. */ - function* observeBuild( + function* selectBuild( agentName: string, agentCommand: string, binding: NativeBinding, ): Operation { - if (!executableObserver) { - throw new AttachmentRefused({ - class: "executable-binding-refused", - message: - `this host cannot observe which build of "${agentName}" it would run, so it cannot ` + - `bind a session to one`, - }); - } - let observed; - try { - observed = yield* executableObserver.observe(binding.command, { - ...(binding.versionArgs === undefined ? {} : { versionArgs: binding.versionArgs }), - }); - } catch (error) { - // Only the observer's own stable reason crosses. Its message names a - // path, and a path is host layout. - throw new AttachmentRefused({ - class: "executable-binding-refused", - message: `the build behind "${agentName}" could not be observed: ${ - error instanceof ExecutableObservationError ? error.refusal : "unavailable" - }`, - }); + const versionOptions = + binding.versionArgs === undefined ? {} : { versionArgs: binding.versionArgs }; + let environment: Record = {}; + let livePath: string | undefined; + let observed: ObservedExecutable | undefined; + if (dependencies?.agentProcessEnv !== undefined) { + let selected: Record | undefined; + try { + selected = yield* dependencies.agentProcessEnv(agentName, agentCommand); + } catch (error) { + // The host's own selector says what to correct, and says it without a + // path; anything else is reported in this provider's stable terms. + throw new AttachmentRefused( + error instanceof Error && error.message.length > 0 + ? { class: "executable-binding-refused", message: error.message } + : unavailable(agentName, error), + ); + } + if (selected !== undefined) { + environment = { ...selected }; + livePath = selectedPath(binding, selected); + } + } else if (executableObserver) { + try { + observed = yield* executableObserver.observe(binding.command, versionOptions); + } catch (error) { + if (!diagnosticOnly(error)) { + throw new AttachmentRefused(unavailable(agentName, error)); + } + } + if (observed !== undefined) { + livePath = observed.path; + environment = binding.environment(observed.path); + } } - const version = binding.version(observed.versionOutput); - if (version === undefined) { - // Deliberately without the raw output: it is provider-private, and this - // message is retained in a diagnostic. - throw new AttachmentRefused({ - class: "executable-binding-refused", - message: - `"${agentName}" reported a version this adapter does not recognize, so the build ` + - `behind it cannot be named`, - }); + if (livePath !== undefined && observed === undefined && executableObserver) { + try { + observed = yield* executableObserver.observe(livePath, versionOptions); + } catch (error) { + if (!diagnosticOnly(error)) { + throw new AttachmentRefused(unavailable(agentName, error)); + } + } } + const version = observed === undefined ? undefined : binding.version(observed.versionOutput); return { agentName, agentCommand, - livePath: observed.path, - binding: { - schema: "executable-build.v1", - reportedVersion: version, - executableDigest: observed.digest, - }, - environment: binding.environment(observed.path), + livePath, + environment, adapterCommand: binding.adapterCommand, + binding: + observed === undefined || version === undefined + ? undefined + : { + schema: "executable-build.v1", + reportedVersion: version, + executableDigest: observed.digest, + }, }; } - /** The stable comparison two builds of one session fail. */ - function buildDrift( - sessionKey: string, - retained: ExecutableBuildBindingV1, - live: ExecutableBuildBindingV1, - ): LaunchFailure { + /** The path a selection names under the variable this adapter's child reads. */ + function selectedPath( + binding: NativeBinding, + selected: Record, + ): string | undefined { + for (const variable of Object.keys(binding.environment(""))) { + const value = selected[variable]; + if (value !== undefined && value.length > 0) { + return value; + } + } + return undefined; + } + + /** + * Whether an observation failure says only that the version is unknown. + * + * A selected file that is missing, is not a file, or cannot be executed is an + * availability failure. Anything else the observer reports leaves the + * selection standing and the version undetermined. + */ + function diagnosticOnly(error: unknown): boolean { + return !( + error instanceof ExecutableObservationError && + (error.refusal === "not-found" || + error.refusal === "not-a-file" || + error.refusal === "not-executable") + ); + } + + /** + * How a retained launch's conversation is reached again over ACP. + * + * A provider-named conversation whose ACPX record is established is reopened + * by that record's own loading target under its retained assertion. Without + * one — and always for an identity XMD chose — the retained native identity + * is loaded exactly and the live answer must assert it. Neither creates. + */ + function* retainedReach( + prepared: PreparedLaunchRecord, + ): Operation<{ attachment?: { resumeSessionId: string } }> { + if (prepared.identityProvenance === "provider-returned") { + const record = yield* until(store.load(prepared.sessionKey)); + if (record !== undefined && record.sessionMaterialization?.state !== "pending") { + return {}; + } + } + return { attachment: { resumeSessionId: prepared.nativeSessionId } }; + } + + /** + * The availability failure a selected executable that cannot run is. + * + * Only the stable reason crosses: an observer's or selector's own message + * names a path, and a path is host layout. + */ + function unavailable(agentName: string, error: unknown): LaunchFailure { + const reason = error instanceof ExecutableObservationError ? `: ${error.refusal}` : ""; return { class: "executable-binding-refused", message: - `session "${sessionKey}" was created by ${retained.reportedVersion} and this run ` + - `would use ${live.reportedVersion}, so the conversation it names cannot be confirmed`, + `the executable "${agentName}" runs is unavailable${reason}. Install it, or correct the ` + + `environment that selects it.`, }; } + /** + * Warn once, before affected live work, about what the version says. + * + * A version that differs from the session's own history is reported, and so + * is one that cannot be determined. History without a version says nothing, + * so it warns about nothing. The key is added in the same step it is + * tested, so two operations of one invocation cannot both deliver it; the + * set admits nothing and is never written down. + */ + function* warnCompatibility( + ownerCommand: string, + sessionKey: string, + placement: string, + historical: string | undefined, + build: BoundBuild, + ): Operation { + const current = build.binding?.reportedVersion; + const before = historical === undefined ? undefined : productVersion(historical); + const now = current === undefined ? undefined : productVersion(current); + let text: string; + if (now === undefined) { + text = `The ${productName(build.agentName)} version could not be determined. Continuing.`; + } else if (before !== undefined && before !== now) { + text = + `${productName(build.agentName)} has changed from ${before} to ${now} since this session ` + + `was established. Continuing the existing conversation.`; + } else { + return; + } + const key = [ACPX_PROVIDER, ownerCommand, sessionKey, placement].join("\u0000"); + if (compatibilityWarnings.has(key)) { + return; + } + compatibilityWarnings.add(key); + yield* writeDiagnostic(text); + } + /** * What a client-native route's provider arrangement already asserts. * @@ -2487,7 +2690,7 @@ function* useAcpxProviderState( */ function* retainedAssertion(sessionKey: string, nativeSessionId: string): Operation { const record = yield* until(store.load(sessionKey)); - if (record === undefined) { + if (record === undefined || record.sessionMaterialization?.state === "pending") { return; } if (record.agentSessionId === nativeSessionId) { @@ -2505,20 +2708,14 @@ function* useAcpxProviderState( } /** - * Observe the build behind a session the provider names, and settle its route. + * Select the executable for a session the provider names, and settle its route. * - * The order is the contract. The build is observed before the route is read, - * because for this construction the build is part of what the route says: an - * identity the provider issues resolves to one conversation only beside the - * build that issued it, so a route published without one would describe a - * session no later run could confirm. What comes back is the build every - * provider effect for this session then goes through. - * - * A session that already has provider state but no route was constructed - * before this contract. Its route is published as the unbound one it is — - * this run's observation says which build is installed today, not which one - * issued that identity — and it refuses here rather than being bound after - * the fact. + * The route is published or adopted while ownership is held and before ACP is + * asked for anything. A fresh route records the current observation as its + * history when there is a complete one, and the unbound form when there is + * not; an existing route is never rewritten, and a version it records is + * compared with today's only to warn. Whether the conversation continues is + * the provider's live confirmation of its identity, never this comparison. */ function* bindProviderNamed( agentName: string, @@ -2526,10 +2723,10 @@ function* useAcpxProviderState( routeCommand: string, adapter: BoundProviderReturnedAdapter, sessionKey: string, + placement: string, hasProviderState: boolean, - verifyChangedBuild = false, ): Operation { - const build = yield* observeBuild(agentName, agentCommand, adapter.binding); + const build = yield* selectBuild(agentName, agentCommand, adapter.binding); let route: AgentSessionRoute; try { route = yield* reconcileRoute( @@ -2537,7 +2734,9 @@ function* useAcpxProviderState( sessionKey, // deno-lint-ignore require-yield function* () { - return boundAcpFirstRoute(routeCommand, sessionKey, build.binding); + return build.binding === undefined + ? acpFirstRoute(routeCommand, sessionKey) + : boundAcpFirstRoute(routeCommand, sessionKey, build.binding); }, hasProviderState, ); @@ -2552,31 +2751,26 @@ function* useAcpxProviderState( `"${agentName}" names its own sessions, so neither account describes the other`, }); } - if (route.schema !== "session-route.v3") { - // Constructed before any build was recorded. A build observed now says - // which build is installed today, not which one issued this identity, so - // there is nothing to compare and nothing to continue. - throw new AttachmentRefused({ - class: "executable-binding-refused", - message: - `session "${sessionKey}" was constructed before XMD recorded which build issued its ` + - `identity, so this run cannot show it is talking to that build. Name a different ` + - `.`, - }); - } - if (!sameExecutableBuild(build.binding, route.executableBinding)) { - if (!verifyChangedBuild) { - throw new AttachmentRefused(buildDrift(sessionKey, route.executableBinding, build.binding)); - } - return { build, verifyReopening: true }; - } - return { build }; + yield* warnCompatibility(routeCommand, sessionKey, placement, historicalVersion(route), build); + return { + build, + ...("executableBinding" in route ? { history: route.executableBinding } : {}), + }; + } + + /** The version a route recorded as its own history, when it recorded one. */ + function historicalVersion(route: AgentSessionRoute | undefined): string | undefined { + return route !== undefined && "executableBinding" in route + ? route.executableBinding.reportedVersion + : undefined; } /** What a settled construction route lets one ACP operation do. */ interface SessionConstruction { - /** The observed build every provider effect for this session goes through. */ + /** The selected executable every provider effect for this session goes through. */ build: BoundBuild; + /** The executable observation the route recorded as its own history, if any. */ + history?: ExecutableBuildBindingV1; /** * The exact conversation ACP must open rather than create. * @@ -2585,7 +2779,6 @@ function* useAcpxProviderState( * a name supplied here would be XMD choosing one after the fact. */ resumeSessionId?: string; - verifyReopening?: boolean; } /** @@ -2593,65 +2786,68 @@ function* useAcpxProviderState( * may do with it. * * `` and `` are eager, so a session nobody constructed is - * constructed here — as `acp-first`, bound to the observed build when the - * adapter pins one — before ensure. A session a native process constructed is - * attached to — never converted, never republished — and only when this host - * has proven that capability for this adapter and can still show it is talking - * to the build that created it. + * constructed here — as `acp-first` — before ensure. A session a native + * process constructed is attached to — never converted, never republished — + * and only when this host has proven that capability for this adapter. + * + * Every supported adapter's executable is selected here, through the current + * environment, and observed once for its diagnostic. An agent this host + * serves over ACP alone keeps no route, and is selected the same way. */ function* constructRoute( agentName: string, prepared: Prepared, ): Operation { const adapter = adapterFor(agentName); - if (!ownable(agentName) || adapter === undefined) { + if (adapter === undefined || !bindsBuild(adapter)) { return undefined; } const agentCommand = agentCommandOf(prepared); // Where the route lives, which for a held conversation is where it was - // first built. The executable is still observed for today's command. + // first built. The executable is still selected for today's command. const routeCommand = ownerCommandOf(prepared); + const placement = placementOf(prepared); + if (!ownable(agentName)) { + const build = yield* selectBuild(agentName, agentCommand, adapter.binding); + yield* warnCompatibility(routeCommand, prepared.sessionKey, placement, undefined, build); + return { build }; + } // An existing managed entry, or a durable record ACPX already kept, is // provider state — and existing history is never reclassified. const constructed = prepared.kind === "existing" || (yield* until(store.load(prepared.sessionKey))) !== undefined; if (!allocatesIdentity(adapter)) { - if (!bindsBuild(adapter)) { - return undefined; - } return yield* bindProviderNamed( agentName, agentCommand, routeCommand, adapter, prepared.sessionKey, + placement, constructed, - agentName === "codex" && prepared.kind === "details" && prepared.continuation !== undefined, ); } + const build = yield* selectBuild(agentName, agentCommand, adapter.binding); const route = yield* reconcileRoute( routeCommand, prepared.sessionKey, // deno-lint-ignore require-yield function* () { - return acpFirstRoute(routeCommand, prepared.sessionKey); + return build.binding === undefined + ? acpFirstRoute(routeCommand, prepared.sessionKey) + : boundAcpFirstRoute(routeCommand, prepared.sessionKey, build.binding); }, constructed, ); if (route.route !== "client-native") { - return undefined; - } - if (route.schema === "session-route.v1") { - // Constructed before any build was recorded. A build observed now says - // which build is installed today, not which one established this - // conversation, so there is nothing to compare and nothing to attach to. - throw new AttachmentRefused({ - class: "executable-binding-refused", - message: - `session "${prepared.sessionKey}" was constructed with a client-allocated identity ` + - `before XMD recorded which build accepted it, so this run cannot show it is talking ` + - `to that build. Continue it with , or name a different .`, - }); + yield* warnCompatibility( + routeCommand, + prepared.sessionKey, + placement, + historicalVersion(route), + build, + ); + return { build }; } if (!attachable(agentName)) { throw new AttachmentRefused({ @@ -2662,16 +2858,22 @@ function* useAcpxProviderState( `.`, }); } - const build = yield* observeBuild(agentName, agentCommand, adapter.binding); - if (!sameExecutableBuild(build.binding, route.executableBinding)) { - throw new AttachmentRefused( - buildDrift(prepared.sessionKey, route.executableBinding, build.binding), - ); - } yield* retainedAssertion(prepared.sessionKey, route.nativeSessionId); + yield* warnCompatibility( + routeCommand, + prepared.sessionKey, + placement, + historicalVersion(route), + build, + ); return { build, resumeSessionId: route.nativeSessionId }; } + /** The directory a session's placement resolved to. */ + function placementOf(prepared: Prepared): string { + return prepared.kind === "existing" ? prepared.entry.cwd : prepared.details.cwd; + } + /** * The prepared instructions, in a file only this invocation can read. * @@ -3186,9 +3388,7 @@ function* useAcpxProviderState( const constructing = state === "new" && resumeSessionId === undefined && prepared.kind === "details"; const entry = yield* ensureFromPrepared(agentName, prepared, { - ...(construction === undefined - ? {} - : { build: construction.build, verifyReopening: construction.verifyReopening }), + ...(construction === undefined ? {} : { build: construction.build }), ...(resumeSessionId === undefined ? {} : { attachment: { resumeSessionId } }), state, ...modelRequest(desired), @@ -3281,7 +3481,7 @@ function* useAcpxProviderState( requestId, host: promptUsageHost, ...adapterUsageBuild(agentName, agentCommandOf(prepared)), - ...(construction?.build === undefined + ...(construction?.build.binding === undefined ? {} : { native: { @@ -3501,40 +3701,61 @@ function* useAcpxProviderState( ); } - // A legacy route: constructed before XMD recorded which build accepted the - // identity. Native resume is exactly what that contract released, so it - // continues on it — under the launcher name, with no build observed, and - // with nothing written into the record it never had. - if (route?.route === "client-native" && route.schema === "session-route.v1") { - invocation.fresh.set(sessionKey, false); - return retained(agentName, adapter, route, instructions, sessionCwd, "resumed"); + // Confirmation is what lets a client-native session be handed over at + // all: an established one is confirmed before its native resume and a new + // one after its native creation, both by loading its exact identity over + // ACP. A host that has not proven that attachment refuses here, before an + // identity is allocated, a file is written or a child starts — an exit + // status is not a confirmation. + if (!attachable(agentName)) { + return refusal( + "unsupported-capability", + `agent "${agentName}" is not advertised as able to attach to the session its native ` + + `process constructs, so the conversation this launch would hand over cannot be ` + + `confirmed.`, + known, + ); } - // Observed before an identity exists, so a build this run cannot name stops - // the launch before anything durable is written. + // Selected before an identity exists, so an executable that cannot run + // stops the launch before anything durable is written. Its observation is + // diagnostic and never decides whether the session continues. let build: BoundBuild; try { - build = yield* observeBuild(agentName, agentCommand, adapter.binding); + build = yield* selectBuild(agentName, agentCommand, adapter.binding); } catch (error) { if (error instanceof AttachmentRefused) { return refusal(error.failure.class, error.failure.message, known); } throw error; } - if ( - route?.route === "client-native" && - !sameExecutableBuild(build.binding, route.executableBinding) - ) { - const drift = buildDrift(sessionKey, route.executableBinding, build.binding); - return refusal(drift.class, drift.message, known); - } // A session that already has an identity is resumed under it, and nothing // is allocated at all: a second candidate for a conversation that already - // exists is a value with nowhere to go. + // exists is a value with nowhere to go. A route recorded before XMD kept + // executable history resumes the same way, with nothing written into it. if (route?.route === "client-native") { + yield* warnCompatibility( + agentCommand, + sessionKey, + sessionCwd, + historicalVersion(route), + build, + ); invocation.fresh.set(sessionKey, false); invocation.bound.set(sessionKey, { build, adapter }); + const confirmed = yield* confirmClientNative( + invocation, + agentName, + agentCommand, + sessionKey, + sessionCwd, + route.nativeSessionId, + build, + ); + if (confirmed !== undefined) { + return refusal(confirmed.class, confirmed.message, known); + } return retained(agentName, adapter, route, instructions, sessionCwd, "resumed"); } @@ -3545,21 +3766,36 @@ function* useAcpxProviderState( // Publish or adopt: a caller meeting a compatible existing route takes its // retained identity rather than insisting its own candidate win, because - // the first durable publication is authoritative. + // the first durable publication is authoritative. The current observation + // is recorded as this session's history when there is a complete one. let winner: AgentSessionRoute; try { - winner = yield* routeStore!.publish({ - schema: "session-route.v2", - route: "client-native", - provider: ACPX_PROVIDER, - agent: agentCommand, - sessionKey, - nativeSessionId: candidate, - identityProvenance: "client-allocated", - instructionsDigest, - launcher: adapter.launcher, - executableBinding: build.binding, - }); + winner = yield* routeStore!.publish( + build.binding === undefined + ? { + schema: "session-route.v1", + route: "client-native", + provider: ACPX_PROVIDER, + agent: agentCommand, + sessionKey, + nativeSessionId: candidate, + identityProvenance: "client-allocated", + instructionsDigest, + launcher: adapter.launcher, + } + : { + schema: "session-route.v2", + route: "client-native", + provider: ACPX_PROVIDER, + agent: agentCommand, + sessionKey, + nativeSessionId: candidate, + identityProvenance: "client-allocated", + instructionsDigest, + launcher: adapter.launcher, + executableBinding: build.binding, + }, + ); } catch (error) { return refusal("identity-unavailable", routeMessage(error), known); } @@ -3579,17 +3815,6 @@ function* useAcpxProviderState( known, ); } - // A concurrent winner published before any build was recorded is legacy - // state, and this launch adopts it as one rather than treating its own - // observation as that session's history. - if (winner.schema === "session-route.v1") { - invocation.fresh.set(sessionKey, false); - return retained(agentName, adapter, winner, instructions, sessionCwd, "resumed"); - } - if (!sameExecutableBuild(winner.executableBinding, build.binding)) { - const drift = buildDrift(sessionKey, winner.executableBinding, build.binding); - return refusal(drift.class, drift.message, known); - } // The record is built from the winner rather than from the candidate, so // the two accounts agree by construction rather than by comparison. Losing @@ -3597,6 +3822,27 @@ function* useAcpxProviderState( const fresh = winner.nativeSessionId === candidate; invocation.fresh.set(sessionKey, fresh); invocation.bound.set(sessionKey, { build, adapter }); + yield* warnCompatibility( + agentCommand, + sessionKey, + sessionCwd, + historicalVersion(winner), + build, + ); + if (!fresh) { + const confirmed = yield* confirmClientNative( + invocation, + agentName, + agentCommand, + sessionKey, + sessionCwd, + winner.nativeSessionId, + build, + ); + if (confirmed !== undefined) { + return refusal(confirmed.class, confirmed.message, known); + } + } void prepared; return retained( agentName, @@ -3755,14 +4001,16 @@ function* useAcpxProviderState( // observed, the route recording it is published or adopted, and the two are // compared, all under ownership and before the first provider effect. let build: BoundBuild | undefined; + let history: ExecutableBuildBindingV1 | undefined; if (bindsBuild(adapter)) { try { - ({ build } = yield* bindProviderNamed( + ({ build, history } = yield* bindProviderNamed( agentName, agentCommand, agentCommand, adapter, sessionKey, + sessionCwd, existing !== undefined, )); } catch (error) { @@ -3773,11 +4021,25 @@ function* useAcpxProviderState( } invocation.bound.set(sessionKey, { build, adapter }); // The check a replay performs at its own first live phase, performed here - // against a live observation. Recording it is what keeps the detach or the - // spawn below from reading the same two accounts a second time. + // under ownership. Recording it is what keeps the detach or the spawn + // below from reading the same two accounts a second time. invocation.reconciled.add(sessionKey); } + // An established conversation is reopened under the provider's live + // confirmation of the identity it already asserts, before anything is + // configured or handed over. One without a retained assertion cannot be + // confirmed, and nothing is loaded in its place. + const expected = existing?.agentSessionId; + if (existing !== undefined && expected === undefined) { + return refusal( + "identity-unavailable", + `session "${sessionKey}" has no retained native identity, so the provider cannot ` + + `confirm it is reopening the same conversation`, + known, + ); + } + // Planned before the ensure it decides the shape of, and only for the // conversation this launch creates through an adapter that says one is // owed. A resumed session has already been spoken in — whatever made it @@ -3800,6 +4062,9 @@ function* useAcpxProviderState( mode: "persistent", cwd: sessionCwd, sessionOptions: { systemPrompt: instructions }, + ...(existing === undefined || expected === undefined + ? {} + : { resumeSessionId: existing.acpSessionId, expectedAgentSessionId: expected }), }; if (plan !== undefined) { // A conversation this adapter cannot open until something has been said @@ -3815,28 +4080,56 @@ function* useAcpxProviderState( // the moment it exists, bound to the runtime that made it: everything below // can refuse, and a handle only the managed map knew about is one teardown // could not close through its creator. - const managedEntry = yield* ensureThrough(build, ensureInput, (handle, entry) => { - const session: Session = { sessionKey, cwd: sessionCwd }; - if (handle.agentSessionId !== undefined) { - session.agentSessionId = handle.agentSessionId; - } - if (plan === undefined) { - publishSessionIdentity(session, { agentSessionId: handle.agentSessionId }); + let managedEntry: ManagedSession; + try { + managedEntry = yield* ensureThrough(build, ensureInput, (handle, entry) => { + const session: Session = { sessionKey, cwd: sessionCwd }; + if (handle.agentSessionId !== undefined) { + session.agentSessionId = handle.agentSessionId; + } + if (plan === undefined) { + publishSessionIdentity(session, { agentSessionId: handle.agentSessionId }); + } + // Established by construction when nothing is owed: this adapter's + // provider returns the identity, so the session exists the moment the + // ensure answers. A launch that owes a turn holds pending details instead, + // and the accepted turn is what establishes it. + return { + handle, + runtime: entry, + agentCommand, + cwd: sessionCwd, + session, + state: plan === undefined ? "existing" : "new", + }; + }); + } catch (error) { + if (existing === undefined) { + throw error; } - // Established by construction when nothing is owed: this adapter's - // provider returns the identity, so the session exists the moment the - // ensure answers. A launch that owes a turn holds pending details instead, - // and the accepted turn is what establishes it. - return { - handle, - runtime: entry, - agentCommand, - cwd: sessionCwd, - session, - state: plan === undefined ? "existing" : "new", - }; - }); + return refusal( + "identity-unavailable", + nativeIdentityRefusal(error)?.message ?? + `session "${sessionKey}" names a conversation this provider could not reopen, so ` + + `there is nothing here to hand over`, + known, + ); + } managed.set(sessionKey, managedEntry); + if (expected !== undefined && managedEntry.handle.agentSessionId !== expected) { + yield* releaseHandle(sessionKey); + return refusal( + "identity-unavailable", + `session "${sessionKey}" reopened a different native conversation from the one it ` + + `names, so it is not handed over`, + known, + ); + } + // The live load confirmed an established conversation, and a creation + // that owes no turn asserted the conversation it made as it answered. + if (expected !== undefined || (plan === undefined && managedEntry.handle.agentSessionId)) { + invocation.confirmed.add(sessionKey); + } const nativeSessionId = plan === undefined ? managedEntry.handle.agentSessionId : ""; if (nativeSessionId === undefined) { @@ -3887,10 +4180,11 @@ function* useAcpxProviderState( permissionMode: providerOptions.permissionMode, launcher: adapter.launcher, }; - if (build) { - // Exactly the binding the route carries, so the journal and the route - // agree by construction rather than by comparison. - record.executableBinding = build.binding; + if (history !== undefined) { + // Exactly the history the route carries, so the journal and the route + // agree by construction rather than by comparison. Today's observation + // is never written as though it established this session. + record.executableBinding = history; } if (plan !== undefined) { record.materialization = plan; @@ -3944,7 +4238,7 @@ function* useAcpxProviderState( try { entry = yield* ensureFromPrepared(prepared.agent, resolved, { ...(bound === undefined ? {} : { build: bound.build }), - attachment: { resumeSessionId: prepared.nativeSessionId }, + ...(yield* retainedReach(prepared)), state: "existing", ...modelRequest(requested), }); @@ -3954,6 +4248,15 @@ function* useAcpxProviderState( } return { class: "configuration-refused", message: toError(error).message }; } + if (entry.handle.agentSessionId !== prepared.nativeSessionId) { + return { + class: "identity-unavailable", + message: + `session "${sessionKey}" reopened a different native conversation from the one ` + + `its launch prepared, so it is not configured or handed over`, + }; + } + invocation.confirmed.add(sessionKey); } try { yield* configureSession(prepared.agent, entry, requested); @@ -3965,6 +4268,179 @@ function* useAcpxProviderState( }); } + /** + * Positively confirm an identity XMD chose, over ACP, and give ACP up again. + * + * The exact native identity is loaded through the advertised attachment + * capability and the live assertion must name it. A record ACPX already + * holds is reopened strictly; with none, the exact load is checked against + * what it returned. Nothing is configured and no turn is sent. The handle is + * released before this answers, and a release that did not settle is a + * failure: nothing may hand the session to a native process while ACP may + * still be in it. + */ + function* confirmClientNative( + invocation: LaunchInvocation, + agentName: string, + agentCommand: string, + sessionKey: string, + sessionCwd: string, + nativeSessionId: string, + build: BoundBuild | undefined, + ): Operation { + if (!attachable(agentName)) { + return { + class: "unsupported-capability", + message: + `agent "${agentName}" is not advertised as able to attach to the session its native ` + + `process constructed, so the conversation cannot be confirmed`, + }; + } + const held = managed.get(sessionKey); + const failure = yield* scoped(function* (): Operation { + yield* ensure(() => releaseHandle(sessionKey)); + if (held !== undefined && isLive(held)) { + // Already attached by the operation that holds it, which confirmed it. + return held.handle.agentSessionId === nativeSessionId + ? undefined + : { + class: "identity-unavailable", + message: + `session "${sessionKey}" is held under a different native conversation than ` + + `the one it was constructed as`, + }; + } + const resolved: Prepared = { + kind: "details", + sessionKey, + agentCommand, + details: { sessionKey, cwd: sessionCwd, state: "existing" }, + ...(held === undefined ? {} : { issued: held.session }), + }; + try { + yield* ensureFromPrepared(agentName, resolved, { + ...(build === undefined ? {} : { build }), + attachment: { resumeSessionId: nativeSessionId }, + state: "existing", + }); + } catch (error) { + if (error instanceof AttachmentRefused) { + return error.failure; + } + return ( + nativeIdentityRefusal(error)?.failure ?? { + class: "identity-unavailable", + message: + `session "${sessionKey}" names a conversation this provider could not open, so ` + + `there is nothing here to confirm`, + } + ); + } + return undefined; + }); + if (failure !== undefined) { + return failure; + } + if (holding(sessionKey)) { + return { + class: "detach-failed", + message: + `session "${sessionKey}" could not be released after its identity was confirmed, so ` + + `it is not handed to a native process`, + }; + } + invocation.confirmed.add(sessionKey); + return undefined; + } + + /** + * Confirm a retained launch's conversation before its native resume. + * + * Reached at a replay's first live phase, or for an established session + * whose preparation did not already confirm it. A provider-named session is + * reopened by its record under the retained assertion; an identity XMD chose + * is attached to by name. Either is released before the native process is + * started. + */ + function* confirmRetained( + invocation: LaunchInvocation, + prepared: PreparedLaunchRecord, + agentCommand: string, + ): Operation { + const sessionKey = prepared.sessionKey; + if (invocation.confirmed.has(sessionKey)) { + return undefined; + } + const build = invocation.bound.get(sessionKey)?.build; + if (prepared.identityProvenance === "client-allocated") { + return yield* confirmClientNative( + invocation, + prepared.agent, + agentCommand, + sessionKey, + prepared.cwd, + prepared.nativeSessionId, + build, + ); + } + const held = managed.get(sessionKey); + const failure = yield* scoped(function* (): Operation { + yield* ensure(() => releaseHandle(sessionKey)); + let entry: ManagedSession; + if (held !== undefined && isLive(held)) { + entry = held; + } else { + const resolved: Prepared = { + kind: "details", + sessionKey, + agentCommand, + details: { sessionKey, cwd: prepared.cwd, state: "existing" }, + ...(held === undefined ? {} : { issued: held.session }), + }; + try { + entry = yield* ensureFromPrepared(prepared.agent, resolved, { + ...(build === undefined ? {} : { build }), + ...(yield* retainedReach(prepared)), + state: "existing", + }); + } catch (error) { + return ( + nativeIdentityRefusal(error)?.failure ?? + (error instanceof AttachmentRefused + ? error.failure + : { + class: "identity-unavailable", + message: + `session "${sessionKey}" names a conversation this provider could not ` + + `reopen, so there is nothing here to hand over`, + }) + ); + } + } + return entry.handle.agentSessionId === prepared.nativeSessionId + ? undefined + : { + class: "identity-unavailable", + message: + `session "${sessionKey}" reopened a different native conversation from the one ` + + `its launch prepared, so it is not handed over`, + }; + }); + if (failure !== undefined) { + return failure; + } + if (holding(sessionKey)) { + return { + class: "detach-failed", + message: + `session "${sessionKey}" could not be released after its identity was confirmed, so ` + + `it is not handed to a native process`, + }; + } + invocation.confirmed.add(sessionKey); + return undefined; + } + /** * What the provider said this turn cost, and nothing else. * @@ -4048,6 +4524,7 @@ function* useAcpxProviderState( * nothing else. */ function materializeSession( + invocation: LaunchInvocation, resolved: Prepared, prepared: PreparedLaunchRecord, plan: MaterializationPlan, @@ -4262,6 +4739,9 @@ function* useAcpxProviderState( entry.session.agentSessionId = nativeSessionId; publishSessionIdentity(entry.session, identity); entry.state = "existing"; + // The backend's own acceptance named this conversation, which is the + // positive assertion the handoff that follows needs. + invocation.confirmed.add(prepared.sessionKey); yield* notifyTerminal( `${prepared.agent}: materialization turn completed in ${durationMs}ms ` + @@ -4409,6 +4889,7 @@ function* useAcpxProviderState( detachedLive: new Set(), reconciled: new Set(), configured: new Set(), + confirmed: new Set(), }; try { @@ -4438,7 +4919,8 @@ function* useAcpxProviderState( routed.configuration, ), ), - materialize: (prepared, plan) => materializeSession(resolved, prepared, plan), + materialize: (prepared, plan) => + materializeSession(invocation, resolved, prepared, plan), detach: (prepared) => detachSession(invocation, prepared, agentCommandOf(resolved)), exit: (prepared) => runNativeUi(invocation, prepared, agentCommandOf(resolved)), }); @@ -4483,7 +4965,7 @@ function* useAcpxProviderState( prepared: PreparedLaunchRecord, adapter: NativeAdapter, agentCommand: string, - ): Operation> { + ): Operation> { const publishedHere = invocation.fresh.get(prepared.sessionKey); if (publishedHere === undefined && bindsBuild(adapter)) { // A replay. Whichever suffix it holds, the two durable accounts are @@ -4498,11 +4980,11 @@ function* useAcpxProviderState( // Creation is a question only for an identity XMD chose. A session the // provider named already exists — ACP made it — so there is nothing here to // create and no instruction layer to install through argv. - let argv: string[]; - if ( + const creating = allocatesIdentity(adapter) && - (publishedHere ?? invocation.detachedLive.has(prepared.sessionKey)) - ) { + (publishedHere ?? invocation.detachedLive.has(prepared.sessionKey)); + let argv: string[]; + if (creating) { argv = adapter.create( prepared.nativeSessionId, yield* privateInstructionFile(prepared.instructions), @@ -4510,12 +4992,15 @@ function* useAcpxProviderState( } else { argv = adapter.resume(prepared.nativeSessionId); } - // The exact file this run observed, in place of the launcher name the - // adapter writes. The name is what durable records carry; the path is what - // this invocation spawns, and it is live only. A legacy session observed no - // build, so it keeps the released behavior and runs the name. - const observed = invocation.bound.get(prepared.sessionKey); - return Ok(observed ? [observed.build.livePath, ...argv.slice(1)] : argv); + // The exact file the current environment selected, in place of the + // launcher name the adapter writes. The name is what durable records carry; + // the path is what this invocation spawns, and it is live only. A custom + // command whose backend was not selected here runs the launcher name. + const livePath = invocation.bound.get(prepared.sessionKey)?.build.livePath; + return Ok({ + argv: livePath === undefined ? argv : [livePath, ...argv.slice(1)], + creating, + }); } /** Check a retained launch against its route once per invocation. */ @@ -4539,10 +5024,13 @@ function* useAcpxProviderState( * Check a retained launch against the route before resuming or creating. * * Two durable accounts of this session already exist — the journal's and the - * route's — and a replay may act only if they still agree. Neither account - * repairs the other and neither is republished: a replay that found a - * disagreement has discovered that the session it was going to continue is - * not the session it prepared. + * route's — and a replay may act only if they still agree about what the + * session is: its identity, who chose it, its instructions, its launcher and + * its provider. Neither account repairs the other and neither is + * republished. Historical executable observations are compared only where + * both accounts kept one; a missing observation is not a disagreement, and + * today's executable is never compared with either. Whether the + * conversation continues is its live confirmation, which follows. */ function* reconcileRetainedLaunch( invocation: LaunchInvocation, @@ -4555,16 +5043,6 @@ function* useAcpxProviderState( `session "${prepared.sessionKey}" is described differently by its journal and its ` + `construction route, and neither account repairs the other`, ); - // A launch that never got as far as the native process, prepared under a - // contract that recorded no build. Nothing here can show which build has - // this session's history, and resuming anyway would be answering the - // question by ignoring it. A completed launch never reaches this code. - const unrecorded = (): LaunchFailure => ({ - class: "executable-binding-refused", - message: - `session "${prepared.sessionKey}" was prepared before XMD recorded which build its ` + - `identity belongs to, so this run cannot confirm the conversation it names`, - }); // Which provider retained this preparation, before anything is compared // against it. A record another provider wrote describes a session this one // does not own, and an ACPX route that happens to agree about a UUID is not @@ -4580,13 +5058,11 @@ function* useAcpxProviderState( // agreeing with a record about one string is not evidence that the same side // named the session both times. const adapter = adapterFor(prepared.agent); - if (!adapter || !bindsBuild(adapter)) { - return { - class: "executable-binding-refused", - message: - `session "${prepared.sessionKey}" names a launcher this build has no way to observe, ` + - `so the conversation it prepared cannot be confirmed`, - }; + if (!adapter) { + return stop( + `session "${prepared.sessionKey}" names a launcher this build does not know, so the ` + + `conversation it prepared cannot be confirmed`, + ); } let route; try { @@ -4594,7 +5070,6 @@ function* useAcpxProviderState( } catch (error) { return stop(routeMessage(error)); } - let retainedBinding: ExecutableBuildBindingV1; if (allocatesIdentity(adapter)) { if (!route || route.route !== "client-native") { return stop( @@ -4610,10 +5085,6 @@ function* useAcpxProviderState( ) { return disagree(); } - if (route.schema === "session-route.v1") { - return unrecorded(); - } - retainedBinding = route.executableBinding; } else { if (!route || route.route !== "acp-first") { return stop( @@ -4621,10 +5092,9 @@ function* useAcpxProviderState( `conversation this launch prepared cannot be confirmed`, ); } - if (route.schema !== "session-route.v3") { - return unrecorded(); + if (prepared.identityProvenance !== "provider-returned") { + return disagree(); } - retainedBinding = route.executableBinding; // ACPX's own record, which is what any later ACP operation would reopen // this session through. A record naming another conversation, or none, // means the identity the native process is about to be handed is not the @@ -4638,25 +5108,35 @@ function* useAcpxProviderState( throw error; } } - if (prepared.executableBinding === undefined) { - return unrecorded(); - } - if (!sameExecutableBuild(retainedBinding, prepared.executableBinding)) { + const routeBinding = "executableBinding" in route ? route.executableBinding : undefined; + if ( + routeBinding !== undefined && + prepared.executableBinding !== undefined && + !sameExecutableBuild(routeBinding, prepared.executableBinding) + ) { return disagree(); } - // The live half, before the first effect a native process could act on. + if (!bindsBuild(adapter)) { + return undefined; + } + // The live half: the executable the current environment selects, before + // the first effect a native process could act on. let build: BoundBuild; try { - build = yield* observeBuild(prepared.agent, agentCommand, adapter.binding); + build = yield* selectBuild(prepared.agent, agentCommand, adapter.binding); } catch (error) { if (error instanceof AttachmentRefused) { return error.failure; } throw error; } - if (!sameExecutableBuild(build.binding, retainedBinding)) { - return buildDrift(prepared.sessionKey, retainedBinding, build.binding); - } + yield* warnCompatibility( + agentCommand, + prepared.sessionKey, + prepared.cwd, + routeBinding?.reportedVersion ?? prepared.executableBinding?.reportedVersion, + build, + ); invocation.bound.set(prepared.sessionKey, { build, adapter }); return undefined; } @@ -4679,18 +5159,18 @@ function* useAcpxProviderState( } // The two durable accounts first, because reattaching to configure is // already acting on the session: a replay that reopened a conversation, put - // a model into force in it and only then discovered its route or its build - // had drifted would have written to a session it could not confirm. This - // also settles which build the reattachment goes through, and it runs once - // per invocation — a prepared-only replay checked them at its own first - // live phase, and a launch that prepared live checked them there. + // a model into force in it and only then discovered its accounts disagree + // would have written to a session it could not confirm. This also selects + // the executable the reattachment goes through, and it runs once per + // invocation — a prepared-only replay checked them at its own first live + // phase, and a launch that prepared live checked them there. if (invocation.fresh.get(prepared.sessionKey) === undefined && bindsBuild(adapter)) { let unconfirmed: LaunchFailure | undefined; try { unconfirmed = yield* reconcile(invocation, prepared, agentCommand); } catch { // Everything this check reaches for is private: a route store on a real - // filesystem, an executable this run observes, an adapter's own code. + // filesystem, an executable this run selects, an adapter's own code. // A settled refusal comes back as one and keeps its class; anything // raised says nothing that may be repeated. return { phase: "exited", failure: privateFailure() }; @@ -4707,7 +5187,7 @@ function* useAcpxProviderState( if (unconfigured) { return { phase: "exited", failure: unconfigured }; } - let resolved: Result; + let resolved: Result<{ argv: string[]; creating: boolean }>; try { resolved = yield* nativeCommand(invocation, prepared, adapter, agentCommand); } catch { @@ -4723,23 +5203,73 @@ function* useAcpxProviderState( resolved.error instanceof RetainedRefusal ? resolved.error.failure : privateFailure(); return { phase: "exited", failure }; } - const command = resolved.value; + const { argv: command, creating } = resolved.value; + // A resume is handed only a conversation the provider has just confirmed + // by its exact identity, with ACP released and joined. A creation has no + // conversation to confirm yet; it is confirmed once the native process + // that made it has exited. + if (!creating) { + let unconfirmed: LaunchFailure | undefined; + try { + unconfirmed = yield* confirmRetained(invocation, prepared, agentCommand); + } catch { + return { phase: "exited", failure: privateFailure() }; + } + if (unconfirmed) { + return { phase: "exited", failure: unconfirmed }; + } + } + if (holding(prepared.sessionKey)) { + return { + phase: "exited", + failure: { + class: "detach-failed", + message: + `session "${prepared.sessionKey}" is still held through ACP, so it is not handed ` + + `to a native process`, + }, + }; + } + let exited: ExitedLaunchRecord; try { const outcome = yield* nativeLaunch({ command, cwd: prepared.cwd }); - const exited: ExitedLaunchRecord = { phase: "exited" }; + exited = { phase: "exited" }; if (outcome.exitCode !== undefined) { exited.exitCode = outcome.exitCode; } if (outcome.signal !== undefined) { exited.signal = outcome.signal; } - return exited; } catch { // Normalized: everything this boundary knows — the argv, the private // file's path, the host's own message about a file nobody else can see — // is what a durable record must not carry. return { phase: "exited", failure: privateFailure() }; } + if (creating) { + // The native child has exited and been reaped. Its exit status says how + // the process ended, never which conversation it made, so the allocated + // identity is loaded over ACP and must be asserted before this launch + // reports success. A refusal fails this launch; nothing is created again. + let unconfirmed: LaunchFailure | undefined; + try { + unconfirmed = yield* confirmClientNative( + invocation, + prepared.agent, + agentCommand, + prepared.sessionKey, + prepared.cwd, + prepared.nativeSessionId, + invocation.bound.get(prepared.sessionKey)?.build, + ); + } catch { + unconfirmed = privateFailure(); + } + if (unconfirmed) { + exited.failure = unconfirmed; + } + } + return exited; } /** The retained refusal an ownership failure becomes, if it is one. */ @@ -4949,9 +5479,7 @@ function* useAcpxProviderState( // second owner of a session a native UI may take. yield* ensure(() => releaseHandle(prepared.sessionKey)); const entry = yield* ensureFromPrepared(agentName, prepared, { - ...(construction === undefined - ? {} - : { build: construction.build, verifyReopening: construction.verifyReopening }), + ...(construction === undefined ? {} : { build: construction.build }), ...(resumeSessionId === undefined ? {} : { attachment: { resumeSessionId } }), state, ...(selectedAgent === undefined @@ -5065,6 +5593,21 @@ function* useAcpxProviderState( }; } +/** How a compatibility warning names the product behind an agent. */ +function productName(agentName: string): string { + return agentName === "codex" ? "Codex" : agentName === "claude" ? "Claude" : agentName; +} + +/** + * The product version a canonical reported version names. + * + * `codex-cli 0.153.2` and `2.1.241 (Claude Code)` are retained whole so two + * products never compare equal; a reader is told the release number. + */ +function productVersion(reported: string): string { + return /\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?/.exec(reported)?.[0] ?? reported; +} + function nativeIdentityRefusal(error: unknown): AttachmentRefused | undefined { if ( error instanceof Error && diff --git a/packages/acp/tests/certification-fixture.ts b/packages/acp/tests/certification-fixture.ts index 98b99734f..e11be8067 100644 --- a/packages/acp/tests/certification-fixture.ts +++ b/packages/acp/tests/certification-fixture.ts @@ -63,7 +63,7 @@ function answer(request) { if (mode === "standard-wait") { update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:"WAITING"}}); } return; } - const value=seed !== undefined ? "READY" : mode === "lost" ? "WRONG" : marker ?? "UNKNOWN"; + const value=seed !== undefined ? "READY" : mode.endsWith("lost") ? "WRONG" : marker ?? "UNKNOWN"; update({sessionUpdate:"agent_message_chunk",content:{type:"text",text:value}}); reply(id,{stopReason:"end_turn"}); }; diff --git a/packages/acp/tests/fixtures/claude-native-launch-proof.ts b/packages/acp/tests/fixtures/claude-native-launch-proof.ts index 3f5bd45fa..f3008035e 100644 --- a/packages/acp/tests/fixtures/claude-native-launch-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-launch-proof.ts @@ -58,9 +58,6 @@ const AUTHORIZED_TURNS = "2"; /** The production target, exactly as an operator would type it. */ const TARGET = "AGENTS.md#Implementor"; -/** The compatibility point these journeys are only meaningful against. */ -const REQUIRED_CLAUDE_VERSION = "2.1.241 (Claude Code)"; - /** * The role contract's opening sentence. * @@ -1501,12 +1498,9 @@ function* ready(journey: Journey, verdict: JourneyVerdict): Operation { verdict.detail = "no installed claude executable was found on PATH"; return false; } + // Recorded as evidence of what ran. A release absent from earlier evidence is + // what an opt-in regression exists to exercise, so it never blocks the run. verdict.claudeVersion = yield* claudeVersion(journey); - if (verdict.claudeVersion !== REQUIRED_CLAUDE_VERSION) { - verdict.verdict = "ENVIRONMENT_BLOCKED"; - verdict.detail = `this journey is only meaningful against ${REQUIRED_CLAUDE_VERSION}`; - return false; - } if (!verdict.projectCopyVerified) { verdict.verdict = "HARNESS_FAILED"; verdict.detail = "the project copy is not byte-identical to the checked-in role document"; @@ -1831,9 +1825,7 @@ function* runPreflight(): Operation { verdict.binaryBuilt = yield* exists(XMD_BINARY); const established = - verdict.claudeVersion === REQUIRED_CLAUDE_VERSION && - verdict.platform === "darwin" && - verdict.architecture === "arm64" && + verdict.claudeVersion.length > 0 && !verdict.claudeConfigDirSet && verdict.sessionIdFlag && verdict.systemPromptFileFlag && diff --git a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts index f70e6656d..d8b28e15e 100644 --- a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts @@ -1793,7 +1793,7 @@ function refusalClass(output: string): string { if (output.includes("could not open")) { return "identity-unavailable"; } - if (output.includes("before XMD recorded which build") || output.includes("would use")) { + if (output.includes("is unavailable")) { return "executable-binding-refused"; } return ""; diff --git a/packages/acp/tests/fixtures/codex-native-launch-proof.ts b/packages/acp/tests/fixtures/codex-native-launch-proof.ts index e3cf04a0b..060af68ae 100644 --- a/packages/acp/tests/fixtures/codex-native-launch-proof.ts +++ b/packages/acp/tests/fixtures/codex-native-launch-proof.ts @@ -88,17 +88,14 @@ const TARGET = "AGENTS.md#Implementor"; const ACP_DOCUMENT = fileURLToPath(new URL("./codex-native-to-acp-prompt.md", import.meta.url)); /** - * The compatibility point these journeys are only meaningful against - * (`issue-755-codex-materialization-turn-implementor-handoff.md`). + * The carried adapter these journeys exercise. * - * Frozen rather than read from the machine, because the proof requires that one - * exact build was proven. A run against another build is not a weaker pass; it - * is a different question, and it says so. + * The adapter snapshot is part of XMD's own integration, so a change to it is a + * change these journeys are meant to catch. The installed Codex release, its + * digest and the host platform are recorded as evidence of what ran and never + * gate the run: a release absent from earlier evidence is exactly what an + * opt-in regression should be able to exercise (#891). */ -const REQUIRED_PLATFORM = "darwin"; -const REQUIRED_ARCHITECTURE = "arm64"; -const REQUIRED_CODEX_VERSION = "codex-cli 0.153.2"; -const REQUIRED_CODEX_DIGEST = "195ace4100a634a9df39147f493e730e666b5bd87795f3c9f3251d8542400424"; const REQUIRED_ADAPTER_PACKAGE = "@agentclientprotocol/codex-acp"; const REQUIRED_ADAPTER_VERSION = "1.6.2"; const REQUIRED_ADAPTER_DIGEST = "3ee22bc6b1649d02fcef80b352516f395fe774e63b459193195a41c42930dd8b"; @@ -1691,10 +1688,6 @@ function* ready(journey: Journey, verdict: JourneyVerdict): Operation { } recordAdapter(verdict); verdict.compatibilityTupleFrozen = - verdict.platform === REQUIRED_PLATFORM && - verdict.architecture === REQUIRED_ARCHITECTURE && - verdict.codexVersion === REQUIRED_CODEX_VERSION && - verdict.codexDigest === REQUIRED_CODEX_DIGEST && verdict.adapterPackage === REQUIRED_ADAPTER_PACKAGE && verdict.adapterVersion === REQUIRED_ADAPTER_VERSION && verdict.adapterDigest === REQUIRED_ADAPTER_DIGEST; @@ -2250,10 +2243,6 @@ function* runPreflight(): Operation { verdict.adapterVersion = snapshot?.version ?? ""; verdict.adapterDigest = snapshot?.sha256 ?? ""; verdict.compatibilityTupleFrozen = - verdict.platform === REQUIRED_PLATFORM && - verdict.architecture === REQUIRED_ARCHITECTURE && - verdict.codexVersion === REQUIRED_CODEX_VERSION && - verdict.codexDigest === REQUIRED_CODEX_DIGEST && verdict.adapterPackage === REQUIRED_ADAPTER_PACKAGE && verdict.adapterVersion === REQUIRED_ADAPTER_VERSION && verdict.adapterDigest === REQUIRED_ADAPTER_DIGEST; diff --git a/packages/acp/tests/helpers.ts b/packages/acp/tests/helpers.ts index 1c7a98f7c..88393e5ec 100644 --- a/packages/acp/tests/helpers.ts +++ b/packages/acp/tests/helpers.ts @@ -400,7 +400,7 @@ export function createFakeRuntime(): FakeRuntimeHarness { create(options) { const runtimeIndex = harness.createdOptions.length; harness.createdOptions.push(options); - return { + const runtime: ProbeCapableRuntime = { doctor() { harness.doctorCalls++; const report = harness.doctorReports.shift() ?? { @@ -413,214 +413,253 @@ export function createFakeRuntime(): FakeRuntimeHarness { if (harness.ensureFailure) { return Promise.reject(harness.ensureFailure); } - harness.activity?.("ensure"); - harness.ensureCalls.push(input); - harness.modelRequests.push(`ensure ${input.requestedModel ?? "-"}`); - const handleId = `${input.sessionKey}#${harness.handleIds.length}`; - harness.handleIds.push(handleId); - // Deferred materialization: the record occupies the key and asserts - // nothing, and the identity the adapter answered with is held here - // until the backend accepts a turn. - const deferred = input.materialization === "first-turn-acceptance"; - // ACPX persists a record as it establishes a session, including the - // instruction layer the caller asked for; a fake that skipped that - // would hide every decision a later launch makes by reading it back. - const record: AcpSessionRecord = { - ...makeRecord( - resolveAgentCommand(options.agentRegistry, input.agent), - input.cwd ?? options.cwd, - ), - acpxRecordId: input.sessionKey, - messages: [], - }; - // What the adapter says it opened. An exact resume of a record this fake - // already wrote answers with the conversation that record asserts, as - // ACPX does when it reuses or reloads its own record; any other exact - // resume answers with the conversation it was told to load, and - // `assertIdentity` is how a test makes it answer with another one. - const resumed = - input.resumeSessionId === undefined - ? undefined - : records.get(`record:${input.sessionKey}`); - const asserted = - harness.assertIdentity ?? - (resumed !== undefined && resumed.acpSessionId === input.resumeSessionId - ? resumed.agentSessionId - : undefined) ?? - input.resumeSessionId ?? - `agent-session:${input.sessionKey}`; - if (input.sessionOptions?.systemPrompt !== undefined) { - record.acpx = { session_options: { system_prompt: input.sessionOptions.systemPrompt } }; - } - const handle: AcpRuntimeHandle = { - sessionKey: input.sessionKey, - backend: "acpx", - runtimeSessionName: handleId, - cwd: input.cwd, - acpxRecordId: `record:${input.sessionKey}`, - backendSessionId: `backend:${input.sessionKey}`, - }; - if (deferred) { - record.sessionMaterialization = { - state: "pending", - contract: "executablemd.session-materialization/v1", - }; - withheld.set(handle.acpxRecordId!, harness.omitAgentSessionId ? undefined : asserted); - } else if (!harness.omitAgentSessionId) { - handle.agentSessionId = asserted; - record.agentSessionId = asserted; + // An exact resume of a record another runtime wrote is answered from + // that record, as ACPX loads it; one this fake wrote is in memory. + if (input.resumeSessionId !== undefined && !records.has(`record:${input.sessionKey}`)) { + return options.sessionStore + .load(input.sessionKey) + .then((stored) => establish(input, stored)); } - const answer = (): AcpRuntimeHandle => { - records.set(handle.acpxRecordId!, record); - void options.sessionStore.save(record); - return handle; - }; - // The gate runs on Effection and `run` bridges it to the acpx Promise - // boundary, the same way a manual turn's release does. - const gate = harness.ensureGate?.(input); - return gate ? run(() => gate).then(answer) : Promise.resolve(answer()); + return establish(input, undefined); }, startTurn(input) { - harness.modelRequests.push(`turn ${input.requestedModel ?? "-"}`); - harness.activity?.("turn"); - const script = scripted.shift() ?? {}; - const recordId = input.handle.acpxRecordId ?? input.handle.sessionKey; - const awaiting = withheld.has(recordId); - // A native promise rather than an Effection future: this is the acpx - // boundary, and a turn nobody accepts leaves it unsettled — which as a - // root task would be a pending operation the runner refuses to end on. - const materialized = promiseWithResolvers(); - // Observed here as the provider's own deferreds are: a test that only - // reads events must not turn an unaccepted turn into an unhandled - // rejection. - materialized.promise.catch(() => {}); - const events = script.events ?? DEFAULT_EVENTS; - const result: AcpRuntimeTurnResult = script.result ?? { - status: "completed", - stopReason: "end_turn", + return startTurn(input); + }, + runTurn(input) { + return startTurn(input).events; + }, + ...configuration(), + cancel() { + return Promise.resolve(); + }, + close(input) { + return close(input); + }, + }; + function establish( + input: AcpRuntimeEnsureInput, + stored: AcpSessionRecord | undefined, + ): Promise { + harness.activity?.("ensure"); + harness.ensureCalls.push(input); + harness.modelRequests.push(`ensure ${input.requestedModel ?? "-"}`); + const handleId = `${input.sessionKey}#${harness.handleIds.length}`; + harness.handleIds.push(handleId); + // Deferred materialization: the record occupies the key and asserts + // nothing, and the identity the adapter answered with is held here + // until the backend accepts a turn. + const deferred = input.materialization === "first-turn-acceptance"; + // ACPX persists a record as it establishes a session, including the + // instruction layer the caller asked for; a fake that skipped that + // would hide every decision a later launch makes by reading it back. + const record: AcpSessionRecord = { + ...makeRecord( + resolveAgentCommand(options.agentRegistry, input.agent), + input.cwd ?? options.cwd, + ), + acpxRecordId: input.sessionKey, + messages: [], + }; + // What the adapter says it opened. An exact resume of a record this fake + // already wrote answers with the conversation that record asserts, as + // ACPX does when it reuses or reloads its own record; any other exact + // resume answers with the conversation it was told to load, and + // `assertIdentity` is how a test makes it answer with another one. + const resumed = + input.resumeSessionId === undefined + ? undefined + : (records.get(`record:${input.sessionKey}`) ?? stored); + const asserted = + harness.assertIdentity ?? + (resumed !== undefined && resumed.acpSessionId === input.resumeSessionId + ? resumed.agentSessionId + : undefined) ?? + input.resumeSessionId ?? + `agent-session:${input.sessionKey}`; + if (input.sessionOptions?.systemPrompt !== undefined) { + record.acpx = { session_options: { system_prompt: input.sessionOptions.systemPrompt } }; + } + const handle: AcpRuntimeHandle = { + sessionKey: input.sessionKey, + backend: "acpx", + runtimeSessionName: handleId, + cwd: input.cwd, + acpxRecordId: `record:${input.sessionKey}`, + backendSessionId: `backend:${input.sessionKey}`, + }; + if (deferred) { + record.sessionMaterialization = { + state: "pending", + contract: "executablemd.session-materialization/v1", }; + withheld.set(handle.acpxRecordId!, harness.omitAgentSessionId ? undefined : asserted); + } else if (!harness.omitAgentSessionId) { + handle.agentSessionId = asserted; + record.agentSessionId = asserted; + } + // ACPX's verified reopen: the live load must assert the retained + // native identity, and a refusal leaves the record as it was. + const expected = input.expectedAgentSessionId; + const confirmed = expected === undefined || handle.agentSessionId === expected; + const answer = (): AcpRuntimeHandle => { + if (!confirmed) { + throw Object.assign( + new Error( + handle.agentSessionId === undefined + ? "The provider did not confirm the retained native conversation." + : "The provider reopened a different native conversation.", + ), + { detailCode: "NATIVE_SESSION_IDENTITY_UNAVAILABLE" }, + ); + } + records.set(handle.acpxRecordId!, record); + void options.sessionStore.save(record); + return handle; + }; + // The gate runs on Effection and `run` bridges it to the acpx Promise + // boundary, the same way a manual turn's release does. + const gate = harness.ensureGate?.(input); + return gate ? run(() => gate).then(answer) : Promise.resolve().then(answer); + } + function startTurn(input: AcpRuntimeTurnInput): AcpRuntimeTurn { + harness.modelRequests.push(`turn ${input.requestedModel ?? "-"}`); + harness.activity?.("turn"); + const script = scripted.shift() ?? {}; + const recordId = input.handle.acpxRecordId ?? input.handle.sessionKey; + const awaiting = withheld.has(recordId); + // A native promise rather than an Effection future: this is the acpx + // boundary, and a turn nobody accepts leaves it unsettled — which as a + // root task would be a pending operation the runner refuses to end on. + const materialized = promiseWithResolvers(); + // Observed here as the provider's own deferreds are: a test that only + // reads events must not turn an unaccepted turn into an unhandled + // rejection. + materialized.promise.catch(() => {}); + const events = script.events ?? DEFAULT_EVENTS; + const result: AcpRuntimeTurnResult = script.result ?? { + status: "completed", + stopReason: "end_turn", + }; - let pushEvents = events; - // Manual-turn timing runs on Effection Futures; `run` bridges them - // to the acpx async-iterable / Promise boundary. - const gate = withResolvers(); - const resultReady = withResolvers(); + let pushEvents = events; + // Manual-turn timing runs on Effection Futures; `run` bridges them + // to the acpx async-iterable / Promise boundary. + const gate = withResolvers(); + const resultReady = withResolvers(); - const promote = (): void => { - if (!withheld.has(recordId)) { - return; - } - const identity = withheld.get(recordId); - withheld.delete(recordId); - const stored = records.get(recordId); - if (stored) { - stored.sessionMaterialization = undefined; - if (identity !== undefined) { - stored.agentSessionId = identity; - } - void options.sessionStore.save(stored); + const promote = (): void => { + if (!withheld.has(recordId)) { + return; + } + const identity = withheld.get(recordId); + withheld.delete(recordId); + const stored = records.get(recordId); + if (stored) { + stored.sessionMaterialization = undefined; + if (identity !== undefined) { + stored.agentSessionId = identity; } - materialized.resolve({ - acpxRecordId: recordId, - ...(identity === undefined ? {} : { agentSessionId: identity }), - }); - }; - const refuse = (): void => { - materialized.reject(new Error("this session still awaits first-turn materialization")); - }; - const fake: FakeTurn = { - input, - cancelled: false, - accept: promote, - finish(finishEvents, finishResult) { - pushEvents = finishEvents; - gate.resolve(); - resultReady.resolve(finishResult); - // A turn that ends still awaiting acceptance never got it. - refuse(); - }, - turn: { - promptStarted: Promise.resolve(), - requestId: input.requestId, - events: { - [Symbol.asyncIterator](): AsyncIterator { - let index = 0; - let gateTask: Task | undefined; - const emit = (): IteratorResult => { - if (index < pushEvents.length) { - return { done: false, value: pushEvents[index++]! }; + void options.sessionStore.save(stored); + } + materialized.resolve({ + acpxRecordId: recordId, + ...(identity === undefined ? {} : { agentSessionId: identity }), + }); + }; + const refuse = (): void => { + materialized.reject(new Error("this session still awaits first-turn materialization")); + }; + const fake: FakeTurn = { + input, + cancelled: false, + accept: promote, + finish(finishEvents, finishResult) { + pushEvents = finishEvents; + gate.resolve(); + resultReady.resolve(finishResult); + // A turn that ends still awaiting acceptance never got it. + refuse(); + }, + turn: { + promptStarted: Promise.resolve(), + requestId: input.requestId, + events: { + [Symbol.asyncIterator](): AsyncIterator { + let index = 0; + let gateTask: Task | undefined; + const emit = (): IteratorResult => { + if (index < pushEvents.length) { + return { done: false, value: pushEvents[index++]! }; + } + return { done: true, value: undefined }; + }; + return { + next(): Promise> { + // A manual turn withholds its events until the release + // gate resolves; run() bridges the Effection Future to + // the acpx async-iterator boundary. + if (script.manual && !gateTask) { + gateTask = run(() => gate.operation); + return gateTask.then(emit); } - return { done: true, value: undefined }; - }; - return { - next(): Promise> { - // A manual turn withholds its events until the release - // gate resolves; run() bridges the Effection Future to - // the acpx async-iterator boundary. - if (script.manual && !gateTask) { - gateTask = run(() => gate.operation); - return gateTask.then(emit); - } - return Promise.resolve(emit()); - }, - return(): Promise> { - index = pushEvents.length; - const halted = gateTask?.halt(); - gateTask = undefined; - // Observe the halt so no root task is left dangling. - if (halted) { - return halted.then(() => ({ done: true, value: undefined })); - } - return Promise.resolve({ done: true, value: undefined }); - }, - }; - }, - }, - result: run(() => resultReady.operation), - materialized: materialized.promise, - cancel() { - fake.cancelled = true; - fake.finish([], { status: "cancelled" }); - return Promise.resolve(); - }, - closeStream() { - return Promise.resolve(); + return Promise.resolve(emit()); + }, + return(): Promise> { + index = pushEvents.length; + const halted = gateTask?.halt(); + gateTask = undefined; + // Observe the halt so no root task is left dangling. + if (halted) { + return halted.then(() => ({ done: true, value: undefined })); + } + return Promise.resolve({ done: true, value: undefined }); + }, + }; }, }, - }; - if (!awaiting) { - // Already asserting. The barrier says the session no longer awaits - // its first accepted turn, not that this one was accepted. - const stored = records.get(recordId); - materialized.resolve({ - acpxRecordId: recordId, - ...(stored?.agentSessionId === undefined - ? {} - : { agentSessionId: stored.agentSessionId }), - }); - } else if (script.accepted !== false && script.manualAcceptance !== true) { - // Acceptance is not the turn's output: a backend takes the turn - // before it says anything, so a manual turn — which withholds its - // events — still reports acceptance at once unless a case asks it - // not to. - promote(); - } - if (!script.manual) { - fake.finish(events, result); - } - harness.turns.push(fake); - for (const barrier of [...waitingForTurns]) { - if (harness.turns.length >= barrier.count) { - waitingForTurns.splice(waitingForTurns.indexOf(barrier), 1); - barrier.settle(); - } + result: run(() => resultReady.operation), + materialized: materialized.promise, + cancel() { + fake.cancelled = true; + fake.finish([], { status: "cancelled" }); + return Promise.resolve(); + }, + closeStream() { + return Promise.resolve(); + }, + }, + }; + if (!awaiting) { + // Already asserting. The barrier says the session no longer awaits + // its first accepted turn, not that this one was accepted. + const stored = records.get(recordId); + materialized.resolve({ + acpxRecordId: recordId, + ...(stored?.agentSessionId === undefined + ? {} + : { agentSessionId: stored.agentSessionId }), + }); + } else if (script.accepted !== false && script.manualAcceptance !== true) { + // Acceptance is not the turn's output: a backend takes the turn + // before it says anything, so a manual turn — which withholds its + // events — still reports acceptance at once unless a case asks it + // not to. + promote(); + } + if (!script.manual) { + fake.finish(events, result); + } + harness.turns.push(fake); + for (const barrier of [...waitingForTurns]) { + if (harness.turns.length >= barrier.count) { + waitingForTurns.splice(waitingForTurns.indexOf(barrier), 1); + barrier.settle(); } - return fake.turn; - }, - runTurn(input) { - return this.startTurn(input).events; - }, - ...(harness.omitConfiguration + } + return fake.turn; + } + function configuration() { + return harness.omitConfiguration ? {} : { getStatus() { @@ -670,22 +709,20 @@ export function createFakeRuntime(): FakeRuntimeHarness { ); return gate ? run(() => gate).then(land) : Promise.resolve(land()); }, - }), - cancel() { - return Promise.resolve(); - }, - close(input) { - harness.activity?.("close"); - harness.closeRuntimes.push(options.agentProcessEnv?.CLAUDE_CODE_EXECUTABLE); - harness.closeRuntimeIndexes.push(runtimeIndex); - harness.closeCalls.push(input.handle); - harness.closeInputs.push({ ...(input as unknown as Record) }); - if (harness.closeFailure) { - return Promise.reject(harness.closeFailure); - } - return Promise.resolve(); - }, - }; + }; + } + function close(input: Parameters[0]): Promise { + harness.activity?.("close"); + harness.closeRuntimes.push(options.agentProcessEnv?.CLAUDE_CODE_EXECUTABLE); + harness.closeRuntimeIndexes.push(runtimeIndex); + harness.closeCalls.push(input.handle); + harness.closeInputs.push({ ...(input as unknown as Record) }); + if (harness.closeFailure) { + return Promise.reject(harness.closeFailure); + } + return Promise.resolve(); + } + return runtime; }, }; return harness; diff --git a/packages/acp/tests/host-conversation.test.ts b/packages/acp/tests/host-conversation.test.ts index b94af54be..35c509b52 100644 --- a/packages/acp/tests/host-conversation.test.ts +++ b/packages/acp/tests/host-conversation.test.ts @@ -24,6 +24,7 @@ */ import { describe, it } from "@executablemd/test-support/bdd"; +import { Stdio } from "@effectionx/process"; import { expect } from "@executablemd/test-support/expect"; import { InMemoryStream, @@ -1334,7 +1335,12 @@ function changingHost(f: CertificationFixture, agent = AGENT): ChangingHost { const ownership = owned(); const runtime = runtimeBoundary(); const observer = createFakeObserver({ - versionOutput: agent === "codex" ? "codex-cli 0.163.0\n" : "scribe 1.0.0\n", + versionOutput: + agent === "codex" + ? "codex-cli 0.163.0\n" + : agent === "claude" + ? "2.1.241 (Claude Code)\n" + : "scribe 1.0.0\n", }); return { store, @@ -1574,7 +1580,9 @@ describe( expect(attempt).toContain("session/load"); expect(attempt).not.toContain("session/new"); expect(attempt).not.toContain("session/prompt"); - expect(history.snapshot()).toEqual(journal); + // The history keeps its prefix; the refused turn is recorded as the + // failure it was, with nothing answered in its place. + expect(history.snapshot().slice(0, journal.length)).toEqual(journal); const unchanged = yield* until(target.store.load(original)); expect([ unchanged?.acpSessionId, @@ -1592,9 +1600,10 @@ describe( throw reopened.error; } expect(reopened.value.refused.ok).toBe(false); - // The adapter's own account of the failed load crosses unchanged. - expect(!reopened.value.refused.ok && reopened.value.refused.error.message).toContain( - "missing controlled history", + // The same refusal a held Codex conversation meets: the resume could not + // be performed, and nothing replaced it. + expect(!reopened.value.refused.ok && reopened.value.refused.error.name).toBe( + "SessionResumeRequiredError", ); expect(reopened.value.later).toEqual(Ok("remembered")); expect( @@ -1602,10 +1611,13 @@ describe( .filter((call) => call.method === "session/prompt") .map((call) => call.kind), ).toEqual(["seed", "recall"]); - // The refused turn recorded nothing; only the seed and the later turn are recorded. + // The refused turn recorded its failure and no answer. const keptTurns = turns(history.snapshot()); - expect(keptTurns).toHaveLength(2); - expect(keptTurns.map((turn) => turn.record.status)).toEqual(["completed", "completed"]); + expect(keptTurns.map((turn) => turn.record.status)).toEqual([ + "completed", + "failed", + "completed", + ]); }); }); @@ -1737,189 +1749,269 @@ describe( }, ); +/** One supported provider's release before and after a host CLI upgrade. */ +const UPGRADES = { + codex: { + before: "codex-cli 0.163.0", + after: "codex-cli 0.167.1\n", + variable: "CODEX_PATH", + warning: + "Codex has changed from 0.163.0 to 0.167.1 since this session was established. " + + "Continuing the existing conversation.", + }, + claude: { + before: "2.1.241 (Claude Code)", + after: "2.1.250 (Claude Code)\n", + variable: "CLAUDE_CODE_EXECUTABLE", + warning: + "Claude has changed from 2.1.241 to 2.1.250 since this session was established. " + + "Continuing the existing conversation.", + }, +} as const; + describe( - "resume retention: a held Codex conversation across a host CLI upgrade", + "resume retention: a held conversation across a host CLI upgrade", { sanitizeOps: false, sanitizeResources: false }, () => { - for (const [mode, failure, errorName] of [ - ["distinct", undefined, undefined], - ["normal", "reopened a different native conversation", "AttachmentRefused"], - ["standard", "did not confirm the retained native conversation", "AttachmentRefused"], - ["missing", "could not be resumed", "SessionResumeRequiredError"], - ["distinct-refused", "could not be resumed", "SessionResumeRequiredError"], - ] as const) { - it(`requires the new build's live identity (${mode})`, function* () { - yield* withCertificationFixture(function* (f) { - const target = changingHost(f, "codex"); - const command = f.command("distinct"); - const key = deriveSessionKey(command, f.dir, "chat-1"); - const tuple = { provider: "acpx", agent: command, sessionKey: key }; - const history = new InMemoryStream(); - expect( - answer( - yield* withConversation( - history, - target.installation(command), - (chat) => chat.prompt("seed:remembered"), - "codex", + for (const agent of ["codex", "claude"] as const) { + const upgrade = UPGRADES[agent]; + for (const [mode, failure, errorName] of [ + ["distinct", undefined, undefined], + ["normal", "reopened a different native conversation", "AttachmentRefused"], + ["standard", "did not confirm the retained native conversation", "AttachmentRefused"], + ["missing", "could not be resumed", "SessionResumeRequiredError"], + ["distinct-refused", "could not be resumed", "SessionResumeRequiredError"], + ] as const) { + it(`${agent}: requires the new build's live identity (${mode})`, function* () { + yield* withCertificationFixture(function* (f) { + const target = changingHost(f, agent); + const command = f.command("distinct"); + const key = deriveSessionKey(command, f.dir, "chat-1"); + const tuple = { provider: "acpx", agent: command, sessionKey: key }; + const history = new InMemoryStream(); + expect( + answer( + yield* withConversation( + history, + target.installation(command), + (chat) => chat.prompt("seed:remembered"), + agent, + ), ), - ), - ).toBe("READY"); - const record = yield* until(target.store.load(key)); - const route = yield* target.ownership.routes.read(tuple); - if (!record?.agentSessionId || route?.schema !== "session-route.v3") { - throw new Error("The original build did not establish a native conversation"); - } - expect(route.executableBinding.reportedVersion).toBe("codex-cli 0.163.0"); - const { lines, stream } = yield* reread(history); - const before = yield* f.calls(); - if (mode === "missing") { - yield* rm(join(f.dir, `fixture-${record.acpSessionId}.json`)); - } - const runtimeCount = target.runtime.environments.length; - target.observer.observation.path = "/opt/builds/codex-0.167.1"; - target.observer.observation.versionOutput = "codex-cli 0.167.1\n"; - target.observer.observation.digest = "b".repeat(64); - const begun: string[] = []; - const published: unknown[] = []; - const provider = target.installation(mode === "missing" ? command : f.command(mode)); - const resumed = yield* withConversation( - stream, - { - ...provider, - *install() { - if (provider.install !== undefined) { - yield* provider.install(); - } - yield* useAgentPromptPublisher({ - *begin(text) { - begun.push(text); - return {}; - }, - *publish(publication) { - published.push(publication.begun); - yield* publication.append(); - }, - }); - }, - }, - (chat) => chat.prompt("recall", { model: "selected", effort: "high" }), - "codex", - ); - const calls = (yield* f.calls()).slice(before.length); - const methods = calls.map((call) => call.method); - const environments = target.runtime.environments.slice(runtimeCount); - expect(environments).toContainEqual({ CODEX_PATH: "/opt/builds/codex-0.167.1" }); - expect(methods).toContain("session/load"); - expect(methods).not.toContain("session/new"); - expect( - calls - .filter((call) => call.sessionId !== undefined) - .every((call) => call.sessionId === record.acpSessionId), - ).toBe(true); - expect(yield* target.ownership.routes.read(tuple)).toEqual(route); - if (failure === undefined) { - expect(answer(resumed)).toBe("remembered"); - expect(methods.indexOf("session/load")).toBeLessThan( - methods.indexOf("session/set_config_option"), - ); - expect(methods.indexOf("session/load")).toBeLessThan(methods.indexOf("session/prompt")); - expect(methods.lastIndexOf("session/set_config_option")).toBeLessThan( - methods.indexOf("session/prompt"), - ); - const kept = yield* until(target.store.load(key)); - expect(kept?.agentSessionId).toBe(record.agentSessionId); - expect(kept?.messages.slice(0, record.messages.length)).toEqual(record.messages); - expect(turns(stream.snapshot()).map((turn) => turn.record.agentSessionId)).toEqual([ - record.agentSessionId, - record.agentSessionId, - ]); - } else { - if (!resumed.ok || resumed.value.ok) { - throw new Error("The held conversation did not report a resume refusal"); + ).toBe("READY"); + const record = yield* until(target.store.load(key)); + const route = yield* target.ownership.routes.read(tuple); + if (!record?.agentSessionId || route?.schema !== "session-route.v3") { + throw new Error("The original build did not establish a native conversation"); } - expect(resumed.value.error.name).toBe(errorName); - expect(resumed.value.error.message).toContain(failure); - expect(methods).not.toContain("session/set_config_option"); - expect(methods).not.toContain("session/prompt"); - expect(yield* until(target.store.load(key))).toEqual(record); - if (errorName === "SessionResumeRequiredError") { - const after = stream.snapshot(); - expect(after.slice(0, lines.length).map(serializeDurableEvent)).toEqual(lines); - expect(after).toHaveLength(lines.length + 1); - const saved = turns(after).at(-1); - const expectedError = { - message: resumed.value.error.message, - name: errorName, - diagnostic: { - provider: "acp", - operation: "session/prompt", - stage: "held-session-ensure", - code: "RUNTIME", - detailCode: "SESSION_RESUME_REQUIRED", - origin: "acp", - retryable: true, - acp: - mode === "missing" - ? { code: -32603, message: "missing controlled history" } - : { - code: -32041, - message: "Internal error", - details: "Release the active writer before reconnecting.", - }, + expect(route.executableBinding.reportedVersion).toBe(upgrade.before); + const { lines, stream } = yield* reread(history); + const before = yield* f.calls(); + if (mode === "missing") { + yield* rm(join(f.dir, `fixture-${record.acpSessionId}.json`)); + } + const runtimeCount = target.runtime.environments.length; + target.observer.observation.path = `/opt/builds/${agent}-next`; + target.observer.observation.versionOutput = upgrade.after; + target.observer.observation.digest = "b".repeat(64); + const begun: string[] = []; + const published: unknown[] = []; + const warned: string[] = []; + const provider = target.installation(mode === "missing" ? command : f.command(mode)); + const resumed = yield* withConversation( + stream, + { + ...provider, + *install() { + if (provider.install !== undefined) { + yield* provider.install(); + } + yield* Stdio.around({ + // deno-lint-ignore require-yield + *stderr([bytes]) { + warned.push(new TextDecoder().decode(bytes).trim()); + }, + }); + yield* useAgentPromptPublisher({ + *begin(text) { + begun.push(text); + return {}; + }, + *publish(publication) { + published.push(publication.begun); + yield* publication.append(); + }, + }); }, - }; - expect(saved?.name).toBe("turn:2"); - expect(saved?.record).toEqual({ - sequence: expect.any(Number), - agent: "codex", - sessionKey: "", - status: "failed", - text: "", - error: expectedError, - }); - const event = after.at(-1); - expect(event?.type === "yield" && event.description.input).toBe("recall"); - expect(begun).toEqual([]); - expect(published).toEqual([undefined]); - expect(resumed.value.error.cause).toBe(undefined); - expect( - Reflect.get(resumed.value.error, "executablemd.agent.prompt-diagnostic"), - ).toEqual(expectedError.diagnostic); - if (mode === "distinct-refused") { - const attemptedCalls = (yield* f.calls()).length; - const later = yield* withConversation( - stream, - target.installation(f.command("distinct-next")), - (chat) => chat.prompt("recover"), - "codex", - ); - expect(answer(later)).toBe("remembered"); - const sent = (yield* f.calls()).slice(attemptedCalls); - expect(sent.filter((call) => call.method === "session/prompt")).toMatchObject([ - { sessionId: record.acpSessionId }, - ]); - expect(sent.map((call) => call.method)).not.toContain("session/new"); - expect(turns(stream.snapshot()).map((turn) => turn.name)).toEqual([ - "turn:1", - "turn:2", - "turn:3", - ]); - expect((yield* until(target.store.load(key)))?.agentSessionId).toBe( - record.agentSessionId, - ); - expect(yield* target.ownership.routes.read(tuple)).toEqual(route); - } + }, + (chat) => chat.prompt("recall", { model: "selected", effort: "high" }), + agent, + ); + const calls = (yield* f.calls()).slice(before.length); + const methods = calls.map((call) => call.method); + const environments = target.runtime.environments.slice(runtimeCount); + expect(environments).toContainEqual({ + [upgrade.variable]: `/opt/builds/${agent}-next`, + }); + // The change is reported once, before the conversation is reached, + // whatever happens to the reopening after it. + expect(warned).toEqual([upgrade.warning]); + expect(methods).toContain("session/load"); + expect(methods).not.toContain("session/new"); + expect( + calls + .filter((call) => call.sessionId !== undefined) + .every((call) => call.sessionId === record.acpSessionId), + ).toBe(true); + expect(yield* target.ownership.routes.read(tuple)).toEqual(route); + if (failure === undefined) { + expect(answer(resumed)).toBe("remembered"); + expect(methods.indexOf("session/load")).toBeLessThan( + methods.indexOf("session/set_config_option"), + ); + expect(methods.indexOf("session/load")).toBeLessThan( + methods.indexOf("session/prompt"), + ); + expect(methods.lastIndexOf("session/set_config_option")).toBeLessThan( + methods.indexOf("session/prompt"), + ); + const kept = yield* until(target.store.load(key)); + expect(kept?.agentSessionId).toBe(record.agentSessionId); + expect(kept?.messages.slice(0, record.messages.length)).toEqual(record.messages); + expect(turns(stream.snapshot()).map((turn) => turn.record.agentSessionId)).toEqual([ + record.agentSessionId, + record.agentSessionId, + ]); } else { - expect(stream.snapshot().map(serializeDurableEvent)).toEqual(lines); + if (!resumed.ok || resumed.value.ok) { + throw new Error("The held conversation did not report a resume refusal"); + } + expect(resumed.value.error.name).toBe(errorName); + expect(resumed.value.error.message).toContain(failure); + expect(methods).not.toContain("session/set_config_option"); + expect(methods).not.toContain("session/prompt"); + expect(yield* until(target.store.load(key))).toEqual(record); + if (errorName === "SessionResumeRequiredError") { + const after = stream.snapshot(); + expect(after.slice(0, lines.length).map(serializeDurableEvent)).toEqual(lines); + expect(after).toHaveLength(lines.length + 1); + const saved = turns(after).at(-1); + const expectedError = { + message: resumed.value.error.message, + name: errorName, + diagnostic: { + provider: "acp", + operation: "session/prompt", + stage: "held-session-ensure", + code: "RUNTIME", + detailCode: "SESSION_RESUME_REQUIRED", + origin: "acp", + retryable: true, + acp: + mode === "missing" + ? { code: -32603, message: "missing controlled history" } + : { + code: -32041, + message: "Internal error", + details: "Release the active writer before reconnecting.", + }, + }, + }; + expect(saved?.name).toBe("turn:2"); + expect(saved?.record).toEqual({ + sequence: expect.any(Number), + agent, + sessionKey: "", + status: "failed", + text: "", + error: expectedError, + }); + const event = after.at(-1); + expect(event?.type === "yield" && event.description.input).toBe("recall"); + expect(begun).toEqual([]); + expect(published).toEqual([undefined]); + expect(resumed.value.error.cause).toBe(undefined); + expect( + Reflect.get(resumed.value.error, "executablemd.agent.prompt-diagnostic"), + ).toEqual(expectedError.diagnostic); + if (mode === "distinct-refused") { + const attemptedCalls = (yield* f.calls()).length; + const later = yield* withConversation( + stream, + target.installation(f.command("distinct-next")), + (chat) => chat.prompt("recover"), + agent, + ); + expect(answer(later)).toBe("remembered"); + const sent = (yield* f.calls()).slice(attemptedCalls); + expect(sent.filter((call) => call.method === "session/prompt")).toMatchObject([ + { sessionId: record.acpSessionId }, + ]); + expect(sent.map((call) => call.method)).not.toContain("session/new"); + expect(turns(stream.snapshot()).map((turn) => turn.name)).toEqual([ + "turn:1", + "turn:2", + "turn:3", + ]); + expect((yield* until(target.store.load(key)))?.agentSessionId).toBe( + record.agentSessionId, + ); + expect(yield* target.ownership.routes.read(tuple)).toEqual(route); + } + } else { + expect(stream.snapshot().map(serializeDurableEvent)).toEqual(lines); + } } - } + }); }); - }); + } } }, ); +describe( + "conformance: a provider that asserts the same identity over empty history", + { sanitizeOps: false, sanitizeResources: false }, + () => { + it("E10: marker recovery detects the lost context that identity alone cannot", function* () { + yield* withCertificationFixture(function* (f) { + const target = changingHost(f, "codex"); + const command = f.command("distinct"); + const history = new InMemoryStream(); + expect( + answer( + yield* withConversation( + history, + target.installation(command), + (chat) => chat.prompt("seed:remembered"), + "codex", + ), + ), + ).toBe("READY"); + const key = deriveSessionKey(command, f.dir, "chat-1"); + const record = yield* until(target.store.load(key)); + // The substitute loads the same ACP target and asserts the same native + // identity, so positive confirmation passes — and its history is empty. + const before = yield* f.calls(); + const substituted = yield* withConversation( + history, + target.installation(f.command("distinct-lost")), + (chat) => chat.prompt("recall"), + "codex", + ); + const sent = (yield* f.calls()).slice(before.length); + expect(sent.map((call) => call.method)).toContain("session/prompt"); + expect(sent.map((call) => call.method)).not.toContain("session/new"); + expect((yield* until(target.store.load(key)))?.agentSessionId).toBe(record?.agentSessionId); + // Equal identities with replacement history do not pass conformance: + // the original-only marker is what proves continuity. + expect(answer(substituted)).not.toBe("remembered"); + expect(answer(substituted)).toBe("WRONG"); + }); + }); + }, +); + describe( "standard held conversation persistence through a changed command", { sanitizeOps: false, sanitizeResources: false }, diff --git a/packages/acp/tests/native-launch.test.ts b/packages/acp/tests/native-launch.test.ts index fb289ca75..a12f375f6 100644 --- a/packages/acp/tests/native-launch.test.ts +++ b/packages/acp/tests/native-launch.test.ts @@ -17,6 +17,7 @@ import { describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Ok, scoped, sleep, spawn, until, withResolvers } from "effection"; +import { Stdio } from "@effectionx/process"; import type { Operation } from "effection"; import { Agent, sameExecutableBuild } from "@executablemd/agent/api"; import type { ConfigureAgentSession, ProviderSessionConfiguration } from "@executablemd/agent/api"; @@ -183,6 +184,29 @@ const OBSERVED_BUILD: ExecutableBuildBindingV1 = { /** The canonical path that same observation reports. */ const OBSERVED_PATH = "/opt/builds/claude"; +/** + * Every diagnostic line this scope's operations write to standard error. + * + * Installed through the same contextual `Stdio` chain a host captures, so what + * a case reads is exactly what a REPL entry or a command's stderr would show. + */ +function* diagnostics(): Operation { + const lines: string[] = []; + const decoder = new TextDecoder(); + yield* Stdio.around({ + // deno-lint-ignore require-yield + *stderr([bytes]) { + lines.push( + ...decoder + .decode(bytes) + .split("\n") + .filter((line) => line.length > 0), + ); + }, + }); + return lines; +} + /** Everything the launch touched, in the order it touched it. */ interface Trace { records: LaunchRecord[]; @@ -808,6 +832,7 @@ describe("Tier NL — native session launch", () => { const existing: AcpSessionRecord = { ...makeRecord(AGENT_COMMAND, CWD), acpxRecordId: SESSION_KEY, + agentSessionId: "native-retained", acpx: { session_options: { system_prompt: INSTRUCTIONS } }, }; const store = makeStore({ [SESSION_KEY]: existing }); @@ -816,7 +841,17 @@ describe("Tier NL — native session launch", () => { yield* launch(INSTRUCTIONS); const prepared = trace.records[0]; - expect(prepared).toMatchObject({ phase: "prepared", sessionState: "resumed" }); + expect(prepared).toMatchObject({ + phase: "prepared", + sessionState: "resumed", + nativeSessionId: "native-retained", + }); + // The established conversation is reopened by its own loading target + // under the provider's live confirmation of its retained identity. + expect(harness.ensureCalls[0]).toMatchObject({ + resumeSessionId: existing.acpSessionId, + expectedAgentSessionId: "native-retained", + }); expect(trace.launches.length).toBe(1); }); }); @@ -1004,6 +1039,7 @@ describe("Tier NL — native session launch", () => { const existing: AcpSessionRecord = { ...makeRecord(AGENT_COMMAND, CWD), acpxRecordId: SESSION_KEY, + agentSessionId: "native-retained", acpx: { session_options: { system_prompt: INSTRUCTIONS } }, }; yield* scoped(function* () { @@ -1785,7 +1821,19 @@ describe("Tier CN — client-allocated construction", () => { expect(prepared.executableBinding).toEqual(OBSERVED_BUILD); expect(trace.launches[0]!.command).toContain(ALLOCATED); // ACP created nothing: this session is materialized by the native process. - expect(harness.ensureCalls).toEqual([]); + // After that process exited, the exact allocated identity was loaded once + // and its live assertion confirmed it, with nothing else sent. + expect(harness.ensureCalls).toEqual([ + { + agent: "claude", + cwd: CWD, + mode: "persistent", + resumeSessionId: ALLOCATED, + sessionKey: SESSION_KEY, + }, + ]); + expect(harness.turns).toEqual([]); + expect(harness.configCalls).toEqual([]); }); it("CN2: a fresh construction hands over a private instruction file", function* () { @@ -1939,6 +1987,7 @@ describe("Tier CN — client-allocated construction", () => { }, }; const trace = newTrace(); + harness.activity = (event) => trace.order.push(event); yield* installClientNative(watched, trace, { routeStore: routes }); const session = yield* Agent.operations.session(); @@ -1955,8 +2004,86 @@ describe("Tier CN — client-allocated construction", () => { // The launch settles how the session is constructed before anything could // act on it: a crash after provider work and before this publication would // leave a conversation that already exists looking unconstructed. - expect(order).toEqual(["publish"]); - expect(watched.ensureCalls.length).toBe(0); + // The only runtime is the confirmation after the native child joined. + expect(order).toEqual(["publish", "runtime"]); + expect(trace.order.indexOf("spawn")).toBeLessThan(trace.order.indexOf("ensure")); + expect(watched.ensureCalls.length).toBe(1); + }); + + it("CN12: an established session with an ACP record is strictly confirmed before resume", function* () { + const harness = createFakeRuntime(); + harness.activity = (event) => trace.order.push(event); + const trace = newTrace(); + const routes = createMemorySessionRouteStore(); + yield* installClientNative(harness, trace, { routeStore: routes }); + + yield* launch(INSTRUCTIONS); + const created = harness.ensureCalls.length; + yield* launch(INSTRUCTIONS); + + // The confirmation after creation left an ACP arrangement, so the second + // launch reopens it strictly, with no configuration requested, and releases + // it before the native resume. + const preflight = harness.ensureCalls.slice(created); + expect(preflight).toHaveLength(1); + expect(preflight[0]).toMatchObject({ + resumeSessionId: ALLOCATED, + expectedAgentSessionId: ALLOCATED, + }); + expect(harness.configCalls).toEqual([]); + expect(harness.turns).toEqual([]); + const second = trace.order.slice(trace.order.lastIndexOf("prepared") - 2); + expect(second.slice(0, 2)).toEqual(["ensure", "close"]); + expect(trace.launches[1]!.command).toEqual([OBSERVED_PATH, "--resume", ALLOCATED]); + }); + + it("CN13: a native exit without a positive assertion of the allocated identity fails", function* () { + for (const asserted of ["another-conversation", undefined] as const) { + yield* scoped(function* () { + const harness = createFakeRuntime(); + if (asserted === undefined) { + harness.omitAgentSessionId = true; + } else { + harness.assertIdentity = asserted; + } + const trace = newTrace(); + yield* installClientNative(harness, trace); + + yield* launch(INSTRUCTIONS); + + // Created once, exited 0, and still not a success: exit status names + // no conversation. Nothing was created again in its place. + expect([asserted, trace.launches.length]).toEqual([asserted, 1]); + const exited = trace.records.find((record) => record.phase === "exited"); + expect([asserted, exited?.failure?.class]).toEqual([asserted, "identity-unavailable"]); + expect([asserted, harness.turns]).toEqual([asserted, []]); + expect([asserted, harness.ensureCalls.map((call) => call.resumeSessionId)]).toEqual([ + asserted, + [ALLOCATED], + ]); + }); + } + }); + + it("CN14: without a confirmation capability, nothing is allocated or started", function* () { + const harness = createFakeRuntime(); + const trace = newTrace(); + let allocated = 0; + yield* installClientNative(harness, trace, { + advertise: ["claude"], + attach: [], + allocate: () => { + allocated += 1; + return ALLOCATED; + }, + }); + + const refusal = yield* attempt(trace, INSTRUCTIONS); + + expect(refusal?.class).toBe("unsupported-capability"); + expect(allocated).toBe(0); + expect(trace.launches).toEqual([]); + expect(harness.ensureCalls).toEqual([]); }); it("CN7: a first turn the backend never accepted leaves the session pending", function* () { @@ -2189,13 +2316,58 @@ describe("Tier CR — client-allocated incomplete replay", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); + harness.activity = (event) => trace.order.push(event); yield* installReplay(harness, trace, routes, "prepared+detached"); yield* routes.publish(agreeing(retained())); yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); expect(trace.launches[0]!.command).toEqual([OBSERVED_PATH, "--resume", ALLOCATED]); - expect(harness.ensureCalls).toEqual([]); + // Confirmed by an exact load before the resume, and released before it. + expect(harness.ensureCalls.map((call) => call.resumeSessionId)).toEqual([ALLOCATED]); + expect(trace.order.slice(-4)).toEqual(["ensure", "close", "spawn", "exited"]); + }); + + it("CR6: a detached replay that cannot be confirmed never creates", function* () { + const harness = createFakeRuntime(); + harness.assertIdentity = "another-conversation"; + const trace = newTrace(); + const routes = createMemorySessionRouteStore(); + yield* installReplay(harness, trace, routes, "prepared+detached"); + yield* routes.publish(agreeing(retained())); + + yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); + + const exited = trace.records.find((record) => record.phase === "exited"); + expect(exited?.failure?.class).toBe("identity-unavailable"); + expect(trace.launches).toEqual([]); + expect(harness.turns).toEqual([]); + }); + + it("CR7: retained bindings that disagree refuse; one missing does not", function* () { + const changed = { ...OBSERVED_BUILD, reportedVersion: "2.1.242 (Claude Code)" }; + for (const [name, route, record, refused] of [ + ["both kept, disagreeing", { executableBinding: changed }, {}, true], + ["the journal kept none", {}, { executableBinding: undefined }, false], + ] as const) { + yield* scoped(function* () { + const harness = createFakeRuntime(); + const trace = newTrace(); + const routes = createMemorySessionRouteStore(); + yield* installReplay(harness, trace, routes, "prepared+detached", record); + yield* routes.publish({ ...agreeing(retained()), ...route } as AgentSessionRoute); + + yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); + + const exited = trace.records.find((one) => one.phase === "exited"); + expect([name, exited?.failure?.class]).toEqual([ + name, + refused ? "identity-unavailable" : undefined, + ]); + expect([name, trace.launches.length]).toEqual([name, refused ? 0 : 1]); + expect([name, harness.ensureCalls.length]).toEqual([name, refused ? 0 : 1]); + }); + } }); it("CR2: a prepared-only replay creates under the retained identity", function* () { @@ -2822,6 +2994,8 @@ describe("Tier CX — cancellation before ownership ends", () => { // A launch that stopped on the way never proved the session stopped, so it // stays owned rather than looking finished. expect(trace.ownership.events).not.toContain("quiesced"); + // Cancellation joined the child and started no confirmation in teardown. + expect(harness.ensureCalls).toEqual([]); }); }); @@ -2934,10 +3108,11 @@ describe("Tier CA — client-native attachment", () => { } } - it("CA1: the route's exact identity crosses as resumeSessionId, with the observed build", function* () { + it("CA1: the route's exact identity crosses as resumeSessionId, through the selected executable", function* () { + const selected = "/selected/bin/claude"; const space = yield* installAttachment(bound(), { - agentProcessEnv: function* () { - throw new Error("native selection invoked default host lookup"); + *agentProcessEnv() { + return { CLAUDE_CODE_EXECUTABLE: selected }; }, }); @@ -2948,18 +3123,18 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.ensureCalls).toHaveLength(1); expect(space.harness.ensureCalls[0]?.resumeSessionId).toBe(ALLOCATED); expect(session.agentSessionId).toBe(ALLOCATED); - // The build was reobserved before the runtime existed, and the exact path - // it found reaches only the matching child's transient environment. - expect(space.observer.observed).toEqual(["claude"]); + // The host's own selection is the file observed and the file the child + // runs; nothing resolved the launcher name again on its own. + expect(space.observer.observed).toEqual([selected]); const options = space.harness.createdOptions.at(-1); - expect(options?.agentProcessEnv).toEqual({ CLAUDE_CODE_EXECUTABLE: OBSERVED_PATH }); + expect(options?.agentProcessEnv).toEqual({ CLAUDE_CODE_EXECUTABLE: selected }); expect(options?.agentRegistry.resolve("claude")).toBe(AGENT_COMMAND); // And nowhere else. - expect(JSON.stringify(yield* space.routes.read(KEY))).not.toContain(OBSERVED_PATH); - expect(JSON.stringify(space.trace.records)).not.toContain(OBSERVED_PATH); + expect(JSON.stringify(yield* space.routes.read(KEY))).not.toContain(selected); + expect(JSON.stringify(space.trace.records)).not.toContain(selected); }); - it("H7: the observed Codex build wins over an ordinary host CODEX_PATH elsewhere", function* () { + it("H7: an explicit selection wins over the launcher a PATH search would find", function* () { const codex = nativeAdapterFor("codex"); if (codex === undefined || !bindsBuild(codex)) { throw new Error("codex must bind a build"); @@ -2972,18 +3147,33 @@ describe("Tier CA — client-native attachment", () => { }, }, *agentProcessEnv() { - return { CODEX_PATH: "/ordinary/host/codex" }; + return { CODEX_PATH: "relative/bin/codex" }; }, }); yield* Agent.operations.session(); - expect(space.observer.observed).toEqual(["claude"]); + expect(space.observer.observed).toEqual(["relative/bin/codex"]); expect(space.harness.createdOptions.at(-1)?.agentProcessEnv).toEqual({ - CODEX_PATH: OBSERVED_PATH, + CODEX_PATH: "relative/bin/codex", }); }); + it("H8: a bad explicit selection is an availability failure, with no PATH fallback", function* () { + const space = yield* installAttachment(bound(), { + *agentProcessEnv(): Operation | undefined> { + throw new Error("Host Claude Code is unavailable. Correct CLAUDE_CODE_EXECUTABLE."); + }, + }); + + const raised = yield* attach(); + + expect(raised?.message).toContain("is unavailable"); + expect(space.observer.observed).toEqual([]); + expect(space.harness.createdOptions).toEqual([]); + expect(space.harness.ensureCalls).toEqual([]); + }); + it("CA2: a subscribed Prompt attaches under the same identity", function* () { const space = yield* installAttachment(bound()); @@ -3003,6 +3193,29 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.turns[0]?.input.handle.agentSessionId).toBe(ALLOCATED); }); + it("CA18: a refused first attachment stands as nothing, and an exact retry succeeds", function* () { + const space = yield* installAttachment(bound()); + space.harness.assertIdentity = "another-conversation"; + + const raised = yield* attach(); + expect(raised?.name).toBe("AttachmentRefused"); + // The first exact load named no expectation a missing record could not + // satisfy, and nothing was prompted, configured or created. + expect(space.harness.ensureCalls[0]?.resumeSessionId).toBe(ALLOCATED); + expect(space.harness.ensureCalls[0]?.expectedAgentSessionId).toBe(undefined); + expect(space.harness.turns).toEqual([]); + expect(space.harness.configCalls).toEqual([]); + const left = yield* until(space.store.load(SESSION_KEY)); + expect(left?.agentSessionId).toBe(undefined); + expect(left?.sessionMaterialization?.state).toBe("pending"); + + space.harness.assertIdentity = undefined; + const session = yield* Agent.operations.session(); + expect(session.agentSessionId).toBe(ALLOCATED); + expect(space.harness.ensureCalls.at(-1)?.expectedAgentSessionId).toBe(undefined); + expect(yield* space.routes.read(KEY)).toEqual(bound()); + }); + it("CA3: an unadvertised attachment gate refuses before ensure", function* () { // Knowing how to hand a session to a native UI is not evidence that this // build can join the conversation afterwards. The two are separate @@ -3016,54 +3229,95 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.turns).toEqual([]); }); - it("CA4: a host that cannot observe a build refuses before any provider effect", function* () { + it("CA4: a host that cannot observe a version continues, and says so once", function* () { + const lines = yield* diagnostics(); const space = yield* installAttachment(bound(), { observer: false }); - const raised = yield* attach(); + const session = yield* Agent.operations.session(); + yield* Agent.operations.session(); - expect(raised?.message).toContain("executable build observation"); - expect(space.harness.ensureCalls).toEqual([]); - expect(space.harness.createdOptions).toEqual([]); + expect(session.agentSessionId).toBe(ALLOCATED); + expect(space.harness.ensureCalls.map((call) => call.resumeSessionId)).toEqual([ + ALLOCATED, + ALLOCATED, + ]); + expect(lines).toEqual(["The Claude version could not be determined. Continuing."]); }); - it("CA5: a build this run cannot name, or cannot reach, refuses before ensure", function* () { - for (const [name, mutate] of [ + it("CA5: a changed, moved, unrecognized or unaskable build continues the same conversation", function* () { + for (const [name, mutate, warning] of [ [ - "another build at the same command", + "another build at the same path", (observer: FakeObserverHarness) => { observer.observation.digest = "b".repeat(64); }, + [], ], [ - "another version of the same bytes", + "identical bytes at another path", + (observer: FakeObserverHarness) => { + observer.observation.path = "/moved/claude"; + }, + [], + ], + [ + "another version of the same product", (observer: FakeObserverHarness) => { observer.observation.versionOutput = "2.1.242 (Claude Code)\n"; + observer.observation.digest = "c".repeat(64); }, + [ + "Claude has changed from 2.1.241 to 2.1.242 since this session was established. " + + "Continuing the existing conversation.", + ], ], [ "output this adapter does not recognize", (observer: FakeObserverHarness) => { observer.observation.versionOutput = "claude version 2.1.241\n"; }, + ["The Claude version could not be determined. Continuing."], ], [ - "an executable that could not be observed at all", + "an executable that would not say its version", (observer: FakeObserverHarness) => { - observer.failure = "not-executable"; + observer.failure = "version-unavailable"; }, + ["The Claude version could not be determined. Continuing."], ], ] as const) { yield* scoped(function* () { + const lines = yield* diagnostics(); const observer = createFakeObserver(); mutate(observer); const space = yield* installAttachment(bound(), { observer: observer.observer }); + const session = yield* Agent.operations.session(); + + expect([name, session.agentSessionId]).toEqual([name, ALLOCATED]); + expect([name, space.harness.ensureCalls.map((call) => call.resumeSessionId)]).toEqual([ + name, + [ALLOCATED], + ]); + expect([name, lines]).toEqual([name, warning]); + // The route is history, and nothing rewrote it to claim today's build. + expect([name, yield* space.routes.read(KEY)]).toEqual([name, bound()]); + expect([name, lines.join("\n").includes(OBSERVED_PATH)]).toEqual([name, false]); + }); + } + }); + + it("CA5b: a selected executable that is missing or cannot run is unavailable", function* () { + for (const failure of ["not-found", "not-a-file", "not-executable"] as const) { + yield* scoped(function* () { + const observer = createFakeObserver(); + observer.failure = failure; + const space = yield* installAttachment(bound(), { observer: observer.observer }); + const raised = yield* attach(); - expect([name, raised === undefined]).toEqual([name, false]); - expect([name, space.harness.ensureCalls]).toEqual([name, []]); - // A moved build is still that build, so nothing here may name a path. - expect([name, raised?.message.includes(OBSERVED_PATH)]).toEqual([name, false]); + expect([failure, raised?.message.includes("is unavailable")]).toEqual([failure, true]); + expect([failure, space.harness.ensureCalls]).toEqual([failure, []]); }); } }); @@ -3439,36 +3693,31 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.createdOptions).toHaveLength(2); }); - it("CA14: output naming several builds refuses before a child, an ensure or a turn", function* () { - // One canonical line is an answer. Several is a list of builds, and taking - // the first would be choosing one — which is the question this refuses. + it("CA14: output naming several builds is an undetermined version, not a refusal", function* () { + const lines = yield* diagnostics(); const observer = createFakeObserver({ versionOutput: "2.1.241 (Claude Code)\n2.1.242 (Claude Code)\n", }); const space = yield* installAttachment(bound(), { observer: observer.observer }); - const raised = yield* attach(); + const session = yield* Agent.operations.session(); - expect(raised?.message).toContain("does not recognize"); + expect(session.agentSessionId).toBe(ALLOCATED); // Nothing was repeated back: the output is the provider's, not the reader's. - expect(raised?.message).not.toContain("2.1.242"); - expect(space.harness.createdOptions).toEqual([]); - expect(space.harness.ensureCalls).toEqual([]); + expect(lines).toEqual(["The Claude version could not be determined. Continuing."]); expect(space.harness.turns).toEqual([]); - expect(space.trace.launches).toEqual([]); }); - it("CA9: a legacy unbound route refuses rather than attaching", function* () { - // Constructed before XMD recorded which build accepted the identity. A - // build observed now says which one is installed today, not which one has - // this conversation, so there is nothing to compare and nothing to join. + it("CA9: a legacy unbound route attaches through today's selection, and stays as it was", function* () { + const lines = yield* diagnostics(); const space = yield* installAttachment(legacy()); - const raised = yield* attach(); + const session = yield* Agent.operations.session(); - expect(raised?.message).toContain("before XMD recorded which build"); - expect(space.harness.ensureCalls).toEqual([]); - expect(space.harness.createdOptions).toEqual([]); + // Missing historical build evidence alone establishes no difference. + expect(session.agentSessionId).toBe(ALLOCATED); + expect(space.harness.ensureCalls.map((call) => call.resumeSessionId)).toEqual([ALLOCATED]); + expect(lines).toEqual([]); // The route is left exactly as it was: not upgraded, not supplemented. expect(yield* space.routes.read(KEY)).toEqual(legacy()); }); @@ -3575,7 +3824,7 @@ describe("Tier RT — bound runtime partitions", () => { expect(harness.closeCalls).toHaveLength(2); }); - it("RT2: a different build never shares a child", function* () { + it("RT2: a different selected file never shares a child", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); @@ -3588,20 +3837,17 @@ describe("Tier RT — bound runtime partitions", () => { }); yield* Agent.operations.session(); - // The same command, a different build behind it, and a route that names - // the old one: the attachment refuses rather than reusing the child. + // The same command and a different file behind it. The same conversation + // continues, and it does so through a child of its own. observer.observation.digest = "c".repeat(64); observer.observation.path = "/opt/builds/other-claude"; - let raised: Error | undefined; - try { - yield* Agent.operations.session(); - } catch (error) { - raised = error as Error; - } + const session = yield* Agent.operations.session(); - expect(raised?.message).toContain("cannot be confirmed"); - // One runtime, for the one build that was ever accepted. - expect(environments(harness)).toEqual([OBSERVED_PATH]); + expect(session.agentSessionId).toBe(FIRST); + expect(environments(harness)).toEqual([OBSERVED_PATH, "/opt/builds/other-claude"]); + expect( + yield* routes.read({ provider: "acpx", agent: AGENT_COMMAND, sessionKey: SESSION_KEY }), + ).toEqual(route(SESSION_KEY, FIRST)); }); it("RT3: each handle is closed by the partition that created it", function* () { @@ -4022,11 +4268,12 @@ describe("Tier LU — legacy unbound client-native", () => { }; } - it("LU1: a legacy route still resumes natively, under the launcher name", function* () { + it("LU1: a legacy route resumes natively through today's selection, after confirmation", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); const observer = createFakeObserver(); + harness.activity = (event) => trace.order.push(event); yield* routes.publish(legacyRoute()); yield* installLaunchStack(harness, trace, { adapters: { claude: ADAPTER }, @@ -4036,20 +4283,25 @@ describe("Tier LU — legacy unbound client-native", () => { yield* launch(INSTRUCTIONS); - // Exactly what the released contract does: the launcher name, the retained - // identity, no build observed, and no binding invented for a session that - // never recorded one. - expect(trace.launches[0]!.command).toEqual(["claude", "--resume", ALLOCATED]); - expect(observer.observed).toEqual([]); + // The current environment's executable resumes the retained identity, once + // an exact ACP load confirmed it and ACP was released. + expect(trace.launches[0]!.command).toEqual([OBSERVED_PATH, "--resume", ALLOCATED]); + expect(harness.ensureCalls.map((call) => call.resumeSessionId)).toEqual([ALLOCATED]); + expect(trace.order.slice(trace.order.indexOf("ensure"))).toEqual([ + "ensure", + "close", + "prepared", + "detached", + "spawn", + "exited", + ]); + // No binding is invented for a session that never recorded one. const prepared = trace.records[0] as PreparedLaunchRecord; expect(prepared.executableBinding).toBe(undefined); expect(yield* routes.read(KEY)).toEqual(legacyRoute()); }); - it("LU2: an incomplete legacy replay refuses before any live work", function* () { - // The predecessor prepared under a contract that recorded no build, so - // nothing here can show which build has this session's history. Resuming - // anyway would be answering the question by ignoring it. + it("LU2: an incomplete legacy replay continues under the same confirmation rules", function* () { for (const suffix of ["prepared", "prepared+detached"] as const) { yield* scoped(function* () { const harness = createFakeRuntime(); @@ -4067,9 +4319,18 @@ describe("Tier LU — legacy unbound client-native", () => { yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); const failed = trace.records.findLast((record) => record.failure); - expect([suffix, failed?.failure?.class]).toEqual([suffix, "executable-binding-refused"]); - expect([suffix, trace.launches]).toEqual([suffix, []]); - expect([suffix, harness.ensureCalls]).toEqual([suffix, []]); + expect([suffix, failed]).toEqual([suffix, undefined]); + // A prepared-only replay still owes creation and confirms after it; a + // detached one resumes only after its exact load confirmed it. + const command = trace.launches[0]?.command ?? []; + expect([suffix, command.includes("--resume")]).toEqual([ + suffix, + suffix === "prepared+detached", + ]); + expect([suffix, harness.ensureCalls.map((call) => call.resumeSessionId)]).toEqual([ + suffix, + [ALLOCATED], + ]); // Nothing was upgraded on the way past. expect([suffix, yield* routes.read(KEY)]).toEqual([suffix, legacyRoute()]); }); @@ -4089,7 +4350,7 @@ describe("Tier LU — legacy unbound client-native", () => { * show none of them is touched. */ describe("Tier AO — explicit ACP-only capability", () => { - it("AO1: an ACP-only Claude prompt touches no coordinator, route or observer", function* () { + it("AO1: an ACP-only Claude prompt touches no coordinator or route, and observes only for diagnostics", function* () { const touched: string[] = []; const harness = createFakeRuntime(); const trace = newTrace(); @@ -4122,11 +4383,13 @@ describe("Tier AO — explicit ACP-only capability", () => { return candidate; }, }, + // Diagnostic only: a failure here leaves the version undetermined and the + // turn running. executableObserver: { // deno-lint-ignore require-yield *observe() { touched.push("observer"); - throw new Error("this profile observes no build"); + throw new Error("this observation is diagnostic"); }, }, }); @@ -4145,9 +4408,10 @@ describe("Tier AO — explicit ACP-only capability", () => { expect(next.value).toBe("hello world"); }); - // The turn happened, through the ordinary unbound ACP path. + // The turn happened, through the ordinary ACP path, and no machine-wide + // account was consulted. expect(harness.turns).toHaveLength(1); - expect(touched).toEqual([]); + expect(touched).toEqual(["observer"]); }); }); @@ -4317,36 +4581,86 @@ describe("Tier BA — bound ACP-first construction", () => { } }); - it("BA4: a drifted build refuses before ACP is asked for anything", function* () { + it("BA4: a changed build reopens the same conversation under live confirmation", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - yield* installBound(harness, trace, { routeStore: routes }); + const store = makeStore(); + yield* installBound(harness, trace, { routeStore: routes, store }); yield* launch(INSTRUCTIONS); const published = yield* routeOf(routes); const drifted = createFakeRuntime(); const second = newTrace(); - // Another build of the same provider, which accepts the same identity - // string and disagrees silently about which conversation it names. const observer = createFakeObserver({ + path: "/opt/builds/claude-next", versionOutput: "2.1.242 (Claude Code)\n", digest: "b".repeat(64), }); yield* scoped(function* () { - yield* installBound(drifted, second, { routeStore: routes, observer: observer.observer }); + const lines = yield* diagnostics(); + yield* installBound(drifted, second, { + routeStore: routes, + store, + observer: observer.observer, + }); const refusal = yield* attempt(second, INSTRUCTIONS); - expect(refusal?.class).toBe("executable-binding-refused"); + expect(refusal).toBe(undefined); + expect(lines).toEqual([ + "Claude has changed from 2.1.241 to 2.1.242 since this session was established. " + + "Continuing the existing conversation.", + ]); }); - // Nothing was ensured, nothing was spawned, and the retained account is - // exactly what it was: a drifted run repairs no route. - expect(drifted.ensureCalls).toEqual([]); - expect(second.launches).toEqual([]); + // The retained conversation, reopened strictly through today's build and + // resumed by the same identity. The route keeps its original history. + expect(drifted.ensureCalls[0]).toMatchObject({ expectedAgentSessionId: ASSERTED }); + expect(second.launches[0]?.command).toEqual(["/opt/builds/claude-next", "--resume", ASSERTED]); + expect(preparedOf(second).executableBinding).toEqual(OBSERVED_BUILD); expect(yield* routeOf(routes)).toEqual(published); }); - it("BA5: a legacy unbound acp-first route refuses rather than gaining a build", function* () { + it("BA4b: a reopen that asserts another conversation is not handed over", function* () { + const harness = createFakeRuntime(); + const trace = newTrace(); + const routes = createMemorySessionRouteStore(); + const store = makeStore(); + yield* installBound(harness, trace, { routeStore: routes, store }); + yield* launch(INSTRUCTIONS); + + const lying = createFakeRuntime(); + lying.assertIdentity = "another-conversation"; + const second = newTrace(); + yield* scoped(function* () { + yield* installBound(lying, second, { routeStore: routes, store }); + const refusal = yield* attempt(second, INSTRUCTIONS); + expect(refusal?.class).toBe("identity-unavailable"); + }); + expect(second.launches).toEqual([]); + expect(lying.turns).toEqual([]); + expect((yield* until(store.load(SESSION_KEY)))?.agentSessionId).toBe(ASSERTED); + }); + + it("BA4c: an established conversation with no retained assertion is not reopened", function* () { + const harness = createFakeRuntime(); + const trace = newTrace(); + const record = { + ...makeRecord(AGENT_COMMAND, CWD), + acpxRecordId: SESSION_KEY, + acpx: { session_options: { system_prompt: INSTRUCTIONS } }, + }; + yield* installBound(harness, trace, { + store: makeStore({ [SESSION_KEY]: record }), + }); + + const refusal = yield* attempt(trace, INSTRUCTIONS); + + expect(refusal?.class).toBe("identity-unavailable"); + expect(harness.ensureCalls).toEqual([]); + expect(trace.launches).toEqual([]); + }); + + it("BA5: a legacy unbound acp-first route continues without gaining a build", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); @@ -4357,16 +4671,28 @@ describe("Tier BA — bound ACP-first construction", () => { agent: AGENT_COMMAND, sessionKey: SESSION_KEY, }; + const record = { + ...makeRecord(AGENT_COMMAND, CWD), + acpxRecordId: SESSION_KEY, + agentSessionId: ASSERTED, + acpx: { session_options: { system_prompt: INSTRUCTIONS } }, + }; yield* routes.publish(legacy); - yield* installBound(harness, trace, { routeStore: routes }); + yield* installBound(harness, trace, { + routeStore: routes, + store: makeStore({ [SESSION_KEY]: record }), + }); const refusal = yield* attempt(trace, INSTRUCTIONS); - expect(refusal?.class).toBe("executable-binding-refused"); - expect(harness.ensureCalls).toEqual([]); - expect(trace.launches).toEqual([]); - // Unbound is what it stays. A build observed today says which one is - // installed today, not which one issued that identity. + expect(refusal).toBe(undefined); + expect(harness.ensureCalls[0]).toMatchObject({ + resumeSessionId: record.acpSessionId, + expectedAgentSessionId: ASSERTED, + }); + expect(trace.launches[0]?.command).toEqual([OBSERVED_PATH, "--resume", ASSERTED]); + // Unbound is what it stays: today's observation is not that session's history. + expect(preparedOf(trace).executableBinding).toBe(undefined); expect(yield* routeOf(routes)).toEqual(legacy); }); @@ -4838,29 +5164,33 @@ describe("Tier MZ — the materialization turn", () => { // spent to reach a refusal that was already decided. const first = createFakeRuntime(); const routes = createMemorySessionRouteStore(); + const store = makeStore(); acknowledges(first); - yield* installOwing(first, newTrace(), { routeStore: routes }); + yield* installOwing(first, newTrace(), { routeStore: routes, store }); yield* launch(INSTRUCTIONS); expect(first.turns.length).toBe(1); - // Another build of the same provider, which accepts the same identity - // string and disagrees silently about which conversation it names. + // Another build of the same provider. The established conversation is + // reopened under live confirmation, and nothing more is spent in it: the + // materialization turn belongs to a conversation this launch creates. const drifted = createFakeRuntime(); const afterDrift = newTrace(); acknowledges(drifted); yield* scoped(function* () { yield* installOwing(drifted, afterDrift, { routeStore: routes, + store, observer: createFakeObserver({ versionOutput: "2.1.242 (Claude Code)\n", digest: "b".repeat(64), }).observer, }); - expect((yield* attempt(afterDrift, INSTRUCTIONS))?.class).toBe("executable-binding-refused"); + expect(yield* attempt(afterDrift, INSTRUCTIONS)).toBe(undefined); }); expect(drifted.turns).toEqual([]); + expect(drifted.ensureCalls[0]?.expectedAgentSessionId).toBeDefined(); expect(afterDrift.notices).toEqual([]); - expect(afterDrift.launches).toEqual([]); + expect(afterDrift.launches).toHaveLength(1); // And an adapter that asserts no native identity for a session that owes no // turn: the session exists, so there is something to send to, and no way to @@ -5445,18 +5775,17 @@ describe("Tier NR — configured incomplete replay", () => { }); }); - it("NR5: a detached replay whose build drifted refuses before it reopens anything", function* () { + it("NR5: a detached replay through a changed build reopens, reconfigures and resumes", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - // Another build of the same provider: it accepts the same identity string - // and disagrees silently about which conversation it names. const observer = createFakeObserver({ versionOutput: "2.1.242 (Claude Code)\n", digest: "b".repeat(64), }); advertiseConfiguration(harness, trace); yield* scoped(function* () { + const lines = yield* diagnostics(); yield* installLaunchStack(harness, trace, { adapters: { claude: BOUND_CLAUDE }, routeStore: routes, @@ -5471,13 +5800,22 @@ describe("Tier NR — configured incomplete replay", () => { yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); const exited = trace.records.find((record) => record.phase === "exited"); - expect(exited?.failure?.class).toBe("executable-binding-refused"); - // Refused before the conversation was reached: nothing was reopened, no - // status was read, nothing was written, and no process started. - expect(trace.order).toEqual(["prepared", "detached", "exited"]); - expect(harness.ensureCalls).toEqual([]); - expect(harness.configCalls).toEqual([]); - expect(trace.launches).toEqual([]); + expect(exited?.failure).toBe(undefined); + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("from 2.1.241 to 2.1.242"); + // The retained conversation is reached first, put back under what it was + // prepared with, released, and only then resumed natively. + expect(trace.order[2]).toBe("ensure"); + expect(trace.order.slice(-3)).toEqual(["close", "spawn", "exited"]); + expect(harness.ensureCalls).toHaveLength(1); + expect(trace.launches[0]?.command).toEqual([ + OBSERVED_PATH, + "--resume", + `agent-session:${SESSION_KEY}`, + ]); + expect( + yield* routes.read({ provider: "acpx", agent: AGENT_COMMAND, sessionKey: SESSION_KEY }), + ).toEqual(BOUND_ACP_ROUTE); }); }); @@ -5579,8 +5917,7 @@ describe("Tier NR — configured incomplete replay", () => { yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); - expect(trace.order).toEqual(["prepared", "detached", "spawn", "exited"]); - expect(harness.ensureCalls).toEqual([]); + expect(trace.order).toEqual(["prepared", "detached", "ensure", "close", "spawn", "exited"]); expect(harness.configCalls).toEqual([]); }); }); @@ -5598,10 +5935,14 @@ describe("Tier NR — configured incomplete replay", () => { yield* Agent.operations.launch(launchRequest(INSTRUCTIONS)); - expect(trace.order).toEqual(["prepared", "detached", "spawn", "exited"]); - expect(harness.ensureCalls).toEqual([]); + // Nothing is reconfigured, and the resume is preceded by one exact load + // that confirms the retained identity and is released before the spawn. + expect(trace.order).toEqual(["prepared", "detached", "ensure", "close", "spawn", "exited"]); + expect(harness.ensureCalls.map((call) => call.resumeSessionId)).toEqual([ + `agent-session:${SESSION_KEY}`, + ]); expect(harness.configCalls).toEqual([]); - expect(harness.modelRequests).toEqual([]); + expect(harness.modelRequests).toEqual(["ensure -"]); }); }); diff --git a/packages/acp/tests/released-peer.ts b/packages/acp/tests/released-peer.ts index 2570436ac..f43e91785 100644 --- a/packages/acp/tests/released-peer.ts +++ b/packages/acp/tests/released-peer.ts @@ -90,7 +90,7 @@ function respond(request) { const text = request.params.prompt.map(block => block.text ?? "").join(""); const answer = () => { if (text !== "no-accept") update({sessionUpdate: "session_info_update", _meta: {"executablemd.session-materialization/v1": {state: "accepted"}}}); - update({sessionUpdate: "agent_message_chunk", content: {type: "text", text: "answer:" + text + (text === "recall-fail" ? ":" + remembered : "")}}); + update({sessionUpdate: "agent_message_chunk", content: {type: "text", text: "answer:" + text + (text === "recall-fail" || text === "recall" ? ":" + remembered : "")}}); if (text === "diagnostic") { send({jsonrpc: "2.0", id: request.id, error: {code: -32041, message: "Internal error", data: {details: "/work/project: adapter unavailable", authorization: ""}}}); } else if (text === "fail" || text === "recall-fail") { diff --git a/packages/agent/src/launch.ts b/packages/agent/src/launch.ts index 9106898a1..2f5926c26 100644 --- a/packages/agent/src/launch.ts +++ b/packages/agent/src/launch.ts @@ -84,12 +84,11 @@ export type LaunchFailureClass = * last owner never proved it stopped, so nothing here can say the session is * free, and no elapsed time, pid or released lock changes that. * - * `executable-binding-refused` is the build question: the session was - * established by one build of a provider executable, and this run could not - * show it is talking to that same build. Resolution, canonicalization, - * executable-file validation, version parsing, digesting, schema recognition, - * equality, and a session established before any build was recorded all end - * here. + * `executable-binding-refused` is the availability question: the executable + * the current environment selects is missing or cannot be run. A version that + * differs from a session's history, or cannot be determined, is a diagnostic + * and never this refusal; whether a conversation continues is decided by its + * provider-confirmed identity. * * `configuration-refused` is the model or effort question: the session could * not be put into the configuration the `` asked for, or the attempt @@ -127,10 +126,9 @@ export type IdentityProvenance = "provider-returned" | "client-allocated"; /** * Which build of a provider executable a session was established against. * - * A client-allocated session is only meaningful while the build that created - * it can be reproduced. Two builds of the same provider accept the same - * identity and disagree silently about what it names, so a session whose build - * cannot be reproduced is refused rather than resumed. + * Diagnostic history: a later run reports when the version it observes + * differs, and continues. The record is never rewritten with today's build, + * and its absence says nothing. * * What is retained is deliberately not a path: a path says where a build was, * which stops being true, while a version and a digest say which build it was, @@ -149,7 +147,9 @@ export interface ExecutableBuildBindingV1 { * Whether two bindings name the same build. * * Equality is over what was retained, so the same build reached through a - * different path is compatible and a different build at the same path is not. + * different path is equal and a different build at the same path is not. Used + * to check that two original accounts of one session agree, never to admit a + * live executable. */ export function sameExecutableBuild( left: ExecutableBuildBindingV1, diff --git a/packages/cli/src/agent-stack.ts b/packages/cli/src/agent-stack.ts index e542e684c..fac9d63e3 100644 --- a/packages/cli/src/agent-stack.ts +++ b/packages/cli/src/agent-stack.ts @@ -65,6 +65,13 @@ export interface PlanWriterStack { adapters: EmbeddedAdapters; /** What this host states about machine-wide agent sessions, if anything. */ sessions?: MachineSessionAssembly; + /** + * The sessions this invocation has already warned about. + * + * Owned by the invocation and shared with every provider its stack builds. + * Absent leaves each provider installation its own. + */ + compatibilityWarnings?: Set; } /** Everything one `xmd run` invocation settled about agents, resolved once. */ @@ -83,6 +90,7 @@ export interface AgentStack extends PlanWriterStack { export function* resolvePlanWriterStack( flags: AuthorshipFlags, sessions: MachineSessionAssembly | undefined, + compatibilityWarnings?: Set, ): Operation> { if (flags.agentProvider !== "acpx") { return Err(new Error(`Unknown agent provider "${flags.agentProvider}"`)); @@ -93,6 +101,7 @@ export function* resolvePlanWriterStack( defaultAgent, adapters: createEmbeddedAdapters(DEFAULT_ADAPTER_ROOT), ...(sessions === undefined ? {} : { sessions }), + ...(compatibilityWarnings === undefined ? {} : { compatibilityWarnings }), }); } @@ -116,6 +125,7 @@ export function* contextualAgent(): Operation { export function* resolveAgentStack( flags: AgentFlags, sessions: MachineSessionAssembly | undefined, + compatibilityWarnings?: Set, ): Operation> { const config = resolveAgentConfig(flags); if ("error" in config) { @@ -124,6 +134,7 @@ export function* resolveAgentStack( const planWriter = yield* resolvePlanWriterStack( { agentProvider: flags.agentProvider, defaultAgent: config.defaultAgent }, sessions, + compatibilityWarnings, ); if (!planWriter.ok) { return planWriter; @@ -150,6 +161,9 @@ export function hostAcpDependencies(stack: PlanWriterStack): AcpxProviderDepende ...embeddedAdapterDependencies(stack.adapters), sessionStore: createAcpxSessionStore(join(homedir(), ".acpx")), ...(sessions?.usage === undefined ? {} : { promptUsageHost: sessions.usage }), + ...(stack.compatibilityWarnings === undefined + ? {} + : { compatibilityWarnings: stack.compatibilityWarnings }), }; if (sessions === undefined) { return adapters; diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index db69cbce5..953eef69d 100755 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -1218,8 +1218,9 @@ function* underRunDeadline(timeouts: RunTimeouts, body: () => Operation): function* settleAgentStack( flags: AgentFlags, sessions: MachineSessionAssembly | undefined, + compatibilityWarnings: Set, ): Operation { - const stack = yield* resolveAgentStack(flags, sessions); + const stack = yield* resolveAgentStack(flags, sessions, compatibilityWarnings); if (!stack.ok) { console.error(stack.error.message); yield* exit(1); @@ -2976,6 +2977,14 @@ function* dispatch( workflowHost: WorkflowHost | undefined, sessions: MachineSessionAssembly | undefined, replHost: ReplHostAssembly | undefined, + /** + * The sessions this invocation has already warned about. + * + * One set for the whole command, shared by every provider it installs, so a + * session is reported once however many entries, roles or nested runs reach + * it. Transient: it is never retained and admits nothing. + */ + compatibilityWarnings: Set, /** * What this invocation's Plugins installed. * @@ -3084,6 +3093,7 @@ function* dispatch( denyAll: config.denyAll, }, sessions, + compatibilityWarnings, ); if (runStack === undefined) { break; @@ -3140,6 +3150,7 @@ function* dispatch( const planWriter = yield* resolvePlanWriterStack( { agentProvider: config.agentProvider, defaultAgent: config.defaultAgent }, sessions, + compatibilityWarnings, ); if (!planWriter.ok) { console.error(planWriter.error.message); @@ -3238,6 +3249,7 @@ function* dispatch( denyAll: command.config.denyAll, }, sessions, + compatibilityWarnings, ); if (replStack === undefined) { break; @@ -3530,6 +3542,7 @@ function* dispatch( // than a document-level default: nothing here runs a document. { agentProvider: "acpx", defaultAgent: scan.agent }, sessions, + compatibilityWarnings, ); if (!stack.ok) { console.error(stack.error.message); @@ -3846,6 +3859,9 @@ function* runCommand( sessions: MachineSessionAssembly | undefined, replHost: ReplHostAssembly | undefined, ): Operation { + // This invocation's compatibility warnings, shared by every provider it + // installs and gone when it ends. A new invocation can warn again. + const compatibilityWarnings = new Set(); // First, so that no later scanner — help, properties, agent flags — can // mistake the inline document's own text for an option. const evalFlags = readEvalFlags(args); @@ -3882,7 +3898,7 @@ function* runCommand( let workflowHost: WorkflowHost | undefined; if (!helpRequest.requested && namesWorkflow(helpRequest.args)) { try { - workflowHost = yield* installWorkflowHost(); + workflowHost = yield* installWorkflowHost({ compatibilityWarnings }); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); yield* exit(1); @@ -3962,6 +3978,7 @@ function* runCommand( denyAll: selected.config.denyAll, }, sessions, + compatibilityWarnings, ); if (stack === undefined) { return; @@ -3995,6 +4012,7 @@ function* runCommand( workflowHost, sessions, replHost, + compatibilityWarnings, plugins, (document) => installTestPlugins(document, selection, loadPluginModule), cold, diff --git a/packages/cli/src/compiled.ts b/packages/cli/src/compiled.ts index 4a457adc0..7b7c6df54 100644 --- a/packages/cli/src/compiled.ts +++ b/packages/cli/src/compiled.ts @@ -149,7 +149,7 @@ if (isReplSubmit(process.argv.slice(2))) { UPGRADE, () => readInputStream(process.stdin), importPluginModule, - () => useDenoWorkflowHost(HELPER, USAGE), + (options) => useDenoWorkflowHost(HELPER, USAGE, options?.compatibilityWarnings), { ...useMachineSessions(), usage: USAGE }, // What this host selects for a REPL command, and what it installs for // one. The selection is the capability an entry runs with — its diff --git a/packages/cli/src/deno-workflow.ts b/packages/cli/src/deno-workflow.ts index 6908d8182..93d0ed7f0 100644 --- a/packages/cli/src/deno-workflow.ts +++ b/packages/cli/src/deno-workflow.ts @@ -23,7 +23,7 @@ import type { PromptUsageHost } from "@executablemd/acp"; import { homedir } from "node:os"; import { join } from "node:path"; import type { Operation } from "effection"; -import { env as readEnv } from "@executablemd/runtime"; +import { createDenoExecutableObserver, env as readEnv } from "@executablemd/runtime"; import { useWorkflowInputDelivery, useWorkflowLifecycle, @@ -46,10 +46,12 @@ export const RUN_STORAGE_ROOT_ENV = "XMD_WORKFLOW_RUNS"; export function* useDenoWorkflowHost( helper: HelperAssembly, usage?: PromptUsageHost, + compatibilityWarnings?: Set, ): Operation { const configured = yield* readEnv(RUN_STORAGE_ROOT_ENV); const root = configured === undefined || configured === "" ? DEFAULT_RUN_STORAGE_ROOT : configured; + const observer = createDenoExecutableObserver(); return { useRunHost(): Operation { return useWorkflowRunHost({ root }); @@ -80,6 +82,10 @@ export function* useDenoWorkflowHost( root, attachment, ...(usage === undefined ? {} : { promptUsageHost: usage }), + // Diagnostic only: which version the selected executable reports, + // for a warning. It admits nothing and grants no native capability. + ...(observer === undefined ? {} : { executableObserver: observer }), + ...(compatibilityWarnings === undefined ? {} : { compatibilityWarnings }), }), }); }, diff --git a/packages/cli/src/deno.ts b/packages/cli/src/deno.ts index 8821f1a06..a0b63c1eb 100644 --- a/packages/cli/src/deno.ts +++ b/packages/cli/src/deno.ts @@ -168,7 +168,7 @@ if (isReplSubmit(process.argv.slice(2))) { UPGRADE, () => readInputStream(process.stdin), importPluginModule, - () => useDenoWorkflowHost(HELPER, USAGE), + (options) => useDenoWorkflowHost(HELPER, USAGE, options?.compatibilityWarnings), { ...useMachineSessions(), usage: USAGE }, // What this host selects for a REPL command, and what it installs for // one. The selection is the capability an entry runs with — its diff --git a/packages/cli/src/repl/application.ts b/packages/cli/src/repl/application.ts index 37239fdcd..3e11f22d0 100644 --- a/packages/cli/src/repl/application.ts +++ b/packages/cli/src/repl/application.ts @@ -464,7 +464,21 @@ export interface ReplSidekickSubmit { readonly admitted: boolean; } +/** One line a held conversation's own work wrote to its standard error. */ +export interface ReplSidekickDiagnostic { + readonly conversation: string; + /** Inert and privacy-projected; never source, a chat turn or a failure. */ + readonly text: string; +} + export interface ReplSidekickReading { + /** + * What this invocation's held conversations wrote to standard error. + * + * Transient and process-local: shown beside the replies and kept on screen + * for this invocation, and never part of the chat's history. + */ + readonly diagnostics?: readonly ReplSidekickDiagnostic[]; readonly feedback?: readonly SidekickFeedback[]; readonly usageTotal?: string; readonly inspectUsage?: boolean; @@ -4344,6 +4358,9 @@ function sidekickComposedRows( ); metadata(); } + for (const [index, line] of sidekickDiagnostics(reading).entries()) { + items.push(text(`sidekick:stderr:${index}`, ` stderr: ${line}`, styleOf("metadata"))); + } if (reading.savedRecovery !== undefined) { const saved = reading.savedRecovery; items.push( @@ -4357,6 +4374,13 @@ function sidekickComposedRows( return items; } +/** The stderr lines the chat being read wrote in this invocation. */ +function sidekickDiagnostics(reading: ReplSidekickReading): string[] { + return (reading.diagnostics ?? []) + .filter((one) => one.conversation === reading.reading) + .flatMap((one) => one.text.split("\n").filter((line) => line.length > 0)); +} + /** * One composed row's own lines, as whoever wrote them wrote them. * @@ -12725,6 +12749,14 @@ function workspaceChatComposed( } } } + for (const [index, line] of sidekickDiagnostics(reading).entries()) { + items.push({ + kind: "text", + key: `sidekick:stderr:${index}`, + text: `${MARKER_ROOM}stderr: ${line}`, + style: styleOf("metadata"), + }); + } if (reading.savedRecovery !== undefined) { const saved = reading.savedRecovery; items.push( diff --git a/packages/cli/src/repl/program.ts b/packages/cli/src/repl/program.ts index f4bd628cc..8325304dd 100644 --- a/packages/cli/src/repl/program.ts +++ b/packages/cli/src/repl/program.ts @@ -3968,6 +3968,7 @@ function sidekickReadingOf( recovery: owner.recoveryPending, recoveryStatus: reading === undefined ? undefined : owner.recoveryStatus(reading), chat: sidekickChatRows(read.value, owner.previewing), + diagnostics: owner.diagnostics, // What the replies of this history actually did to this execution's // entries, as the coordinates their records hold. Detached from the chat // beside it: a row is what a conversation said, and these are what one of diff --git a/packages/cli/src/repl/sidekick/assembly.ts b/packages/cli/src/repl/sidekick/assembly.ts index 1313eb5ce..de7939237 100644 --- a/packages/cli/src/repl/sidekick/assembly.ts +++ b/packages/cli/src/repl/sidekick/assembly.ts @@ -76,6 +76,9 @@ export function sidekickAssembly( const worker = yield* scripted.worker(conversation); yield* installSidekickProvider(scripted.agent, { sessionStore: scripted.store, + ...(dependencies.compatibilityWarnings === undefined + ? {} + : { compatibilityWarnings: dependencies.compatibilityWarnings }), ...(dependencies.agentCwd === undefined ? {} : { agentCwd: dependencies.agentCwd }), diff --git a/packages/cli/src/repl/sidekick/owner.ts b/packages/cli/src/repl/sidekick/owner.ts index d7a6d89af..049c60e59 100644 --- a/packages/cli/src/repl/sidekick/owner.ts +++ b/packages/cli/src/repl/sidekick/owner.ts @@ -3,6 +3,8 @@ import { DESIGNATED } from "./controls.ts"; import { SCRIPTED_AGENT_PREFIX } from "./scripted.ts"; import type { ReplPluginExtension } from "../../repl-api.ts"; import { projectInputValue, useSecretInputs } from "@executablemd/core/host"; +import { Stdio } from "@effectionx/process"; +import { inertCommandText } from "../command-output.ts"; import { cwd } from "@executablemd/runtime"; import { inspectRecoveryOwnership } from "./recovery-owner.ts"; import { recoveryBlocked, uncertainRequests } from "./recovery-state.ts"; @@ -572,6 +574,17 @@ export interface SidekickOwner { * a screen showing it needs no keystroke to learn that more has arrived. */ readonly previewing: SidekickPreview | undefined; + /** + * What held conversations' own work wrote to standard error in this + * invocation, oldest first. + * + * Captured in the task that owns each conversation, so a provider's warning + * before a reopened conversation's turn lands here rather than on a terminal + * this program is drawing. Inert, privacy-projected display copies only: + * never generated source, a chat record or a failure, and gone with this + * owner. + */ + readonly diagnostics: readonly { readonly conversation: string; readonly text: string }[]; /** * The turn this owner is running, where it is running one. * @@ -842,6 +855,8 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation 0) { + diagnostics.push(Object.freeze({ conversation, text: inertCommandText(shown) })); + moved(); + } + }, + }, + { at: "min" }, + ); const opened = yield* useAgentConversation({ history: conversationStream(writer, conversation, records), id: conversation, @@ -3050,6 +3086,9 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation; } /** @@ -438,12 +447,19 @@ export function* useWorkflowAgentProfile(options: WorkflowAgentProfileOptions): ...(options.createRuntime === undefined ? {} : { createRuntime: options.createRuntime }), ...(options.agentProcessEnv === undefined ? {} : { agentProcessEnv: options.agentProcessEnv }), ...(options.promptUsageHost === undefined ? {} : { promptUsageHost: options.promptUsageHost }), + ...(options.executableObserver === undefined + ? {} + : { executableObserver: options.executableObserver }), + ...(options.compatibilityWarnings === undefined + ? {} + : { compatibilityWarnings: options.compatibilityWarnings }), // ACP-only, stated rather than inherited. A workflow session belongs to a // run, not to this machine: it is named by a row in the run's own database, // arranged in the run's own sidecar, and continued by reattaching that row. // The ordinary-run capabilities are about a different account entirely — - // machine-wide ownership, construction routes, and one observed executable - // build — and this profile supplies none of them. Inheriting the package's + // machine-wide ownership and construction routes — and this profile + // supplies neither. An executable observer, when given, only reports the + // selected version for a diagnostic. Inheriting the package's // advertised sets by omission would make a workflow Claude prompt demand // ownership and a route that this profile has no way to give it. advertiseNativeLaunch: [], diff --git a/packages/cli/src/workflow.ts b/packages/cli/src/workflow.ts index 96307506d..408020ebc 100644 --- a/packages/cli/src/workflow.ts +++ b/packages/cli/src/workflow.ts @@ -150,7 +150,10 @@ export interface WorkflowHost { attach(database: WorkflowRunDatabase, operation: Operation): Operation; } -export type HostWorkflowInstaller = () => Operation; +export type HostWorkflowInstaller = (options?: { + /** The sessions this invocation has already warned about. */ + readonly compatibilityWarnings?: Set; +}) => Operation; /** The one sentence a host without workflow support says. */ export const UNSUPPORTED_WORKFLOW_HOST = diff --git a/packages/cli/tests/adversarial-session-continuity.test.ts b/packages/cli/tests/adversarial-session-continuity.test.ts index 8206ba899..075648558 100644 --- a/packages/cli/tests/adversarial-session-continuity.test.ts +++ b/packages/cli/tests/adversarial-session-continuity.test.ts @@ -16,6 +16,7 @@ import type { Json } from "@executablemd/core"; import type { AgentPromptEvent, Session } from "@executablemd/agent/api"; import { executeInstalled } from "@executablemd/core/host"; import { Permissions, useHostFiles } from "@executablemd/runtime"; +import { Stdio } from "@effectionx/process"; import { InMemoryStream } from "@executablemd/durable-streams"; import type { AcpRuntimeOptions, ProbeCapableRuntime } from "@executablemd/acp"; import { createEmbeddedAdapters } from "@executablemd/acp/embedded-adapters"; @@ -63,20 +64,47 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) { strong?: boolean; guard?: boolean; receiptDirectory?: string; + /** A carried agent, observed through this version output, in its own invocation. */ + agent?: "codex" | "claude"; + version?: string; }) { return scoped(function* () { + const warned: string[] = []; + yield* Stdio.around({ + // deno-lint-ignore require-yield + *stderr([bytes]) { + warned.push(...new TextDecoder().decode(bytes).split("\n").filter(Boolean)); + }, + }); yield* useHostFiles(); yield* Permissions.around({ files: () => true }); yield* useNormalizedOutput(); + const agentName = options.agent ?? "scribe"; yield* installAgentComponents({ - defaultAgent: "scribe", + defaultAgent: agentName, rootProvider: { - options: { defaultAgent: "scribe", permissionMode: "deny-all" }, + options: { defaultAgent: agentName, permissionMode: "deny-all" }, factory: createAcpxProvider({ sessionStore: current.store, agentRegistry: current.registry, advertiseNativeLaunch: [], advertiseClientNativeAttachment: [], + ...(options.agent === undefined + ? {} + : { + // Diagnostic only, exactly as the workflow host supplies it. + executableObserver: { + // deno-lint-ignore require-yield + *observe() { + return { + path: `/selected/${agentName}`, + digest: { algorithm: "sha256" as const, value: "a".repeat(64) }, + versionOutput: options.version ?? "", + }; + }, + }, + compatibilityWarnings: new Set(), + }), ...(options.strong ? { nativeAdapters: { @@ -145,7 +173,7 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) { const doc = join(current.dir, "guard.md"); yield* writeTextFile( doc, - `${body}`, + `${body}`, ); const journal = new InMemoryStream(); const execution = yield* executeInstalled({ path: doc, stream: journal }, [ @@ -174,7 +202,14 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) { ]); const output = yield* execution.output; while (!(yield* output.next()).done) {} - return { result: yield* execution, history: journal.snapshot(), started, resolved, content }; + return { + result: yield* execution, + history: journal.snapshot(), + started, + resolved, + content, + warned, + }; }); } function* methods() { @@ -187,6 +222,93 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) { return { ...current, run, methods }; } +describe( + "E1 ordinary workflow Session continuity across a CLI release (#891)", + { sanitizeOps: false, sanitizeResources: false }, + () => { + const RELEASES = { + codex: ["codex-cli 0.167.1\n", "codex-cli 0.169.1\n", "Codex"], + claude: ["2.1.241 (Claude Code)\n", "2.1.250 (Claude Code)\n", "Claude"], + } as const; + for (const agent of ["codex", "claude"] as const) { + const [before, after, product] = RELEASES[agent]; + it(`${agent}: an upgraded executable continues the configured conversation and its original-only context`, function* () { + const peer = yield* guardPeer(AGENT_SOURCE); + const first = yield* peer.run({ text: "marker", agent, version: before }); + expect(first.result.ok).toBe(true); + expect(first.warned).toEqual([]); + const asserted = first.resolved?.identity; + expect(asserted?.kind).toBe("acpx.agentSessionId"); + + const continued = yield* peer.run({ + existing: true, + text: "recall", + agent, + version: after, + }); + expect(continued.result.ok).toBe(true); + // Context only the original conversation held, through today's build. + expect(JSON.stringify(continued.history)).toContain("answer:recall:marker"); + expect(continued.resolved?.identity).toEqual(asserted); + // An ACP-only account keeps no executable history, so there is no + // difference to report; the work continued without a question. + expect(continued.warned).toEqual([]); + const methods = (yield* peer.methods()).map((entry) => entry.method); + expect(methods.filter((method) => method === "session/new")).toHaveLength(1); + const reopened = methods.lastIndexOf("session/load"); + expect(reopened).toBeGreaterThan(methods.indexOf("session/prompt")); + expect(reopened).toBeLessThan(methods.lastIndexOf("session/set_config_option")); + expect(methods.lastIndexOf("session/set_config_option")).toBeLessThan( + methods.lastIndexOf("session/prompt"), + ); + + // An unfamiliar version string is undetermined, said once, and works. + const unfamiliar = yield* peer.run({ + existing: true, + text: "recall", + agent, + version: "development build\n", + }); + expect(unfamiliar.result.ok).toBe(true); + expect(unfamiliar.warned).toEqual([ + `The ${product} version could not be determined. Continuing.`, + ]); + // Another native conversation, or none asserted at all on an unchanged + // build: refused before any setting or prompt, with nothing created. + for (const refusal of ["different", "missing"] as const) { + const prompts = (yield* peer.methods()).filter( + (entry) => entry.method === "session/prompt", + ).length; + if (refusal === "different") { + yield* writeTextFile(join(peer.dir, "different-native-identity"), ""); + } else { + yield* writeTextFile(peer.agent, STANDARD_AGENT_SOURCE); + } + const refused = yield* peer.run({ + existing: true, + text: "recall", + agent, + version: after, + }); + expect([refusal, refused.result.ok]).toEqual([refusal, false]); + const now = yield* peer.methods(); + expect(now.filter((entry) => entry.method === "session/prompt")).toHaveLength(prompts); + expect(now.filter((entry) => entry.method === "session/new")).toHaveLength(1); + if (refusal === "different") { + yield* rm(join(peer.dir, "different-native-identity")); + } else { + yield* writeTextFile(peer.agent, AGENT_SOURCE); + } + } + // A later explicit attempt reaches the same conversation. + const retried = yield* peer.run({ existing: true, text: "recall", agent, version: after }); + expect(retried.result.ok).toBe(true); + expect(retried.resolved?.identity).toEqual(asserted); + }); + } + }, +); + describe("workflow Session continuity", { sanitizeOps: false, sanitizeResources: false }, () => { it("retains the real ACP-only started pair through close/load and a failed continuation", function* () { const peer = yield* guardPeer(); diff --git a/packages/cli/tests/fixtures/host-agent.ts b/packages/cli/tests/fixtures/host-agent.ts index ede2c4617..e1cf13b53 100644 --- a/packages/cli/tests/fixtures/host-agent.ts +++ b/packages/cli/tests/fixtures/host-agent.ts @@ -9,7 +9,7 @@ import { DatabaseSync } from "node:sqlite"; import { collect, retainedSource } from "@executablemd/core"; import { agentIdentityComponents } from "@executablemd/agent/host"; import { executeInstalled } from "@executablemd/core/host"; -import { API, useHostFiles } from "@executablemd/runtime"; +import { API, createDenoExecutableObserver, useHostFiles } from "@executablemd/runtime"; import { createEmbeddedAdapters } from "@executablemd/acp/embedded-adapters"; import { withWorkflowWorkspace, @@ -58,6 +58,8 @@ main(function* () { useWorkflowAgentProfile({ root, attachment, + // As the Deno workflow host supplies it: diagnostic only. + ...(replay ? {} : { executableObserver: createDenoExecutableObserver() }), adapters: replay ? { ...adapters, diff --git a/packages/cli/tests/repl-agent-journey.test.ts b/packages/cli/tests/repl-agent-journey.test.ts index 1ffd80db9..065639cfb 100644 --- a/packages/cli/tests/repl-agent-journey.test.ts +++ b/packages/cli/tests/repl-agent-journey.test.ts @@ -29,6 +29,7 @@ import { assembleReplProfile } from "../src/repl-profile.ts"; import type { ReplExecutionProfile } from "../src/repl-profile.ts"; import { NO_PLUGINS } from "../src/plugin-host.ts"; import { resolveAgentStack } from "../src/agent-stack.ts"; +import type { AcpxProviderDependencies } from "@executablemd/acp"; import { createFakeAcp, makeRegistry, makeStore, tripwireAcp } from "./support/fake-acp.ts"; import type { FakeAcp } from "./support/fake-acp.ts"; import { ADAPTERS, AGENT } from "./support/plan-harness.ts"; @@ -464,6 +465,68 @@ describe("C1 — the command line this REPL runs under", () => { }); }); +describe("E9 — a compatibility warning is the entry's own Command stderr", () => { + beforeAll(() => useTempFileCompiler()); + + it("E9: the first live use of a session warns once in its entry, and a later entry does not repeat it", function* () { + const fake = createFakeAcp(); + fake.script({ reply: ANSWERED }); + fake.script({ reply: ANSWERED }); + const warnings = new Set(); + + yield* scoped(function* (): Operation { + const { page, hostRoot } = yield* beginJourney({ + fake, + size: WIDE, + acp: { + // An adapter whose executable this host selects but cannot ask its + // version: the warning the issue requires, from the real provider. + nativeAdapters: { + [AGENT]: { + launcher: AGENT, + identity: "provider-returned", + resume: () => [], + binding: { + command: AGENT, + version: () => undefined, + environment: () => ({}), + }, + }, + }, + advertiseNativeLaunch: [], + advertiseClientNativeAttachment: [], + compatibilityWarnings: warnings, + }, + }); + yield* submitted(page, 'first', 1); + yield* awaitedFact("entry 1 never settled", function* () { + return (yield* journal(hostRoot)).some((event) => event.type === "close"); + }); + yield* page.type("\x073"); + const shown = yield* page.until( + "the warning inside the entry's own reading", + (frame) => + frame.shows("Command stderr") && + frame.shows(`The ${AGENT} version could not be determined. Continuing.`), + ); + expect(shown.shows("Command stdout")).toBe(false); + expect(warnings.size).toBe(1); + expect(fake.prompts).toHaveLength(1); + yield* page.type("\x073"); + + yield* submitted(page, 'second', 2); + yield* awaitedFact("entry 2 never settled", function* () { + return (yield* journal(hostRoot)).filter((event) => event.type === "close").length >= 2; + }); + // The same session in the same invocation: the warning is not repeated, + // and the turn still ran. + expect(warnings.size).toBe(1); + expect(fake.prompts).toHaveLength(2); + yield* leave(page); + }); + }); +}); + function greetingSource(which: "First" | "Second"): string { const prop = `from${which}`; return [ @@ -1512,6 +1575,7 @@ function* useJourneyHost(options: { readonly includes?: readonly string[]; readonly planWriterRoot?: string; readonly permissionMode?: "approve-reads" | "deny-all"; + readonly acp?: Partial; }): Operation { const dataRoot = options.dataRoot ?? (yield* untilResolved(mkdtemp(join(tmpdir(), "xmd-repl-journey-")))); @@ -1537,6 +1601,7 @@ function* useJourneyHost(options: { options.held === undefined ? options.fake.create : options.held.create(options.fake), sessionStore: makeStore(), agentRegistry: makeRegistry({ [AGENT]: `${AGENT}-cmd` }), + ...options.acp, }, planWriterRoot: options.planWriterRoot ?? (yield* untilResolved(mkdtemp(join(tmpdir(), "xmd-repl-plan-")))), @@ -1563,6 +1628,7 @@ function* beginJourney(options: { readonly includes?: readonly string[]; readonly planWriterRoot?: string; readonly permissionMode?: "approve-reads" | "deny-all"; + readonly acp?: Partial; readonly workspace?: boolean; }): Operation<{ @@ -1580,6 +1646,7 @@ function* beginJourney(options: { ...(options.includes === undefined ? {} : { includes: options.includes }), ...(options.planWriterRoot === undefined ? {} : { planWriterRoot: options.planWriterRoot }), ...(options.permissionMode === undefined ? {} : { permissionMode: options.permissionMode }), + ...(options.acp === undefined ? {} : { acp: options.acp }), }); const page = yield* useReplPage({ host, diff --git a/packages/cli/tests/repl-sidekick-journey.test.ts b/packages/cli/tests/repl-sidekick-journey.test.ts index 6d1495439..3a5cd5b4f 100644 --- a/packages/cli/tests/repl-sidekick-journey.test.ts +++ b/packages/cli/tests/repl-sidekick-journey.test.ts @@ -5657,3 +5657,64 @@ describe("1342 — written Markdown in the chat and in entry Output", () => { expect(reopened.model.entries.map((entry) => entry.terminal?.output)).toEqual([ENTRY_MARKDOWN]); }); }); + +describe("E9 — a held conversation's compatibility warning beside its reply", () => { + it("E9: the warning is transient stderr in the Sidekick pane, once per invocation, and never history", function* () { + const warnings = new Set(); + const host = yield* useMountedHost({ + usageAcp: { + nativeAdapters: { + [MOUNTED_AGENT]: { + launcher: MOUNTED_AGENT, + identity: "provider-returned", + resume: () => [], + binding: { command: MOUNTED_AGENT, version: () => undefined, environment: () => ({}) }, + }, + }, + advertiseNativeLaunch: [], + advertiseClientNativeAttachment: [], + compatibilityWarnings: warnings, + }, + }); + const line = `The ${MOUNTED_AGENT} version could not be determined. Continuing.`; + yield* scoped(function* (): Operation { + const page = yield* useReplPage({ host, size: { columns: 160, rows: 60 } }); + const repl = page.repl; + repl.fake.script({ reply: "First answer.\n" }); + yield* sendMessage(page, "first question"); + yield* page.until("the reply", (one) => saidBySidekick(one, "First answer.")); + // Beside the reply, and still there once the turn has settled. + const settled = yield* page.until("the held warning beside the reply", (one) => + sidekickShows(one, `stderr: ${line}`), + ); + expect(sidekickShows(settled, "First answer.")).toBe(true); + + repl.fake.script({ reply: "Second answer.\n" }); + yield* sendMessage(page, "second question"); + yield* page.until("the second reply", (one) => saidBySidekick(one, "Second answer.")); + const later = page.screen(); + expect(later.occurrences(`stderr: ${line}`)).toBe(1); + expect(warnings.size).toBe(1); + expect(repl.fake.prompts).toHaveLength(2); + }); + // Display only: nothing durable — no chat record, generated source or + // failure — holds the warning. + const written: string[] = []; + function* readAll(directory: string): Operation { + if (!(yield* exists(directory))) { + return; + } + for (const name of yield* until(readdir(directory))) { + const path = join(directory, name); + if ((yield* until(stat(path))).isDirectory()) { + yield* readAll(path); + } else { + written.push(yield* readTextFile(path)); + } + } + } + yield* readAll(host.root); + expect(written.length).toBeGreaterThan(0); + expect(written.join("\n")).not.toContain("could not be determined"); + }); +}); diff --git a/packages/cli/tests/session-compatibility.test.ts b/packages/cli/tests/session-compatibility.test.ts new file mode 100644 index 000000000..0a62dbea5 --- /dev/null +++ b/packages/cli/tests/session-compatibility.test.ts @@ -0,0 +1,485 @@ +/** + * Session compatibility across agent CLI releases (#891). + * + * The production provider, installed the way a host installs it, over a + * controlled ACP runtime and executable observer. What these rows read is what + * an invocation would actually show on standard error and what it actually + * asked the agent to do: a version change warns once per logical session in one + * invocation and the retained conversation continues under the provider's live + * confirmation; nothing about a version admits or refuses. + */ + +import { describe, it } from "@executablemd/test-support/bdd"; +import { expect } from "@executablemd/test-support/expect"; +import { Stdio } from "@effectionx/process"; +import { all, scoped, until } from "effection"; +import type { Operation } from "effection"; +import { Agent } from "@executablemd/agent/api"; +import type { AcpxProvider, AcpxProviderDependencies } from "@executablemd/acp"; +import { embeddedAdapterDependencies } from "@executablemd/acp/embedded-adapters"; +import { useAcpxProvider } from "../../acp/src/provider.ts"; +import { createMemorySessionRouteStore } from "../../acp/src/session-route.ts"; +import type { AgentSessionRouteStore } from "../../acp/src/session-route.ts"; +import { + createFakeObserver, + createFakeRuntime, + makeCoordinator, + makeRegistry, + makeStore, + useFlatWorld, +} from "../../acp/tests/helpers.ts"; +import type { + CoordinatorHarness, + FakeObserverHarness, + FakeRuntimeHarness, +} from "../../acp/tests/helpers.ts"; +import { ADAPTERS } from "./support/plan-harness.ts"; + +const CWD = "/work"; + +/** What one product reports at two releases, and the selector it is chosen by. */ +const PRODUCTS = { + codex: { + name: "Codex", + before: "codex-cli 0.167.1\n", + after: "codex-cli 0.169.1\n", + variable: "CODEX_PATH", + command: "codex-cmd", + }, + claude: { + name: "Claude", + before: "2.1.241 (Claude Code)\n", + after: "2.1.250 (Claude Code)\n", + variable: "CLAUDE_CODE_EXECUTABLE", + command: "claude-cmd", + }, +} as const; + +type Product = keyof typeof PRODUCTS; + +/** The provider state one host keeps across its invocations. */ +interface Machine { + readonly store: ReturnType; + readonly routes: AgentSessionRouteStore; + readonly ownership: CoordinatorHarness; + readonly observer: FakeObserverHarness; +} + +function machine(product: Product): Machine { + return { + store: makeStore(), + routes: createMemorySessionRouteStore(), + ownership: makeCoordinator(), + observer: createFakeObserver({ + path: `/selected/${product}`, + versionOutput: PRODUCTS[product].before, + }), + }; +} + +/** Every line this scope's operations wrote to standard error. */ +function* stderr(fail?: Error): Operation { + const lines: string[] = []; + const decoder = new TextDecoder(); + yield* Stdio.around({ + // deno-lint-ignore require-yield + *stderr([bytes]) { + if (fail !== undefined) { + throw fail; + } + lines.push( + ...decoder + .decode(bytes) + .split("\n") + .filter((line) => line.length > 0), + ); + }, + // deno-lint-ignore require-yield + *stdout() { + throw new Error("a compatibility diagnostic reached standard output"); + }, + }); + return lines; +} + +/** + * Install one provider for `product` over this host's state, as the CLI does: + * the built-in adapter, the host's own selection, and the invocation's set. + */ +let provider: AcpxProvider | undefined; + +function* install( + product: Product, + host: Machine, + harness: FakeRuntimeHarness, + extra: Partial = {}, +): Operation { + const { variable, command } = PRODUCTS[product]; + // The agent a Prompt that names none means, as the installed chain answers it. + yield* Agent.around( + { + // deno-lint-ignore require-yield + *agent([name]) { + return name ?? product; + }, + }, + { at: "min" }, + ); + provider = yield* useAcpxProvider( + { defaultAgent: product, permissionMode: "deny-all" }, + { + createRuntime: harness.create, + sessionStore: host.store, + agentRegistry: makeRegistry({ [product]: command }), + coordinator: host.ownership.coordinator, + routeStore: host.routes, + executableObserver: host.observer.observer, + advertiseNativeLaunch: [product], + advertiseClientNativeAttachment: product === "claude" ? ["claude"] : [], + // deno-lint-ignore require-yield + *agentProcessEnv() { + return { [variable]: `/selected/${product}` }; + }, + ...extra, + }, + ); +} + +/** Run one Prompt to completion and return its text. */ +function* prompt(text: string, session = "review"): Operation { + return yield* scoped(function* () { + if (provider === undefined) { + throw new Error("no provider is installed"); + } + const subscription = yield* provider.promptStream(text, { session }); + let next = yield* subscription.next(); + while (!next.done) { + next = yield* subscription.next(); + } + return next.value; + }); +} + +/** Establish a session in one invocation, under the release recorded as its history. */ +function* establish(product: Product, host: Machine, session = "review"): Operation { + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install(product, host, createFakeRuntime(), { + compatibilityWarnings: new Set(), + }); + yield* prompt("seed", session); + expect(lines).toEqual([]); + }); +} + +function changed(product: Product): string { + const { name } = PRODUCTS[product]; + const [from, to] = + product === "codex" ? ["0.167.1", "0.169.1"] : (["2.1.241", "2.1.250"] as const); + return ( + `${name} has changed from ${from} to ${to} since this session was established. ` + + `Continuing the existing conversation.` + ); +} + +describe("SC — a CLI release change warns and continues", () => { + for (const product of ["codex", "claude"] as const) { + it(`SC1 (${product}): an upgraded executable continues the retained conversation and warns once`, function* () { + const host = machine(product); + yield* establish(product, host); + const established = yield* until(host.store.load([...host.store.records.keys()][0]!)); + expect(established?.agentSessionId).toBeDefined(); + const route = yield* host.routes.read({ + provider: "acpx", + agent: PRODUCTS[product].command, + sessionKey: established!.acpxRecordId, + }); + expect(route?.schema).toBe("session-route.v3"); + + host.observer.observation.versionOutput = PRODUCTS[product].after; + host.observer.observation.digest = "b".repeat(64); + const harness = createFakeRuntime(); + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install(product, host, harness, { + compatibilityWarnings: new Set(), + }); + + yield* prompt("first after the upgrade"); + yield* prompt("second after the upgrade"); + + // One warning, before the live work it concerns, and no repetition. + expect(lines).toEqual([changed(product)]); + }); + // Each operation reopened the exact retained conversation and required + // the provider's live confirmation of its native identity first. + expect(harness.ensureCalls.length).toBeGreaterThan(0); + for (const call of harness.ensureCalls) { + expect(call.resumeSessionId).toBe(established?.acpSessionId); + expect(call.expectedAgentSessionId).toBe(established?.agentSessionId); + expect(call.materialization).toBe(undefined); + } + expect(harness.turns.map((turn) => turn.input.text)).toEqual([ + "first after the upgrade", + "second after the upgrade", + ]); + // Through the executable the current environment selected. + expect(harness.createdOptions[0]?.agentProcessEnv).toEqual({ + [PRODUCTS[product].variable]: `/selected/${product}`, + }); + // History is not rewritten to claim today's executable made it. + expect( + yield* host.routes.read({ + provider: "acpx", + agent: PRODUCTS[product].command, + sessionKey: established!.acpxRecordId, + }), + ).toEqual(route); + }); + } + + it("SC2: one invocation set spans installations; a second session and a new invocation each warn", function* () { + const host = machine("codex"); + yield* establish("codex", host, "review"); + yield* establish("codex", host, "build"); + host.observer.observation.versionOutput = PRODUCTS.codex.after; + + const invocation = new Set(); + const runs: string[][] = []; + for (const installation of ["root", "nested"]) { + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, createFakeRuntime(), { + compatibilityWarnings: invocation, + }); + yield* prompt(`${installation} review`, "review"); + if (installation === "nested") { + yield* prompt("nested build", "build"); + } + runs.push(lines); + }); + } + // The nested installation shares the invocation's set: the reviewed session + // is not repeated, and the second session gets its own warning. + expect(runs).toEqual([[changed("codex")], [changed("codex")]]); + expect(invocation.size).toBe(2); + + // A new invocation starts with nothing and may warn again. + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, createFakeRuntime(), { + compatibilityWarnings: new Set(), + }); + yield* prompt("next invocation", "review"); + expect(lines).toEqual([changed("codex")]); + }); + }); + + it("SC3: distinct placements of one session name warn separately", function* () { + const host = machine("codex"); + for (const cwd of ["/work/a", "/work/b"]) { + yield* scoped(function* () { + yield* useFlatWorld(cwd); + yield* install("codex", host, createFakeRuntime(), { + compatibilityWarnings: new Set(), + }); + yield* prompt("seed", "review"); + }); + } + host.observer.observation.versionOutput = PRODUCTS.codex.after; + const invocation = new Set(); + const shown: string[] = []; + for (const cwd of ["/work/a", "/work/b"]) { + yield* scoped(function* () { + yield* useFlatWorld(cwd); + const lines = yield* stderr(); + yield* install("codex", host, createFakeRuntime(), { + compatibilityWarnings: invocation, + }); + yield* prompt("continue", "review"); + shown.push(...lines); + }); + } + expect(shown).toEqual([changed("codex"), changed("codex")]); + }); + + it("SC4: an embedding host that omits the set gets one per installation", function* () { + const host = machine("codex"); + yield* establish("codex", host); + host.observer.observation.versionOutput = PRODUCTS.codex.after; + const shown: string[] = []; + for (const _ of [1, 2]) { + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, createFakeRuntime()); + yield* prompt("continue"); + yield* prompt("again"); + shown.push(...lines); + }); + } + expect(shown).toEqual([changed("codex"), changed("codex")]); + }); + + it("SC5: concurrent first uses of one session deliver one warning", function* () { + const host = machine("codex"); + yield* establish("codex", host, "review"); + yield* establish("codex", host, "build"); + host.observer.observation.versionOutput = PRODUCTS.codex.after; + const invocation = new Set(); + const shown: string[] = []; + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, createFakeRuntime(), { + compatibilityWarnings: invocation, + }); + yield* all([prompt("one", "review"), prompt("two", "review"), prompt("three", "build")]); + shown.push(...lines); + }); + expect(shown).toEqual([changed("codex"), changed("codex")]); + expect(invocation.size).toBe(2); + }); + + it("SC6: a diagnostic that cannot be written is a host I/O failure, never model work", function* () { + const host = machine("codex"); + yield* establish("codex", host); + host.observer.observation.versionOutput = PRODUCTS.codex.after; + const harness = createFakeRuntime(); + let raised: Error | undefined; + yield* scoped(function* () { + yield* useFlatWorld(CWD); + yield* stderr(new Error("standard error is closed")); + yield* install("codex", host, harness, { + compatibilityWarnings: new Set(), + }); + try { + yield* prompt("continue"); + } catch (error) { + raised = error as Error; + } + }); + expect(raised?.message).toBe("standard error is closed"); + // Nothing was reopened, replaced or retried on its account. + expect(harness.ensureCalls).toEqual([]); + expect(harness.turns).toEqual([]); + }); +}); + +describe("SV — what a version observation can and cannot say", () => { + it("SV1: unrecognized or private version output says only that it is undetermined", function* () { + const host = machine("codex"); + yield* establish("codex", host); + host.observer.observation.versionOutput = "codex-cli 0.169.1 built at /home/private/secret\n"; + const harness = createFakeRuntime(); + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, harness, { + compatibilityWarnings: new Set(), + }); + expect(yield* prompt("continue")).toBe("hello world"); + expect(lines).toEqual(["The Codex version could not be determined. Continuing."]); + expect(lines.join("\n")).not.toContain("/home/private"); + expect(lines.join("\n")).not.toContain("/selected"); + }); + expect(harness.turns).toHaveLength(1); + }); + + it("SV2: a fresh session under a release no evidence names works, with no warning", function* () { + const host = machine("claude"); + host.observer.observation.versionOutput = "9.0.0 (Claude Code)\n"; + const harness = createFakeRuntime(); + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("claude", host, harness, { + compatibilityWarnings: new Set(), + }); + expect(yield* prompt("first")).toBe("hello world"); + expect(lines).toEqual([]); + }); + }); + + it("SV3: history without a recorded version continues without a difference warning", function* () { + const host = machine("codex"); + yield* establish("codex", host); + // Rewritten here only to stand for a session established before XMD kept + // executable history: the released unbound form of the same route. + const key = [...host.store.records.keys()][0]!; + const tuple = { + provider: "acpx", + agent: PRODUCTS.codex.command, + sessionKey: key, + }; + const legacy = createMemorySessionRouteStore(); + yield* legacy.publish({ + schema: "session-route.v1", + route: "acp-first", + ...tuple, + }); + const before = yield* legacy.read(tuple); + host.observer.observation.versionOutput = PRODUCTS.codex.after; + const harness = createFakeRuntime(); + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", { ...host, routes: legacy }, harness, { + compatibilityWarnings: new Set(), + }); + expect(yield* prompt("continue")).toBe("hello world"); + expect(lines).toEqual([]); + }); + expect(harness.ensureCalls[0]?.expectedAgentSessionId).toBeDefined(); + expect(yield* legacy.read(tuple)).toEqual(before); + }); + + it("SV4: a custom command named codex keeps its own command and selects nothing", function* () { + const host = machine("codex"); + const { agentProcessEnv } = embeddedAdapterDependencies(ADAPTERS); + const harness = createFakeRuntime(); + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, harness, { + agentRegistry: makeRegistry({ codex: "my-wrapper --acp" }), + ...(agentProcessEnv === undefined ? {} : { agentProcessEnv }), + compatibilityWarnings: new Set(), + }); + expect(yield* prompt("through the wrapper")).toBe("hello world"); + // The wrapper's backend is not guessed at: its version is undetermined. + expect(lines).toEqual(["The Codex version could not be determined. Continuing."]); + }); + expect(host.observer.observed).toEqual([]); + const options = harness.createdOptions.at(-1); + expect(options?.agentRegistry.resolve("codex")).toBe("my-wrapper --acp"); + expect(options?.agentProcessEnv ?? {}).toEqual({}); + expect(harness.turns).toHaveLength(1); + }); + + it("SV5: a selected executable that cannot run is an availability failure", function* () { + const host = machine("codex"); + host.observer.failure = "not-found"; + const harness = createFakeRuntime(); + let raised: Error | undefined; + yield* scoped(function* () { + yield* useFlatWorld(CWD); + const lines = yield* stderr(); + yield* install("codex", host, harness, { + compatibilityWarnings: new Set(), + }); + try { + yield* prompt("first"); + } catch (error) { + raised = error as Error; + } + expect(lines).toEqual([]); + }); + expect(raised?.message).toContain("is unavailable"); + expect(harness.ensureCalls).toEqual([]); + }); +}); diff --git a/packages/cli/tests/support/mounted-repl.ts b/packages/cli/tests/support/mounted-repl.ts index 2089c793c..214148033 100644 --- a/packages/cli/tests/support/mounted-repl.ts +++ b/packages/cli/tests/support/mounted-repl.ts @@ -812,6 +812,8 @@ export function* useMountedHost( | "agentRegistry" | "advertiseNativeLaunch" | "advertiseClientNativeAttachment" + | "nativeAdapters" + | "compatibilityWarnings" >; readonly agentCwd?: AcpxProviderDependencies["agentCwd"]; } = {}, diff --git a/packages/cli/tests/workflow-agent-sessions.test.ts b/packages/cli/tests/workflow-agent-sessions.test.ts index 090629c48..1f225e8b0 100644 --- a/packages/cli/tests/workflow-agent-sessions.test.ts +++ b/packages/cli/tests/workflow-agent-sessions.test.ts @@ -413,7 +413,15 @@ function* hostClaudeWorkflow( env: { PATH: bin, CLAUDE_CODE_EXECUTABLE: selected }, }); }); - expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ exitCode: 0, stderr: "" }); + // An unfamiliar version is reported once, before the live work it concerns, + // and the work continues; completed replay in the same invocation adds + // nothing. An unavailable executable is an availability failure instead. + expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ + exitCode: 0, + stderr: ["missing", "invalid", "unlaunchable"].includes(mode) + ? "" + : "The Claude version could not be determined. Continuing.\n", + }); const report = JSON.parse(yield* readTextFile(join(root, "report.json"))); expect(yield* exists(staleLog)).toBe(false); expect(yield* exists(pathLog)).toBe(false); @@ -501,7 +509,8 @@ type HostCodexMode = | "invalid" | "unlaunchable" | "effort" - | "no-selector"; + | "no-selector" + | "versioned"; /** * One production workflow Prompt through the carried Codex adapter, with the @@ -524,7 +533,9 @@ function* hostCodexWorkflow(mode: HostCodexMode): Operation { "#!/usr/bin/env node", `process.env.FAKE_CODEX_LOG = ${JSON.stringify(log)};`, `process.env.FAKE_CODEX_CATALOG = ${JSON.stringify(catalog)};`, - 'if (process.argv.includes("--version")) { console.log("unfamiliar development build"); process.exit(0); }', + `if (process.argv.includes("--version")) { console.log(${JSON.stringify( + mode === "versioned" ? "codex-cli 0.169.1" : "unfamiliar development build", + )}); process.exit(0); }`, `require("node:fs").appendFileSync(${JSON.stringify(log)}, JSON.stringify({ launched: process.argv.slice(2) }) + "\\n");`, fake, ].join("\n"); @@ -577,7 +588,14 @@ function* hostCodexWorkflow(mode: HostCodexMode): Operation { env: mode === "path" ? { PATH: bin } : { PATH: bin, CODEX_PATH: override ?? "" }, }); }); - expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ exitCode: 0, stderr: "" }); + expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ + exitCode: 0, + stderr: ["missing", "invalid", "unlaunchable"].includes(mode) + ? "" + : mode === "versioned" + ? "" + : "The Codex version could not be determined. Continuing.\n", + }); const report = JSON.parse(yield* readTextFile(join(root, "report.json"))); expect(report.environmentPreserved).toBe(true); const selectedRan = ["explicit", "relative", "bare"].includes(mode); @@ -646,6 +664,8 @@ describe("H host Codex through the production workflow", () => { hostCodexWorkflow("effort")); it("H4: a host without the model's effort selector refuses with no turn", () => hostCodexWorkflow("no-selector")); + it("H5: a release absent from recorded evidence works and is observed without a warning", () => + hostCodexWorkflow("versioned")); }); describe("workflow ACP loading identity", { sanitizeOps: false, sanitizeResources: false }, () => { diff --git a/packages/runtime/apis.ts b/packages/runtime/apis.ts index 693a1995f..33ee50784 100644 --- a/packages/runtime/apis.ts +++ b/packages/runtime/apis.ts @@ -905,3 +905,17 @@ export const compile: typeof API.Env.operations.compile = API.Env.operations.com export function useQuietProcessOutput(): Operation { return Stdio.around({ *stdout() {} }, { at: "min" }); } + +/** + * Write one diagnostic line to the contextual standard error. + * + * Through the same `Stdio` chain a subprocess's stderr travels, so whatever the + * enclosing scope installed — a REPL entry's Command stderr, a held + * conversation's transient reading, or the process stream itself — receives it + * in order with the rest of that scope's diagnostics. Standard output is never + * touched, which keeps a machine-readable result intact. + */ +export function writeDiagnostic(text: string): Operation { + const line = text.endsWith("\n") ? text : `${text}\n`; + return Stdio.operations.stderr(new TextEncoder().encode(line)); +} diff --git a/packages/runtime/executable-observer.ts b/packages/runtime/executable-observer.ts index a7cd9d454..5eeaf62f8 100644 --- a/packages/runtime/executable-observer.ts +++ b/packages/runtime/executable-observer.ts @@ -2,28 +2,21 @@ * Observing which executable build a command actually runs * (specs/native-agent-session-launch-spec.md §Executable binding). * - * A provider session whose identity XMD chose itself only means something - * while the build that established it can be reproduced. Two builds of one - * provider accept the same session identity and disagree silently about what - * it names — that is how issue #519's first gate produced a healthy-looking - * session with no history in it. So before a session crosses an ownership - * boundary, the exact file about to run is observed, and enough is retained to - * recognize it later. - * * What is observed is a canonical path, the SHA-256 of that file's bytes, and * whatever the file says when asked its version. Only the last two ever become - * durable: a path stops being true when a build moves, and names host layout - * besides. + * durable, as diagnostic history beside a session XMD constructs: a path stops + * being true when a build moves, and names host layout besides. A host asks + * this about the file it already selected; the observation reports, and never + * decides whether a conversation continues. * * This is a plain capability the trusted host builds and hands directly to the - * provider that needs it. It is deliberately not a contextual Api. Executable - * validation decides which retained history is accepted, and a decision - * document middleware could replace is not one — a replaceable resolver could - * point the observation at a different binary than the one that runs. + * provider that needs it. It is deliberately not a contextual Api: a + * replaceable resolver could point the observation at a different binary than + * the one that runs. * * Provider-specific meaning is not this module's business: which command to - * run, what a version string looks like, and what to do about a mismatch - * belong to the adapter that knows the provider. + * run and what a version string looks like belong to the adapter that knows the + * provider. */ import type { Operation } from "effection"; diff --git a/packages/runtime/mod.ts b/packages/runtime/mod.ts index 46daef97a..205066d15 100644 --- a/packages/runtime/mod.ts +++ b/packages/runtime/mod.ts @@ -48,6 +48,7 @@ export { command, compile, useQuietProcessOutput, + writeDiagnostic, } from "./apis.ts"; export type { DirectoryEntry, diff --git a/packages/runtime/tests/executable-observer.test.ts b/packages/runtime/tests/executable-observer.test.ts index b48d85354..e808e8cb7 100644 --- a/packages/runtime/tests/executable-observer.test.ts +++ b/packages/runtime/tests/executable-observer.test.ts @@ -186,3 +186,42 @@ describe("Tier EO — executable observation", () => { expect(Object.keys(observed).sort()).toEqual(["digest", "path", "versionOutput"]); }); }); + +describe("Tier EO — observing the file a host already selected (#891)", () => { + it("EO-S1: a replaced file at one path and identical bytes at another are each what they are", function* () { + if (!hasDenoExecutableObserver()) { + return; + } + const root = yield* workspace(); + const observer = createDenoExecutableObserver(); + if (observer === undefined) { + throw new Error("a Deno host observes executables"); + } + // The host's selection is an exact path; the observer is asked about that + // file and searches nothing. + const selected = yield* script(root, "codex", "codex-cli 0.167.1"); + const first = yield* observer.observe(selected); + expect(first.path).toBe(yield* canonical(selected)); + + // Upgraded in place: the same path, other bytes, another version. + yield* writeTextFile(selected, `#!/bin/sh\necho "codex-cli 0.169.1"\n`); + const replaced = yield* observer.observe(selected); + expect(replaced.path).toBe(first.path); + expect(replaced.digest.value).not.toBe(first.digest.value); + expect(replaced.versionOutput.trim()).toBe("codex-cli 0.169.1"); + + // Identical bytes reached through another path: another path, one digest. + const moved = path.join(root, "elsewhere"); + yield* ensureDir(moved); + const copy = yield* script(moved, "codex", "codex-cli 0.169.1"); + const elsewhere = yield* observer.observe(copy); + expect(elsewhere.path).not.toBe(replaced.path); + expect(elsewhere.digest).toEqual(replaced.digest); + + // A digest-only change keeps the version it reports. + yield* writeTextFile(copy, `#!/bin/sh\n# rebuilt\necho "codex-cli 0.169.1"\n`); + const rebuilt = yield* observer.observe(copy); + expect(rebuilt.digest.value).not.toBe(elsewhere.digest.value); + expect(rebuilt.versionOutput).toBe(elsewhere.versionOutput); + }); +}); diff --git a/specs/acp-client-spec.md b/specs/acp-client-spec.md index f9d842e96..da615a7d0 100644 --- a/specs/acp-client-spec.md +++ b/specs/acp-client-spec.md @@ -265,17 +265,21 @@ there is no ownership format selection or compatibility reader. Recovery sends no provider request and repairs no identity, route or journal. The host also passes in a **construction-route store** and an **executable -observer**, directly and from the same trusted root as the coordinator. Both -are required only for an advertised agent whose adapter binds a build. Which -side chose the identity does not decide that: whoever named the session, the -name resolves to one conversation only beside the build that issued or -accepted it, so an adapter that pins a build needs a route to say how the -session was constructed and an observer to say which build that was. An -adapter that binds nothing keeps its behavior unchanged on a host that has -neither. A host missing either refuses that agent before any provider effect, -on the same terms as a missing coordinator. The observer is not a contextual -Api for the same reason the coordinator is not: executable validation decides -which retained history may be accepted. +observer**, directly and from the same trusted root as the coordinator. The +route store is required for an advertised agent whose adapter carries an +executable binding, and a host missing it refuses that agent before any +provider effect, on the same terms as a missing coordinator. The observer is +diagnostic: it reports the version and digest of the executable the current +environment selected, and a host without one continues with the version +reported as undetermined. Neither is a contextual Api, so document middleware +cannot point the observation at one binary while the run spawns another. + +XMD uses the executable selected by the current environment and opens the +retained provider conversation. It requires the provider to confirm the same +native conversation identity. A version or digest change does not refuse +continuation. Missing required confirmation, a different identity or a real +resume failure stops the operation without creating a replacement +conversation. Historical executable observations remain unchanged. While ownership is held and before any provider construction effect, the provider reconciles the route. A fresh `session()` places the session and @@ -286,32 +290,37 @@ fails afterwards leaves that route standing. A launch by an adapter that names its own sessions publishes `client-native` under an identity that adapter allocated, unless existing durable ACPX state or an existing route says the session was constructed through ACP — in which case it publishes or adopts -`acp-first` and retains `identity-unavailable`. A launch by an adapter that -binds a build and lets the provider name the session publishes or adopts the -**bound** `acp-first` form, carrying the build it just observed, before ACP -creates anything; an existing unbound `acp-first` record refuses rather than -gaining the current executable. Publication is create-once, so the loser of +`acp-first` and retains `identity-unavailable`. A fresh `acp-first` +route for an adapter with an executable binding is published in the **bound** +form, carrying the complete observation of the selected executable as its +history, before ACP creates anything; with no complete observation it is +published unbound. An existing route is never rewritten: an unbound record +stays unbound and continues. Publication is create-once, so the loser of either order adopts the winner, and no route converts. -A `session()` or subscribed `prompt()` meeting a **bound** `client-native` -route **attaches** to it. Under the same ownership it reobserves the build and -compares the binding exactly, requires any retained ACP arrangement to assert -that route's identity, selects the runtime for (resolved agent command, -binding), calls `ensureSession()` with `resumeSessionId` equal to that -identity, and requires the returned canonical assertion to equal it before a -turn. The observed executable path reaches only that runtime's transient child -environment. A legacy unbound `client-native` route, an agent this host has not -advertised for attachment, build drift, a disagreeing arrangement and a -differing returned identity each refuse before a turn and create no substitute -conversation. +A `session()` or subscribed `prompt()` meeting a `client-native` route, +bound or legacy unbound, **attaches** to it. Under the same ownership it +selects the current executable, requires any retained ACP arrangement to +assert that route's identity, selects the runtime for (resolved agent command, +selected environment) and calls `ensureSession()` with `resumeSessionId` equal +to that identity. An existing ACP record is reopened strictly with +`expectedAgentSessionId` equal to the route's identity. With no record, the +exact load carries no expectation that presupposes one; the returned canonical +assertion must equal the route's identity, and a refused first arrangement is +left asserting nothing so a later exact retry is not blocked by it. Either way +the assertion is confirmed before settings or a turn. The selected executable +path reaches only that runtime's transient child environment. An agent this +host has not advertised for attachment, a disagreeing arrangement and a +missing or differing returned identity each refuse before a turn and create no +substitute conversation. A held conversation is owned and routed where it began. Its coordinator key and its construction route use the provider and resolved command of the history's initial configuration record with the recorded placement, before a Prompt records one with the placement the provider resolves, and the first setup with no initial record uses today's coordinates. Today's command still -drives everything that executes: runtime selection, executable observation and -the bound-build comparison, and usage reporting. So a conversation whose adapter +drives everything that executes: runtime selection, executable selection and +observation, and usage reporting. So a conversation whose adapter command changed between releases keeps one owner, one route and its original construction provenance, and an earlier owner still holding that original tuple refuses the changed-command contender before any ensure, prompt or route @@ -877,6 +886,14 @@ history nor starts a fresh conversation after uncertain acceptance. Reconnection first establishes the exact original live child; missing identity or outcome remains uncertain and never authorizes resend. +A held conversation's work executes through its captured provider in the +conversation's own task, so diagnostic capture is installed in that owning +task before `useAgentConversation()`; middleware around the caller of a turn +does not move queued work into the caller's scope. A compatibility warning a +reopened conversation owes is therefore delivered to the host that holds it, +and continuation follows the same confirmation and refusal policy as an +ordinary Session. + ```ts const opened = yield* useAgentConversation({ history, // the DurableStream holding this conversation's canonical history @@ -1026,8 +1043,8 @@ adapter a host runs — the bundled Codex adapter became the host-installed one while the conversation it continues is the same native history, so the current adapter is attempted on that history. What the provider actually applies is verified where it applies it (§Session configuration), and a genuine resume, -assertion, build or configuration failure still fails the turn without a -replacement conversation or a new prompt. A reopening on its own performs no +assertion or configuration failure still fails the turn without a replacement +conversation or a new prompt. A version change is reported, never a failure. A reopening on its own performs no activation and no provider work at all; the configuration record is re-offered in its own position so the turns written after it replay in order, and it is never rewritten. The record is configuration, not identity: an absent Prompt @@ -1532,8 +1549,11 @@ machine-wide account of ownership, construction routes and executable builds describes a different thing entirely. Inheriting the package's advertised sets by omission would make an ordinary workflow Claude prompt demand machine ownership and a route this profile has no way to give it. The profile therefore -supplies no session coordinator, no route store and no executable observer, and -never consults their namespace. +supplies no session coordinator and no route store, and never consults their +namespace. A host may supply an executable observer for diagnostics only: it +reports the version of the executable the run's selection chose, grants no +native capability and admits nothing. A workflow session keeps no executable +history, so it warns only when the current version cannot be determined. A native permission request under this profile does not reach `Agent.requestPermission`. The provider answers it: a reject option when ACP @@ -1866,6 +1886,38 @@ model prompt; the SDK executable is never a fallback. Version output is observation rather than an admission condition. Custom agent commands retain their own selection, and completed replay performs no selection or launch. +The provider retains the selected path before it asks the observer anything, +observes that same file and executes it through the transient child +environment and native argv. It never resolves the launcher name again on the +observer's own PATH. A version that cannot be asked or read leaves no current +build binding and keeps the selection; a missing, non-file or non-executable +selection is an availability failure. A command the host configured other than +the carried adapter is never replaced by it because the agent shares a name: +its backend is not guessed at, so its version is undetermined, and actual +protocol, capability and identity results decide whether it works. + +Before affected live work, XMD warns once per logical session in the current +invocation when the observed version differs from its historical observation. +If the current version cannot be determined, it reports that once and +continues otherwise supported work. Missing historical metadata alone +establishes no observed difference. Diagnostics use stderr and leave +machine-readable stdout unchanged. Completed replay performs no executable +observation and emits no new compatibility warning. + +The warning reads ` has changed from to since this session +was established. Continuing the existing conversation.` with normalized product +versions, or `The version could not be determined. Continuing.`; raw +version output and paths are never displayed. It is written through the +contextual `Stdio` stderr of the task performing the work. The CLI owns one +transient set per invocation and passes the same reference to every provider +it installs as `AcpxProviderDependencies.compatibilityWarnings`; a host that +omits it gives each installation its own. A provider keys a warning by its +private logical placement — provider, original owner command, session key and +placement directory — and claims it synchronously before yielding delivery. +The set admits nothing and is never serialized. A failed diagnostic write is an +ordinary host I/O failure; it authorizes no replacement and no retry of model +work. + For the retained embedded Codex adapter, live availability selects nonempty `CODEX_PATH`, otherwise `codex` on the host PATH. Relative path selections resolve against the host execution directory. Selection resolves to a canonical @@ -1875,8 +1927,7 @@ PATH or correct `CODEX_PATH`. A bad explicit selection does not retry the default command. Version output and exit status impose no ordinary version admission policy. No bundled CLI or download supplies a fallback. Custom commands retain their selection; completed replay performs no host selection or -launch. Native-bound work uses its observed executable under the native -build-binding contract. [Decision 004](decisions/004-host-installed-codex-cli.md) +launch. Native work uses the same selected executable. [Decision 004](decisions/004-host-installed-codex-cli.md) records why Codex runs the host CLI. ## ACPX provider @@ -2001,25 +2052,27 @@ its caller supplied, from Prompt `timeout` or the enclosing AgentProvider Reopening loads/resumes the exact stored ACP id. ACPX reuses a persistent record in place only for the same command string and argv that created it, - and would otherwise create a fresh conversation under the same key, so a - held conversation's non-pending record is always ensured with + and would otherwise create a fresh conversation under the same key, so an + established non-pending record — a held conversation's, or any ordinary or + workflow session of a built-in adapter — is always ensured with `resumeSessionId` equal to that record's ACP loading target, through today's command and in the record's own directory, under the conversation's queue and ownership: a record ACPX can reuse in place is reused, and any other is loaded, whether the adapter changed or the same command changed from an argv - array to its string. The loading target is not the native identity: the returned - native assertion, when the adapter reports one, must equal the one the - history's Prompt records assert, or — before the host acknowledged one — the - one the provider's promoted record asserts. A pending record supplies - neither. For an established Codex conversation held by a host such as Sidekick, - a different observed executable version or digest requires a live load on - the current build before applying settings or sending a prompt. The live - response must assert the retained native identity; an omitted assertion does - not inherit the saved identity. The same check applies if the runtime has - to reconnect again during the operation. The ACP record retains its history - and saved preferences, and the original construction route is unchanged. - The exact-build rule still applies to explicit native launch and attachment. - A failed load uses the ordinary resume error. A different native identity, + array to its string. The loading target is not the native identity. The retained native + assertion is the one the history's Prompt records assert, or — before the + host acknowledged one — the one the provider's promoted record asserts, and + the ensure carries it as `expectedAgentSessionId`, whether or not the + executable changed. A pending first-turn record is occupancy rather than an + established conversation and keeps its acceptance and promotion order. An + established session of an adapter that owes a native identity, with no + retained assertion, refuses before loading. The live response must assert + the retained native identity before settings are applied or a prompt is + sent; an omitted assertion does not inherit the saved identity. The same + check applies to a cold reconnect during the operation, and it costs no + model turn. The ACP record retains its history and saved preferences, and + the original construction route is unchanged. Native launch and attachment + follow the same policy. A failed load uses the ordinary resume error. A different native identity, or an omitted identity when live confirmation is required, refuses with `identity-unavailable`. A refusal at ensure sends no `session/new` or prompt and leaves the record, history and route as they were. If a client disconnects diff --git a/specs/decisions.md b/specs/decisions.md index a6e8e8095..d6d7c8a6e 100644 --- a/specs/decisions.md +++ b/specs/decisions.md @@ -16,6 +16,7 @@ conformance belong to [the language specification](executable-mdx-spec.md). | Main health and verification ownership | [DEC-013](#dec-013-a-red-main-is-reported-as-an-issue-and-gates-pull-requests-no-merge-queue), [DEC-014](#dec-014-composability-proves-ownership-not-correctness-a-second-time), and [contribution verification](../AGENTS.md#verification). | | Withdrawn terminal-grid surface | [DEC-016](#dec-016-withdraw-the-unimplemented-terminal-grid-surface); [installed structural syntax](../architecture.md#the-installed-structural-syntax-boundary) remains the extension boundary. | | Host-installed Codex CLI for the carried adapter | [Decision record 004](decisions/004-host-installed-codex-cli.md); [ACP Availability](acp-client-spec.md#availability), [Adapter snapshots](acp-client-spec.md#adapter-snapshots) and [the maintained Codex adapter](release-process-spec.md#maintained-codex-adapter) own current behavior. | +| Session continuation across agent CLI releases | [Decision record 005](decisions/005-current-executable-session-continuation.md); [ACP client sessions](acp-client-spec.md#sessions-ownership-routes-and-attachment) and [native launch executable binding](native-agent-session-launch-spec.md#executable-build-binding) own current behavior. | --- diff --git a/specs/decisions/004-host-installed-codex-cli.md b/specs/decisions/004-host-installed-codex-cli.md index 7c64b1d12..0edae7204 100644 --- a/specs/decisions/004-host-installed-codex-cli.md +++ b/specs/decisions/004-host-installed-codex-cli.md @@ -43,9 +43,11 @@ Updating the host CLI can change ordinary availability and the advertised model and effort catalog while the adapter digest stays the same. A session offers whatever the selected host CLI reports. -Native launch and attachment keep strict build equality. For a held Codex -conversation over ACP, the [ACP client contract](../acp-client-spec.md#acpx-provider) -requires live confirmation of the original native identity after a host upgrade. +A session continues on whichever host CLI is selected today, under the +provider's live confirmation of its original native identity, for every +operation including native launch and attachment. The strict build equality +this record first kept for native work was replaced by +[decision record 005](005-current-executable-session-continuation.md). The repacked snapshot has a new digest. It neither migrates saved records nor equates the old and new snapshot identities. diff --git a/specs/decisions/005-current-executable-session-continuation.md b/specs/decisions/005-current-executable-session-continuation.md new file mode 100644 index 000000000..1410d1edc --- /dev/null +++ b/specs/decisions/005-current-executable-session-continuation.md @@ -0,0 +1,81 @@ +# Sessions continue on the current executable + +Date: 2026-11-18 + +Approved through issue [#891](https://github.com/taras/executable.md/issues/891). + +## Context + +A Codex desktop update replaced `codex-cli 0.167.1` with `0.169.1`, and XMD +refused the next prompt of an ordinary workflow role Session: the conversation +had been created by the old version and could not be confirmed under the new +one. Native launch, client-native attachment and incomplete replay imposed the +same exact-build binding, and advertisement rested on the specific releases an +integration proof had run against. Only a held Codex conversation could +continue after an upgrade, through a narrower exception. + +A build observation cannot tell whether a conversation is the same one. The +provider's live assertion of the native identity can, and ACPX already carries +a verified reopen that requires it. + +## Decision + +XMD uses the executable selected by the current environment and opens the +retained provider conversation. It requires the provider to confirm the same +native conversation identity. A version or digest change does not refuse +continuation. Missing required confirmation, a different identity or a real +resume failure stops the operation without creating a replacement +conversation. Historical executable observations remain unchanged. + +Ordinary Session and Prompt, held conversations, native launch, client-native +attachment and incomplete replay share this one policy; there is no opt-in flag +and no separate held policy. A native handoff is confirmed over ACP — before a +native resume, and after a fresh client-allocated creation once the child has +joined. Exit status never confirms identity. A selected executable that is +missing or cannot run remains an availability failure. + +Before affected live work, XMD warns once per logical session in the current +invocation when the observed version differs from its historical observation. +If the current version cannot be determined, it reports that once and +continues otherwise supported work. Missing historical metadata alone +establishes no observed difference. Diagnostics use stderr and leave +machine-readable stdout unchanged. Completed replay performs no executable +observation and emits no new compatibility warning. + +The invocation owns the warning state. `AcpxProviderDependencies` gains one +member, `compatibilityWarnings?: Set`: the CLI shares one transient set +across every provider installation of an invocation, and a host that omits it +gives each installation its own. Delivery uses the contextual `Stdio` stderr of +the task doing the work; no Agent operation or callback was added. + +Recorded CLI, adapter and host versions describe the checks that ran. They are +evidence, not an allowlist or a requirement to repeat certification for every +release. The existing live documents remain opt-in integration regressions for +initial use, original-context continuity and native handoff where supported. +Actual protocol capabilities and provider-native identity assertions remain +required. + +## Consequences + +Updating an agent CLI no longer requires a new XMD release, a downgrade or a +replacement conversation. A user sees one warning naming both versions. + +Routes and journals keep the observation recorded when their session was +constructed. Equality between two original records still refuses a +disagreement; nothing compares today's executable with either for admission, +and nothing rewrites history to claim today's executable made it. + +Positive identity is not proof of history: a provider asserting the same +identity over empty history passes confirmation. Regression suites detect that +with an original-only marker; no runtime detector is claimed. + +The adapter metadata patches that supply turn identity, acceptance and native +identity remain required. This decision does not retire them. + +## Current owner + +- [ACP client — Sessions: ownership, routes and attachment](../acp-client-spec.md#sessions-ownership-routes-and-attachment) +- [ACP client — Availability](../acp-client-spec.md#availability) +- [ACP client — ACPX provider](../acp-client-spec.md#acpx-provider) +- [Native agent session launch — Executable build binding](../native-agent-session-launch-spec.md#executable-build-binding) +- [Native agent session launch — Structural checklist](../native-agent-session-launch-spec.md#structural-checklist) diff --git a/specs/decisions/README.md b/specs/decisions/README.md index f81ffd149..57220d432 100644 --- a/specs/decisions/README.md +++ b/specs/decisions/README.md @@ -19,3 +19,4 @@ do not govern behavior. - [002 — Composability scope](002-composability-scope.md) - [003 — Frozen lockfile](003-frozen-lockfile.md) - [004 — Host-installed Codex CLI](004-host-installed-codex-cli.md) +- [005 — Sessions continue on the current executable](005-current-executable-session-continuation.md) diff --git a/specs/native-agent-session-launch-spec.md b/specs/native-agent-session-launch-spec.md index a5ae3149a..6c86a8ee7 100644 --- a/specs/native-agent-session-launch-spec.md +++ b/specs/native-agent-session-launch-spec.md @@ -383,10 +383,15 @@ codex resume ### Executable build binding -A client-allocated identity means one thing only while the build that accepted -it can be recognized later. Two builds of one provider accept the same identity -and disagree silently about what it names, so a new client-allocated session -retains which build accepted it: +XMD uses the executable selected by the current environment and opens the +retained provider conversation. It requires the provider to confirm the same +native conversation identity. A version or digest change does not refuse +continuation. Missing required confirmation, a different identity or a real +resume failure stops the operation without creating a replacement +conversation. Historical executable observations remain unchanged. + +A session XMD constructs retains, as diagnostic history, the complete +observation of the executable that constructed it, when one could be made: ```ts interface ExecutableBuildBindingV1 { @@ -396,26 +401,30 @@ interface ExecutableBuildBindingV1 { } ``` -Every member is exact, and equality requires all of them to agree. The digest is -the lowercase SHA-256 of the canonical executable target; `reportedVersion` is -the adapter's canonical parse of what that exact target reports. That parse -accepts exactly one canonical line: output naming no build is unrecognized, and -output naming several is a list of builds rather than an answer — taking the -first would be choosing one, which is the question a binding exists to settle. -Neither is repeated in a diagnostic. A matching build -reached at another path is the same build; a changed build at the same path is -not. A path is never a member: it says where a build was, which stops being -true, and it names host layout besides. - -The host supplies an executable observer directly to the provider, alongside the -coordinator and the route store. It resolves the launcher command through the -host's real execution environment, canonicalizes the target, requires an -executable regular file, hashes that target, and asks that same file its -version. It is deliberately not a Context, contextual Api, Agent operation, -component or middleware value: executable validation decides which retained -history may be accepted, and a resolver document middleware could replace could -point the observation at one binary while the run spawns another. A controlled -test substitutes the whole observer through the same constructor seam. +The digest is the lowercase SHA-256 of the canonical executable target; +`reportedVersion` is the adapter's canonical parse of what that exact target +reports. That parse accepts exactly one canonical line: output naming no build, +or naming several, is an undetermined version rather than an answer. Neither is +repeated in a diagnostic, and a binding is never invented for it. A path is +never a member: it says where a build was, which stops being true, and it names +host layout besides. Equality over these members is used only to check that two +original accounts of one session agree; it never admits a live executable. + +Selection comes first. A carried adapter's executable is selected by the host +once — Claude's nonempty `CLAUDE_CODE_EXECUTABLE`, otherwise `claude` on the +host PATH; Codex's nonempty `CODEX_PATH`, otherwise `codex` on the host PATH; +relative selections against the host execution directory, and a bad explicit +choice with no PATH fallback. A host that makes no selection of its own lets +its observer resolve the launcher command. The host supplies an executable +observer directly to the provider, alongside the coordinator and the route +store. It canonicalizes the selected target, requires an executable regular +file, hashes it, and asks that same file its version. It is deliberately not a +Context, contextual Api, Agent operation, component or middleware value: a +resolver document middleware could replace could point the observation at one +binary while the run spawns another. A controlled test substitutes the whole +observer through the same constructor seam. A missing, non-file or +non-executable selection is an availability failure; a version that cannot be +asked or read is a diagnostic and keeps the selection. One observation yields two kinds of value: @@ -424,7 +433,7 @@ durable: the executable build binding live: the canonical executable path ``` -The live path exists only in the operation that observed it. Native creation and +The live path exists only in the operation that selected it. Native creation and resume replace the adapter command's first argv member with it, and the matching Claude ACP child receives it through `CLAUDE_CODE_EXECUTABLE` in a transient child-process environment. The integrity-pinned ACPX 0.22.0 source closure @@ -433,11 +442,22 @@ barrier remains required independently of that released capability. It enters no record, public result, diagnostic, `process.env`, or provider partition that outlives its last handle. -A session established before any build was recorded is legacy-unbound. It keeps -exactly the native-only behavior that released it: resume works, nothing is -observed, and no binding is invented for it. It never authorizes ACP attachment -and is never upgraded in place, because a build observed today says which build -is installed now, not which one established the conversation. +A session established before any build was recorded is legacy-unbound. Its +route directly supplies the native identity, allocation provenance, +instruction digest and launcher, so no historical build is needed for exact +attachment or native preflight. It continues under the same selection and +confirmation as any other session, and no binding is invented for it: it is +never upgraded in place, because a build observed today says which build is +installed now, not which one established the conversation. Missing historical +metadata alone establishes no observed difference. + +Before affected live work, XMD warns once per logical session in the current +invocation when the observed version differs from its historical observation. +If the current version cannot be determined, it reports that once and +continues otherwise supported work. Missing historical metadata alone +establishes no observed difference. Diagnostics use stderr and leave +machine-readable stdout unchanged. Completed replay performs no executable +observation and emits no new compatibility warning. ### Attachment capability @@ -449,47 +469,50 @@ join that conversation afterwards. `claude` is advertised for both. Its attachment claim was proven by `packages/acp/src/ClaudeNativeToAcp.test.md`: one native turn planted a random marker, a checked-in marker-free ACP `` recovered it under the same -identity and the same observed build, and an independent route naming an absent -identity refused before a turn without creating history in its place. +identity, and an independent route naming an absent identity refused before a +turn without creating history in its place. That same attachment is how a +client-native session's identity is positively confirmed around a native +handoff; a host that does not advertise it cannot hand such a session over. Those command shapes are adapter implementation details, not authored document values. A custom ACP agent without a declared native launcher fails with an unsupported-capability error before XMD releases its ACP session. Knowing a command shape is not the same as being launch-capable. Advertisement -is separate: an adapter becomes launch-capable only once an opt-in proof runs -the claims its provenance names against the installed CLI. Until then +is separate: an adapter becomes launch-capable once XMD's integration with it is +proven by an opt-in proof of the claims its provenance names. Until then `` refuses that agent before anything of the session moves — before a provider-returned adapter's ACP session is released, and before a client-allocated adapter allocates an identity or writes a private file. That is the failure this contract asks for rather than a hopeful spawn. `claude` is advertised. Its client-allocated claims were proven through the -production CLI against **Claude Code 2.1.241 on macOS arm64**, which is the -compatibility point the advertisement stands on. +production CLI against Claude Code 2.1.241 on macOS arm64. -`codex` is advertised for native launch, gated by the complete provider-returned -proof through the production CLI against **`codex-cli 0.153.2` on macOS arm64**, +`codex` is advertised for native launch, from the complete provider-returned +proof through the production CLI against `codex-cli 0.153.2` on macOS arm64, with the vendored `@agentclientprotocol/codex-acp` 1.6.2 snapshot that asserts -the App Server thread on the response `_meta` — that whole tuple is the -compatibility point the advertisement stands on. - -Admission is a question about the product, not about that release. What the -executable observer accepts is one canonical `codex-cli x.y.z` line and nothing -else: another canonical version is admitted, and output that is bare -(`codex-cli`), malformed, or carries a second line refuses — even when one of -those lines would have been canonical on its own. The product word travels with -the number because a bare semver from another tool compares equal to one from -this one. - -What is exact is the session, not the release. The canonical string a -preparation accepted becomes that session's retained executable binding, and -every later native launch, attachment or incomplete launch replay reobserves the live -build and compares it against that binding before a process, an ensure or a -turn. A build that no longer matches refuses without creating a substitute -conversation. This is the native launch and attachment contract. A held Codex -conversation can continue over ACP on a different build when a live load -confirms its original native identity; see [ACP client](acp-client-spec.md#acpx-provider). +the App Server thread on the response `_meta`. + +Recorded CLI, adapter and host versions describe the checks that ran. They are +evidence, not an allowlist or a requirement to repeat certification for every +release. The existing live documents remain opt-in integration regressions for +initial use, original-context continuity and native handoff where supported. +Actual protocol capabilities and provider-native identity assertions remain +required. + +What the executable observer recognizes is one canonical `codex-cli x.y.z` +line and nothing else: another canonical version is recognized, and output +that is bare (`codex-cli`), malformed, or carries a second line is an +undetermined version. The product word travels with the number because a bare +semver from another tool compares equal to one from this one. + +Every later native launch, attachment or incomplete launch replay selects the +current executable and positively confirms the retained native identity before +a native process, a configuration or a turn; a version that differs from the +session's history is reported and never refuses. This is the native launch and +attachment contract, and it is the same policy ordinary and held ACP +continuation follow; see [ACP client](acp-client-spec.md#acpx-provider). Complete means through to history: the gate closes only when XMD rejoins that same conversation over ACP afterwards and reads the native turn back out of it, because a conversation that cannot be rejoined is @@ -530,15 +553,21 @@ session one of them constructs through ACP and the other does not. where the adapter owes a materialization turn the identity does not exist until that turn is accepted: -9. The live build is observed and the bound V3 `acp-first` route is published or - adopted — **before** the provider constructs anything, so the route a later - run is held to already exists when there is a session to hold it to. A build - this run cannot name, or a route naming a different one, ends the launch here - with nothing durable written about a session. +9. The current executable is selected and observed, and the `acp-first` route is + published or adopted — **before** the provider constructs anything, so the + route a later run is held to already exists when there is a session to hold + it to. A fresh route records the complete observation as V3 history, or is + unbound without one; an existing route is never rewritten. An executable that + cannot run ends the launch here with nothing durable written about a session; + a version difference is reported once and continues. 10. The provider creates or resumes the durable provider session through ACPX, applying the prepared instruction layer and contextual cwd configuration. - An **already-established** session has an identity of its own: the provider - verifies a native-resume capability and obtains that asserted identity. A + An **already-established** session has an identity of its own: the provider + reopens its exact retained loading target with `expectedAgentSessionId` + equal to the retained native assertion, under exclusive ownership and + before any configuration or handoff, and spends no turn. A record with no + retained assertion, or a live load that is missing or differing, refuses + with `identity-unavailable`. A **fresh** session on an adapter that owes a materialization turn does not: creation yields provisional occupancy and asserts no native identity at all. 11. XMD commits the prepared launch record before releasing ownership. For an @@ -564,19 +593,26 @@ owner to release — what has to be settled first is which conversation this is: 9. The provider reads both durable accounts under ownership and refuses rather than converting: a session ACP already established, or a route that disagrees about the instruction layer or the launcher, ends the launch here. -10. The build is observed before an identity is made, so a build this run - cannot name ends the launch before anything durable is written, and a route - that already names a different build ends it with - `executable-binding-refused`. A legacy unbound route is the exception: it - observes nothing, resumes under the launcher name, and gains no binding. - Whether an identity is needed at all is decided next. An existing compatible +10. A launcher without an advertised confirmation capability — client-native + ACP attachment — refuses with `unsupported-capability` before allocation or + handoff; exit status is never substituted for confirmation. The current + executable is selected before an identity is made, so one that cannot run + ends the launch before anything durable is written. Its version is a + diagnostic, reported once against the route's history, and a legacy unbound + route continues the same way and gains no binding. Whether an identity is + needed at all is decided next. An existing compatible `client-native` route already names this conversation, so its retained - identity is adopted and **nothing is allocated** — a second candidate for a - conversation that already exists is a value with nowhere to go. Only where + identity is adopted and **nothing is allocated** — a second candidate for a + conversation that already exists is a value with nowhere to go. That + established conversation is positively confirmed now: its exact native + identity is loaded over ACP — strictly, with `expectedAgentSessionId`, when + an ACP record exists; with no record, by exact `resumeSessionId` and a + required returned assertion — with no configuration or turn, and the ACP + close is joined before preparation is retained. Only where no route names it yet does the adapter allocate one, inside ownership and before any process exists; nothing else supplies or replaces it. -11. A launch that allocated publishes the bound V2 `client-native` route - create-once, and +11. A launch that allocated publishes the `client-native` route create-once — + V2 with the complete observation as history, or V1 without one — and what it publishes against is authoritative — whoever published first described the session that exists. Four outcomes, and no other: - this launch's own candidate won — `created`; @@ -604,22 +640,30 @@ From there both rejoin: terminal inherited — resuming, for a provider-returned adapter, the identity its materialization turn asserted, or the one an already-existing session already had; and for a client-allocated one - creating it under the allocated identity from the private file, or resuming - it by the same name when the route already named it. No provider-returned - path reaches this step without an asserted identity. + creating it under the allocated identity from the private file, or resuming + it by the same name when the route already named it. No resume reaches this + step without a positive assertion of its exact identity from this + invocation, and ACP's close is joined first; a close that failed stops the + handoff and retains unresolved ownership. 14. `Session.Launch` suspends while the child runs. 15. The child handles prompts, tools, permission dialogs, rendering, and native transcript persistence directly. 16. When the child exits, XMD records its terminal outcome, removes the private file and its directory while ownership is still held, and releases the - foreground-terminal lease. The route and the retained phases stay: they are + foreground-terminal lease. A fresh client-allocated creation is confirmed + after the child has fully joined and before the launch acknowledges success + or releases the coordinator: the allocated identity is loaded over ACP, its + returned assertion must equal it, and the ACP close is joined. Exit status is + retained as process evidence and never as identity. A failed or absent + confirmation fails this launch and never creates again. Cancellation joins + the child and propagates; it starts no confirmation during teardown. The route and the retained phases stay: they are what the next invocation resumes from. 17. Later Agent work depends on the route again. On an `acp-first` session it - lazily reattaches through ACP to the same provider session. On a bound + lazily reattaches through ACP to the same provider session. On a `client-native` route advertised for attachment, `` and `` follow *ACP attachment on a bound route* below and join the same provider - conversation. A legacy unbound route or an unavailable attachment - capability refuses before a turn and creates no substitute conversation. + conversation, bound or legacy unbound. An unavailable attachment capability + refuses before a turn and creates no substitute conversation. 18. Execution continues after `Session.Launch` in its enclosing document flow. An enclosing `` or `` resolves by its own contract, before @@ -642,25 +686,31 @@ this sequence, and every step happens while the coordinator holds the session: 3. Read and classify the route. `acp-first` follows the existing ACP path; a session with no route at all is constructed as `acp-first` here, which is what makes a nested client-native launch refuse afterwards. -4. A legacy unbound `client-native` route refuses with - `executable-binding-refused`, and an agent this host has not advertised for - attachment refuses with `unsupported-capability`. -5. Reobserve the executable and compare the binding exactly. +4. An agent this host has not advertised for attachment refuses with + `unsupported-capability`. A legacy unbound route attaches like a bound one. +5. Select the current executable and observe it for its diagnostic. A version + that differs from the route's history is reported once; one that cannot run + is an availability failure. 6. Inspect any retained ACP arrangement without creating one: absence may enter exact resume, because exact resume is the operation being attempted; a record must assert this route's identity and nothing else. -7. Select the live runtime for `(resolved agent command, binding)` and give the - observed path only to that runtime's child environment. -8. Ensure with `resumeSessionId` equal to the route's identity. +7. Select the live runtime for `(resolved agent command, selected environment)` + and give the selected path only to that runtime's child environment. +8. Ensure with `resumeSessionId` equal to the route's identity, and with + `expectedAgentSessionId` equal to it when an ACP record exists. A first + attachment without a record carries no expectation that presupposes one and + sends no configuration or turn. 9. Require the provider's canonical assertion to equal it. Absence or - disagreement closes the handle and refuses before a turn. + disagreement closes the handle and refuses before a turn; a refused first + arrangement is left asserting nothing, so a later exact retry is not blocked. 10. Only then return a `Session`, or start the subscribed turn. -Runtime partitions are scope-owned. Different bindings never share an ACP child, +Runtime partitions are scope-owned. Different selected environments never share +an ACP child, a managed handle remembers the partition that created it, and every turn, close, detach, cancellation and stale-handle release goes through that same partition. When a bound partition's last handle closes it is removed and torn down; a later -attachment reobserves and builds another. +attachment selects again and builds another. A partition is kept exactly as long as something is standing on it, and two different things can be: a handle nobody has closed, and work that has claimed @@ -983,14 +1033,17 @@ V1 record from being read as a bound one. So are missing, malformed, unknown-schema, moved and natural-key-mismatched records. Only a file that is not there means the session has not been constructed yet. -A V1 route of either kind is legacy-unbound. A V1 `client-native` route remains -valid for native resume under the contract that created it, authorizes no ACP -attachment, and is never overwritten, supplemented or upgraded. A V1 `acp-first` -route is the same story from the other side: it says the session was constructed -before XMD recorded which build issued its identity, so an agent whose adapter -binds a build refuses it rather than writing the current executable into it. A -user who needs either bound behavior creates a differently named logical session -under the bound contract. +A V1 route of either kind is legacy-unbound, and is never overwritten, +supplemented or upgraded. A V1 `client-native` route directly supplies the +native identity, client allocation provenance, instruction digest and launcher, +so it continues through native resume and ACP attachment under the same +selection and positive confirmation as a bound one. A V1 `acp-first` route has +no native identity itself: its conversation is located by the exact retained +ACP loading target and record placement, and its native assertion comes from +the acknowledged host or history account, or the promoted provider record in +the pre-commit window. Missing both a usable locator and the required native +assertion is a real refusal; the absence of an old version or digest alone is +not. Unknown schemas and corrupt records remain rejected. The route shares the coordinator's namespace, natural key and digest, so one session names one lease, one ownership record and one route. The route directory @@ -1018,12 +1071,12 @@ construction effect: and otherwise the adapter allocates a candidate and publishes `client-native`; 4. a launch that adopts `acp-first` retains `identity-unavailable` at `prepared`, before allocation, private-file creation, detach or spawn; -5. a `session()` or subscribed prompt that meets a legacy unbound - `client-native` route raises the provider's typed route error before runtime - creation, ensure, turn, close or accepted history. It retains no launch - failure, because no launch was asked for. A bound route instead follows +5. a `session()` or subscribed prompt that meets a `client-native` route, bound + or legacy unbound, follows [ACP attachment on a bound route](#acp-attachment-on-a-bound-route), including - advertisement, exact build and canonical assertion checks. + advertisement and canonical assertion checks. A refusal there raises the + provider's typed error and retains no launch failure, because no launch was + asked for. The resolved agent command is carried from session resolution through the coordinator key, the route key and provider work. It is never resolved a second time inside @@ -1141,30 +1194,38 @@ turn**. Neither is ever substituted for the other, and the turn spent here cannot perform the task the body describes. A prepared record carries `executableBinding` exactly when the route it agrees -with is bound, whichever side named the session. It is optional for -compatibility: the client-allocated path was released before any build was -observed, so a record without it is legacy history — readable, and resumable -only under the native-only contract that wrote it. A provider-returned +with is bound, whichever side named the session, and it carries the route's +original observation rather than today's. It is optional for compatibility: a +record without it is legacy history, readable and continued under the same +selection and confirmation as any other. A provider-returned preparation whose adapter binds a build carries one too — `codex` does, on the bound V3 ACP-first route — and a refusal that prepared no identity invents none. -Every incomplete replay requires exact agreement between its journal and its -route on identity, provenance, instruction digest, launcher and build binding -before its first live effect, and then requires the live build to equal that -binding. Neither account repairs or republishes the other: a replay that +Every incomplete replay requires agreement between its journal and its route on +identity, provenance, instruction digest, launcher and provider before its first +live effect. When both original accounts carry an executable binding, those +bindings must agree exactly; a missing observation alone is not a disagreement, +and today's observation is never compared with either. The live executable is +then selected, and the conversation is confirmed positively instead of by +build equality. Neither account repairs or republishes the other: a replay that found a disagreement has discovered that the session it was going to continue is not the session it prepared, and retains `identity-unavailable` without starting a child. Equal instructions may resume the retained identity; different instructions retain `instructions-refused` and replace neither the layer, the route, the identity, nor any provider state. -An incomplete replay of a legacy unbound client-allocated launch retains -`executable-binding-refused` before any live work: nothing available to it can -show which build has that session's history, and resuming anyway would answer -the question by ignoring it. A **completed** replay of the same launch reads its -journal and nothing else, exactly as before — it performs no live validation and -contacts no route store, observer, ACP runtime or process. +Incomplete replay continues at its first remaining live phase under the same +rules as a live launch. An established native resume — provider-returned, or +client-allocated after a retained detach — is preceded by the same positive +confirmation and joined ACP release, even when no configuration was requested. +A client-allocated prepared-only replay still owes creation under the retained +identity when handoff never began, and confirms after the joined creation. A +detached replay resumes only and never creates if confirmation fails. An +ambiguous materialization stays recovery-required and sends no turn. Legacy +unbound launches follow these same paths. A **completed** replay reads its +journal and nothing else — it performs no selection, observation, warning or +live validation and contacts no route store, observer, ACP runtime or process. A session XMD named takes its instruction layer from one invocation-private file, mode `0600`, passed by path. The text appears in neither argv nor @@ -1262,13 +1323,11 @@ different layer, exactly as a session a native UI has been in is. A `` that only placed one has established nothing, so a launch inside it constructs the session it named rather than meeting one. -A build this run cannot show is the build behind the session fails with -`executable-binding-refused`. Resolution, canonicalization, executable-file -validation, version parsing, digesting, schema recognition, equality, and a -session established before any build was recorded all end there. The diagnostic -names the stable class, the launcher, and the two canonical versions being -compared; it carries no executable path, raw version output, host error, argv, -environment, credential, instruction text or provider payload. +A selected executable that is missing, is not a file or cannot be run fails with +`executable-binding-refused`, the availability class. A version that differs +from the session's history, or cannot be determined, is a diagnostic warning and +never this refusal. Neither carries an executable path, raw version output, host +error, argv, environment, credential, instruction text or provider payload. An attachment that reaches the provider and cannot open the conversation the route names fails with `identity-unavailable`: missing provider history, an @@ -1376,19 +1435,20 @@ Focused tests prove: natural key, contention refuses instead of queueing, a crashed owner leaves a recovery tombstone, and a host with no coordinator refuses before contacting an agent; -18. a build binding is read and compared exactly — a moved matching build is - accepted, a changed build is not, and an inexact record refuses rather than - being read past; -19. new client-native construction observes the build before it allocates, - publishes a bound V2 route, and retains a preparation that agrees with it, - while a legacy V1 route resumes natively under the launcher name and gains - nothing; -20. a `` or `` on a bound route supplies the route identity as - the exact resume identity, delivers the observed path only to the matching - child's transient environment, and refuses before ensure on a missing - attachment gate, a missing observer, build drift, a disagreeing retained - arrangement or a returned identity that is not the route's; and -21. ACP runtimes are partitioned by resolved agent command and binding, a handle +18. a build binding is read exactly, an inexact record refuses rather than being + read past, and a changed, moved or unrecognized current build continues the + same confirmed conversation with at most one warning; +19. new client-native construction selects the executable before it allocates, + publishes a route recording any complete observation, and retains a + preparation that agrees with it, while a legacy V1 route continues under + today's selection and gains nothing; +20. a `` or `` on a client-native route supplies the route + identity as the exact resume identity, delivers the selected path only to + the matching child's transient environment, and refuses before a turn on a + missing attachment gate, a disagreeing retained arrangement or a returned + identity that is not the route's; and +21. ACP runtimes are partitioned by resolved agent command and selected + environment, a handle is closed by the partition that created it, the last close evicts a bound partition, and provider teardown settles what remains; 22. claimed runtime work that produced no handle releases its claim, a partition @@ -1541,15 +1601,10 @@ degrading: record. New records write neither member, and an incomplete older record does no configuration work because one was present. Canonical `configuration` beside either released member is ambiguous and refuses. -- **Executable upgrade migration is unbuilt.** A V2 route freezes one build for - that logical session, and a later build refuses with - `executable-binding-refused` rather than modifying the route or the provider's - history. Rebinding old provider history to a new build is a separate design. -- **A legacy unbound client-native session never attaches.** It was constructed - before XMD recorded which build accepted its identity, so nothing available - now can show this run is talking to that build. It keeps native resume and - refuses ACP attachment; a session that needs attachment is created anew under - a different logical name. +- **Executable history is never rebound.** A route keeps the observation of the + executable that constructed its session. A later build continues the same + confirmed conversation and is reported against that history; nothing rewrites + the route or the provider's history to claim the current executable made it. Additional provider adapters land independently against the same core contract. An adapter that cannot prove instruction injection before the first user turn @@ -1599,9 +1654,12 @@ Implementation review checks these frozen invariants: reaches neither argv nor environment. 17. Private setup and child-creation failures are normalized before they cross a public or durable boundary. -18. A new client-native session is bound to one observed executable build, and - every later create, resume, attachment and incomplete replay reobserves and - compares before a process, an ensure or a turn. +18. Every create, resume, attachment and incomplete replay uses the executable + the current environment selects and requires the provider's positive + assertion of the exact retained native identity before a configuration, a + turn or a native handoff — or, for a fresh client-allocated creation, after + the child joins and before success. A version or digest difference is + reported and never admits or refuses; exit status never confirms identity. 19. The canonical executable path is live only: it enters no route, journal, retained provider state, public result, diagnostic or global environment, and no partition that outlives its last handle. @@ -1609,14 +1667,20 @@ Implementation review checks these frozen invariants: the provider's canonical assertion must equal it before the first turn. 21. Native-launch advertisement and client-native attachment advertisement are separate trusted-host choices, and neither is inferred from the other. -22. A released V1 route and a completed legacy journal remain readable, and - neither authorizes ACP attachment or incomplete live replay. +22. A released V1 route and a legacy journal remain readable and are never + rewritten; they continue through attachment and incomplete replay under the + same selection and confirmation, and missing historical build evidence alone + refuses nothing. 23. A failed acquisition retains no partition and no live path; a partition is evicted only when it holds no handle and no work in flight; every handle-producing path enters one ownership account bound to its creator the moment its handle exists; a cancellation observes and settles an ensure it already started before quiescence; quiescence is answered from that account; and a close that failed releases nothing and acknowledges none. +Items 18 and 22 are the #891 amendment: tested versions are evidence, and a +session continues on the current executable under positive identity +confirmation. + Item 12 is the 2026-08-20 architecture amendment. ACPX fixes `systemPrompt` at session creation, while native turns are not authoritative in its cached transcript. The amendment prevents transcript absence from authorizing loss of diff --git a/specs/repl-spec.md b/specs/repl-spec.md index 7108ff698..bb2282406 100644 --- a/specs/repl-spec.md +++ b/specs/repl-spec.md @@ -2078,6 +2078,16 @@ from rendered document Output: forwarding adds nothing to the root result. Bound commands display only what the document explicitly renders, a `` capture still hides stdout, and `silent exec` displays neither channel. +Entry diagnostics appear as Command stderr beside the entry's execution output. +Held-conversation diagnostics appear as transient stderr beside the Sidekick reply +and remain visible after the turn settles in this invocation. They do not become +generated document source, durable chat messages or failed-reply text. The held +reading is captured in the task that owns the conversation, before it opens, +because a held conversation's queued work runs there rather than under the +message that asked for a turn; each line is privacy-projected by that +conversation's protected-input owner and made inert like Command text. The CLI +root owns these display copies for the life of the command. + Command text is inert before measurement and drawing. LF separates rows; other C0 controls, DEL and C1 controls appear as ASCII `\xNN` escapes. Cursor motion, clearing, OSC and terminal mode sequences therefore remain readable text. The diff --git a/specs/workflow-workspace-spec.md b/specs/workflow-workspace-spec.md index 14f10bdcf..d9e6f7a50 100644 --- a/specs/workflow-workspace-spec.md +++ b/specs/workflow-workspace-spec.md @@ -2746,16 +2746,24 @@ provider session key are not identity at all. states both ordinary-run native capability sets empty — no native-launch advertisement and no client-native ACP attachment advertisement — rather than inheriting the provider package's by omission. It supplies no machine session -coordinator, no construction-route store and no executable observer, and -consults none of their namespace. `xmd run` owns a machine-wide account of who -owns a session, how it was constructed and which executable build accepted its -identity; a workflow session is named by the row below instead, and an agent -served here is served over ACP alone. Composing the two is a separate design. - -The workflow host separately selects its installed Claude launcher and supplies -its path only through the retained adapter child's transient environment. This -selection grants no native-session capability and performs no executable-build -admission. +coordinator and no construction-route store, and consults none of their +namespace. `xmd run` owns a machine-wide account of who owns a session and how +it was constructed; a workflow session is named by the row below instead, and +an agent served here is served over ACP alone. Composing the two is a separate +design. The workflow host may supply an executable observer for diagnostics +only; it grants no native capability. + +The workflow host separately selects its installed Claude or Codex launcher and +supplies its path only through the retained adapter child's transient +environment. This selection grants no native-session capability and performs +no executable-build admission. A retained session of a built-in adapter is +reopened by its exact loading target under the provider's live confirmation of +its retained native identity, whichever executable is selected today; a +missing or differing assertion refuses before settings or a prompt and creates +no substitute. Because the run keeps no executable history, a release change +emits no difference warning; a version that cannot be determined is reported +once per session in the invocation. Partial replay attaches lazily, and +completed replay performs no selection, observation, warning or live work. **The mapping lives in the run.** Its database row commits in the run's transaction and is part of the initial schema. Provider session stores and empty From aa75411919c05f73a8ec8e70e85d6821c0fa17f3 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 04:31:21 -0500 Subject: [PATCH 2/7] Stop a native replay whose reconfiguration release failed (#891) A configured prepared-only replay reopened its conversation, reconfigured it, and then could not give ACP up. Its scope recorded the close failure for teardown and answered success, so the detach retried the close and, when that retry succeeded, recorded a detach and started the native UI. The replay now stops with detach-failed before any detach or spawn; teardown still owes and reports the original failure. NR9 reproduces the reviewed probe: the first close fails, later closes would succeed, and no native launch is requested. The native launch spec no longer says a build-bound agent requires an executable observer. --- packages/acp/src/provider.ts | 19 +++++- packages/acp/tests/native-launch.test.ts | 75 +++++++++++++++++++++++ specs/native-agent-session-launch-spec.md | 17 ++--- 3 files changed, 102 insertions(+), 9 deletions(-) diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index d262a9265..6ba606d76 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -4218,7 +4218,8 @@ function* useAcpxProviderState( } const sessionKey = prepared.sessionKey; const held = managed.get(sessionKey); - return yield* scoped(function* (): Operation { + const reattached = held === undefined || !isLive(held); + const failure = yield* scoped(function* (): Operation { let entry: ManagedSession; if (held !== undefined && isLive(held)) { entry = held; @@ -4266,6 +4267,22 @@ function* useAcpxProviderState( invocation.configured.add(sessionKey); return undefined; }); + if (failure !== undefined) { + return failure; + } + // A release this replay owed that did not settle leaves ACP possibly still + // in the conversation. The launch stops here: no detach is recorded and no + // native process starts, and a later close that happens to succeed — at + // detach or at teardown — authorizes nothing for this attempt. + if (reattached && holding(sessionKey)) { + return { + class: "detach-failed", + message: + `session "${sessionKey}" could not be released after it was reconfigured, so it is ` + + `not handed to a native process`, + }; + } + return undefined; } /** diff --git a/packages/acp/tests/native-launch.test.ts b/packages/acp/tests/native-launch.test.ts index a12f375f6..594507eca 100644 --- a/packages/acp/tests/native-launch.test.ts +++ b/packages/acp/tests/native-launch.test.ts @@ -5922,6 +5922,81 @@ describe("Tier NR — configured incomplete replay", () => { }); }); + it("NR9: a reconfiguration release that failed stops the replay, whatever a later close does", function* () { + // The replay reopens its conversation, puts it back under what it was + // prepared with, and then could not give ACP up. A later close of the same + // handle may well succeed — at the detach, or at teardown — and none of + // that is permission to record a detach or start the native UI. + const harness = createFakeRuntime(); + const trace = newTrace(); + advertiseConfiguration(harness, trace); + const routes = createMemorySessionRouteStore(); + // This suite's registry leaves `codex` resolving to its own name. + const command = "codex"; + const key = deriveSessionKey(command, CWD); + const codex = nativeAdapterFor("codex"); + if (codex === undefined) { + throw new Error("missing the production Codex adapter"); + } + harness.closeFailure = new Error("controlled first replay release failure"); + const create = harness.create; + harness.create = (options) => { + const runtime = create(options); + return { + ...runtime, + close(input) { + // Only the first close fails; every later one would succeed. + return runtime.close(input).catch((error: unknown) => { + harness.closeFailure = undefined; + throw error; + }); + }, + }; + }; + let reported: Error | undefined; + try { + yield* scoped(function* () { + yield* installLaunchStack(harness, trace, { + advertise: ["codex"], + adapters: { codex }, + routeStore: routes, + observer: createFakeObserver({ versionOutput: "codex-cli 0.169.1\n" }).observer, + }); + yield* routes.publish({ + schema: "session-route.v1", + route: "acp-first", + provider: "acpx", + agent: command, + sessionKey: key, + }); + trace.replay = { + suffix: "prepared", + prepared: retainedConfigured({ + agent: "codex", + sessionKey: key, + nativeSessionId: `agent-session:${key}`, + sessionState: "resumed", + instructionReconciliation: "resumed", + launcher: "codex", + }), + }; + yield* Agent.operations.launch(launchRequest(INSTRUCTIONS, { agent: "codex" })); + // The handoff stopped at the detach this replay was about to retain. + const detached = trace.records.find((record) => record.phase === "detached"); + expect(detached?.failure?.class).toBe("detach-failed"); + expect(trace.launches).toEqual([]); + expect(trace.order).not.toContain("spawn"); + // One release was attempted before the refusal, and it failed. + expect(trace.order.filter((event) => event === "close")).toEqual(["close"]); + }); + } catch (error) { + reported = error as Error; + } + // Teardown still owes the cleanup, and it reports the failure it inherited. + expect(reported?.message).toBe("controlled first replay release failure"); + expect(trace.launches).toEqual([]); + }); + it("NR3: an unconfigured replay reattaches nothing and behaves as it always did", function* () { const harness = createFakeRuntime(); const trace = newTrace(); diff --git a/specs/native-agent-session-launch-spec.md b/specs/native-agent-session-launch-spec.md index 6c86a8ee7..e32034dc9 100644 --- a/specs/native-agent-session-launch-spec.md +++ b/specs/native-agent-session-launch-spec.md @@ -869,10 +869,11 @@ calls a paused process dead and admits two owners. So every advertised session, prompt, launch and incomplete replay refuses there with `unsupported-capability`, before contacting an agent, while read-only resolution and non-advertised ACP work are unaffected. An advertised agent whose adapter -binds a build also requires a route store and -executable observer. Missing either refuses before any provider effect, -whichever side names the session. An adapter that binds no build keeps its -ordinary behavior without those dependencies. +carries an executable binding also requires a route store; a host without one +refuses before any provider effect, whichever side names the session. The +executable observer is diagnostic and optional: a host without one continues +and reports the version as undetermined. An adapter that carries no binding +keeps its ordinary behavior without those dependencies. ### Exact-target ownership inspection and recovery @@ -1533,10 +1534,10 @@ native-launch capability in the ACPX provider; provider-native identity that is either asserted by the provider or allocated by the adapter before the provider exists, retained explicitly and never inferred; a strict create-once construction route beside the coordinator's own records, -in a released unbound form and a bound one; the host-owned executable observer -and the build binding it produces; ACP attachment to a bound client-native -session under its exact retained identity, through runtime partitions keyed by -agent command and build; +in a released unbound form and a bound one; the host-owned diagnostic +executable observer and the build history it records; ACP attachment to a +client-native session under its exact retained identity, through runtime +partitions keyed by agent command and selected environment; an inherited foreground-terminal interactive child with cancellation and bounded reaping; and the controlled TestAgent fixture that proves all of it without starting a From 35ea371623e985f3c2facf1199eb867e2831c481 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 05:57:56 -0500 Subject: [PATCH 3/7] Continue sessions quietly on the current executable (#891) The user withdrew version history and compatibility notices: a session continues on the executable the current environment selects, under the provider's positive confirmation of its retained native identity, and says nothing about the change. - Remove warnCompatibility, AcpxProviderDependencies.compatibilityWarnings and executableObserver, the CLI invocation set and its forwarding, the workflow diagnostic observer, MachineSessionAssembly's observer, writeDiagnostic, and the Sidekick held-stderr reading and rendering. - Production no longer hashes or parses executables. Selection stays with the host selectors and their launchability check; custom commands are untouched. - Fresh routes are released unbound V1. Existing V2/V3 routes and journals stay byte-preserved; their original bindings are still compared when both exist. - Launch detach/exit ACP work (reconfiguration and native confirmation) now runs under the launch's session route pin, as preparation already did, so a host that pins routes places the post-child confirmation correctly (TL11). - Remove the Test Agent controlled observer and build version; replace test fake observers with a controlled host-selection double. - Amend architecture, ACP, native, workflow and REPL specs and decisions 004/005. --- architecture.md | 4 +- packages/acp/src/native-launch.ts | 46 +- packages/acp/src/provider.ts | 436 ++++-------------- packages/acp/tests/helpers.ts | 88 ++-- packages/acp/tests/host-conversation.test.ts | 63 +-- packages/acp/tests/native-launch.test.ts | 383 ++++++--------- packages/agent/src/launch.ts | 18 +- packages/cli/src/agent-stack.ts | 15 - packages/cli/src/cli.ts | 22 +- packages/cli/src/compiled.ts | 2 +- packages/cli/src/deno-workflow.ts | 9 +- packages/cli/src/deno.ts | 2 +- packages/cli/src/diagnostic-agent.ts | 1 - packages/cli/src/repl/application.ts | 32 -- packages/cli/src/repl/program.ts | 1 - packages/cli/src/repl/sidekick/assembly.ts | 3 - packages/cli/src/repl/sidekick/owner.ts | 39 -- packages/cli/src/session-coordinator.ts | 18 +- packages/cli/src/workflow-agent.ts | 19 +- packages/cli/src/workflow.ts | 5 +- .../adversarial-session-continuity.test.ts | 61 +-- .../tests/agent-session-coordinator.test.ts | 80 ++-- packages/cli/tests/fixtures/host-agent.ts | 4 +- packages/cli/tests/repl-agent-journey.test.ts | 67 --- .../cli/tests/repl-sidekick-journey.test.ts | 61 --- .../cli/tests/session-compatibility.test.ts | 330 +++---------- packages/cli/tests/support/mounted-repl.ts | 2 - .../cli/tests/workflow-agent-sessions.test.ts | 24 +- packages/runtime/apis.ts | 14 - packages/runtime/executable-observer.ts | 10 +- packages/runtime/mod.ts | 1 - packages/test-agent/src/components.ts | 6 +- .../test-agent/src/executable-observer.ts | 54 --- packages/test-agent/src/provider.ts | 10 +- specs/acp-client-spec.md | 115 ++--- .../decisions/004-host-installed-codex-cli.md | 2 +- ...current-executable-session-continuation.md | 51 +- specs/native-agent-session-launch-spec.md | 183 ++++---- specs/repl-spec.md | 10 - specs/workflow-workspace-spec.md | 26 +- 40 files changed, 661 insertions(+), 1656 deletions(-) delete mode 100644 packages/test-agent/src/executable-observer.ts diff --git a/architecture.md b/architecture.md index b8d6807ea..43a8d694b 100644 --- a/architecture.md +++ b/architecture.md @@ -254,11 +254,11 @@ The workflow executor holds the run’s exclusive executor lock through executio Native Agent ownership separately protects a logical provider conversation. Construction provenance and executable metadata do not replace live ownership; release requires evidence that the owner’s work can no longer act. -A conversation continues on the executable the current environment selects. The provider's positive assertion of the retained native identity — not version or digest equality — decides whether it continues; a missing or different assertion refuses without creating a replacement. Executable observations are diagnostic history: kept with the records that first made them, never rewritten to name today's build, and reported once per logical session in an invocation when they differ or cannot be determined. That warning state belongs to the invocation's owning scope, and a held conversation's diagnostics are captured in the task that runs its work. +A conversation continues quietly on the executable the current environment selects. The provider must positively confirm the retained native identity before work that requires it. A missing or different assertion refuses without creating a replacement conversation. Executable version and digest do not decide admission. Existing routes and journal history remain unchanged; normal continuation creates no new version-history record. A released operating-system lock proves a previous local workflow executor is gone. It does not, by itself, prove native Agent backend quiescence or clear an unresolved ownership record. -The [Workflow Workspace specification](specs/workflow-workspace-spec.md) owns executor and storage lifetimes. The [Native Agent session launch specification](specs/native-agent-session-launch-spec.md) owns handoff, identity confirmation, and release proof; the [ACP client specification](specs/acp-client-spec.md#availability) owns executable selection and compatibility warnings. +The [Workflow Workspace specification](specs/workflow-workspace-spec.md) owns executor and storage lifetimes. The [Native Agent session launch specification](specs/native-agent-session-launch-spec.md) owns handoff, identity confirmation, and release proof; the [ACP client specification](specs/acp-client-spec.md#availability) owns executable selection and continuation. ### Cancellation and attachment diff --git a/packages/acp/src/native-launch.ts b/packages/acp/src/native-launch.ts index cb8aaa138..2997fdebd 100644 --- a/packages/acp/src/native-launch.ts +++ b/packages/acp/src/native-launch.ts @@ -11,10 +11,9 @@ * * A launch refuses before ACP detach, client identity allocation or * private-file creation for an adapter this host does not advertise. The - * executable each operation runs is the one the current environment selects; - * its observed version and digest are diagnostic history, recorded beside a - * session XMD constructs and compared only to warn. What continues a session is - * the provider's positive confirmation of its native identity. + * executable each operation runs is the one the current environment selects, + * and nothing about its version is read, retained or reported. What continues a + * session is the provider's positive confirmation of its native identity. */ import { randomUUID } from "node:crypto"; @@ -23,22 +22,21 @@ import type { IdentityProvenance } from "@executablemd/agent/api"; /** * What an adapter knows about the executable behind it. * - * Everything here is that adapter's private dialect — which command a host - * resolves when it makes no selection of its own, what its version output - * looks like, and what the ACP adapter child needs in order to run the selected - * file. None of it reaches a document, and none of it admits or refuses a - * session: the version is reported, and the provider's live identity assertion - * decides whether a conversation continues. + * Everything here is that adapter's private dialect — its launcher command, + * what its version output looks like when an opt-in proof measures one, and + * what the ACP adapter child needs in order to run the selected file. None of it + * reaches a document, and none of it admits or refuses a session: the + * provider's live identity assertion decides whether a conversation continues. */ export interface NativeBinding { - /** The command a host without its own selection resolves and observes. */ + /** The launcher command whose executable a host selects. */ command: string; /** The arguments that ask that exact file its version. */ versionArgs?: readonly string[]; /** * The canonical version from that output, or `undefined` when the output is - * not something this adapter recognizes. An unrecognized version is reported - * as undetermined and never retained under a guess; it does not stop work. + * not something this adapter recognizes. Used by the opt-in proofs that + * record the version they ran against as evidence; normal work never asks. */ version(output: string): string | undefined; /** @@ -73,14 +71,13 @@ export interface NativeBinding { * * The whole line is retained rather than the number alone, because the number * alone is not a build: the same version string from a different product would - * compare equal. Anything that does not look like this is unrecognized, and is - * reported as undetermined rather than retained under a guess. + * compare equal. Anything that does not look like this is unrecognized rather + * than read under a guess. * * Exactly one line may match. Zero is an output this adapter does not * recognize; two or more is output it cannot read as one answer, and taking * the first would be picking a build out of a list of them. Neither is - * repeated anywhere — the caller reports the version as undetermined, and the - * output itself is provider-private. + * repeated anywhere: the output itself is provider-private. */ function claudeVersion(output: string): string | undefined { const canonical = output @@ -95,9 +92,7 @@ function claudeVersion(output: string): string | undefined { * release this was proven against. * * What is recognized is that shape, not that release: another canonical - * version passes here. The string recognized for a session XMD constructs is - * retained as its executable history, and a later different version is - * reported against that history; it is never compared with a constant here. + * version passes here, and none is compared with a constant. * * The product word is retained with the number for the same reason Claude's * whole line is: a bare semver from another tool compares equal. The one-line @@ -109,7 +104,7 @@ function codexVersion(output: string): string | undefined { // second build's line ride along unnoticed: the answer would be "one // canonical line was in there somewhere" rather than "this is what the // executable reported". A wrapper that prints anything beside the version has - // not told us which build ran, so its version is undetermined. + // not told us which build ran, so it has no answer. const lines = output .split("\n") .map((line) => line.trim()) @@ -187,9 +182,8 @@ export interface ProviderReturnedAdapter extends AdapterCommands { * A provider-returned adapter whose executable this host selects and describes. * * The provider still names the session, so nothing here chooses an identity. - * What the binding adds is which file runs and what version it reports, so a - * session's construction route can keep that as history and a later run can - * warn when it differs. + * What the binding adds is which executable a host selects for it and how + * that selection reaches the adapter's child. * * It is a separate type rather than an optional member on the one above, * because an adapter a host supplies for a provider without a carried @@ -218,8 +212,8 @@ export function allocatesIdentity(adapter: NativeAdapter): adapter is ClientAllo * * Independent of who names the session: `claude` allocates its identities and * `codex` is handed them, and for both the current environment selects the - * executable and its version is reported. An adapter without a binding keeps - * the released native-only behavior — it observes nothing. + * executable. An adapter without a binding keeps the released native-only + * behavior — it selects nothing. */ export function bindsBuild(adapter: NativeAdapter): adapter is BuildBoundAdapter { return "binding" in adapter; diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index 6ba606d76..ded66cdfc 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -93,11 +93,7 @@ import type { NativeBinding, } from "./native-launch.ts"; import { AgentSessionRouteError } from "./session-route.ts"; -import type { - AgentSessionRoute, - AgentSessionRouteStore, - AgentSessionRouteV3, -} from "./session-route.ts"; +import type { AgentSessionRoute, AgentSessionRouteStore } from "./session-route.ts"; import { createAcpRuntime, createAgentRegistry, @@ -137,18 +133,14 @@ import { AgentSessionBusy, AgentSessionRecoveryRequired, cwd, - ExecutableObservationError, nativeLaunch, notifyTerminal, - writeDiagnostic, } from "@executablemd/runtime"; import type { AgentSessionCoordinator, AgentSessionKey, AgentSessionOwnerKind, AgentSessionOwnership, - ExecutableObserver, - ObservedExecutable, } from "@executablemd/runtime"; import { ADVERTISED_CLIENT_NATIVE_ATTACHMENT, @@ -322,20 +314,6 @@ export interface AcpxProviderDependencies { * prove different things. Absent means none. */ advertiseClientNativeAttachment?: readonly string[]; - /** - * How this host observes the build behind an executable. - * - * Supplied directly by the host that built it, like the coordinator and the - * route store beside it. What it reports is diagnostic: the version and - * digest of the executable this run selected, recorded beside a session it - * constructs and compared with that history to warn when they differ. It - * never decides whether a conversation may continue, and it is never asked - * to resolve a command the host has already selected. - * - * Absent means this host cannot say which version it runs. Work continues, - * with that reported once per logical session. - */ - executableObserver?: ExecutableObserver; /** * Extra native adapters, by agent name. A harness driving an agent this * package has never heard of supplies its own resume command shape here @@ -413,35 +391,21 @@ export interface AcpxProviderDependencies { */ permissions?: "composable" | "strict"; sessions?: AcpxSessionPolicy; - /** - * Sessions already warned about in this host invocation. - * - * Share one set across its provider installations. Omission gives this - * installation its own set. Keys are private logical placements, and the - * set is never retained or used to admit execution. - */ - compatibilityWarnings?: Set; } /** - * The executable one live operation selected, and what was observed about it. + * The executable one live operation selected. * - * `livePath` is the file the current environment selected — the host's own - * selection for a carried adapter, or the observer's resolution on a host that - * makes none — and it is what this run spawns and hands to the matching ACP - * child through `environment`. It is absent for an opaque custom command, - * whose backend this provider does not guess at. It appears in no record, - * route, diagnostic, result, or parent environment, and it does not outlive the - * operation that selected it. - * - * `binding` is the complete current observation of that file, when one could - * be made. It is diagnostic: a fresh construction records it as history, and a - * later run compares it with that history only to warn. + * `livePath` is the file the host's selection for a carried adapter names, and + * it is what this run spawns and hands to the matching ACP child through + * `environment`. It is absent for an opaque custom command, whose backend this + * provider does not guess at, and for a host that makes no selection. It + * appears in no record, route, diagnostic, result, or parent environment, and + * it does not outlive the operation that selected it. */ interface BoundBuild { agentName: string; agentCommand: string; - binding: ExecutableBuildBindingV1 | undefined; livePath: string | undefined; environment: Record; /** The exact ACP adapter command this binding was proven against, if pinned. */ @@ -452,7 +416,7 @@ interface BoundBuild { * One live ACP runtime, and what it is for. * * A bound entry exists only while it owns handles. When its last one closes it - * is removed and a later operation reobserves the build and builds another — + * is removed and a later operation selects again and builds another — * because what a bound partition holds is a live executable path, and a * partition kept past its work would be holding one for nobody. */ @@ -688,12 +652,12 @@ interface LaunchInvocation { /** Sessions this invocation published an identity for. */ readonly fresh: Map; /** - * The build each bound session in this invocation observed, and the argv - * shape that goes with it. + * The executable each bound session in this invocation selected, and the + * argv shape that goes with it. * * Held on the invocation rather than the provider, because a live executable - * path is only true for the run that observed it. A later replay reobserves - * rather than finding one lying about. + * path is only true for the run that selected it. A later replay selects + * again rather than finding one lying about. */ readonly bound: Map; /** Sessions whose detach phase ran live in this invocation. */ @@ -725,6 +689,15 @@ interface LaunchInvocation { * only after this, and a creation acknowledges success only after it. */ readonly confirmed: Set; + /** + * Run registry-dependent work under this launch's session route. + * + * Preparation already runs inside it. The detach and exit phases do not — + * a native UI may hold the session for hours — so the ACP work they owe + * (reattaching to reconfigure, confirming before a resume, confirming after a + * creation) takes the same pin for exactly as long as that work lasts. + */ + readonly route: (op: () => Operation) => Operation; } /** @@ -1181,7 +1154,7 @@ function* useAcpxProviderState( }; const coordinator = dependencies?.coordinator; const routeStore = dependencies?.routeStore; - const executableObserver = dependencies?.executableObserver; + const promptUsageHost = dependencies?.promptUsageHost; const adapterBuild = dependencies?.adapterBuild; const agentCwd = dependencies?.agentCwd ?? cwd; @@ -1202,7 +1175,7 @@ function* useAcpxProviderState( ? undefined : structuredClone(dependencies.newSessionOptions); const sessions = checkedSessionPolicy(dependencies?.sessions); - const compatibilityWarnings = dependencies?.compatibilityWarnings ?? new Set(); + const strict = dependencies?.permissions === "strict"; const stateScope = yield* useScope(); const turns = yield* useSerialQueues(); @@ -1225,12 +1198,11 @@ function* useAcpxProviderState( ); /** - * One ACP runtime per `(agent command, executable build)`, plus the unbound - * one ordinary ACP-first work has always used. + * One ACP runtime per `(agent command, selected environment)`, plus the + * unbound one ordinary ACP-first work has always used. * - * Sessions established against different builds never share an ACP child. - * That is what observing a build is for: a child running the wrong Claude - * accepts the session identity and disagrees silently about what it names. + * Two selections never share an ACP child: a child started for one executable + * is never asked to serve work selected for another. */ let unbound: RuntimeEntry | undefined; const runtimes = new Map(); @@ -1333,9 +1305,8 @@ function* useAcpxProviderState( * The `(agent command, selected environment)` partition a bound runtime is * kept under. * - * Keyed by what the child is actually started with, never by what was - * observed about it: two selections never share a child, and the same - * selection reached twice does, whatever its version reports. + * Keyed by what the child is actually started with: two selections never + * share a child, and the same selection reached twice does. */ function partitionOf(build: BoundBuild): string { const environment = Object.entries(build.environment).sort(([a], [b]) => (a < b ? -1 : 1)); @@ -1658,8 +1629,8 @@ function* useAcpxProviderState( // construction has not been settled yet — it would run before the route is // published, before a route this surface cannot serve can refuse it, and // before a host missing either capability has said so. It would also spawn a - // child of a build nothing has observed, which is the one thing a bound - // session may not talk to. Nothing on that path needs the answer: a + // child of an executable this operation has not selected yet. Nothing on + // that path needs the answer: a // client-native session is created by a native process, and where ACP does // serve one, the establishment itself reports being unable to. // Routed inspection acquires its own temporary session without a bound build. @@ -1938,7 +1909,7 @@ function* useAcpxProviderState( /** What one ensure is for, beyond the session it is for. */ interface EnsureIntent { /** - * The observed build this ensure's ACP child must be. + * The selected executable this ensure's ACP child must run. * * Separate from `attachment`, because the two answer different questions * and not every session that has one has the other: a session the provider @@ -2478,101 +2449,50 @@ function* useAcpxProviderState( }; } - /** The same route, for a session whose build was observed as it was bound. */ - function boundAcpFirstRoute( - agentCommand: string, - sessionKey: string, - executableBinding: AgentSessionRouteV3["executableBinding"], - ): AgentSessionRouteV3 { - return { - schema: "session-route.v3", - route: "acp-first", - provider: ACPX_PROVIDER, - agent: agentCommand, - sessionKey, - executableBinding, - }; - } - /** - * Select the executable one live operation runs, and observe it. + * Select the executable one live operation runs. * - * Selection comes first and is the only thing that can refuse. A carried - * adapter's executable is chosen by the host's own selection — its explicit - * environment variable, then the host PATH — exactly once, and that same file - * is what is observed, spawned and handed to the matching child. A host that - * makes no selection of its own lets its observer resolve the command. A - * custom command is the host's to run as configured: nothing here guesses - * which backend an opaque wrapper starts, so its version is simply unknown. - * - * Observation is diagnostic. An executable whose version cannot be asked or - * read leaves no binding and keeps its selection; only a selected file that is - * missing or cannot be run is an availability failure. + * A carried adapter's executable is chosen by the host's own selection — its + * explicit environment variable, then the host PATH — exactly once, and that + * same file is what is spawned and handed to the matching child. The host's + * selector checks that the file can start; what it reports as a version + * decides nothing. A custom command is the host's to run as configured: + * nothing here guesses which backend an opaque wrapper starts. A selection + * that cannot run is an availability failure, and the selector's own message + * says what to correct. */ function* selectBuild( agentName: string, agentCommand: string, binding: NativeBinding, ): Operation { - const versionOptions = - binding.versionArgs === undefined ? {} : { versionArgs: binding.versionArgs }; let environment: Record = {}; let livePath: string | undefined; - let observed: ObservedExecutable | undefined; if (dependencies?.agentProcessEnv !== undefined) { let selected: Record | undefined; try { selected = yield* dependencies.agentProcessEnv(agentName, agentCommand); } catch (error) { - // The host's own selector says what to correct, and says it without a - // path; anything else is reported in this provider's stable terms. - throw new AttachmentRefused( - error instanceof Error && error.message.length > 0 - ? { class: "executable-binding-refused", message: error.message } - : unavailable(agentName, error), - ); + throw new AttachmentRefused({ + class: "executable-binding-refused", + message: + error instanceof Error && error.message.length > 0 + ? error.message + : `the executable "${agentName}" runs is unavailable. Install it, or correct ` + + `the environment that selects it.`, + }); } if (selected !== undefined) { environment = { ...selected }; livePath = selectedPath(binding, selected); } - } else if (executableObserver) { - try { - observed = yield* executableObserver.observe(binding.command, versionOptions); - } catch (error) { - if (!diagnosticOnly(error)) { - throw new AttachmentRefused(unavailable(agentName, error)); - } - } - if (observed !== undefined) { - livePath = observed.path; - environment = binding.environment(observed.path); - } - } - if (livePath !== undefined && observed === undefined && executableObserver) { - try { - observed = yield* executableObserver.observe(livePath, versionOptions); - } catch (error) { - if (!diagnosticOnly(error)) { - throw new AttachmentRefused(unavailable(agentName, error)); - } - } } - const version = observed === undefined ? undefined : binding.version(observed.versionOutput); return { agentName, agentCommand, livePath, environment, adapterCommand: binding.adapterCommand, - binding: - observed === undefined || version === undefined - ? undefined - : { - schema: "executable-build.v1", - reportedVersion: version, - executableDigest: observed.digest, - }, }; } @@ -2590,22 +2510,6 @@ function* useAcpxProviderState( return undefined; } - /** - * Whether an observation failure says only that the version is unknown. - * - * A selected file that is missing, is not a file, or cannot be executed is an - * availability failure. Anything else the observer reports leaves the - * selection standing and the version undetermined. - */ - function diagnosticOnly(error: unknown): boolean { - return !( - error instanceof ExecutableObservationError && - (error.refusal === "not-found" || - error.refusal === "not-a-file" || - error.refusal === "not-executable") - ); - } - /** * How a retained launch's conversation is reached again over ACP. * @@ -2626,59 +2530,6 @@ function* useAcpxProviderState( return { attachment: { resumeSessionId: prepared.nativeSessionId } }; } - /** - * The availability failure a selected executable that cannot run is. - * - * Only the stable reason crosses: an observer's or selector's own message - * names a path, and a path is host layout. - */ - function unavailable(agentName: string, error: unknown): LaunchFailure { - const reason = error instanceof ExecutableObservationError ? `: ${error.refusal}` : ""; - return { - class: "executable-binding-refused", - message: - `the executable "${agentName}" runs is unavailable${reason}. Install it, or correct the ` + - `environment that selects it.`, - }; - } - - /** - * Warn once, before affected live work, about what the version says. - * - * A version that differs from the session's own history is reported, and so - * is one that cannot be determined. History without a version says nothing, - * so it warns about nothing. The key is added in the same step it is - * tested, so two operations of one invocation cannot both deliver it; the - * set admits nothing and is never written down. - */ - function* warnCompatibility( - ownerCommand: string, - sessionKey: string, - placement: string, - historical: string | undefined, - build: BoundBuild, - ): Operation { - const current = build.binding?.reportedVersion; - const before = historical === undefined ? undefined : productVersion(historical); - const now = current === undefined ? undefined : productVersion(current); - let text: string; - if (now === undefined) { - text = `The ${productName(build.agentName)} version could not be determined. Continuing.`; - } else if (before !== undefined && before !== now) { - text = - `${productName(build.agentName)} has changed from ${before} to ${now} since this session ` + - `was established. Continuing the existing conversation.`; - } else { - return; - } - const key = [ACPX_PROVIDER, ownerCommand, sessionKey, placement].join("\u0000"); - if (compatibilityWarnings.has(key)) { - return; - } - compatibilityWarnings.add(key); - yield* writeDiagnostic(text); - } - /** * What a client-native route's provider arrangement already asserts. * @@ -2711,11 +2562,11 @@ function* useAcpxProviderState( * Select the executable for a session the provider names, and settle its route. * * The route is published or adopted while ownership is held and before ACP is - * asked for anything. A fresh route records the current observation as its - * history when there is a complete one, and the unbound form when there is - * not; an existing route is never rewritten, and a version it records is - * compared with today's only to warn. Whether the conversation continues is - * the provider's live confirmation of its identity, never this comparison. + * asked for anything. A fresh route is the unbound `acp-first` form; an + * existing route is never rewritten, and an executable binding it already + * carries is that session's original history, which a launch preparation + * repeats so the two accounts agree. Whether the conversation continues is the + * provider's live confirmation of its identity. */ function* bindProviderNamed( agentName: string, @@ -2723,7 +2574,6 @@ function* useAcpxProviderState( routeCommand: string, adapter: BoundProviderReturnedAdapter, sessionKey: string, - placement: string, hasProviderState: boolean, ): Operation { const build = yield* selectBuild(agentName, agentCommand, adapter.binding); @@ -2734,9 +2584,7 @@ function* useAcpxProviderState( sessionKey, // deno-lint-ignore require-yield function* () { - return build.binding === undefined - ? acpFirstRoute(routeCommand, sessionKey) - : boundAcpFirstRoute(routeCommand, sessionKey, build.binding); + return acpFirstRoute(routeCommand, sessionKey); }, hasProviderState, ); @@ -2751,25 +2599,17 @@ function* useAcpxProviderState( `"${agentName}" names its own sessions, so neither account describes the other`, }); } - yield* warnCompatibility(routeCommand, sessionKey, placement, historicalVersion(route), build); return { build, ...("executableBinding" in route ? { history: route.executableBinding } : {}), }; } - /** The version a route recorded as its own history, when it recorded one. */ - function historicalVersion(route: AgentSessionRoute | undefined): string | undefined { - return route !== undefined && "executableBinding" in route - ? route.executableBinding.reportedVersion - : undefined; - } - /** What a settled construction route lets one ACP operation do. */ interface SessionConstruction { /** The selected executable every provider effect for this session goes through. */ build: BoundBuild; - /** The executable observation the route recorded as its own history, if any. */ + /** The executable binding the route recorded as its original history, if any. */ history?: ExecutableBuildBindingV1; /** * The exact conversation ACP must open rather than create. @@ -2791,8 +2631,8 @@ function* useAcpxProviderState( * and only when this host has proven that capability for this adapter. * * Every supported adapter's executable is selected here, through the current - * environment, and observed once for its diagnostic. An agent this host - * serves over ACP alone keeps no route, and is selected the same way. + * environment. An agent this host serves over ACP alone keeps no route, and is + * selected the same way. */ function* constructRoute( agentName: string, @@ -2806,11 +2646,8 @@ function* useAcpxProviderState( // Where the route lives, which for a held conversation is where it was // first built. The executable is still selected for today's command. const routeCommand = ownerCommandOf(prepared); - const placement = placementOf(prepared); if (!ownable(agentName)) { - const build = yield* selectBuild(agentName, agentCommand, adapter.binding); - yield* warnCompatibility(routeCommand, prepared.sessionKey, placement, undefined, build); - return { build }; + return { build: yield* selectBuild(agentName, agentCommand, adapter.binding) }; } // An existing managed entry, or a durable record ACPX already kept, is // provider state — and existing history is never reclassified. @@ -2823,7 +2660,6 @@ function* useAcpxProviderState( routeCommand, adapter, prepared.sessionKey, - placement, constructed, ); } @@ -2833,20 +2669,11 @@ function* useAcpxProviderState( prepared.sessionKey, // deno-lint-ignore require-yield function* () { - return build.binding === undefined - ? acpFirstRoute(routeCommand, prepared.sessionKey) - : boundAcpFirstRoute(routeCommand, prepared.sessionKey, build.binding); + return acpFirstRoute(routeCommand, prepared.sessionKey); }, constructed, ); if (route.route !== "client-native") { - yield* warnCompatibility( - routeCommand, - prepared.sessionKey, - placement, - historicalVersion(route), - build, - ); return { build }; } if (!attachable(agentName)) { @@ -2859,21 +2686,9 @@ function* useAcpxProviderState( }); } yield* retainedAssertion(prepared.sessionKey, route.nativeSessionId); - yield* warnCompatibility( - routeCommand, - prepared.sessionKey, - placement, - historicalVersion(route), - build, - ); return { build, resumeSessionId: route.nativeSessionId }; } - /** The directory a session's placement resolved to. */ - function placementOf(prepared: Prepared): string { - return prepared.kind === "existing" ? prepared.entry.cwd : prepared.details.cwd; - } - /** * The prepared instructions, in a file only this invocation can read. * @@ -3481,14 +3296,6 @@ function* useAcpxProviderState( requestId, host: promptUsageHost, ...adapterUsageBuild(agentName, agentCommandOf(prepared)), - ...(construction?.build.binding === undefined - ? {} - : { - native: { - version: construction.build.binding.reportedVersion, - digest: `${construction.build.binding.executableDigest.algorithm}:${construction.build.binding.executableDigest.value}`, - }, - }), }); let completed = false; yield* ensure(function* () { @@ -3718,8 +3525,7 @@ function* useAcpxProviderState( } // Selected before an identity exists, so an executable that cannot run - // stops the launch before anything durable is written. Its observation is - // diagnostic and never decides whether the session continues. + // stops the launch before anything durable is written. let build: BoundBuild; try { build = yield* selectBuild(agentName, agentCommand, adapter.binding); @@ -3735,13 +3541,6 @@ function* useAcpxProviderState( // exists is a value with nowhere to go. A route recorded before XMD kept // executable history resumes the same way, with nothing written into it. if (route?.route === "client-native") { - yield* warnCompatibility( - agentCommand, - sessionKey, - sessionCwd, - historicalVersion(route), - build, - ); invocation.fresh.set(sessionKey, false); invocation.bound.set(sessionKey, { build, adapter }); const confirmed = yield* confirmClientNative( @@ -3766,36 +3565,21 @@ function* useAcpxProviderState( // Publish or adopt: a caller meeting a compatible existing route takes its // retained identity rather than insisting its own candidate win, because - // the first durable publication is authoritative. The current observation - // is recorded as this session's history when there is a complete one. + // the first durable publication is authoritative. A fresh route records + // the facts the session needs and no executable history. let winner: AgentSessionRoute; try { - winner = yield* routeStore!.publish( - build.binding === undefined - ? { - schema: "session-route.v1", - route: "client-native", - provider: ACPX_PROVIDER, - agent: agentCommand, - sessionKey, - nativeSessionId: candidate, - identityProvenance: "client-allocated", - instructionsDigest, - launcher: adapter.launcher, - } - : { - schema: "session-route.v2", - route: "client-native", - provider: ACPX_PROVIDER, - agent: agentCommand, - sessionKey, - nativeSessionId: candidate, - identityProvenance: "client-allocated", - instructionsDigest, - launcher: adapter.launcher, - executableBinding: build.binding, - }, - ); + winner = yield* routeStore!.publish({ + schema: "session-route.v1", + route: "client-native", + provider: ACPX_PROVIDER, + agent: agentCommand, + sessionKey, + nativeSessionId: candidate, + identityProvenance: "client-allocated", + instructionsDigest, + launcher: adapter.launcher, + }); } catch (error) { return refusal("identity-unavailable", routeMessage(error), known); } @@ -3822,13 +3606,6 @@ function* useAcpxProviderState( const fresh = winner.nativeSessionId === candidate; invocation.fresh.set(sessionKey, fresh); invocation.bound.set(sessionKey, { build, adapter }); - yield* warnCompatibility( - agentCommand, - sessionKey, - sessionCwd, - historicalVersion(winner), - build, - ); if (!fresh) { const confirmed = yield* confirmClientNative( invocation, @@ -3995,11 +3772,10 @@ function* useAcpxProviderState( ); } - // Which build this session belongs to, settled before ACP is asked for - // anything. The provider names the session, and the name it issues resolves - // to one conversation only beside the build that issued it — so the build is - // observed, the route recording it is published or adopted, and the two are - // compared, all under ownership and before the first provider effect. + // The executable this session runs through and its construction route, + // settled under ownership before ACP is asked for anything. An existing + // route's original binding is repeated into the preparation below so the + // two accounts agree. let build: BoundBuild | undefined; let history: ExecutableBuildBindingV1 | undefined; if (bindsBuild(adapter)) { @@ -4010,7 +3786,6 @@ function* useAcpxProviderState( agentCommand, adapter, sessionKey, - sessionCwd, existing !== undefined, )); } catch (error) { @@ -4832,7 +4607,9 @@ function* useAcpxProviderState( // A replay that stopped before handing over reaches its conversation here // for the first time, so this is where what it was prepared with is put // back into force — before the detach that follows says the handoff began. - const unconfigured = yield* reconfigureRetained(invocation, prepared, agentCommand); + const unconfigured = yield* invocation.route(() => + reconfigureRetained(invocation, prepared, agentCommand), + ); if (unconfigured) { return { phase: "detached", failure: unconfigured }; } @@ -4907,6 +4684,7 @@ function* useAcpxProviderState( reconciled: new Set(), configured: new Set(), confirmed: new Set(), + route: (op) => withSessionRoute(context, op), }; try { @@ -5147,13 +4925,6 @@ function* useAcpxProviderState( } throw error; } - yield* warnCompatibility( - agentCommand, - prepared.sessionKey, - prepared.cwd, - routeBinding?.reportedVersion ?? prepared.executableBinding?.reportedVersion, - build, - ); invocation.bound.set(prepared.sessionKey, { build, adapter }); return undefined; } @@ -5200,7 +4971,9 @@ function* useAcpxProviderState( // the first time here. It is configured and relinquished again before the // UI opens, and nothing durable is appended for that: the detach this // replay is standing on is the one that happened. - const unconfigured = yield* reconfigureRetained(invocation, prepared, agentCommand); + const unconfigured = yield* invocation.route(() => + reconfigureRetained(invocation, prepared, agentCommand), + ); if (unconfigured) { return { phase: "exited", failure: unconfigured }; } @@ -5228,7 +5001,9 @@ function* useAcpxProviderState( if (!creating) { let unconfirmed: LaunchFailure | undefined; try { - unconfirmed = yield* confirmRetained(invocation, prepared, agentCommand); + unconfirmed = yield* invocation.route(() => + confirmRetained(invocation, prepared, agentCommand), + ); } catch { return { phase: "exited", failure: privateFailure() }; } @@ -5270,14 +5045,16 @@ function* useAcpxProviderState( // reports success. A refusal fails this launch; nothing is created again. let unconfirmed: LaunchFailure | undefined; try { - unconfirmed = yield* confirmClientNative( - invocation, - prepared.agent, - agentCommand, - prepared.sessionKey, - prepared.cwd, - prepared.nativeSessionId, - invocation.bound.get(prepared.sessionKey)?.build, + unconfirmed = yield* invocation.route(() => + confirmClientNative( + invocation, + prepared.agent, + agentCommand, + prepared.sessionKey, + prepared.cwd, + prepared.nativeSessionId, + invocation.bound.get(prepared.sessionKey)?.build, + ), ); } catch { unconfirmed = privateFailure(); @@ -5610,21 +5387,6 @@ function* useAcpxProviderState( }; } -/** How a compatibility warning names the product behind an agent. */ -function productName(agentName: string): string { - return agentName === "codex" ? "Codex" : agentName === "claude" ? "Claude" : agentName; -} - -/** - * The product version a canonical reported version names. - * - * `codex-cli 0.153.2` and `2.1.241 (Claude Code)` are retained whole so two - * products never compare equal; a reader is told the release number. - */ -function productVersion(reported: string): string { - return /\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?/.exec(reported)?.[0] ?? reported; -} - function nativeIdentityRefusal(error: unknown): AttachmentRefused | undefined { if ( error instanceof Error && diff --git a/packages/acp/tests/helpers.ts b/packages/acp/tests/helpers.ts index 88393e5ec..a64518ec7 100644 --- a/packages/acp/tests/helpers.ts +++ b/packages/acp/tests/helpers.ts @@ -16,7 +16,6 @@ import { agentSessionKeyDigest, AgentSessionRecoveryRequired, API, - ExecutableObservationError, } from "@executablemd/runtime"; import type { AgentSessionCoordinator, @@ -24,8 +23,6 @@ import type { AgentSessionOwner, AgentSessionOwnerKind, AgentSessionOwnership, - ExecutableObserver, - ExecutableRefusal, } from "@executablemd/runtime"; import type { AcpAgentRegistry, @@ -41,7 +38,9 @@ import type { AcpSessionRecord, AcpSessionStore, } from "../src/acpx-runtime.ts"; -import type { ProbeCapableRuntime } from "../src/provider.ts"; +import type { AcpxProviderDependencies, ProbeCapableRuntime } from "../src/provider.ts"; +import { bindsBuild, nativeAdapterFor } from "../src/native-launch.ts"; +import type { NativeAdapter } from "../src/native-launch.ts"; import { resolveAgentCommand } from "../src/acpx-runtime.ts"; export function makeRecord(agentCommand: string, cwd: string): AcpSessionRecord { @@ -284,58 +283,55 @@ export function group( return { group: id, name, options }; } -/** One controlled build, as an observer would report it. */ -export interface FakeObservation { +/** A controlled stand-in for the host's own executable selection. */ +export interface FakeSelectionHarness { + /** The executable the next selection names. */ path: string; - digest: string; - versionOutput: string; -} - -export interface FakeObserverHarness { - observer: ExecutableObserver; - /** Every command this observer was asked about, in order. */ - observed: string[]; - /** What the next observation answers, or the failure it raises. */ - observation: FakeObservation; - /** Answers taken in order before `observation`, so a build can change. */ - queued: FakeObservation[]; - failure?: ExecutableRefusal; + /** Paths answered in order before `path`, so a selection can change. */ + queued: string[]; + /** Every agent the host was asked to select for, in order. */ + selected: string[]; + /** Raised by the selector, as a missing or unlaunchable selection is. */ + failure?: Error; + /** + * The provider's `agentProcessEnv` for these adapters. + * + * The same seam a host's carried-adapter selector fills: the selected path, + * under the variable the adapter's child reads. An adapter without an + * executable binding is selected for nothing. + */ + agentProcessEnv( + adapters?: Readonly>, + ): NonNullable; } /** - * A complete substitute for the host's executable observer. + * A complete substitute for the host's executable selection. * - * The whole seam is replaced, exactly as a trusted host supplies the whole - * thing: nothing inside the observer is made replaceable to be testable, so - * drift is expressed by answering differently rather than by a control the - * production path also has. + * The whole seam is replaced, exactly as a trusted host supplies it: a change + * of executable is expressed by selecting a different path, and nothing about + * the file is read or parsed, because production reads nothing either. */ -export function createFakeObserver(observation?: Partial): FakeObserverHarness { - const harness: FakeObserverHarness = { - observed: [], +export function createFakeSelection(path = "/opt/builds/claude"): FakeSelectionHarness { + const harness: FakeSelectionHarness = { + path, queued: [], - observation: { - path: "/opt/builds/claude", - digest: "a".repeat(64), - versionOutput: "2.1.241 (Claude Code)\n", - ...observation, - }, - observer: { + selected: [], + agentProcessEnv(adapters = {}) { // deno-lint-ignore require-yield - *observe(command) { - harness.observed.push(command); + return function* (agentName) { + const adapter = Object.hasOwn(adapters, agentName) + ? adapters[agentName] + : nativeAdapterFor(agentName); + if (adapter === undefined || !bindsBuild(adapter)) { + return undefined; + } + harness.selected.push(agentName); if (harness.failure) { - throw new ExecutableObservationError(`${command} could not be observed`, { - refusal: harness.failure, - }); + throw harness.failure; } - const answer = harness.queued.shift() ?? harness.observation; - return { - path: answer.path, - digest: { algorithm: "sha256", value: answer.digest }, - versionOutput: answer.versionOutput, - }; - }, + return adapter.binding.environment(harness.queued.shift() ?? harness.path); + }; }, }; return harness; diff --git a/packages/acp/tests/host-conversation.test.ts b/packages/acp/tests/host-conversation.test.ts index 35c509b52..dccb01d4e 100644 --- a/packages/acp/tests/host-conversation.test.ts +++ b/packages/acp/tests/host-conversation.test.ts @@ -62,7 +62,7 @@ import type { AgentSessionRouteStore } from "../src/session-route.ts"; import { deriveSessionKey } from "../src/session-key.ts"; import type { AgentSessionRequest } from "@executablemd/agent/api"; import { - createFakeObserver, + createFakeSelection, createFakeRuntime, makeCoordinator, makeRegistry, @@ -247,8 +247,6 @@ function host(options: HostOptions = {}): Host { advertiseClientNativeAttachment: [], coordinator: options.owned.coordinator.coordinator, routeStore: options.owned.routes, - executableObserver: createFakeObserver({ versionOutput: "scribe 1.0.0\n" }) - .observer, }), ...(options.states === false ? {} @@ -1326,7 +1324,7 @@ interface ChangingHost { readonly store: ReturnType; readonly ownership: Owned; readonly runtime: RuntimeBoundary; - readonly observer: ReturnType; + readonly selection: ReturnType; installation(command: string | string[]): ExecutionInstallation; } @@ -1334,19 +1332,12 @@ function changingHost(f: CertificationFixture, agent = AGENT): ChangingHost { const store = createAcpxSessionStore(join(f.dir, "store")); const ownership = owned(); const runtime = runtimeBoundary(); - const observer = createFakeObserver({ - versionOutput: - agent === "codex" - ? "codex-cli 0.163.0\n" - : agent === "claude" - ? "2.1.241 (Claude Code)\n" - : "scribe 1.0.0\n", - }); + const selection = createFakeSelection(`/opt/builds/${agent}`); return { store, ownership, runtime, - observer, + selection, installation(command) { return { *install() { @@ -1363,7 +1354,9 @@ function changingHost(f: CertificationFixture, agent = AGENT): ChangingHost { advertiseClientNativeAttachment: [], coordinator: ownership.coordinator.coordinator, routeStore: ownership.routes, - executableObserver: observer.observer, + agentProcessEnv: selection.agentProcessEnv( + agent === AGENT ? { scribe: BOUND_SCRIBE } : {}, + ), mcpServers: [], newSessionOptions: { allowedTools: [] }, permissions: "strict", @@ -1512,7 +1505,7 @@ describe( ]); const route = yield* target.ownership.routes.read(tuple); expect(route?.route).toBe("acp-first"); - expect(route?.schema).toBe("session-route.v3"); + expect(route?.schema).toBe("session-route.v1"); expect(yield* target.ownership.routes.read({ ...tuple, agent: after })).toBe(undefined); expect( yield* target.ownership.routes.read({ ...tuple, agent: after, sessionKey: natural }), @@ -1749,32 +1742,15 @@ describe( }, ); -/** One supported provider's release before and after a host CLI upgrade. */ -const UPGRADES = { - codex: { - before: "codex-cli 0.163.0", - after: "codex-cli 0.167.1\n", - variable: "CODEX_PATH", - warning: - "Codex has changed from 0.163.0 to 0.167.1 since this session was established. " + - "Continuing the existing conversation.", - }, - claude: { - before: "2.1.241 (Claude Code)", - after: "2.1.250 (Claude Code)\n", - variable: "CLAUDE_CODE_EXECUTABLE", - warning: - "Claude has changed from 2.1.241 to 2.1.250 since this session was established. " + - "Continuing the existing conversation.", - }, -} as const; +/** The variable each supported provider's selected executable reaches its child through. */ +const SELECTED = { codex: "CODEX_PATH", claude: "CLAUDE_CODE_EXECUTABLE" } as const; describe( "resume retention: a held conversation across a host CLI upgrade", { sanitizeOps: false, sanitizeResources: false }, () => { for (const agent of ["codex", "claude"] as const) { - const upgrade = UPGRADES[agent]; + const variable = SELECTED[agent]; for (const [mode, failure, errorName] of [ ["distinct", undefined, undefined], ["normal", "reopened a different native conversation", "AttachmentRefused"], @@ -1801,19 +1777,19 @@ describe( ).toBe("READY"); const record = yield* until(target.store.load(key)); const route = yield* target.ownership.routes.read(tuple); - if (!record?.agentSessionId || route?.schema !== "session-route.v3") { + if (!record?.agentSessionId || route?.route !== "acp-first") { throw new Error("The original build did not establish a native conversation"); } - expect(route.executableBinding.reportedVersion).toBe(upgrade.before); + // A fresh route records how the session was constructed, and no + // executable history. + expect(route.schema).toBe("session-route.v1"); const { lines, stream } = yield* reread(history); const before = yield* f.calls(); if (mode === "missing") { yield* rm(join(f.dir, `fixture-${record.acpSessionId}.json`)); } const runtimeCount = target.runtime.environments.length; - target.observer.observation.path = `/opt/builds/${agent}-next`; - target.observer.observation.versionOutput = upgrade.after; - target.observer.observation.digest = "b".repeat(64); + target.selection.path = `/opt/builds/${agent}-next`; const begun: string[] = []; const published: unknown[] = []; const warned: string[] = []; @@ -1851,11 +1827,10 @@ describe( const methods = calls.map((call) => call.method); const environments = target.runtime.environments.slice(runtimeCount); expect(environments).toContainEqual({ - [upgrade.variable]: `/opt/builds/${agent}-next`, + [variable]: `/opt/builds/${agent}-next`, }); - // The change is reported once, before the conversation is reached, - // whatever happens to the reopening after it. - expect(warned).toEqual([upgrade.warning]); + // Continuation is quiet: the executable changing is not news. + expect(warned).toEqual([]); expect(methods).toContain("session/load"); expect(methods).not.toContain("session/new"); expect( diff --git a/packages/acp/tests/native-launch.test.ts b/packages/acp/tests/native-launch.test.ts index 594507eca..b0b054a5e 100644 --- a/packages/acp/tests/native-launch.test.ts +++ b/packages/acp/tests/native-launch.test.ts @@ -17,7 +17,6 @@ import { describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { ensure, Ok, scoped, sleep, spawn, until, withResolvers } from "effection"; -import { Stdio } from "@effectionx/process"; import type { Operation } from "effection"; import { Agent, sameExecutableBuild } from "@executablemd/agent/api"; import type { ConfigureAgentSession, ProviderSessionConfiguration } from "@executablemd/agent/api"; @@ -62,7 +61,7 @@ import type { AgentSessionRoute, AgentSessionRouteStore } from "../src/session-r import { deriveSessionKey } from "../src/session-key.ts"; import { choice, - createFakeObserver, + createFakeSelection, createFakeRuntime, selector, makeCoordinator, @@ -73,13 +72,12 @@ import { } from "./helpers.ts"; import type { CoordinatorHarness, - FakeObserverHarness, + FakeSelectionHarness, FakeRuntimeHarness, ScriptedTurn, } from "./helpers.ts"; import type { ExecutableBuildBindingV1 } from "@executablemd/agent/api"; import type { AcpxSessionPolicy } from "../src/provider.ts"; -import type { ExecutableObserver } from "@executablemd/runtime"; import type { AcpRuntimeEvent, AcpSessionRecord, AcpSessionStore } from "../src/acpx-runtime.ts"; const CWD = "/work"; @@ -174,39 +172,16 @@ const TEST_BINDING: NativeBinding = { environment: (livePath) => ({ CLAUDE_CODE_EXECUTABLE: livePath }), }; -/** What `createFakeObserver()`'s default observation binds to. */ +/** The executable history an earlier release recorded beside a session. */ const OBSERVED_BUILD: ExecutableBuildBindingV1 = { schema: "executable-build.v1", reportedVersion: "2.1.241 (Claude Code)", executableDigest: { algorithm: "sha256", value: "a".repeat(64) }, }; -/** The canonical path that same observation reports. */ +/** The path the default controlled selection names. */ const OBSERVED_PATH = "/opt/builds/claude"; -/** - * Every diagnostic line this scope's operations write to standard error. - * - * Installed through the same contextual `Stdio` chain a host captures, so what - * a case reads is exactly what a REPL entry or a command's stderr would show. - */ -function* diagnostics(): Operation { - const lines: string[] = []; - const decoder = new TextDecoder(); - yield* Stdio.around({ - // deno-lint-ignore require-yield - *stderr([bytes]) { - lines.push( - ...decoder - .decode(bytes) - .split("\n") - .filter((line) => line.length > 0), - ); - }, - }); - return lines; -} - /** Everything the launch touched, in the order it touched it. */ interface Trace { records: LaunchRecord[]; @@ -243,8 +218,8 @@ interface ProviderOptions { advertise?: readonly string[]; /** Advertised for client-native attachment; defaults to `advertise`. */ attach?: readonly string[]; - /** `false` gives this host no way to observe a build at all. */ - observer?: ExecutableObserver | false; + /** The host's executable selection; `false` gives this host none at all. */ + selection?: FakeSelectionHarness | false; store?: AcpSessionStore; adapters?: Record; /** @@ -463,14 +438,22 @@ function* installLaunchStack( const factory = createAcpxProvider({ createRuntime: harness.create, - ...(options.agentProcessEnv ? { agentProcessEnv: options.agentProcessEnv } : {}), + // The host's own selection, for the adapters that carry an executable. + // One that carries none keeps the ordinary unselected ACP runtime. + ...(options.agentProcessEnv + ? { agentProcessEnv: options.agentProcessEnv } + : options.selection === false || + !Object.values(options.adapters ?? {}).some((adapter) => bindsBuild(adapter)) + ? {} + : { + agentProcessEnv: (options.selection ?? createFakeSelection()).agentProcessEnv( + options.adapters, + ), + }), sessionStore: options.store ?? makeStore(), agentRegistry: makeRegistry({ claude: AGENT_COMMAND, mystery: "mystery-cmd" }), advertiseNativeLaunch: options.advertise ?? ["claude"], advertiseClientNativeAttachment: options.attach ?? options.advertise ?? ["claude"], - ...(options.observer === false - ? {} - : { executableObserver: options.observer ?? createFakeObserver().observer }), coordinator: options.coordinator ?? trace.ownership.coordinator, ...(options.routeStore ? { routeStore: options.routeStore } : {}), ...(options.withSessionRoute ? { withSessionRoute: options.withSessionRoute } : {}), @@ -1804,10 +1787,10 @@ describe("Tier CN — client-allocated construction", () => { expect(prepared.identityProvenance).toBe("client-allocated"); expect(prepared.nativeSessionId).toBe(ALLOCATED); const route = yield* routeOf(routes); - // A new client-native session publishes the bound form: the identity XMD - // chose, beside the build that was observed accepting it. + // A new client-native session publishes the released unbound form: the + // identity XMD chose and the facts it needs, and nothing about the build. expect(route).toEqual({ - schema: "session-route.v2", + schema: "session-route.v1", route: "client-native", provider: "acpx", agent: AGENT_COMMAND, @@ -1816,9 +1799,8 @@ describe("Tier CN — client-allocated construction", () => { identityProvenance: "client-allocated", instructionsDigest: createHash("sha256").update(INSTRUCTIONS).digest("hex"), launcher: "claude", - executableBinding: OBSERVED_BUILD, }); - expect(prepared.executableBinding).toEqual(OBSERVED_BUILD); + expect(prepared.executableBinding).toBe(undefined); expect(trace.launches[0]!.command).toContain(ALLOCATED); // ACP created nothing: this session is materialized by the native process. // After that process exited, the exact allocated identity was loaded once @@ -3072,18 +3054,18 @@ describe("Tier CA — client-native attachment", () => { harness: FakeRuntimeHarness; trace: Trace; routes: AgentSessionRouteStore; - observer: FakeObserverHarness; + selection: FakeSelectionHarness; store: ReturnType; } function* installAttachment( published: AgentSessionRoute | undefined, - options: ProviderOptions & { observer?: ExecutableObserver | false } = {}, + options: ProviderOptions = {}, ): Operation { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); const store = makeStore(); if (published) { yield* routes.publish(published); @@ -3092,10 +3074,19 @@ describe("Tier CA — client-native attachment", () => { adapters: { claude: adapter() }, routeStore: routes, store, - observer: options.observer === undefined ? observer.observer : options.observer, + selection: options.selection === undefined ? selection : options.selection, ...options, }); - return { harness, trace, routes, observer, store }; + return { + harness, + trace, + routes, + selection: + options.selection === undefined || options.selection === false + ? selection + : options.selection, + store, + }; } /** What a Session attempt raised, or nothing. */ @@ -3123,9 +3114,8 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.ensureCalls).toHaveLength(1); expect(space.harness.ensureCalls[0]?.resumeSessionId).toBe(ALLOCATED); expect(session.agentSessionId).toBe(ALLOCATED); - // The host's own selection is the file observed and the file the child - // runs; nothing resolved the launcher name again on its own. - expect(space.observer.observed).toEqual([selected]); + // The host's own selection is the file the child runs; nothing resolved + // the launcher name again on its own. const options = space.harness.createdOptions.at(-1); expect(options?.agentProcessEnv).toEqual({ CLAUDE_CODE_EXECUTABLE: selected }); expect(options?.agentRegistry.resolve("claude")).toBe(AGENT_COMMAND); @@ -3153,7 +3143,6 @@ describe("Tier CA — client-native attachment", () => { yield* Agent.operations.session(); - expect(space.observer.observed).toEqual(["relative/bin/codex"]); expect(space.harness.createdOptions.at(-1)?.agentProcessEnv).toEqual({ CODEX_PATH: "relative/bin/codex", }); @@ -3169,7 +3158,6 @@ describe("Tier CA — client-native attachment", () => { const raised = yield* attach(); expect(raised?.message).toContain("is unavailable"); - expect(space.observer.observed).toEqual([]); expect(space.harness.createdOptions).toEqual([]); expect(space.harness.ensureCalls).toEqual([]); }); @@ -3229,9 +3217,8 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.turns).toEqual([]); }); - it("CA4: a host that cannot observe a version continues, and says so once", function* () { - const lines = yield* diagnostics(); - const space = yield* installAttachment(bound(), { observer: false }); + it("CA4: a host that makes no selection runs the declared command and continues", function* () { + const space = yield* installAttachment(bound(), { selection: false }); const session = yield* Agent.operations.session(); yield* Agent.operations.session(); @@ -3241,92 +3228,55 @@ describe("Tier CA — client-native attachment", () => { ALLOCATED, ALLOCATED, ]); - expect(lines).toEqual(["The Claude version could not be determined. Continuing."]); + expect(space.harness.createdOptions.at(-1)?.agentProcessEnv ?? {}).toEqual({}); }); - it("CA5: a changed, moved, unrecognized or unaskable build continues the same conversation", function* () { - for (const [name, mutate, warning] of [ - [ - "another build at the same path", - (observer: FakeObserverHarness) => { - observer.observation.digest = "b".repeat(64); - }, - [], - ], - [ - "identical bytes at another path", - (observer: FakeObserverHarness) => { - observer.observation.path = "/moved/claude"; - }, - [], - ], - [ - "another version of the same product", - (observer: FakeObserverHarness) => { - observer.observation.versionOutput = "2.1.242 (Claude Code)\n"; - observer.observation.digest = "c".repeat(64); - }, - [ - "Claude has changed from 2.1.241 to 2.1.242 since this session was established. " + - "Continuing the existing conversation.", - ], - ], - [ - "output this adapter does not recognize", - (observer: FakeObserverHarness) => { - observer.observation.versionOutput = "claude version 2.1.241\n"; - }, - ["The Claude version could not be determined. Continuing."], - ], - [ - "an executable that would not say its version", - (observer: FakeObserverHarness) => { - observer.failure = "version-unavailable"; - }, - ["The Claude version could not be determined. Continuing."], - ], - ] as const) { + it("CA5: a replaced, moved or rebuilt executable continues the same conversation", function* () { + // Nothing about the file is read: a different file at the same path, the + // same bytes at another path, and new bytes that report the same version + // are all just today's selection. + for (const path of [OBSERVED_PATH, "/moved/claude", "/rebuilt/claude"]) { yield* scoped(function* () { - const lines = yield* diagnostics(); - const observer = createFakeObserver(); - mutate(observer); - const space = yield* installAttachment(bound(), { observer: observer.observer }); + const selection = createFakeSelection(path); + const space = yield* installAttachment(bound(), { selection }); const session = yield* Agent.operations.session(); - expect([name, session.agentSessionId]).toEqual([name, ALLOCATED]); - expect([name, space.harness.ensureCalls.map((call) => call.resumeSessionId)]).toEqual([ - name, + expect([path, session.agentSessionId]).toEqual([path, ALLOCATED]); + expect([path, space.harness.ensureCalls.map((call) => call.resumeSessionId)]).toEqual([ + path, [ALLOCATED], ]); - expect([name, lines]).toEqual([name, warning]); + expect([path, space.harness.createdOptions.at(-1)?.agentProcessEnv]).toEqual([ + path, + { CLAUDE_CODE_EXECUTABLE: path }, + ]); // The route is history, and nothing rewrote it to claim today's build. - expect([name, yield* space.routes.read(KEY)]).toEqual([name, bound()]); - expect([name, lines.join("\n").includes(OBSERVED_PATH)]).toEqual([name, false]); + expect([path, yield* space.routes.read(KEY)]).toEqual([path, bound()]); }); } }); - it("CA5b: a selected executable that is missing or cannot run is unavailable", function* () { - for (const failure of ["not-found", "not-a-file", "not-executable"] as const) { - yield* scoped(function* () { - const observer = createFakeObserver(); - observer.failure = failure; - const space = yield* installAttachment(bound(), { observer: observer.observer }); + it("CA5b: a selection that is missing or cannot run is unavailable", function* () { + const selection = createFakeSelection(); + selection.failure = new Error( + "Host Claude Code is unavailable. Install claude on the host PATH or correct " + + "CLAUDE_CODE_EXECUTABLE to select a launchable host executable.", + ); + const space = yield* installAttachment(bound(), { selection }); - const raised = yield* attach(); + const raised = yield* attach(); - expect([failure, raised?.message.includes("is unavailable")]).toEqual([failure, true]); - expect([failure, space.harness.ensureCalls]).toEqual([failure, []]); - }); - } + expect(raised?.message).toContain("is unavailable"); + expect(space.harness.ensureCalls).toEqual([]); + expect(space.harness.createdOptions).toEqual([]); }); it("CA6: a moved build is the same build", function* () { // Equality is over what was retained — a version and a digest — so the same // bytes reached at another path attach exactly as they would have before. - const observer = createFakeObserver({ path: "/elsewhere/bin/claude" }); - const space = yield* installAttachment(bound(), { observer: observer.observer }); + const selection = createFakeSelection("/elsewhere/bin/claude"); + const space = yield* installAttachment(bound(), { selection }); const session = yield* Agent.operations.session(); @@ -3399,16 +3349,9 @@ describe("Tier CA — client-native attachment", () => { // A binding compares a version and a digest, so the same build found // somewhere else is the same partition key and a different file to run — // and handing the next attachment the old path is how it would run one. - const observer = createFakeObserver(); - observer.queued = [ - { path: OBSERVED_PATH, digest: "a".repeat(64), versionOutput: "2.1.241 (Claude Code)\n" }, - { - path: "/moved/bin/claude", - digest: "a".repeat(64), - versionOutput: "2.1.241 (Claude Code)\n", - }, - ]; - const space = yield* installAttachment(bound(), { observer: observer.observer }); + const selection = createFakeSelection(); + selection.queued = [OBSERVED_PATH, "/moved/bin/claude"]; + const space = yield* installAttachment(bound(), { selection }); // A second session bound to the same build, so what the next attachment // reaches for is the same partition. It is a different session because the // refusal below withholds quiescence, and a session whose owner never @@ -3427,7 +3370,7 @@ describe("Tier CA — client-native attachment", () => { const session = yield* Agent.operations.session("second"); expect(session.agentSessionId).toBe(SECOND_ALLOCATED); - expect(observer.observed).toEqual(["claude", "claude"]); + expect(selection.selected).toEqual(["claude", "claude"]); expect( space.harness.createdOptions.map( (options) => options.agentProcessEnv?.CLAUDE_CODE_EXECUTABLE, @@ -3567,16 +3510,9 @@ describe("Tier CA — client-native attachment", () => { }); it("CA16: a halted ensure that then fails gives its claim back", function* () { - const observer = createFakeObserver(); - observer.queued = [ - { path: OBSERVED_PATH, digest: "a".repeat(64), versionOutput: "2.1.241 (Claude Code)\n" }, - { - path: "/moved/bin/claude", - digest: "a".repeat(64), - versionOutput: "2.1.241 (Claude Code)\n", - }, - ]; - const space = yield* installAttachment(bound(), { observer: observer.observer }); + const selection = createFakeSelection(); + selection.queued = [OBSERVED_PATH, "/moved/bin/claude"]; + const space = yield* installAttachment(bound(), { selection }); const second = deriveSessionKey(AGENT_COMMAND, CWD, "second"); yield* space.routes.publish(bound({ sessionKey: second, nativeSessionId: SECOND_ALLOCATED })); const gate = withResolvers(); @@ -3596,7 +3532,7 @@ describe("Tier CA — client-native attachment", () => { space.harness.ensureGate = undefined; const later = yield* Agent.operations.session("second"); expect(later.agentSessionId).toBe(SECOND_ALLOCATED); - expect(observer.observed).toEqual(["claude", "claude"]); + expect(selection.selected).toEqual(["claude", "claude"]); expect( space.harness.createdOptions.map( (options) => options.agentProcessEnv?.CLAUDE_CODE_EXECUTABLE, @@ -3611,16 +3547,9 @@ describe("Tier CA — client-native attachment", () => { // canonical executable path. Reusing it re-ensures, and the observation // that goes with it is a fresh one: a value that still named a runtime // would answer from the path that runtime was built with. - const observer = createFakeObserver(); - observer.queued = [ - { path: OBSERVED_PATH, digest: "a".repeat(64), versionOutput: "2.1.241 (Claude Code)\n" }, - { - path: "/moved/bin/claude", - digest: "a".repeat(64), - versionOutput: "2.1.241 (Claude Code)\n", - }, - ]; - const space = yield* installAttachment(bound(), { observer: observer.observer }); + const selection = createFakeSelection(); + selection.queued = [OBSERVED_PATH, "/moved/bin/claude"]; + const space = yield* installAttachment(bound(), { selection }); const session = yield* Agent.operations.session(); expect(session.agentSessionId).toBe(ALLOCATED); @@ -3639,7 +3568,7 @@ describe("Tier CA — client-native attachment", () => { // The same conversation, reached again — by observing the build afresh and // building a runtime around what that observation found. - expect(observer.observed).toEqual(["claude", "claude"]); + expect(selection.selected).toEqual(["claude", "claude"]); expect(space.harness.ensureCalls).toHaveLength(2); expect(space.harness.ensureCalls[1]?.resumeSessionId).toBe(ALLOCATED); expect( @@ -3693,23 +3622,7 @@ describe("Tier CA — client-native attachment", () => { expect(space.harness.createdOptions).toHaveLength(2); }); - it("CA14: output naming several builds is an undetermined version, not a refusal", function* () { - const lines = yield* diagnostics(); - const observer = createFakeObserver({ - versionOutput: "2.1.241 (Claude Code)\n2.1.242 (Claude Code)\n", - }); - const space = yield* installAttachment(bound(), { observer: observer.observer }); - - const session = yield* Agent.operations.session(); - - expect(session.agentSessionId).toBe(ALLOCATED); - // Nothing was repeated back: the output is the provider's, not the reader's. - expect(lines).toEqual(["The Claude version could not be determined. Continuing."]); - expect(space.harness.turns).toEqual([]); - }); - it("CA9: a legacy unbound route attaches through today's selection, and stays as it was", function* () { - const lines = yield* diagnostics(); const space = yield* installAttachment(legacy()); const session = yield* Agent.operations.session(); @@ -3717,7 +3630,6 @@ describe("Tier CA — client-native attachment", () => { // Missing historical build evidence alone establishes no difference. expect(session.agentSessionId).toBe(ALLOCATED); expect(space.harness.ensureCalls.map((call) => call.resumeSessionId)).toEqual([ALLOCATED]); - expect(lines).toEqual([]); // The route is left exactly as it was: not upgraded, not supplemented. expect(yield* space.routes.read(KEY)).toEqual(legacy()); }); @@ -3807,18 +3719,18 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); yield* routes.publish(route(SESSION_KEY, FIRST)); yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, }); yield* Agent.operations.session(); yield* Agent.operations.session(); - expect(observer.observed).toEqual(["claude", "claude"]); + expect(selection.selected).toEqual(["claude", "claude"]); expect(environments(harness)).toEqual([OBSERVED_PATH, OBSERVED_PATH]); // Each handle was closed through the runtime that created it. expect(harness.closeCalls).toHaveLength(2); @@ -3828,19 +3740,18 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); yield* routes.publish(route(SESSION_KEY, FIRST)); yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, }); yield* Agent.operations.session(); // The same command and a different file behind it. The same conversation // continues, and it does so through a child of its own. - observer.observation.digest = "c".repeat(64); - observer.observation.path = "/opt/builds/other-claude"; + selection.path = "/opt/builds/other-claude"; const session = yield* Agent.operations.session(); expect(session.agentSessionId).toBe(FIRST); @@ -3863,18 +3774,15 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); - observer.queued = [ - { path: OBSERVED_PATH, digest: "a".repeat(64), versionOutput: "2.1.241 (Claude Code)\n" }, - { path: OTHER_PATH, digest: "d".repeat(64), versionOutput: "2.1.242 (Claude Code)\n" }, - ]; + const selection = createFakeSelection(); + selection.queued = [OBSERVED_PATH, OTHER_PATH]; const second = deriveSessionKey(AGENT_COMMAND, CWD, "second"); yield* routes.publish(route(SESSION_KEY, FIRST)); yield* routes.publish(route(second, SECOND, other)); yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, }); yield* Agent.operations.session(); @@ -3893,7 +3801,7 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); const held = deriveSessionKey(AGENT_COMMAND, CWD, "held"); const failing = deriveSessionKey(AGENT_COMMAND, CWD, "failing"); const later = deriveSessionKey(AGENT_COMMAND, CWD, "later"); @@ -3903,7 +3811,7 @@ describe("Tier RT — bound runtime partitions", () => { yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, }); const gate = withResolvers(); @@ -3963,7 +3871,7 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); const barrier = createCwdBarrier(CWD); const alpha = deriveSessionKey(AGENT_COMMAND, CWD, "alpha"); const beta = deriveSessionKey(AGENT_COMMAND, CWD, "beta"); @@ -3972,7 +3880,7 @@ describe("Tier RT — bound runtime partitions", () => { yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, agentCwd: barrier.agentCwd, }); @@ -4013,7 +3921,7 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); const held = deriveSessionKey(AGENT_COMMAND, CWD, "held"); const beta = deriveSessionKey(AGENT_COMMAND, CWD, "beta"); const gamma = deriveSessionKey(AGENT_COMMAND, CWD, "gamma"); @@ -4025,7 +3933,7 @@ describe("Tier RT — bound runtime partitions", () => { yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, }); const gate = withResolvers(); @@ -4089,7 +3997,7 @@ describe("Tier RT — bound runtime partitions", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); const barrier = createCwdBarrier(CWD); const held = deriveSessionKey(AGENT_COMMAND, CWD, "held"); const sibling = deriveSessionKey(AGENT_COMMAND, CWD, "sibling"); @@ -4102,7 +4010,7 @@ describe("Tier RT — bound runtime partitions", () => { yield* installLaunchStack(harness, trace, { adapters: { claude: adapter() }, routeStore: routes, - observer: observer.observer, + selection, agentCwd: barrier.agentCwd, }); @@ -4272,13 +4180,13 @@ describe("Tier LU — legacy unbound client-native", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); harness.activity = (event) => trace.order.push(event); yield* routes.publish(legacyRoute()); yield* installLaunchStack(harness, trace, { adapters: { claude: ADAPTER }, routeStore: routes, - observer: observer.observer, + selection, }); yield* launch(INSTRUCTIONS); @@ -4307,12 +4215,12 @@ describe("Tier LU — legacy unbound client-native", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); yield* routes.publish(legacyRoute()); yield* installLaunchStack(harness, trace, { adapters: { claude: ADAPTER }, routeStore: routes, - observer: observer.observer, + selection, }); trace.replay = { prepared: legacyRecord(), suffix }; @@ -4350,7 +4258,7 @@ describe("Tier LU — legacy unbound client-native", () => { * show none of them is touched. */ describe("Tier AO — explicit ACP-only capability", () => { - it("AO1: an ACP-only Claude prompt touches no coordinator or route, and observes only for diagnostics", function* () { + it("AO1: an ACP-only Claude prompt touches no coordinator or route", function* () { const touched: string[] = []; const harness = createFakeRuntime(); const trace = newTrace(); @@ -4383,15 +4291,6 @@ describe("Tier AO — explicit ACP-only capability", () => { return candidate; }, }, - // Diagnostic only: a failure here leaves the version undetermined and the - // turn running. - executableObserver: { - // deno-lint-ignore require-yield - *observe() { - touched.push("observer"); - throw new Error("this observation is diagnostic"); - }, - }, }); yield* scoped(function* () { @@ -4411,7 +4310,7 @@ describe("Tier AO — explicit ACP-only capability", () => { // The turn happened, through the ordinary ACP path, and no machine-wide // account was consulted. expect(harness.turns).toHaveLength(1); - expect(touched).toEqual(["observer"]); + expect(touched).toEqual([]); }); }); @@ -4497,6 +4396,15 @@ describe("Tier BA — bound ACP-first construction", () => { executableBinding: OBSERVED_BUILD, }; + /** The route a fresh construction publishes: the released unbound form. */ + const FRESH_ROUTE: AgentSessionRoute = { + schema: "session-route.v1", + route: "acp-first", + provider: "acpx", + agent: AGENT_COMMAND, + sessionKey: SESSION_KEY, + }; + function* installBound( harness: FakeRuntimeHarness, trace: Trace, @@ -4513,7 +4421,7 @@ describe("Tier BA — bound ACP-first construction", () => { return yield* store.read({ provider: "acpx", agent: AGENT_COMMAND, sessionKey: SESSION_KEY }); } - it("BA1: the bound route is published before ACP creates anything", function* () { + it("BA1: the unbound route is published before ACP creates anything", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); @@ -4532,13 +4440,15 @@ describe("Tier BA — bound ACP-first construction", () => { yield* launch(INSTRUCTIONS); expect(ensuresAtPublication).toEqual([0]); - expect(yield* routeOf(routes)).toEqual(BOUND_ROUTE); + // How the session was constructed, and nothing about the executable that + // constructed it. + expect(yield* routeOf(routes)).toEqual(FRESH_ROUTE); const prepared = preparedOf(trace); // XMD supplied no identity and accepted only what the provider asserted. expect(prepared.identityProvenance).toBe("provider-returned"); expect(prepared.nativeSessionId).toBe(ASSERTED); - expect(prepared.executableBinding).toEqual(OBSERVED_BUILD); + expect(prepared.executableBinding).toBe(undefined); // The launch spends no model turn. expect(harness.turns).toEqual([]); }); @@ -4546,15 +4456,15 @@ describe("Tier BA — bound ACP-first construction", () => { it("BA2: ACP creation and the native resume go through one observed build", function* () { const harness = createFakeRuntime(); const trace = newTrace(); - const observer = createFakeObserver(); - yield* installBound(harness, trace, { observer: observer.observer }); + const selection = createFakeSelection(); + yield* installBound(harness, trace, { selection }); yield* launch(INSTRUCTIONS); // Observed once, under ownership, and both sides of the handoff run it: the // ACP child through its transient environment, the native child in place of // the launcher name the adapter returned. - expect(observer.observed).toEqual(["claude"]); + expect(selection.selected).toEqual(["claude"]); const created = only(harness.createdOptions, "a created runtime"); const launched = only(trace.launches, "a native launch"); expect(created.agentProcessEnv?.CLAUDE_CODE_EXECUTABLE).toBe(OBSERVED_PATH); @@ -4581,39 +4491,35 @@ describe("Tier BA — bound ACP-first construction", () => { } }); - it("BA4: a changed build reopens the same conversation under live confirmation", function* () { + it("BA4: a changed executable reopens the same conversation under live confirmation", function* () { const harness = createFakeRuntime(); const trace = newTrace(); + // A route an earlier release published with executable history. It is + // original evidence: kept exactly, repeated into the preparation, and never + // compared with today's executable. const routes = createMemorySessionRouteStore(); + yield* routes.publish(BOUND_ROUTE); const store = makeStore(); yield* installBound(harness, trace, { routeStore: routes, store }); yield* launch(INSTRUCTIONS); const published = yield* routeOf(routes); + expect(published).toEqual(BOUND_ROUTE); const drifted = createFakeRuntime(); const second = newTrace(); - const observer = createFakeObserver({ - path: "/opt/builds/claude-next", - versionOutput: "2.1.242 (Claude Code)\n", - digest: "b".repeat(64), - }); + const selection = createFakeSelection("/opt/builds/claude-next"); yield* scoped(function* () { - const lines = yield* diagnostics(); yield* installBound(drifted, second, { routeStore: routes, store, - observer: observer.observer, + selection, }); const refusal = yield* attempt(second, INSTRUCTIONS); expect(refusal).toBe(undefined); - expect(lines).toEqual([ - "Claude has changed from 2.1.241 to 2.1.242 since this session was established. " + - "Continuing the existing conversation.", - ]); }); - // The retained conversation, reopened strictly through today's build and - // resumed by the same identity. The route keeps its original history. + // The retained conversation, reopened strictly through today's selection + // and resumed by the same identity. The route keeps its original history. expect(drifted.ensureCalls[0]).toMatchObject({ expectedAgentSessionId: ASSERTED }); expect(second.launches[0]?.command).toEqual(["/opt/builds/claude-next", "--resume", ASSERTED]); expect(preparedOf(second).executableBinding).toEqual(OBSERVED_BUILD); @@ -4717,7 +4623,7 @@ describe("Tier BA — bound ACP-first construction", () => { expect(only(harness.closeInputs, "a close").discardPersistentState).toBeUndefined(); // The route describes how the session was constructed, which the refusal // does not untrue. - expect(yield* routeOf(routes)).toEqual(BOUND_ROUTE); + expect(yield* routeOf(routes)).toEqual(FRESH_ROUTE); }); it("BA7: a host with no route store refuses this agent before provider work", function* () { @@ -5180,10 +5086,7 @@ describe("Tier MZ — the materialization turn", () => { yield* installOwing(drifted, afterDrift, { routeStore: routes, store, - observer: createFakeObserver({ - versionOutput: "2.1.242 (Claude Code)\n", - digest: "b".repeat(64), - }).observer, + selection: createFakeSelection("/opt/builds/claude-next"), }); expect(yield* attempt(afterDrift, INSTRUCTIONS)).toBe(undefined); }); @@ -5722,13 +5625,13 @@ describe("Tier NR — configured incomplete replay", () => { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver(); + const selection = createFakeSelection(); advertiseConfiguration(harness, trace); yield* scoped(function* () { yield* installLaunchStack(harness, trace, { adapters: { claude: BOUND_CLAUDE }, routeStore: routes, - observer: observer.observer, + selection, }); yield* routes.publish(BOUND_ACP_ROUTE); trace.replay = { @@ -5755,7 +5658,7 @@ describe("Tier NR — configured incomplete replay", () => { // reattachment went through the build that check verified: the runtime // this ensure was made on carries that build's transient environment, // and the native UI runs the same file. - expect(observer.observed).toEqual(["claude"]); + expect(selection.selected).toEqual(["claude"]); const created = only(harness.createdOptions, "a created runtime"); expect(created.agentProcessEnv?.CLAUDE_CODE_EXECUTABLE).toBe(OBSERVED_PATH); expect(harness.closeRuntimes).toEqual([OBSERVED_PATH]); @@ -5775,21 +5678,17 @@ describe("Tier NR — configured incomplete replay", () => { }); }); - it("NR5: a detached replay through a changed build reopens, reconfigures and resumes", function* () { + it("NR5: a detached replay with original history reopens, reconfigures and resumes", function* () { const harness = createFakeRuntime(); const trace = newTrace(); const routes = createMemorySessionRouteStore(); - const observer = createFakeObserver({ - versionOutput: "2.1.242 (Claude Code)\n", - digest: "b".repeat(64), - }); + const selection = createFakeSelection(); advertiseConfiguration(harness, trace); yield* scoped(function* () { - const lines = yield* diagnostics(); yield* installLaunchStack(harness, trace, { adapters: { claude: BOUND_CLAUDE }, routeStore: routes, - observer: observer.observer, + selection, }); yield* routes.publish(BOUND_ACP_ROUTE); trace.replay = { @@ -5801,8 +5700,6 @@ describe("Tier NR — configured incomplete replay", () => { const exited = trace.records.find((record) => record.phase === "exited"); expect(exited?.failure).toBe(undefined); - expect(lines).toHaveLength(1); - expect(lines[0]).toContain("from 2.1.241 to 2.1.242"); // The retained conversation is reached first, put back under what it was // prepared with, released, and only then resumed natively. expect(trace.order[2]).toBe("ensure"); @@ -5960,7 +5857,7 @@ describe("Tier NR — configured incomplete replay", () => { advertise: ["codex"], adapters: { codex }, routeStore: routes, - observer: createFakeObserver({ versionOutput: "codex-cli 0.169.1\n" }).observer, + selection: createFakeSelection("/opt/builds/codex"), }); yield* routes.publish({ schema: "session-route.v1", diff --git a/packages/agent/src/launch.ts b/packages/agent/src/launch.ts index 2f5926c26..afa3f46de 100644 --- a/packages/agent/src/launch.ts +++ b/packages/agent/src/launch.ts @@ -126,9 +126,9 @@ export type IdentityProvenance = "provider-returned" | "client-allocated"; /** * Which build of a provider executable a session was established against. * - * Diagnostic history: a later run reports when the version it observes - * differs, and continues. The record is never rewritten with today's build, - * and its absence says nothing. + * Original history an earlier release recorded. Fresh records carry none; an + * existing one is never rewritten with today's build, only compared with the + * other original account of the same session, and its absence says nothing. * * What is retained is deliberately not a path: a path says where a build was, * which stops being true, while a version and a digest say which build it was, @@ -282,14 +282,10 @@ export interface PreparedLaunchRecord { */ identityProvenance: IdentityProvenance; /** - * Which build the provider-native identity belongs to, present exactly when - * the adapter behind it binds one. Independent of who chose the identity: a - * build accepted the name XMD allocated, or issued the name XMD was handed, - * and neither name resolves to one conversation without it. - * - * Optional because both paths were released before any build was observed. A - * record without it is legacy history: readable, resumable by the native-only - * contract that wrote it, and never an attachable session. + * The executable binding the existing construction route recorded, repeated + * so the two original accounts agree. Fresh preparations carry none, and a + * record without one is readable and continued like any other: absence + * alone never refuses. */ executableBinding?: ExecutableBuildBindingV1; /** diff --git a/packages/cli/src/agent-stack.ts b/packages/cli/src/agent-stack.ts index fac9d63e3..743027e45 100644 --- a/packages/cli/src/agent-stack.ts +++ b/packages/cli/src/agent-stack.ts @@ -65,13 +65,6 @@ export interface PlanWriterStack { adapters: EmbeddedAdapters; /** What this host states about machine-wide agent sessions, if anything. */ sessions?: MachineSessionAssembly; - /** - * The sessions this invocation has already warned about. - * - * Owned by the invocation and shared with every provider its stack builds. - * Absent leaves each provider installation its own. - */ - compatibilityWarnings?: Set; } /** Everything one `xmd run` invocation settled about agents, resolved once. */ @@ -90,7 +83,6 @@ export interface AgentStack extends PlanWriterStack { export function* resolvePlanWriterStack( flags: AuthorshipFlags, sessions: MachineSessionAssembly | undefined, - compatibilityWarnings?: Set, ): Operation> { if (flags.agentProvider !== "acpx") { return Err(new Error(`Unknown agent provider "${flags.agentProvider}"`)); @@ -101,7 +93,6 @@ export function* resolvePlanWriterStack( defaultAgent, adapters: createEmbeddedAdapters(DEFAULT_ADAPTER_ROOT), ...(sessions === undefined ? {} : { sessions }), - ...(compatibilityWarnings === undefined ? {} : { compatibilityWarnings }), }); } @@ -125,7 +116,6 @@ export function* contextualAgent(): Operation { export function* resolveAgentStack( flags: AgentFlags, sessions: MachineSessionAssembly | undefined, - compatibilityWarnings?: Set, ): Operation> { const config = resolveAgentConfig(flags); if ("error" in config) { @@ -134,7 +124,6 @@ export function* resolveAgentStack( const planWriter = yield* resolvePlanWriterStack( { agentProvider: flags.agentProvider, defaultAgent: config.defaultAgent }, sessions, - compatibilityWarnings, ); if (!planWriter.ok) { return planWriter; @@ -161,9 +150,6 @@ export function hostAcpDependencies(stack: PlanWriterStack): AcpxProviderDepende ...embeddedAdapterDependencies(stack.adapters), sessionStore: createAcpxSessionStore(join(homedir(), ".acpx")), ...(sessions?.usage === undefined ? {} : { promptUsageHost: sessions.usage }), - ...(stack.compatibilityWarnings === undefined - ? {} - : { compatibilityWarnings: stack.compatibilityWarnings }), }; if (sessions === undefined) { return adapters; @@ -172,7 +158,6 @@ export function hostAcpDependencies(stack: PlanWriterStack): AcpxProviderDepende ...adapters, ...(sessions.coordinator ? { coordinator: sessions.coordinator } : {}), ...(sessions.routeStore ? { routeStore: sessions.routeStore } : {}), - ...(sessions.executableObserver ? { executableObserver: sessions.executableObserver } : {}), advertiseNativeLaunch: sessions.advertiseNativeLaunch, advertiseClientNativeAttachment: sessions.advertiseClientNativeAttachment, }; diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 953eef69d..db69cbce5 100755 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -1218,9 +1218,8 @@ function* underRunDeadline(timeouts: RunTimeouts, body: () => Operation): function* settleAgentStack( flags: AgentFlags, sessions: MachineSessionAssembly | undefined, - compatibilityWarnings: Set, ): Operation { - const stack = yield* resolveAgentStack(flags, sessions, compatibilityWarnings); + const stack = yield* resolveAgentStack(flags, sessions); if (!stack.ok) { console.error(stack.error.message); yield* exit(1); @@ -2977,14 +2976,6 @@ function* dispatch( workflowHost: WorkflowHost | undefined, sessions: MachineSessionAssembly | undefined, replHost: ReplHostAssembly | undefined, - /** - * The sessions this invocation has already warned about. - * - * One set for the whole command, shared by every provider it installs, so a - * session is reported once however many entries, roles or nested runs reach - * it. Transient: it is never retained and admits nothing. - */ - compatibilityWarnings: Set, /** * What this invocation's Plugins installed. * @@ -3093,7 +3084,6 @@ function* dispatch( denyAll: config.denyAll, }, sessions, - compatibilityWarnings, ); if (runStack === undefined) { break; @@ -3150,7 +3140,6 @@ function* dispatch( const planWriter = yield* resolvePlanWriterStack( { agentProvider: config.agentProvider, defaultAgent: config.defaultAgent }, sessions, - compatibilityWarnings, ); if (!planWriter.ok) { console.error(planWriter.error.message); @@ -3249,7 +3238,6 @@ function* dispatch( denyAll: command.config.denyAll, }, sessions, - compatibilityWarnings, ); if (replStack === undefined) { break; @@ -3542,7 +3530,6 @@ function* dispatch( // than a document-level default: nothing here runs a document. { agentProvider: "acpx", defaultAgent: scan.agent }, sessions, - compatibilityWarnings, ); if (!stack.ok) { console.error(stack.error.message); @@ -3859,9 +3846,6 @@ function* runCommand( sessions: MachineSessionAssembly | undefined, replHost: ReplHostAssembly | undefined, ): Operation { - // This invocation's compatibility warnings, shared by every provider it - // installs and gone when it ends. A new invocation can warn again. - const compatibilityWarnings = new Set(); // First, so that no later scanner — help, properties, agent flags — can // mistake the inline document's own text for an option. const evalFlags = readEvalFlags(args); @@ -3898,7 +3882,7 @@ function* runCommand( let workflowHost: WorkflowHost | undefined; if (!helpRequest.requested && namesWorkflow(helpRequest.args)) { try { - workflowHost = yield* installWorkflowHost({ compatibilityWarnings }); + workflowHost = yield* installWorkflowHost(); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); yield* exit(1); @@ -3978,7 +3962,6 @@ function* runCommand( denyAll: selected.config.denyAll, }, sessions, - compatibilityWarnings, ); if (stack === undefined) { return; @@ -4012,7 +3995,6 @@ function* runCommand( workflowHost, sessions, replHost, - compatibilityWarnings, plugins, (document) => installTestPlugins(document, selection, loadPluginModule), cold, diff --git a/packages/cli/src/compiled.ts b/packages/cli/src/compiled.ts index 7b7c6df54..4a457adc0 100644 --- a/packages/cli/src/compiled.ts +++ b/packages/cli/src/compiled.ts @@ -149,7 +149,7 @@ if (isReplSubmit(process.argv.slice(2))) { UPGRADE, () => readInputStream(process.stdin), importPluginModule, - (options) => useDenoWorkflowHost(HELPER, USAGE, options?.compatibilityWarnings), + () => useDenoWorkflowHost(HELPER, USAGE), { ...useMachineSessions(), usage: USAGE }, // What this host selects for a REPL command, and what it installs for // one. The selection is the capability an entry runs with — its diff --git a/packages/cli/src/deno-workflow.ts b/packages/cli/src/deno-workflow.ts index 93d0ed7f0..09ca29e7a 100644 --- a/packages/cli/src/deno-workflow.ts +++ b/packages/cli/src/deno-workflow.ts @@ -23,7 +23,7 @@ import type { PromptUsageHost } from "@executablemd/acp"; import { homedir } from "node:os"; import { join } from "node:path"; import type { Operation } from "effection"; -import { createDenoExecutableObserver, env as readEnv } from "@executablemd/runtime"; +import { env as readEnv } from "@executablemd/runtime"; import { useWorkflowInputDelivery, useWorkflowLifecycle, @@ -46,12 +46,11 @@ export const RUN_STORAGE_ROOT_ENV = "XMD_WORKFLOW_RUNS"; export function* useDenoWorkflowHost( helper: HelperAssembly, usage?: PromptUsageHost, - compatibilityWarnings?: Set, ): Operation { const configured = yield* readEnv(RUN_STORAGE_ROOT_ENV); const root = configured === undefined || configured === "" ? DEFAULT_RUN_STORAGE_ROOT : configured; - const observer = createDenoExecutableObserver(); + return { useRunHost(): Operation { return useWorkflowRunHost({ root }); @@ -82,10 +81,6 @@ export function* useDenoWorkflowHost( root, attachment, ...(usage === undefined ? {} : { promptUsageHost: usage }), - // Diagnostic only: which version the selected executable reports, - // for a warning. It admits nothing and grants no native capability. - ...(observer === undefined ? {} : { executableObserver: observer }), - ...(compatibilityWarnings === undefined ? {} : { compatibilityWarnings }), }), }); }, diff --git a/packages/cli/src/deno.ts b/packages/cli/src/deno.ts index a0b63c1eb..8821f1a06 100644 --- a/packages/cli/src/deno.ts +++ b/packages/cli/src/deno.ts @@ -168,7 +168,7 @@ if (isReplSubmit(process.argv.slice(2))) { UPGRADE, () => readInputStream(process.stdin), importPluginModule, - (options) => useDenoWorkflowHost(HELPER, USAGE, options?.compatibilityWarnings), + () => useDenoWorkflowHost(HELPER, USAGE), { ...useMachineSessions(), usage: USAGE }, // What this host selects for a REPL command, and what it installs for // one. The selection is the capability an entry runs with — its diff --git a/packages/cli/src/diagnostic-agent.ts b/packages/cli/src/diagnostic-agent.ts index 43e59533b..44831c5fd 100644 --- a/packages/cli/src/diagnostic-agent.ts +++ b/packages/cli/src/diagnostic-agent.ts @@ -51,7 +51,6 @@ export function diagnosticAgent( ...dependencies, coordinator: undefined, routeStore: undefined, - executableObserver: undefined, advertiseNativeLaunch: [], advertiseClientNativeAttachment: [], adapterBuild(agent) { diff --git a/packages/cli/src/repl/application.ts b/packages/cli/src/repl/application.ts index 3e11f22d0..37239fdcd 100644 --- a/packages/cli/src/repl/application.ts +++ b/packages/cli/src/repl/application.ts @@ -464,21 +464,7 @@ export interface ReplSidekickSubmit { readonly admitted: boolean; } -/** One line a held conversation's own work wrote to its standard error. */ -export interface ReplSidekickDiagnostic { - readonly conversation: string; - /** Inert and privacy-projected; never source, a chat turn or a failure. */ - readonly text: string; -} - export interface ReplSidekickReading { - /** - * What this invocation's held conversations wrote to standard error. - * - * Transient and process-local: shown beside the replies and kept on screen - * for this invocation, and never part of the chat's history. - */ - readonly diagnostics?: readonly ReplSidekickDiagnostic[]; readonly feedback?: readonly SidekickFeedback[]; readonly usageTotal?: string; readonly inspectUsage?: boolean; @@ -4358,9 +4344,6 @@ function sidekickComposedRows( ); metadata(); } - for (const [index, line] of sidekickDiagnostics(reading).entries()) { - items.push(text(`sidekick:stderr:${index}`, ` stderr: ${line}`, styleOf("metadata"))); - } if (reading.savedRecovery !== undefined) { const saved = reading.savedRecovery; items.push( @@ -4374,13 +4357,6 @@ function sidekickComposedRows( return items; } -/** The stderr lines the chat being read wrote in this invocation. */ -function sidekickDiagnostics(reading: ReplSidekickReading): string[] { - return (reading.diagnostics ?? []) - .filter((one) => one.conversation === reading.reading) - .flatMap((one) => one.text.split("\n").filter((line) => line.length > 0)); -} - /** * One composed row's own lines, as whoever wrote them wrote them. * @@ -12749,14 +12725,6 @@ function workspaceChatComposed( } } } - for (const [index, line] of sidekickDiagnostics(reading).entries()) { - items.push({ - kind: "text", - key: `sidekick:stderr:${index}`, - text: `${MARKER_ROOM}stderr: ${line}`, - style: styleOf("metadata"), - }); - } if (reading.savedRecovery !== undefined) { const saved = reading.savedRecovery; items.push( diff --git a/packages/cli/src/repl/program.ts b/packages/cli/src/repl/program.ts index 8325304dd..f4bd628cc 100644 --- a/packages/cli/src/repl/program.ts +++ b/packages/cli/src/repl/program.ts @@ -3968,7 +3968,6 @@ function sidekickReadingOf( recovery: owner.recoveryPending, recoveryStatus: reading === undefined ? undefined : owner.recoveryStatus(reading), chat: sidekickChatRows(read.value, owner.previewing), - diagnostics: owner.diagnostics, // What the replies of this history actually did to this execution's // entries, as the coordinates their records hold. Detached from the chat // beside it: a row is what a conversation said, and these are what one of diff --git a/packages/cli/src/repl/sidekick/assembly.ts b/packages/cli/src/repl/sidekick/assembly.ts index de7939237..1313eb5ce 100644 --- a/packages/cli/src/repl/sidekick/assembly.ts +++ b/packages/cli/src/repl/sidekick/assembly.ts @@ -76,9 +76,6 @@ export function sidekickAssembly( const worker = yield* scripted.worker(conversation); yield* installSidekickProvider(scripted.agent, { sessionStore: scripted.store, - ...(dependencies.compatibilityWarnings === undefined - ? {} - : { compatibilityWarnings: dependencies.compatibilityWarnings }), ...(dependencies.agentCwd === undefined ? {} : { agentCwd: dependencies.agentCwd }), diff --git a/packages/cli/src/repl/sidekick/owner.ts b/packages/cli/src/repl/sidekick/owner.ts index 049c60e59..d7a6d89af 100644 --- a/packages/cli/src/repl/sidekick/owner.ts +++ b/packages/cli/src/repl/sidekick/owner.ts @@ -3,8 +3,6 @@ import { DESIGNATED } from "./controls.ts"; import { SCRIPTED_AGENT_PREFIX } from "./scripted.ts"; import type { ReplPluginExtension } from "../../repl-api.ts"; import { projectInputValue, useSecretInputs } from "@executablemd/core/host"; -import { Stdio } from "@effectionx/process"; -import { inertCommandText } from "../command-output.ts"; import { cwd } from "@executablemd/runtime"; import { inspectRecoveryOwnership } from "./recovery-owner.ts"; import { recoveryBlocked, uncertainRequests } from "./recovery-state.ts"; @@ -574,17 +572,6 @@ export interface SidekickOwner { * a screen showing it needs no keystroke to learn that more has arrived. */ readonly previewing: SidekickPreview | undefined; - /** - * What held conversations' own work wrote to standard error in this - * invocation, oldest first. - * - * Captured in the task that owns each conversation, so a provider's warning - * before a reopened conversation's turn lands here rather than on a terminal - * this program is drawing. Inert, privacy-projected display copies only: - * never generated source, a chat record or a failure, and gone with this - * owner. - */ - readonly diagnostics: readonly { readonly conversation: string; readonly text: string }[]; /** * The turn this owner is running, where it is running one. * @@ -855,8 +842,6 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation 0) { - diagnostics.push(Object.freeze({ conversation, text: inertCommandText(shown) })); - moved(); - } - }, - }, - { at: "min" }, - ); const opened = yield* useAgentConversation({ history: conversationStream(writer, conversation, records), id: conversation, @@ -3086,9 +3050,6 @@ export function useSidekickOwner(input: SidekickOwnerInput): Operation; } /** @@ -447,19 +438,13 @@ export function* useWorkflowAgentProfile(options: WorkflowAgentProfileOptions): ...(options.createRuntime === undefined ? {} : { createRuntime: options.createRuntime }), ...(options.agentProcessEnv === undefined ? {} : { agentProcessEnv: options.agentProcessEnv }), ...(options.promptUsageHost === undefined ? {} : { promptUsageHost: options.promptUsageHost }), - ...(options.executableObserver === undefined - ? {} - : { executableObserver: options.executableObserver }), - ...(options.compatibilityWarnings === undefined - ? {} - : { compatibilityWarnings: options.compatibilityWarnings }), + // ACP-only, stated rather than inherited. A workflow session belongs to a // run, not to this machine: it is named by a row in the run's own database, // arranged in the run's own sidecar, and continued by reattaching that row. // The ordinary-run capabilities are about a different account entirely — // machine-wide ownership and construction routes — and this profile - // supplies neither. An executable observer, when given, only reports the - // selected version for a diagnostic. Inheriting the package's + // supplies neither. Inheriting the package's // advertised sets by omission would make a workflow Claude prompt demand // ownership and a route that this profile has no way to give it. advertiseNativeLaunch: [], diff --git a/packages/cli/src/workflow.ts b/packages/cli/src/workflow.ts index 408020ebc..96307506d 100644 --- a/packages/cli/src/workflow.ts +++ b/packages/cli/src/workflow.ts @@ -150,10 +150,7 @@ export interface WorkflowHost { attach(database: WorkflowRunDatabase, operation: Operation): Operation; } -export type HostWorkflowInstaller = (options?: { - /** The sessions this invocation has already warned about. */ - readonly compatibilityWarnings?: Set; -}) => Operation; +export type HostWorkflowInstaller = () => Operation; /** The one sentence a host without workflow support says. */ export const UNSUPPORTED_WORKFLOW_HOST = diff --git a/packages/cli/tests/adversarial-session-continuity.test.ts b/packages/cli/tests/adversarial-session-continuity.test.ts index 075648558..743e3c3c7 100644 --- a/packages/cli/tests/adversarial-session-continuity.test.ts +++ b/packages/cli/tests/adversarial-session-continuity.test.ts @@ -64,9 +64,9 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) { strong?: boolean; guard?: boolean; receiptDirectory?: string; - /** A carried agent, observed through this version output, in its own invocation. */ + /** A carried agent, run through this host-selected executable, in its own invocation. */ agent?: "codex" | "claude"; - version?: string; + executable?: string; }) { return scoped(function* () { const warned: string[] = []; @@ -92,18 +92,15 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) { ...(options.agent === undefined ? {} : { - // Diagnostic only, exactly as the workflow host supplies it. - executableObserver: { - // deno-lint-ignore require-yield - *observe() { - return { - path: `/selected/${agentName}`, - digest: { algorithm: "sha256" as const, value: "a".repeat(64) }, - versionOutput: options.version ?? "", - }; - }, + // The host's own selection, through the seam its carried-adapter + // selector fills: today's executable reaches the adapter child. + // deno-lint-ignore require-yield + *agentProcessEnv() { + return { + [agentName === "codex" ? "CODEX_PATH" : "CLAUDE_CODE_EXECUTABLE"]: + options.executable ?? `/selected/${agentName}`, + }; }, - compatibilityWarnings: new Set(), }), ...(options.strong ? { @@ -226,15 +223,12 @@ describe( "E1 ordinary workflow Session continuity across a CLI release (#891)", { sanitizeOps: false, sanitizeResources: false }, () => { - const RELEASES = { - codex: ["codex-cli 0.167.1\n", "codex-cli 0.169.1\n", "Codex"], - claude: ["2.1.241 (Claude Code)\n", "2.1.250 (Claude Code)\n", "Claude"], - } as const; for (const agent of ["codex", "claude"] as const) { - const [before, after, product] = RELEASES[agent]; - it(`${agent}: an upgraded executable continues the configured conversation and its original-only context`, function* () { + const before = `/selected/${agent}-0.167.1`; + const after = `/selected/${agent}-0.169.1`; + it(`${agent}: a changed executable quietly continues the configured conversation and its original-only context`, function* () { const peer = yield* guardPeer(AGENT_SOURCE); - const first = yield* peer.run({ text: "marker", agent, version: before }); + const first = yield* peer.run({ text: "marker", agent, executable: before }); expect(first.result.ok).toBe(true); expect(first.warned).toEqual([]); const asserted = first.resolved?.identity; @@ -244,14 +238,13 @@ describe( existing: true, text: "recall", agent, - version: after, + executable: after, }); expect(continued.result.ok).toBe(true); - // Context only the original conversation held, through today's build. + // Context only the original conversation held, through today's executable. expect(JSON.stringify(continued.history)).toContain("answer:recall:marker"); expect(continued.resolved?.identity).toEqual(asserted); - // An ACP-only account keeps no executable history, so there is no - // difference to report; the work continued without a question. + // Quiet: a changed executable is not news, here or anywhere else. expect(continued.warned).toEqual([]); const methods = (yield* peer.methods()).map((entry) => entry.method); expect(methods.filter((method) => method === "session/new")).toHaveLength(1); @@ -262,17 +255,6 @@ describe( methods.lastIndexOf("session/prompt"), ); - // An unfamiliar version string is undetermined, said once, and works. - const unfamiliar = yield* peer.run({ - existing: true, - text: "recall", - agent, - version: "development build\n", - }); - expect(unfamiliar.result.ok).toBe(true); - expect(unfamiliar.warned).toEqual([ - `The ${product} version could not be determined. Continuing.`, - ]); // Another native conversation, or none asserted at all on an unchanged // build: refused before any setting or prompt, with nothing created. for (const refusal of ["different", "missing"] as const) { @@ -288,7 +270,7 @@ describe( existing: true, text: "recall", agent, - version: after, + executable: after, }); expect([refusal, refused.result.ok]).toEqual([refusal, false]); const now = yield* peer.methods(); @@ -301,7 +283,12 @@ describe( } } // A later explicit attempt reaches the same conversation. - const retried = yield* peer.run({ existing: true, text: "recall", agent, version: after }); + const retried = yield* peer.run({ + existing: true, + text: "recall", + agent, + executable: after, + }); expect(retried.result.ok).toBe(true); expect(retried.resolved?.identity).toEqual(asserted); }); diff --git a/packages/cli/tests/agent-session-coordinator.test.ts b/packages/cli/tests/agent-session-coordinator.test.ts index fd145eb8f..e5ef48ad6 100644 --- a/packages/cli/tests/agent-session-coordinator.test.ts +++ b/packages/cli/tests/agent-session-coordinator.test.ts @@ -39,11 +39,11 @@ import { createMemorySessionRouteStore, } from "@executablemd/acp"; import type { AgentSessionRouteStore, NativeAdapter, NativeBinding } from "@executablemd/acp"; -import type { ExecutableObserver, NativeLaunchRequest } from "@executablemd/runtime"; -import { createFakeObserver } from "../../acp/tests/helpers.ts"; +import type { NativeLaunchRequest } from "@executablemd/runtime"; +import { createFakeSelection } from "../../acp/tests/helpers.ts"; +import type { FakeSelectionHarness } from "../../acp/tests/helpers.ts"; import { sessionCoordinatorRoot, - useExecutableObserver, useMachineSessions, useSessionCoordinator, } from "../src/session-coordinator.ts"; @@ -74,7 +74,14 @@ interface RuntimeProbe { closes: number; } -function probeRuntime(probe: RuntimeProbe) { +/** + * A runtime that counts what reaches it. + * + * `confirms` lets it answer exactly one kind of work: an exact load of a named + * conversation, asserting that same identity — what a fresh client-native + * launch asks after its native child has exited. Everything else is refused. + */ +function probeRuntime(probe: RuntimeProbe, confirms = false) { return () => { probe.runtimes += 1; return { @@ -82,8 +89,16 @@ function probeRuntime(probe: RuntimeProbe) { probe.doctors += 1; return Promise.resolve({ ok: true, agents: [] } as never); }, - ensureSession() { + ensureSession(input: { sessionKey: string; resumeSessionId?: string }) { probe.ensures += 1; + if (confirms && input.resumeSessionId !== undefined) { + return Promise.resolve({ + sessionKey: input.sessionKey, + backend: "acpx", + runtimeSessionName: input.sessionKey, + agentSessionId: input.resumeSessionId, + }); + } return Promise.reject(new Error("this test's provider must not reach a runtime")); }, startTurn() { @@ -267,7 +282,7 @@ function* launchUnder( launched?: NativeLaunchRequest[]; agent?: string; /** The build this host would observe. Absent means it can observe none. */ - observer?: ExecutableObserver; + selection?: FakeSelectionHarness; /** Drive every phase, not only preparation. */ perform?: boolean; } = {}, @@ -284,7 +299,7 @@ function* launchUnder( record: (request) => options.launched?.push(request), }); const factory = createAcpxProvider({ - createRuntime: probeRuntime(probe), + createRuntime: probeRuntime(probe, options.perform === true), sessionStore: { load: () => Promise.resolve(undefined), save: () => Promise.resolve(), @@ -302,7 +317,7 @@ function* launchUnder( }), ...(coordinator ? { coordinator } : {}), ...(options.routeStore ? { routeStore: options.routeStore } : {}), - ...(options.observer ? { executableObserver: options.observer } : {}), + ...(options.selection ? { agentProcessEnv: options.selection.agentProcessEnv() } : {}), }); yield* factory( { defaultAgent: agent, permissionMode: "deny-all" }, @@ -385,7 +400,7 @@ describe("Tier HC — host session ownership", () => { : undefined, records, probe, - { adapter: CLIENT_ALLOCATED, observer: createFakeObserver().observer }, + { adapter: CLIENT_ALLOCATED, selection: createFakeSelection() }, ); const failure = records.find((record) => record.failure)?.failure; @@ -444,9 +459,9 @@ describe("Tier HC — host session ownership", () => { // Only this host assembles both halves. Node and Bun build neither, which // is what makes the same call refuse there. const routeStore = onDeno() ? createDenoSessionRouteStore(root) : undefined; - // A controlled observation, because the subject is the host assembly rather + // A controlled selection, because the subject is the host assembly rather // than which Claude happens to be installed on the machine running this. - const observer = createFakeObserver(); + const selection = createFakeSelection(); yield* launchUnder( onDeno() ? createDenoAgentSessionCoordinator(root) : undefined, @@ -456,7 +471,7 @@ describe("Tier HC — host session ownership", () => { defaults: true, perform: true, launched, - observer: observer.observer, + selection, ...(routeStore ? { routeStore } : {}), }, ); @@ -476,15 +491,18 @@ describe("Tier HC — host session ownership", () => { } // The whole way to the launcher, and nothing was created through ACP on the - // way: a session Claude names is materialized by the native process. + // way: a session Claude names is materialized by the native process. Only + // once that process exited was its allocated identity loaded over ACP, and + // confirmed, before the launch reported success. expect(records.find((record) => record.failure)).toBe(undefined); - expect(probe.runtimes).toBe(0); - expect(probe.ensures).toBe(0); + expect(probe.runtimes).toBe(1); + expect(probe.ensures).toBe(1); + expect(probe.closes).toBe(1); expect(launched.length).toBe(1); const command = launched[0]!.command; - // The exact file that was observed, not the launcher name: the name is what - // the durable record carries, and this is what the run spawns. - expect(command[0]).toBe(observer.observation.path); + // The exact file the host selected, not the launcher name: the name is + // what the durable record carries, and this is what the run spawns. + expect(command[0]).toBe(selection.path); expect(command[1]).toBe("--session-id"); expect(command[3]).toBe("--system-prompt-file"); // The prepared text crossed as a path, so it is in neither surface another @@ -531,30 +549,6 @@ describe("Tier HC — host session ownership", () => { } }); - it("HC11: an agent that names its own sessions needs an observer too", function* () { - // The third half of fail-closed. A host that can say who owns the session - // and how it was constructed still cannot act on one whose build it has no - // way to recognize. - const records: LaunchRecord[] = []; - const probe: RuntimeProbe = { ensures: 0, closes: 0, doctors: 0, runtimes: 0 }; - yield* launchUnder( - onDeno() - ? createDenoAgentSessionCoordinator(join(tmpdir(), `xmd-hc11-${randomUUID()}`)) - : undefined, - records, - probe, - { adapter: CLIENT_ALLOCATED, routeStore: createMemorySessionRouteStore() }, - ); - - const failure = records.find((record) => record.failure)?.failure; - expect(failure?.class).toBe("unsupported-capability"); - if (onDeno()) { - expect(failure?.message).toContain("executable build observation"); - } - expect(probe.runtimes).toBe(0); - expect(probe.ensures).toBe(0); - }); - it("HC12: the two advertised sets are separate, and this host states both", function* () { // What a host actually assembles. Native launch and ACP attachment are // different proofs, so they are different lists — and the ordinary profile @@ -569,8 +563,6 @@ describe("Tier HC — host session ownership", () => { // Built from the same trusted root as the coordinator beside it. expect(assembly.coordinator === undefined).toBe(!onDeno()); expect(assembly.routeStore === undefined).toBe(!onDeno()); - expect(assembly.executableObserver === undefined).toBe(!onDeno()); - expect(useExecutableObserver() === undefined).toBe(!onDeno()); }); }); diff --git a/packages/cli/tests/fixtures/host-agent.ts b/packages/cli/tests/fixtures/host-agent.ts index e1cf13b53..ede2c4617 100644 --- a/packages/cli/tests/fixtures/host-agent.ts +++ b/packages/cli/tests/fixtures/host-agent.ts @@ -9,7 +9,7 @@ import { DatabaseSync } from "node:sqlite"; import { collect, retainedSource } from "@executablemd/core"; import { agentIdentityComponents } from "@executablemd/agent/host"; import { executeInstalled } from "@executablemd/core/host"; -import { API, createDenoExecutableObserver, useHostFiles } from "@executablemd/runtime"; +import { API, useHostFiles } from "@executablemd/runtime"; import { createEmbeddedAdapters } from "@executablemd/acp/embedded-adapters"; import { withWorkflowWorkspace, @@ -58,8 +58,6 @@ main(function* () { useWorkflowAgentProfile({ root, attachment, - // As the Deno workflow host supplies it: diagnostic only. - ...(replay ? {} : { executableObserver: createDenoExecutableObserver() }), adapters: replay ? { ...adapters, diff --git a/packages/cli/tests/repl-agent-journey.test.ts b/packages/cli/tests/repl-agent-journey.test.ts index 065639cfb..1ffd80db9 100644 --- a/packages/cli/tests/repl-agent-journey.test.ts +++ b/packages/cli/tests/repl-agent-journey.test.ts @@ -29,7 +29,6 @@ import { assembleReplProfile } from "../src/repl-profile.ts"; import type { ReplExecutionProfile } from "../src/repl-profile.ts"; import { NO_PLUGINS } from "../src/plugin-host.ts"; import { resolveAgentStack } from "../src/agent-stack.ts"; -import type { AcpxProviderDependencies } from "@executablemd/acp"; import { createFakeAcp, makeRegistry, makeStore, tripwireAcp } from "./support/fake-acp.ts"; import type { FakeAcp } from "./support/fake-acp.ts"; import { ADAPTERS, AGENT } from "./support/plan-harness.ts"; @@ -465,68 +464,6 @@ describe("C1 — the command line this REPL runs under", () => { }); }); -describe("E9 — a compatibility warning is the entry's own Command stderr", () => { - beforeAll(() => useTempFileCompiler()); - - it("E9: the first live use of a session warns once in its entry, and a later entry does not repeat it", function* () { - const fake = createFakeAcp(); - fake.script({ reply: ANSWERED }); - fake.script({ reply: ANSWERED }); - const warnings = new Set(); - - yield* scoped(function* (): Operation { - const { page, hostRoot } = yield* beginJourney({ - fake, - size: WIDE, - acp: { - // An adapter whose executable this host selects but cannot ask its - // version: the warning the issue requires, from the real provider. - nativeAdapters: { - [AGENT]: { - launcher: AGENT, - identity: "provider-returned", - resume: () => [], - binding: { - command: AGENT, - version: () => undefined, - environment: () => ({}), - }, - }, - }, - advertiseNativeLaunch: [], - advertiseClientNativeAttachment: [], - compatibilityWarnings: warnings, - }, - }); - yield* submitted(page, 'first', 1); - yield* awaitedFact("entry 1 never settled", function* () { - return (yield* journal(hostRoot)).some((event) => event.type === "close"); - }); - yield* page.type("\x073"); - const shown = yield* page.until( - "the warning inside the entry's own reading", - (frame) => - frame.shows("Command stderr") && - frame.shows(`The ${AGENT} version could not be determined. Continuing.`), - ); - expect(shown.shows("Command stdout")).toBe(false); - expect(warnings.size).toBe(1); - expect(fake.prompts).toHaveLength(1); - yield* page.type("\x073"); - - yield* submitted(page, 'second', 2); - yield* awaitedFact("entry 2 never settled", function* () { - return (yield* journal(hostRoot)).filter((event) => event.type === "close").length >= 2; - }); - // The same session in the same invocation: the warning is not repeated, - // and the turn still ran. - expect(warnings.size).toBe(1); - expect(fake.prompts).toHaveLength(2); - yield* leave(page); - }); - }); -}); - function greetingSource(which: "First" | "Second"): string { const prop = `from${which}`; return [ @@ -1575,7 +1512,6 @@ function* useJourneyHost(options: { readonly includes?: readonly string[]; readonly planWriterRoot?: string; readonly permissionMode?: "approve-reads" | "deny-all"; - readonly acp?: Partial; }): Operation { const dataRoot = options.dataRoot ?? (yield* untilResolved(mkdtemp(join(tmpdir(), "xmd-repl-journey-")))); @@ -1601,7 +1537,6 @@ function* useJourneyHost(options: { options.held === undefined ? options.fake.create : options.held.create(options.fake), sessionStore: makeStore(), agentRegistry: makeRegistry({ [AGENT]: `${AGENT}-cmd` }), - ...options.acp, }, planWriterRoot: options.planWriterRoot ?? (yield* untilResolved(mkdtemp(join(tmpdir(), "xmd-repl-plan-")))), @@ -1628,7 +1563,6 @@ function* beginJourney(options: { readonly includes?: readonly string[]; readonly planWriterRoot?: string; readonly permissionMode?: "approve-reads" | "deny-all"; - readonly acp?: Partial; readonly workspace?: boolean; }): Operation<{ @@ -1646,7 +1580,6 @@ function* beginJourney(options: { ...(options.includes === undefined ? {} : { includes: options.includes }), ...(options.planWriterRoot === undefined ? {} : { planWriterRoot: options.planWriterRoot }), ...(options.permissionMode === undefined ? {} : { permissionMode: options.permissionMode }), - ...(options.acp === undefined ? {} : { acp: options.acp }), }); const page = yield* useReplPage({ host, diff --git a/packages/cli/tests/repl-sidekick-journey.test.ts b/packages/cli/tests/repl-sidekick-journey.test.ts index 3a5cd5b4f..6d1495439 100644 --- a/packages/cli/tests/repl-sidekick-journey.test.ts +++ b/packages/cli/tests/repl-sidekick-journey.test.ts @@ -5657,64 +5657,3 @@ describe("1342 — written Markdown in the chat and in entry Output", () => { expect(reopened.model.entries.map((entry) => entry.terminal?.output)).toEqual([ENTRY_MARKDOWN]); }); }); - -describe("E9 — a held conversation's compatibility warning beside its reply", () => { - it("E9: the warning is transient stderr in the Sidekick pane, once per invocation, and never history", function* () { - const warnings = new Set(); - const host = yield* useMountedHost({ - usageAcp: { - nativeAdapters: { - [MOUNTED_AGENT]: { - launcher: MOUNTED_AGENT, - identity: "provider-returned", - resume: () => [], - binding: { command: MOUNTED_AGENT, version: () => undefined, environment: () => ({}) }, - }, - }, - advertiseNativeLaunch: [], - advertiseClientNativeAttachment: [], - compatibilityWarnings: warnings, - }, - }); - const line = `The ${MOUNTED_AGENT} version could not be determined. Continuing.`; - yield* scoped(function* (): Operation { - const page = yield* useReplPage({ host, size: { columns: 160, rows: 60 } }); - const repl = page.repl; - repl.fake.script({ reply: "First answer.\n" }); - yield* sendMessage(page, "first question"); - yield* page.until("the reply", (one) => saidBySidekick(one, "First answer.")); - // Beside the reply, and still there once the turn has settled. - const settled = yield* page.until("the held warning beside the reply", (one) => - sidekickShows(one, `stderr: ${line}`), - ); - expect(sidekickShows(settled, "First answer.")).toBe(true); - - repl.fake.script({ reply: "Second answer.\n" }); - yield* sendMessage(page, "second question"); - yield* page.until("the second reply", (one) => saidBySidekick(one, "Second answer.")); - const later = page.screen(); - expect(later.occurrences(`stderr: ${line}`)).toBe(1); - expect(warnings.size).toBe(1); - expect(repl.fake.prompts).toHaveLength(2); - }); - // Display only: nothing durable — no chat record, generated source or - // failure — holds the warning. - const written: string[] = []; - function* readAll(directory: string): Operation { - if (!(yield* exists(directory))) { - return; - } - for (const name of yield* until(readdir(directory))) { - const path = join(directory, name); - if ((yield* until(stat(path))).isDirectory()) { - yield* readAll(path); - } else { - written.push(yield* readTextFile(path)); - } - } - } - yield* readAll(host.root); - expect(written.length).toBeGreaterThan(0); - expect(written.join("\n")).not.toContain("could not be determined"); - }); -}); diff --git a/packages/cli/tests/session-compatibility.test.ts b/packages/cli/tests/session-compatibility.test.ts index 0a62dbea5..5df4a731d 100644 --- a/packages/cli/tests/session-compatibility.test.ts +++ b/packages/cli/tests/session-compatibility.test.ts @@ -1,18 +1,19 @@ /** - * Session compatibility across agent CLI releases (#891). + * Session continuation across agent CLI releases (#891). * * The production provider, installed the way a host installs it, over a - * controlled ACP runtime and executable observer. What these rows read is what - * an invocation would actually show on standard error and what it actually - * asked the agent to do: a version change warns once per logical session in one - * invocation and the retained conversation continues under the provider's live - * confirmation; nothing about a version admits or refuses. + * controlled ACP runtime and the host's own executable selection. What these + * rows read is what an invocation actually asked the agent to do, and what it + * wrote to standard error: the retained conversation continues on today's + * selected executable under the provider's live confirmation of its native + * identity, quietly. Nothing about an executable's version admits, refuses or + * reports. */ import { describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; import { Stdio } from "@effectionx/process"; -import { all, scoped, until } from "effection"; +import { scoped, until } from "effection"; import type { Operation } from "effection"; import { Agent } from "@executablemd/agent/api"; import type { AcpxProvider, AcpxProviderDependencies } from "@executablemd/acp"; @@ -21,8 +22,8 @@ import { useAcpxProvider } from "../../acp/src/provider.ts"; import { createMemorySessionRouteStore } from "../../acp/src/session-route.ts"; import type { AgentSessionRouteStore } from "../../acp/src/session-route.ts"; import { - createFakeObserver, createFakeRuntime, + createFakeSelection, makeCoordinator, makeRegistry, makeStore, @@ -30,29 +31,17 @@ import { } from "../../acp/tests/helpers.ts"; import type { CoordinatorHarness, - FakeObserverHarness, FakeRuntimeHarness, + FakeSelectionHarness, } from "../../acp/tests/helpers.ts"; import { ADAPTERS } from "./support/plan-harness.ts"; const CWD = "/work"; -/** What one product reports at two releases, and the selector it is chosen by. */ +/** The selector variable and registered command for each supported product. */ const PRODUCTS = { - codex: { - name: "Codex", - before: "codex-cli 0.167.1\n", - after: "codex-cli 0.169.1\n", - variable: "CODEX_PATH", - command: "codex-cmd", - }, - claude: { - name: "Claude", - before: "2.1.241 (Claude Code)\n", - after: "2.1.250 (Claude Code)\n", - variable: "CLAUDE_CODE_EXECUTABLE", - command: "claude-cmd", - }, + codex: { variable: "CODEX_PATH", command: "codex-cmd" }, + claude: { variable: "CLAUDE_CODE_EXECUTABLE", command: "claude-cmd" }, } as const; type Product = keyof typeof PRODUCTS; @@ -62,7 +51,7 @@ interface Machine { readonly store: ReturnType; readonly routes: AgentSessionRouteStore; readonly ownership: CoordinatorHarness; - readonly observer: FakeObserverHarness; + readonly selection: FakeSelectionHarness; } function machine(product: Product): Machine { @@ -70,23 +59,17 @@ function machine(product: Product): Machine { store: makeStore(), routes: createMemorySessionRouteStore(), ownership: makeCoordinator(), - observer: createFakeObserver({ - path: `/selected/${product}`, - versionOutput: PRODUCTS[product].before, - }), + selection: createFakeSelection(`/selected/${product}-0.167.1`), }; } /** Every line this scope's operations wrote to standard error. */ -function* stderr(fail?: Error): Operation { +function* stderr(): Operation { const lines: string[] = []; const decoder = new TextDecoder(); yield* Stdio.around({ // deno-lint-ignore require-yield *stderr([bytes]) { - if (fail !== undefined) { - throw fail; - } lines.push( ...decoder .decode(bytes) @@ -94,27 +77,22 @@ function* stderr(fail?: Error): Operation { .filter((line) => line.length > 0), ); }, - // deno-lint-ignore require-yield - *stdout() { - throw new Error("a compatibility diagnostic reached standard output"); - }, }); return lines; } +let provider: AcpxProvider | undefined; + /** * Install one provider for `product` over this host's state, as the CLI does: - * the built-in adapter, the host's own selection, and the invocation's set. + * the built-in adapter and the host's own selection. */ -let provider: AcpxProvider | undefined; - function* install( product: Product, host: Machine, harness: FakeRuntimeHarness, extra: Partial = {}, ): Operation { - const { variable, command } = PRODUCTS[product]; // The agent a Prompt that names none means, as the installed chain answers it. yield* Agent.around( { @@ -130,16 +108,12 @@ function* install( { createRuntime: harness.create, sessionStore: host.store, - agentRegistry: makeRegistry({ [product]: command }), + agentRegistry: makeRegistry({ [product]: PRODUCTS[product].command }), coordinator: host.ownership.coordinator, routeStore: host.routes, - executableObserver: host.observer.observer, advertiseNativeLaunch: [product], advertiseClientNativeAttachment: product === "claude" ? ["claude"] : [], - // deno-lint-ignore require-yield - *agentProcessEnv() { - return { [variable]: `/selected/${product}` }; - }, + agentProcessEnv: host.selection.agentProcessEnv(), ...extra, }, ); @@ -160,58 +134,45 @@ function* prompt(text: string, session = "review"): Operation { }); } -/** Establish a session in one invocation, under the release recorded as its history. */ +/** Establish a session in one invocation. */ function* establish(product: Product, host: Machine, session = "review"): Operation { yield* scoped(function* () { yield* useFlatWorld(CWD); const lines = yield* stderr(); - yield* install(product, host, createFakeRuntime(), { - compatibilityWarnings: new Set(), - }); + yield* install(product, host, createFakeRuntime()); yield* prompt("seed", session); expect(lines).toEqual([]); }); } -function changed(product: Product): string { - const { name } = PRODUCTS[product]; - const [from, to] = - product === "codex" ? ["0.167.1", "0.169.1"] : (["2.1.241", "2.1.250"] as const); - return ( - `${name} has changed from ${from} to ${to} since this session was established. ` + - `Continuing the existing conversation.` - ); -} - -describe("SC — a CLI release change warns and continues", () => { +describe("SC — a changed executable continues the same conversation, quietly", () => { for (const product of ["codex", "claude"] as const) { - it(`SC1 (${product}): an upgraded executable continues the retained conversation and warns once`, function* () { + it(`SC1 (${product}): today's selected executable continues the retained conversation`, function* () { const host = machine(product); yield* establish(product, host); const established = yield* until(host.store.load([...host.store.records.keys()][0]!)); expect(established?.agentSessionId).toBeDefined(); - const route = yield* host.routes.read({ + const tuple = { provider: "acpx", agent: PRODUCTS[product].command, sessionKey: established!.acpxRecordId, - }); - expect(route?.schema).toBe("session-route.v3"); + }; + // A fresh route records how the session was constructed and nothing about + // the executable that constructed it. + const route = yield* host.routes.read(tuple); + expect(route).toEqual({ schema: "session-route.v1", route: "acp-first", ...tuple }); - host.observer.observation.versionOutput = PRODUCTS[product].after; - host.observer.observation.digest = "b".repeat(64); + host.selection.path = `/selected/${product}-0.169.1`; const harness = createFakeRuntime(); yield* scoped(function* () { yield* useFlatWorld(CWD); const lines = yield* stderr(); - yield* install(product, host, harness, { - compatibilityWarnings: new Set(), - }); + yield* install(product, host, harness); yield* prompt("first after the upgrade"); yield* prompt("second after the upgrade"); - // One warning, before the live work it concerns, and no repetition. - expect(lines).toEqual([changed(product)]); + expect(lines).toEqual([]); }); // Each operation reopened the exact retained conversation and required // the provider's live confirmation of its native identity first. @@ -227,215 +188,77 @@ describe("SC — a CLI release change warns and continues", () => { ]); // Through the executable the current environment selected. expect(harness.createdOptions[0]?.agentProcessEnv).toEqual({ - [PRODUCTS[product].variable]: `/selected/${product}`, + [PRODUCTS[product].variable]: `/selected/${product}-0.169.1`, }); - // History is not rewritten to claim today's executable made it. - expect( - yield* host.routes.read({ - provider: "acpx", - agent: PRODUCTS[product].command, - sessionKey: established!.acpxRecordId, - }), - ).toEqual(route); + // Nothing was written to say today's executable made this session. + expect(yield* host.routes.read(tuple)).toEqual(route); }); } - - it("SC2: one invocation set spans installations; a second session and a new invocation each warn", function* () { - const host = machine("codex"); - yield* establish("codex", host, "review"); - yield* establish("codex", host, "build"); - host.observer.observation.versionOutput = PRODUCTS.codex.after; - - const invocation = new Set(); - const runs: string[][] = []; - for (const installation of ["root", "nested"]) { - yield* scoped(function* () { - yield* useFlatWorld(CWD); - const lines = yield* stderr(); - yield* install("codex", host, createFakeRuntime(), { - compatibilityWarnings: invocation, - }); - yield* prompt(`${installation} review`, "review"); - if (installation === "nested") { - yield* prompt("nested build", "build"); - } - runs.push(lines); - }); - } - // The nested installation shares the invocation's set: the reviewed session - // is not repeated, and the second session gets its own warning. - expect(runs).toEqual([[changed("codex")], [changed("codex")]]); - expect(invocation.size).toBe(2); - - // A new invocation starts with nothing and may warn again. - yield* scoped(function* () { - yield* useFlatWorld(CWD); - const lines = yield* stderr(); - yield* install("codex", host, createFakeRuntime(), { - compatibilityWarnings: new Set(), - }); - yield* prompt("next invocation", "review"); - expect(lines).toEqual([changed("codex")]); - }); - }); - - it("SC3: distinct placements of one session name warn separately", function* () { - const host = machine("codex"); - for (const cwd of ["/work/a", "/work/b"]) { - yield* scoped(function* () { - yield* useFlatWorld(cwd); - yield* install("codex", host, createFakeRuntime(), { - compatibilityWarnings: new Set(), - }); - yield* prompt("seed", "review"); - }); - } - host.observer.observation.versionOutput = PRODUCTS.codex.after; - const invocation = new Set(); - const shown: string[] = []; - for (const cwd of ["/work/a", "/work/b"]) { - yield* scoped(function* () { - yield* useFlatWorld(cwd); - const lines = yield* stderr(); - yield* install("codex", host, createFakeRuntime(), { - compatibilityWarnings: invocation, - }); - yield* prompt("continue", "review"); - shown.push(...lines); - }); - } - expect(shown).toEqual([changed("codex"), changed("codex")]); - }); - - it("SC4: an embedding host that omits the set gets one per installation", function* () { - const host = machine("codex"); - yield* establish("codex", host); - host.observer.observation.versionOutput = PRODUCTS.codex.after; - const shown: string[] = []; - for (const _ of [1, 2]) { - yield* scoped(function* () { - yield* useFlatWorld(CWD); - const lines = yield* stderr(); - yield* install("codex", host, createFakeRuntime()); - yield* prompt("continue"); - yield* prompt("again"); - shown.push(...lines); - }); - } - expect(shown).toEqual([changed("codex"), changed("codex")]); - }); - - it("SC5: concurrent first uses of one session deliver one warning", function* () { - const host = machine("codex"); - yield* establish("codex", host, "review"); - yield* establish("codex", host, "build"); - host.observer.observation.versionOutput = PRODUCTS.codex.after; - const invocation = new Set(); - const shown: string[] = []; - yield* scoped(function* () { - yield* useFlatWorld(CWD); - const lines = yield* stderr(); - yield* install("codex", host, createFakeRuntime(), { - compatibilityWarnings: invocation, - }); - yield* all([prompt("one", "review"), prompt("two", "review"), prompt("three", "build")]); - shown.push(...lines); - }); - expect(shown).toEqual([changed("codex"), changed("codex")]); - expect(invocation.size).toBe(2); - }); - - it("SC6: a diagnostic that cannot be written is a host I/O failure, never model work", function* () { - const host = machine("codex"); - yield* establish("codex", host); - host.observer.observation.versionOutput = PRODUCTS.codex.after; - const harness = createFakeRuntime(); - let raised: Error | undefined; - yield* scoped(function* () { - yield* useFlatWorld(CWD); - yield* stderr(new Error("standard error is closed")); - yield* install("codex", host, harness, { - compatibilityWarnings: new Set(), - }); - try { - yield* prompt("continue"); - } catch (error) { - raised = error as Error; - } - }); - expect(raised?.message).toBe("standard error is closed"); - // Nothing was reopened, replaced or retried on its account. - expect(harness.ensureCalls).toEqual([]); - expect(harness.turns).toEqual([]); - }); }); -describe("SV — what a version observation can and cannot say", () => { - it("SV1: unrecognized or private version output says only that it is undetermined", function* () { +describe("SV — what selection can and cannot decide", () => { + it("SV1: a replaced file at the same selected path continues without a word", function* () { const host = machine("codex"); yield* establish("codex", host); - host.observer.observation.versionOutput = "codex-cli 0.169.1 built at /home/private/secret\n"; + // The same path, other bytes: nothing about the file is read. const harness = createFakeRuntime(); yield* scoped(function* () { yield* useFlatWorld(CWD); const lines = yield* stderr(); - yield* install("codex", host, harness, { - compatibilityWarnings: new Set(), - }); + yield* install("codex", host, harness); expect(yield* prompt("continue")).toBe("hello world"); - expect(lines).toEqual(["The Codex version could not be determined. Continuing."]); - expect(lines.join("\n")).not.toContain("/home/private"); - expect(lines.join("\n")).not.toContain("/selected"); + expect(lines).toEqual([]); }); expect(harness.turns).toHaveLength(1); + expect(harness.ensureCalls[0]?.expectedAgentSessionId).toBeDefined(); }); - it("SV2: a fresh session under a release no evidence names works, with no warning", function* () { + it("SV2: a fresh session under a release no evidence names works, quietly", function* () { const host = machine("claude"); - host.observer.observation.versionOutput = "9.0.0 (Claude Code)\n"; + host.selection.path = "/selected/claude-9.0.0"; const harness = createFakeRuntime(); yield* scoped(function* () { yield* useFlatWorld(CWD); const lines = yield* stderr(); - yield* install("claude", host, harness, { - compatibilityWarnings: new Set(), - }); + yield* install("claude", host, harness); expect(yield* prompt("first")).toBe("hello world"); expect(lines).toEqual([]); }); + expect(harness.createdOptions[0]?.agentProcessEnv).toEqual({ + CLAUDE_CODE_EXECUTABLE: "/selected/claude-9.0.0", + }); }); - it("SV3: history without a recorded version continues without a difference warning", function* () { + it("SV3: an earlier release's bound route continues, unchanged and unrewritten", function* () { const host = machine("codex"); yield* establish("codex", host); - // Rewritten here only to stand for a session established before XMD kept - // executable history: the released unbound form of the same route. const key = [...host.store.records.keys()][0]!; - const tuple = { - provider: "acpx", - agent: PRODUCTS.codex.command, - sessionKey: key, - }; - const legacy = createMemorySessionRouteStore(); - yield* legacy.publish({ - schema: "session-route.v1", + const tuple = { provider: "acpx", agent: PRODUCTS.codex.command, sessionKey: key }; + // The route an earlier release published, carrying the executable history + // it recorded then. It is original evidence, read and left as it was. + const earlier = createMemorySessionRouteStore(); + yield* earlier.publish({ + schema: "session-route.v3", route: "acp-first", ...tuple, + executableBinding: { + schema: "executable-build.v1", + reportedVersion: "codex-cli 0.153.2", + executableDigest: { algorithm: "sha256", value: "a".repeat(64) }, + }, }); - const before = yield* legacy.read(tuple); - host.observer.observation.versionOutput = PRODUCTS.codex.after; + const before = yield* earlier.read(tuple); + host.selection.path = "/selected/codex-0.169.1"; const harness = createFakeRuntime(); yield* scoped(function* () { yield* useFlatWorld(CWD); const lines = yield* stderr(); - yield* install("codex", { ...host, routes: legacy }, harness, { - compatibilityWarnings: new Set(), - }); + yield* install("codex", { ...host, routes: earlier }, harness); expect(yield* prompt("continue")).toBe("hello world"); expect(lines).toEqual([]); }); expect(harness.ensureCalls[0]?.expectedAgentSessionId).toBeDefined(); - expect(yield* legacy.read(tuple)).toEqual(before); + expect(yield* earlier.read(tuple)).toEqual(before); }); it("SV4: a custom command named codex keeps its own command and selects nothing", function* () { @@ -448,38 +271,37 @@ describe("SV — what a version observation can and cannot say", () => { yield* install("codex", host, harness, { agentRegistry: makeRegistry({ codex: "my-wrapper --acp" }), ...(agentProcessEnv === undefined ? {} : { agentProcessEnv }), - compatibilityWarnings: new Set(), }); expect(yield* prompt("through the wrapper")).toBe("hello world"); - // The wrapper's backend is not guessed at: its version is undetermined. - expect(lines).toEqual(["The Codex version could not be determined. Continuing."]); + // The wrapper's backend is not guessed at, and nothing is said about it. + expect(lines).toEqual([]); }); - expect(host.observer.observed).toEqual([]); const options = harness.createdOptions.at(-1); expect(options?.agentRegistry.resolve("codex")).toBe("my-wrapper --acp"); expect(options?.agentProcessEnv ?? {}).toEqual({}); expect(harness.turns).toHaveLength(1); }); - it("SV5: a selected executable that cannot run is an availability failure", function* () { + it("SV5: a selection that cannot run is an availability failure, in the selector's words", function* () { const host = machine("codex"); - host.observer.failure = "not-found"; + host.selection.failure = new Error( + "Host Codex is unavailable. Install codex on the host PATH or correct CODEX_PATH to " + + "select a launchable host executable.", + ); const harness = createFakeRuntime(); let raised: Error | undefined; yield* scoped(function* () { yield* useFlatWorld(CWD); - const lines = yield* stderr(); - yield* install("codex", host, harness, { - compatibilityWarnings: new Set(), - }); + yield* install("codex", host, harness); try { yield* prompt("first"); } catch (error) { raised = error as Error; } - expect(lines).toEqual([]); }); - expect(raised?.message).toContain("is unavailable"); + expect(raised?.message).toContain("Host Codex is unavailable"); + expect(raised?.message).toContain("CODEX_PATH"); expect(harness.ensureCalls).toEqual([]); + expect(harness.turns).toEqual([]); }); }); diff --git a/packages/cli/tests/support/mounted-repl.ts b/packages/cli/tests/support/mounted-repl.ts index 214148033..2089c793c 100644 --- a/packages/cli/tests/support/mounted-repl.ts +++ b/packages/cli/tests/support/mounted-repl.ts @@ -812,8 +812,6 @@ export function* useMountedHost( | "agentRegistry" | "advertiseNativeLaunch" | "advertiseClientNativeAttachment" - | "nativeAdapters" - | "compatibilityWarnings" >; readonly agentCwd?: AcpxProviderDependencies["agentCwd"]; } = {}, diff --git a/packages/cli/tests/workflow-agent-sessions.test.ts b/packages/cli/tests/workflow-agent-sessions.test.ts index 1f225e8b0..5e263175c 100644 --- a/packages/cli/tests/workflow-agent-sessions.test.ts +++ b/packages/cli/tests/workflow-agent-sessions.test.ts @@ -413,15 +413,10 @@ function* hostClaudeWorkflow( env: { PATH: bin, CLAUDE_CODE_EXECUTABLE: selected }, }); }); - // An unfamiliar version is reported once, before the live work it concerns, - // and the work continues; completed replay in the same invocation adds - // nothing. An unavailable executable is an availability failure instead. - expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ - exitCode: 0, - stderr: ["missing", "invalid", "unlaunchable"].includes(mode) - ? "" - : "The Claude version could not be determined. Continuing.\n", - }); + // Quiet: an unfamiliar version is no news, and completed replay in the same + // invocation adds nothing. An unavailable executable is reported as an + // availability failure in the report instead. + expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ exitCode: 0, stderr: "" }); const report = JSON.parse(yield* readTextFile(join(root, "report.json"))); expect(yield* exists(staleLog)).toBe(false); expect(yield* exists(pathLog)).toBe(false); @@ -588,14 +583,7 @@ function* hostCodexWorkflow(mode: HostCodexMode): Operation { env: mode === "path" ? { PATH: bin } : { PATH: bin, CODEX_PATH: override ?? "" }, }); }); - expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ - exitCode: 0, - stderr: ["missing", "invalid", "unlaunchable"].includes(mode) - ? "" - : mode === "versioned" - ? "" - : "The Codex version could not be determined. Continuing.\n", - }); + expect({ exitCode: child.exitCode, stderr: child.stderr }).toEqual({ exitCode: 0, stderr: "" }); const report = JSON.parse(yield* readTextFile(join(root, "report.json"))); expect(report.environmentPreserved).toBe(true); const selectedRan = ["explicit", "relative", "bare"].includes(mode); @@ -664,7 +652,7 @@ describe("H host Codex through the production workflow", () => { hostCodexWorkflow("effort")); it("H4: a host without the model's effort selector refuses with no turn", () => hostCodexWorkflow("no-selector")); - it("H5: a release absent from recorded evidence works and is observed without a warning", () => + it("H5: a release absent from recorded evidence works, quietly", () => hostCodexWorkflow("versioned")); }); diff --git a/packages/runtime/apis.ts b/packages/runtime/apis.ts index 33ee50784..693a1995f 100644 --- a/packages/runtime/apis.ts +++ b/packages/runtime/apis.ts @@ -905,17 +905,3 @@ export const compile: typeof API.Env.operations.compile = API.Env.operations.com export function useQuietProcessOutput(): Operation { return Stdio.around({ *stdout() {} }, { at: "min" }); } - -/** - * Write one diagnostic line to the contextual standard error. - * - * Through the same `Stdio` chain a subprocess's stderr travels, so whatever the - * enclosing scope installed — a REPL entry's Command stderr, a held - * conversation's transient reading, or the process stream itself — receives it - * in order with the rest of that scope's diagnostics. Standard output is never - * touched, which keeps a machine-readable result intact. - */ -export function writeDiagnostic(text: string): Operation { - const line = text.endsWith("\n") ? text : `${text}\n`; - return Stdio.operations.stderr(new TextEncoder().encode(line)); -} diff --git a/packages/runtime/executable-observer.ts b/packages/runtime/executable-observer.ts index 5eeaf62f8..4992c8936 100644 --- a/packages/runtime/executable-observer.ts +++ b/packages/runtime/executable-observer.ts @@ -3,11 +3,11 @@ * (specs/native-agent-session-launch-spec.md §Executable binding). * * What is observed is a canonical path, the SHA-256 of that file's bytes, and - * whatever the file says when asked its version. Only the last two ever become - * durable, as diagnostic history beside a session XMD constructs: a path stops - * being true when a build moves, and names host layout besides. A host asks - * this about the file it already selected; the observation reports, and never - * decides whether a conversation continues. + * whatever the file says when asked its version. Opt-in integration proofs use + * it to record the build they ran against as evidence; normal session work + * neither observes nor retains anything about an executable, and an + * observation never decides whether a conversation continues. A path is never + * retained: it stops being true when a build moves, and names host layout. * * This is a plain capability the trusted host builds and hands directly to the * provider that needs it. It is deliberately not a contextual Api: a diff --git a/packages/runtime/mod.ts b/packages/runtime/mod.ts index 205066d15..46daef97a 100644 --- a/packages/runtime/mod.ts +++ b/packages/runtime/mod.ts @@ -48,7 +48,6 @@ export { command, compile, useQuietProcessOutput, - writeDiagnostic, } from "./apis.ts"; export type { DirectoryEntry, diff --git a/packages/test-agent/src/components.ts b/packages/test-agent/src/components.ts index 87fd11d0b..361775f6e 100644 --- a/packages/test-agent/src/components.ts +++ b/packages/test-agent/src/components.ts @@ -33,7 +33,7 @@ import { command, installControlledLauncher, readTextFile } from "@executablemd/ import { Test } from "@executablemd/testing"; import { NativeLaunchObserver, useTestAgentController } from "./controller.ts"; import type { ScenarioHandle, ScenarioRecord, TestAgentControllerInternals } from "./controller.ts"; -import { createControlledExecutableObserver } from "./executable-observer.ts"; + import { createDeterministicSessionCoordinator } from "./session-coordinator.ts"; import type { AcpxProviderDependencies } from "@executablemd/acp"; import { normalizeModels, INSPECTION_PROPS, MODELS_PROPS } from "./configuration.ts"; @@ -312,9 +312,7 @@ export function* provisionPartition(options: { // owning two sessions and never exclude each other — and so a route // one published is not an account the next has to live with. coordinator: createDeterministicSessionCoordinator(), - // And its own build, so a client-allocated session in one boundary is - // bound to a build the next does not share. - executableObserver: createControlledExecutableObserver().observer, + routeStore, ...(planConfiguration === undefined ? {} : { planConfiguration }), }); diff --git a/packages/test-agent/src/executable-observer.ts b/packages/test-agent/src/executable-observer.ts deleted file mode 100644 index 47e7df0e9..000000000 --- a/packages/test-agent/src/executable-observer.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * The build a `` partition observes - * (specs/native-agent-session-launch-spec.md §Executable binding). - * - * A session whose identity XMD chose is only meaningful while the build that - * accepted it can be recognized later, and the provider will not act on one - * without an observer to ask. There is no real executable here, so this answers - * the same question deterministically: one stable digest and one canonical - * version for the life of the partition. - * - * Its lifetime is that partition, which is what makes two sibling `` - * elements two worlds rather than two views of one. A harness that wants to - * watch a build drift replaces what this whole seam answers, rather than - * reaching for a control the production path also has. - */ - -import { createHash } from "node:crypto"; -import { TEST_AGENT_BUILD_VERSION } from "./provider.ts"; -import type { ExecutableObserver } from "@executablemd/runtime"; - -export interface ControlledExecutableObserver { - observer: ExecutableObserver; - /** What the next observation answers. Change it to drift the build. */ - observed: { path: string; digest: string; versionOutput: string }; - /** Every command this partition was asked about, in order. */ - asked: string[]; -} - -export function createControlledExecutableObserver( - seed = "test-agent", -): ControlledExecutableObserver { - const controlled: ControlledExecutableObserver = { - asked: [], - observed: { - // Never a real path: nothing is spawned, and the value exists only so - // that a test can prove it does not reach a record. - path: `/xmd-test-agent/${seed}/ui`, - digest: createHash("sha256").update(seed).digest("hex"), - versionOutput: `${TEST_AGENT_BUILD_VERSION}\n`, - }, - observer: { - // deno-lint-ignore require-yield - *observe(command) { - controlled.asked.push(command); - return { - path: controlled.observed.path, - digest: { algorithm: "sha256", value: controlled.observed.digest }, - versionOutput: controlled.observed.versionOutput, - }; - }, - }, - }; - return controlled; -} diff --git a/packages/test-agent/src/provider.ts b/packages/test-agent/src/provider.ts index 66f8d279c..87e0f2779 100644 --- a/packages/test-agent/src/provider.ts +++ b/packages/test-agent/src/provider.ts @@ -25,7 +25,7 @@ import type { } from "@executablemd/acp"; import type { AgentSessionRouteStore, NativeAdapter } from "@executablemd/acp"; import { useRouteSlot } from "./route-slot.ts"; -import type { AgentSessionCoordinator, ExecutableObserver } from "@executablemd/runtime"; +import type { AgentSessionCoordinator } from "@executablemd/runtime"; /** * The name `` registers its partition-selecting factory under. @@ -75,8 +75,7 @@ export interface TestAgentProviderOptions { coordinator?: AgentSessionCoordinator; /** How this partition's sessions were constructed. Its own, like the rest. */ routeStore?: AgentSessionRouteStore; - /** Which build this partition observes. Its own controlled one. */ - executableObserver?: ExecutableObserver; + dependencies?: AcpxProviderDependencies; inspection?: { agent: string; @@ -123,9 +122,6 @@ export const TEST_AGENT_NATIVE_ADAPTER: NativeAdapter = { */ export const TEST_AGENT_CLIENT_NATIVE = "test-agent-client-native"; -/** The version this partition's controlled build reports. Shaped like a real one. */ -export const TEST_AGENT_BUILD_VERSION = "9.9.9 (Test Agent)"; - /** A controlled adapter that names its own sessions, in the test agent's dialect. */ export const TEST_AGENT_CLIENT_NATIVE_ADAPTER: NativeAdapter = { launcher: TEST_AGENT_LAUNCHER, @@ -301,7 +297,7 @@ export function* useTestAgentProvider( }), ...(options.coordinator ? { coordinator: options.coordinator } : {}), ...(options.routeStore ? { routeStore: options.routeStore } : {}), - ...(options.executableObserver ? { executableObserver: options.executableObserver } : {}), + ...(options.dependencies?.createRuntime ? { createRuntime: options.dependencies.createRuntime } : {}), diff --git a/specs/acp-client-spec.md b/specs/acp-client-spec.md index da615a7d0..27fdf7cb9 100644 --- a/specs/acp-client-spec.md +++ b/specs/acp-client-spec.md @@ -238,10 +238,9 @@ Built-in **`claude` and `codex` are advertised** for native launch, and `claude` additionally for attaching ACP to a session a native process constructed. Claude's sessions are named by XMD and created by the native process; Codex names its own and reports it back -(native-agent-session-launch-spec.md). The ownership, construction-route and -executable-observation requirements below therefore apply to them on every -host, and only the hosts that assemble all three — Deno and the compiled -binary — can serve them. An agent that is not advertised keeps ordinary ACP +(native-agent-session-launch-spec.md). The ownership and construction-route requirements +below therefore apply to them on every host, and only the hosts that assemble +both — Deno and the compiled binary — can serve them. An agent that is not advertised keeps ordinary ACP behavior on every host. Every operation that can act on an advertised session — `session()`, a @@ -264,22 +263,19 @@ latest forced-release marker across ordinary ownership. Obsolete shapes refuse; there is no ownership format selection or compatibility reader. Recovery sends no provider request and repairs no identity, route or journal. -The host also passes in a **construction-route store** and an **executable -observer**, directly and from the same trusted root as the coordinator. The -route store is required for an advertised agent whose adapter carries an -executable binding, and a host missing it refuses that agent before any -provider effect, on the same terms as a missing coordinator. The observer is -diagnostic: it reports the version and digest of the executable the current -environment selected, and a host without one continues with the version -reported as undetermined. Neither is a contextual Api, so document middleware -cannot point the observation at one binary while the run spawns another. - -XMD uses the executable selected by the current environment and opens the -retained provider conversation. It requires the provider to confirm the same -native conversation identity. A version or digest change does not refuse -continuation. Missing required confirmation, a different identity or a real -resume failure stops the operation without creating a replacement -conversation. Historical executable observations remain unchanged. +The host also passes in a **construction-route store**, directly and from the +same trusted root as the coordinator. It is required for an advertised agent +whose adapter carries an executable binding, and a host missing it refuses +that agent before any provider effect, on the same terms as a missing +coordinator. It is not a contextual Api, for the same reason the coordinator is +not. + +A conversation continues quietly on the executable the current environment +selects. The provider must positively confirm the retained native identity +before work that requires it. A missing or different assertion refuses without +creating a replacement conversation. Executable version and digest do not +decide admission. Existing routes and journal history remain unchanged; normal +continuation creates no new version-history record. While ownership is held and before any provider construction effect, the provider reconciles the route. A fresh `session()` places the session and @@ -291,11 +287,9 @@ its own sessions publishes `client-native` under an identity that adapter allocated, unless existing durable ACPX state or an existing route says the session was constructed through ACP — in which case it publishes or adopts `acp-first` and retains `identity-unavailable`. A fresh `acp-first` -route for an adapter with an executable binding is published in the **bound** -form, carrying the complete observation of the selected executable as its -history, before ACP creates anything; with no complete observation it is -published unbound. An existing route is never rewritten: an unbound record -stays unbound and continues. Publication is create-once, so the loser of +route is published in the released unbound form before ACP creates anything. +An existing route is never rewritten: a bound record keeps its original +binding, an unbound record stays unbound, and both continue. Publication is create-once, so the loser of either order adopts the winner, and no route converts. A `session()` or subscribed `prompt()` meeting a `client-native` route, @@ -887,12 +881,8 @@ Reconnection first establishes the exact original live child; missing identity or outcome remains uncertain and never authorizes resend. A held conversation's work executes through its captured provider in the -conversation's own task, so diagnostic capture is installed in that owning -task before `useAgentConversation()`; middleware around the caller of a turn -does not move queued work into the caller's scope. A compatibility warning a -reopened conversation owes is therefore delivered to the host that holds it, -and continuation follows the same confirmation and refusal policy as an -ordinary Session. +conversation's own task, and continuation follows the same quiet confirmation +and refusal policy as an ordinary Session. ```ts const opened = yield* useAgentConversation({ @@ -1548,12 +1538,13 @@ arranged in the run's own sidecar, continued by reattaching that row — and the machine-wide account of ownership, construction routes and executable builds describes a different thing entirely. Inheriting the package's advertised sets by omission would make an ordinary workflow Claude prompt demand machine -ownership and a route this profile has no way to give it. The profile therefore -supplies no session coordinator and no route store, and never consults their -namespace. A host may supply an executable observer for diagnostics only: it -reports the version of the executable the run's selection chose, grants no -native capability and admits nothing. A workflow session keeps no executable -history, so it warns only when the current version cannot be determined. +ownership and a route this profile has no way to give it. Workflow sessions use the current selected executable and the provider's +positive confirmation of their retained native identity. They follow the same +quiet-continuation policy as ordinary and held sessions. The workflow profile +supplies no diagnostic observer, machine coordinator or construction-route +store, and both native capability sets remain empty. The run mapping and +provider assertion retain their existing authority. No diagnostic baseline or +journal field is added. A native permission request under this profile does not reach `Agent.requestPermission`. The provider answers it: a reject option when ACP @@ -1886,37 +1877,17 @@ model prompt; the SDK executable is never a fallback. Version output is observation rather than an admission condition. Custom agent commands retain their own selection, and completed replay performs no selection or launch. -The provider retains the selected path before it asks the observer anything, -observes that same file and executes it through the transient child -environment and native argv. It never resolves the launcher name again on the -observer's own PATH. A version that cannot be asked or read leaves no current -build binding and keeps the selection; a missing, non-file or non-executable -selection is an availability failure. A command the host configured other than -the carried adapter is never replaced by it because the agent shares a name: -its backend is not guessed at, so its version is undetermined, and actual -protocol, capability and identity results decide whether it works. - -Before affected live work, XMD warns once per logical session in the current -invocation when the observed version differs from its historical observation. -If the current version cannot be determined, it reports that once and -continues otherwise supported work. Missing historical metadata alone -establishes no observed difference. Diagnostics use stderr and leave -machine-readable stdout unchanged. Completed replay performs no executable -observation and emits no new compatibility warning. - -The warning reads ` has changed from to since this session -was established. Continuing the existing conversation.` with normalized product -versions, or `The version could not be determined. Continuing.`; raw -version output and paths are never displayed. It is written through the -contextual `Stdio` stderr of the task performing the work. The CLI owns one -transient set per invocation and passes the same reference to every provider -it installs as `AcpxProviderDependencies.compatibilityWarnings`; a host that -omits it gives each installation its own. A provider keys a warning by its -private logical placement — provider, original owner command, session key and -placement directory — and claims it synchronously before yielding delivery. -The set admits nothing and is never serialized. A failed diagnostic write is an -ordinary host I/O failure; it authorizes no replacement and no retry of model -work. +The provider carries the selected executable into the matching ACP child +environment and native argv. It does not use a second PATH resolution to +replace that choice. Host selectors retain their joined, output-suppressed +launchability check; the child's version text and exit status impose no +version admission policy. Missing or unlaunchable selections remain +availability failures. Supported custom commands keep their arguments and +environment, and XMD does not guess the backend of an opaque wrapper. + +Continuation produces no compatibility or undetermined-version notice and +retains no new version baseline. Completed replay performs no selection, +observation or launch. For the retained embedded Codex adapter, live availability selects nonempty `CODEX_PATH`, otherwise `codex` on the host PATH. Relative path selections @@ -2171,11 +2142,9 @@ its caller supplied, from Prompt `timeout` or the enclosing AgentProvider availability probe and live runtime. Each embedded Claude or Codex default applies only to its matching retained command; another provider or deliberate custom command receives no default overlay for either agent. A - native-bound operation's observed executable takes precedence: its runtime - receives the bound build's environment in place of the ordinary host - selection, which is never consulted for it. The inputs never enter durable - session records or global process environment. `executableObserver` says how - this host observes the build behind an executable; `agentCwd` answers with the + native-capable operation selects through this same seam once, and carries + that selection into its runtime and native argv. The inputs never enter durable + session records or global process environment. `agentCwd` answers with the directory an Agent runs in when the contextual one is not a directory an agent process could stand in; `mcpServers` and `newSessionOptions` are passed to runtime creation and to `ensureSession()` exactly as given; diff --git a/specs/decisions/004-host-installed-codex-cli.md b/specs/decisions/004-host-installed-codex-cli.md index 0edae7204..c033228d6 100644 --- a/specs/decisions/004-host-installed-codex-cli.md +++ b/specs/decisions/004-host-installed-codex-cli.md @@ -43,7 +43,7 @@ Updating the host CLI can change ordinary availability and the advertised model and effort catalog while the adapter digest stays the same. A session offers whatever the selected host CLI reports. -A session continues on whichever host CLI is selected today, under the +A session continues quietly on whichever host CLI is selected today, under the provider's live confirmation of its original native identity, for every operation including native launch and attachment. The strict build equality this record first kept for native work was replaced by diff --git a/specs/decisions/005-current-executable-session-continuation.md b/specs/decisions/005-current-executable-session-continuation.md index 1410d1edc..bce74652d 100644 --- a/specs/decisions/005-current-executable-session-continuation.md +++ b/specs/decisions/005-current-executable-session-continuation.md @@ -34,19 +34,11 @@ native resume, and after a fresh client-allocated creation once the child has joined. Exit status never confirms identity. A selected executable that is missing or cannot run remains an availability failure. -Before affected live work, XMD warns once per logical session in the current -invocation when the observed version differs from its historical observation. -If the current version cannot be determined, it reports that once and -continues otherwise supported work. Missing historical metadata alone -establishes no observed difference. Diagnostics use stderr and leave -machine-readable stdout unchanged. Completed replay performs no executable -observation and emits no new compatibility warning. - -The invocation owns the warning state. `AcpxProviderDependencies` gains one -member, `compatibilityWarnings?: Set`: the CLI shares one transient set -across every provider installation of an invocation, and a host that omits it -gives each installation its own. Delivery uses the contextual `Stdio` stderr of -the task doing the work; no Agent operation or callback was added. +Sessions continue quietly. XMD does not retain or compare old versions to +produce compatibility messages and emits no undetermined-version replacement +notice. Current executable selection, real availability errors and required +positive native identity confirmation remain. + Recorded CLI, adapter and host versions describe the checks that ran. They are evidence, not an allowlist or a requirement to repeat certification for every @@ -58,12 +50,16 @@ required. ## Consequences Updating an agent CLI no longer requires a new XMD release, a downgrade or a -replacement conversation. A user sees one warning naming both versions. +replacement conversation, and continuing says nothing about the change. -Routes and journals keep the observation recorded when their session was -constructed. Equality between two original records still refuses a -disagreement; nothing compares today's executable with either for admission, -and nothing rewrites history to claim today's executable made it. +Existing routes and journals retain original facts. Fresh construction writes +only the required unbound construction and lifecycle records. Equality between +two original records that both carry a binding still refuses a disagreement; +nothing compares today's executable with either for admission, and nothing +rewrites history to claim today's executable made it. Tested versions remain +evidence rather than release certification. Independently reported usage and +supplied provenance retain their existing contract; an unmeasured build is +absent. Positive identity is not proof of history: a provider asserting the same identity over empty history passes confirmation. Regression suites detect that @@ -72,6 +68,25 @@ with an original-only marker; no runtime detector is claimed. The adapter metadata patches that supply turn identity, acceptance and native identity remain required. This decision does not retire them. +## Amendment: quiet continuation + +Date: 2026-11-18 + +An earlier form of this decision also required a once-per-session warning when +a session's recorded version differed from today's, a notice when the version +could not be determined, fresh executable history in new routes to compare +against, and an invocation-owned `compatibilityWarnings` set to deliver it. +Review then found that newly established ACP-only workflow sessions had no +place to keep that history. + +The user withdrew the requirement: “We don’t need to save the old version,l or +show the message but if we did, we could store it in the journal”. The journal +suggestion is conditional future guidance, not a request to add storage. The +amendment supersedes the earlier warning requirement and the workflow warning +gap; it does not repair that gap or approve the storage proposal made for it. +The earlier warning-state approval remains historical evidence, not a reason to +keep the member, which was removed with its consumers. + ## Current owner - [ACP client — Sessions: ownership, routes and attachment](../acp-client-spec.md#sessions-ownership-routes-and-attachment) diff --git a/specs/native-agent-session-launch-spec.md b/specs/native-agent-session-launch-spec.md index e32034dc9..99362c801 100644 --- a/specs/native-agent-session-launch-spec.md +++ b/specs/native-agent-session-launch-spec.md @@ -383,15 +383,19 @@ codex resume ### Executable build binding -XMD uses the executable selected by the current environment and opens the -retained provider conversation. It requires the provider to confirm the same -native conversation identity. A version or digest change does not refuse -continuation. Missing required confirmation, a different identity or a real -resume failure stops the operation without creating a replacement -conversation. Historical executable observations remain unchanged. +A conversation continues quietly on the executable the current environment +selects. The provider must positively confirm the retained native identity +before work that requires it. A missing or different assertion refuses without +creating a replacement conversation. Executable version and digest do not +decide admission. Existing routes and journal history remain unchanged; normal +continuation creates no new version-history record. -A session XMD constructs retains, as diagnostic history, the complete -observation of the executable that constructed it, when one could be made: +Fresh production construction uses the released unbound V1 route forms. +Client-native construction retains its native identity, client-allocation +provenance, launcher and instruction digest. No current version or digest is +persisted for compatibility reporting. + +Released records may still carry the binding an earlier release recorded: ```ts interface ExecutableBuildBindingV1 { @@ -401,63 +405,41 @@ interface ExecutableBuildBindingV1 { } ``` -The digest is the lowercase SHA-256 of the canonical executable target; -`reportedVersion` is the adapter's canonical parse of what that exact target -reports. That parse accepts exactly one canonical line: output naming no build, -or naming several, is an undetermined version rather than an answer. Neither is -repeated in a diagnostic, and a binding is never invented for it. A path is -never a member: it says where a build was, which stops being true, and it names -host layout besides. Equality over these members is used only to check that two -original accounts of one session agree; it never admits a live executable. +Released V1/V2/V3 routes and prepared journals remain readable and unchanged. +Before incomplete live work, compare the original provider, identity, +provenance, launcher, instructions and policy. When both original accounts +contain executable bindings, those original bindings must agree. A missing +binding alone is not disagreement. No original binding is compared with +today's executable for admission. A new phase referring to an existing bound +route carries its original binding only where required to preserve that +agreement. Selection comes first. A carried adapter's executable is selected by the host once — Claude's nonempty `CLAUDE_CODE_EXECUTABLE`, otherwise `claude` on the host PATH; Codex's nonempty `CODEX_PATH`, otherwise `codex` on the host PATH; relative selections against the host execution directory, and a bad explicit -choice with no PATH fallback. A host that makes no selection of its own lets -its observer resolve the launcher command. The host supplies an executable -observer directly to the provider, alongside the coordinator and the route -store. It canonicalizes the selected target, requires an executable regular -file, hashes it, and asks that same file its version. It is deliberately not a -Context, contextual Api, Agent operation, component or middleware value: a -resolver document middleware could replace could point the observation at one -binary while the run spawns another. A controlled test substitutes the whole -observer through the same constructor seam. A missing, non-file or -non-executable selection is an availability failure; a version that cannot be -asked or read is a diagnostic and keeps the selection. - -One observation yields two kinds of value: - -```text -durable: the executable build binding -live: the canonical executable path -``` - -The live path exists only in the operation that selected it. Native creation and -resume replace the adapter command's first argv member with it, and the matching -Claude ACP child receives it through `CLAUDE_CODE_EXECUTABLE` in a transient -child-process environment. The integrity-pinned ACPX 0.22.0 source closure -supplies the child-only environment seam. Its local first-turn materialization -barrier remains required independently of that released capability. It enters no route, journal, ACPX session option or -record, public result, diagnostic, `process.env`, or provider partition that -outlives its last handle. +choice with no PATH fallback. The host selector resolves a canonical regular +executable and verifies that it can start; its joined, output-suppressed +`--version` child is a launchability check, and its version text and exit +status decide nothing. A missing or unlaunchable selection is an availability +failure. A host that makes no selection runs the adapter's declared launcher +name, and a custom native adapter keeps its declared command. + +The selected path is live only. It exists only in the operation that selected +it. Native creation and resume replace the adapter command's first argv member +with it, and the matching ACP child receives it through its adapter's variable +— `CLAUDE_CODE_EXECUTABLE` or `CODEX_PATH` — in a transient child-process +environment. The integrity-pinned ACPX 0.22.0 source closure supplies the +child-only environment seam. Its local first-turn materialization barrier +remains required independently of that released capability. The path enters no +route, journal, ACPX session option or record, public result, diagnostic, +`process.env`, or provider partition that outlives its last handle. A session established before any build was recorded is legacy-unbound. Its route directly supplies the native identity, allocation provenance, instruction digest and launcher, so no historical build is needed for exact attachment or native preflight. It continues under the same selection and -confirmation as any other session, and no binding is invented for it: it is -never upgraded in place, because a build observed today says which build is -installed now, not which one established the conversation. Missing historical -metadata alone establishes no observed difference. - -Before affected live work, XMD warns once per logical session in the current -invocation when the observed version differs from its historical observation. -If the current version cannot be determined, it reports that once and -continues otherwise supported work. Missing historical metadata alone -establishes no observed difference. Diagnostics use stderr and leave -machine-readable stdout unchanged. Completed replay performs no executable -observation and emits no new compatibility warning. +confirmation as any other session, and no binding is invented for it. ### Attachment capability @@ -501,11 +483,11 @@ initial use, original-context continuity and native handoff where supported. Actual protocol capabilities and provider-native identity assertions remain required. -What the executable observer recognizes is one canonical `codex-cli x.y.z` -line and nothing else: another canonical version is recognized, and output -that is bare (`codex-cli`), malformed, or carries a second line is an -undetermined version. The product word travels with the number because a bare -semver from another tool compares equal to one from this one. +The opt-in proofs may still measure a version explicitly. Their Codex parser +recognizes one canonical `codex-cli x.y.z` line and nothing else: output that is +bare (`codex-cli`), malformed, or carries a second line is no answer. The +product word travels with the number because a bare semver from another tool +compares equal to one from this one. Normal work reads no version at all. Every later native launch, attachment or incomplete launch replay selects the current executable and positively confirms the retained native identity before @@ -553,13 +535,12 @@ session one of them constructs through ACP and the other does not. where the adapter owes a materialization turn the identity does not exist until that turn is accepted: -9. The current executable is selected and observed, and the `acp-first` route is - published or adopted — **before** the provider constructs anything, so the - route a later run is held to already exists when there is a session to hold - it to. A fresh route records the complete observation as V3 history, or is - unbound without one; an existing route is never rewritten. An executable that - cannot run ends the launch here with nothing durable written about a session; - a version difference is reported once and continues. +9. The current executable is selected, and the `acp-first` route is published or + adopted — **before** the provider constructs anything, so the route a later + run is held to already exists when there is a session to hold it to. A fresh + route is unbound V1; an existing route is never rewritten. An executable that + cannot run ends the launch here with nothing durable written about a + session. 10. The provider creates or resumes the durable provider session through ACPX, applying the prepared instruction layer and contextual cwd configuration. An **already-established** session has an identity of its own: the provider @@ -611,8 +592,8 @@ owner to release — what has to be settled first is which conversation this is: close is joined before preparation is retained. Only where no route names it yet does the adapter allocate one, inside ownership and before any process exists; nothing else supplies or replaces it. -11. A launch that allocated publishes the `client-native` route create-once — - V2 with the complete observation as history, or V1 without one — and +11. A launch that allocated publishes the unbound V1 `client-native` route + create-once, and what it publishes against is authoritative — whoever published first described the session that exists. Four outcomes, and no other: - this launch's own candidate won — `created`; @@ -870,10 +851,9 @@ session, prompt, launch and incomplete replay refuses there with `unsupported-capability`, before contacting an agent, while read-only resolution and non-advertised ACP work are unaffected. An advertised agent whose adapter carries an executable binding also requires a route store; a host without one -refuses before any provider effect, whichever side names the session. The -executable observer is diagnostic and optional: a host without one continues -and reports the version as undetermined. An adapter that carries no binding -keeps its ordinary behavior without those dependencies. +refuses before any provider effect, whichever side names the session. No executable +observer is needed. An adapter that carries no binding keeps its ordinary +behavior without those dependencies. ### Exact-target ownership inspection and recovery @@ -1194,21 +1174,19 @@ retained with the preparation and is what governs the **first native user turn**. Neither is ever substituted for the other, and the turn spent here cannot perform the task the body describes. -A prepared record carries `executableBinding` exactly when the route it agrees -with is bound, whichever side named the session, and it carries the route's -original observation rather than today's. It is optional for compatibility: a -record without it is legacy history, readable and continued under the same -selection and confirmation as any other. A provider-returned -preparation whose adapter binds a build carries one too — `codex` does, on the -bound V3 ACP-first route — and a refusal that prepared no identity invents -none. +A prepared record carries `executableBinding` exactly when the existing route it +agrees with is bound, whichever side named the session, and it carries the +route's original binding rather than anything about today's executable. A +fresh preparation carries none. A record without it is readable and continued +under the same selection and confirmation as any other, and a refusal that +prepared no identity invents none. Every incomplete replay requires agreement between its journal and its route on identity, provenance, instruction digest, launcher and provider before its first live effect. When both original accounts carry an executable binding, those -bindings must agree exactly; a missing observation alone is not a disagreement, -and today's observation is never compared with either. The live executable is -then selected, and the conversation is confirmed positively instead of by +bindings must agree exactly; a missing binding alone is not a disagreement, and +no original binding is compared with today's executable. The live executable +is then selected, and the conversation is confirmed positively instead of by build equality. Neither account repairs or republishes the other: a replay that found a disagreement has discovered that the session it was going to continue is not the session it prepared, and retains `identity-unavailable` without starting @@ -1225,8 +1203,8 @@ identity when handoff never began, and confirms after the joined creation. A detached replay resumes only and never creates if confirmation fails. An ambiguous materialization stays recovery-required and sends no turn. Legacy unbound launches follow these same paths. A **completed** replay reads its -journal and nothing else — it performs no selection, observation, warning or -live validation and contacts no route store, observer, ACP runtime or process. +journal and nothing else — it performs no selection, observation or live +validation and contacts no route store, ACP runtime or process. A session XMD named takes its instruction layer from one invocation-private file, mode `0600`, passed by path. The text appears in neither argv nor @@ -1325,9 +1303,8 @@ that only placed one has established nothing, so a launch inside it constructs the session it named rather than meeting one. A selected executable that is missing, is not a file or cannot be run fails with -`executable-binding-refused`, the availability class. A version that differs -from the session's history, or cannot be determined, is a diagnostic warning and -never this refusal. Neither carries an executable path, raw version output, host +`executable-binding-refused`, the availability class. An executable's version +never causes this refusal, or any notice. It carries an executable path, raw version output, host error, argv, environment, credential, instruction text or provider payload. An attachment that reaches the provider and cannot open the conversation the @@ -1381,8 +1358,7 @@ belongs to whoever is running the tests. That is what lets an authored means a launch under `` never reaches the host's launcher. Only the Deno and compiled hosts assemble machine-wide agent sessions: a session -coordinator, a construction-route store and an executable observer, all rooted -together, plus the two advertised capability sets this host has proven. Node and +coordinator and a construction-route store, rooted together, plus the two advertised capability sets this host has proven. Node and Bun keep the same advertised names and assemble none of the answers, so every advertised operation refuses before provider work rather than acting while a native UI may be in the conversation — as *Ownership and concurrency* describes. @@ -1436,13 +1412,12 @@ Focused tests prove: natural key, contention refuses instead of queueing, a crashed owner leaves a recovery tombstone, and a host with no coordinator refuses before contacting an agent; -18. a build binding is read exactly, an inexact record refuses rather than being - read past, and a changed, moved or unrecognized current build continues the - same confirmed conversation with at most one warning; +18. a released build binding is read exactly, an inexact record refuses rather + than being read past, and a changed or moved current executable continues the + same confirmed conversation quietly; 19. new client-native construction selects the executable before it allocates, - publishes a route recording any complete observation, and retains a - preparation that agrees with it, while a legacy V1 route continues under - today's selection and gains nothing; + publishes an unbound V1 route, and retains a preparation that agrees with it, + while an existing route continues under today's selection and gains nothing; 20. a `` or `` on a client-native route supplies the route identity as the exact resume identity, delivers the selected path only to the matching child's transient environment, and refuses before a turn on a @@ -1534,8 +1509,8 @@ native-launch capability in the ACPX provider; provider-native identity that is either asserted by the provider or allocated by the adapter before the provider exists, retained explicitly and never inferred; a strict create-once construction route beside the coordinator's own records, -in a released unbound form and a bound one; the host-owned diagnostic -executable observer and the build history it records; ACP attachment to a +in a released unbound form and a bound one, of which fresh construction writes +the unbound form; ACP attachment to a client-native session under its exact retained identity, through runtime partitions keyed by agent command and selected environment; an inherited foreground-terminal interactive child with cancellation and @@ -1602,10 +1577,10 @@ degrading: record. New records write neither member, and an incomplete older record does no configuration work because one was present. Canonical `configuration` beside either released member is ambiguous and refuses. -- **Executable history is never rebound.** A route keeps the observation of the - executable that constructed its session. A later build continues the same - confirmed conversation and is reported against that history; nothing rewrites - the route or the provider's history to claim the current executable made it. +- **Executable history is never rebound.** A released route keeps any binding + it recorded. A later executable continues the same confirmed conversation + quietly; nothing rewrites the route or the provider's history to claim the + current executable made it. Additional provider adapters land independently against the same core contract. An adapter that cannot prove instruction injection before the first user turn @@ -1679,7 +1654,7 @@ Implementation review checks these frozen invariants: already started before quiescence; quiescence is answered from that account; and a close that failed releases nothing and acknowledges none. Items 18 and 22 are the #891 amendment: tested versions are evidence, and a -session continues on the current executable under positive identity +session continues quietly on the current executable under positive identity confirmation. Item 12 is the 2026-08-20 architecture amendment. ACPX fixes `systemPrompt` at diff --git a/specs/repl-spec.md b/specs/repl-spec.md index bb2282406..7108ff698 100644 --- a/specs/repl-spec.md +++ b/specs/repl-spec.md @@ -2078,16 +2078,6 @@ from rendered document Output: forwarding adds nothing to the root result. Bound commands display only what the document explicitly renders, a `` capture still hides stdout, and `silent exec` displays neither channel. -Entry diagnostics appear as Command stderr beside the entry's execution output. -Held-conversation diagnostics appear as transient stderr beside the Sidekick reply -and remain visible after the turn settles in this invocation. They do not become -generated document source, durable chat messages or failed-reply text. The held -reading is captured in the task that owns the conversation, before it opens, -because a held conversation's queued work runs there rather than under the -message that asked for a turn; each line is privacy-projected by that -conversation's protected-input owner and made inert like Command text. The CLI -root owns these display copies for the life of the command. - Command text is inert before measurement and drawing. LF separates rows; other C0 controls, DEL and C1 controls appear as ASCII `\xNN` escapes. Cursor motion, clearing, OSC and terminal mode sequences therefore remain readable text. The diff --git a/specs/workflow-workspace-spec.md b/specs/workflow-workspace-spec.md index d9e6f7a50..c4926e7cd 100644 --- a/specs/workflow-workspace-spec.md +++ b/specs/workflow-workspace-spec.md @@ -2362,8 +2362,7 @@ by #496 and does not widen this ceiling. both ordinary-run native capability sets empty and installs no native foreground launcher, so a launch is refused before provider preparation, session ownership transfer, or process creation. The host does not expose the -machine-wide coordinator, construction-route store or executable observer to -repair that refusal. Supporting an interactive workflow-native handoff would +machine-wide coordinator or construction-route store to repair that refusal. Supporting an interactive workflow-native handoff would require a separate retained-host and permission contract; it does not weaken the current sandbox. @@ -2750,20 +2749,23 @@ coordinator and no construction-route store, and consults none of their namespace. `xmd run` owns a machine-wide account of who owns a session and how it was constructed; a workflow session is named by the row below instead, and an agent served here is served over ACP alone. Composing the two is a separate -design. The workflow host may supply an executable observer for diagnostics -only; it grants no native capability. +design. The workflow host separately selects its installed Claude or Codex launcher and supplies its path only through the retained adapter child's transient environment. This selection grants no native-session capability and performs -no executable-build admission. A retained session of a built-in adapter is -reopened by its exact loading target under the provider's live confirmation of -its retained native identity, whichever executable is selected today; a -missing or differing assertion refuses before settings or a prompt and creates -no substitute. Because the run keeps no executable history, a release change -emits no difference warning; a version that cannot be determined is reported -once per session in the invocation. Partial replay attaches lazily, and -completed replay performs no selection, observation, warning or live work. +no executable-build admission. + +Workflow sessions use the current selected executable and the provider's +positive confirmation of their retained native identity. They follow the same +quiet-continuation policy as ordinary and held sessions: a missing or +differing assertion refuses before settings or a prompt and creates no +substitute. The workflow profile supplies no diagnostic observer, machine +coordinator or construction-route store, and both native capability sets +remain empty. The run mapping and provider assertion retain their existing +authority. No diagnostic baseline or journal field is added. Partial replay +attaches lazily, and completed replay performs no selection, observation or +live work. **The mapping lives in the run.** Its database row commits in the run's transaction and is part of the initial schema. Provider session stores and empty From 996e9b9af8483f388a0571a3b496af160448268a Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 06:47:32 -0500 Subject: [PATCH 4/7] Reconcile proofs and specs with quiet unbound continuation (#891) The opt-in live proofs still required bound fresh routes and pinned CLI releases, and the specs still described version reporting and bound V2/V3 fresh construction. - ClaudeNativeToAcp: assert the unbound V1 fresh route and an absent journal binding, check only that route and journal agree, and keep the observed version and digest as recorded evidence. The absent-identity case still publishes a historical V2 route. - Codex native and zero-turn documents: Codex release, digest and platform are evidence; only the carried adapter identity is asserted; fresh routes carry no build. - Claude launch documents: version and platform are evidence. The zero-turn journey accepts XMD's own confirmation refusal (identity-unavailable, no re-entry child) as the exact-identity refusal it is. - Native and ACP specs: fresh construction is unbound V1 and nothing about an executable's version is compared or reported. - Remove the unreadable NativeBinding.versionArgs, the stale boundSessions comment and leftover blank lines. --- packages/acp/src/ClaudeNativeLaunch.test.md | 6 +- packages/acp/src/ClaudeNativeToAcp.test.md | 33 +++++---- packages/acp/src/ClaudeZeroTurnExit.test.md | 38 ++++++++--- packages/acp/src/CodexNativeLaunch.test.md | 46 ++++++------- .../acp/src/CodexZeroNativeTurnExit.test.md | 48 ++++++------- packages/acp/src/native-launch.ts | 2 - packages/acp/src/provider.ts | 16 ++--- .../fixtures/claude-native-launch-proof.ts | 17 ++++- .../fixtures/claude-native-to-acp-proof.ts | 27 ++++---- .../fixtures/codex-native-launch-proof.ts | 6 +- packages/cli/src/deno-workflow.ts | 1 - packages/cli/src/workflow-agent.ts | 7 +- packages/test-agent/src/components.ts | 2 - packages/test-agent/src/provider.ts | 2 - specs/acp-client-spec.md | 3 +- specs/native-agent-session-launch-spec.md | 68 ++++++++++--------- 16 files changed, 167 insertions(+), 155 deletions(-) diff --git a/packages/acp/src/ClaudeNativeLaunch.test.md b/packages/acp/src/ClaudeNativeLaunch.test.md index 717240272..3b525206b 100644 --- a/packages/acp/src/ClaudeNativeLaunch.test.md +++ b/packages/acp/src/ClaudeNativeLaunch.test.md @@ -244,11 +244,9 @@ nothing was said before the first. The question named neither the sentence nor any file. The answer carried the opening sentence of `.agents/implementor.md` exactly, which only the prepared -layer could have supplied. +layer could have supplied. The Claude version, platform and architecture the +verdict reports are evidence of what ran, never a condition of passing. - - - ## The resumed session is the same conversation diff --git a/packages/acp/src/ClaudeNativeToAcp.test.md b/packages/acp/src/ClaudeNativeToAcp.test.md index b80008aff..e342057a3 100644 --- a/packages/acp/src/ClaudeNativeToAcp.test.md +++ b/packages/acp/src/ClaudeNativeToAcp.test.md @@ -183,11 +183,10 @@ would fail this document. "observed": { "type": "object", "additionalProperties": false, - "required": ["version", "digestPresent", "matchesRoute"], + "required": ["version", "digestPresent"], "properties": { "version": { "type": "string" }, - "digestPresent": { "type": "boolean" }, - "matchesRoute": { "type": "boolean" } + "digestPresent": { "type": "boolean" } } }, "absent": { @@ -276,8 +275,6 @@ memory — never in the instruction file, the argument vector, the environment, session key, or the document the ACP turn ran. The answer produced it behind a prefix that appears in no earlier turn. - - @@ -297,32 +294,33 @@ the launch, and nothing after it named a second. -## One conversation, one build, four accounts +## One conversation, four accounts The route, the journal, the ACP client's own arrangement and the identity the -launch reported all name the same conversation — and the build this run would -use is the build the route retained. +launch reported all name the same conversation. A fresh route records how the +session was constructed and nothing about the executable that ran it, so +neither the route nor the journal carries a build. The platform, architecture, +Claude version and digest the verdict reports are evidence of what ran, never +a condition of passing. - + - - + + - + - - ## The adapter the attachment was proven against @@ -337,9 +335,10 @@ so this binding names one — and the name is live, reaching no durable record. ## An identity nobody ever had is refused before a turn -The independent case. A bound route naming a fresh random conversation, in a -directory of its own, with no provider arrangement beside it: the prompt refuses -rather than starting an empty conversation and answering from it. +The independent case. A route in the historical bound V2 form an earlier release +published, naming a fresh random conversation, in a directory of its own, with +no provider arrangement beside it: the prompt reads that released record, and +refuses rather than starting an empty conversation and answering from it. diff --git a/packages/acp/src/ClaudeZeroTurnExit.test.md b/packages/acp/src/ClaudeZeroTurnExit.test.md index c4fcfb706..13414cff8 100644 --- a/packages/acp/src/ClaudeZeroTurnExit.test.md +++ b/packages/acp/src/ClaudeZeroTurnExit.test.md @@ -4,7 +4,13 @@ session and hands you Claude's own interactive UI for it. This document asks the smallest question about that session's identity: if you leave without saying anything, does running the same command again put you back in *that* -conversation — or does Claude at least refuse that exact session out loud? +conversation — or is that exact session refused out loud? + +XMD confirms the identity it allocated over ACP once the native process has +exited, and again before it resumes one. If Claude kept nothing of a session +nobody spoke in, that confirmation is where the refusal happens: the first +launch records `identity-unavailable`, and the second refuses before starting +any Claude at all. Silently landing somewhere else is the failure this is looking for. A session picker, a replacement identity, or a fresh conversation wearing the old name @@ -232,9 +238,9 @@ One session identity was chosen by the adapter before any process existed. The first command created that conversation; the second resumed it. Nothing translated an ACP or ACPX value into it, and no second candidate was allocated. - - - +The Claude version, platform and architecture the verdict reports are evidence +of what ran, never a condition of passing. + @@ -251,7 +257,7 @@ section and no other role's. - + ## Every key sent was terminal control @@ -263,17 +269,24 @@ Ctrl-D bytes: one to ask the prompt whether it is there, one to leave. expr={proof.reentryExitControlBytes === "0404" || proof.outcome === "no-session"} /> -## The two commands are the documented ones +## The commands are the documented ones Creation names the session and hands over a private instruction file. Re-entry resumes that same name and hands over nothing — a `--session-id` there would be -a second conversation, not a continuation. +a second conversation, not a continuation. When the identity was refused, no +re-entry command ran at all. "]} /> + + + + + + ## The instruction layer travelled privately @@ -300,14 +313,17 @@ process on the machine can read from. - + + + + ## Only two answers are accepted -Re-entry reached the identity it was given, or Claude refused that exact -identity and XMD failed closed. A picker, a replacement identity or a fresh -conversation is none of those. +Re-entry reached the identity it was given, or that exact identity was refused — +by XMD's own confirmation or by Claude — and XMD failed closed. A picker, a +replacement identity or a fresh conversation is none of those. diff --git a/packages/acp/src/CodexNativeLaunch.test.md b/packages/acp/src/CodexNativeLaunch.test.md index fee0096e7..8a55cc40e 100644 --- a/packages/acp/src/CodexNativeLaunch.test.md +++ b/packages/acp/src/CodexNativeLaunch.test.md @@ -18,13 +18,14 @@ rejoins the same conversation over ACP — from an authored document that has never seen the marker — and asks for it. Recovering it is what makes the native UI and the ACP session one conversation rather than two wearing the same name. -Getting there costs one turn nobody asked for. Codex CLI 0.153.2 does not write -a conversation anywhere `codex resume` can find it until a turn has completed in -it, so XMD spends exactly one of its own first: `codex-materialization.v1`, -whose only job is to make the conversation openable. That the operator can then -leave without ever speaking — and come back without buying a second one — is the -subject of `CodexZeroNativeTurnExit.test.md`, so that question can be corrected -without respending the three turns this document is authorized to spend. +Getting there costs one turn nobody asked for. Codex CLI, as first proven at +0.153.2, does not write a conversation anywhere `codex resume` can find it +until a turn has completed in it, so XMD spends exactly one of its own first: +`codex-materialization.v1`, whose only job is to make the conversation +openable. That the operator can then leave without ever speaking — and come +back without buying a second one — is the subject of +`CodexZeroNativeTurnExit.test.md`, so that question can be corrected without +respending the three turns this document is authorized to spend. ## What this costs, and what it touches @@ -38,8 +39,10 @@ authored content. It is opt-in twice over. Without `XMD_CODEX_NATIVE_PROOF=1` the fixture refuses before starting any Codex process; without a separate `XMD_CODEX_MODEL_TURNS_AUTHORIZED=3` it refuses before spending a turn. It also -refuses on a machine outside the frozen compatibility tuple below, because the -finding this feature rests on is a fact about one Codex build. +refuses when the carried Codex adapter is not the one named below, because that +adapter is part of XMD's own integration. The installed Codex release, its +digest and the host platform are recorded as evidence of what ran and never +decide whether it passes. Everything sent besides those three turns is terminal control: Codex's own directory trust dialog is answered at most once with the choice it pre-selects, @@ -278,19 +281,12 @@ that one did. -## The frozen compatibility point +## The carried adapter, and what else ran -The materialization turn exists because of a fact about one Codex build. This -records which one, so a later build that stopped needing it — or started needing -something else — cannot pass as this one. +The adapter is XMD's own integration, so this run names it exactly. The Codex +release, its digest, the platform and the architecture are reported beside it +as evidence of what this run exercised; none is compared with an earlier run. - - - - - - + + diff --git a/packages/acp/src/CodexZeroNativeTurnExit.test.md b/packages/acp/src/CodexZeroNativeTurnExit.test.md index 73b706bac..5cb32dda5 100644 --- a/packages/acp/src/CodexZeroNativeTurnExit.test.md +++ b/packages/acp/src/CodexZeroNativeTurnExit.test.md @@ -4,12 +4,12 @@ A prepared session you never speak in should still be there tomorrow. For Claude that costs nothing, and `ClaudeZeroTurnExit.test.md` proves it: the session the launch constructs is openable the moment it exists. -Codex is not like that. Codex CLI 0.153.2 does not write a conversation anywhere -`codex resume` can find it until a turn has completed in it, so a launch that -handed you the native UI without one would hand you a name Codex disowns. XMD -therefore spends exactly one model turn of its own — `codex-materialization.v1`, -whose only job is to make the conversation openable — and then gets out of the -way. +Codex is not like that. Codex CLI, as first proven at 0.153.2, does not write a +conversation anywhere `codex resume` can find it until a turn has completed in +it, so a launch that handed you the native UI without one would hand you a name +Codex disowns. XMD therefore spends exactly one model turn of its own — +`codex-materialization.v1`, whose only job is to make the conversation openable +— and then gets out of the way. That turn is the whole subject of this document, and it asks the two questions that decide whether it was worth spending. @@ -38,8 +38,10 @@ identity, environment or authored content. It is opt-in twice over. Without `XMD_CODEX_NATIVE_PROOF=1` the fixture refuses before starting any Codex process; without a separate `XMD_CODEX_MODEL_TURNS_AUTHORIZED=1` it refuses before spending the turn. It -also refuses on a machine outside the frozen compatibility tuple below, because -the finding this feature rests on is a fact about one Codex build. +also refuses when the carried Codex adapter is not the one named below, because +that adapter is part of XMD's own integration. The installed Codex release, its +digest and the host platform are recorded as evidence of what ran and never +decide whether it passes. Everything sent besides that turn is terminal control: Codex's own directory trust dialog is answered at most once with the choice it pre-selects, and the @@ -254,19 +256,12 @@ of the public contract may not open. -## The frozen compatibility point +## The carried adapter, and what else ran -The materialization turn exists because of a fact about one Codex build. This -records which one, so a later build that stopped needing it — or started needing -something else — cannot pass as this one. +The adapter is XMD's own integration, so this run names it exactly. The Codex +release, its digest, the platform and the architecture are reported beside it +as evidence of what this run exercised; none is compared with an earlier run. - - - - - - + + @@ -404,11 +399,12 @@ finding a conversation that is already openable, does not. -## Without the authorization, or the build, nothing started +## Without the authorization, or the carried adapter, nothing started The refusal happens before any Codex conversation exists, so an unauthorized run spends no turn and observes nothing. This is the branch that runs on an ordinary -machine, and the branch that runs on a machine outside the frozen tuple. +machine, and the branch that runs when the carried adapter is not the one named +above. { verdict.advertised[0] === "claude"; verdict.verdict = established ? "PASS" : "ENVIRONMENT_BLOCKED"; verdict.detail = established - ? "the frozen compatibility point is established, and no model turn was spent" - : "the frozen compatibility point is not established"; + ? "the surfaces this journey needs are established, and no model turn was spent" + : "the surfaces this journey needs are not established"; return verdict; } diff --git a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts index d8b28e15e..720063121 100644 --- a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts @@ -856,11 +856,16 @@ interface JourneyVerdict { present: boolean; agentSessionId: string; }; - /** The build this run observed, reobserved after the whole journey. */ + /** + * The build this run observed after the whole journey. + * + * Recorded evidence of what ran. It decides nothing: a fresh route keeps no + * executable history to compare it with, and a release absent from earlier + * evidence is what this opt-in regression exists to exercise. + */ observed: { version: string; digestPresent: boolean; - matchesRoute: boolean; }; /** The independent case: a route naming a conversation nobody ever had. */ absent: { @@ -943,7 +948,7 @@ function blankJourney(mode: Mode): JourneyVerdict { failureClasses: [], }, arrangement: { present: false, agentSessionId: "" }, - observed: { version: "", digestPresent: false, matchesRoute: false }, + observed: { version: "", digestPresent: false }, absent: { ran: false, xmdExitCode: -1, @@ -1676,8 +1681,8 @@ function* runAttachment( verdict.markerRecovered = squeeze(acp.stdout).includes(`${RECOVER_PREFIX}${marker}`); verdict.outcome = verdict.markerRecovered ? "same-conversation" : "unresolved"; - // Reobserved after the whole journey, against what the route retained. A - // build that moved is the same build; a build that changed is not. + // Observed after the whole journey, as evidence of which build ran. Nothing + // is compared with it. const reobserved = yield* observeBuild(journey); verdict.observed.version = reobserved.version; verdict.observed.digestPresent = reobserved.digest.length === 64; @@ -1826,14 +1831,12 @@ function decideAttachment(verdict: JourneyVerdict): void { verdict.detail = "the route, the journal and the ACP arrangement do not name one conversation"; return; } - verdict.observed.matchesRoute = - verdict.observed.version.length > 0 && verdict.observed.version === verdict.route.buildVersion; - if ( - !verdict.observed.matchesRoute || - verdict.journal.buildVersion !== verdict.route.buildVersion - ) { + // A fresh route and its journal record no executable history. Whatever the + // two original accounts say about a build, they must say the same thing; the + // build this run used is never compared with either. + if (verdict.journal.buildVersion !== verdict.route.buildVersion) { verdict.verdict = "PRODUCT_FAILED"; - verdict.detail = "the retained build and the build this run would use are not the same"; + verdict.detail = "the route and the journal describe the session's build differently"; return; } if (verdict.substitutedIdentity || verdict.freshFallback || verdict.routeConverted) { diff --git a/packages/acp/tests/fixtures/codex-native-launch-proof.ts b/packages/acp/tests/fixtures/codex-native-launch-proof.ts index 060af68ae..b6200338b 100644 --- a/packages/acp/tests/fixtures/codex-native-launch-proof.ts +++ b/packages/acp/tests/fixtures/codex-native-launch-proof.ts @@ -1694,7 +1694,7 @@ function* ready(journey: Journey, verdict: JourneyVerdict): Operation { if (!verdict.compatibilityTupleFrozen) { verdict.ran = false; verdict.verdict = "ENVIRONMENT_BLOCKED"; - verdict.detail = "this journey is only meaningful against the frozen compatibility tuple"; + verdict.detail = "this journey is only meaningful through the carried adapter it names"; return false; } if (!verdict.projectCopyVerified) { @@ -2284,8 +2284,8 @@ function* runPreflight(): Operation { verdict.binaryBuilt; verdict.verdict = established ? "PASS" : "ENVIRONMENT_BLOCKED"; verdict.detail = established - ? "the frozen compatibility point is established, and no model turn was spent" - : "the frozen compatibility point is not established"; + ? "the surfaces this journey needs are established, and no model turn was spent" + : "the surfaces this journey needs are not established"; return verdict; } diff --git a/packages/cli/src/deno-workflow.ts b/packages/cli/src/deno-workflow.ts index 09ca29e7a..6908d8182 100644 --- a/packages/cli/src/deno-workflow.ts +++ b/packages/cli/src/deno-workflow.ts @@ -50,7 +50,6 @@ export function* useDenoWorkflowHost( const configured = yield* readEnv(RUN_STORAGE_ROOT_ENV); const root = configured === undefined || configured === "" ? DEFAULT_RUN_STORAGE_ROOT : configured; - return { useRunHost(): Operation { return useWorkflowRunHost({ root }); diff --git a/packages/cli/src/workflow-agent.ts b/packages/cli/src/workflow-agent.ts index 24c4520a8..bdf5276bf 100644 --- a/packages/cli/src/workflow-agent.ts +++ b/packages/cli/src/workflow-agent.ts @@ -438,15 +438,14 @@ export function* useWorkflowAgentProfile(options: WorkflowAgentProfileOptions): ...(options.createRuntime === undefined ? {} : { createRuntime: options.createRuntime }), ...(options.agentProcessEnv === undefined ? {} : { agentProcessEnv: options.agentProcessEnv }), ...(options.promptUsageHost === undefined ? {} : { promptUsageHost: options.promptUsageHost }), - // ACP-only, stated rather than inherited. A workflow session belongs to a // run, not to this machine: it is named by a row in the run's own database, // arranged in the run's own sidecar, and continued by reattaching that row. // The ordinary-run capabilities are about a different account entirely — // machine-wide ownership and construction routes — and this profile - // supplies neither. Inheriting the package's - // advertised sets by omission would make a workflow Claude prompt demand - // ownership and a route that this profile has no way to give it. + // supplies neither. Inheriting the package's advertised sets by omission + // would make a workflow Claude prompt demand ownership and a route that + // this profile has no way to give it. advertiseNativeLaunch: [], advertiseClientNativeAttachment: [], // The Workspace root is a logical path, not a directory an agent process diff --git a/packages/test-agent/src/components.ts b/packages/test-agent/src/components.ts index 361775f6e..533510bfa 100644 --- a/packages/test-agent/src/components.ts +++ b/packages/test-agent/src/components.ts @@ -33,7 +33,6 @@ import { command, installControlledLauncher, readTextFile } from "@executablemd/ import { Test } from "@executablemd/testing"; import { NativeLaunchObserver, useTestAgentController } from "./controller.ts"; import type { ScenarioHandle, ScenarioRecord, TestAgentControllerInternals } from "./controller.ts"; - import { createDeterministicSessionCoordinator } from "./session-coordinator.ts"; import type { AcpxProviderDependencies } from "@executablemd/acp"; import { normalizeModels, INSPECTION_PROPS, MODELS_PROPS } from "./configuration.ts"; @@ -312,7 +311,6 @@ export function* provisionPartition(options: { // owning two sessions and never exclude each other — and so a route // one published is not an account the next has to live with. coordinator: createDeterministicSessionCoordinator(), - routeStore, ...(planConfiguration === undefined ? {} : { planConfiguration }), }); diff --git a/packages/test-agent/src/provider.ts b/packages/test-agent/src/provider.ts index 87e0f2779..839cd7f21 100644 --- a/packages/test-agent/src/provider.ts +++ b/packages/test-agent/src/provider.ts @@ -75,7 +75,6 @@ export interface TestAgentProviderOptions { coordinator?: AgentSessionCoordinator; /** How this partition's sessions were constructed. Its own, like the rest. */ routeStore?: AgentSessionRouteStore; - dependencies?: AcpxProviderDependencies; inspection?: { agent: string; @@ -297,7 +296,6 @@ export function* useTestAgentProvider( }), ...(options.coordinator ? { coordinator: options.coordinator } : {}), ...(options.routeStore ? { routeStore: options.routeStore } : {}), - ...(options.dependencies?.createRuntime ? { createRuntime: options.dependencies.createRuntime } : {}), diff --git a/specs/acp-client-spec.md b/specs/acp-client-spec.md index 27fdf7cb9..288fd0013 100644 --- a/specs/acp-client-spec.md +++ b/specs/acp-client-spec.md @@ -1034,7 +1034,8 @@ while the conversation it continues is the same native history, so the current adapter is attempted on that history. What the provider actually applies is verified where it applies it (§Session configuration), and a genuine resume, assertion or configuration failure still fails the turn without a replacement -conversation or a new prompt. A version change is reported, never a failure. A reopening on its own performs no +conversation or a new prompt. A changed executable is neither reported nor a +failure. A reopening on its own performs no activation and no provider work at all; the configuration record is re-offered in its own position so the turns written after it replay in order, and it is never rewritten. The record is configuration, not identity: an absent Prompt diff --git a/specs/native-agent-session-launch-spec.md b/specs/native-agent-session-launch-spec.md index 99362c801..a78b56624 100644 --- a/specs/native-agent-session-launch-spec.md +++ b/specs/native-agent-session-launch-spec.md @@ -491,8 +491,8 @@ compares equal to one from this one. Normal work reads no version at all. Every later native launch, attachment or incomplete launch replay selects the current executable and positively confirms the retained native identity before -a native process, a configuration or a turn; a version that differs from the -session's history is reported and never refuses. This is the native launch and +a native process, a configuration or a turn, quietly: nothing about the +executable's version is compared or reported. This is the native launch and attachment contract, and it is the same policy ordinary and held ACP continuation follow; see [ACP client](acp-client-spec.md#acpx-provider). Complete means through to history: the gate closes @@ -554,8 +554,8 @@ that turn is accepted: 11. XMD commits the prepared launch record before releasing ownership. For an already-existing session it carries the asserted identity and **no** materialization plan, and no turn is spent. For a fresh one it carries an - **empty** `nativeSessionId`, its executable binding, and the exact - materialization plan this launch owes. + **empty** `nativeSessionId` and the exact materialization plan this launch + owes, and no executable binding. Once `prepared` is durable — and only then — the fixed materialization turn is announced on the reserved terminal and executed. It is retained as an @@ -578,13 +578,12 @@ owner to release — what has to be settled first is which conversation this is: ACP attachment — refuses with `unsupported-capability` before allocation or handoff; exit status is never substituted for confirmation. The current executable is selected before an identity is made, so one that cannot run - ends the launch before anything durable is written. Its version is a - diagnostic, reported once against the route's history, and a legacy unbound - route continues the same way and gains no binding. Whether an identity is - needed at all is decided next. An existing compatible - `client-native` route already names this conversation, so its retained - identity is adopted and **nothing is allocated** — a second candidate for a - conversation that already exists is a value with nowhere to go. That + ends the launch before anything durable is written. Nothing about its version + is read or reported, and a legacy unbound route continues the same way and + gains no binding. Whether an identity is needed at all is decided next. An + existing compatible `client-native` route already names this conversation, + so its retained identity is adopted and **nothing is allocated** — a second + candidate for a conversation that already exists is a value with nowhere to go. That established conversation is positively confirmed now: its exact native identity is loaded over ACP — strictly, with `expectedAgentSessionId`, when an ACP record exists; with no record, by exact `resumeSessionId` and a @@ -669,9 +668,8 @@ this sequence, and every step happens while the coordinator holds the session: what makes a nested client-native launch refuse afterwards. 4. An agent this host has not advertised for attachment refuses with `unsupported-capability`. A legacy unbound route attaches like a bound one. -5. Select the current executable and observe it for its diagnostic. A version - that differs from the route's history is reported once; one that cannot run - is an availability failure. +5. Select the current executable. One that cannot run is an availability + failure; nothing about its version is read or reported. 6. Inspect any retained ACP arrangement without creating one: absence may enter exact resume, because exact resume is the operation being attempted; a record must assert this route's identity and nothing else. @@ -789,7 +787,7 @@ A conversation a trusted host holds open is the one qualification. Its key and its construction route keep the provider and resolved command of the history's initial configuration record, with the session key its Prompt records name, for as long as the conversation lasts; the command that executes it, and the -build observed for it, are today's (acp-client-spec.md §Sessions: ownership, +executable selected for it, are today's (acp-client-spec.md §Sessions: ownership, routes and attachment). One logical conversation therefore keeps one owner when its adapter command changes, an earlier owner of the original tuple still refuses a changed-command contender, and a tombstone on that tuple still @@ -963,7 +961,9 @@ type AgentSessionRouteV1 = }; ``` -V2 exists only for `client-native`, and adds the one fact V1 never had: +V2 exists only for `client-native`, and adds the one fact V1 never had. Earlier +releases published it; fresh construction no longer does, and a V2 record is +read exactly and never rewritten: ```ts interface AgentSessionRouteV2 { @@ -980,7 +980,8 @@ interface AgentSessionRouteV2 { } ``` -ACP-first construction bound to a build is V3, and only V3: +ACP-first construction an earlier release bound to a build is V3, and only V3; +fresh construction publishes the unbound V1 form instead: ```ts interface AgentSessionRouteV3 { @@ -995,16 +996,15 @@ interface AgentSessionRouteV3 { It carries the binding and nothing more. The other members of V2 describe an identity XMD chose and a layer it wrote a file for, and neither is a fact about -a session the provider named — so an ACP-first route says how the session was -constructed and which build constructed it, exactly as it always did, with the -one fact that was missing. +a session the provider named — so a V3 route says how the session was constructed +and which build an earlier release recorded constructing it. Each bound schema admits only its own construction: a V2 record is `client-native` and a V3 record is `acp-first`, and the two pairings do not -cross. New client-native construction publishes V2 and observes the build before -it allocates an identity; new bound ACP-first construction publishes V3 and -observes the build before it creates a session. Serialization preserves the -schema it was given, so nothing here upgrades a route. +cross. New construction of either kind publishes the unbound V1 form and observes +nothing; V2 and V3 records come only from earlier releases. Serialization +preserves the schema it was given, so nothing here upgrades or downgrades a +route. Every member of all three schemas is exact. A path, adapter command, environment, argv, instruction text, credential, transcript, process fact or temporary path @@ -1129,12 +1129,12 @@ continuation, because `detached` is retained before the exit phase is invoked: For a session the provider named, the same rule reads against two more durable operations, and the order they are written in is what a replay reads. -A **fresh** launch observes the live build and publishes the bound V3 ACP-first -route *before* the provider constructs anything, so the route a later run is -held to exists before there is a session to hold it to. ACPX then creates +A **fresh** launch selects the current executable and publishes the unbound V1 +ACP-first route *before* the provider constructs anything, so the route a later +run is held to exists before there is a session to hold it to. ACPX then creates provisional occupancy and asserts no native identity at all: `prepared` retains -an **empty** `nativeSessionId`, the executable binding, and the exact -materialization plan this launch owes. A preparation is not a report of the +an **empty** `nativeSessionId` and the exact materialization plan this launch +owes, and no executable binding. A preparation is not a report of the conversation's name. The coordinator retains `prepared` *before* the turn starts. It then executes the turn and @@ -1304,8 +1304,9 @@ the session it named rather than meeting one. A selected executable that is missing, is not a file or cannot be run fails with `executable-binding-refused`, the availability class. An executable's version -never causes this refusal, or any notice. It carries an executable path, raw version output, host -error, argv, environment, credential, instruction text or provider payload. +never causes this refusal, or any notice. The refusal carries no executable +path, raw version output, host error, argv, environment, credential, +instruction text or provider payload. An attachment that reaches the provider and cannot open the conversation the route names fails with `identity-unavailable`: missing provider history, an @@ -1634,8 +1635,9 @@ Implementation review checks these frozen invariants: the current environment selects and requires the provider's positive assertion of the exact retained native identity before a configuration, a turn or a native handoff — or, for a fresh client-allocated creation, after - the child joins and before success. A version or digest difference is - reported and never admits or refuses; exit status never confirms identity. + the child joins and before success. Nothing about the executable's version + or digest is compared, reported, admitted or refused; exit status never + confirms identity. 19. The canonical executable path is live only: it enters no route, journal, retained provider state, public result, diagnostic or global environment, and no partition that outlives its last handle. From d7f65f3938a53b9ac7796ba56eed91b1dd884f1f Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 07:28:56 -0500 Subject: [PATCH 5/7] Make Claude attachment build evidence optional --- .../fixtures/claude-native-to-acp-proof.ts | 62 +++++++------------ 1 file changed, 24 insertions(+), 38 deletions(-) diff --git a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts index 720063121..94c6a1b76 100644 --- a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts @@ -1593,21 +1593,13 @@ function bindingDigestPresent(value: unknown): boolean { return isRecord(digest) && typeof digest.value === "string" && digest.value.length === 64; } -function* claudeVersion(journey: Journey): Operation { - const reported = yield* bounded("claude-version", VERSION_MS, () => - runChild("claude", ["--version"], { cwd: journey.root, live: journey.live }), - ); - return reported.code === 0 ? reported.stdout.trim() : ""; -} - /** Everything both journeys establish before they are allowed to launch. */ -function* ready(journey: Journey, verdict: JourneyVerdict): Operation { +function ready(journey: Journey, verdict: JourneyVerdict): boolean { if (journey.realClaude.length === 0) { verdict.verdict = "ENVIRONMENT_BLOCKED"; verdict.detail = "no installed claude executable was found on PATH"; return false; } - verdict.claudeVersion = yield* claudeVersion(journey); if (!verdict.projectCopyVerified) { verdict.verdict = "HARNESS_FAILED"; verdict.detail = "the project copy is not byte-identical to the checked-in role document"; @@ -1625,7 +1617,7 @@ function* runAttachment( verdict: JourneyVerdict, marker: string, ): Operation { - if (!(yield* ready(journey, verdict))) { + if (!ready(journey, verdict)) { return; } verdict.adapterCommand = boundAdapterCommand(); @@ -1681,13 +1673,8 @@ function* runAttachment( verdict.markerRecovered = squeeze(acp.stdout).includes(`${RECOVER_PREFIX}${marker}`); verdict.outcome = verdict.markerRecovered ? "same-conversation" : "unresolved"; - // Observed after the whole journey, as evidence of which build ran. Nothing - // is compared with it. - const reobserved = yield* observeBuild(journey); - verdict.observed.version = reobserved.version; - verdict.observed.digestPresent = reobserved.digest.length === 64; - yield* runAbsentIdentity(journey, verdict); + yield* observeBuild(verdict); } /** The exact ACP adapter command a bound Claude attachment is proven against. */ @@ -1699,20 +1686,22 @@ function boundAdapterCommand(): string { return adapter.binding.adapterCommand ?? ""; } -/** What this run's own observer says the installed Claude build is. */ -function* observeBuild(journey: Journey): Operation<{ version: string; digest: string }> { - const observer = createDenoExecutableObserver(); - if (!observer) { - return { version: "", digest: "" }; +/** Record only the build evidence available after both cases finish. */ +function* observeBuild(verdict: JourneyVerdict): Operation { + try { + const observer = createDenoExecutableObserver(); + if (observer) { + const found = yield* observer.observe("claude"); + const adapter = nativeAdapterFor("claude"); + if (adapter && allocatesIdentity(adapter)) { + verdict.observed.version = adapter.binding.version(found.versionOutput) ?? ""; + verdict.claudeVersion = verdict.observed.version; + } + verdict.observed.digestPresent = found.digest.value.length === 64; + } + } catch { + // An unavailable observation leaves the evidence fields at their defaults. } - const found = yield* observer.observe("claude"); - const adapter = nativeAdapterFor("claude"); - const version = - adapter && allocatesIdentity(adapter) - ? adapter.binding.version(found.versionOutput) - : undefined; - void journey; - return { version: version ?? "", digest: found.digest.value }; } /** @@ -1732,11 +1721,8 @@ function* runAbsentIdentity(journey: Journey, verdict: JourneyVerdict): Operatio const sessionKey = deriveSessionKey(agentCommand, journey.absentProject, "implementer"); journey.absentKey = sessionKey; const store = createDenoSessionRouteStore(SESSION_COORDINATOR_ROOT); - const observed = yield* observeBuild(journey); - if (!store || observed.version.length === 0 || observed.digest.length !== 64) { - verdict.verdict = "HARNESS_FAILED"; - verdict.detail = "the absent-identity case could not name a build to bind to"; - return; + if (!store) { + throw new Error("the absent-identity case requires the session route store"); } yield* store.publish({ schema: "session-route.v2", @@ -1750,8 +1736,8 @@ function* runAbsentIdentity(journey: Journey, verdict: JourneyVerdict): Operatio launcher: "claude", executableBinding: { schema: "executable-build.v1", - reportedVersion: observed.version, - executableDigest: { algorithm: "sha256", value: observed.digest }, + reportedVersion: "2.1.241 (Claude Code)", + executableDigest: { algorithm: "sha256", value: "c".repeat(64) }, }, }); @@ -1851,8 +1837,8 @@ function decideAttachment(verdict: JourneyVerdict): void { } verdict.verdict = "PASS"; verdict.detail = - "a marker-free ACP prompt recovered the native turn's history under the same identity " + - "and the same build, and an absent identity refused without a turn"; + "a marker-free ACP prompt recovered the native turn's history under the same identity, " + + "and the provider refused an absent identity before a turn"; } /** From 5e45ba5d337de755548af0dffcce436fe049be9d Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 08:36:01 -0500 Subject: [PATCH 6/7] Reopen retained ACP sessions when executable selection changes --- packages/acp/src/ClaudeNativeLaunch.test.md | 1 + packages/acp/src/ClaudeNativeToAcp.test.md | 23 +- packages/acp/src/ClaudeZeroTurnExit.test.md | 7 +- packages/acp/src/CodexNativeLaunch.test.md | 2 +- .../acp/src/CodexZeroNativeTurnExit.test.md | 2 +- packages/acp/src/provider.ts | 19 +- .../fixtures/claude-native-launch-proof.ts | 196 ++++-------- .../fixtures/claude-native-to-acp-proof.ts | 138 ++++---- .../tests/fixtures/claude-proof-evidence.ts | 98 ++++++ .../fixtures/codex-native-launch-proof.ts | 224 +++++-------- .../acp/tests/fixtures/native-proof-child.ts | 76 +++++ packages/acp/tests/native-proof.test.ts | 294 ++++++++++++++++++ packages/acp/tests/provider.test.ts | 157 +++++++++- .../cli/tests/workflow-agent-sessions.test.ts | 170 +++++++++- specs/native-agent-session-launch-spec.md | 11 +- 15 files changed, 1040 insertions(+), 378 deletions(-) create mode 100644 packages/acp/tests/fixtures/claude-proof-evidence.ts create mode 100644 packages/acp/tests/fixtures/native-proof-child.ts create mode 100644 packages/acp/tests/native-proof.test.ts diff --git a/packages/acp/src/ClaudeNativeLaunch.test.md b/packages/acp/src/ClaudeNativeLaunch.test.md index 3b525206b..bb2deb84c 100644 --- a/packages/acp/src/ClaudeNativeLaunch.test.md +++ b/packages/acp/src/ClaudeNativeLaunch.test.md @@ -278,6 +278,7 @@ on screen. ## The two commands are the documented ones +Only native UI invocations count here. Availability and ACP subprocesses may also run. Creation names the session and hands over a private instruction file. Resuming hands over nothing — a `--session-id` there would be a second conversation, not a continuation. diff --git a/packages/acp/src/ClaudeNativeToAcp.test.md b/packages/acp/src/ClaudeNativeToAcp.test.md index e342057a3..62913da16 100644 --- a/packages/acp/src/ClaudeNativeToAcp.test.md +++ b/packages/acp/src/ClaudeNativeToAcp.test.md @@ -82,7 +82,7 @@ would fail this document. "preparedTextInArgv", "preparedTextInEnvironment", "modelTurns", "conversationInputByteCount", "consentInputBytes", "consentSurfaces", "exitControlBytes", - "adapterCommand", "inheritedAgentMarkersRemoved", + "adapterIdentity", "inheritedAgentMarkersRemoved", "markerStored", "markerRecovered", "markerInReportedEvidence", "answerSurface", "outcome", "route", "journal", "arrangement", "observed", "absent", @@ -125,7 +125,7 @@ would fail this document. "consentInputBytes": { "type": "string" }, "consentSurfaces": { "type": "array", "items": { "type": "string" } }, "exitControlBytes": { "type": "string" }, - "adapterCommand": { "type": "string" }, + "adapterIdentity": { "type": "string" }, "inheritedAgentMarkersRemoved": { "type": "integer" }, "markerStored": { "type": "boolean" }, "markerRecovered": { "type": "boolean" }, @@ -324,21 +324,22 @@ a condition of passing. ## The adapter the attachment was proven against -ACPX resolves adapters through a semver range of its own. A capability that -depends on how an adapter handles resume identity cannot be left to that range, -so this binding names one — and the name is live, reaching no durable record. +The binary's carried adapter supplies both the command used to address the route +and this path-free snapshot identity. The native UI count covers create and +resume invocations. Availability probes and ACP subprocesses have separate argv. ## An identity nobody ever had is refused before a turn -The independent case. A route in the historical bound V2 form an earlier release -published, naming a fresh random conversation, in a directory of its own, with -no provider arrangement beside it: the prompt reads that released record, and -refuses rather than starting an empty conversation and answering from it. +The fixture publishes a historical bound V2 route for a fresh random conversation +in its own directory. It reads the record back under the command and key the +binary will use before attempting the prompt. The provider must refuse that +exact missing conversation. ACPX saves each user submission to this key before +sending a model request, so the independent arrangement counts attempted turns. diff --git a/packages/acp/src/ClaudeZeroTurnExit.test.md b/packages/acp/src/ClaudeZeroTurnExit.test.md index 13414cff8..9685fe5f6 100644 --- a/packages/acp/src/ClaudeZeroTurnExit.test.md +++ b/packages/acp/src/ClaudeZeroTurnExit.test.md @@ -257,7 +257,7 @@ section and no other role's. - + ## Every key sent was terminal control @@ -273,14 +273,13 @@ Ctrl-D bytes: one to ask the prompt whether it is there, one to leave. Creation names the session and hands over a private instruction file. Re-entry resumes that same name and hands over nothing — a `--session-id` there would be -a second conversation, not a continuation. When the identity was refused, no -re-entry command ran at all. +a second conversation, not a continuation. XMD can refuse during preflight before launching the second UI. A refusal from the UI itself still requires the exact resume command. "]} /> - + diff --git a/packages/acp/src/CodexNativeLaunch.test.md b/packages/acp/src/CodexNativeLaunch.test.md index 8a55cc40e..c21f38485 100644 --- a/packages/acp/src/CodexNativeLaunch.test.md +++ b/packages/acp/src/CodexNativeLaunch.test.md @@ -291,7 +291,7 @@ as evidence of what this run exercised; none is compared with an earlier run. diff --git a/packages/acp/src/CodexZeroNativeTurnExit.test.md b/packages/acp/src/CodexZeroNativeTurnExit.test.md index 5cb32dda5..fad25d6ee 100644 --- a/packages/acp/src/CodexZeroNativeTurnExit.test.md +++ b/packages/acp/src/CodexZeroNativeTurnExit.test.md @@ -266,7 +266,7 @@ as evidence of what this run exercised; none is compared with an earlier run. diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index b8fdeb082..e81f814eb 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -1941,6 +1941,19 @@ function* useAcpxProviderState( prepared: Prepared, intent: EnsureIntent, ): Operation { + if ( + prepared.kind === "existing" && + intent.build !== undefined && + prepared.entry.runtime.partition !== partitionOf(intent.build) + ) { + // Keep the session slot until the old transport has finished closing, even on halt. + const { sessionKey } = prepared; + yield* scoped(() => ensure(() => releaseHandle(sessionKey))); + if (holding(prepared.sessionKey)) { + throw new Error(`could not release session "${prepared.sessionKey}" to change executables`); + } + prepared = yield* requeried(prepared); + } if (newSessionOptions?.disallowedTools !== undefined) { const launchOptionsRecord = yield* until(store.load(prepared.sessionKey)); if (launchOptionsRecord !== undefined) { @@ -1986,7 +1999,11 @@ function* useAcpxProviderState( // here rather than loading something it could not tell apart. let expectedAgentSessionId = reopening?.agentSessionId; if ( - reopening !== undefined && + (reopening !== undefined || + (attachment === undefined && + intent.state === "existing" && + intent.build !== undefined && + held?.session.agentSessionId !== undefined)) && expectedAgentSessionId === undefined && owesIdentity(agentName) ) { diff --git a/packages/acp/tests/fixtures/claude-native-launch-proof.ts b/packages/acp/tests/fixtures/claude-native-launch-proof.ts index 79fbc9a11..8b9a72d0c 100644 --- a/packages/acp/tests/fixtures/claude-native-launch-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-launch-proof.ts @@ -34,6 +34,8 @@ * and private paths never leave this file. */ +import { runChild } from "./native-proof-child.ts"; +import type { ChildOutcome, LiveSet } from "./native-proof-child.ts"; import { ensure, main, race, scoped, sleep, spawn, until, withResolvers } from "effection"; import type { Operation } from "effection"; import { exists, rm } from "@effectionx/fs"; @@ -45,9 +47,13 @@ import { homedir, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import process from "node:process"; -import { createAgentRegistry, resolveAgentCommand } from "../../src/acpx-runtime.ts"; -import { agentSessionKeyDigest } from "@executablemd/runtime"; -import { ADVERTISED_NATIVE_LAUNCH } from "../../src/native-launch.ts"; +import { createEmbeddedAdapters } from "../../src/adapter-snapshots.ts"; +import { claudeKeyPaths, nativeUiInvocations } from "./claude-proof-evidence.ts"; +import { + ADVERTISED_NATIVE_LAUNCH, + allocatesIdentity, + nativeAdapterFor, +} from "../../src/native-launch.ts"; /** Opting in at all. Absent, every mode refuses before a provider child. */ const PROOF_ENV = "XMD_CLAUDE_NATIVE_PROOF"; @@ -317,91 +323,6 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -interface ChildOutcome { - code: number | null; - signal: string | null; - stdout: string; - stderr: string; -} - -/** Every child a mode started, so cleanup can prove none outlived it. */ -type LiveSet = Set; - -/** Run one captured child to settlement. Never the production command. */ -function runChild( - command: string, - args: string[], - options: { cwd: string; input?: string; live: LiveSet }, -): Operation { - return (function* (): Operation { - const settled = withResolvers(); - const failed = withResolvers(); - let child: ChildProcess | undefined; - - // Registered before the spawn: a halt between acquiring a process and - // registering its cleanup leaks the process. - yield* ensure(() => { - const running = child; - if (!running?.pid) { - return; - } - if (running.exitCode === null && running.signalCode === null) { - killed(running.pid); - } - options.live.delete(running.pid); - }); - - const started = spawnChild(command, args, { - cwd: options.cwd, - stdio: ["pipe", "pipe", "pipe"], - }); - child = started; - if (started.pid) { - options.live.add(started.pid); - } - let stdout = ""; - let stderr = ""; - - const onStdout = (chunk: Buffer): void => { - stdout += chunk.toString(); - }; - const onStderr = (chunk: Buffer): void => { - stderr += chunk.toString(); - }; - const onError = (error: Error): void => failed.reject(error); - const onClose = (code: number | null, signal: string | null): void => { - if (started.pid) { - options.live.delete(started.pid); - } - settled.resolve({ code, signal, stdout, stderr }); - }; - - // Registered after the cleanup above and so torn down before it: the child - // stops being observed before it is signalled, and a race this arm loses - // leaves nothing attached to a process somebody else is still reading. - // Established before the subscriptions, because `yield* ensure(...)` is - // itself a suspension an owner can be halted at. - yield* ensure(() => { - started.stdout?.off("data", onStdout); - started.stderr?.off("data", onStderr); - started.off("error", onError); - started.off("close", onClose); - }); - - started.stdout?.on("data", onStdout); - started.stderr?.on("data", onStderr); - started.on("error", onError); - started.on("close", onClose); - - if (options.input !== undefined) { - started.stdin?.write(options.input); - } - started.stdin?.end(); - - return yield* race([settled.operation, failed.operation]); - })(); -} - /** * One production command running under a pseudo-terminal. * @@ -836,7 +757,7 @@ interface JourneyVerdict { privateStateInspected: boolean; } -function blankJourney(mode: Mode): JourneyVerdict { +export function blankJourney(mode: Mode): JourneyVerdict { return { mode, verdict: "HARNESS_FAILED", @@ -917,15 +838,7 @@ const REPO_ROOT = fileURLToPath(new URL("../../../..", import.meta.url)); const XMD_BINARY = join(REPO_ROOT, "dist", "xmd"); const SESSION_COORDINATOR_ROOT = join(homedir(), ".acpx", "xmd-native-sessions", "v1"); -/** The exact absolute paths one natural key owns, and nothing else. */ -function keyPaths(agentCommand: string, sessionKey: string): string[] { - const digest = agentSessionKeyDigest({ provider: "acpx", agent: agentCommand, sessionKey }); - return [ - join(SESSION_COORDINATOR_ROOT, "routes", `${digest}.json`), - join(SESSION_COORDINATOR_ROOT, "ownership", `${digest}.json`), - join(SESSION_COORDINATOR_ROOT, "leases", `${digest}.lease`), - ]; -} +const adapters = createEmbeddedAdapters(join(homedir(), ".xmd", "adapters")); /** * A path this fixture may write into a generated shell script. @@ -969,7 +882,7 @@ interface Invocation { argv: string[]; } -function parseObservations(text: string): Invocation[] { +export function parseObservations(text: string): Invocation[] { const invocations: Invocation[] = []; let current: Invocation | undefined; for (const line of text.split("\n")) { @@ -998,7 +911,7 @@ function valueOf(invocation: Invocation, flag: string): string | undefined { } /** The command shape a verdict may carry: the private path is never in it. */ -function filtered(invocation: Invocation): string[] { +export function filtered(invocation: Invocation): string[] { const argv = ["claude", ...invocation.argv]; const index = argv.indexOf("--system-prompt-file"); if (index >= 0 && index + 1 < argv.length) { @@ -1249,7 +1162,7 @@ function* invoke( index: 0 | 1, plan: TurnPlan, ): Operation { - const before = (yield* observedInvocations(journey)).length; + const before = nativeUiInvocations(yield* observedInvocations(journey)).length; const first = index === 0; const channels: PtyChannels = { charged(bytes) { @@ -1301,7 +1214,7 @@ function* invoke( }, ); - outcome.children = (yield* observedInvocations(journey)).length - before; + outcome.children = nativeUiInvocations(yield* observedInvocations(journey)).length - before; return outcome; } @@ -1398,8 +1311,9 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation typeof entry === "string"); const observed = yield* observedInvocations(journey); - const opening = observed[0]; - const reentry = observed[1]; + const native = nativeUiInvocations(observed); + const opening = native[0]; + const reentry = native[1]; if (opening) { verdict.firstCommand = filtered(opening); } @@ -1407,7 +1321,7 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation valueOf(invocation, "--session-id")) .filter((value): value is string => typeof value === "string"), ); @@ -1437,7 +1351,7 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation 0) { - const paths = keyPaths(resolveAgentCommand(createAgentRegistry(), "claude"), sessionKey); + const paths = claudeKeyPaths(SESSION_COORDINATOR_ROOT, adapters.command("claude"), sessionKey); const [route] = paths; if (route !== undefined && (yield* exists(route))) { const parsed: unknown = JSON.parse(yield* until(readFile(route, "utf8"))); @@ -1484,15 +1398,26 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation { - const reported = yield* bounded("claude-version", VERSION_MS, () => - runChild("claude", ["--version"], { cwd: journey.root, live: journey.live }), - ); - return reported.code === 0 ? reported.stdout.trim() : ""; +function* claudeVersion(cwd: string, live: LiveSet, child: typeof runChild): Operation { + try { + const reported = yield* bounded("claude-version", VERSION_MS, () => + child("claude", ["--version"], { cwd, live }), + ); + const adapter = nativeAdapterFor("claude"); + return reported.code === 0 && adapter && allocatesIdentity(adapter) + ? (adapter.binding.version(reported.stdout) ?? "") + : ""; + } catch { + return ""; + } } /** Everything both journeys establish before they are allowed to launch. */ -function* ready(journey: Journey, verdict: JourneyVerdict): Operation { +export function* ready( + journey: Pick, + verdict: JourneyVerdict, + child = runChild, +): Operation { if (journey.realClaude.length === 0) { verdict.verdict = "ENVIRONMENT_BLOCKED"; verdict.detail = "no installed claude executable was found on PATH"; @@ -1500,7 +1425,7 @@ function* ready(journey: Journey, verdict: JourneyVerdict): Operation { } // Recorded as evidence of what ran. A release absent from earlier evidence is // what an opt-in regression exists to exercise, so it never blocks the run. - verdict.claudeVersion = yield* claudeVersion(journey); + verdict.claudeVersion = yield* claudeVersion(journey.root, journey.live, child); if (!verdict.projectCopyVerified) { verdict.verdict = "HARNESS_FAILED"; verdict.detail = "the project copy is not byte-identical to the checked-in role document"; @@ -1592,7 +1517,7 @@ function* runTwoTurn(journey: Journey, verdict: JourneyVerdict, marker: string): const ZERO_TURN_ACCEPTED: readonly string[] = ["same-identity", "no-session"]; -function decideZeroTurn(verdict: JourneyVerdict): void { +export function decideZeroTurn(verdict: JourneyVerdict): void { // XMD confirms a client-native identity over ACP after creating it and again // before resuming it. A session Claude kept nothing of is therefore refused // by XMD itself, before any re-entry child, with the stable class in the @@ -1621,7 +1546,7 @@ function decideZeroTurn(verdict: JourneyVerdict): void { : "the exact retained identity was refused, and XMD failed closed"; } -function decideTwoTurn(verdict: JourneyVerdict): void { +export function decideTwoTurn(verdict: JourneyVerdict): void { if (!verdict.openingSentenceExact) { verdict.verdict = "PRODUCT_FAILED"; verdict.detail = "the prepared layer did not govern the first native turn"; @@ -1743,11 +1668,15 @@ function recognized(outcome: ChildOutcome, option: string): boolean { return !`${outcome.stdout}${outcome.stderr}`.includes(`unknown option '${option}'`); } -function* runPreflight(): Operation { +export function* runPreflight( + child = runChild, + authorized = process.env[PROOF_ENV] === "1", + binary = XMD_BINARY, +): Operation { const verdict: PreflightVerdict = { mode: "preflight", verdict: "HARNESS_FAILED", - authorized: process.env[PROOF_ENV] === "1", + authorized, refusal: "", detail: "preflight did not reach a verdict", head: "", @@ -1778,22 +1707,19 @@ function* runPreflight(): Operation { const live: LiveSet = new Set(); const cwd = REPO_ROOT; - verdict.head = (yield* runChild("git", ["rev-parse", "HEAD"], { cwd, live })).stdout.trim(); - verdict.branch = (yield* runChild("git", ["branch", "--show-current"], { + verdict.head = (yield* child("git", ["rev-parse", "HEAD"], { cwd, live })).stdout.trim(); + verdict.branch = (yield* child("git", ["branch", "--show-current"], { cwd, live, })).stdout.trim(); - const version = yield* bounded("claude-version", VERSION_MS, () => - runChild("claude", ["--version"], { cwd, live }), - ); - verdict.claudeVersion = version.code === 0 ? version.stdout.trim() : ""; + verdict.claudeVersion = yield* claudeVersion(cwd, live, child); // Every invocation below is given empty stdin and fails on an argument rather // than reaching a model. const missing = join(tmpdir(), `xmd-520-absent-${randomUUID()}`); const options = yield* bounded("claude-options", VERSION_MS, () => - runChild("claude", ["--session-id", randomUUID(), "--system-prompt-file", missing, "--print"], { + child("claude", ["--session-id", randomUUID(), "--system-prompt-file", missing, "--print"], { cwd, live, input: "", @@ -1804,18 +1730,18 @@ function* runPreflight(): Operation { recognized(options, "--system-prompt-file") && `${options.stdout}${options.stderr}`.includes("System prompt file not found"); const resume = yield* bounded("claude-resume", VERSION_MS, () => - runChild("claude", ["--resume", randomUUID(), "--print"], { cwd, live, input: "" }), + child("claude", ["--resume", randomUUID(), "--print"], { cwd, live, input: "" }), ); verdict.resumeFlag = recognized(resume, "--resume"); const purge = yield* bounded("claude-purge-help", VERSION_MS, () => - runChild("claude", ["project", "purge", "--help"], { cwd, live }), + child("claude", ["project", "purge", "--help"], { cwd, live }), ); verdict.projectPurgeSurface = purge.code === 0 && purge.stdout.includes("--dry-run"); // Whether an account is usable, and nothing about whose it is. const auth = yield* bounded("claude-auth-status", VERSION_MS, () => - runChild("claude", ["auth", "status"], { cwd, live }), + child("claude", ["auth", "status"], { cwd, live }), ); if (auth.code === 0) { try { @@ -1827,16 +1753,15 @@ function* runPreflight(): Operation { } const pty = yield* bounded("pty-capability", VERSION_MS, () => - runChild("/usr/bin/script", ["-q", "/dev/null", "/bin/sh", "-c", "test -t 1 && echo PTY"], { + child("/usr/bin/script", ["-q", "/dev/null", "/bin/sh", "-c", "test -t 1 && echo PTY"], { cwd, live, }), ); verdict.ptyUsable = pty.stdout.includes("PTY"); - verdict.binaryBuilt = yield* exists(XMD_BINARY); + verdict.binaryBuilt = yield* exists(binary); const established = - verdict.claudeVersion.length > 0 && !verdict.claudeConfigDirSet && verdict.sessionIdFlag && verdict.systemPromptFileFlag && @@ -1845,8 +1770,7 @@ function* runPreflight(): Operation { verdict.credentialsUsable && verdict.ptyUsable && verdict.binaryBuilt && - verdict.advertised.length === 1 && - verdict.advertised[0] === "claude"; + verdict.advertised.includes("claude"); verdict.verdict = established ? "PASS" : "ENVIRONMENT_BLOCKED"; verdict.detail = established ? "the surfaces this journey needs are established, and no model turn was spent" @@ -1858,7 +1782,7 @@ function render(value: unknown): void { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); } -main(function* () { +function* runProof(): Operation { const mode = process.argv[2]; if (mode === "preflight") { @@ -1885,4 +1809,8 @@ main(function* () { } throw new Error(`claude-native-launch-proof: unknown mode "${mode ?? ""}"`); -}); +} + +if (import.meta.main) { + main(runProof); +} diff --git a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts index 94c6a1b76..9bab0284d 100644 --- a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts @@ -55,11 +55,17 @@ import { homedir, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import process from "node:process"; -import { createAgentRegistry, resolveAgentCommand } from "../../src/acpx-runtime.ts"; -import { agentSessionKeyDigest, createDenoExecutableObserver } from "@executablemd/runtime"; -import { allocatesIdentity, nativeAdapterFor } from "../../src/native-launch.ts"; import { createDenoSessionRouteStore } from "../../src/session-route.ts"; -import { deriveSessionKey } from "../../src/session-key.ts"; +import { createEmbeddedAdapters } from "../../src/adapter-snapshots.ts"; +import { claudeKeyPaths, nativeUiInvocations } from "./claude-proof-evidence.ts"; +import { createDenoExecutableObserver } from "@executablemd/runtime"; +import { allocatesIdentity, nativeAdapterFor } from "../../src/native-launch.ts"; +import { + claudeRouteKey, + prepareAbsentRoute, + readProofArrangement, + submittedModelTurns, +} from "./claude-proof-evidence.ts"; /** Opting in at all. Absent, this refuses before a provider child. */ const PROOF_ENV = "XMD_CLAUDE_ATTACHMENT_PROOF"; @@ -820,7 +826,7 @@ interface JourneyVerdict { consentSurfaces: string[]; exitControlBytes: string; /** The bound ACP adapter this attachment is proven against. */ - adapterCommand: string; + adapterIdentity: string; /** How many markers of an enclosing agent session were kept out. */ inheritedAgentMarkersRemoved: number; markerStored: boolean; @@ -880,7 +886,7 @@ interface JourneyVerdict { privateStateInspected: boolean; } -function blankJourney(mode: Mode): JourneyVerdict { +export function blankJourney(mode: Mode): JourneyVerdict { return { mode, verdict: "HARNESS_FAILED", @@ -918,7 +924,7 @@ function blankJourney(mode: Mode): JourneyVerdict { consentInputBytes: "", consentSurfaces: [], exitControlBytes: "", - adapterCommand: "", + adapterIdentity: "", inheritedAgentMarkersRemoved: 0, markerStored: false, markerRecovered: false, @@ -975,18 +981,10 @@ const REPO_ROOT = fileURLToPath(new URL("../../../..", import.meta.url)); const XMD_BINARY = join(REPO_ROOT, "dist", "xmd"); const SESSION_COORDINATOR_ROOT = join(homedir(), ".acpx", "xmd-native-sessions", "v1"); -/** The exact absolute paths one natural key owns, and nothing else. */ -function keyPaths(agentCommand: string, sessionKey: string): string[] { - const digest = agentSessionKeyDigest({ provider: "acpx", agent: agentCommand, sessionKey }); - return [ - join(SESSION_COORDINATOR_ROOT, "routes", `${digest}.json`), - join(SESSION_COORDINATOR_ROOT, "ownership", `${digest}.json`), - join(SESSION_COORDINATOR_ROOT, "leases", `${digest}.lease`), - ]; -} +const adapters = createEmbeddedAdapters(join(homedir(), ".xmd", "adapters")); /** Where the ACP client keeps its own arrangement for one session key. */ -const ACPX_SESSION_DIR = join(homedir(), ".acpx", "sessions"); +const ACP_STATE_DIR = join(homedir(), ".acpx"); /** * The one arrangement record this run's session key owns. @@ -997,7 +995,7 @@ const ACPX_SESSION_DIR = join(homedir(), ".acpx", "sessions"); * opened anywhere in this fixture. */ function arrangementPath(sessionKey: string): string { - return join(ACPX_SESSION_DIR, `${encodeURIComponent(sessionKey)}.json`); + return join(ACP_STATE_DIR, "sessions", `${encodeURIComponent(sessionKey)}.json`); } /** @@ -1042,7 +1040,7 @@ interface Invocation { argv: string[]; } -function parseObservations(text: string): Invocation[] { +export function parseObservations(text: string): Invocation[] { const invocations: Invocation[] = []; let current: Invocation | undefined; for (const line of text.split("\n")) { @@ -1071,7 +1069,7 @@ function valueOf(invocation: Invocation, flag: string): string | undefined { } /** The command shape a verdict may carry: the private path is never in it. */ -function filtered(invocation: Invocation): string[] { +export function filtered(invocation: Invocation): string[] { const argv = ["claude", ...invocation.argv]; const index = argv.indexOf("--system-prompt-file"); if (index >= 0 && index + 1 < argv.length) { @@ -1335,7 +1333,7 @@ function* invoke( verdict: JourneyVerdict, plan: TurnPlan, ): Operation { - const before = (yield* observedInvocations(journey)).length; + const before = nativeUiInvocations(yield* observedInvocations(journey)).length; const channels: PtyChannels = { charged(bytes) { verdict.conversationInputByteCount += bytes; @@ -1377,7 +1375,7 @@ function* invoke( }, ); - outcome.children = (yield* observedInvocations(journey)).length - before; + outcome.children = nativeUiInvocations(yield* observedInvocations(journey)).length - before; return outcome; } @@ -1474,19 +1472,20 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation typeof entry === "string"); const observed = yield* observedInvocations(journey); - const opening = observed[0]; + const ui = nativeUiInvocations(observed); + const opening = ui[0]; if (opening) { verdict.firstCommand = filtered(opening); } const allocated = new Set( - observed + ui .map((invocation) => valueOf(invocation, "--session-id")) .filter((value): value is string => typeof value === "string"), ); verdict.identityAllocations = allocated.size; // Nothing after the native launch may start a Claude of its own: an ACP turn // that spawned one would be a native UI, not an attachment. - verdict.substitutedIdentity = observed.length > 1; + verdict.substitutedIdentity = ui.length > 1; verdict.freshFallback = allocated.size > 1; // The prepared text, held here and nowhere else. It answers the two questions @@ -1506,11 +1505,11 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation 0) { - const paths = keyPaths(agentCommand, sessionKey); + const paths = claudeKeyPaths(SESSION_COORDINATOR_ROOT, agentCommand, sessionKey); const [route] = paths; if (route !== undefined && (yield* exists(route))) { const parsed: unknown = JSON.parse(yield* until(readFile(route, "utf8"))); @@ -1531,13 +1530,10 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation runChild(XMD_BINARY, xmdArguments(ACP_DOCUMENT, journey.journals[1]), { cwd: journey.project, @@ -1666,7 +1667,8 @@ function* runAttachment( ); verdict.modelTurns += 1; verdict.acpXmdExitCode = acp.code ?? -1; - verdict.acpInvocationChildren = (yield* observedInvocations(journey)).length - before; + verdict.acpInvocationChildren = + nativeUiInvocations(yield* observedInvocations(journey)).length - before; // The one thing that crosses out of the answer is whether the marker came // back behind a prefix that appears in no earlier turn. The answer itself // stays here. @@ -1677,15 +1679,6 @@ function* runAttachment( yield* observeBuild(verdict); } -/** The exact ACP adapter command a bound Claude attachment is proven against. */ -function boundAdapterCommand(): string { - const adapter = nativeAdapterFor("claude"); - if (!adapter || !allocatesIdentity(adapter)) { - return ""; - } - return adapter.binding.adapterCommand ?? ""; -} - /** Record only the build evidence available after both cases finish. */ function* observeBuild(verdict: JourneyVerdict): Operation { try { @@ -1717,32 +1710,18 @@ function* observeBuild(verdict: JourneyVerdict): Operation { * instead of refusing would answer the prompt and fail this. */ function* runAbsentIdentity(journey: Journey, verdict: JourneyVerdict): Operation { - const agentCommand = resolveAgentCommand(createAgentRegistry(), "claude"); - const sessionKey = deriveSessionKey(agentCommand, journey.absentProject, "implementer"); - journey.absentKey = sessionKey; + const key = claudeRouteKey(adapters, journey.absentProject); + const { sessionKey } = key; const store = createDenoSessionRouteStore(SESSION_COORDINATOR_ROOT); if (!store) { - throw new Error("the absent-identity case requires the session route store"); + throw new Error("the absent-identity proof requires the session route store"); } - yield* store.publish({ - schema: "session-route.v2", - route: "client-native", - provider: "acpx", - agent: agentCommand, - sessionKey, - nativeSessionId: randomUUID(), - identityProvenance: "client-allocated", - instructionsDigest: createHash("sha256").update(sessionKey).digest("hex"), - launcher: "claude", - executableBinding: { - schema: "executable-build.v1", - reportedVersion: "2.1.241 (Claude Code)", - executableDigest: { algorithm: "sha256", value: "c".repeat(64) }, - }, - }); - - const before = (yield* observedInvocations(journey)).length; - const turnsBefore = verdict.modelTurns; + if (yield* readProofArrangement(ACP_STATE_DIR, sessionKey)) { + throw new Error("the absent identity already has an ACP arrangement"); + } + journey.absentKey = sessionKey; + yield* prepareAbsentRoute(store, key, randomUUID()); + const before = nativeUiInvocations(yield* observedInvocations(journey)).length; const attempt = yield* bounded("absent-identity", ANSWER_MS, () => runChild(XMD_BINARY, xmdArguments(ACP_DOCUMENT, journey.journals[2]), { cwd: journey.absentProject, @@ -1752,8 +1731,9 @@ function* runAbsentIdentity(journey: Journey, verdict: JourneyVerdict): Operatio ); verdict.absent.ran = true; verdict.absent.xmdExitCode = attempt.code ?? -1; - verdict.absent.nativeChildren = (yield* observedInvocations(journey)).length - before; - verdict.absent.modelTurns = verdict.modelTurns - turnsBefore; + verdict.absent.nativeChildren = + nativeUiInvocations(yield* observedInvocations(journey)).length - before; + verdict.absent.modelTurns = yield* submittedModelTurns(ACP_STATE_DIR, sessionKey); // An answer at all would mean history was created for an identity nobody // ever had. The failure class is the product's own, filtered. verdict.absent.answered = squeeze(attempt.stdout).includes(RECOVER_PREFIX); @@ -1790,7 +1770,7 @@ function refusalClass(output: string): string { return ""; } -function decideAttachment(verdict: JourneyVerdict): void { +export function decideAttachment(verdict: JourneyVerdict): void { if (verdict.acpDocumentCarriesMarker) { verdict.verdict = "HARNESS_FAILED"; verdict.detail = "the ACP document carries the marker, so recovering it would prove nothing"; @@ -1910,7 +1890,7 @@ function render(value: unknown): void { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); } -main(function* () { +function* runProof(): Operation { // Planted only in the first native user turn and held here. It reaches no // instruction file, no argument vector, no environment, no session key, no // durable record, no document this run executes, and no rendered field. @@ -1928,4 +1908,8 @@ main(function* () { verdict.detail = "the verdict carried the history marker"; } render(verdict); -}); +} + +if (import.meta.main) { + main(runProof); +} diff --git a/packages/acp/tests/fixtures/claude-proof-evidence.ts b/packages/acp/tests/fixtures/claude-proof-evidence.ts new file mode 100644 index 000000000..b6f351d29 --- /dev/null +++ b/packages/acp/tests/fixtures/claude-proof-evidence.ts @@ -0,0 +1,98 @@ +import { exists } from "@effectionx/fs"; +import type { AgentSessionKey } from "@executablemd/runtime"; +import { agentSessionKeyDigest } from "@executablemd/runtime"; +import { until } from "effection"; +import type { Operation } from "effection"; +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import type { AcpSessionRecord } from "../../src/acpx-runtime.ts"; +import type { EmbeddedAdapters } from "../../src/adapter-snapshots.ts"; +import { deriveSessionKey } from "../../src/session-key.ts"; +import type { AgentSessionRouteStore, AgentSessionRouteV2 } from "../../src/session-route.ts"; +import { createAcpxSessionStore } from "../../src/session-store.ts"; + +export function nativeUiInvocations(invocations: T[]): T[] { + return invocations.filter( + ({ argv }) => + !argv.some((arg) => ["--print", "-p", "--input-format", "--output-format"].includes(arg)) && + ((argv[0] === "--session-id" && argv.includes("--system-prompt-file")) || + (argv[0] === "--resume" && !argv.includes("--session-id"))), + ); +} + +export function claudeKeyPaths(root: string, agent: string, sessionKey: string): string[] { + const digest = agentSessionKeyDigest({ provider: "acpx", agent, sessionKey }); + return [ + join(root, "routes", digest + ".json"), + join(root, "ownership", digest + ".json"), + join(root, "leases", digest + ".lease"), + ]; +} + +export function claudeRouteKey(adapters: EmbeddedAdapters, project: string): AgentSessionKey { + const agent = adapters.command("claude"); + return { provider: "acpx", agent, sessionKey: deriveSessionKey(agent, project, "implementer") }; +} + +export function* prepareAbsentRoute( + store: AgentSessionRouteStore, + key: AgentSessionKey, + nativeSessionId: string, +): Operation { + const { agent, sessionKey } = key; + const route: AgentSessionRouteV2 = { + schema: "session-route.v2", + route: "client-native", + provider: "acpx", + agent, + sessionKey, + nativeSessionId, + identityProvenance: "client-allocated", + instructionsDigest: createHash("sha256").update(sessionKey).digest("hex"), + launcher: "claude", + executableBinding: { + schema: "executable-build.v1", + reportedVersion: "2.1.241 (Claude Code)", + executableDigest: { algorithm: "sha256", value: "c".repeat(64) }, + }, + }; + yield* store.publish(route); + const read = yield* store.read({ provider: "acpx", agent, sessionKey }); + if ( + read?.schema !== "session-route.v2" || + read.nativeSessionId !== nativeSessionId || + read.instructionsDigest !== route.instructionsDigest || + read.launcher !== "claude" || + read.executableBinding.reportedVersion !== route.executableBinding.reportedVersion || + read.executableBinding.executableDigest.value !== route.executableBinding.executableDigest.value + ) { + throw new Error( + "the product-addressed route does not contain the absent identity's historical record", + ); + } + return read; +} + +export function* readProofArrangement( + root: string, + sessionKey: string, +): Operation { + const record = yield* until(createAcpxSessionStore(root).load(sessionKey)); + if ( + !record && + (yield* exists(join(root, "sessions", encodeURIComponent(sessionKey) + ".json"))) + ) { + throw new Error("the proof arrangement could not be read"); + } + return record; +} + +/** ACPX persists the User submission before connecting or writing session/prompt. */ +export function* submittedModelTurns(root: string, sessionKey: string): Operation { + const record = yield* readProofArrangement(root, sessionKey); + return ( + record?.messages.filter( + (message) => typeof message === "object" && message !== null && "User" in message, + ).length ?? 0 + ); +} diff --git a/packages/acp/tests/fixtures/codex-native-launch-proof.ts b/packages/acp/tests/fixtures/codex-native-launch-proof.ts index b6200338b..1b46cd472 100644 --- a/packages/acp/tests/fixtures/codex-native-launch-proof.ts +++ b/packages/acp/tests/fixtures/codex-native-launch-proof.ts @@ -44,6 +44,8 @@ * summarized on the way out. */ +import { runChild } from "./native-proof-child.ts"; +import type { LiveSet } from "./native-proof-child.ts"; import { ensure, main, race, scoped, sleep, until, withResolvers } from "effection"; import type { Operation } from "effection"; import { exists, rm } from "@effectionx/fs"; @@ -56,7 +58,7 @@ import { join } from "node:path"; import { fileURLToPath } from "node:url"; import process from "node:process"; import { createEmbeddedAdapters, embeddedAdapterIdentities } from "../../src/adapter-snapshots.ts"; -import { ADVERTISED_NATIVE_LAUNCH } from "../../src/native-launch.ts"; +import { ADVERTISED_NATIVE_LAUNCH, bindsBuild, nativeAdapterFor } from "../../src/native-launch.ts"; import { agentSessionKeyDigest } from "@executablemd/runtime"; import type { AnswerQuestion, ScreenSnapshot, TerminalReader } from "./terminal-screen.ts"; import { @@ -98,7 +100,7 @@ const ACP_DOCUMENT = fileURLToPath(new URL("./codex-native-to-acp-prompt.md", im */ const REQUIRED_ADAPTER_PACKAGE = "@agentclientprotocol/codex-acp"; const REQUIRED_ADAPTER_VERSION = "1.6.2"; -const REQUIRED_ADAPTER_DIGEST = "3ee22bc6b1649d02fcef80b352516f395fe774e63b459193195a41c42930dd8b"; +const REQUIRED_ADAPTER_DIGEST = "a3f699537970127972635b4596aef40ab8a4caa25a9028861d9ee07bf6c4b1a1"; /** The one prompt version a Codex launch may spend a turn on. */ const PROMPT_VERSION = "codex-materialization.v1"; @@ -337,88 +339,6 @@ function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -interface ChildOutcome { - code: number | null; - signal: string | null; - stdout: string; - stderr: string; -} - -/** Every child a mode started, so cleanup can prove none outlived it. */ -type LiveSet = Set; - -/** Run one captured child to settlement. Never a TUI. */ -function runChild( - command: string, - args: string[], - options: { cwd: string; input?: string; live: LiveSet; env?: Record }, -): Operation { - return (function* (): Operation { - const settled = withResolvers(); - const failed = withResolvers(); - let child: ChildProcess | undefined; - - // Registered before the spawn: a halt between acquiring a process and - // registering its cleanup leaks the process. - yield* ensure(() => { - const running = child; - if (!running?.pid) { - return; - } - if (running.exitCode === null && running.signalCode === null) { - killed(running.pid); - } - options.live.delete(running.pid); - }); - - child = spawnChild(command, args, { - cwd: options.cwd, - stdio: ["pipe", "pipe", "pipe"], - ...(options.env === undefined ? {} : { env: options.env }), - }); - if (child.pid) { - options.live.add(child.pid); - } - let stdout = ""; - let stderr = ""; - // Every registration is named and removed by this operation's own teardown: - // a cancelled wait leaves nothing attached to a child it no longer owns. - const onStdout = (chunk: Buffer): void => { - stdout += chunk.toString(); - }; - const onStderr = (chunk: Buffer): void => { - stderr += chunk.toString(); - }; - const onError = (error: Error): void => failed.reject(error); - const onClose = (code: number | null, signal: string | null): void => { - if (child?.pid) { - options.live.delete(child.pid); - } - settled.resolve({ code, signal, stdout, stderr }); - }; - const proc = child; - const outStream = proc.stdout; - const errStream = proc.stderr; - yield* ensure(() => { - outStream?.off("data", onStdout); - errStream?.off("data", onStderr); - proc.off("error", onError); - proc.off("close", onClose); - }); - outStream?.on("data", onStdout); - errStream?.on("data", onStderr); - proc.on("error", onError); - proc.on("close", onClose); - - if (options.input !== undefined) { - child.stdin?.write(options.input); - } - child.stdin?.end(); - - return yield* race([settled.operation, failed.operation]); - })(); -} - /** * A path this fixture may write into a generated shell command. * @@ -912,7 +832,7 @@ interface JourneyVerdict { privateStateInspected: boolean; } -function blankJourney(mode: Mode): JourneyVerdict { +export function blankJourney(mode: Mode): JourneyVerdict { return { mode, verdict: "UNDECIDED", @@ -1646,38 +1566,71 @@ const MATERIALIZATION_PROMPT = "task, inspect or modify files, call tools, or take any external action. Reply with a " + "brief acknowledgement only."; -/** Resolve the installed Codex, canonically, and hash exactly that file. */ -function* observeCodex(journey: Journey, verdict: JourneyVerdict): Operation { +function* executableDigest(path: string): Operation { + return createHash("sha256") + .update(yield* until(readFile(path))) + .digest("hex"); +} + +function* observeCodex( + cwd: string, + live: LiveSet, + verdict: Pick, + child: typeof runChild, + digest: typeof executableDigest, +): Operation { const located = yield* bounded("resolve-codex", VERSION_MS, () => - runChild("/usr/bin/which", ["codex"], { cwd: journey.root, live: journey.live }), + child("/usr/bin/which", ["codex"], { cwd, live }), ); - if (located.code !== 0 || located.stdout.trim().length === 0) { - return false; + if (located.code !== 0 || !located.stdout.trim()) { + return undefined; } - // Canonicalized for the same reason the product canonicalizes: a launcher - // symlink and the build behind it are one file. - journey.codex = yield* until(realpath(located.stdout.trim())); - verdict.codexDigest = createHash("sha256") - .update(yield* until(readFile(journey.codex))) - .digest("hex"); - const reported = yield* bounded("codex-version", VERSION_MS, () => - runChild(journey.codex, ["--version"], { cwd: journey.root, live: journey.live }), - ); - verdict.codexVersion = reported.code === 0 ? reported.stdout.trim() : ""; - return true; + const codex = yield* until(realpath(located.stdout.trim())); + try { + verdict.codexDigest = yield* bounded("codex-digest", VERSION_MS, () => digest(codex)); + } catch { + verdict.codexDigest = ""; + } + try { + const version = yield* bounded("codex-version", VERSION_MS, () => + child(codex, ["--version"], { cwd, live }), + ); + const adapter = nativeAdapterFor("codex"); + verdict.codexVersion = + version.code === 0 && adapter && bindsBuild(adapter) + ? (adapter.binding.version(version.stdout) ?? "") + : ""; + } catch { + verdict.codexVersion = ""; + } + return codex; } -/** The vendored adapter's own snapshot identity, from the product's own list. */ -function recordAdapter(verdict: JourneyVerdict): void { +function recordAdapter( + verdict: Pick< + JourneyVerdict, + "adapterPackage" | "adapterVersion" | "adapterDigest" | "compatibilityTupleFrozen" + >, +): void { const snapshot = embeddedAdapterIdentities().find((entry) => entry.provider === "codex"); verdict.adapterPackage = snapshot?.package ?? ""; verdict.adapterVersion = snapshot?.version ?? ""; verdict.adapterDigest = snapshot?.sha256 ?? ""; + verdict.compatibilityTupleFrozen = + verdict.adapterPackage === REQUIRED_ADAPTER_PACKAGE && + verdict.adapterVersion === REQUIRED_ADAPTER_VERSION && + verdict.adapterDigest === REQUIRED_ADAPTER_DIGEST; } /** Everything every journey establishes before it is allowed to launch. */ -function* ready(journey: Journey, verdict: JourneyVerdict): Operation { - if (!(yield* observeCodex(journey, verdict))) { +export function* ready( + journey: Pick, + verdict: JourneyVerdict, + child = runChild, + digest = executableDigest, +): Operation { + const codex = yield* observeCodex(journey.root, journey.live, verdict, child, digest); + if (!codex) { // Nothing has been launched, so the journey did not run. Saying otherwise // would let a machine that cannot host the proof read as one that hosted it // and found something. @@ -1686,11 +1639,8 @@ function* ready(journey: Journey, verdict: JourneyVerdict): Operation { verdict.detail = "no installed codex executable was found on PATH"; return false; } + journey.codex = codex; recordAdapter(verdict); - verdict.compatibilityTupleFrozen = - verdict.adapterPackage === REQUIRED_ADAPTER_PACKAGE && - verdict.adapterVersion === REQUIRED_ADAPTER_VERSION && - verdict.adapterDigest === REQUIRED_ADAPTER_DIGEST; if (!verdict.compatibilityTupleFrozen) { verdict.ran = false; verdict.verdict = "ENVIRONMENT_BLOCKED"; @@ -2177,11 +2127,17 @@ function* unmaterializedIsRefused( }); } -function* runPreflight(): Operation { +export function* runPreflight( + child = runChild, + digest = executableDigest, + checkIdentity = unmaterializedIsRefused, + authorized = process.env[PROOF_ENV] === "1", + binary = XMD_BINARY, +): Operation { const verdict: PreflightVerdict = { mode: "preflight", verdict: "HARNESS_FAILED", - authorized: process.env[PROOF_ENV] === "1", + authorized, refusal: "", detail: "preflight did not reach a verdict", head: "", @@ -2215,52 +2171,34 @@ function* runPreflight(): Operation { const live: LiveSet = new Set(); const cwd = REPO_ROOT; - verdict.head = (yield* runChild("git", ["rev-parse", "HEAD"], { cwd, live })).stdout.trim(); - verdict.branch = (yield* runChild("git", ["branch", "--show-current"], { + verdict.head = (yield* child("git", ["rev-parse", "HEAD"], { cwd, live })).stdout.trim(); + verdict.branch = (yield* child("git", ["branch", "--show-current"], { cwd, live, })).stdout.trim(); - const located = yield* bounded("resolve-codex", VERSION_MS, () => - runChild("/usr/bin/which", ["codex"], { cwd, live }), - ); - if (located.code !== 0 || located.stdout.trim().length === 0) { + const codex = yield* observeCodex(cwd, live, verdict, child, digest); + if (!codex) { verdict.verdict = "ENVIRONMENT_BLOCKED"; verdict.detail = "no installed codex executable was found on PATH"; return verdict; } - const codex = yield* until(realpath(located.stdout.trim())); - verdict.codexDigest = createHash("sha256") - .update(yield* until(readFile(codex))) - .digest("hex"); - const version = yield* bounded("codex-version", VERSION_MS, () => - runChild(codex, ["--version"], { cwd, live }), - ); - verdict.codexVersion = version.code === 0 ? version.stdout.trim() : ""; - - const snapshot = embeddedAdapterIdentities().find((entry) => entry.provider === "codex"); - verdict.adapterPackage = snapshot?.package ?? ""; - verdict.adapterVersion = snapshot?.version ?? ""; - verdict.adapterDigest = snapshot?.sha256 ?? ""; - verdict.compatibilityTupleFrozen = - verdict.adapterPackage === REQUIRED_ADAPTER_PACKAGE && - verdict.adapterVersion === REQUIRED_ADAPTER_VERSION && - verdict.adapterDigest === REQUIRED_ADAPTER_DIGEST; + recordAdapter(verdict); // Both are asked without a session, so they fail on an argument rather than // reaching a model. const resume = yield* bounded("codex-resume-help", VERSION_MS, () => - runChild(codex, ["resume", "--help"], { cwd, live }), + child(codex, ["resume", "--help"], { cwd, live }), ); verdict.resumeSurface = resume.code === 0 && resume.stdout.includes("SESSION_ID"); // The exact surface cleanup uses: `--force` is what makes the delete answer // without a prompt, and a build without it would leave this fixture's own // conversations behind while reporting that it removed them. const surface = yield* bounded("codex-delete-help", VERSION_MS, () => - runChild(codex, ["delete", "--help"], { cwd, live }), + child(codex, ["delete", "--help"], { cwd, live }), ); const remove = yield* bounded("codex-delete", VERSION_MS, () => - runChild(codex, ["delete", "--force", randomUUID()], { cwd, live, input: "" }), + child(codex, ["delete", "--force", randomUUID()], { cwd, live, input: "" }), ); verdict.deleteSurface = surface.code === 0 && @@ -2268,10 +2206,10 @@ function* runPreflight(): Operation { remove.code !== 0 && shows(`${remove.stdout}${remove.stderr}`, "failed to delete session"); - verdict.binaryBuilt = yield* exists(XMD_BINARY); + verdict.binaryBuilt = yield* exists(binary); if (verdict.compatibilityTupleFrozen) { - yield* unmaterializedIsRefused(codex, live, verdict); + yield* checkIdentity(codex, live, verdict); } const established = @@ -2293,7 +2231,7 @@ function render(value: unknown): void { process.stdout.write(`${JSON.stringify(value, null, 2)}\n`); } -main(function* () { +function* runProof(): Operation { const mode = process.argv[2]; if (mode === "preflight") { @@ -2320,4 +2258,8 @@ main(function* () { } throw new Error(`codex-native-launch-proof: unknown mode "${mode ?? ""}"`); -}); +} + +if (import.meta.main) { + main(runProof); +} diff --git a/packages/acp/tests/fixtures/native-proof-child.ts b/packages/acp/tests/fixtures/native-proof-child.ts new file mode 100644 index 000000000..5790e61fa --- /dev/null +++ b/packages/acp/tests/fixtures/native-proof-child.ts @@ -0,0 +1,76 @@ +import { ensure, scoped, race, withResolvers } from "effection"; +import type { Operation } from "effection"; +import { spawn as spawnChild } from "node:child_process"; +import type { ChildProcess } from "node:child_process"; + +export interface ChildOutcome { + code: number | null; + signal: string | null; + stdout: string; + stderr: string; +} + +/** Every child a mode started, so cleanup can prove none outlived it. */ +export type LiveSet = Set; + +/** Run one captured child to settlement. Never the production command. */ +export function runChild( + command: string, + args: string[], + options: { cwd: string; input?: string; live: LiveSet; env?: Record }, +): Operation { + return scoped(function* () { + const settled = withResolvers(); + const failed = withResolvers(); + let child: ChildProcess | undefined; + let stdout = ""; + let stderr = ""; + let closed = false; + const onStdout = (chunk: Buffer) => { + stdout += chunk.toString(); + }; + const onStderr = (chunk: Buffer) => { + stderr += chunk.toString(); + }; + const onError = (error: Error) => failed.reject(error); + const onClose = (code: number | null, signal: string | null) => { + closed = true; + settled.resolve({ code, signal, stdout, stderr }); + }; + yield* ensure(function* () { + if (!child) { + return; + } + try { + if (!closed) { + if (child.pid) { + child.kill("SIGKILL"); + } + yield* settled.operation; + } + } finally { + child.stdout?.off("data", onStdout); + child.stderr?.off("data", onStderr); + child.off("error", onError); + child.off("close", onClose); + if (child.pid) { + options.live.delete(child.pid); + } + } + }); + child = spawnChild(command, args, { + cwd: options.cwd, + stdio: ["pipe", "pipe", "pipe"], + ...(options.env === undefined ? {} : { env: options.env }), + }); + if (child.pid) { + options.live.add(child.pid); + } + child.stdout?.on("data", onStdout); + child.stderr?.on("data", onStderr); + child.on("error", onError); + child.on("close", onClose); + child.stdin?.end(options.input); + return yield* race([settled.operation, failed.operation]); + }); +} diff --git a/packages/acp/tests/native-proof.test.ts b/packages/acp/tests/native-proof.test.ts new file mode 100644 index 000000000..6c9f3c775 --- /dev/null +++ b/packages/acp/tests/native-proof.test.ts @@ -0,0 +1,294 @@ +import { readTextFile, rm, writeTextFile } from "@effectionx/fs"; +import { Agent } from "@executablemd/agent/api"; +import { agentSessionKeyDigest } from "@executablemd/runtime"; +import { describe, it } from "@executablemd/test-support/bdd"; +import { expect } from "@executablemd/test-support/expect"; +import { scoped, sleep, spawn } from "effection"; +import type { Operation } from "effection"; +import { randomUUID } from "node:crypto"; +import { join, basename } from "node:path"; +import process from "node:process"; +import { createAcpRuntime, createAgentRegistry, resolveAgentCommand } from "../src/acpx-runtime.ts"; +import { + createEmbeddedAdapters, + embeddedAdapterIdentities, + overlaidAdapterRegistry, +} from "../src/adapter-snapshots.ts"; +import { useAcpxProvider } from "../src/provider.ts"; +import { deriveSessionKey } from "../src/session-key.ts"; +import { + createDenoSessionRouteStore, + createMemorySessionRouteStore, +} from "../src/session-route.ts"; +import { createAcpxSessionStore } from "../src/session-store.ts"; +import { withCertificationFixture } from "./certification-fixture.ts"; +import { makeCoordinator, useFlatWorld } from "./helpers.ts"; +import * as attachment from "./fixtures/claude-native-to-acp-proof.ts"; +import * as claude from "./fixtures/claude-native-launch-proof.ts"; +import * as codex from "./fixtures/codex-native-launch-proof.ts"; +import { + claudeKeyPaths, + claudeRouteKey, + nativeUiInvocations, + prepareAbsentRoute, + submittedModelTurns, +} from "./fixtures/claude-proof-evidence.ts"; +import { runChild } from "./fixtures/native-proof-child.ts"; +import type { ChildOutcome } from "./fixtures/native-proof-child.ts"; + +describe("native proof evidence", { sanitizeOps: false, sanitizeResources: false }, () => { + it("P1: the carried key addresses the refused load and its persisted prompt-attempt evidence", function* () { + yield* withCertificationFixture(function* (peer) { + const root = join(peer.dir, "coordination"); + const adapters = createEmbeddedAdapters(join(peer.dir, "adapters")); + const agent = resolveAgentCommand(overlaidAdapterRegistry(adapters), "claude"); + const sessionKey = deriveSessionKey(agent, peer.dir, "implementer"); + const key = { provider: "acpx", agent, sessionKey }; + expect(claudeRouteKey(adapters, peer.dir)).toEqual(key); + expect( + deriveSessionKey( + resolveAgentCommand(createAgentRegistry(), "claude"), + peer.dir, + "implementer", + ), + ).not.toBe(sessionKey); + const durable = createDenoSessionRouteStore(root); + const routeStore = durable ?? createMemorySessionRouteStore(); + const route = yield* prepareAbsentRoute(routeStore, key, randomUUID()); + const registry = overlaidAdapterRegistry(adapters); + expect(yield* routeStore.read(key)).toEqual(route); + const paths = claudeKeyPaths(root, agent, sessionKey); + expect(paths.map((path) => basename(path).split(".")[0])).toEqual( + Array(3).fill(agentSessionKeyDigest(key)), + ); + const store = createAcpxSessionStore(peer.home); + const owner = makeCoordinator(); + yield* useFlatWorld(peer.dir); + yield* Agent.around( + { + *agent([name]) { + return name ?? "claude"; + }, + }, + { at: "min" }, + ); + const run = function* () { + yield* scoped(function* () { + const provider = yield* useAcpxProvider( + { defaultAgent: "claude", permissionMode: "deny-all" }, + { + sessionStore: store, + agentRegistry: registry, + coordinator: owner.coordinator, + routeStore, + advertiseNativeLaunch: ["claude"], + advertiseClientNativeAttachment: ["claude"], + createRuntime(options) { + return createAcpRuntime({ + ...options, + agentRegistry: { resolve: () => peer.command("normal"), list: () => ["claude"] }, + }); + }, + }, + ); + const session = yield* provider.session("implementer"); + const sub = yield* provider.promptStream("recall", { session }); + let next = yield* sub.next(); + while (!next.done) { + next = yield* sub.next(); + } + }); + }; + let caught: unknown; + try { + yield* run(); + } catch (error) { + caught = error; + } + expect(caught).toMatchObject({ failure: { class: "identity-unavailable" } }); + const methods = (yield* peer.calls()).filter((call) => call.method.startsWith("session/")); + expect(methods.map((call) => [call.method, call.sessionId])).toEqual([ + ["session/load", route.nativeSessionId], + ]); + expect(owner.events.at(-1)).toBe("released-idle"); + expect(yield* submittedModelTurns(peer.home, sessionKey)).toBe(0); + // Supply history to this synthetic peer only. The exact load now succeeds + // and the same counter must observe the prompt the subprocess received. + yield* writeTextFile( + join(peer.dir, "fixture-" + route.nativeSessionId + ".json"), + JSON.stringify({ marker: "synthetic" }), + ); + yield* run(); + expect((yield* peer.methods()).filter((m) => m === "session/prompt")).toHaveLength(1); + expect(yield* submittedModelTurns(peer.home, sessionKey)).toBe(1); + for (const path of paths) { + yield* rm(path, { force: true }); + } + if (durable) { + expect(yield* durable.read(key)).toBe(undefined); + } + }); + }); + + it("P2: both Claude shims distinguish native UI argv from availability and ACP", function* () { + const create = ["--session-id", "identity", "--system-prompt-file", "/private/file"]; + const resume = ["--resume", "identity"]; + const trace = [ + ["--version"], + ["--print", "--input-format", "stream-json", "--resume", "unrelated"], + create, + resume, + ] + .map((args) => ["invocation", ...args.map((arg) => "arg " + arg)].join("\n")) + .join("\n"); + for (const fixture of [claude, attachment]) { + const all = fixture.parseObservations(trace); + expect(all).toHaveLength(4); + expect(nativeUiInvocations(all).map(fixture.filtered)).toEqual([ + ["claude", "--session-id", "identity", "--system-prompt-file", ""], + ["claude", "--resume", "identity"], + ]); + } + const zero = claude.blankJourney("zero-turn"); + zero.nativeSessionId = "identity"; + zero.secondInvocationChildren = 1; + zero.secondCommand = ["claude", "--resume", "identity"]; + zero.outcome = "same-identity"; + claude.decideZeroTurn(zero); + expect(zero.verdict).toBe("PASS"); + zero.outcome = "unresolved"; + zero.secondInvocationChildren = 0; + zero.secondCommand = []; + zero.journal.failureClasses = ["identity-unavailable"]; + claude.decideZeroTurn(zero); + expect([zero.outcome, zero.verdict]).toEqual(["no-session", "PASS"]); + const established = claude.blankJourney("two-turn"); + established.openingSentenceExact = true; + claude.decideTwoTurn(established); + expect(established.verdict).toBe("PRODUCT_FAILED"); + const acp = attachment.blankJourney("native-to-acp"); + acp.markerStored = true; + attachment.decideAttachment(acp); + expect(acp.verdict).toBe("PRODUCT_FAILED"); + const snapshot = embeddedAdapterIdentities().find((item) => item.provider === "codex"); + expect(snapshot).toMatchObject({ + package: "@agentclientprotocol/codex-acp", + version: "1.6.2", + sha256: "a3f699537970127972635b4596aef40ab8a4caa25a9028861d9ee07bf6c4b1a1", + }); + for (const doc of ["CodexNativeLaunch", "CodexZeroNativeTurnExit"]) { + const content = yield* readTextFile(new URL("../src/" + doc + ".test.md", import.meta.url)); + expect(content).toContain('expected={"' + snapshot?.sha256 + '"}'); + } + const carried = createEmbeddedAdapters("/test/adapter-root").identity("claude"); + expect( + yield* readTextFile(new URL("../src/ClaudeNativeToAcp.test.md", import.meta.url)), + ).toContain('expected={"' + carried + '"}'); + }); + + it("P3: ready and preflight continue after optional version and digest failures", function* () { + const binary = process.execPath; + const live = new Set(); + let missing = false; + let unfamiliar = false; + const child: typeof runChild = function* (command, args): Operation { + const outcome = { code: 0, signal: null, stdout: "", stderr: "" }; + if (args[0] === "--version") { + if (!unfamiliar) { + throw new Error("controlled version timeout"); + } + return { ...outcome, stdout: "unfamiliar release banner" }; + } + if (command === "/usr/bin/which") { + return { ...outcome, code: missing ? 1 : 0, stdout: missing ? "" : binary }; + } + if (args.includes("--system-prompt-file")) { + return { ...outcome, stderr: "System prompt file not found" }; + } + if (args[0] === "auth") { + return { ...outcome, stdout: '{"loggedIn":true}' }; + } + if (command === "/usr/bin/script") { + return { ...outcome, stdout: "PTY" }; + } + if (args.includes("--help")) { + return { ...outcome, stdout: "--dry-run --force SESSION_ID" }; + } + if (args[0] === "delete") { + return { ...outcome, code: 1, stderr: "failed to delete session" }; + } + return outcome; + }; + const digest = function* (): Operation { + throw new Error("controlled unreadable bytes"); + }; + const a = claude.blankJourney("two-turn"), + b = codex.blankJourney("native-launch"); + a.projectCopyVerified = b.projectCopyVerified = true; + const claudeJourney = { root: ".", live, realClaude: binary }, + codexJourney = { root: ".", live, codex: "" }; + expect(yield* claude.ready(claudeJourney, a, child)).toBe(true); + expect(yield* codex.ready(codexJourney, b, child, digest)).toBe(true); + expect([a.claudeVersion, b.codexVersion, b.codexDigest, b.compatibilityTupleFrozen]).toEqual([ + "", + "", + "", + true, + ]); + unfamiliar = true; + expect(yield* claude.ready(claudeJourney, a, child)).toBe(true); + expect(yield* codex.ready(codexJourney, b, child, digest)).toBe(true); + expect([a.claudeVersion, b.codexVersion]).toEqual(["", ""]); + unfamiliar = false; + const claudeFlight = yield* claude.runPreflight(child, true, binary); + const codexFlight = yield* codex.runPreflight( + child, + digest, + function* (_path, _live, verdict) { + verdict.adapterNamesNativeIdentity = verdict.unmaterializedIdentityRefused = true; + }, + true, + binary, + ); + expect([ + claudeFlight.sessionIdFlag, + claudeFlight.ptyUsable, + codexFlight.resumeSurface, + codexFlight.deleteSurface, + ]).toEqual([true, true, true, true]); + expect([claudeFlight.claudeVersion, codexFlight.codexVersion, codexFlight.codexDigest]).toEqual( + ["", "", ""], + ); + expect(claudeFlight.verdict).toBe( + claudeFlight.claudeConfigDirSet ? "ENVIRONMENT_BLOCKED" : "PASS", + ); + expect(codexFlight.verdict).toBe(codexFlight.codexHomeSet ? "ENVIRONMENT_BLOCKED" : "PASS"); + expect(yield* claude.ready({ ...claudeJourney, realClaude: "" }, a, child)).toBe(false); + missing = true; + expect(yield* codex.ready(codexJourney, b, child, digest)).toBe(false); + expect([a.verdict, b.verdict]).toEqual(["ENVIRONMENT_BLOCKED", "ENVIRONMENT_BLOCKED"]); + }); + + it("P3: halting optional observation joins its child before releasing the caller", function* () { + const live = new Set(); + const verdict = claude.blankJourney("zero-turn"); + verdict.projectCopyVerified = true; + let advanced = false; + const work = yield* spawn(function* () { + yield* claude.ready( + { root: ".", realClaude: "controlled", live }, + verdict, + (_cmd, _args, options) => runChild("/bin/sleep", ["30"], options), + ); + advanced = true; + }); + while (!live.size) { + yield* sleep(1); + } + const [pid] = live; + yield* work.halt(); + expect(advanced).toBe(false); + expect(live.size).toBe(0); + expect(() => process.kill(pid!, 0)).toThrow(); + }); +}); diff --git a/packages/acp/tests/provider.test.ts b/packages/acp/tests/provider.test.ts index 81751373b..eee8df95b 100644 --- a/packages/acp/tests/provider.test.ts +++ b/packages/acp/tests/provider.test.ts @@ -4,9 +4,13 @@ * Drives the provider through its dependencies with a scriptable fake runtime: * no agent process ever starts. */ +import { join } from "node:path"; +import { readTextFile, rm, writeTextFile } from "@effectionx/fs"; +import { createAcpRuntime } from "../src/acpx-runtime.ts"; +import { AGENT_SOURCE, STANDARD_AGENT_SOURCE, world } from "./released-peer.ts"; import { describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; -import { scoped, sleep, spawn, until, withResolvers } from "effection"; +import { scoped, sleep, spawn, until, useScope, withResolvers } from "effection"; import type { Operation } from "effection"; import { Config } from "@executablemd/core"; import { Agent, claimsConfiguration, sessionOf } from "@executablemd/agent/api"; @@ -3553,3 +3557,154 @@ describe("Tier AP — Prompt usage observation", () => { expect(seen.reports[0].coverage.finalReport).toBe("received"); }); }); + +describe( + "changed executable on a retained live handle", + { sanitizeOps: false, sanitizeResources: false }, + () => { + for (const [agent, refusal] of [ + ["codex", "close"], + ["codex", "missing"], + ["claude", "different"], + ] as const) { + it(`W3: ${agent} refuses ${refusal} before another turn`, function* () { + const peer = yield* world(true); + yield* useFlatWorld(peer.dir); + yield* Agent.around( + { + *agent([name]) { + return name ?? agent; + }, + }, + { at: "min" }, + ); + let selected = "A"; + const ensures: string[] = []; + let failClose = refusal === "close"; + let cleanupFailure: unknown; + let recovered = false; + let beforeReopen = ""; + try { + yield* scoped(function* () { + const scope = yield* useScope(); + const provider = yield* useAcpxProvider( + { defaultAgent: agent, permissionMode: "deny-all" }, + { + sessionStore: peer.store, + agentRegistry: peer.registry, + advertiseNativeLaunch: [], + advertiseClientNativeAttachment: [], + *agentProcessEnv() { + return { SELECTION: selected }; + }, + createRuntime(options) { + const runtime = createAcpRuntime({ ...options, agentRegistry: peer.registry }); + const open = runtime.ensureSession.bind(runtime); + runtime.ensureSession = (input) => { + ensures.push(options.agentProcessEnv?.SELECTION ?? ""); + if (!input.expectedAgentSessionId) { + return open(input); + } + return scope + .run(() => + readTextFile( + join( + peer.dir, + "sessions", + encodeURIComponent(input.sessionKey) + ".json", + ), + ), + ) + .then((bytes) => { + beforeReopen = bytes; + return open(input); + }); + }; + const close = runtime.close.bind(runtime); + runtime.close = (input) => { + if (failClose) { + failClose = false; + return Promise.reject(new Error("controlled release rejection")); + } + return close(input); + }; + return runtime; + }, + }, + ); + const session = yield* provider.session("retained"); + function prompt(text: string) { + return scoped(function* () { + const subscription = yield* provider.promptStream(text, { session }); + let output = ""; + let value = yield* subscription.next(); + while (!value.done) { + if (value.value.type === "text_delta") { + output += value.value.text; + } + value = yield* subscription.next(); + } + return output; + }); + } + yield* prompt("marker"); + const retained = yield* until(peer.store.load(session.sessionKey)); + expect(retained?.agentSessionId).toBeDefined(); + const recordPath = join( + peer.dir, + "sessions", + encodeURIComponent(session.sessionKey) + ".json", + ); + const original = yield* readTextFile(recordPath); + const calls = join(peer.dir, "methods.jsonl"); + const seed = yield* readTextFile(calls); + selected = "B"; + if (refusal === "missing") { + yield* writeTextFile(peer.agent, STANDARD_AGENT_SOURCE); + } else if (refusal === "different") { + yield* writeTextFile(join(peer.dir, "different-native-identity"), "1"); + } + let caught: unknown; + try { + yield* prompt("must not run"); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(Error); + const delta = (yield* readTextFile(calls)).slice(seed.length); + if (refusal === "close") { + expect(ensures).toEqual(["A"]); + expect(delta).toBe(""); + } else { + expect(ensures).toEqual(["A", "B"]); + expect( + delta + .trim() + .split("\n") + .map((line) => JSON.parse(line).method), + ).toEqual(["session/load"]); + expect(JSON.parse(delta).sessionId).toBe(retained?.acpSessionId); + } + expect(yield* readTextFile(recordPath)).toBe( + refusal === "close" ? original : beforeReopen, + ); + expect(session.agentSessionId).toBe(retained?.agentSessionId); + yield* writeTextFile(peer.agent, AGENT_SOURCE); + yield* rm(join(peer.dir, "different-native-identity"), { force: true }); + expect(yield* prompt("recall")).toContain("answer:recall:marker"); + recovered = true; + expect(session.agentSessionId).toBe(retained?.agentSessionId); + }); + } catch (error) { + cleanupFailure = error; + } + if (refusal === "close") { + expect(String(cleanupFailure)).toContain("controlled release rejection"); + } else if (cleanupFailure) { + throw cleanupFailure; + } + expect(recovered).toBe(true); + }); + } + }, +); diff --git a/packages/cli/tests/workflow-agent-sessions.test.ts b/packages/cli/tests/workflow-agent-sessions.test.ts index 5e263175c..cbb4ae873 100644 --- a/packages/cli/tests/workflow-agent-sessions.test.ts +++ b/packages/cli/tests/workflow-agent-sessions.test.ts @@ -15,11 +15,17 @@ import { describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; -import { scoped, spawn, until, suspend, withResolvers } from "effection"; +import { ensure, scoped, spawn, until, suspend, withResolvers } from "effection"; import type { Operation } from "effection"; import { readdir, ensureDir, exists, readTextFile, writeTextFile } from "@effectionx/fs"; -import { chmod, symlink } from "node:fs/promises"; +import { chmod, realpath, rename, symlink } from "node:fs/promises"; import process from "node:process"; +import { randomUUID } from "node:crypto"; +import { + hostClaudeExecutable, + hostCodexExecutable, +} from "../../runtime/node-host-agent-executable.ts"; +import type { AcpRuntimeEnsureInput } from "../../acp/src/acpx-runtime.ts"; import { exec, useQuietProcessOutput } from "@executablemd/runtime"; import { createAcpRuntime, createAcpxSessionStore } from "@executablemd/acp"; import { withCertificationFixture } from "../../acp/tests/certification-fixture.ts"; @@ -29,6 +35,8 @@ import { DatabaseSync } from "node:sqlite"; import { dirname, join, relative as relativePath } from "node:path"; import { fileURLToPath } from "node:url"; import { registerComponents, collect, retainedSource } from "@executablemd/core"; +import { Agent, sessionOf } from "@executablemd/agent/api"; +import type { Session } from "@executablemd/agent/api"; import { agentIdentityComponents } from "@executablemd/agent/host"; import { executeInstalled } from "@executablemd/core/host"; import type { Json } from "@executablemd/durable-streams"; @@ -68,6 +76,8 @@ function attach( readonly sessionStore: WorkflowAgentProfileOptions["sessionStore"]; readonly defaultAgent?: string; readonly installation?: ExecutionInstallation; + readonly agentProcessEnv?: WorkflowAgentProfileOptions["agentProcessEnv"]; + readonly adapters?: WorkflowAgentProfileOptions["adapters"]; }, ): Operation { return scoped(function* () { @@ -741,3 +751,159 @@ describe("workflow ACP loading identity", { sanitizeOps: false, sanitizeResource }); } }); + +describe( + "current executable within one workflow Session", + { sanitizeOps: false, sanitizeResources: false }, + () => { + for (const [agent, changes] of [ + ["claude", true], + ["codex", true], + ["codex", false], + ] as const) { + it(`${changes ? "W1" : "W2"}: ${agent} ${changes ? "switches executable" : "reuses the live handle"} between prompts`, function* () { + yield* withCertificationFixture(function* (peer) { + const root = yield* useStorageRoot(); + const first = yield* until(realpath("/usr/bin/true")); + const second = yield* until(realpath("/bin/echo")); + const selected = join(peer.dir, "selected"); + yield* until(symlink(first, selected)); + const variable = agent === "claude" ? "CLAUDE_CODE_EXECUTABLE" : "CODEX_PATH"; + const original = process.env[variable]; + yield* ensure(() => { + if (original === undefined) { + delete process.env[variable]; + } else { + process.env[variable] = original; + } + }); + process.env[variable] = selected; + yield* withStorage(root, function* () { + const db = yield* createRun(); + const path = workflowRunPath(root, db.record.runId); + const trace: string[] = []; + const ensures: AcpRuntimeEnsureInput[] = []; + let rows: MappingRow[] = []; + const issued: Array = []; + const marker = randomUUID(); + const source = ``; + const result = yield* attach(root, db, source, { + defaultAgent: agent, + sessionStore: createAcpxSessionStore(peer.home), + adapters: { ...createEmbeddedAdapters(join(root, "adapters")), *materialize() {} }, + *agentProcessEnv() { + return { + [variable]: yield* agent === "claude" + ? hostClaudeExecutable() + : hostCodexExecutable(), + }; + }, + createRuntime(options) { + const executable = options.agentProcessEnv?.[variable]; + const runtime = createAcpRuntime({ + ...options, + agentRegistry: { + resolve: () => peer.command("distinct"), + list: () => [agent], + }, + }); + const open = runtime.ensureSession.bind(runtime); + runtime.ensureSession = (input) => { + ensures.push(input); + trace.push("ensure " + executable); + return open(input); + }; + const close = runtime.close.bind(runtime); + runtime.close = (input) => + close(input).then(() => { + trace.push("closed " + executable); + }); + const turn = runtime.startTurn.bind(runtime); + runtime.startTurn = (input) => { + trace.push("turn " + executable); + return turn(input); + }; + return runtime; + }, + installation: { + *install() { + yield* Agent.around({ + *prompt(args, next) { + issued.push(sessionOf(args[1]?.session)); + return yield* next(...args); + }, + }); + yield* registerComponents([ + { + name: "Gate", + origin: "test://workflow-executable-switch", + props: { type: "object", properties: {}, additionalProperties: false }, + *fn() { + rows = mappingRows(path); + if (changes) { + yield* until(symlink(second, selected + ".next")); + yield* until(rename(selected + ".next", selected)); + } + return ""; + }, + }, + ]); + }, + }, + }); + expect(result.failure).toBe(undefined); + expect(JSON.stringify(result.output)).toContain(marker); + expect(issued).toHaveLength(2); + expect(issued[0]).toBeDefined(); + expect(issued[1]).toBe(issued[0]); + expect(issued[0]?.agentSessionId).toBe(rows[0]?.value); + expect(rows).toHaveLength(1); + expect(rows[0]?.kind).toBe("acpx.agentSessionId"); + expect(mappingRows(path)).toEqual(rows); + const next = changes ? second : first; + expect(trace.filter((e) => e.startsWith("turn "))).toEqual([ + "turn " + first, + "turn " + next, + ]); + const calls = (yield* peer.calls()).filter((e) => e.method.startsWith("session/")); + expect(calls.filter((e) => e.method === "session/new")).toHaveLength(1); + expect(calls.filter((e) => e.method === "session/prompt").map((e) => e.kind)).toEqual([ + "seed", + "recall", + ]); + const target = calls.find((e) => e.kind === "seed")?.sessionId; + expect(target).toBeDefined(); + expect(ensures).toHaveLength(changes ? 2 : 1); + if (changes) { + expect(ensures[1]).toMatchObject({ + sessionKey: ensures[0]?.sessionKey, + resumeSessionId: target, + expectedAgentSessionId: rows[0]?.value, + }); + expect(calls.filter((e) => e.method === "session/load").at(-1)?.sessionId).toBe( + target, + ); + expect( + trace.slice(trace.indexOf("turn " + first), trace.indexOf("turn " + second) + 1), + ).toEqual(["turn " + first, "closed " + first, "ensure " + second, "turn " + second]); + const recalled = calls.slice(calls.findIndex((e) => e.kind === "seed") + 1); + expect( + recalled + .filter((e) => + ["session/load", "session/set_config_option", "session/prompt"].includes( + e.method, + ), + ) + .map((e) => e.method), + ).toEqual(["session/load", "session/set_config_option", "session/prompt"]); + } else { + expect( + trace.slice(trace.indexOf("turn " + first), trace.lastIndexOf("turn " + first) + 1), + ).toEqual(["turn " + first, "turn " + first]); + } + }); + }); + }); + } + }, +); diff --git a/specs/native-agent-session-launch-spec.md b/specs/native-agent-session-launch-spec.md index a78b56624..809bd5066 100644 --- a/specs/native-agent-session-launch-spec.md +++ b/specs/native-agent-session-launch-spec.md @@ -714,11 +714,12 @@ are met rather than a further invariant beside them: - **Claimed work that produced no handle releases its claim.** The runtime is built before the ensure that would use it, so a rejection would otherwise - strand a partition holding a live path for work that never happened — and a - binding compares a version and a digest, so the same build found somewhere - else is the same partition key and a different file to run. Success transfers - the claim into ownership of the handle instead, in one step: a moment where - neither count is held is a moment another operation could evict. + strand a partition holding a live path for work that never happened. The + selected command, adapter command and environment determine the partition. + Identical executable bytes selected through different paths can therefore + use different partitions. Success transfers the claim into ownership of the + handle in one step. A moment where neither count is held is a moment another + operation could evict. - **Cancellation observes the ensure it started, and settles it before quiescence.** Starting an ensure is not the same as owning it: the call runs whether or not anybody is still waiting, so a cancellation is not the end of From bbff2453750997cd5241a496987975eb33d03615 Mon Sep 17 00:00:00 2001 From: Taras Mankovski Date: Wed, 18 Nov 2026 09:19:01 -0500 Subject: [PATCH 7/7] Join live ACP ownership before eager named-session reopening --- packages/acp/src/provider.ts | 85 +++--- .../fixtures/claude-native-to-acp-proof.ts | 34 ++- .../tests/fixtures/claude-proof-evidence.ts | 28 +- packages/acp/tests/native-proof.test.ts | 26 +- packages/acp/tests/provider.test.ts | 287 +++++++++++++++++- 5 files changed, 392 insertions(+), 68 deletions(-) diff --git a/packages/acp/src/provider.ts b/packages/acp/src/provider.ts index e81f814eb..cf02792b7 100644 --- a/packages/acp/src/provider.ts +++ b/packages/acp/src/provider.ts @@ -1696,24 +1696,15 @@ function* useAcpxProviderState( `"${named.sessionKey}" (${entry.agentCommand})`, ); } - if (!isLive(entry)) { - // Nothing of this provider's holds the session any more: the handle was - // released, or handed to a native UI. Reaching for the same key - // re-ensures it, which reattaches ACP to whatever holds it now rather - // than reusing a connection older than that. - refuseIfUnusable(entry.session.sessionKey); - return { - kind: "details", - sessionKey: entry.session.sessionKey, - agentCommand: entry.agentCommand, - details: { - sessionKey: entry.session.sessionKey, - cwd: entry.cwd, - state: entry.state, - }, - issued: entry.session, - ...(entry.continuation === undefined ? {} : { continuation: entry.continuation }), - }; + const continuation = continuationOf(facts); + if (!isLive(entry) || continuation !== undefined) { + // Reopening needs the caller's retained history, even when this provider + // still has the exact object previously issued for the placement. + return prepareSessionDetails( + agentCommand, + { sessionKey: named.sessionKey, cwd: entry.cwd, state: entry.state }, + continuation, + ); } refuseIfUnusable(named.sessionKey); return { kind: "existing", sessionKey: named.sessionKey, entry }; @@ -1827,16 +1818,21 @@ function* useAcpxProviderState( */ function* sessionCreationState( agentName: string, - agentCommand: string, - details: AcpxSessionDetails, + prepared: Prepared, ): Operation<"new" | "existing"> { + if (prepared.kind === "existing") { + return prepared.entry.state; + } + const { details } = prepared; if (details.state === "existing") { return "existing"; } if (!namesOwnSessions(agentName) || !routeStore) { return "new"; } - const route = yield* routeStore.read(sessionKeyOf(agentCommand, details.sessionKey)); + const route = yield* routeStore.read( + sessionKeyOf(ownerCommandOf(prepared), details.sessionKey), + ); return route?.route === "client-native" ? "existing" : "new"; } @@ -1847,13 +1843,22 @@ function* useAcpxProviderState( * caller is about to construct, and acting on what was read before waiting is * how one session ends up with two conversations. */ - function* requeried(prepared: Prepared): Operation { + function* requeried(prepared: Prepared, validatePlacement = false): Operation { const sessionKey = prepared.sessionKey; const held = managed.get(sessionKey); - if (held && isLive(held)) { + const agentCommand = agentCommandOf(prepared); + const continuation = continuationOfPrepared(prepared) ?? held?.continuation; + // A named eager lookup validates its placement through the host and ACPX. + // Caller-supplied history also needs its own assertion on reopening. + if ( + held && + isLive(held) && + !validatePlacement && + held.agentCommand === agentCommand && + held.continuation === continuation + ) { return { kind: "existing", sessionKey, entry: held }; } - const agentCommand = agentCommandOf(prepared); const cwd = held?.cwd ?? (prepared.kind === "existing" ? prepared.entry.cwd : prepared.details.cwd); const record = yield* until(store.load(sessionKey)); @@ -1861,13 +1866,14 @@ function* useAcpxProviderState( // does not touch; what this provider holds in memory is the translated value. const exists = held?.state === "existing" || + (prepared.kind === "details" && prepared.details.state === "existing") || (record !== undefined && record.sessionMaterialization?.state !== "pending"); const details: AcpxSessionDetails = { sessionKey, cwd, state: exists ? "existing" : "new", }; - return prepareSessionDetails(agentCommand, details, continuationOfPrepared(prepared)); + return prepareSessionDetails(agentCommand, details, continuation); } /** @@ -1941,16 +1947,18 @@ function* useAcpxProviderState( prepared: Prepared, intent: EnsureIntent, ): Operation { + const current = managed.get(prepared.sessionKey); if ( - prepared.kind === "existing" && + current && + isLive(current) && intent.build !== undefined && - prepared.entry.runtime.partition !== partitionOf(intent.build) + (prepared.kind === "details" || current.runtime.partition !== partitionOf(intent.build)) ) { // Keep the session slot until the old transport has finished closing, even on halt. const { sessionKey } = prepared; yield* scoped(() => ensure(() => releaseHandle(sessionKey))); if (holding(prepared.sessionKey)) { - throw new Error(`could not release session "${prepared.sessionKey}" to change executables`); + throw new Error(`could not release session "${prepared.sessionKey}" before reopening it`); } prepared = yield* requeried(prepared); } @@ -3205,10 +3213,7 @@ function* useAcpxProviderState( // continues what its predecessor established instead of constructing // a second conversation beside it. const prepared = yield* requeried(resolved); - const state = - prepared.kind === "existing" - ? prepared.entry.state - : yield* sessionCreationState(agentName, ownerCommandOf(prepared), prepared.details); + const state = yield* sessionCreationState(agentName, prepared); // Inside ownership, before the runtime exists and before a turn: a // first Prompt constructs this session through ACP, so that is what // its construction route says — and a session a native process @@ -5222,10 +5227,7 @@ function* useAcpxProviderState( setup, ), ); - const state = - prepared.kind === "existing" - ? prepared.entry.state - : yield* sessionCreationState(agentName, ownerCommandOf(prepared), prepared.details); + const state = yield* sessionCreationState(agentName, prepared); if (setup !== undefined) { // The command is resolved and the construction inputs are settled, and // nothing has been reattached or created yet — which is the only place @@ -5278,19 +5280,20 @@ function* useAcpxProviderState( // before the caller saw the failure, and preserving the route is what // stops that uncertainty from later being reclassified as // client-native. - const construction = yield* constructRoute(agentName, prepared); - const resumeSessionId = construction?.resumeSessionId; return yield* turns.withSlot(prepared.sessionKey, () => withSessionRoute(context, () => scoped(function* (): Operation { + const current = yield* requeried(prepared, prepared.kind === "details"); + const construction = yield* constructRoute(agentName, current); + const resumeSessionId = construction?.resumeSessionId; // Before the ensure that creates it, so nothing this scope takes // outlives the scope — a handle held past this operation is a // second owner of a session a native UI may take. - yield* ensure(() => releaseHandle(prepared.sessionKey)); - const entry = yield* ensureFromPrepared(agentName, prepared, { + yield* ensure(() => releaseHandle(current.sessionKey)); + const entry = yield* ensureFromPrepared(agentName, current, { ...(construction === undefined ? {} : { build: construction.build }), ...(resumeSessionId === undefined ? {} : { attachment: { resumeSessionId } }), - state, + state: yield* sessionCreationState(agentName, current), ...(selectedAgent === undefined ? {} : { resumeFailureStage: "held-session-ensure" }), diff --git a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts index 9bab0284d..3205cb3f1 100644 --- a/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts +++ b/packages/acp/tests/fixtures/claude-native-to-acp-proof.ts @@ -1068,6 +1068,24 @@ function valueOf(invocation: Invocation, flag: string): string | undefined { return index >= 0 ? invocation.argv[index + 1] : undefined; } +export function recordNativeInvocations(observed: Invocation[], verdict: JourneyVerdict): void { + const ui = nativeUiInvocations(observed); + const opening = ui[0]; + if (opening) { + verdict.firstCommand = filtered(opening); + } + const allocated = new Set( + ui + .map((invocation) => valueOf(invocation, "--session-id")) + .filter((value): value is string => typeof value === "string"), + ); + verdict.identityAllocations = allocated.size; + // Nothing after the native launch may start a Claude of its own: an ACP turn + // that spawned one would be a native UI, not an attachment. + verdict.substitutedIdentity = ui.length > 1; + verdict.freshFallback = allocated.size > 1; +} + /** The command shape a verdict may carry: the private path is never in it. */ export function filtered(invocation: Invocation): string[] { const argv = ["claude", ...invocation.argv]; @@ -1472,21 +1490,7 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation typeof entry === "string"); const observed = yield* observedInvocations(journey); - const ui = nativeUiInvocations(observed); - const opening = ui[0]; - if (opening) { - verdict.firstCommand = filtered(opening); - } - const allocated = new Set( - ui - .map((invocation) => valueOf(invocation, "--session-id")) - .filter((value): value is string => typeof value === "string"), - ); - verdict.identityAllocations = allocated.size; - // Nothing after the native launch may start a Claude of its own: an ACP turn - // that spawned one would be a native UI, not an attachment. - verdict.substitutedIdentity = ui.length > 1; - verdict.freshFallback = allocated.size > 1; + recordNativeInvocations(observed, verdict); // The prepared text, held here and nowhere else. It answers the two questions // about where it travelled, and reaches no rendered field. diff --git a/packages/acp/tests/fixtures/claude-proof-evidence.ts b/packages/acp/tests/fixtures/claude-proof-evidence.ts index b6f351d29..c8de4e680 100644 --- a/packages/acp/tests/fixtures/claude-proof-evidence.ts +++ b/packages/acp/tests/fixtures/claude-proof-evidence.ts @@ -12,12 +12,28 @@ import type { AgentSessionRouteStore, AgentSessionRouteV2 } from "../../src/sess import { createAcpxSessionStore } from "../../src/session-store.ts"; export function nativeUiInvocations(invocations: T[]): T[] { - return invocations.filter( - ({ argv }) => - !argv.some((arg) => ["--print", "-p", "--input-format", "--output-format"].includes(arg)) && - ((argv[0] === "--session-id" && argv.includes("--system-prompt-file")) || - (argv[0] === "--resume" && !argv.includes("--session-id"))), - ); + return invocations.filter(({ argv }) => { + const [command, option] = argv; + if (["--version", "-v", "--help", "-h", "help", "--print", "-p"].includes(command ?? "")) { + return false; + } + if ( + (command === "auth" && option === "status") || + (command === "project" && option === "purge") || + ((command === "--output-format" || command === "--input-format") && option === "stream-json") + ) { + return false; + } + // The two headless capability probes put --print *after* their option values. + // A flag-like id or private-file path is still just that option's value. + return !( + (command === "--resume" && argv.length === 3 && argv[2] === "--print") || + (command === "--session-id" && + argv.length === 5 && + argv[2] === "--system-prompt-file" && + argv[4] === "--print") + ); + }); } export function claudeKeyPaths(root: string, agent: string, sessionKey: string): string[] { diff --git a/packages/acp/tests/native-proof.test.ts b/packages/acp/tests/native-proof.test.ts index 6c9f3c775..04f3d2179 100644 --- a/packages/acp/tests/native-proof.test.ts +++ b/packages/acp/tests/native-proof.test.ts @@ -133,22 +133,38 @@ describe("native proof evidence", { sanitizeOps: false, sanitizeResources: false it("P2: both Claude shims distinguish native UI argv from availability and ACP", function* () { const create = ["--session-id", "identity", "--system-prompt-file", "/private/file"]; const resume = ["--resume", "identity"]; - const trace = [ + const unexpected = ["--session-id", "different"]; + const nonUi = [ ["--version"], + ["--help"], + ["auth", "status"], + ["project", "purge", "--dry-run", "project"], ["--print", "--input-format", "stream-json", "--resume", "unrelated"], - create, - resume, - ] + ["--output-format", "stream-json", "--verbose", "--input-format", "stream-json"], + ["--resume", "absent", "--print"], + ["--session-id", "absent", "--system-prompt-file", "/absent", "--print"], + ]; + const commands = [create, ...nonUi, unexpected, [], ["--resume", "--print"], resume]; + const trace = commands .map((args) => ["invocation", ...args.map((arg) => "arg " + arg)].join("\n")) .join("\n"); for (const fixture of [claude, attachment]) { const all = fixture.parseObservations(trace); - expect(all).toHaveLength(4); + expect(all).toHaveLength(commands.length); expect(nativeUiInvocations(all).map(fixture.filtered)).toEqual([ ["claude", "--session-id", "identity", "--system-prompt-file", ""], + ["claude", "--session-id", "different"], + ["claude"], + ["claude", "--resume", "--print"], ["claude", "--resume", "identity"], ]); } + const observed = attachment.parseObservations(trace); + const extra = attachment.blankJourney("native-to-acp"); + attachment.recordNativeInvocations(observed.slice(0, 2 + nonUi.length), extra); + expect(extra.identityAllocations).toBe(2); + expect(extra.substitutedIdentity).toBe(true); + expect(extra.freshFallback).toBe(true); const zero = claude.blankJourney("zero-turn"); zero.nativeSessionId = "identity"; zero.secondInvocationChildren = 1; diff --git a/packages/acp/tests/provider.test.ts b/packages/acp/tests/provider.test.ts index eee8df95b..07f4ddcaa 100644 --- a/packages/acp/tests/provider.test.ts +++ b/packages/acp/tests/provider.test.ts @@ -5,12 +5,15 @@ * no agent process ever starts. */ import { join } from "node:path"; +import { realpath, rename, symlink } from "node:fs/promises"; +import process from "node:process"; +import { hostClaudeExecutable, hostCodexExecutable } from "@executablemd/runtime"; import { readTextFile, rm, writeTextFile } from "@effectionx/fs"; import { createAcpRuntime } from "../src/acpx-runtime.ts"; import { AGENT_SOURCE, STANDARD_AGENT_SOURCE, world } from "./released-peer.ts"; import { describe, it } from "@executablemd/test-support/bdd"; import { expect } from "@executablemd/test-support/expect"; -import { scoped, sleep, spawn, until, useScope, withResolvers } from "effection"; +import { ensure, race, scoped, sleep, spawn, until, useScope, withResolvers } from "effection"; import type { Operation } from "effection"; import { Config } from "@executablemd/core"; import { Agent, claimsConfiguration, sessionOf } from "@executablemd/agent/api"; @@ -58,6 +61,7 @@ import { useGitWorld, } from "./helpers.ts"; import type { + AcpRuntimeEnsureInput, AcpPermissionRequest, AcpRuntimeEvent, AcpRuntimeTurnResult, @@ -3708,3 +3712,284 @@ describe( } }, ); + +/** One public named placement using the diagnostic host's executable selectors and the strict wire peer. */ +function* eagerWorld(agent: "claude" | "codex") { + const peer = yield* world(true); + yield* useFlatWorld(peer.dir); + yield* Agent.around( + { + *agent([name]) { + return name ?? agent; + }, + }, + { at: "min" }, + ); + const variable = agent === "claude" ? "CLAUDE_CODE_EXECUTABLE" : "CODEX_PATH"; + const prior = process.env[variable]; + yield* ensure(() => { + if (prior === undefined) { + delete process.env[variable]; + } else { + process.env[variable] = prior; + } + }); + const first = yield* until(realpath("/usr/bin/true")); + const second = yield* until(realpath("/bin/echo")); + const link = join(peer.dir, "selected"); + yield* until(symlink(first, link)); + process.env[variable] = link; + const events: string[] = []; + const ensures: AcpRuntimeEnsureInput[] = []; + const hooks: { + closeA?: () => Promise; + turn?: () => void; + route?: (phase: "enter" | "leave") => void; + } = {}; + const provider = yield* useAcpxProvider( + { defaultAgent: agent, permissionMode: "deny-all" }, + { + sessionStore: peer.store, + agentRegistry: peer.registry, + advertiseNativeLaunch: [], + advertiseClientNativeAttachment: [], + *withSessionRoute(context, op) { + if (context.session === "review") { + hooks.route?.("enter"); + } + const value = yield* op(); + if (context.session === "review") { + hooks.route?.("leave"); + } + return value; + }, + *agentProcessEnv() { + return { + [variable]: + agent === "claude" ? yield* hostClaudeExecutable() : yield* hostCodexExecutable(), + }; + }, + createRuntime(options) { + const executable = options.agentProcessEnv?.[variable]; + const owner = executable === first ? "A" : executable === second ? "B" : "doctor"; + const runtime = createAcpRuntime({ ...options, agentRegistry: peer.registry }); + const open = runtime.ensureSession.bind(runtime); + runtime.ensureSession = (input) => { + events.push(owner + " ensure"); + ensures.push(input); + return open(input); + }; + const close = runtime.close.bind(runtime); + runtime.close = (input) => { + events.push(owner + " closing"); + const wait = owner === "A" ? hooks.closeA?.() : undefined; + return Promise.resolve(wait) + .then(() => close(input)) + .then(() => { + events.push(owner + " closed"); + }); + }; + const start = runtime.startTurn.bind(runtime); + runtime.startTurn = (input) => { + events.push(owner + " turn"); + hooks.turn?.(); + return start(input); + }; + return runtime; + }, + }, + ); + const issued = yield* provider.session("review"); + function prompt(text: string) { + return scoped(function* () { + const stream = yield* provider.promptStream(text, { session: issued }); + let next = yield* stream.next(); + let output = ""; + while (!next.done) { + if (next.value.type === "text_delta") { + output += next.value.text; + } + next = yield* stream.next(); + } + return output; + }); + } + yield* prompt("marker"); + const original = yield* until(peer.store.load(issued.sessionKey)); + expect(original?.agentSessionId).toBeDefined(); + expect(events).toEqual(["A ensure", "A turn"]); + function* switchExecutable() { + yield* until(symlink(second, link + ".next")); + yield* until(rename(link + ".next", link)); + } + return { peer, issued, provider, prompt, switchExecutable, events, hooks, ensures, original }; +} + +describe( + "eager resolution of a live named Session", + { sanitizeOps: false, sanitizeResources: false }, + () => { + for (const [agent, refusal] of [ + ["codex", undefined], + ["claude", undefined], + ["codex", "close"], + ["claude", "different"], + ] as const) { + it(`Eager: ${agent} ${refusal ?? "reopens"} at the named Session boundary`, function* () { + let cleanup: unknown; + let complete = false; + try { + yield* scoped(function* () { + const f = yield* eagerWorld(agent); + yield* f.switchExecutable(); + const trace = join(f.peer.dir, "methods.jsonl"); + const before = yield* readTextFile(trace); + if (refusal === "close") { + f.hooks.closeA = () => { + delete f.hooks.closeA; + return Promise.reject(new Error("eager close rejected")); + }; + } else if (refusal === "different") { + yield* writeTextFile(join(f.peer.dir, "different-native-identity"), "1"); + } + let resolved: Session | undefined; + let caught: unknown; + try { + resolved = yield* f.provider.session("review"); + } catch (error) { + caught = error; + } + const delta = (yield* readTextFile(trace)).slice(before.length).trim(); + if (refusal === "close") { + expect(caught).toBeInstanceOf(Error); + expect(resolved).toBe(undefined); + expect(delta).toBe(""); + expect(f.events).toEqual([ + "A ensure", + "A turn", + "A closing", + "A closing", + "A closed", + ]); + } else { + expect(JSON.parse(delta)).toMatchObject({ + method: "session/load", + sessionId: f.original?.acpSessionId, + }); + expect(f.ensures[1]).toMatchObject({ + sessionKey: f.issued.sessionKey, + resumeSessionId: f.original?.acpSessionId, + expectedAgentSessionId: f.original?.agentSessionId, + }); + if (refusal === "different") { + expect(caught).toBeInstanceOf(Error); + expect(resolved).toBe(undefined); + expect(f.events).toEqual([ + "A ensure", + "A turn", + "A closing", + "A closed", + "B ensure", + ]); + expect((yield* until(f.peer.store.load(f.issued.sessionKey)))?.agentSessionId).toBe( + f.original?.agentSessionId, + ); + yield* rm(join(f.peer.dir, "different-native-identity")); + resolved = yield* f.provider.session("review"); + } else { + if (caught) { + throw caught; + } + expect(f.events).toEqual([ + "A ensure", + "A turn", + "A closing", + "A closed", + "B ensure", + "B closing", + "B closed", + ]); + } + expect(resolved).toBe(f.issued); + } + expect(f.issued.agentSessionId).toBe(f.original?.agentSessionId); + expect(yield* f.prompt("recall")).toContain("answer:recall:marker"); + complete = true; + }); + } catch (error) { + cleanup = error; + } + if (refusal === "close" && complete) { + expect(String(cleanup)).toContain("eager close rejected"); + } else if (cleanup) { + throw cleanup; + } + expect(complete).toBe(true); + }); + } + + it("Eager: the queued Codex lookup joins the old close when halted", function* () { + const f = yield* eagerWorld("codex"); + const turnStarted = withResolvers(); + const closing = withResolvers(); + const release = withResolvers(); + const scope = yield* useScope(); + f.hooks.turn = turnStarted.resolve; + yield* writeTextFile(join(f.peer.dir, "hold-prompt"), "1"); + const busy = yield* spawn(() => f.prompt("recall")); + yield* turnStarted.operation; + yield* f.switchExecutable(); + const placed = withResolvers(); + f.hooks.route = (phase) => { + if (phase === "leave") { + placed.resolve(); + } + }; + f.hooks.closeA = () => { + closing.resolve("closing"); + return scope.run(() => release.operation); + }; + const returned = withResolvers(); + const eager = yield* spawn(function* () { + yield* f.provider.session("review"); + returned.resolve("returned"); + }); + yield* placed.operation; + expect(f.events).toEqual(["A ensure", "A turn", "A turn"]); + yield* writeTextFile(join(f.peer.dir, "release-prompt"), "1"); + yield* busy; + try { + expect(yield* race([closing.operation, returned.operation])).toBe("closing"); + const halted = yield* spawn(() => eager.halt()); + const waiting = withResolvers(); + let enters = 0; + f.hooks.route = (phase) => { + if (phase === "leave") { + waiting.resolve(); + } else if (++enters === 2) { + f.events.push("retry holds slot"); + } + }; + const retry = yield* spawn(() => f.provider.session("review")); + yield* waiting.operation; + expect(f.events).toEqual(["A ensure", "A turn", "A turn", "A closing"]); + release.resolve(); + yield* halted; + expect(yield* retry).toBe(f.issued); + expect(f.events).toEqual([ + "A ensure", + "A turn", + "A turn", + "A closing", + "A closed", + "retry holds slot", + "B ensure", + "B closing", + "B closed", + ]); + } finally { + release.resolve(); + } + }); + }, +);