diff --git a/architecture.md b/architecture.md
index beeeb340f..43a8d694b 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 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, 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 continuation.
### Cancellation and attachment
diff --git a/packages/acp/src/ClaudeNativeLaunch.test.md b/packages/acp/src/ClaudeNativeLaunch.test.md
index 717240272..bb2deb84c 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
@@ -280,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 b80008aff..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" },
@@ -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,49 +294,52 @@ 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
-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 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 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 c4fcfb706..9685fe5f6 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,23 @@ 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. XMD can refuse during preflight before launching the second UI. A refusal from the UI itself still requires the exact resume command.
"]}
/>
+
+
+
+
+
+
## The instruction layer travelled privately
@@ -300,14 +312,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..c21f38485 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,24 +281,17 @@ 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.
-
-
-
-
@@ -399,16 +395,16 @@ inconvenient.
## Route and journal agree
-The route names the construction and the Codex build the tuple above froze, and
-nothing else: an ACP-first route deliberately records no conversation identity,
-launcher or instruction layer, so those are read from the journal instead. A
+The route names the construction and nothing else: a fresh ACP-first route
+records no conversation identity, launcher, instruction layer or executable
+build, so the identity and instructions are read from the journal instead. A
route that had converted to anything but `acp-first` would mean the launch
stopped being the one this document describes.
-
-
+
+
diff --git a/packages/acp/src/CodexZeroNativeTurnExit.test.md b/packages/acp/src/CodexZeroNativeTurnExit.test.md
index 73b706bac..fad25d6ee 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,24 +256,17 @@ 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.
-
-
-
-
@@ -362,16 +357,16 @@ inconvenient.
## Route and journal agree
-The route names the construction and the Codex build the tuple above froze, and
-nothing else: an ACP-first route deliberately records no conversation identity,
-launcher or instruction layer, so those are read from the journal instead. A
+The route names the construction and nothing else: a fresh ACP-first route
+records no conversation identity, launcher, instruction layer or executable
+build, so the identity and instructions are read from the journal instead. A
route that had converted to anything but `acp-first` would mean the launch
stopped being the one this document describes.
-
-
+
+
@@ -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.
line.trim())
@@ -170,12 +163,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 +177,16 @@ 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 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 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 +197,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 +206,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. 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;
@@ -287,8 +278,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 +317,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 +327,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..cf02792b7 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,7 +133,6 @@ import {
AgentSessionBusy,
AgentSessionRecoveryRequired,
cwd,
- ExecutableObservationError,
nativeLaunch,
notifyTerminal,
} from "@executablemd/runtime";
@@ -146,7 +141,6 @@ import type {
AgentSessionKey,
AgentSessionOwnerKind,
AgentSessionOwnership,
- ExecutableObserver,
} from "@executablemd/runtime";
import {
ADVERTISED_CLIENT_NATIVE_ATTACHMENT,
@@ -320,19 +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. 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.
- *
- * Absent means this host cannot say which build it would run, so an agent
- * whose sessions XMD names refuses before any provider effect.
- */
- 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,18 +394,19 @@ export interface AcpxProviderDependencies {
}
/**
- * One observed build, ready to be bound to a session.
+ * The executable one live operation selected.
*
- * `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 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;
- livePath: string;
+ livePath: string | undefined;
environment: Record;
/** The exact ACP adapter command this binding was proven against, if pinned. */
adapterCommand: string | undefined;
@@ -434,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.
*/
@@ -670,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. */
@@ -699,6 +681,23 @@ 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;
+ /**
+ * 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;
}
/**
@@ -1155,7 +1154,6 @@ 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;
@@ -1198,12 +1196,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();
@@ -1302,14 +1299,18 @@ 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: two selections never
+ * share a child, and the same selection reached twice does.
+ */
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",
+ );
}
/**
@@ -1626,8 +1627,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.
@@ -1695,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 };
@@ -1826,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";
}
@@ -1846,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));
@@ -1860,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);
}
/**
@@ -1906,7 +1913,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
@@ -1915,8 +1922,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";
/**
@@ -1942,6 +1947,21 @@ function* useAcpxProviderState(
prepared: Prepared,
intent: EnsureIntent,
): Operation {
+ const current = managed.get(prepared.sessionKey);
+ if (
+ current &&
+ isLive(current) &&
+ intent.build !== undefined &&
+ (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}" before reopening it`);
+ }
+ prepared = yield* requeried(prepared);
+ }
if (newSessionOptions?.disallowedTools !== undefined) {
const launchOptionsRecord = yield* until(store.load(prepared.sessionKey));
if (launchOptionsRecord !== undefined) {
@@ -1978,17 +1998,41 @@ 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 ||
+ (attachment === undefined &&
+ intent.state === "existing" &&
+ intent.build !== undefined &&
+ held?.session.agentSessionId !== 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 +2093,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 +2143,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 +2181,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 +2214,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 +2223,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.
*
@@ -2271,14 +2369,14 @@ function* useAcpxProviderState(
}
/**
- * Whether this agent's sessions carry a construction route and one build.
+ * Whether this agent's sessions carry a construction route and a selected
+ * executable.
*
- * The two facts arrive together and for the same reason. A route says how the
- * session was first constructed, and for an adapter that pins a build the
- * build is part of that account: whichever side chose the identity, the name
- * resolves to one conversation only beside the build that issued or accepted
- * it. An agent whose adapter binds nothing keeps its merged behavior, on a
- * host that installs neither.
+ * An advertised adapter that carries an executable binding has its
+ * executable selected by this host, and whichever side chose the identity,
+ * the route is what says how the session was first constructed. An agent
+ * whose adapter binds nothing keeps its merged behavior, on a host that
+ * installs no route store.
*/
function boundSessions(agentName: string): boolean {
const adapter = adapterFor(agentName);
@@ -2289,10 +2387,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 +2405,6 @@ function* useAcpxProviderState(
if (!routeStore) {
missing.push("construction routes");
}
- if (!executableObserver) {
- missing.push("executable build observation");
- }
}
if (missing.length === 0) {
return;
@@ -2376,104 +2472,85 @@ 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,
- };
- }
-
- /**
- * Publish or adopt `acp-first` for an agent whose sessions XMD would
- * otherwise name, and refuse if this session already has an identity.
- *
- * 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.
+ * Select the executable one live operation runs.
*
- * 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.
+ * 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* 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 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`,
- });
+ let environment: Record = {};
+ let livePath: string | undefined;
+ if (dependencies?.agentProcessEnv !== undefined) {
+ let selected: Record | undefined;
+ try {
+ selected = yield* dependencies.agentProcessEnv(agentName, agentCommand);
+ } catch (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);
+ }
}
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,
};
}
- /** The stable comparison two builds of one session fail. */
- function buildDrift(
- sessionKey: string,
- retained: ExecutableBuildBindingV1,
- live: ExecutableBuildBindingV1,
- ): LaunchFailure {
- 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 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;
+ }
+
+ /**
+ * 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 } };
}
/**
@@ -2487,7 +2564,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 +2582,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 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,
@@ -2527,9 +2598,8 @@ function* useAcpxProviderState(
adapter: BoundProviderReturnedAdapter,
sessionKey: 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 +2607,7 @@ function* useAcpxProviderState(
sessionKey,
// deno-lint-ignore require-yield
function* () {
- return boundAcpFirstRoute(routeCommand, sessionKey, build.binding);
+ return acpFirstRoute(routeCommand, sessionKey);
},
hasProviderState,
);
@@ -2552,31 +2622,18 @@ 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 };
+ return {
+ build,
+ ...("executableBinding" in route ? { history: route.executableBinding } : {}),
+ };
}
/** 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 binding the route recorded as its original history, if any. */
+ history?: ExecutableBuildBindingV1;
/**
* The exact conversation ACP must open rather than create.
*
@@ -2585,7 +2642,6 @@ function* useAcpxProviderState(
* a name supplied here would be XMD choosing one after the fact.
*/
resumeSessionId?: string;
- verifyReopening?: boolean;
}
/**
@@ -2593,32 +2649,34 @@ 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. 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);
+ if (!ownable(agentName)) {
+ 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.
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,
@@ -2626,9 +2684,9 @@ function* useAcpxProviderState(
adapter,
prepared.sessionKey,
constructed,
- agentName === "codex" && prepared.kind === "details" && prepared.continuation !== undefined,
);
}
+ const build = yield* selectBuild(agentName, agentCommand, adapter.binding);
const route = yield* reconcileRoute(
routeCommand,
prepared.sessionKey,
@@ -2639,19 +2697,7 @@ function* useAcpxProviderState(
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 .`,
- });
+ return { build };
}
if (!attachable(agentName)) {
throw new AttachmentRefused({
@@ -2662,12 +2708,6 @@ 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);
return { build, resumeSessionId: route.nativeSessionId };
}
@@ -3173,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
@@ -3186,9 +3223,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,14 +3316,6 @@ function* useAcpxProviderState(
requestId,
host: promptUsageHost,
...adapterUsageBuild(agentName, agentCommandOf(prepared)),
- ...(construction?.build === undefined
- ? {}
- : {
- native: {
- version: construction.build.binding.reportedVersion,
- digest: `${construction.build.binding.executableDigest.algorithm}:${construction.build.binding.executableDigest.value}`,
- },
- }),
});
let completed = false;
yield* ensure(function* () {
@@ -3501,40 +3528,53 @@ 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.
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") {
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,11 +3585,12 @@ 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. A fresh route records
+ // the facts the session needs and no executable history.
let winner: AgentSessionRoute;
try {
winner = yield* routeStore!.publish({
- schema: "session-route.v2",
+ schema: "session-route.v1",
route: "client-native",
provider: ACPX_PROVIDER,
agent: agentCommand,
@@ -3558,7 +3599,6 @@ function* useAcpxProviderState(
identityProvenance: "client-allocated",
instructionsDigest,
launcher: adapter.launcher,
- executableBinding: build.binding,
});
} catch (error) {
return refusal("identity-unavailable", routeMessage(error), known);
@@ -3579,17 +3619,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 +3626,20 @@ function* useAcpxProviderState(
const fresh = winner.nativeSessionId === candidate;
invocation.fresh.set(sessionKey, fresh);
invocation.bound.set(sessionKey, { build, adapter });
+ 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,
@@ -3749,15 +3792,15 @@ 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)) {
try {
- ({ build } = yield* bindProviderNamed(
+ ({ build, history } = yield* bindProviderNamed(
agentName,
agentCommand,
agentCommand,
@@ -3773,11 +3816,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 +3857,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 +3875,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 +3975,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;
@@ -3924,7 +4013,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;
@@ -3944,7 +4034,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 +4044,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);
@@ -3963,6 +4062,195 @@ 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;
+ }
+
+ /**
+ * 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;
}
/**
@@ -4048,6 +4336,7 @@ function* useAcpxProviderState(
* nothing else.
*/
function materializeSession(
+ invocation: LaunchInvocation,
resolved: Prepared,
prepared: PreparedLaunchRecord,
plan: MaterializationPlan,
@@ -4262,6 +4551,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 ` +
@@ -4335,7 +4627,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 };
}
@@ -4409,6 +4703,8 @@ function* useAcpxProviderState(
detachedLive: new Set(),
reconciled: new Set(),
configured: new Set(),
+ confirmed: new Set(),
+ route: (op) => withSessionRoute(context, op),
};
try {
@@ -4438,7 +4734,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 +4780,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 +4795,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 +4807,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 +4839,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 +4858,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 +4873,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 +4885,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 +4900,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 +4907,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 +4923,28 @@ 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);
- }
invocation.bound.set(prepared.sessionKey, { build, adapter });
return undefined;
}
@@ -4679,18 +4967,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() };
@@ -4703,11 +4991,13 @@ 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 };
}
- let resolved: Result;
+ let resolved: Result<{ argv: string[]; creating: boolean }>;
try {
resolved = yield* nativeCommand(invocation, prepared, adapter, agentCommand);
} catch {
@@ -4723,23 +5013,77 @@ 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* invocation.route(() =>
+ 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* invocation.route(() =>
+ 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. */
@@ -4883,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
@@ -4939,21 +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, {
- ...(construction === undefined
- ? {}
- : { build: construction.build, verifyReopening: construction.verifyReopening }),
+ 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/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..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";
@@ -58,9 +64,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.
*
@@ -320,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.
*
@@ -839,7 +757,7 @@ interface JourneyVerdict {
privateStateInspected: boolean;
}
-function blankJourney(mode: Mode): JourneyVerdict {
+export function blankJourney(mode: Mode): JourneyVerdict {
return {
mode,
verdict: "HARNESS_FAILED",
@@ -920,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.
@@ -972,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")) {
@@ -1001,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) {
@@ -1252,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) {
@@ -1304,7 +1214,7 @@ function* invoke(
},
);
- outcome.children = (yield* observedInvocations(journey)).length - before;
+ outcome.children = nativeUiInvocations(yield* observedInvocations(journey)).length - before;
return outcome;
}
@@ -1401,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);
}
@@ -1410,7 +1321,7 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation valueOf(invocation, "--session-id"))
.filter((value): value is string => typeof value === "string"),
);
@@ -1440,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")));
@@ -1487,26 +1398,34 @@ 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";
return false;
}
- 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;
- }
+ // 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.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";
@@ -1598,7 +1517,18 @@ 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
+ // journal — the same exact-identity refusal, said one step earlier.
+ if (
+ verdict.outcome === "unresolved" &&
+ verdict.secondInvocationChildren === 0 &&
+ verdict.journal.failureClasses.includes("identity-unavailable")
+ ) {
+ verdict.outcome = "no-session";
+ }
if (!ZERO_TURN_ACCEPTED.includes(verdict.outcome)) {
verdict.verdict = "PRODUCT_FAILED";
verdict.detail = "re-entry was neither the same identity nor an explicit refusal";
@@ -1613,10 +1543,10 @@ function decideZeroTurn(verdict: JourneyVerdict): void {
verdict.detail =
verdict.outcome === "same-identity"
? "re-entry reached its conversation surface under the exact retained identity"
- : "re-entry refused the exact retained identity, and XMD failed closed";
+ : "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";
@@ -1738,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: "",
@@ -1773,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: "",
@@ -1799,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 {
@@ -1822,18 +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 === REQUIRED_CLAUDE_VERSION &&
- verdict.platform === "darwin" &&
- verdict.architecture === "arm64" &&
!verdict.claudeConfigDirSet &&
verdict.sessionIdFlag &&
verdict.systemPromptFileFlag &&
@@ -1842,12 +1770,11 @@ 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 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;
}
@@ -1855,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") {
@@ -1882,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 f70e6656d..3205cb3f1 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;
@@ -856,11 +862,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: {
@@ -875,7 +886,7 @@ interface JourneyVerdict {
privateStateInspected: boolean;
}
-function blankJourney(mode: Mode): JourneyVerdict {
+export function blankJourney(mode: Mode): JourneyVerdict {
return {
mode,
verdict: "HARNESS_FAILED",
@@ -913,7 +924,7 @@ function blankJourney(mode: Mode): JourneyVerdict {
consentInputBytes: "",
consentSurfaces: [],
exitControlBytes: "",
- adapterCommand: "",
+ adapterIdentity: "",
inheritedAgentMarkersRemoved: 0,
markerStored: false,
markerRecovered: false,
@@ -943,7 +954,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,
@@ -970,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.
@@ -992,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`);
}
/**
@@ -1037,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")) {
@@ -1065,8 +1068,26 @@ 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. */
-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) {
@@ -1330,7 +1351,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;
@@ -1372,7 +1393,7 @@ function* invoke(
},
);
- outcome.children = (yield* observedInvocations(journey)).length - before;
+ outcome.children = nativeUiInvocations(yield* observedInvocations(journey)).length - before;
return outcome;
}
@@ -1469,20 +1490,7 @@ function* settleAccounts(journey: Journey, verdict: JourneyVerdict): Operation typeof entry === "string");
const observed = yield* observedInvocations(journey);
- const opening = observed[0];
- if (opening) {
- verdict.firstCommand = filtered(opening);
- }
- const allocated = new Set(
- observed
- .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.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.
@@ -1501,11 +1509,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")));
@@ -1526,13 +1534,10 @@ 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() : "";
-}
-
/** 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";
@@ -1620,10 +1622,10 @@ function* runAttachment(
verdict: JourneyVerdict,
marker: string,
): Operation {
- if (!(yield* ready(journey, verdict))) {
+ if (!ready(journey, verdict)) {
return;
}
- verdict.adapterCommand = boundAdapterCommand();
+ verdict.adapterIdentity = adapters.identity("claude");
verdict.acpDocumentCarriesMarker = (yield* until(readFile(ACP_DOCUMENT, "utf8"))).includes(
marker,
);
@@ -1659,7 +1661,7 @@ function* runAttachment(
// The second command: the checked-in document, verbatim, through the same
// built binary in the same directory. No terminal, no consent, no native
// child — an ordinary ACP turn against the session the native process made.
- const before = (yield* observedInvocations(journey)).length;
+ const before = nativeUiInvocations(yield* observedInvocations(journey)).length;
const acp = yield* bounded("acp-prompt", ANSWER_MS, () =>
runChild(XMD_BINARY, xmdArguments(ACP_DOCUMENT, journey.journals[1]), {
cwd: journey.project,
@@ -1669,45 +1671,34 @@ 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.
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.
- 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. */
-function boundAdapterCommand(): string {
- const adapter = nativeAdapterFor("claude");
- if (!adapter || !allocatesIdentity(adapter)) {
- return "";
- }
- 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 };
}
/**
@@ -1723,35 +1714,18 @@ function* observeBuild(journey: Journey): Operation<{ version: string; digest: s
* 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);
- 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 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: observed.version,
- executableDigest: { algorithm: "sha256", value: observed.digest },
- },
- });
-
- 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,
@@ -1761,8 +1735,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);
@@ -1793,13 +1768,13 @@ 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 "";
}
-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";
@@ -1826,14 +1801,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) {
@@ -1848,8 +1821,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";
}
/**
@@ -1921,7 +1894,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.
@@ -1939,4 +1912,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..c8de4e680
--- /dev/null
+++ b/packages/acp/tests/fixtures/claude-proof-evidence.ts
@@ -0,0 +1,114 @@
+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 }) => {
+ 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[] {
+ 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 e3cf04a0b..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 {
@@ -88,20 +90,17 @@ 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";
+const REQUIRED_ADAPTER_DIGEST = "a3f699537970127972635b4596aef40ab8a4caa25a9028861d9ee07bf6c4b1a1";
/** The one prompt version a Codex launch may spend a turn on. */
const PROMPT_VERSION = "codex-materialization.v1";
@@ -340,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.
*
@@ -915,7 +832,7 @@ interface JourneyVerdict {
privateStateInspected: boolean;
}
-function blankJourney(mode: Mode): JourneyVerdict {
+export function blankJourney(mode: Mode): JourneyVerdict {
return {
mode,
verdict: "UNDECIDED",
@@ -1649,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.
@@ -1689,19 +1639,12 @@ 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.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;
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) {
@@ -2184,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: "",
@@ -2222,56 +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.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;
+ 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 &&
@@ -2279,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 =
@@ -2295,8 +2222,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;
}
@@ -2304,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") {
@@ -2331,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/helpers.ts b/packages/acp/tests/helpers.ts
index 1c7a98f7c..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;
@@ -400,7 +396,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 +409,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 } };
+ // 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 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;
- }
- 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 +705,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..dccb01d4e 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,
@@ -61,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,
@@ -246,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
? {}
@@ -1325,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;
}
@@ -1333,14 +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" : "scribe 1.0.0\n",
- });
+ const selection = createFakeSelection(`/opt/builds/${agent}`);
return {
store,
ownership,
runtime,
- observer,
+ selection,
installation(command) {
return {
*install() {
@@ -1357,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",
@@ -1506,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 }),
@@ -1574,7 +1573,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 +1593,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 +1604,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 +1742,251 @@ describe(
},
);
+/** 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 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 variable = SELECTED[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?.route !== "acp-first") {
+ 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.",
- },
+ // 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.selection.path = `/opt/builds/${agent}-next`;
+ 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({
+ [variable]: `/opt/builds/${agent}-next`,
+ });
+ // Continuation is quiet: the executable changing is not news.
+ expect(warned).toEqual([]);
+ 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..b0b054a5e 100644
--- a/packages/acp/tests/native-launch.test.ts
+++ b/packages/acp/tests/native-launch.test.ts
@@ -61,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,
@@ -72,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";
@@ -173,14 +172,14 @@ 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";
/** Everything the launch touched, in the order it touched it. */
@@ -219,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;
/**
@@ -439,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 } : {}),
@@ -808,6 +815,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 +824,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 +1022,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* () {
@@ -1768,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,
@@ -1780,12 +1799,23 @@ 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.
- 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 +1969,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 +1986,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 +2298,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 +2976,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([]);
});
});
@@ -2898,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);
@@ -2918,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. */
@@ -2934,10 +3099,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 +3114,17 @@ 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 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: 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 +3137,31 @@ 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.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.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 +3181,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,63 +3217,66 @@ 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* () {
- 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 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(space.harness.createdOptions.at(-1)?.agentProcessEnv ?? {}).toEqual({});
});
- it("CA5: a build this run cannot name, or cannot reach, refuses before ensure", function* () {
- for (const [name, mutate] of [
- [
- "another build at the same command",
- (observer: FakeObserverHarness) => {
- observer.observation.digest = "b".repeat(64);
- },
- ],
- [
- "another version of the same bytes",
- (observer: FakeObserverHarness) => {
- observer.observation.versionOutput = "2.1.242 (Claude Code)\n";
- },
- ],
- [
- "output this adapter does not recognize",
- (observer: FakeObserverHarness) => {
- observer.observation.versionOutput = "claude version 2.1.241\n";
- },
- ],
- [
- "an executable that could not be observed at all",
- (observer: FakeObserverHarness) => {
- observer.failure = "not-executable";
- },
- ],
- ] 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 observer = createFakeObserver();
- mutate(observer);
- 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]);
+ const selection = createFakeSelection(path);
+ const space = yield* installAttachment(bound(), { selection });
+
+ const session = yield* Agent.operations.session();
+
+ expect([path, session.agentSessionId]).toEqual([path, ALLOCATED]);
+ expect([path, space.harness.ensureCalls.map((call) => call.resumeSessionId)]).toEqual([
+ path,
+ [ALLOCATED],
+ ]);
+ 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([path, yield* space.routes.read(KEY)]).toEqual([path, bound()]);
});
}
});
+ 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();
+
+ 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();
@@ -3145,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
@@ -3173,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,
@@ -3313,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();
@@ -3342,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,
@@ -3357,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);
@@ -3385,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(
@@ -3439,36 +3622,14 @@ 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.
- 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();
-
- expect(raised?.message).toContain("does not recognize");
- // 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(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 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]);
// The route is left exactly as it was: not upgraded, not supplemented.
expect(yield* space.routes.read(KEY)).toEqual(legacy());
});
@@ -3558,50 +3719,46 @@ 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);
});
- 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();
- 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, a different build behind it, and a route that names
- // the old one: the attachment refuses rather than reusing the child.
- 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;
- }
+ // The same command and a different file behind it. The same conversation
+ // continues, and it does so through a child of its own.
+ selection.path = "/opt/builds/other-claude";
+ 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* () {
@@ -3617,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();
@@ -3647,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");
@@ -3657,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();
@@ -3717,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");
@@ -3726,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,
});
@@ -3767,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");
@@ -3779,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();
@@ -3843,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");
@@ -3856,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,
});
@@ -4022,54 +4176,69 @@ 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();
+ 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);
- // 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();
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 };
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 +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, route or observer", function* () {
+ it("AO1: an ACP-only Claude prompt touches no coordinator or route", function* () {
const touched: string[] = [];
const harness = createFakeRuntime();
const trace = newTrace();
@@ -4122,13 +4291,6 @@ describe("Tier AO — explicit ACP-only capability", () => {
return candidate;
},
},
- executableObserver: {
- // deno-lint-ignore require-yield
- *observe() {
- touched.push("observer");
- throw new Error("this profile observes no build");
- },
- },
});
yield* scoped(function* () {
@@ -4145,7 +4307,8 @@ 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([]);
});
@@ -4233,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,
@@ -4249,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();
@@ -4268,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([]);
});
@@ -4282,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);
@@ -4317,36 +4491,82 @@ describe("Tier BA — bound ACP-first construction", () => {
}
});
- it("BA4: a drifted build refuses before ACP is asked for anything", 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* installBound(harness, trace, { routeStore: routes });
+ 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();
- // Another build of the same provider, which 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),
- });
+ const selection = createFakeSelection("/opt/builds/claude-next");
yield* scoped(function* () {
- yield* installBound(drifted, second, { routeStore: routes, observer: observer.observer });
+ yield* installBound(drifted, second, {
+ routeStore: routes,
+ store,
+ selection,
+ });
const refusal = yield* attempt(second, INSTRUCTIONS);
- expect(refusal?.class).toBe("executable-binding-refused");
+ expect(refusal).toBe(undefined);
});
- // 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 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);
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 +4577,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);
});
@@ -4391,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* () {
@@ -4838,29 +5070,30 @@ 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,
- observer: createFakeObserver({
- versionOutput: "2.1.242 (Claude Code)\n",
- digest: "b".repeat(64),
- }).observer,
+ store,
+ selection: createFakeSelection("/opt/builds/claude-next"),
});
- 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
@@ -5392,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 = {
@@ -5425,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]);
@@ -5445,22 +5678,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 with original history 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),
- });
+ 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 = {
@@ -5471,13 +5699,20 @@ 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);
+ // 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,12 +5814,86 @@ 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([]);
});
});
+ 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,
+ selection: createFakeSelection("/opt/builds/codex"),
+ });
+ 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();
@@ -5598,10 +5907,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/native-proof.test.ts b/packages/acp/tests/native-proof.test.ts
new file mode 100644
index 000000000..04f3d2179
--- /dev/null
+++ b/packages/acp/tests/native-proof.test.ts
@@ -0,0 +1,310 @@
+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 unexpected = ["--session-id", "different"];
+ const nonUi = [
+ ["--version"],
+ ["--help"],
+ ["auth", "status"],
+ ["project", "purge", "--dry-run", "project"],
+ ["--print", "--input-format", "stream-json", "--resume", "unrelated"],
+ ["--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(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;
+ 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..07f4ddcaa 100644
--- a/packages/acp/tests/provider.test.ts
+++ b/packages/acp/tests/provider.test.ts
@@ -4,9 +4,16 @@
* Drives the provider through its dependencies with a scriptable fake runtime:
* 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, 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";
@@ -54,6 +61,7 @@ import {
useGitWorld,
} from "./helpers.ts";
import type {
+ AcpRuntimeEnsureInput,
AcpPermissionRequest,
AcpRuntimeEvent,
AcpRuntimeTurnResult,
@@ -3553,3 +3561,435 @@ 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);
+ });
+ }
+ },
+);
+
+/** 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();
+ }
+ });
+ },
+);
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..afa3f46de 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.
+ * 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,
@@ -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,
@@ -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 e542e684c..743027e45 100644
--- a/packages/cli/src/agent-stack.ts
+++ b/packages/cli/src/agent-stack.ts
@@ -158,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/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/session-coordinator.ts b/packages/cli/src/session-coordinator.ts
index bbc5ba78e..554836f0e 100644
--- a/packages/cli/src/session-coordinator.ts
+++ b/packages/cli/src/session-coordinator.ts
@@ -14,11 +14,10 @@
*/
import { homedir } from "node:os";
import { join } from "node:path";
-import { createDenoAgentSessionHost, createDenoExecutableObserver } from "@executablemd/runtime";
+import { createDenoAgentSessionHost } from "@executablemd/runtime";
import type {
AgentSessionCoordinator,
AgentSessionOwnershipAdministration,
- ExecutableObserver,
} from "@executablemd/runtime";
import {
ADVERTISED_CLIENT_NATIVE_ATTACHMENT,
@@ -45,7 +44,6 @@ export interface MachineSessionAssembly {
coordinator?: AgentSessionCoordinator;
ownershipAdministration?: AgentSessionOwnershipAdministration;
routeStore?: AgentSessionRouteStore;
- executableObserver?: ExecutableObserver;
advertiseNativeLaunch: readonly string[];
advertiseClientNativeAttachment: readonly string[];
/** What this host states about its own build, for the Prompt usage its turns retain. */
@@ -65,18 +63,6 @@ export function useSessionRouteStore(): AgentSessionRouteStore | undefined {
return createDenoSessionRouteStore(sessionCoordinatorRoot());
}
-/**
- * How this host observes which build of an agent executable it would run.
- *
- * Built here, beside the coordinator, and handed straight to the provider. It
- * is 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.
- */
-export function useExecutableObserver(): ExecutableObserver | undefined {
- return createDenoExecutableObserver();
-}
-
/**
* The ordinary `xmd run` profile: this machine's sessions, and the adapters
* proven against the installed CLI.
@@ -84,13 +70,11 @@ export function useExecutableObserver(): ExecutableObserver | undefined {
export function useMachineSessions(): MachineSessionAssembly {
const host = createDenoAgentSessionHost(sessionCoordinatorRoot());
const routeStore = useSessionRouteStore();
- const executableObserver = useExecutableObserver();
return {
...(host
? { coordinator: host.coordinator, ownershipAdministration: host.ownershipAdministration }
: {}),
...(routeStore ? { routeStore } : {}),
- ...(executableObserver ? { executableObserver } : {}),
advertiseNativeLaunch: ADVERTISED_NATIVE_LAUNCH,
advertiseClientNativeAttachment: ADVERTISED_CLIENT_NATIVE_ATTACHMENT,
};
diff --git a/packages/cli/src/workflow-agent.ts b/packages/cli/src/workflow-agent.ts
index 84542859b..bdf5276bf 100644
--- a/packages/cli/src/workflow-agent.ts
+++ b/packages/cli/src/workflow-agent.ts
@@ -442,10 +442,10 @@ export function* useWorkflowAgentProfile(options: WorkflowAgentProfileOptions):
// 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
- // advertised sets by omission would make a workflow Claude prompt demand
- // ownership and a route that this profile has no way to give it.
+ // 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.
advertiseNativeLaunch: [],
advertiseClientNativeAttachment: [],
// The Workspace root is a logical path, not a directory an agent process
diff --git a/packages/cli/tests/adversarial-session-continuity.test.ts b/packages/cli/tests/adversarial-session-continuity.test.ts
index 8206ba899..743e3c3c7 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,44 @@ function* guardPeer(source = STANDARD_AGENT_SOURCE, cwd?: string) {
strong?: boolean;
guard?: boolean;
receiptDirectory?: string;
+ /** A carried agent, run through this host-selected executable, in its own invocation. */
+ agent?: "codex" | "claude";
+ executable?: 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
+ ? {}
+ : {
+ // 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}`,
+ };
+ },
+ }),
...(options.strong
? {
nativeAdapters: {
@@ -145,7 +170,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 +199,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 +219,83 @@ 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 },
+ () => {
+ for (const agent of ["codex", "claude"] as const) {
+ 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, executable: 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,
+ executable: after,
+ });
+ expect(continued.result.ok).toBe(true);
+ // 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);
+ // 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);
+ 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"),
+ );
+
+ // 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,
+ executable: 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,
+ executable: 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/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/session-compatibility.test.ts b/packages/cli/tests/session-compatibility.test.ts
new file mode 100644
index 000000000..5df4a731d
--- /dev/null
+++ b/packages/cli/tests/session-compatibility.test.ts
@@ -0,0 +1,307 @@
+/**
+ * Session continuation across agent CLI releases (#891).
+ *
+ * The production provider, installed the way a host installs it, over a
+ * 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 { 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 {
+ createFakeRuntime,
+ createFakeSelection,
+ makeCoordinator,
+ makeRegistry,
+ makeStore,
+ useFlatWorld,
+} from "../../acp/tests/helpers.ts";
+import type {
+ CoordinatorHarness,
+ FakeRuntimeHarness,
+ FakeSelectionHarness,
+} from "../../acp/tests/helpers.ts";
+import { ADAPTERS } from "./support/plan-harness.ts";
+
+const CWD = "/work";
+
+/** The selector variable and registered command for each supported product. */
+const PRODUCTS = {
+ codex: { variable: "CODEX_PATH", command: "codex-cmd" },
+ claude: { 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 selection: FakeSelectionHarness;
+}
+
+function machine(product: Product): Machine {
+ return {
+ store: makeStore(),
+ routes: createMemorySessionRouteStore(),
+ ownership: makeCoordinator(),
+ selection: createFakeSelection(`/selected/${product}-0.167.1`),
+ };
+}
+
+/** Every line this scope's operations wrote to standard error. */
+function* stderr(): 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;
+}
+
+let provider: AcpxProvider | undefined;
+
+/**
+ * Install one provider for `product` over this host's state, as the CLI does:
+ * the built-in adapter and the host's own selection.
+ */
+function* install(
+ product: Product,
+ host: Machine,
+ harness: FakeRuntimeHarness,
+ extra: Partial = {},
+): Operation {
+ // 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]: PRODUCTS[product].command }),
+ coordinator: host.ownership.coordinator,
+ routeStore: host.routes,
+ advertiseNativeLaunch: [product],
+ advertiseClientNativeAttachment: product === "claude" ? ["claude"] : [],
+ agentProcessEnv: host.selection.agentProcessEnv(),
+ ...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. */
+function* establish(product: Product, host: Machine, session = "review"): Operation {
+ yield* scoped(function* () {
+ yield* useFlatWorld(CWD);
+ const lines = yield* stderr();
+ yield* install(product, host, createFakeRuntime());
+ yield* prompt("seed", session);
+ expect(lines).toEqual([]);
+ });
+}
+
+describe("SC — a changed executable continues the same conversation, quietly", () => {
+ for (const product of ["codex", "claude"] as const) {
+ 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 tuple = {
+ provider: "acpx",
+ agent: PRODUCTS[product].command,
+ sessionKey: established!.acpxRecordId,
+ };
+ // 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.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);
+
+ yield* prompt("first after the upgrade");
+ yield* prompt("second after the upgrade");
+
+ expect(lines).toEqual([]);
+ });
+ // 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}-0.169.1`,
+ });
+ // Nothing was written to say today's executable made this session.
+ expect(yield* host.routes.read(tuple)).toEqual(route);
+ });
+ }
+});
+
+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);
+ // 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);
+ expect(yield* prompt("continue")).toBe("hello world");
+ 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, quietly", function* () {
+ const host = machine("claude");
+ 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);
+ 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: an earlier release's bound route continues, unchanged and unrewritten", function* () {
+ const host = machine("codex");
+ yield* establish("codex", host);
+ const key = [...host.store.records.keys()][0]!;
+ 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* 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: earlier }, harness);
+ expect(yield* prompt("continue")).toBe("hello world");
+ expect(lines).toEqual([]);
+ });
+ expect(harness.ensureCalls[0]?.expectedAgentSessionId).toBeDefined();
+ expect(yield* earlier.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 }),
+ });
+ expect(yield* prompt("through the wrapper")).toBe("hello world");
+ // The wrapper's backend is not guessed at, and nothing is said about it.
+ expect(lines).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 selection that cannot run is an availability failure, in the selector's words", function* () {
+ const host = machine("codex");
+ 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);
+ yield* install("codex", host, harness);
+ try {
+ yield* prompt("first");
+ } catch (error) {
+ raised = error as Error;
+ }
+ });
+ 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/workflow-agent-sessions.test.ts b/packages/cli/tests/workflow-agent-sessions.test.ts
index 090629c48..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* () {
@@ -413,6 +423,9 @@ function* hostClaudeWorkflow(
env: { PATH: bin, CLAUDE_CODE_EXECUTABLE: selected },
});
});
+ // 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);
@@ -501,7 +514,8 @@ type HostCodexMode =
| "invalid"
| "unlaunchable"
| "effort"
- | "no-selector";
+ | "no-selector"
+ | "versioned";
/**
* One production workflow Prompt through the carried Codex adapter, with the
@@ -524,7 +538,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");
@@ -646,6 +662,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, quietly", () =>
+ hostCodexWorkflow("versioned"));
});
describe("workflow ACP loading identity", { sanitizeOps: false, sanitizeResources: false }, () => {
@@ -733,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/packages/runtime/executable-observer.ts b/packages/runtime/executable-observer.ts
index a7cd9d454..4992c8936 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.
+ * 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. 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/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/packages/test-agent/src/components.ts b/packages/test-agent/src/components.ts
index 87fd11d0b..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 { 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 +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(),
- // 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..839cd7f21 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,6 @@ 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 +121,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 +296,6 @@ 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 f9d842e96..288fd0013 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,18 +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. 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.
+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
@@ -286,32 +286,35 @@ 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 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 **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 +880,10 @@ 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, and continuation follows the same quiet confirmation
+and refusal policy as an ordinary Session.
+
```ts
const opened = yield* useAgentConversation({
history, // the DurableStream holding this conversation's canonical history
@@ -1026,8 +1033,9 @@ 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 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
@@ -1531,9 +1539,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, no route store and no executable observer, and
-never consults their namespace.
+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
@@ -1866,6 +1878,18 @@ 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 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
resolve against the host execution directory. Selection resolves to a canonical
@@ -1875,8 +1899,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 +2024,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
@@ -2118,11 +2143,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.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..c033228d6 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 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
+[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..bce74652d
--- /dev/null
+++ b/specs/decisions/005-current-executable-session-continuation.md
@@ -0,0 +1,96 @@
+# 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.
+
+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
+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, and continuing says nothing about the change.
+
+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
+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)
+- [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..809bd5066 100644
--- a/specs/native-agent-session-launch-spec.md
+++ b/specs/native-agent-session-launch-spec.md
@@ -383,10 +383,19 @@ 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:
+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.
+
+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 {
@@ -396,48 +405,41 @@ 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.
-
-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 observed 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.
-
-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.
+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. 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.
### Attachment capability
@@ -449,47 +451,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.
+
+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
+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
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,22 +535,27 @@ 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
+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 build
- this run cannot name, or a route naming a different one, ends the launch here
- with nothing durable written about a session.
+ 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
- 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
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
@@ -564,18 +574,24 @@ 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
- `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
+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. 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
+ 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
+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:
@@ -604,22 +620,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 +666,30 @@ 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. 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.
-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
@@ -685,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
@@ -758,7 +788,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
@@ -819,10 +849,10 @@ 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. No executable
+observer is needed. An adapter that carries no binding keeps its ordinary
+behavior without those dependencies.
### Exact-target ownership inspection and recovery
@@ -932,7 +962,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 {
@@ -949,7 +981,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 {
@@ -964,16 +997,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
@@ -983,14 +1015,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 +1053,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
@@ -1095,12 +1130,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
@@ -1140,31 +1175,37 @@ 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. 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
-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
+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 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
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 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
@@ -1262,13 +1303,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. An executable's version
+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
@@ -1321,8 +1360,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.
@@ -1376,19 +1414,19 @@ 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 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 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
+ 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
@@ -1473,10 +1511,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, 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
bounded reaping;
and the controlled TestAgent fixture that proves all of it without starting a
@@ -1541,15 +1579,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 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
@@ -1599,9 +1632,13 @@ 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. 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.
@@ -1609,14 +1646,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 quietly 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/workflow-workspace-spec.md b/specs/workflow-workspace-spec.md
index 14f10bdcf..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.
@@ -2746,16 +2745,27 @@ 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 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.
+
+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