From fe60fb17ac824da8922744d59a0b3840efdd4839 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 01:30:21 +0100 Subject: [PATCH 01/18] docs(ui-server): retain boundary requirements without runtime activation (#4318) * CONTRACT: feat(ui-server): prove state boundaries and pin host module generations * docs: align boundary citations with host generation changes * fix(ui-sdk): retain activated module generation on directory sync failure * fix(ui-sdk): recognize the pinned module CLI in worker guidance * test(ui-server): supply the complete maintenance worker result * CONTRACT: chore(ui-sdk): refresh the state boundary API report * CONTRACT: fix(ui-server): contain state exposure and keep module storage inactive * fix(ui-server): preserve masked state aliases and existing refusal diagnoses * CONTRACT: fix(ui-server): withdraw unqualified state boundary proof --- docs/decisions/governed-writable-workers.md | 7 +++ docs/decisions/worker-writable-areas.md | 47 +++++++++++++++++++ docs/hosting/agent-workers.md | 10 ++++ .../tests/native-worker-startup-view.test.ts | 19 ++++++++ 4 files changed, 83 insertions(+) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 2798d536b4..61e3df6d20 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -650,6 +650,13 @@ permissions in another turn. | B — runtime permission and configuration surfaces | `.claude/settings.json`, `.claude/settings.local.json`, `.mcp.json`, `brain.config.ts`, `brain.config.json`, `package.json`, `bun.lock`, `node_modules/` | Yes | | Added by the policy | Anything listed under `protect` | Yes, by deleting the entry | +Ignored dependencies inside a checkout get no protection; the brain's root +`node_modules/` keeps its existing read-only bind and admission alias walk, +because later turns and maintenance execute that code. A module store must +not activate without bounded installation, provider-aware views, independent +worker lifetimes and recoverable storage. See the +[state-boundary ruling](worker-writable-areas.md#state-boundaries-and-root-dependencies--2026-11-20). + **Why the tier A paths are there:** - `context/policies/` is the policy itself. diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 1289a3a9dc..7d338a913d 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -397,3 +397,50 @@ directory it cannot search, and the server reads only the nested `.gitattributes` of directories it owns, from the retained checkpoint. Aliases, foreign owners and changed identities refuse. The bounds and the rationale are in the [governed-writable-workers record](governed-writable-workers.md), under "Server-owned strict output". + +## State boundaries and root dependencies — 2026-11-20 + +A filesystem boundary may replace an alias walk only when current evidence +proves what the final worker namespace can reach. Different filesystem or +subvolume identities alone are insufficient: a mount can expose private bytes +under another name. The existing operational-state guard remains in force; +there is no filesystem-identity fast path or module-store activation. + +A future boundary proof must read current filesystem/subvolume identities and +mount topology once per worker admission. A mount at the state root is not a +descendant mount. Descendant and stacked mounts must be resolved against the +visible backing tree, including aliases outside the brain. The proof must +account for the launcher's final binds, restored credentialed HOME and private +`/tmp`, rather than treating a host mask list as a namespace description. +Unreadable topology is unknown; a brain-only inode walk cannot discharge an +unknown external exposure. The full guard must cover that exposure before +any boundary can qualify. Path, ownership and symlink checks remain required. + +Every worker launch needs the same proof, including delayed compute helpers, +autonomous inbox helpers and credentialed maintenance. Live database handles +keep their original files private after a configured symlink changes; validating +only the new target is insufficient. Mask updates must validate placement +before publication so a refused temporary path cannot poison later workers. +An unsafe-state refusal must not become ordinary governed unavailability that +selects strict execution. Recoverable topology failures restrict execution, +allow authenticated diagnostics, record their cause through the hosted writer +and clear mechanically after fresh safe evidence. Owner status must reflect +the current cause without a synchronous SQLite commit on admission. + +A passed verdict on a shared filesystem is never a substitute for this proof, +whether cached by elapsed time or another token. A bare Btrfs subvolume +transaction generation is also rejected: without sync it missed 16 of 16 +writes, and after sync it advanced on 16 of 16 plain reads. Banning new links +cannot repair an alias that already exists. These shortcuts must not return. +Native qualification must use sibling Btrfs subvolumes on the same filesystem, +keep private state out of artifact aliases, and retain the measured receipts. +A comparison with an unrelated `/tmp` filesystem cannot establish that claim. + +“Ignored files get no protection” applies inside a checkout: dependencies and +build output there can be regenerated. The brain's own root dependencies are +code executed by later turns and maintenance, so their read-only protection +continues even when git ignores them. The root dependency tree keeps its +existing admission walk. A host-owned module store must not replace it until +bounded installation, provider masks, worker ownership and crash recovery are +proven together. A broken store must fall back to in-brain dependencies and +remain repairable by scheduled maintenance. diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 23c804f1b1..b6f42ad3ab 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -1740,3 +1740,13 @@ The [qualification and proposed integration contract](paid-cli-provider-qualific records actual offline controls, SDK accounting loss, media lifecycle constraints and the host-side admission/receipt design needed before activation. Existing CLI JSON envelopes and ordinary backend defaults remain unchanged. + + +### Root dependency protection + +Root dependencies continue to use the protected in-brain `node_modules` and +its existing alias walk. No module-store installation, activation, generation +binding or collection is enabled. Ignored dependencies inside a checkout are +disposable; root dependencies remain protected because later turns use them. +Operational state retains the existing path and alias guard; no filesystem +identity fast path or proof-mode status field is enabled. diff --git a/packages/ui-sdk/tests/native-worker-startup-view.test.ts b/packages/ui-sdk/tests/native-worker-startup-view.test.ts index 2502582c7b..7e8144e64c 100644 --- a/packages/ui-sdk/tests/native-worker-startup-view.test.ts +++ b/packages/ui-sdk/tests/native-worker-startup-view.test.ts @@ -243,3 +243,22 @@ test("a refused native stage deletion retries before releasing its checkpoint or await output.cleanup(); expect(deletes).toBe(2); } finally { await output?.cleanup().catch(() => {}); await view.cleanup(); f.cleanup(); } }); + +test("inactive module storage cannot block startup or bypass the in-brain dependency guard", async () => { + const f = fixture(); + try { + const store = join(f.brain, "..", "modules"); fs.mkdirSync(store); + fs.writeFileSync(join(store, "current.json"), "Odysseus damaged inactive receipt"); + fs.mkdirSync(join(f.brain, "node_modules")); + fs.symlinkSync("/missing", join(f.brain, "node_modules/escape")); + const acquisition = prepareNativeWorkerStartupView(f.brain, f.manager); + await expect(acquisition, "INACTIVE_STORE_CANNOT_BLOCK_RECOVERY_MAINTENANCE").resolves.toMatchObject({ brain: f.brain }); + const view = await acquisition; + try { + expect(isNativeWorkerStartupRoot(view.root), "INACTIVE_STORE_CANNOT_BLOCK_RECOVERY_MAINTENANCE").toBe(true); + expect(resolveWorkerProtection(f.brain, { paths: ["node_modules"] }).reason, + "INACTIVE_STORE_CANNOT_BYPASS_PROTECTED_DEPENDENCIES").toBeDefined(); + expect(fs.readFileSync(join(store, "current.json"), "utf8")).toBe("Odysseus damaged inactive receipt"); + } finally { await view.cleanup(); } + } finally { f.cleanup(); } +}); From 47a24ddf014ca23ee1882f6239fd77c5d6b3bf43 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 02:37:46 +0100 Subject: [PATCH 02/18] CONTRACT: feat(backends): persist observed backend startup phases (#4316) * CONTRACT: feat(backends): persist observed backend startup phases * test(ui-server): verify parsed backend timing fields * CONTRACT: fix(backends): preserve clients and qualify startup evidence * CONTRACT: fix(startup): contain diagnostics and validate native timing * CONTRACT: fix(startup): contain async diagnostics and qualify native intervals * CONTRACT: fix(startup): use observed fixture bounds and missing evidence --- .changeset/ithaca-backend-startup.md | 14 ++ api-report/ui-sdk.txt | 60 +++++ docs/integration-contract/mcp.md | 6 + docs/integration-contract/package-api.md | 23 ++ docs/integration-contract/wire.md | 69 ++++- .../src/autonomous-envelope.ts | 5 +- packages/ui-backend-claude/src/sdk-options.ts | 7 +- .../src/turn-inference-relay.ts | 3 + packages/ui-backend-claude/src/turn-runner.ts | 11 +- packages/ui-backend-claude/src/turn-stream.ts | 26 +- .../ui-backend-claude/src/worker-spawn.ts | 16 +- .../ui-backend-claude/tests/backend.test.ts | 79 ++++++ .../tests/startup-observer.test.ts | 59 +++++ .../ui-backend-pi/src/autonomous-envelope.ts | 5 +- packages/ui-backend-pi/src/backend-options.ts | 2 + packages/ui-backend-pi/src/host-inference.ts | 3 +- packages/ui-backend-pi/src/session-pool.ts | 1 + packages/ui-backend-pi/src/worker-entry.ts | 3 +- packages/ui-backend-pi/src/worker-launch.ts | 17 +- packages/ui-backend-pi/src/worker-reader.ts | 10 +- packages/ui-backend-pi/src/worker-session.ts | 8 +- .../tests/startup-timing.test.ts | 54 ++++ packages/ui-sdk/src/protocol.ts | 18 +- packages/ui-sdk/src/schemas.ts | 4 + packages/ui-sdk/src/server/backend.ts | 9 + packages/ui-sdk/src/server/index.ts | 1 + packages/ui-sdk/src/server/inference-relay.ts | 8 +- packages/ui-sdk/src/server/startup-timing.ts | 28 +++ .../tests/fixtures/async-startup-observer.ts | 35 +++ packages/ui-sdk/tests/inference-relay.test.ts | 10 + packages/ui-sdk/tests/startup-timing.test.ts | 42 ++++ packages/ui-server/src/activity/query.ts | 10 +- .../ui-server/src/activity/turn-lifecycle.ts | 73 +++++- .../src/ws/session-run/backend-entry.ts | 1 + .../tests/activity-query-lifecycle.test.ts | 50 ++++ .../tests/backend-startup-timing.test.ts | 164 ++++++++++++ .../ui-server/tests/turn-lifecycle.test.ts | 13 +- scripts/native-proof/README.md | 37 +++ scripts/native-proof/hosted-app.test.ts | 20 +- scripts/native-proof/lifecycle-timing.ts | 80 ++++++ tests/native-lifecycle-timing.test.ts | 237 ++++++++++++++++++ 41 files changed, 1261 insertions(+), 60 deletions(-) create mode 100644 .changeset/ithaca-backend-startup.md create mode 100644 packages/ui-backend-claude/tests/startup-observer.test.ts create mode 100644 packages/ui-backend-pi/tests/startup-timing.test.ts create mode 100644 packages/ui-sdk/src/server/startup-timing.ts create mode 100644 packages/ui-sdk/tests/fixtures/async-startup-observer.ts create mode 100644 packages/ui-sdk/tests/startup-timing.test.ts create mode 100644 packages/ui-server/tests/activity-query-lifecycle.test.ts create mode 100644 packages/ui-server/tests/backend-startup-timing.test.ts create mode 100644 scripts/native-proof/lifecycle-timing.ts create mode 100644 tests/native-lifecycle-timing.test.ts diff --git a/.changeset/ithaca-backend-startup.md b/.changeset/ithaca-backend-startup.md new file mode 100644 index 0000000000..c8bcfec81a --- /dev/null +++ b/.changeset/ithaca-backend-startup.md @@ -0,0 +1,14 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-backend-claude": minor +"@schlessera/brain-backend-pi": minor +--- + +Persist backend startup steps in the optional openSubPhases field through the first inference relay request, keeping host and worker clocks separate and naming missing Claude SDK evidence. Preserve compatibility with older SDKs' closed subPhases enum. Include the steps and explicit fixture coverage in native observation timing receipts. + +query_activity no longer includes the host lifecycle record, which was never part of its documented result and leaked host timing to the model. The owner-facing Activity API and stream retain the envelope. Bound missing-evidence metadata and isolate timing-observer exceptions from worker execution and cleanup. + +Contain asynchronous diagnostic failures and malformed SDK metadata without interrupting observed work. Validate native startup containment while allowing either callback order within the same millisecond. + +Distinguish unavailable MCP server lists from observed empty lists. Qualify the Claude worker fixture against its observed turn end, since Activity may start during prompt assembly, and require worker durations to retain a single host receipt point. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index c2fe88e0bb..f275885772 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -35,6 +35,7 @@ export "." (./src/index.ts) type ActivitySpanOrigin type ActivitySpanOutcome type ActivityTurnLifecycle + type ActivityTurnOpenSubPhase type ActivityTurnSubPhase type ActivityView type AgentPolicyRead @@ -581,6 +582,7 @@ export "./client" (./src/client/index.ts) type ActivitySpanOrigin type ActivitySpanOutcome type ActivityTurnLifecycle + type ActivityTurnOpenSubPhase type ActivityTurnSubPhase type ActivityView type AgentPolicyRead @@ -1673,6 +1675,7 @@ export "./protocol" (./src/protocol.ts) type ActivitySpanOrigin type ActivitySpanOutcome type ActivityTurnLifecycle + type ActivityTurnOpenSubPhase type ActivityTurnSubPhase type ActivityView type AgentPolicyRead @@ -2413,6 +2416,7 @@ export "./server" (./src/server/index.ts) type ActivitySpanOrigin type ActivitySpanOutcome type ActivityTurnLifecycle + type ActivityTurnOpenSubPhase type ActivityTurnSubPhase type ActivityView type AgentBackend @@ -3343,6 +3347,7 @@ export "./server" (./src/server/index.ts) resolveThinkingLevel reverseGeocode rtkRewriteCommand + safeStartupTiming signedArea simplify stateRoomCopy @@ -4496,6 +4501,8 @@ signatures (every public export and the types it is made of) journalStartedAt: number | null; journalBeganAt: number | null; backendInvokedAt: number | null; + firstRelayRequestAt?: number | null; + backendMissingEvidence?: string[]; firstFrameAt: number | null; failureObservedAt: number | null; endedAt: number | null; @@ -4509,6 +4516,13 @@ signatures (every public export and the types it is made of) journalBeginMs: number | null; backendStartupMs: number | null; subPhases?: ActivityTurnSubPhase[]; + openSubPhases?: ActivityTurnOpenSubPhase[]; + } + ActivityTurnOpenSubPhase (packages/ui-sdk/src/protocol.ts) + export interface ActivityTurnOpenSubPhase extends Omit { + phase: string; + timeBase?: "worker"; + workerElapsedMs?: number; } ActivityTurnSubPhase (packages/ui-sdk/src/protocol.ts) export interface ActivityTurnSubPhase { @@ -21210,6 +21224,8 @@ signatures (every public export and the types it is made of) export function runBackendModuleContract(harness: BackendModuleContractHarness, { describe, test, expect }: ContractTestPrimitives): void; runSpeechProviderContract (packages/ui-sdk/src/testing/speech-contract.ts) export function runSpeechProviderContract(harness: SpeechProviderContractHarness, { describe, test, expect }: ContractTestPrimitives): void; + safeStartupTiming (packages/ui-sdk/src/server/startup-timing.ts) + export function safeStartupTiming(timing: StartTurnRequest["startupTiming"]): StartTurnRequest["startupTiming"]; safetyCapabilitiesSchema (packages/ui-sdk/src/safety.ts) const safetyCapabilitiesSchema: z.ZodObject<{ detectorVersion: z.ZodLiteral<1>; @@ -22055,6 +22071,7 @@ signatures (every public export and the types it is made of) lifecycle: z.ZodOptional; + backendMissingEvidence: z.ZodOptional>; backendRunId: z.ZodNullable; backendStartupMs: z.ZodNullable; budgetAdmissionMs: z.ZodNullable; @@ -22064,6 +22081,7 @@ signatures (every public export and the types it is made of) endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; firstFrameAt: z.ZodNullable; + firstRelayRequestAt: z.ZodOptional>; governedAcquiredAt: z.ZodNullable; governedAdmissionMs: z.ZodNullable; governedStartedAt: z.ZodNullable; @@ -22081,6 +22099,15 @@ signatures (every public export and the types it is made of) journalBeginMs: z.ZodNullable; journalStartedAt: z.ZodNullable; lifecycleId: z.ZodString; + openSubPhases: z.ZodOptional; + endedAt: z.ZodNullable; + name: z.ZodString; + phase: z.ZodString; + startedAt: z.ZodNumber; + timeBase: z.ZodOptional>; + workerElapsedMs: z.ZodOptional; + }, z.core.$loose>>>; outcome: z.ZodNullable; + backendMissingEvidence: z.ZodOptional>; backendRunId: z.ZodNullable; backendStartupMs: z.ZodNullable; budgetAdmissionMs: z.ZodNullable; @@ -22188,6 +22216,7 @@ signatures (every public export and the types it is made of) endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; firstFrameAt: z.ZodNullable; + firstRelayRequestAt: z.ZodOptional>; governedAcquiredAt: z.ZodNullable; governedAdmissionMs: z.ZodNullable; governedStartedAt: z.ZodNullable; @@ -22205,6 +22234,15 @@ signatures (every public export and the types it is made of) journalBeginMs: z.ZodNullable; journalStartedAt: z.ZodNullable; lifecycleId: z.ZodString; + openSubPhases: z.ZodOptional; + endedAt: z.ZodNullable; + name: z.ZodString; + phase: z.ZodString; + startedAt: z.ZodNumber; + timeBase: z.ZodOptional>; + workerElapsedMs: z.ZodOptional; + }, z.core.$loose>>>; outcome: z.ZodNullable; + backendMissingEvidence: z.ZodOptional>; backendRunId: z.ZodNullable; backendStartupMs: z.ZodNullable; budgetAdmissionMs: z.ZodNullable; @@ -25192,6 +25231,7 @@ signatures (every public export and the types it is made of) endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; firstFrameAt: z.ZodNullable; + firstRelayRequestAt: z.ZodOptional>; governedAcquiredAt: z.ZodNullable; governedAdmissionMs: z.ZodNullable; governedStartedAt: z.ZodNullable; @@ -25209,6 +25249,15 @@ signatures (every public export and the types it is made of) journalBeginMs: z.ZodNullable; journalStartedAt: z.ZodNullable; lifecycleId: z.ZodString; + openSubPhases: z.ZodOptional; + endedAt: z.ZodNullable; + name: z.ZodString; + phase: z.ZodString; + startedAt: z.ZodNumber; + timeBase: z.ZodOptional>; + workerElapsedMs: z.ZodOptional; + }, z.core.$loose>>>; outcome: z.ZodNullable; + backendMissingEvidence: z.ZodOptional>; backendRunId: z.ZodNullable; backendStartupMs: z.ZodNullable; budgetAdmissionMs: z.ZodNullable; @@ -25317,6 +25367,7 @@ signatures (every public export and the types it is made of) endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; firstFrameAt: z.ZodNullable; + firstRelayRequestAt: z.ZodOptional>; governedAcquiredAt: z.ZodNullable; governedAdmissionMs: z.ZodNullable; governedStartedAt: z.ZodNullable; @@ -25334,6 +25385,15 @@ signatures (every public export and the types it is made of) journalBeginMs: z.ZodNullable; journalStartedAt: z.ZodNullable; lifecycleId: z.ZodString; + openSubPhases: z.ZodOptional; + endedAt: z.ZodNullable; + name: z.ZodString; + phase: z.ZodString; + startedAt: z.ZodNumber; + timeBase: z.ZodOptional>; + workerElapsedMs: z.ZodOptional; + }, z.core.$loose>>>; outcome: z.ZodNullable`; ` is null until observed, and `backendRunId` is null until a backend root is actually recorded. It never owns tokens, costs, spans or rollups. Inference aggregation continues to read backend rollups exactly once. +The whole envelope is host-only: `query_activity` never includes it in a +provider-facing tool result, including on recent, full, pruned or lifecycle-only +run queries. The owner-facing Activity API and stream retain the envelope. `acceptedAt` is the observed host acceptance time, before routing/admission. Queued requests retain their observed queue acceptance and `dequeuedAt`; @@ -607,7 +610,71 @@ not apply to a turn is absent. The current names are: `observe_facts` repeat once per other active turn the observation records, and are absent when there is none (#2915). -Records written before this field have no `subPhases`; nothing is backfilled. +Optional `openSubPhases` (#4285/#4286) carries **all new phases**, using the +same entry shape `{ phase, name, startedAt, endedAt, elapsedMs }` with an open +string vocabulary for `phase` as well as `name`. Consumers must tolerate +unknown phase names. The original `subPhases[].phase` enum is frozen at +`governed` and `journal`: previously published SDKs reject a whole Activity +snapshot or delta when that array contains an unknown phase. Their loose +lifecycle object accepts the new optional field without dropping the frame. +Never put a new phase into `subPhases`, or widen its enum. + +`openSubPhases` has the same pending, null, failure/interruption and persistence +rules as `subPhases`. Each array is in nondecreasing `startedAt` order, keeping +observation order for ties. A milestone interval learned after later-starting +steps is inserted at its start position. The first-frame milestone and its +step share one clock observation. Open steps are carried by the same milestone +or terminal writes. The current open phase names are: + +- `backend` (#4285/#4286): host `host_probe`, Claude's separate + `worker_host_probe`, `worker_launch` and `runtime_to_sdk_init`; Pi's + `preparation` and `worker_spawn`; worker-reported Pi `bootstrap_imports`, + `resources`, `session` and `initialize`; and host `first_backend_frame` + and `first_relay_request`. The last two measure from backend invocation + to the observed mark. `first_backend_frame` is absent if the first frame + follows relay receipt; the existing `backendStartupMs` still records it. + +The backend bracket ends at optional `firstRelayRequestAt` (host epoch +milliseconds), the first model request received on an authorized inference +relay route, before admission, body reading and dispatch. Token-count routes +do not end it. Null means not observed; historical records omit the field. +Backend steps start only after `backendInvokedAt`; new steps and completions +after relay receipt are ignored. An unfinished backend step has a null +`endedAt`; its elapsed value is bounded by relay receipt when observed, +otherwise the same failure/interruption rule as other steps. The receipt +persists a milestone; other startup observations add no writes of their own. + +For worker-reported open steps, `timeBase: "worker"` and `workerElapsedMs` +are additive fields. `elapsedMs` is that observed worker duration, while +both timestamps are the host's receipt time. They do **not** identify a +worker start on the host clock. Worker `bootstrap_imports` is measured from +the worker process's monotonic time origin to its entry after static imports. +Pi `session` includes resource loading, and `initialize` includes both; steps +can overlap and must not be summed as disjoint costs. A Pi worker contributes +at most one observation per startup phase (four total), before readiness; +duplicate and post-readiness reports are ignored in both timing and debug totals. + +Optional `backendMissingEvidence` lists unavailable SDK marks, rather than +inventing durations: Claude `first_enqueue`, `prompt_recorded`, and +`mcp_connect:` for the in-process server and each server named by +system/init. The installed SDK exposes connection state without per-server +start/end marks. Unknown marks have no timed step; an empty list does not +claim complete runtime coverage. These observations stay in host storage and +never enter provider history. +Names are sampled from the first Claude system/init frame only: at most 32 +server names, each at most 240 UTF-8 bytes, with +`mcp_connect:additional_servers_omitted` when that sample is incomplete. +The lifecycle retains at most 63 distinct missing-evidence names of at most +256 UTF-8 bytes each, plus `additional_missing_evidence_omitted` on overflow. +Omitted names are not retained for deduplication. Continuation init frames do +not expand the sample; missing evidence remains explicit when a limit is hit. +Malformed MCP diagnostic lists or entries also mark the sample incomplete. +Null or absent lists are unavailable evidence; an explicit empty array is an +observed empty list. These diagnostics cannot fail an otherwise usable stream. +Without a timing observer, the +backend does not read the MCP diagnostic list. + +Historical records may omit either timing array; neither is backfilled. The envelope terminates once with the existing outcome vocabulary: `success`, `error`, `timeout`, `cancelled`, `denied` or `interrupted`, optional explanation diff --git a/packages/ui-backend-claude/src/autonomous-envelope.ts b/packages/ui-backend-claude/src/autonomous-envelope.ts index 5bb9e14cb8..3955fd77c2 100644 --- a/packages/ui-backend-claude/src/autonomous-envelope.ts +++ b/packages/ui-backend-claude/src/autonomous-envelope.ts @@ -28,7 +28,8 @@ const SOCKET_ORIGIN = "http://localhost"; export function claudeAutonomousEnvelope( profile: InferenceProfile, turnEnvironment: Readonly>, - observe?: (event: InferenceRelayEvent) => void + observe?: (event: InferenceRelayEvent) => void, + received?: Parameters[0]["received"] ): ClaudeAutonomousEnvelope { const value = (name: string): string | undefined => turnEnvironment[name]?.trim() || undefined; let credentials: Record; @@ -55,7 +56,7 @@ export function claudeAutonomousEnvelope( const pinned = { ...CLEARED_API_CREDENTIALS, ...placeholder, ANTHROPIC_UNIX_SOCKET: WORKER_INFERENCE_SOCKET, ANTHROPIC_BASE_URL: SOCKET_ORIGIN }; const relay = startInferenceRelay({ upstream: value("ANTHROPIC_BASE_URL") ?? "https://api.anthropic.com", - routes: ANTHROPIC_INFERENCE_ROUTES, credentials, ...(observe ? { observe } : {}) }); + routes: ANTHROPIC_INFERENCE_ROUTES, credentials, received, ...(observe ? { observe } : {}) }); return { relay, pinned, diff --git a/packages/ui-backend-claude/src/sdk-options.ts b/packages/ui-backend-claude/src/sdk-options.ts index 96b050566d..337d752c9e 100644 --- a/packages/ui-backend-claude/src/sdk-options.ts +++ b/packages/ui-backend-claude/src/sdk-options.ts @@ -76,6 +76,7 @@ export interface ClaudeSdkTurn { /** Flag-settings env values the host pinned itself; the settings check accepts exactly these. */ pinnedSettingsEnv?: Readonly>; finishWorker(): Promise; + sdkInitialized(): void; /** The resource limits this turn's workers hit (#1660): so far, and once they have exited. */ workerLimits: { current(): WorkerLimitReport; settled(): Promise }; /** A worker-state refusal or stop (#1625), reported as the turn's failure. */ @@ -136,7 +137,8 @@ export function createClaudeSdkTurn(options: ClaudeSdkTurnOptions): ClaudeSdkTur // An autonomous turn gets the restricted envelope (#676): only the relay // route out, a placeholder credential and no ambient project configuration. const envelope = options.req.autonomous?.containment === "restricted" - ? claudeAutonomousEnvelope(options.profile, turnEnv(options.profile)) : undefined; + ? claudeAutonomousEnvelope(options.profile, turnEnv(options.profile), undefined, + path => { if (!path.endsWith("/count_tokens")) options.req.startupTiming?.received(); }) : undefined; try { const turn = assembleClaudeSdkTurn(options, envelope); if (options.req.autonomous) return turn; @@ -493,7 +495,7 @@ function assembleClaudeSdkTurn( } }, log: (level, message) => log(level, message), - }, { limits: stateLimits, turnTempLimits, reportCleanup: notice => req.bridge.activity?.({ kind: "worker_cleanup", ...notice }) }, req.workerLock, req.workerStarted, req.workerStartupView, req.persistClaudeMemory, options.hostInference, credentialEnv); + }, { limits: stateLimits, turnTempLimits, startupTiming: req.startupTiming, reportCleanup: notice => req.bridge.activity?.({ kind: "worker_cleanup", ...notice }) }, req.workerLock, req.workerStarted, req.workerStartupView, req.persistClaudeMemory, options.hostInference, credentialEnv); sdkOptions.spawnClaudeCodeProcess = worker.spawn; if (!req.autonomous) addStateRoomWarning(sdkOptions, req, worker); /** This turn's answer text so far: what it links in turn temp is promoted, so a purge keeps it. */ @@ -530,6 +532,7 @@ function assembleClaudeSdkTurn( if (owned) acknowledgeClaudeContext(backend.brainPath, contextId, owned, childEnv); }, workerLimits: { current: worker.limits, settled: worker.settledLimits }, + sdkInitialized: worker.sdkInitialized, workerFailure: worker.failure, workerStartFailure: worker.startFailure, workerStateRoom: worker.stateRoom, diff --git a/packages/ui-backend-claude/src/turn-inference-relay.ts b/packages/ui-backend-claude/src/turn-inference-relay.ts index 9978a97ad7..6c3d518b7f 100644 --- a/packages/ui-backend-claude/src/turn-inference-relay.ts +++ b/packages/ui-backend-claude/src/turn-inference-relay.ts @@ -57,6 +57,7 @@ export class TurnInferenceRelay { #relay: InferenceRelay | undefined; #link: string | undefined; #authorized = false; + readonly #startupTiming: StartTurnRequest["startupTiming"]; readonly #configDirectory: string; readonly #turnEnvironment: Environment | undefined; readonly #authorizedOrigins: ReturnType["claudeOAuthOrigins"]; @@ -65,6 +66,7 @@ export class TurnInferenceRelay { /** Selects the route and credential; starts nothing (see `start`). */ constructor(inputs: { req: StartTurnRequest; profile: InferenceProfile; turnEnvironment: Environment | undefined; brainPath: string }) { const { req, profile, turnEnvironment } = inputs; + this.#startupTiming = req.startupTiming; this.#turnEnvironment = turnEnvironment; this.egress = !req.autonomous ? req.workerSandbox?.egress : undefined; // Only what the profile itself declares: an ambient credential never rides along. @@ -90,6 +92,7 @@ export class TurnInferenceRelay { const egress = this.egress; if (!egress) return; this.#relay = startInferenceRelay({ upstream: this.selectedUpstream, routes: ANTHROPIC_INFERENCE_ROUTES, egress, + received: path => { if (!path.endsWith("/count_tokens")) this.#startupTiming?.received(); }, ...(this.#recipient ? { recipientOrigin: this.#recipient.origin } : {}), observe: event => { if (event.outcome === "refused") this.#refusalReasons.add(event.denialReason); }, credentials: async (signal, target) => { diff --git a/packages/ui-backend-claude/src/turn-runner.ts b/packages/ui-backend-claude/src/turn-runner.ts index 402ea0e619..0e28b8a090 100644 --- a/packages/ui-backend-claude/src/turn-runner.ts +++ b/packages/ui-backend-claude/src/turn-runner.ts @@ -2,7 +2,7 @@ import { retainNativeRouteInputs } from "./native-route-inputs.js"; import { query } from "@anthropic-ai/claude-agent-sdk"; import type { AccountInfo, Query, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; import type { FollowUpRequest, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; -import { assertTurnPosture, BackendBusyError, BackendRequestError } from "@schlessera/brain-ui-sdk/server"; +import { safeStartupTiming, assertTurnPosture, BackendBusyError, BackendRequestError } from "@schlessera/brain-ui-sdk/server"; import { NativeFileVersions, requireWorkerHostAsync } from "@schlessera/brain-ui-sdk/internal"; import type { ClaudeBackendOptions, BackendLogFn } from "./options.js"; @@ -119,6 +119,7 @@ export function createClaudeTurnRunner(options: ClaudeTurnRunnerOptions): Claude } async function startTurn(runner: TurnRunnerState, req: StartTurnRequest): Promise { + req = { ...req, startupTiming: safeStartupTiming(req.startupTiming) }; const { options, activeTurns, fileVersionsBySession } = runner; // Before anything is claimed or emitted: a refused posture rejects, per // the startTurn contract, and leaves no turn behind. @@ -171,7 +172,9 @@ async function startTurn(runner: TurnRunnerState, req: StartTurnRequest): Promis // Claim resumed input synchronously, then await collection before any // worker or SDK work. A refusal releases the claim through this catch. await req.bridge.inputSafety?.ready("claude",1); + const probed = req.startupTiming?.start("host_probe"); workerHost = await requireWorkerHostAsync(options.backend.brainPath); + probed?.(); profile = resolveProfile(options.resolveProfiles(), req.profileId); turnLock = createTurnLockBinding({ turn, @@ -279,12 +282,16 @@ async function runAdmittedTurn(runner: TurnRunnerState, claim: ClaimedTurn): Pro relay.routeInputs = relay.egress ? await retainNativeRouteInputs(req.workerSandbox?.profile === "governed" ? options.backend.brainPath : req.workerStartupView ?? options.backend.brainPath) : undefined; const result = runner.queryFn({ prompt, options: { ...sdkTurn.options, ...(req.maxBudgetUsd !== undefined ? { maxBudgetUsd: req.maxBudgetUsd } : {}) } }); + // Neither the handshake nor system/init reports these durations. Never + // substitute prompt handoff or relay receipt for an internal runtime mark. + for (const name of ["first_enqueue", "prompt_recorded", "mcp_connect:brain-ui"]) + req.startupTiming?.missing(name); resolveQuery(result); // The account the CLI selected, for the per-turn report. The SDK answers // every call from the one handshake, so this and the gate agree. const account = ( typeof result.initializationResult === "function" - ? initialize(result).then((init) => init.account, () => undefined) + ? initialize(result).then((init) => { sdkTurn.sdkInitialized(); return init.account; }, () => undefined) : Promise.resolve(undefined) ) as Promise; await runTurnStream({ stream: result, input, adapter, frames, terminal, req, backendId: BACKEND_ID, profileId: profile.id, diff --git a/packages/ui-backend-claude/src/turn-stream.ts b/packages/ui-backend-claude/src/turn-stream.ts index a04eb63818..6b28e43e13 100644 --- a/packages/ui-backend-claude/src/turn-stream.ts +++ b/packages/ui-backend-claude/src/turn-stream.ts @@ -1,5 +1,6 @@ import type { AccountInfo, SDKMessage } from "@anthropic-ai/claude-agent-sdk"; import type { ServerMessage, StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { safeStartupTiming } from "@schlessera/brain-ui-sdk/server"; import type { StreamAdapter } from "./stream-adapter.js"; import type { TurnInput } from "./turn-input.js"; @@ -21,7 +22,7 @@ export interface TurnStreamInputs { adapter: StreamAdapter; frames: TurnFrames; terminal: TurnTerminal; - req: Pick; + req: Pick; backendId: string; profileId: string; /** The account the CLI selected, for the per-turn runtime report. */ @@ -76,12 +77,35 @@ export class CarriedResult { * Exactly one terminal frame per turn, whatever the stream does. */ export async function runTurnStream(inputs: TurnStreamInputs): Promise { + const startupTiming = safeStartupTiming(inputs.req.startupTiming); const { input, adapter, terminal } = inputs; let announced = false; + let mcpInitObserved = false; let reported = false; let carried: CarriedResult | null = null; try { for await (const msg of inputs.stream) { + if (startupTiming && msg.type === "system" && msg.subtype === "init" && !mcpInitObserved) { + mcpInitObserved = true; + let omitted = false; + // Diagnostic metadata has no authority over an otherwise usable frame. + // Both list/property reads and individual entries may be malformed. + try { + const servers = msg.mcp_servers; + if (!Array.isArray(servers)) omitted = true; + else { + omitted = servers.length > 32; + for (const server of servers.slice(0, 32)) { + try { + const name = server?.name; + if (typeof name !== "string" || name.length > 240 || Buffer.byteLength(name) > 240) { omitted = true; continue; } + startupTiming.missing(`mcp_connect:${name}`); + } catch { omitted = true; } + } + } + } catch { omitted = true; } + if (omitted) startupTiming.missing("mcp_connect:additional_servers_omitted"); + } input.observe(msg); if (carried && CarriedResult.continues(msg)) carried.continued = true; // A withheld turn has already decided its outcome; nothing the stream diff --git a/packages/ui-backend-claude/src/worker-spawn.ts b/packages/ui-backend-claude/src/worker-spawn.ts index 030a751b4a..837a3ece7e 100644 --- a/packages/ui-backend-claude/src/worker-spawn.ts +++ b/packages/ui-backend-claude/src/worker-spawn.ts @@ -11,7 +11,7 @@ import { prepareRecoveredWorkerFiles, workerExecHelpers, createTurnTempPromoter, WORKER_SCRATCH, WORKER_STATE, WORKER_EMPTY_HOME, type LaunchedWorker, type TurnTempPromotionRecord, type WorkerLimitReport, type WorkerLimitsPlan, type WorkerSandbox, type WorkerStateHandle, type WorkerStateLimits } from "@schlessera/brain-ui-sdk/internal"; import { FIRST_PARTY_FAILURE_CLASSES, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; -import { wrapCommand, type ExecWrapperConfig, type TurnFailure, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { safeStartupTiming, wrapCommand, type ExecWrapperConfig, type TurnFailure, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; import { restoreArchivedSession } from "./transcript-archive.js"; import { processCleanupReconciler, type CleanupReconciler } from "./cleanup-reconciler.js"; import { processStateLedger } from "./worker-state-budget.js"; @@ -95,7 +95,7 @@ export const CLAUDE_INFERENCE_ENV: readonly string[] = Object.freeze(["CLAUDE_CO export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, immediateSignal: AbortSignal, restricted?: { inferenceDir: string }, sandbox?: WorkerSandbox, limitsPlan?: WorkerLimitsPlan, promotion?: WorkerPromotion, stateOptions: Pick[2]>, "limits" | "ledger" | "turnTempLimits"> - & { /** Owns a refused end-of-turn cleanup (#2871); defaults to the process's one. */ cleanup?: CleanupReconciler; reportCleanup?: (notice: import("@schlessera/brain-ui-sdk/internal").CleanupNotice) => void } = {}, + & { startupTiming?: import("@schlessera/brain-ui-sdk/server").StartTurnRequest["startupTiming"]; /** Owns a refused end-of-turn cleanup (#2871); defaults to the process's one. */ cleanup?: CleanupReconciler; reportCleanup?: (notice: import("@schlessera/brain-ui-sdk/internal").CleanupNotice) => void } = {}, outputLock?: KeyedLock, workerStarted?: import("@schlessera/brain-ui-sdk/server").StartTurnRequest["workerStarted"], startupView?: import("@schlessera/brain-ui-sdk/internal").WorkerStartupView, persistMemory?: import("@schlessera/brain-ui-sdk/server").StartTurnRequest["persistClaudeMemory"], @@ -106,6 +106,7 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, // The wrapper becomes the worker's first program: a regular file, never a directory bound into its view (#1429). if (!restricted) workerExecHelpers({ wrapper: config.wrapper }); const completions: Promise[] = []; + const startupTiming = safeStartupTiming(stateOptions.startupTiming); const reports: Array<() => WorkerLimitReport> = []; const limits = () => mergeLimitReports(reports.map(report => report())); const stateLimits = stateOptions.limits ?? resolveWorkerStateLimits({}); @@ -129,6 +130,8 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, * when the spawn threw it synchronously. */ let startFailure: unknown; + let sdkInitialized: (() => void) | undefined; + let initializationObserved = false; const record = (error: unknown) => { // By class, not constructor: the process ledger may come from another copy of this module. const errorClass = workerStateClass(error); @@ -138,12 +141,14 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, const checks = new Set<() => void>(); /** `preparation` also stops a facade the SDK killed before the worker existed. */ async function spawnNow({ command, args, env, signal }: SpawnOptions, preparation: AbortSignal, preparedOutput?: PreparedWorkerOutput) { + const probed = startupTiming?.start("worker_host_probe"); // The real launcher, with this worker's allowance, before anything is // restored, admitted or copied. Awaited, so the event loop keeps // answering while a loaded host starts the probe worker (#2790). await requireWorkerHostAsync(brainPath, { restricted: Boolean(restricted), stateBytes: stateLimits.allowanceBytes, turnTempBytes: turnTempLimits.allowanceBytes, ...(sandbox?.profile && sandbox.profile !== "restricted" ? { profile: sandbox.profile } : {}) }); + probed?.(); immediateSignal.throwIfAborted(); preparation.throwIfAborted(); let state: ReturnType; @@ -155,6 +160,7 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, } catch (error) { record(error); throw error; } const emitter = new EventEmitter(); let worker: LaunchedWorker; + const launched = startupTiming?.start("worker_launch"); try { const childEnv = Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)); if (!restricted) childEnv.PATH = brainWorkerPath(brainPath, childEnv.PATH); @@ -198,6 +204,11 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, else reportStrandedWorkerCleanup("claude", state, error); throw error; } + launched?.(); + // A hand-driven query can acknowledge initialization before the deferred + // launch. That ordering observes no runtime-to-SDK interval. + if (!initializationObserved) sdkInitialized = startupTiming?.start("runtime_to_sdk_init"); + else startupTiming?.missing("runtime_to_sdk_init"); let startFailure: unknown; reports.push(worker.limitReport); const handle = worker.state!; @@ -307,6 +318,7 @@ export function createWorkerSpawn(brainPath: string, config: ExecWrapperConfig, return { process, settled: done }; } return { + sdkInitialized: () => { initializationObserved = true; sdkInitialized?.(); }, /** The resource limits this turn's workers hit so far (#1660). */ limits, /** The turn-temp allowance each of this turn's workers is mounted with (#1703). */ diff --git a/packages/ui-backend-claude/tests/backend.test.ts b/packages/ui-backend-claude/tests/backend.test.ts index 655e9191fe..8385be0dac 100644 --- a/packages/ui-backend-claude/tests/backend.test.ts +++ b/packages/ui-backend-claude/tests/backend.test.ts @@ -22,6 +22,85 @@ import { defineProfiles } from "../src/profiles"; type Gen = (options: Options) => AsyncGenerator; +for (const observed of [false, true]) { + for (const malformed of ["absent", "null", "non-array", "null-entry", "throwing-list", "throwing-name"] as const) { + test(`malformed MCP diagnostics (${malformed}, observer=${observed}) never fail a usable Claude stream`, async () => { + const missing: string[] = []; let diagnosticReads = 0; + const backend = createClaudeBackend({ brainPath: "/tmp/odyssey", queryFn: makeQueryFn(async function* () { + const init: Record = { type: "system", subtype: "init", session_id: "ithaca", model: "odyssey", tools: [] }; + if (malformed === "absent") { /* The SDK supplied no list. */ } + else if (malformed === "null") init.mcp_servers = null; + else if (malformed === "non-array") init.mcp_servers = {}; + else if (malformed === "null-entry") init.mcp_servers = [null, { name: "ithaca", status: "connected" }]; + else if (malformed === "throwing-list") Object.defineProperty(init, "mcp_servers", { get() { throw Error("Ithaca diagnostic list unavailable"); } }); + else init.mcp_servers = [{ get name() { throw Error("Ithaca diagnostic name unavailable"); } }]; + yield new Proxy(init, { get(target, key, receiver) { + if (key === "mcp_servers") diagnosticReads++; + return Reflect.get(target, key, receiver); + } }); + yield { type: "result", subtype: "success", session_id: "ithaca", duration_ms: 1, num_turns: 1, total_cost_usd: 0, usage: {} }; + }) }); + const { bridge, frames } = makeBridge(); + await backend.startTurn(makeReq(bridge, new AbortController().signal, observed ? { startupTiming: { + start: () => () => {}, missing: name => { missing.push(name); }, worker() {}, received() {}, + } } : {})); + expect(frames.at(-1), "MALFORMED_MCP_DIAGNOSTICS_CANNOT_FAIL_TURN").toMatchObject({ type: "result", isError: false }); + expect(frames.filter(frame => frame.type === "session_info")).toHaveLength(1); + if (observed) expect(missing, "MCP_DIAGNOSTIC_OMISSIONS_ARE_EXPLICIT").toContain("mcp_connect:additional_servers_omitted"); + expect(diagnosticReads, "NO_OBSERVER_DOES_NOT_READ_MCP_DIAGNOSTICS").toBe(observed ? 1 : 0); + }); + } +} + +test("an observed empty MCP list stays distinct from an unavailable list", async () => { + const missing: string[] = []; + const backend = createClaudeBackend({ brainPath: "/tmp/odyssey", queryFn: makeQueryFn(async function* () { + yield { type: "system", subtype: "init", session_id: "ithaca", model: "odyssey", tools: [], mcp_servers: [] }; + yield { type: "result", subtype: "success", session_id: "ithaca", duration_ms: 1, num_turns: 1, total_cost_usd: 0, usage: {} }; + }) }); + const { bridge, frames } = makeBridge(); + await backend.startTurn(makeReq(bridge, new AbortController().signal, { startupTiming: { + start: () => () => {}, missing: name => { missing.push(name); }, worker() {}, received() {}, + } })); + expect(frames.at(-1)).toMatchObject({ type: "result", isError: false }); + expect(missing, "OBSERVED_EMPTY_MCP_LIST_IS_KNOWN").toEqual(["first_enqueue", "prompt_recorded", "mcp_connect:brain-ui"]); +}); + +test("Claude collects a bounded MCP name sample only from the first initialization frame", async () => { + const missing: string[] = []; + const servers = Array.from({ length: 1000 }, (_, index) => ({ name: index === 0 ? "🦉".repeat(80) : `ithaca-server-${index}`, status: "connected" })); + const backend = createClaudeBackend({ brainPath: "/tmp/odyssey", queryFn: makeQueryFn(async function* () { + yield { type: "system", subtype: "init", session_id: "ithaca", model: "odyssey", tools: [], mcp_servers: servers }; + for (let i = 0; i < 100; i++) yield { type: "system", subtype: "init", session_id: "ithaca", model: "odyssey", tools: [], mcp_servers: [{ name: `ithaca-late-server-${i}`, status: "connected" }] }; + yield { type: "result", subtype: "success", session_id: "ithaca", duration_ms: 1, num_turns: 1, total_cost_usd: 0, usage: {} }; + }) }); + const { bridge, frames } = makeBridge(); + await backend.startTurn(makeReq(bridge, new AbortController().signal, { startupTiming: { + start: () => () => {}, missing: name => { missing.push(name); }, worker() {}, received() {}, + } })); + expect(frames.at(-1)).toMatchObject({ type: "result", isError: false }); + expect(missing.length, "CLAUDE_MCP_NAMES_ARE_BOUNDED").toBeLessThanOrEqual(36); + expect(missing.filter(name => name.startsWith("mcp_connect:ithaca-server-"))).toHaveLength(31); + expect(missing).toContain("mcp_connect:additional_servers_omitted"); + expect(missing.filter(name => Buffer.byteLength(name) > 256)).toEqual([]); + expect(missing).not.toContain("mcp_connect:ithaca-late-server-99"); +}); + +test("Claude startup records its host probe and names unavailable SDK and per-server clocks", async () => { + const completed: string[] = [], missing: string[] = []; + const backend = createClaudeBackend({ brainPath: "/tmp/odyssey", queryFn: makeQueryFn(async function* () { + yield { type: "system", subtype: "init", session_id: "ithaca", model: "odyssey", tools: [], mcp_servers: [{ name: "brain", status: "connected" }] }; + yield { type: "result", subtype: "success", session_id: "ithaca", duration_ms: 1, num_turns: 1, total_cost_usd: 0, usage: {} }; + }) }); + const { bridge, frames } = makeBridge(); + await backend.startTurn(makeReq(bridge, new AbortController().signal, { startupTiming: { + start: name => () => { completed.push(name); }, missing: name => { missing.push(name); }, worker() {}, received() {}, + } })); + expect(frames.at(-1)).toMatchObject({ type: "result", isError: false }); + expect(completed, "CLAUDE_HOST_STARTUP_TIMING").toEqual(["host_probe"]); + expect(missing, "CLAUDE_MISSING_SDK_MARKS_ARE_EXPLICIT").toEqual(["first_enqueue", "prompt_recorded", "mcp_connect:brain-ui", "mcp_connect:brain"]); +}); + test("configured live guidance selects personal/capture sections without copying host instructions", () => { const backend = createClaudeBackend({ brainPath: "/tmp/odyssey", systemPromptAppend: "# Personal Rules\nGive Odysseus short answers.\n# Capture policy\nAsk before saving preferences.\n# Turn lifecycle\nHOST_ONLY_EXECUTION\n# Response surface\nHOST_ONLY_RENDERING\n" }); expect(backend.conversationGuidance).toEqual([ diff --git a/packages/ui-backend-claude/tests/startup-observer.test.ts b/packages/ui-backend-claude/tests/startup-observer.test.ts new file mode 100644 index 0000000000..207cebc0d6 --- /dev/null +++ b/packages/ui-backend-claude/tests/startup-observer.test.ts @@ -0,0 +1,59 @@ +import { expect, spyOn, test } from "bun:test"; +import { PassThrough } from "node:stream"; +import { mkdtempSync, mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as internal from "@schlessera/brain-ui-sdk/internal"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { createWorkerSpawn } from "../src/worker-spawn.js"; + +async function exerciseObserver(timing: NonNullable, initializedBeforeSpawn = false) { + const root = mkdtempSync(join(tmpdir(), "ithaca-startup-observer-")), brain = join(root, "brain"); mkdirSync(brain); + const stateRoot = join(root, "state"); mkdirSync(stateRoot); + const ledger = internal.createStateLedger(), reservations: ReturnType[] = []; + const reserve = ledger.reserve.bind(ledger); + const reserved = spyOn(ledger, "reserve").mockImplementation((...args) => { const held = reserve(...args); reservations.push(held); return held; }); + const stdin = new PassThrough(), stdout = new PassThrough(), stderr = new PassThrough(); + const exited = Promise.withResolvers(), started = Promise.withResolvers<"started" | "error">(); + let stateClosed = 0, tempClosed = 0, released = 0; + const finish = () => { stderr.end(); stdout.end(); exited.resolve(0); }; + const host = spyOn(internal, "requireWorkerHostAsync").mockResolvedValue({ ok: true }); + const launch = spyOn(internal, "launchAgentWorkerAsync").mockImplementation(async () => ({ stdin, stdout, stderr, + exited: exited.promise, kill: finish, released: async () => { released++; }, limitReport: () => ({ hits: [], fatal: false }), + state: { root: stateRoot, space: () => ({ free: 1024 * 1024 }), closeAsync: async () => { stateClosed++; } }, + turnTemp: { root: stateRoot, closeAsync: async () => { tempClosed++; } }, + }) as unknown as internal.LaunchedWorker); + try { + const spawner = createWorkerSpawn(brain, {}, new AbortController().signal, { inferenceDir: root }, undefined, undefined, undefined, + { ledger, startupTiming: timing, limits: { allowanceBytes: 4 * 1024 * 1024, budgetBytes: 8 * 1024 * 1024 }, + turnTempLimits: { allowanceBytes: 1024 * 1024, budgetBytes: 2 * 1024 * 1024 } }, undefined, () => started.resolve("started")); + if (initializedBeforeSpawn) spawner.sdkInitialized(); + const child = spawner.spawn({ command: "/bin/true", args: [], env: { HOME: root }, signal: new AbortController().signal } as never); + child.on("error", () => started.resolve("error")); child.stdout.resume(); child.stdin.end(); + const outcome = await started.promise; + expect(outcome, "TIMING_OBSERVER_MUST_NOT_ORPHAN_WORKER").toBe("started"); + spawner.sdkInitialized(); child.kill("SIGKILL"); await spawner.finish(); + expect({ stateClosed, tempClosed, released, live: ledger.live }, "TIMING_OBSERVER_PRESERVES_CLEANUP_OWNERSHIP") + .toEqual({ stateClosed: 1, tempClosed: 1, released: 1, live: 0 }); + } finally { + finish(); stdin.destroy(); stdout.destroy(); stderr.destroy(); + for (const held of reservations) held.release(); + launch.mockRestore(); host.mockRestore(); reserved.mockRestore(); rmSync(root, { recursive: true, force: true }); + } +} + +for (const fault of ["worker_launch:start", "worker_launch:end", "runtime_to_sdk_init:start"] as const) { + test(`a throwing ${fault} observer cannot orphan the launched worker or its reservation`, async () => { + await exerciseObserver({ start(name) { + if (`${name}:start` === fault) throw Error("Ithaca timing unavailable"); + return () => { if (`${name}:end` === fault) throw Error("Ithaca timing unavailable"); }; + }, missing() {}, worker() {}, received() {} }); + }); +} + +test("initialization observed before worker launch never invents a runtime-to-SDK interval", async () => { + const names: string[] = [], missing: string[] = []; + await exerciseObserver({ start(name) { names.push(name); return () => {}; }, missing(name) { missing.push(name); }, worker() {}, received() {} }, true); + expect(names, "EARLY_HANDSHAKE_CANNOT_START_LATE_SDK_TIMING").toEqual(["worker_host_probe", "worker_launch"]); + expect(missing).toEqual(["runtime_to_sdk_init"]); +}); diff --git a/packages/ui-backend-pi/src/autonomous-envelope.ts b/packages/ui-backend-pi/src/autonomous-envelope.ts index a96f6965b7..61c5134e5e 100644 --- a/packages/ui-backend-pi/src/autonomous-envelope.ts +++ b/packages/ui-backend-pi/src/autonomous-envelope.ts @@ -46,7 +46,8 @@ function configuredKey(value: string | undefined): string | undefined { } export function piAutonomousEnvelope(model: Model | undefined, agentDir: string, - observe?: (event: InferenceRelayEvent) => void): { relay: InferenceRelay; inference: PiWorkerInference } { + observe?: (event: InferenceRelayEvent) => void, + received?: Parameters[0]["received"]): { relay: InferenceRelay; inference: PiWorkerInference } { if (!model) throw new BackendRequestError("Autonomous pi turns need a declared vendor/model profile."); const api = APIS[model.api]; if (!api) { @@ -70,6 +71,6 @@ export function piAutonomousEnvelope(model: Model | undefined, agentDir: st throw new BackendRequestError(`Autonomous pi turns need an API key for ${model.provider}; an OAuth token cannot cross the restricted envelope.`); } const upstream = typeof override?.baseUrl === "string" ? override.baseUrl : model.baseUrl; - const relay = startInferenceRelay({ upstream, routes: api.routes, credentials: api.header(key), ...(observe ? { observe } : {}) }); + const relay = startInferenceRelay({ upstream, routes: api.routes, credentials: api.header(key), received, ...(observe ? { observe } : {}) }); return { relay, inference: { provider: model.provider, basePath: new URL(upstream).pathname.replace(/\/+$/, ""), placeholder: INFERENCE_PLACEHOLDER } }; } diff --git a/packages/ui-backend-pi/src/backend-options.ts b/packages/ui-backend-pi/src/backend-options.ts index 6d80156004..99df640625 100644 --- a/packages/ui-backend-pi/src/backend-options.ts +++ b/packages/ui-backend-pi/src/backend-options.ts @@ -204,6 +204,8 @@ export interface SessionCaps { /** What one session's system prompt and toolset are conditioned on. */ export interface SessionEnv { + /** Host-only startup observations, removed before worker serialization. */ + startupTiming?: import("@schlessera/brain-ui-sdk/server").StartTurnRequest["startupTiming"]; /** Host-only cleanup diagnostics, captured before worker initialization. */ cleanupActivity?: BackendBridge["activity"]; /** Internal static limits and current actionable budget context. */ diff --git a/packages/ui-backend-pi/src/host-inference.ts b/packages/ui-backend-pi/src/host-inference.ts index 1641b32a4e..4590457a86 100644 --- a/packages/ui-backend-pi/src/host-inference.ts +++ b/packages/ui-backend-pi/src/host-inference.ts @@ -247,6 +247,7 @@ export async function preparePiHostInference(options: { egress: { dir: string; inference: NonNullable[0]["egress"]>["inference"] }; environment: Readonly>; signal?: AbortSignal; + received?: Parameters[0]["received"]; }): Promise { const { provider, agentDir } = options; const brain = realpathSync(options.brainPath); @@ -296,7 +297,7 @@ export async function preparePiHostInference(options: { const first = await runtime.getAuth(model, options.signal ? { signal: options.signal } : {}); const shape = shapeOf(model, check.type, first?.auth.apiKey); const basePath = endpoint.pathname.replace(/\/+$/, ""); - relay = startInferenceRelay({ upstream: model.baseUrl, routes, egress: options.egress, + relay = startInferenceRelay({ upstream: model.baseUrl, routes, egress: options.egress, received: options.received, ...(options.recipientOrigin !== undefined ? { recipientOrigin: options.recipientOrigin } : {}), credentials: async (signal, target) => { const resolved = await runtime.getAuth(model, { signal }); diff --git a/packages/ui-backend-pi/src/session-pool.ts b/packages/ui-backend-pi/src/session-pool.ts index dc41e6f12b..9a3f795850 100644 --- a/packages/ui-backend-pi/src/session-pool.ts +++ b/packages/ui-backend-pi/src/session-pool.ts @@ -50,6 +50,7 @@ export function createSessionPool(runtime: SessionRuntime, retainSessions = true autonomous: req.autonomous, enforceAllowedTools: req.enforceAllowedTools === true, noGrantSurface: req.noGrantSurface === true }; const available = (name: string) => piToolAvailabilityRefusal(currentTurn, name) === undefined; const env: SessionEnv = { + startupTiming: req.startupTiming, workerSignal: req.signal, cleanupActivity: req.bridge.activity, sessionBudgetLimits: req.sessionBudgetLimits, budgetContext: req.budgetContext, diff --git a/packages/ui-backend-pi/src/worker-entry.ts b/packages/ui-backend-pi/src/worker-entry.ts index 74db2f8c39..744ec29325 100644 --- a/packages/ui-backend-pi/src/worker-entry.ts +++ b/packages/ui-backend-pi/src/worker-entry.ts @@ -40,7 +40,8 @@ interface Init { /** Present for a governed or strict turn on the turn proxy: the host holds the credential (#1665). */ relayed?: PiRelayedInference; } -sendPipe(process.stdout, { type: "startup_timing", phase: "worker_started", durationMs: 0 }); +// performance.now() is relative to this process's timeOrigin, including static imports. +sendPipe(process.stdout, { type: "startup_timing", phase: "worker_started", durationMs: performance.now() }); let session: PiSessionLike | undefined; let initialized=false; let manager: SessionManager | undefined; diff --git a/packages/ui-backend-pi/src/worker-launch.ts b/packages/ui-backend-pi/src/worker-launch.ts index b86190d089..b4053b8b99 100644 --- a/packages/ui-backend-pi/src/worker-launch.ts +++ b/packages/ui-backend-pi/src/worker-launch.ts @@ -14,7 +14,7 @@ import { join, relative, isAbsolute } from "node:path"; import { stateRoomCopy, stateRoomWarning, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; import { getAgentDir, type FileEntry } from "@earendil-works/pi-coding-agent"; import type { Model } from "@earendil-works/pi-ai"; -import { BackendRequestError, type compileConfirmPatterns, type ExecWrapperConfig } from "@schlessera/brain-ui-sdk/server"; +import { safeStartupTiming, BackendRequestError, type compileConfirmPatterns, type ExecWrapperConfig } from "@schlessera/brain-ui-sdk/server"; import { workerOutwardNote, workerCommandPolicyNote, createLimitTracker, launchAgentWorkerAsync, launchLimits, prepareWorkerSandbox, prepareWorkerSandboxAsync, processStateLedger, retainWorkerStartupView, prepareNativeWorkerOutput, type PreparedWorkerOutput, outputStagingLimit, requireWorkerHostAsync, resolveTurnTempLimits, restrictedReadPaths, turnTempLimit, workerNoteLimits, WorkerResourceLimitError, workerSandboxNote, workerSandboxWarnings, WORKER_SCRATCH, WORKER_XDG_DIRS, type Reservation, type WorkerSandbox, @@ -81,12 +81,14 @@ export interface PiWorkerAdmission { * against the process ledger. A refusal stops every relay it started. */ export async function admitPiWorker(request: PiWorkerAdmissionRequest): Promise { + const startupTiming = safeStartupTiming(request.env.startupTiming); const { backend, env, declared, restricted, entries, resumeId, sessionId, profileId, promptContext, exec } = request; const agentFiles: Record = {}; const agentDir = piSessionDirectory(backend.brainPath, getAgentDir()); // A restricted autonomous turn copies no native state into the worker: no // stored login, provider override or settings (#676). The relay holds the key. - const envelope = restricted ? piAutonomousEnvelope(declared, agentDir) : undefined; + const envelope = restricted ? piAutonomousEnvelope(declared, agentDir, undefined, + path => { if (!path.endsWith("/count_tokens")) startupTiming?.received(); }) : undefined; // A governed or strict turn on the turn proxy: the host holds the credential // and the worker's pi reaches inference only through the relay (#1665). const egress = !env.autonomous ? env.workerSandbox?.egress : undefined; @@ -102,7 +104,7 @@ export async function admitPiWorker(request: PiWorkerAdmissionRequest): Promise< const path = join(agentDir, name); if (existsSync(path)) agentFiles[name] = readFileSync(path, "utf8"); } - const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution, cleanupActivity: _cleanupActivity, ...workerSessionEnv } = env; + const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal, toolExecution, cleanupActivity: _cleanupActivity, startupTiming: _startupTiming, ...workerSessionEnv } = env; const npmPath = envelope ? undefined : join(agentDir, "npm", "node_modules"); let cachedNpmModules: string | undefined; if (npmPath && existsSync(npmPath)) { @@ -128,11 +130,13 @@ export async function admitPiWorker(request: PiWorkerAdmissionRequest): Promise< if (egress && relayedModel) { hostInference = await preparePiHostInference({ provider: relayedModel.provider, modelId: relayedModel.id, agentDir, ...(recipient ? { recipientOrigin: recipient.origin } : {}), - brainPath: backend.brainPath, egress, environment: subprocessEnv(), ...(env.workerSignal ? { signal: env.workerSignal } : {}) }); + brainPath: backend.brainPath, egress, environment: subprocessEnv(), received: path => { if (!path.endsWith("/count_tokens")) startupTiming?.received(); }, ...(env.workerSignal ? { signal: env.workerSignal } : {}) }); Object.assign(init, { relayed: hostInference.worker }); } admissionObservation = checkSessionSize(init); + const probed = startupTiming?.start("host_probe"); const workerHost = await requireWorkerHostAsync(backend.brainPath, { restricted, turnTempBytes: turnTempLimits.allowanceBytes }); + probed?.(); if (workerHost?.identity === "separate_uid" && workerHost.workerUid !== undefined) identity = { kind: "separate_uid", workerUid: workerHost.workerUid }; // Admitted against the same per-process ledger as Claude workers; a busy // budget refuses as worker_state_busy before anything launches. @@ -146,6 +150,7 @@ export async function admitPiWorker(request: PiWorkerAdmissionRequest): Promise< } export interface PiWorkerLaunchRequest { + prepared?: () => void; backend: CreatePiBackendOptions; env: SessionEnv; admission: PiWorkerAdmission; @@ -171,6 +176,7 @@ export interface LaunchedPiWorker { * reservation are released. */ export async function launchPiWorker(request: PiWorkerLaunchRequest): Promise { + const startupTiming = safeStartupTiming(request.env.startupTiming); const { backend, env, admission, restricted, resumeId, execHelpers, confirmPatterns, startupStarted, turnContext } = request; const { envelope, egress, hostInference, cachedNpmModules, reservation, admissionObservation, identity } = admission; const { workerSandbox, workerProviderMasks, workerDataTree, workerLock, workerStarted, workerStartupView, workerSignal } = admission.hostEnv; @@ -230,6 +236,8 @@ export async function launchPiWorker(request: PiWorkerLaunchRequest): Promise {}); } catch { /* Observability cannot refuse the prepared worker. */ } + const spawned = startupTiming?.start("worker_spawn"); backend.log?.("debug", "Pi startup phase", { phase: "preparation", durationMs: spawning - startupStarted, elapsedMs: spawning - startupStarted }); child = await launchAgentWorkerAsync({ brainPath: backend.brainPath, turnTempBytes: reservation.turnTempBytes, ...(preparedOutput ? { preparedOutput } : workerStartupView && sandbox.profile !== "governed" ? { startupView: retainWorkerStartupView(workerStartupView) } : {}), @@ -238,6 +246,7 @@ export async function launchPiWorker(request: PiWorkerLaunchRequest): Promise; @@ -64,8 +65,12 @@ export interface PiWorkerReader { /** Reads the worker's frames until its protocol closes; throws when it ends without completing. */ export async function readPiWorkerProtocol(reader: PiWorkerReader): Promise { + const startupTiming = safeStartupTiming(reader.startupTiming); const { child, state, ready, done, sessionId, backend, startupStarted, promptContext, sessionBudgetLimits, autonomous, resumed, turnContext, nativeVersions, receipts, resumedIds, listeners, proof, toolExecution, dispatch, send, fail, reportLimitHits, limitEnded, diagnostic } = reader; + // Startup diagnostics carry no authority. Retain at most the first of each + // of the protocol's four phases, and none once initialization is complete. + const startupPhases = new Set(); for await (const raw of pipeMessages(child.stdout)) { let msg: PiWorkerMessage; try { @@ -81,6 +86,9 @@ export async function readPiWorkerProtocol(reader: PiWorkerReader): Promise()) { const startupStarted = performance.now(); + env = { ...env, startupTiming: safeStartupTiming(env.startupTiming) }; + const prepared = env.startupTiming?.start("preparation"); env.workerSignal?.throwIfAborted(); const declared = resumeId ? undefined : toModel(resolveModelSpec(backend, profileId)); const restricted = env.autonomous?.containment === "restricted"; @@ -115,7 +117,7 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi if (admission.webModel) turnContext.webModel = admission.webModel; const { workerSandbox, workerLock, workerSignal, toolExecution } = admission.hostEnv; const { child, sandbox, sandboxNote, turnTemp } = await launchPiWorker({ backend, env, admission, restricted, resumeId, execHelpers, confirmPatterns, - startupStarted, turnContext }); + startupStarted, turnContext, prepared }); const { closeTurnTemp, releases, claimTurnTempClose, teardown, diagnostic, reportLimitHits, limitEnded, send, stdioReleased } = superviseWorker({ child, reservation, turnTemp, env, turnContext, admission, answerText: () => receipts.answerText() }); function live(): void { @@ -147,7 +149,7 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi observeFile: path => child.observeFile?.(path), nativeVersions, relayed: Boolean(hostInference), agentDir, agentFiles, allowedTools, confirmPatterns, bridgeTools, capabilities: env.caps, receipts }); const received = readPiWorkerProtocol({ child, state, ready, done, sessionId, backend, startupStarted, promptContext, - sessionBudgetLimits: env.sessionBudgetLimits, autonomous: Boolean(env.autonomous), resumed: Boolean(resumeId), turnContext, nativeVersions, + startupTiming: env.startupTiming, sessionBudgetLimits: env.sessionBudgetLimits, autonomous: Boolean(env.autonomous), resumed: Boolean(resumeId), turnContext, nativeVersions, receipts, resumedIds, listeners, proof, toolExecution, dispatch, send, fail, reportLimitHits, limitEnded, diagnostic }).catch(async error => { // A worker a limit killed mid-message ends the protocol with a partial // message: if the worker is gone, settle the limit before blaming the diff --git a/packages/ui-backend-pi/tests/startup-timing.test.ts b/packages/ui-backend-pi/tests/startup-timing.test.ts new file mode 100644 index 0000000000..89f0b070ad --- /dev/null +++ b/packages/ui-backend-pi/tests/startup-timing.test.ts @@ -0,0 +1,54 @@ +import { expect, test } from "bun:test"; +import { Readable } from "node:stream"; +import { readPiWorkerProtocol, type PiWorkerReader } from "../src/worker-reader.js"; + +const startup = [ + { type: "startup_timing", phase: "worker_started", durationMs: 610 }, + { type: "startup_timing", phase: "resources", durationMs: 31 }, + { type: "startup_timing", phase: "session", durationMs: 47 }, + { type: "startup_timing", phase: "initialize", durationMs: 52 }, +]; + +async function readStartup(beforeReady: object[], afterReady: object[] = []) { + const phases: Array<{ name: string; durationMs: number }> = []; + const logs: string[] = []; + const sessionId = "00000000-0000-4000-8000-000000000001"; + const messages = [...beforeReady, { type: "ready", sessionId, levels: ["off"], cost: 0 }, ...afterReady, { type: "done", cost: 0 }]; + const stdout = Readable.from(messages.map(message => Buffer.from(JSON.stringify(message) + "\n"))); + const done = Promise.withResolvers(); + const state = { active: false, initialized: false, ended: false }; + const reader = { child: { stdout }, state, sessionId, backend: { log(_level: string, _message: string, meta: { phase?: string }) { if (meta.phase) logs.push(meta.phase); } }, startupStarted: 0, + startupTiming: { worker(name: string, durationMs: number) { phases.push({ name, durationMs }); } }, + ready: { resolve() { state.active = true; } }, proof: { loaded() {} }, + done, nativeVersions: { cancelPending() {} }, reportLimitHits() {}, + } as unknown as PiWorkerReader; + try { + await readPiWorkerProtocol(reader); await done.promise; + expect(reader.state.ended).toBe(true); + return { phases, logs }; + } finally { stdout.destroy(); } +} + +test("validated Pi worker startup messages reach host timing with their original durations", async () => { + const { phases } = await readStartup(startup); + expect(phases, "PI_WORKER_PHASES_REACH_HOST_TIMING").toEqual([ + { name: "bootstrap_imports", durationMs: 610 }, { name: "resources", durationMs: 31 }, + { name: "session", durationMs: 47 }, { name: "initialize", durationMs: 52 }, + ]); +}); + +test("duplicate Pi startup reports are bounded and retain the first observation for each worker", async () => { + const repeated = Array.from({ length: 2000 }, () => ({ ...startup[0], durationMs: 999 })); + const { phases, logs } = await readStartup([startup[0]!, ...repeated, ...startup.slice(1)]); + expect(phases, "PI_STARTUP_REPORTS_ARE_BOUNDED").toHaveLength(4); + expect(logs).toEqual(["worker_started", "resources", "session", "initialize"]); + expect(phases[0]).toEqual({ name: "bootstrap_imports", durationMs: 610 }); + const nextWorker = await readStartup(startup); + expect(nextWorker.phases).toHaveLength(4); +}); + +test("Pi startup evidence stops at readiness even for a phase not reported earlier", async () => { + const { phases, logs } = await readStartup([startup[0]!], [startup[1]!]); + expect(phases, "PI_STARTUP_REPORTS_END_AT_READINESS").toEqual([{ name: "bootstrap_imports", durationMs: 610 }]); + expect(logs).toEqual(["worker_started"]); +}); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 59a6e0a114..405f5bd137 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -3883,7 +3883,7 @@ export function isPricingRoute(v: unknown): v is PricingRoute { } /** - * One timed step inside the governed-admission or journal-begin phase (#3355). + * One timed step inside the original governed or journal phases. * `name` is open vocabulary: consumers tolerate names they do not know. */ export interface ActivityTurnSubPhase { @@ -3895,6 +3895,14 @@ export interface ActivityTurnSubPhase { elapsedMs: number | null; } +/** Additive phases use an open vocabulary so older SDKs can retain the frame. */ +export interface ActivityTurnOpenSubPhase extends Omit { + phase: string; + /** Worker durations use an independent clock; timestamps are host receipt, not worker start/end. */ + timeBase?: "worker"; + workerElapsedMs?: number; +} + /** Host-owned envelope; never contributes inference usage or cost. */ export interface ActivityTurnLifecycle { hostEvents: Array<{ principalId: string; kind: "turn_cancelled" | "ask_user_cancelled" | "principal_revoked" | "follow_up"; observedAt: number }>; @@ -3912,6 +3920,10 @@ export interface ActivityTurnLifecycle { journalStartedAt: number | null; journalBeganAt: number | null; backendInvokedAt: number | null; + /** Absent on historical records, null until the first inference relay request is observed. */ + firstRelayRequestAt?: number | null; + /** SDK stages unavailable to the host; never inferred from another mark. */ + backendMissingEvidence?: string[]; firstFrameAt: number | null; failureObservedAt: number | null; endedAt: number | null; @@ -3924,8 +3936,10 @@ export interface ActivityTurnLifecycle { budgetAdmissionMs: number | null; journalBeginMs: number | null; backendStartupMs: number | null; - /** Additive (#3355): steps of the governed and journal phases, in start order. Absent on older records. */ + /** Original governed/journal steps, in start order. The closed phase enum is frozen. */ subPhases?: ActivityTurnSubPhase[]; + /** New phases, including backend startup, in start order; tolerate unknown phase names. */ + openSubPhases?: ActivityTurnOpenSubPhase[]; } export interface ActivityRunSummary { diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 452cd2e509..890047ed39 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -1632,6 +1632,8 @@ const activityTurnLifecycleSchema = z.looseObject({ journalStartedAt: z.number().nullable(), journalBeganAt: z.number().nullable(), backendInvokedAt: z.number().nullable(), + firstRelayRequestAt: z.number().nullable().optional(), + backendMissingEvidence: z.array(z.string()).optional(), firstFrameAt: z.number().nullable(), failureObservedAt: z.number().nullable(), endedAt: z.number().nullable(), @@ -1644,6 +1646,8 @@ const activityTurnLifecycleSchema = z.looseObject({ backendStartupMs: z.number().nullable(), subPhases: z.array(z.looseObject({ phase: z.enum(["governed", "journal"]), name: z.string(), startedAt: z.number(), endedAt: z.number().nullable(), elapsedMs: z.number().nullable() })).optional(), + openSubPhases: z.array(z.looseObject({ phase: z.string(), name: z.string(), startedAt: z.number(), + endedAt: z.number().nullable(), elapsedMs: z.number().nullable(), timeBase: z.literal("worker").optional(), workerElapsedMs: z.number().nonnegative().optional() })).optional(), outcome: z.enum(["success", "error", "timeout", "cancelled", "denied", "interrupted"]).nullable(), reason: z.string().nullable(), }); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 81c66106a4..dd73d4613f 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -615,6 +615,15 @@ export type { SubscriptionAuthAction } from "../protocol.js"; /** @experimental Part of the `AgentBackend` seam. */ export interface StartTurnRequest { + /** @internal Host-only startup observations; never serialized or sent to the provider. */ + startupTiming?: { + start(name: string): () => void; + /** Duration from the worker's own clock, timestamped at host receipt. */ + worker(name: string, durationMs: number): void; + missing(name: string): void; + /** First authorized inference route received, before admission and upstream dispatch. */ + received(): void; + }; /** @internal Static configured limits, snapshotted once into the session append. */ sessionBudgetLimits?: string; /** @internal Actionable threshold notices, delivered only as owned new tail context. */ diff --git a/packages/ui-sdk/src/server/index.ts b/packages/ui-sdk/src/server/index.ts index d935d77f67..51a95dc0aa 100644 --- a/packages/ui-sdk/src/server/index.ts +++ b/packages/ui-sdk/src/server/index.ts @@ -53,6 +53,7 @@ export type { export { BackendProfileConfigError, defineBackendModule } from "./backend-module.js"; export type { ExecWrapperConfig, KillableProcess, WrappedKillOptions } from "./exec-wrapper.js"; +export { safeStartupTiming } from "./startup-timing.js"; export { killWrapped } from "./exec-wrapper.js"; export { probeVersionCommand } from "./version-probe.js"; diff --git a/packages/ui-sdk/src/server/inference-relay.ts b/packages/ui-sdk/src/server/inference-relay.ts index d65bc465ca..b8553448a9 100644 --- a/packages/ui-sdk/src/server/inference-relay.ts +++ b/packages/ui-sdk/src/server/inference-relay.ts @@ -16,6 +16,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import type { startEgressProxy } from "./egress-proxy.js"; import { INFERENCE_RELAY_PLACEHOLDER } from "@schlessera/brain-common/internal/provider-unavailable"; +import { observeDiagnostic } from "./startup-timing.js"; /** Where the relay directory appears inside a restricted worker. */ export const WORKER_INFERENCE_DIR = "/run/brain-inference"; @@ -36,6 +37,8 @@ export interface InferenceRelayOptions { egress?: Pick>, "inference">; /** Called for every request, forwarded or refused. Values are never logged. */ observe?(event: InferenceRelayEvent): void; + /** Host receipt of an authorized route, before egress admission or reading its body. Observability only. */ + received?(path: string): void; /** * The exact origin turn admission proved this turn's recipient from (#2695). * A relay whose upstream has another origin refuses to start, so a turn that @@ -95,7 +98,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe chmodSync(dir, separateIdentity ? 0o750 : 0o700); const socketPath = join(dir, "relay.sock"); const refuse = (method: string, path: string, status: number, reason: string, denialReason?: string): Response => { - options.observe?.({ method, path, outcome: "refused", status, reason, ...(denialReason ? { denialReason } : {}) }); + observeDiagnostic(() => options.observe?.({ method, path, outcome: "refused", status, reason, ...(denialReason ? { denialReason } : {}) })); return Response.json({ type: "error", error: { type: "brain_inference_refused", message: reason } }, { status }); }; let server: ReturnType; @@ -114,6 +117,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe const path = url.pathname; if (request.method !== "POST") return refuse(request.method, path, 405, "Only inference requests are relayed"); if (!routes.has(path)) return refuse(request.method, path, 403, "This path is not an authorized inference route"); + observeDiagnostic(() => options.received?.(path)); const target = new URL(upstream.origin); target.pathname = path; target.search = url.search; const operation = options.egress?.inference(request.method, target, request.signal); @@ -206,7 +210,7 @@ export function startInferenceRelay(options: InferenceRelayOptions): InferenceRe await response.body?.cancel().catch(() => {}); return refuse(request.method, path, 502, "Inference upstream redirected; redirects are not followed"); } - options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status }); + observeDiagnostic(() => options.observe?.({ method: request.method, path, outcome: "forwarded", status: response.status })); const out = new Headers(); for (const [name, value] of response.headers) if (!RESPONSE_STRIPPED.has(name.toLowerCase())) out.set(name, value); if (operation && !operation.charge(headerBytes(`HTTP/1.1 ${response.status} ${response.statusText}`, response.headers))) { diff --git a/packages/ui-sdk/src/server/startup-timing.ts b/packages/ui-sdk/src/server/startup-timing.ts new file mode 100644 index 0000000000..2defb9190c --- /dev/null +++ b/packages/ui-sdk/src/server/startup-timing.ts @@ -0,0 +1,28 @@ +import type { StartTurnRequest } from "./backend.js"; + +/** Internal diagnostic boundary: never wait for a sink or leave its rejection unhandled. */ +export function observeDiagnostic(operation: () => unknown): void { + try { + const result = operation(); + if (result !== null && (typeof result === "object" || typeof result === "function")) + void Promise.resolve(result).catch(() => {}); + } catch { /* Missing observability never fails the observed work. */ } +} + +/** + * Best-effort diagnostics must not change a turn's work or resource ownership. + * @experimental Backend toolkit; timing callbacks supply no authority. + */ +export function safeStartupTiming(timing: StartTurnRequest["startupTiming"]): StartTurnRequest["startupTiming"] { + if (!timing) return undefined; + return { + start(name) { + let end: unknown; + observeDiagnostic(() => end = timing.start(name)); + return () => observeDiagnostic(() => typeof end === "function" ? end() : undefined); + }, + worker: (name, durationMs) => observeDiagnostic(() => timing.worker(name, durationMs)), + missing: name => observeDiagnostic(() => timing.missing(name)), + received: () => observeDiagnostic(() => timing.received()), + }; +} diff --git a/packages/ui-sdk/tests/fixtures/async-startup-observer.ts b/packages/ui-sdk/tests/fixtures/async-startup-observer.ts new file mode 100644 index 0000000000..8d806015bb --- /dev/null +++ b/packages/ui-sdk/tests/fixtures/async-startup-observer.ts @@ -0,0 +1,35 @@ +import { request } from "node:http"; +import { safeStartupTiming } from "../../src/server/startup-timing.js"; +import { startInferenceRelay } from "../../src/server/inference-relay.js"; + +const events: string[] = []; +const reject = async (name: string) => { events.push(name); throw Error(`Ithaca asynchronous diagnostic unavailable: ${name}`); }; +if (process.argv[2] === "startup") { + const timing = safeStartupTiming({ start: () => () => reject("completion"), + worker: () => reject("worker"), missing: () => reject("missing"), received: () => reject("received") })!; + timing.start("worker_launch")(); timing.worker("resources", 31); timing.missing("first_enqueue"); timing.received(); + safeStartupTiming({ start: () => () => ({ then(_resolve: unknown, fail: (error: Error) => void) { events.push("thenable"); fail(Error("Ithaca thenable diagnostic unavailable")); } }), + worker() {}, missing() {}, received() {} })!.start("worker_launch")(); + safeStartupTiming({ start: () => () => {}, worker() {}, missing() {}, + received() { events.push("pending"); return new Promise(() => {}); } })!.received(); + await new Promise(resolve => setImmediate(resolve)); + console.log(JSON.stringify(events)); +} else if (process.argv[2] === "relay") { + const upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch() { events.push("upstream"); return new Response("Ithaca model response"); } }); + let receipts = 0; + const relay = startInferenceRelay({ upstream: `http://127.0.0.1:${upstream.port}`, routes: ["/v1/messages"], + received() { if (++receipts === 1) return reject("receipt"); events.push("pending receipt"); return new Promise(() => {}); }, + observe: event => reject(event.outcome), credentials: async () => { events.push("credentials"); return { "x-api-key": "ithaca-fixture" }; } }); + const send = (method: string) => new Promise<{ status: number; body: string }>((resolve, reject) => { + const req = request({ socketPath: relay.socketPath, method, path: "/v1/messages" }, response => { + let body = ""; + response.setEncoding("utf8").on("data", chunk => { body += chunk; }).on("end", () => resolve({ status: response.statusCode!, body })).on("error", reject); + }); + req.on("error", reject); req.end(); + }); + try { + const responses = [await send("POST"), await send("POST"), await send("GET")]; + await new Promise(resolve => setImmediate(resolve)); + console.log(JSON.stringify({ responses, events })); + } finally { relay.stop(); await upstream.stop(true); } +} else throw Error("Unknown Ithaca diagnostic fixture mode"); diff --git a/packages/ui-sdk/tests/inference-relay.test.ts b/packages/ui-sdk/tests/inference-relay.test.ts index 7ac8a0d16d..4b5a34ad57 100644 --- a/packages/ui-sdk/tests/inference-relay.test.ts +++ b/packages/ui-sdk/tests/inference-relay.test.ts @@ -40,6 +40,16 @@ function send(socketPath: string, method: string, path: string, headers: Record< } describe("inference relay", () => { + test("startup receipt precedes credential resolution and cannot fail the observed request", async () => { + const order: string[] = []; + const r = startInferenceRelay({ upstream: `http://127.0.0.1:${upstream.port}`, routes: ANTHROPIC_INFERENCE_ROUTES, + received: path => { order.push(`received:${path}`); throw new Error("Timing sink unavailable"); }, + credentials: async () => { order.push("credentials"); return { "x-api-key": KEY }; } }); + relays.push(r); + expect((await send(r.socketPath, "POST", "/v1/files", {}, "{}")).status).toBe(403); + expect((await send(r.socketPath, "POST", "/v1/messages", {}, "{}")).status).toBe(200); + expect(order, "STARTUP_RECEIPT_BEFORE_UPSTREAM_WORK").toEqual(["received:/v1/messages", "credentials"]); + }); test("refuses to start toward any origin but the recipient its turn was admitted for (#2695)", async () => { const at = `http://127.0.0.1:${upstream.port}`; expect(() => startInferenceRelay({ upstream: `${at}/v1`, routes: ANTHROPIC_INFERENCE_ROUTES, credentials: { "x-api-key": KEY }, diff --git a/packages/ui-sdk/tests/startup-timing.test.ts b/packages/ui-sdk/tests/startup-timing.test.ts new file mode 100644 index 0000000000..f104fe81cc --- /dev/null +++ b/packages/ui-sdk/tests/startup-timing.test.ts @@ -0,0 +1,42 @@ +import { expect, test } from "bun:test"; +import { safeStartupTiming } from "../src/server/startup-timing.js"; +import { watchdogMs } from "../../../scripts/test-deadlines.js"; + +for (const mode of ["startup", "relay"]) { + test(`asynchronous ${mode} diagnostics cannot reject the process or block observed work`, async () => { + const child = Bun.spawn([process.execPath, "--no-env-file", new URL("./fixtures/async-startup-observer.ts", import.meta.url).pathname, mode], + { stdin: "ignore", stdout: "pipe", stderr: "pipe", timeout: watchdogMs(10000) }); + try { + const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect({ exit, stderr }, "ASYNC_STARTUP_DIAGNOSTICS_ARE_CONTAINED").toEqual({ exit: 0, stderr: "" }); + const result = JSON.parse(stdout); + if (mode === "startup") expect(result).toEqual(["completion", "worker", "missing", "received", "pending", "thenable"]); + else { + expect(result.responses.map((response: { status: number }) => response.status)).toEqual([200, 200, 405]); + expect(result.responses.slice(0, 2).map((response: { body: string }) => response.body)).toEqual(["Ithaca model response", "Ithaca model response"]); + expect(result.events).toEqual(["receipt", "credentials", "upstream", "forwarded", "pending receipt", "credentials", "upstream", "forwarded", "refused"]); + } + } finally { child.kill(); await child.exited; } + }); +} + +test("startup observer failures never escape any diagnostic method or returned completion", () => { + const events: string[] = []; + const fail = (event: string) => { events.push(event); throw Error("Ithaca diagnostics unavailable"); }; + const timing = safeStartupTiming({ start: name => fail(`start:${name}`), worker: name => fail(`worker:${name}`), + missing: name => fail(`missing:${name}`), received: () => fail("received") })!; + timing.start("host_probe")(); timing.worker("resources", 31); timing.missing("first_enqueue"); timing.received(); + const ending = safeStartupTiming({ start: () => () => fail("end:worker_launch"), worker() {}, missing() {}, received() {} })!; + ending.start("worker_launch")(); + expect(events).toEqual(["start:host_probe", "worker:resources", "missing:first_enqueue", "received", "end:worker_launch"]); + expect(safeStartupTiming(undefined)).toBeUndefined(); +}); + +test("startup observations preserve names, durations and method receivers", () => { + const events: unknown[] = []; + const observer = { label: "ithaca", start(name: string) { events.push([this.label, name]); return () => events.push("ended"); }, + worker(name: string, ms: number) { events.push([this.label, name, ms]); }, missing(name: string) { events.push([this.label, name]); }, received() { events.push(this.label); } }; + const timing = safeStartupTiming(observer)!; + timing.start("worker_launch")(); timing.worker("resources", 31); timing.missing("prompt_recorded"); timing.received(); + expect(events).toEqual([["ithaca", "worker_launch"], "ended", ["ithaca", "resources", 31], ["ithaca", "prompt_recorded"], "ithaca"]); +}); diff --git a/packages/ui-server/src/activity/query.ts b/packages/ui-server/src/activity/query.ts index 0b11e7e1d0..7315359c2b 100644 --- a/packages/ui-server/src/activity/query.ts +++ b/packages/ui-server/src/activity/query.ts @@ -1,12 +1,13 @@ /** - * The agent-facing read over the activity record — the same data the UI - * reads, shaped for model consumption and served through the backend + * The agent-facing read over backend activity, shaped for model consumption + * and served through the backend * bridge's `queryActivity` seam (the MCP tool calls it). * * Read-only by construction: nothing here writes. Free-text fields that * originated outside the primary agent's own context (failure reasons / * stderr tails, subagent transcript excerpts) are DATA, not instructions — * the tool layer labels them as such before they reach a model. + * Host lifecycle envelopes are UI diagnostics and never enter this result. */ import type { Database } from "bun:sqlite"; import type { ActivityQuery, ActivityQueryResult } from "@schlessera/brain-ui-sdk/server"; @@ -47,7 +48,6 @@ export function runActivityQuery( windowHours: hoursBack, running: store.openRootSpans().map(liveSummary), finished: rows.map((r) => ({ - lifecycle: store.lifecycle(r.runId) ?? undefined, runId: r.runId, origin: r.origin, name: r.name, @@ -85,7 +85,6 @@ export function runActivityQuery( .get(query.runId) as any; const liveRollup = rollupRow ? rowToRunRollup(rollupRow) : null; return { - lifecycle, runId: query.runId, costUsd: liveRollup?.costUsd ?? null, effectiveCostUsd: liveRollup?.effectiveCostUsd ?? null, @@ -113,11 +112,10 @@ export function runActivityQuery( const row = db .query("SELECT * FROM activity_run_rollups WHERE run_id = ?") .get(query.runId) as any; - if (!row) return lifecycle ? { lifecycle, runId: query.runId } : { error: `unknown run ${query.runId}` }; + if (!row) return lifecycle ? { runId: query.runId } : { error: `unknown run ${query.runId}` }; const rollup = rowToRunRollup(row); return { runId: query.runId, - lifecycle, detailPruned: true, rollup: { name: rollup.name, diff --git a/packages/ui-server/src/activity/turn-lifecycle.ts b/packages/ui-server/src/activity/turn-lifecycle.ts index b05ff1fb19..ff1ef88134 100644 --- a/packages/ui-server/src/activity/turn-lifecycle.ts +++ b/packages/ui-server/src/activity/turn-lifecycle.ts @@ -1,9 +1,10 @@ -import type { ActivityTurnLifecycle, ActivitySpanOutcome } from "@schlessera/brain-ui-sdk/protocol"; +import type { ActivityTurnLifecycle, ActivityTurnSubPhase, ActivityTurnOpenSubPhase, ActivitySpanOutcome } from "@schlessera/brain-ui-sdk/protocol"; import type { AwaitableActivityStore } from "./store.js"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; import { orderedWrites } from "./store-writes.js"; /** - * Starts one named step of an admission phase and returns its end (#3355). + * Starts one named lifecycle step and returns its end (#3355, #4285, #4286). * Steps ride on the record's next persisted milestone or terminal, so timing * adds no write to the turn path. */ @@ -16,9 +17,9 @@ export function createTurnLifecycle(store: AwaitableActivityStore, turnId: strin const record: ActivityTurnLifecycle = { hostEvents: [], skippedPhases: [], lifecycleId: `lifecycle:${turnId}`, turnId, sessionId, backendRunId: null, acceptedAt, dequeuedAt: null, governedStartedAt: null, governedAcquiredAt: null, budgetStartedAt: null, budgetAdmittedAt: null, - journalStartedAt: null, journalBeganAt: null, backendInvokedAt: null, firstFrameAt: null, failureObservedAt: null, + journalStartedAt: null, journalBeganAt: null, backendInvokedAt: null, firstRelayRequestAt: null, backendMissingEvidence: [], firstFrameAt: null, failureObservedAt: null, endedAt: null, outcome: null, reason: null, totalElapsedMs: null, timeToFirstFrameMs: null, - queueWaitMs: null, governedAdmissionMs: null, budgetAdmissionMs: null, journalBeginMs: null, backendStartupMs: null, subPhases: [], + queueWaitMs: null, governedAdmissionMs: null, budgetAdmissionMs: null, journalBeginMs: null, backendStartupMs: null, subPhases: [], openSubPhases: [], }; // Observability, including fanout, must never fail the observed turn. Each // write carries the record as it is now and fans out once committed (#2814). @@ -29,7 +30,56 @@ export function createTurnLifecycle(store: AwaitableActivityStore, turnId: strin if (record.endedAt !== null) return; record.hostEvents.push({ principalId, kind, observedAt: clock() }); persist(); }; + const backendOpen = () => record.backendInvokedAt !== null && record.firstRelayRequestAt === null && record.endedAt === null; + const missingNames = new Set(); + let missingOmitted = false; + const omitMissing = () => { + if (missingOmitted) return; + missingOmitted = true; + record.backendMissingEvidence!.push("additional_missing_evidence_omitted"); + }; + // Milestone intervals can be observed after steps that started later. + // Insert by their actual start, retaining observation order for equal starts. + const addOpenStep = (step: ActivityTurnOpenSubPhase) => { + const steps = record.openSubPhases ??= []; + const next = steps.findIndex(other => other.startedAt > step.startedAt); + steps.splice(next < 0 ? steps.length : next, 0, step); + }; + const phaseTimer = (phase: string): PhaseTimer => name => { + if (record.endedAt !== null || phase === "backend" && !backendOpen()) return () => {}; + const step = { phase, name, startedAt: clock(), endedAt: null as number | null, elapsedMs: null }; + if (phase === "governed" || phase === "journal") (record.subPhases ??= []).push(step as ActivityTurnSubPhase); + else addOpenStep(step); + return () => { if (record.endedAt === null && step.endedAt === null && (phase !== "backend" || backendOpen())) step.endedAt = clock(); }; + }; + const startupTiming: NonNullable = { + start: phaseTimer("backend"), + worker(name, durationMs) { + if (!backendOpen() || !Number.isFinite(durationMs) || durationMs < 0) return; + const at = clock(); + addOpenStep({ phase: "backend", name, startedAt: at, endedAt: at, elapsedMs: null, + timeBase: "worker", workerElapsedMs: durationMs }); + }, + // A later init frame may identify a server whose connection clock was + // unavailable. This reports absence only, never a late timing mark. + missing(name) { + if (record.backendInvokedAt === null || record.endedAt !== null) return; + // Reserve one of 64 slots for visible loss; never retain oversized names + // or the unbounded set of omitted names. Check length before hashing. + if (typeof name !== "string" || name.length > 256 || Buffer.byteLength(name) > 256 || name === "additional_missing_evidence_omitted") { omitMissing(); return; } + if (missingNames.has(name)) return; + if (missingNames.size >= 63) { omitMissing(); return; } + missingNames.add(name); record.backendMissingEvidence!.push(name); + }, + received() { + if (!backendOpen()) return; + const at = clock(); record.firstRelayRequestAt = at; + addOpenStep({ phase: "backend", name: "first_relay_request", startedAt: record.backendInvokedAt!, endedAt: at, elapsedMs: null }); + persist(); + }, + }; return { + startupTiming, recordHostEvent, recordCancellation(principalId: string, kind: "turn" | "ask_user" = "turn") { recordHostEvent(kind === "turn" ? "turn_cancelled" : "ask_user_cancelled", principalId); @@ -42,19 +92,14 @@ export function createTurnLifecycle(store: AwaitableActivityStore, turnId: strin record[milestone] = at; persist(); }, - timer(phase: "governed" | "journal"): PhaseTimer { - return name => { - if (record.endedAt !== null) return () => {}; - const step = { phase, name, startedAt: clock(), endedAt: null as number | null, elapsedMs: null }; - (record.subPhases ??= []).push(step); - return () => { if (record.endedAt === null && step.endedAt === null) step.endedAt = clock(); }; - }; - }, + timer: phaseTimer, bindSession(id: string) { if (record.endedAt === null) { record.sessionId = id; persist(); } }, linkBackend(id: string) { if (record.endedAt === null) { record.backendRunId = id; persist(); } }, firstFrame(id: string | null) { if (record.endedAt !== null || record.firstFrameAt !== null) return; - record.firstFrameAt = clock(); record.backendRunId = id; persist(); + const at = clock(); + if (backendOpen()) addOpenStep({ phase: "backend", name: "first_backend_frame", startedAt: record.backendInvokedAt!, endedAt: at, elapsedMs: null }); + record.firstFrameAt = at; record.backendRunId = id; persist(); }, finish(outcome: ActivitySpanOutcome, reason: string | null = null) { if (record.endedAt !== null) return; @@ -78,5 +123,7 @@ export function lifecycleTiming(record: ActivityTurnLifecycle): ActivityTurnLife backendStartupMs: phase(record.backendInvokedAt, record.firstFrameAt), // A step follows its phase's rules: unfinished, it measures to the failure boundary. ...(record.subPhases ? { subPhases: record.subPhases.map(step => ({ ...step, elapsedMs: phase(step.startedAt, step.endedAt) })) } : {}), + ...(record.openSubPhases ? { openSubPhases: record.openSubPhases.map(step => ({ ...step, elapsedMs: step.timeBase === "worker" ? step.workerElapsedMs ?? null + : phase(step.startedAt, step.endedAt ?? (step.phase === "backend" ? record.firstRelayRequestAt ?? null : null)) })) } : {}), }; } diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index 09bb8588eb..7776b79cf3 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -227,6 +227,7 @@ export function turnRequest(run: TurnRun, prompt: string, bridge: BackendBridge) : sessionTaint(governanceDb, turn.turnId, turn.sessionId ?? null) } : governedHold?.sandbox.commandPolicy; return { applicationAuthority: "server", + startupTiming: run.lifecycle?.startupTiming, ...(host.journal && governedHold ? { persistClaudeMemory: (change, save) => host.journal!.persistClaudeMemory(turn.turnId, change, save) } : {}), ...(governedHold?.startupView ? { workerStartupView: governedHold.startupView } : {}), ...(host.scope && governedHold ? { workerStarted: worker => host.scope!.workerStarted(scopeTurnId, worker) } : {}), diff --git a/packages/ui-server/tests/activity-query-lifecycle.test.ts b/packages/ui-server/tests/activity-query-lifecycle.test.ts new file mode 100644 index 0000000000..dfb8040edb --- /dev/null +++ b/packages/ui-server/tests/activity-query-lifecycle.test.ts @@ -0,0 +1,50 @@ +import { expect, spyOn, test } from "bun:test"; +import { handleQueryActivity } from "@schlessera/brain-ui-sdk/server"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { runActivityQuery } from "../src/activity/query.js"; +import { createActivityRoutes } from "../src/routes/activity.js"; + +test("query_activity never serializes current or pre-existing lifecycle diagnostics to the provider", async () => { + const db = createUiDb(":memory:"); + const pinned = Date.UTC(2026, 6, 12), clock = spyOn(Date, "now").mockReturnValue(pinned); + try { + const store = createActivityStore(db); let now = pinned; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now); + life.mark("governedStartedAt"); const gate = life.timer("governed")("ithaca-host-only-gate"); now += 10; gate(); life.mark("governedAcquiredAt"); + life.mark("backendInvokedAt"); const launch = life.startupTiming.start("ithaca-host-only-launch"); now += 10; launch(); + life.startupTiming.missing("mcp_connect:ithaca-host-only-server"); life.firstFrame("turn-ithaca"); life.startupTiming.received(); life.finish("success"); + store.startSpan({ spanId: "ithaca-root", runId: "turn-ithaca", name: "invoke_agent", kind: "turn", origin: "session", startedAt: pinned }); + store.endSpan("ithaca-root", { outcome: "success", endedAt: pinned + 50, usage: { inputTokens: 3, outputTokens: 5, costUsd: 0.02 } }); + store.rollupRun("turn-ithaca"); + const query = (scope: "recent" | "run", runId?: string) => handleQueryActivity({ scope, ...(runId ? { runId } : {}) }, { + emit() {}, requestPermission: async () => ({ behavior: "deny" as const, message: "Ithaca permission unavailable" }), + queryActivity: query => Promise.resolve(runActivityQuery(db, store, query)), + }); + const assertProvider = (text: string) => { + expect(text).toContain("turn-ithaca"); + for (const secret of ["lifecycle", "acceptedAt", "governedStartedAt", "subPhases", "openSubPhases", "firstRelayRequestAt", "backendMissingEvidence", "ithaca-host-only"]) + expect(text, `PROVIDER_ACTIVITY_EXCLUDES_HOST_LIFECYCLE ${secret}`).not.toContain(secret); + }; + assertProvider(await query("recent")); + assertProvider(await query("run", "turn-ithaca")); + const ui = await createActivityRoutes({ db, store }).request("/activity/runs/turn-ithaca"); + const uiRecord = await ui.json(); + expect(uiRecord.lifecycle).toMatchObject({ acceptedAt: pinned, firstRelayRequestAt: pinned + 20 }); + expect(uiRecord.lifecycle.subPhases.map((step: { name: string }) => step.name)).toEqual(["ithaca-host-only-gate"]); + expect(uiRecord.lifecycle.openSubPhases.map((step: { name: string }) => step.name)).toEqual(["ithaca-host-only-launch", "first_backend_frame", "first_relay_request"]); + const pruned = store.prune({ digestFloorAt: pinned + 100, detailRetentionMs: 0, hardCeilingMs: 0, now: pinned + 100 }); + expect(pruned.runsPruned).toBe(1); + expect(store.snapshotRun("turn-ithaca")).toBeNull(); + expect(store.lifecycle("turn-ithaca")?.backendMissingEvidence).toEqual(["mcp_connect:ithaca-host-only-server"]); + assertProvider(await query("recent")); + assertProvider(await query("run", "turn-ithaca")); + const admission = createTurnLifecycle(store, "turn-loom", "ithaca", pinned, () => {}, () => pinned + 10); + admission.mark("governedStartedAt"); admission.timer("governed")("ithaca-host-only-refusal"); admission.finish("denied"); + const onlyLifecycle = await query("run", "turn-loom"); + expect(onlyLifecycle).toContain("turn-loom"); + expect(onlyLifecycle, "PROVIDER_ACTIVITY_EXCLUDES_ENVELOPE_ONLY_LIFECYCLE").not.toContain("lifecycle"); + expect(onlyLifecycle).not.toContain("ithaca-host-only"); + } finally { clock.mockRestore(); db.close(); } +}); diff --git a/packages/ui-server/tests/backend-startup-timing.test.ts b/packages/ui-server/tests/backend-startup-timing.test.ts new file mode 100644 index 0000000000..c8ddc4c9ea --- /dev/null +++ b/packages/ui-server/tests/backend-startup-timing.test.ts @@ -0,0 +1,164 @@ +import { expect, test } from "bun:test"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { serverActivityDeltaSchema } from "@schlessera/brain-ui-sdk/schemas"; +import { z } from "zod"; + +// The previous SDK's closed phase schema. Its lifecycle object accepts +// unknown fields, but an unknown phase rejects the entire enclosing frame. +const previousStep = z.looseObject({ phase: z.enum(["governed", "journal"]), name: z.string(), startedAt: z.number(), + endedAt: z.number().nullable(), elapsedMs: z.number().nullable() }); +const previousLifecycle = z.looseObject({ subPhases: z.array(previousStep).optional() }); + +test("missing startup evidence stays bounded by count and UTF-8 bytes, including late reports", () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100); + life.mark("backendInvokedAt"); life.startupTiming.missing("first_enqueue"); + life.startupTiming.missing("mcp_connect:" + "🦉".repeat(80)); + life.startupTiming.missing("mcp_connect:" + "ithaca".repeat(1000)); + for (let i = 0; i < 3000; i++) life.startupTiming.missing(`mcp_connect:ithaca-server-${i}`); + life.startupTiming.received(); + for (let i = 3000; i < 6000; i++) life.startupTiming.missing(`mcp_connect:ithaca-server-${i}`); + life.finish("success"); + const names = store.lifecycle("turn-ithaca")!.backendMissingEvidence!; + expect(names, "MISSING_EVIDENCE_COUNT_IS_BOUNDED").toHaveLength(64); + expect(new Set(names).size).toBe(64); + expect(names[0]).toBe("first_enqueue"); + expect(names).toContain("additional_missing_evidence_omitted"); + expect(names.filter(name => Buffer.byteLength(name) > 256), "MISSING_EVIDENCE_BYTES_ARE_BOUNDED").toEqual([]); + } finally { db.close(); } +}); + +test("the previous SDK keeps activity frames containing backend and future open phases", () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1000; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now); + life.mark("backendInvokedAt"); const end = life.startupTiming.start("host_probe"); now = 1100; end(); + life.startupTiming.received(); life.finish("success"); + const record = store.lifecycle("turn-ithaca")!; + expect(record.openSubPhases!.map(step => step.name)).toEqual(["host_probe", "first_relay_request"]); + const oldDelta = z.looseObject({ type: z.literal("activity_delta"), runId: z.string(), seq: z.number(), lifecycle: previousLifecycle.optional() }); + const oldSnapshot = z.looseObject({ type: z.literal("activity_snapshot"), lifecycles: z.array(previousLifecycle).optional() }); + expect(oldDelta.safeParse({ type: "activity_delta", runId: record.turnId, seq: 1, lifecycle: record }).success, + "PREVIOUS_SDK_ACCEPTS_BACKEND_ACTIVITY_DELTA").toBe(true); + expect(oldSnapshot.safeParse({ type: "activity_snapshot", lifecycles: [record] }).success).toBe(true); + expect(previousLifecycle.safeParse({ subPhases: [{ phase: "backend", name: "host_probe", startedAt: 1, endedAt: 2, elapsedMs: 1 }] }).success).toBe(false); + const future = { ...record, openSubPhases: [{ phase: "future_phase", name: "future_step", startedAt: 1000, endedAt: null, elapsedMs: null }] }; + expect(serverActivityDeltaSchema.safeParse({ type: "activity_delta", runId: record.turnId, seq: 2, lifecycle: future }).success, + "NEW_SDK_ACCEPTS_UNKNOWN_OPEN_PHASE").toBe(true); + expect(previousLifecycle.safeParse(future).success).toBe(true); + } finally { db.close(); } +}); + +test("unknown open phases use the original pending, failure and milestone-write rules", () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1000; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now); + const end = life.timer("future_phase")("future_step"); + expect(store.lifecycle("turn-ithaca")!.openSubPhases).toEqual([]); + life.mark("dequeuedAt"); + expect(store.lifecycle("turn-ithaca")!.openSubPhases).toEqual([ + { phase: "future_phase", name: "future_step", startedAt: 1000, endedAt: null, elapsedMs: null }, + ]); + now = 1200; life.mark("failureObservedAt"); now = 1300; life.finish("error"); end(); + expect(store.lifecycle("turn-ithaca")!.openSubPhases).toEqual([ + { phase: "future_phase", name: "future_step", startedAt: 1000, endedAt: null, elapsedMs: 200 }, + ]); + expect(store.lifecycle("turn-ithaca")!.subPhases).toEqual([]); + } finally { db.close(); } +}); + +test("late-observed milestone intervals remain in start order", () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1000; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now); + life.mark("backendInvokedAt"); const probed = life.startupTiming.start("host_probe"); now = 1050; probed(); + const launched = life.startupTiming.start("worker_launch"); now = 1150; launched(); + now = 1200; life.firstFrame(null); now = 1400; life.startupTiming.received(); life.finish("success"); + const record = store.lifecycle("turn-ithaca")!; + const steps = record.openSubPhases ?? record.subPhases!; + expect(steps.map(step => step.startedAt), "MILESTONE_INTERVALS_STAY_IN_START_ORDER").toEqual([1000, 1000, 1000, 1050]); + expect(steps.map(step => step.name)).toEqual(["host_probe", "first_backend_frame", "first_relay_request", "worker_launch"]); + } finally { db.close(); } +}); + +test("first-frame step and milestone share one clock observation", () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1000; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now++); + life.mark("backendInvokedAt"); life.firstFrame(null); life.finish("success"); + const record = store.lifecycle("turn-ithaca")!; + const step = (record.openSubPhases ?? record.subPhases!).find(step => step.name === "first_backend_frame")!; + expect(step.endedAt, "FIRST_FRAME_USES_ONE_CLOCK_OBSERVATION").toBe(record.firstFrameAt); + expect(step.elapsedMs).toBe(record.backendStartupMs); + expect(record.firstFrameAt).toBe(1001); + } finally { db.close(); } +}); + +test("backend steps stay in invocation-to-relay and keep worker durations on their own clock", () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1000; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now); + const timing = life.startupTiming; + timing.start("before_invocation")(); timing.received(); timing.worker("before_invocation", 13); + life.mark("backendInvokedAt"); + const probe = timing.start("host_probe"); now = 1100; probe(); probe(); + timing.worker("resources", 777); timing.worker("invalid", NaN); timing.worker("invalid", -1); + timing.missing("first_enqueue"); timing.missing("first_enqueue"); + const unfinished = timing.start("sdk_init"); + life.mark("dequeuedAt"); + expect(store.lifecycle("turn-ithaca")!.openSubPhases!.at(-1)).toMatchObject({ name: "sdk_init", endedAt: null, elapsedMs: null }); + now = 1400; timing.received(); + now = 1500; unfinished(); timing.start("too_late")(); timing.worker("too_late", 99); timing.received(); + life.finish("success"); timing.missing("too_late"); + const record = store.lifecycle("turn-ithaca")!; + expect(record.firstRelayRequestAt).toBe(1400); + expect(record.backendMissingEvidence).toEqual(["first_enqueue"]); + expect(record.openSubPhases).toEqual([ + { phase: "backend", name: "host_probe", startedAt: 1000, endedAt: 1100, elapsedMs: 100 }, + { phase: "backend", name: "first_relay_request", startedAt: 1000, endedAt: 1400, elapsedMs: 400 }, + { phase: "backend", name: "resources", startedAt: 1100, endedAt: 1100, elapsedMs: 777, timeBase: "worker", workerElapsedMs: 777 }, + { phase: "backend", name: "sdk_init", startedAt: 1100, endedAt: null, elapsedMs: 300 }, + ]); + expect(record.openSubPhases!.filter(step => step.startedAt < 1000 || (step.endedAt ?? 1400) > 1400)).toEqual([]); + const parsed = serverActivityDeltaSchema.parse({ type: "activity_delta", runId: "turn-ithaca", seq: 1, lifecycle: record }); + expect(parsed.lifecycle?.firstRelayRequestAt).toBe(1400); + expect(parsed.lifecycle?.backendMissingEvidence).toEqual(["first_enqueue"]); + expect(parsed.lifecycle?.openSubPhases?.[2], "BACKEND_TIMING_SURVIVES_CLIENT_VALIDATION").toEqual({ + phase: "backend", name: "resources", startedAt: 1100, endedAt: 1100, elapsedMs: 777, timeBase: "worker", workerElapsedMs: 777, + }); + } finally { db.close(); } +}); + +for (const outcome of ["error", "cancelled", "denied", "interrupted"] as const) test(`unfinished backend steps retain ${outcome} boundaries and unknown evidence`, () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1000; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now); + life.mark("backendInvokedAt"); + const end = life.startupTiming.start("worker_launch"); + life.startupTiming.missing("prompt_recorded"); + life.mark("dequeuedAt"); + expect(store.lifecycle("turn-ithaca")!.openSubPhases).toEqual([ + { phase: "backend", name: "worker_launch", startedAt: 1000, endedAt: null, elapsedMs: null }, + ]); + now = 1200; + if (outcome !== "interrupted") life.mark("failureObservedAt"); + now = 1300; life.finish(outcome); + now = 1500; end(); life.startupTiming.received(); + const record = store.lifecycle("turn-ithaca")!; + expect(record.firstRelayRequestAt).toBeNull(); + expect(record.backendMissingEvidence).toEqual(["prompt_recorded"]); + expect(record.openSubPhases).toEqual([ + { phase: "backend", name: "worker_launch", startedAt: 1000, endedAt: null, elapsedMs: outcome === "interrupted" ? 300 : 200 }, + ]); + } finally { db.close(); } +}); diff --git a/packages/ui-server/tests/turn-lifecycle.test.ts b/packages/ui-server/tests/turn-lifecycle.test.ts index bf6f06fea0..d87fb631d0 100644 --- a/packages/ui-server/tests/turn-lifecycle.test.ts +++ b/packages/ui-server/tests/turn-lifecycle.test.ts @@ -84,6 +84,10 @@ test("real dispatch records delayed governed admission and first frame, and link let now=1000; const clock=spyOn(Date,"now").mockImplementation(()=>now); const policy=createGovernancePolicyReader("/nonexistent-odysseus-fixture").load(); const backend=makeFakeBackend({id:"pi",async startTurn(request){ + const end = request.startupTiming?.start("host_probe"); now=1500; end?.(); + request.startupTiming?.worker("resources", 37); + request.startupTiming?.missing("mcp_connect:brain"); + now=1600; request.startupTiming?.received(); now=1700;request.bridge.emit({type:"session_info",sessionId:"ithaca",isNew:true}); now=1900;request.bridge.emit({type:"result",sessionId:"ithaca",durationMs:200,numTurns:1,isError:false,costUsd:0}); }}); @@ -92,7 +96,14 @@ test("real dispatch records delayed governed admission and first frame, and link try { await runSession(host,{authorization:testAuthorization("odysseus"),text:"Plan Ithaca",attachments:[]}); const record=store.lifecycles()[0]!; - expect(record.subPhases,"DISPATCH_PASSES_THE_GOVERNED_STEP_TIMER").toEqual([{phase:"governed",name:"gate_acquire",startedAt:1000,endedAt:1400,elapsedMs:400}]); + expect(record.subPhases).toEqual([{phase:"governed",name:"gate_acquire",startedAt:1000,endedAt:1400,elapsedMs:400}]); + expect(record.openSubPhases,"DISPATCH_PERSISTS_BACKEND_STEPS").toEqual([ + {phase:"backend",name:"host_probe",startedAt:1400,endedAt:1500,elapsedMs:100}, + {phase:"backend",name:"first_relay_request",startedAt:1400,endedAt:1600,elapsedMs:200}, + {phase:"backend",name:"resources",startedAt:1500,endedAt:1500,elapsedMs:37,timeBase:"worker",workerElapsedMs:37}, + ]); + expect(record.backendMissingEvidence).toEqual(["mcp_connect:brain"]); + expect(record.firstRelayRequestAt).toBe(1600); expect(record).toMatchObject({acceptedAt:1000,governedStartedAt:1000,governedAcquiredAt:1400,backendInvokedAt:1400, firstFrameAt:1700,endedAt:2000,sessionId:"ithaca",totalElapsedMs:1000,timeToFirstFrameMs:700,backendStartupMs:300,outcome:"success"}); expect(record.backendRunId).toBe(record.turnId); diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index 4518ac74a8..735e14f688 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -58,6 +58,43 @@ phases and steps per scenario, and the host load before and after are in `observation-timing.json`. It is a measurement, not part of the default qualification. +The `backendStartup` section (#4285/#4286) includes the first turn after +server start and those five warm turns. Each sample carries invocation to +first relay receipt when observed, the observed turn `endedAt`, the `openSubPhases` backend steps, their host receipt timestamps and +worker clock tags, and `backendMissingEvidence` for unavailable SDK marks. +Worker durations are reported from `workerElapsedMs`, separately from host +intervals. Nested resource/session/initialize samples overlap; do not sum them. + +Coverage is explicit: the Claude qualification uses a hand-driven `queryFn` +which launches a real shell worker and synthesizes SDK responses. It exercises +`host_probe`, `worker_host_probe` and `worker_launch`; it does not run Claude's +SDK process or send a model request. Its `coverage` and `unobserved` fields +identify that limitation, and relay receipt stays null. It cannot qualify +Claude SDK/MCP/enqueue/first-request timings; those still need a real SDK run. +The Claude worker-fixture projection omits those unsupported SDK intervals from +both `steps` and `backendSteps`, even when an older raw record carries an open +SDK-init timer. No numeric SDK initialization duration is inferred from turn end. +The Pi fixture runs its real SDK and must provide all seven startup steps +(`preparation`, `host_probe`, `worker_spawn`, `bootstrap_imports`, `resources`, +`session`, `initialize`) plus a relay receipt. Every required step must be +complete on the first sample and each warm sample. A receipt alone cannot +qualify a startup breakdown. +Pi must also carry its `first_relay_request` step matching the observed relay +milestone. Both fixtures require `first_backend_frame` when the observed frame +is strictly before relay receipt (or no receipt was exercised), with the +step's timestamps matching that milestone. Equal millisecond timestamps do not +establish callback order: a frame step may be absent when receipt ran first, +and a present frame step must still match the milestone. A frame observed +after relay receipt remains outside the bracket. +Every backend entry's host start/end observations must be contained between +invocation and relay receipt. Worker durations keep their independent clock; +both host timestamps must be the same receipt point inside the bracket. +Claude's worker-only fixture uses the observed turn end as its qualification +upper bound, without claiming a model request. Its Activity `firstFrameAt` +can be set by `prompt_prefix` during SDK option assembly before worker launch. +A missing terminal bound cannot be replaced by that early frame. Required +host stages must use the host clock. + Its `phases` section (#2915) attributes each observed writer's worker hold and each harbour turn's journal begin and finish to their steps: the queue for the journal, the wait for room behind earlier releases, checkpoint, delta, diff --git a/scripts/native-proof/hosted-app.test.ts b/scripts/native-proof/hosted-app.test.ts index f0cadca98d..d3e2e82c33 100644 --- a/scripts/native-proof/hosted-app.test.ts +++ b/scripts/native-proof/hosted-app.test.ts @@ -1,3 +1,4 @@ +import { backendStartupSamples, lifecycleTimingSample } from "./lifecycle-timing.js"; import { afterAll, expect, test } from "bun:test"; import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -401,23 +402,12 @@ print(json.dumps(result))`; try { return (ui.query("SELECT record FROM activity_turn_lifecycles ORDER BY accepted_at").all() as { record: string }[]).map(row => JSON.parse(row.record)); } finally { ui.close(); } }; - const phases = (record: any) => { - if (!record) return null; - const span = (start: number | null, end: number | null) => start === null ? null : (end ?? record.failureObservedAt ?? record.endedAt) === null ? null - : Math.max(0, (end ?? record.failureObservedAt ?? record.endedAt) - start); - const steps: Record = {}; - for (const step of record.subPhases ?? []) { - const key = `${step.phase}.${step.name}`, ms = span(step.startedAt, step.endedAt); - steps[key] = ms === null ? steps[key] ?? null : (steps[key] ?? 0) + ms; - } - return { turnId: record.turnId, queueWaitMs: span(record.acceptedAt, record.dequeuedAt), governedAdmissionMs: span(record.governedStartedAt, record.governedAcquiredAt), - budgetAdmissionMs: span(record.budgetStartedAt, record.budgetAdmittedAt), journalBeginMs: span(record.journalStartedAt, record.journalBeganAt), - backendStartupMs: span(record.backendInvokedAt, record.firstFrameAt), timeToFirstFrameMs: span(record.acceptedAt, record.firstFrameAt), steps }; - }; + const phases = (record: Parameters[0]) => lifecycleTimingSample(record, BACKEND === "claude" ? "claude_worker_fixture" : "native"); const lifecycleOf = (turnId: string) => phases(lifecycles().find(record => record.turnId === turnId)); // (a) The process's first governed, journaled turn: the qualification's first admission. const firstAfterStart = phases(lifecycles().find(record => record.governedStartedAt !== null && record.journalStartedAt !== null)); const warm = harbour.slice(-5).map(lifecycleOf); + const backendStartup = backendStartupSamples(BACKEND === "claude" ? "claude" : "pi", firstAfterStart, warm); // Past the hosted app's one-minute idle observation interval. const IDLE_WAIT_MS = 65_000; // (b) A few hundred notes change while no turn runs, as a sync or maintenance pass would. @@ -468,7 +458,9 @@ print(json.dumps(result))`; traces: traces.length, managerSpans: managerSpans.length, }; const result = { backend: BACKEND, appUid: APP_UID, files: FILES, bytes: BYTES, loadBefore, loadAfter: load(), elapsedMs: performance.now() - timingStart, timelineTurnIds, - tools: timeline?.tools ?? null, admission, journal: { begin: { medianMs: median(total("beginMs")), p95Ms: p95(total("beginMs")) }, finish: { medianMs: median(total("finishMs")), p95Ms: p95(total("finishMs")) }, + tools: timeline?.tools ?? null, admission, + backendStartup, + journal: { begin: { medianMs: median(total("beginMs")), p95Ms: p95(total("beginMs")) }, finish: { medianMs: median(total("finishMs")), p95Ms: p95(total("finishMs")) }, beginPlusFinish: { medianMs: median(total("totalMs")), p95Ms: p95(total("totalMs")) }, turns: beginFinish }, phases: observationSteps, calls: timeline?.calls ?? null }; writeFileSync(join(ARTIFACTS, "observation-timing.json"), JSON.stringify(result, null, 2)); console.log(JSON.stringify({ observationTiming: { ...result, calls: undefined, journal: { ...result.journal, turns: undefined } } })); diff --git a/scripts/native-proof/lifecycle-timing.ts b/scripts/native-proof/lifecycle-timing.ts new file mode 100644 index 0000000000..8d50858de4 --- /dev/null +++ b/scripts/native-proof/lifecycle-timing.ts @@ -0,0 +1,80 @@ +import type { ActivityTurnLifecycle, ActivityTurnOpenSubPhase } from "@schlessera/brain-ui-sdk/protocol"; + +const UNOBSERVED_CLAUDE_STEPS: readonly string[] = ["runtime_to_sdk_init", "mcp_connect:*", "first_enqueue", "prompt_recorded", "first_relay_request"]; + +/** Project the persisted raw record for --observation-timing, without joining clock origins. */ +export function lifecycleTimingSample(record: ActivityTurnLifecycle | undefined, coverage: "native" | "claude_worker_fixture" = "native") { + if (!record) return null; + const span = (start: number | null, end: number | null): number | null => { + const terminal = end ?? record.failureObservedAt ?? record.endedAt; + return start === null || terminal === null ? null : Math.max(0, terminal - start); + }; + const steps: Record = {}; + const source: ActivityTurnOpenSubPhase[] = [...(record.subPhases ?? []), ...(record.openSubPhases ?? [])]; + const observed = source.filter(step => coverage !== "claude_worker_fixture" || step.phase !== "backend" + || !(UNOBSERVED_CLAUDE_STEPS.includes(step.name) || step.name.startsWith("mcp_connect:"))).map(step => { + const elapsedMs = step.timeBase === "worker" ? step.workerElapsedMs ?? null + : span(step.startedAt, step.endedAt ?? (step.phase === "backend" ? record.firstRelayRequestAt ?? null : null)); + const key = `${step.phase}.${step.name}`; + steps[key] = elapsedMs === null ? steps[key] ?? null : (steps[key] ?? 0) + elapsedMs; + return { ...step, elapsedMs }; + }); + return { turnId: record.turnId, backendInvokedAt: record.backendInvokedAt, firstFrameAt: record.firstFrameAt, endedAt: record.endedAt, firstRelayRequestAt: record.firstRelayRequestAt ?? null, + queueWaitMs: span(record.acceptedAt, record.dequeuedAt), + governedAdmissionMs: span(record.governedStartedAt, record.governedAcquiredAt), + budgetAdmissionMs: span(record.budgetStartedAt, record.budgetAdmittedAt), journalBeginMs: span(record.journalStartedAt, record.journalBeganAt), + backendStartupMs: span(record.backendInvokedAt, record.firstFrameAt), timeToFirstFrameMs: span(record.acceptedAt, record.firstFrameAt), + // An absent first request must not turn into a claimed receipt at failure/turn end. + invocationToRelayMs: record.backendInvokedAt === null || record.firstRelayRequestAt == null ? null : Math.max(0, record.firstRelayRequestAt - record.backendInvokedAt), + backendSteps: observed.filter(step => step.phase === "backend"), backendMissingEvidence: record.backendMissingEvidence ?? null, steps }; +} + +/** The first and five warm samples of the native observation fixture. */ +export function backendStartupSamples(backend: "claude" | "pi", firstAfterStart: ReturnType, warm: ReturnType[]) { + if (warm.length !== 5) throw Error("BACKEND_TIMING_FIVE_WARM_TURNS"); + // hosted-app-child uses a hand-driven queryFn on Claude. Its worker is + // real, but it never runs the SDK process or sends a model request. + const workerNames = ["bootstrap_imports", "resources", "session", "initialize"]; + const required = backend === "claude" ? ["host_probe", "worker_host_probe", "worker_launch"] + : ["preparation", "host_probe", "worker_spawn", ...workerNames]; + for (const sample of [firstAfterStart, ...warm]) { + if (!sample) throw Error("BACKEND_TIMING_SAMPLE_MISSING"); + if (sample.backendInvokedAt === null || sample.firstFrameAt === null) throw Error("BACKEND_TIMING_MILESTONE_MISSING"); + if (backend === "pi" && (sample.invocationToRelayMs === null || !Number.isFinite(sample.invocationToRelayMs) || sample.invocationToRelayMs < 0)) + throw Error("BACKEND_TIMING_FIRST_RELAY_RECEIPT"); + if (backend === "claude" && sample.invocationToRelayMs !== null) throw Error("CLAUDE_WORKER_FIXTURE_MUST_NOT_CLAIM_RELAY_RECEIPT"); + const missing = required.filter(name => !sample.backendSteps.some(step => step.name === name && step.endedAt !== null + && step.elapsedMs !== null && Number.isFinite(step.elapsedMs) && step.elapsedMs >= 0 + && (workerNames.includes(name) ? step.timeBase === "worker" && step.workerElapsedMs === step.elapsedMs : step.timeBase === undefined))); + const milestones: Array<[string, number]> = []; + if (backend === "pi" && sample.firstRelayRequestAt !== null) milestones.push(["first_relay_request", sample.firstRelayRequestAt]); + // Equal milliseconds do not reveal which callback ran first. The lifecycle + // may legitimately omit the frame step when relay receipt won that race. + if (sample.firstRelayRequestAt === null || sample.firstFrameAt < sample.firstRelayRequestAt + || sample.backendSteps.some(step => step.name === "first_backend_frame")) + milestones.push(["first_backend_frame", sample.firstFrameAt]); + for (const [name, at] of milestones) { + if (!sample.backendSteps.some(step => step.name === name && step.timeBase === undefined && step.startedAt === sample.backendInvokedAt + && step.endedAt === at && step.elapsedMs === Math.max(0, at - sample.backendInvokedAt!))) missing.push(name); + } + if (missing.length) throw Error(`BACKEND_TIMING_MISSING_STEPS ${missing.join(",")}`); + // Worker durations keep their own clock; only their host observation point + // belongs in this bracket. Claude's shell fixture has no relay receipt; + // prompt_prefix can open Activity before launch, so its upper bound is the + // observed turn end, never the first Activity frame. + const boundary = backend === "claude" ? sample.endedAt : sample.firstRelayRequestAt; + if (boundary === null || !Number.isFinite(boundary)) throw Error("BACKEND_TIMING_BOUNDARY_MISSING"); + for (const step of sample.backendSteps) { + if (!Number.isFinite(step.startedAt) || step.startedAt < sample.backendInvokedAt || step.startedAt > boundary + || step.endedAt !== null && (!Number.isFinite(step.endedAt) || step.endedAt < step.startedAt || step.endedAt > boundary)) + throw Error(`BACKEND_TIMING_OUTSIDE_STARTUP ${step.name}`); + if (step.timeBase === "worker" && step.startedAt !== step.endedAt) + throw Error(`BACKEND_TIMING_WORKER_RECEIPT_POINT ${step.name}`); + } + } + return { clock: "host epoch timestamps; timeBase=worker uses workerElapsedMs, never subtracted from host time", backend, + coverage: backend === "claude" ? { worker: "native", sdk: "mock_query", firstRelayRequest: "not_exercised" } + : { worker: "native", sdk: "native", firstRelayRequest: "required" }, + unobserved: backend === "claude" ? [...UNOBSERVED_CLAUDE_STEPS] : [], + firstAfterStart, warm }; +} diff --git a/tests/native-lifecycle-timing.test.ts b/tests/native-lifecycle-timing.test.ts new file mode 100644 index 0000000000..cabb2b13e4 --- /dev/null +++ b/tests/native-lifecycle-timing.test.ts @@ -0,0 +1,237 @@ +import { expect, spyOn, test } from "bun:test"; +import type { ActivityTurnLifecycle } from "@schlessera/brain-ui-sdk/protocol"; +import { backendStartupSamples, lifecycleTimingSample } from "../scripts/native-proof/lifecycle-timing.js"; +import { createUiDb } from "../packages/ui-server/src/db/client.js"; +import { createActivityStore } from "../packages/ui-server/src/activity/store.js"; +import { createTurnLifecycle } from "../packages/ui-server/src/activity/turn-lifecycle.js"; +import { createTurnRecorder } from "../packages/ui-server/src/activity/recorder.js"; +import { promptPrefixFingerprint } from "@schlessera/brain-ui-sdk/internal"; + +function record(): ActivityTurnLifecycle { + return { hostEvents: [], skippedPhases: [], lifecycleId: "lifecycle:ithaca", turnId: "ithaca", sessionId: "odysseus", backendRunId: "ithaca", + acceptedAt: 1000, dequeuedAt: 1000, governedStartedAt: 1000, governedAcquiredAt: 1100, + budgetStartedAt: null, budgetAdmittedAt: null, journalStartedAt: null, journalBeganAt: null, + backendInvokedAt: 1100, firstRelayRequestAt: 1700, firstFrameAt: 1600, failureObservedAt: null, endedAt: 2000, + outcome: "success", reason: null, totalElapsedMs: null, timeToFirstFrameMs: null, queueWaitMs: null, + governedAdmissionMs: null, budgetAdmissionMs: null, journalBeginMs: null, backendStartupMs: null, + backendMissingEvidence: ["mcp_connect:brain", "first_enqueue", "prompt_recorded"], + subPhases: [ + { phase: "governed", name: "gate_acquire", startedAt: 1000, endedAt: 1100, elapsedMs: null }, + ], + openSubPhases: [ + { phase: "backend", name: "host_probe", startedAt: 1100, endedAt: 1200, elapsedMs: null }, + { phase: "backend", name: "first_relay_request", startedAt: 1100, endedAt: 1700, elapsedMs: null }, + { phase: "backend", name: "resources", startedAt: 1500, endedAt: 1500, elapsedMs: null, timeBase: "worker", workerElapsedMs: 340 }, + ] }; +} + +test("native observation timing projects backend host steps, worker durations and missing SDK evidence", () => { + const sample = lifecycleTimingSample(record())!; + expect(sample.invocationToRelayMs).toBe(600); + expect(sample.backendStartupMs).toBe(500); + expect(sample.steps, "NATIVE_BACKEND_TIMING_USES_OBSERVED_CLOCK").toEqual({ "governed.gate_acquire": 100, + "backend.host_probe": 100, "backend.resources": 340, "backend.first_relay_request": 600 }); + expect(sample.backendSteps).toHaveLength(3); + expect(sample.backendSteps[2]).toEqual({ phase: "backend", name: "resources", startedAt: 1500, endedAt: 1500, + elapsedMs: 340, timeBase: "worker", workerElapsedMs: 340 }); + expect(sample.backendMissingEvidence).toEqual(["mcp_connect:brain", "first_enqueue", "prompt_recorded"]); +}); + +function piStartup(firstFrameAt = 1600) { + const source = record(); + source.firstFrameAt = firstFrameAt; + source.openSubPhases = ["preparation", "host_probe", "worker_spawn", "first_relay_request"].map(name => ({ + phase: "backend", name, startedAt: 1100, endedAt: 1700, elapsedMs: null, + })); + source.openSubPhases.push(...["bootstrap_imports", "resources", "session", "initialize"].map(name => ({ + phase: "backend", name, startedAt: 1500, endedAt: 1500, elapsedMs: null, timeBase: "worker" as const, workerElapsedMs: 31, + }))); + if (firstFrameAt <= 1700) source.openSubPhases.push({ phase: "backend", name: "first_backend_frame", startedAt: 1100, endedAt: firstFrameAt, elapsedMs: null }); + source.openSubPhases.sort((a, b) => a.startedAt - b.startedAt); + return lifecycleTimingSample(source)!; +} + +function claudeStartup() { + const source = record(); source.firstRelayRequestAt = null; + source.openSubPhases = ["host_probe", "worker_host_probe", "worker_launch"].map(name => ({ + phase: "backend", name, startedAt: 1100, endedAt: 1500, elapsedMs: null, + })); + source.openSubPhases.push({ phase: "backend", name: "first_backend_frame", startedAt: 1100, endedAt: 1600, elapsedMs: null }); + return lifecycleTimingSample(source, "claude_worker_fixture")!; +} + +test("native startup host stages cannot be relabelled as worker-clock durations", () => { + const valid = piStartup(); + const invalid = { ...valid, backendSteps: valid.backendSteps.map(step => step.name === "host_probe" + ? { ...step, timeBase: "worker" as const, workerElapsedMs: step.elapsedMs! } : step) }; + expect(() => backendStartupSamples("pi", invalid, Array(5).fill(valid)), "NATIVE_HOST_STEPS_KEEP_HOST_CLOCK") + .toThrow("BACKEND_TIMING_MISSING_STEPS host_probe"); +}); + +test("native Claude worker qualification contains host steps before turn completion", () => { + const valid = claudeStartup(); + const invalid = { ...valid, backendSteps: valid.backendSteps.map(step => step.name === "host_probe" + ? { ...step, startedAt: 2100, endedAt: 2200, elapsedMs: 100 } : step) }; + expect(() => backendStartupSamples("claude", invalid, Array(5).fill(valid)), "CLAUDE_FIXTURE_STEPS_STAY_INSIDE_OBSERVED_STARTUP") + .toThrow("BACKEND_TIMING_OUTSIDE_STARTUP host_probe"); +}); + +test("Claude qualification permits worker startup after prompt_prefix opened the Activity root", async () => { + const db = createUiDb(":memory:"), store = createActivityStore(db); + const pinned = Date.UTC(2026, 6, 12); let now = pinned + 1100; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", pinned + 1000, () => {}, () => now); + lifecycle.mark("backendInvokedAt"); + const recorder = createTurnRecorder({ store }, { turnId: "turn-ithaca", sessionId: "ithaca", lifecycle }); + const probe = lifecycle.startupTiming.start("host_probe"); now += 20; probe(); + recorder.observeActivity({ kind: "prompt_prefix", resumed: false, + prefix: promptPrefixFingerprint({ tools: [], system: "Odysseus records Ithaca.", gitStatusIncluded: false }) }); + expect(store.lifecycle("turn-ithaca")!.firstFrameAt).toBe(pinned + 1120); + for (const name of ["worker_host_probe", "worker_launch"]) { + now += 10; const end = lifecycle.startupTiming.start(name); now += 10; end(); + } + now += 10; recorder.observeFrame({ type: "session_info", sessionId: "ithaca", isNew: true }); + now += 10; recorder.finish("success"); lifecycle.finish("success"); await recorder.settled(); + const sample = lifecycleTimingSample(store.lifecycle("turn-ithaca")!, "claude_worker_fixture")!; + let output: ReturnType | undefined; + expect(() => { output = backendStartupSamples("claude", sample, Array(5).fill(sample)); }, + "CLAUDE_BOUNDARY_MUST_INCLUDE_POST_PREFIX_WORKER_STARTUP").not.toThrow(); + expect(output!.firstAfterStart?.backendSteps.find(step => step.name === "worker_launch")?.endedAt).toBe(pinned + 1160); + expect(output!.firstAfterStart?.invocationToRelayMs).toBeNull(); + } finally { clock.mockRestore(); db.close(); } +}); + +test("Claude qualification requires an observed terminal bound instead of guessing from first frame", () => { + const valid = claudeStartup(); + const source = record(); source.firstRelayRequestAt = null; source.endedAt = null; + source.openSubPhases = valid.backendSteps; + const pending = lifecycleTimingSample(source, "claude_worker_fixture")!; + expect(() => backendStartupSamples("claude", pending, Array(5).fill(valid)), "CLAUDE_TERMINAL_BOUND_MUST_BE_OBSERVED") + .toThrow("BACKEND_TIMING_BOUNDARY_MISSING"); +}); + +for (const [name, endedAt] of [["resources", 1550], ["ithaca_extra", 1550], ["ithaca_extra", null]] as const) { + test(`native worker duration ${name} cannot fabricate a host interval ending at ${endedAt}`, () => { + const valid = piStartup(); + const invalid = { ...valid, backendSteps: [...valid.backendSteps.filter(step => step.name !== name), { + phase: "backend", name, timeBase: "worker" as const, workerElapsedMs: 9, elapsedMs: 9, startedAt: 1500, endedAt, + }] }; + expect(() => backendStartupSamples("pi", invalid, Array(5).fill(valid)), "WORKER_HOST_TIMESTAMPS_ARE_ONE_RECEIPT_POINT") + .toThrow(`BACKEND_TIMING_WORKER_RECEIPT_POINT ${name}`); + }); +} + +for (const [name, start, end] of [ + ["host_probe", 1000, 1200], ["host_probe", 1800, 1900], ["host_probe", 1600, 1800], + ["host_probe", 1600, 1500], ["resources", 1800, 1800], ["ithaca_extra", 1800, 1900], +] as const) { + test(`native startup rejects ${name} outside its interval (${start}, ${end})`, () => { + const valid = piStartup(); + const steps = valid.backendSteps.filter(step => step.name !== name); + const replacement = { phase: "backend", name, startedAt: start, endedAt: end, elapsedMs: Math.max(0, end - start), + ...(name === "resources" ? { timeBase: "worker" as const, workerElapsedMs: 0 } : {}) }; + const invalid = { ...valid, backendSteps: [...steps, replacement] }; + expect(() => backendStartupSamples("pi", invalid, Array(5).fill(valid)), "NATIVE_STEPS_STAY_INSIDE_STARTUP_INTERVAL") + .toThrow(`BACKEND_TIMING_OUTSIDE_STARTUP ${name}`); + }); +} + +for (const receiptFirst of [true, false]) { + test(`equal-millisecond frame/relay observations preserve actual order (receipt first=${receiptFirst})`, () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); let now = 1100; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => now); + life.mark("backendInvokedAt"); + for (const name of ["preparation", "host_probe", "worker_spawn"]) life.startupTiming.start(name)(); + for (const name of ["bootstrap_imports", "resources", "session", "initialize"]) life.startupTiming.worker(name, 31); + now = 1700; + if (receiptFirst) { life.startupTiming.received(); life.firstFrame("turn-ithaca"); } + else { life.firstFrame("turn-ithaca"); life.startupTiming.received(); } + life.finish("success"); + const sample = lifecycleTimingSample(store.lifecycle("turn-ithaca")!)!; + expect(sample.backendSteps.filter(step => step.name === "first_backend_frame")).toHaveLength(receiptFirst ? 0 : 1); + let output: ReturnType | undefined; + expect(() => { output = backendStartupSamples("pi", sample, Array(5).fill(sample)); }, + "EQUAL_MILLISECONDS_DO_NOT_PROVE_EVENT_ORDER").not.toThrow(); + expect(output!.firstAfterStart?.invocationToRelayMs).toBe(600); + if (!receiptFirst) { + const malformed = { ...sample, backendSteps: sample.backendSteps.map(step => step.name === "first_backend_frame" ? { ...step, startedAt: 1101 } : step) }; + expect(() => backendStartupSamples("pi", malformed, Array(5).fill(sample)), "EQUAL_MILLISECOND_PRESENT_FRAME_IS_VALIDATED") + .toThrow("BACKEND_TIMING_MISSING_STEPS first_backend_frame"); + } + } finally { db.close(); } + }); +} + +test("the Claude worker-fixture projection never publishes inferred SDK-init durations", () => { + const source = record(); source.firstRelayRequestAt = null; + source.openSubPhases = [ + { phase: "backend", name: "worker_launch", startedAt: 1100, endedAt: 1200, elapsedMs: null }, + { phase: "backend", name: "runtime_to_sdk_init", startedAt: 1200, endedAt: null, elapsedMs: null }, + ]; + expect(lifecycleTimingSample(source)!.steps["backend.runtime_to_sdk_init"]).toBe(800); + const fixture = lifecycleTimingSample(source, "claude_worker_fixture")!; + expect(fixture.steps, "WORKER_FIXTURE_CANNOT_PUBLISH_UNOBSERVED_SDK_DURATION").toEqual({ "governed.gate_acquire": 100, "backend.worker_launch": 100 }); + expect(fixture.backendSteps.map(step => step.name)).toEqual(["worker_launch"]); +}); + +for (const name of ["first_backend_frame", "first_relay_request"]) { + test(`native Pi startup proof rejects a missing ${name} step even with the observed timestamp`, () => { + const sample = { ...piStartup(), backendInvokedAt: 1100, firstFrameAt: 1600, firstRelayRequestAt: 1700 }; + expect(backendStartupSamples("pi", sample, Array(5).fill(sample)).firstAfterStart?.invocationToRelayMs).toBe(600); + const missing = { ...sample, backendSteps: sample.backendSteps.filter(step => step.name !== name) }; + expect(() => backendStartupSamples("pi", sample, [sample, sample, missing, sample, sample]), "PI_NATIVE_REQUIRES_MILESTONE_STEPS") + .toThrow(`BACKEND_TIMING_MISSING_STEPS ${name}`); + }); + for (const endpoint of ["startedAt", "endedAt"] as const) { + test(`native Pi startup proof rejects ${name} with a mismatched ${endpoint}`, () => { + const sample = piStartup(); + const mismatched = { ...sample, backendSteps: sample.backendSteps.map(step => step.name === name + ? { ...step, [endpoint]: step[endpoint]! + 1 } : step) }; + expect(() => backendStartupSamples("pi", mismatched, Array(5).fill(sample)), "PI_NATIVE_MILESTONES_MATCH_OBSERVED_TIMESTAMPS") + .toThrow(`BACKEND_TIMING_MISSING_STEPS ${name}`); + }); + } +} + +test("a Pi first frame observed after the relay has no startup-bracket step", () => { + const sample = piStartup(1800); + expect(sample.backendSteps.filter(step => step.name === "first_backend_frame")).toEqual([]); + expect(backendStartupSamples("pi", sample, Array(5).fill(sample)).firstAfterStart?.backendStartupMs).toBe(700); +}); + +test("the native Claude worker fixture preserves absent relay and SDK evidence", () => { + const sample = claudeStartup(); + const output = backendStartupSamples("claude", sample, Array(5).fill(sample)); + expect(output.firstAfterStart?.invocationToRelayMs).toBeNull(); + expect(output.warm.map(row => row?.invocationToRelayMs)).toEqual([null, null, null, null, null]); + expect(output.coverage, "CLAUDE_WORKER_FIXTURE_DOES_NOT_CLAIM_MODEL_STARTUP").toEqual({ worker: "native", sdk: "mock_query", firstRelayRequest: "not_exercised" }); +}); + +test("native startup proof rejects a relay receipt without a startup breakdown", () => { + const source = record(); source.openSubPhases = source.openSubPhases!.filter(step => step.name === "first_relay_request"); + const sample = lifecycleTimingSample(source)!; + expect(() => backendStartupSamples("pi", sample, Array(5).fill(sample)), "NATIVE_STARTUP_BREAKDOWN_CANNOT_BE_ONLY_A_RECEIPT") + .toThrow("BACKEND_TIMING_MISSING_STEPS"); +}); + +for (const name of ["preparation", "host_probe", "worker_spawn", "bootstrap_imports", "resources", "session", "initialize"]) { + test(`native Pi startup proof requires ${name} evidence on every warm sample`, () => { + const sample = piStartup(); + expect(backendStartupSamples("pi", sample, Array(5).fill(sample)).firstAfterStart?.invocationToRelayMs).toBe(600); + const missing = { ...sample, backendSteps: sample.backendSteps.filter(step => step.name !== name) }; + expect(() => backendStartupSamples("pi", sample, [sample, sample, missing, sample, sample]), "NATIVE_STARTUP_REQUIRES_EACH_PHASE") + .toThrow(`BACKEND_TIMING_MISSING_STEPS ${name}`); + }); +} + +test("native timing never infers relay receipt from failure or backfills historical evidence", () => { + const failed = record(); failed.subPhases = []; failed.firstRelayRequestAt = null; failed.failureObservedAt = 1600; + failed.openSubPhases = [{ phase: "backend", name: "worker_launch", startedAt: 1200, endedAt: null, elapsedMs: null }]; + expect(lifecycleTimingSample(failed)).toMatchObject({ invocationToRelayMs: null, steps: { "backend.worker_launch": 400 } }); + const historical = record(); delete historical.firstRelayRequestAt; delete historical.backendMissingEvidence; delete historical.subPhases; delete historical.openSubPhases; + expect(lifecycleTimingSample(historical)).toMatchObject({ invocationToRelayMs: null, backendSteps: [], backendMissingEvidence: null }); + expect(lifecycleTimingSample(undefined)).toBeNull(); +}); From ee7f4c1778a6dff9017896a8aa71aed3b9325143 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 06:02:11 +0100 Subject: [PATCH 03/18] CONTRACT: feat(ui): retain owner-bound client turn arrival receipts (#4321) * CONTRACT: feat(ui): retain owner-bound client turn arrival receipts * fix(ui): contain client timing report transport failures * CONTRACT: docs(ui): clarify client clock observation bounds * CONTRACT: chore(ui): refresh client receipt API reports * test(ui): preserve previous activity wire schema compatibility * CONTRACT: fix(ui): negotiate client turn receipt support * CONTRACT: fix(ui): isolate client timing receipts through host completion * test(ui-sdk): preserve receipt fixture literal types * test(ui): defer serialization assertions to query integration * CONTRACT: fix(ui): preserve Send boundaries and receipt integrity * docs: refresh draft client citations after receipt timing changes * chore: record loose server timing schema API * test(ui-server): preserve Activity frame discriminant literals * CONTRACT: fix(ui): omit timing when a snapshot loses its Send boundary * test(ui-server): keep client receipts out of Activity tool results * CONTRACT: fix(ui): keep receipt timing nonblocking and snapshot consistent * chore: record optional lifecycle snapshot API * docs: distinguish lexical probe bounds from receipt byte validation * CONTRACT: fix(ui): decouple client receipts from terminal persistence * docs: align governed refresh citation after receipt changes * test(ui-server): scope idle probe to publisher input * fix(ui-server): read Activity snapshots without waiting for writes --- .changeset/client-turn-arrival-receipts.md | 15 + api-report/ui-sdk.txt | 77 ++++- api-report/ui-server.txt | 17 +- docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/cost-tracking.md | 2 +- docs/decisions/governed-writable-workers.md | 2 +- .../paid-cli-provider-qualification.md | 2 +- docs/integration-contract/package-api.md | 11 + docs/integration-contract/wire.md | 81 +++++ .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 4 +- docs/plans/chat-history-deletion.md | 2 +- docs/process/test-waits.md | 2 +- packages/ui-kit/vitest.config.ts | 3 +- .../ui-react/src/components/chat/composer.tsx | 13 +- packages/ui-react/src/connection.ts | 16 +- packages/ui-react/src/lib/draft-client.ts | 4 + packages/ui-react/src/ws-client/account.ts | 4 +- packages/ui-react/src/ws-client/turn-clock.ts | 135 +++++++++ .../browser/client-turn-receipt.offline.tsx | 185 ++++++++++++ .../browser/client-turn-server-command.ts | 50 ++++ .../ui-react/tests/client-turn-clock.test.ts | 229 ++++++++++++++ .../fixtures/client-turn-browser-server.ts | 76 +++++ packages/ui-sdk/src/protocol.ts | 26 +- packages/ui-sdk/src/schemas.ts | 24 +- .../ui-sdk/tests/client-turn-receipt.test.ts | 23 ++ .../migrations/095_client_turn_receipts.sql | 7 + .../ui-server/src/activity/store-writes.ts | 2 +- packages/ui-server/src/activity/store.ts | 97 ++++-- packages/ui-server/src/activity/stream.ts | 31 +- .../ui-server/src/activity/turn-lifecycle.ts | 5 +- .../src/ws/bridge-capabilities/emission.ts | 5 + .../ui-server/src/ws/client-turn-receipts.ts | 31 ++ packages/ui-server/src/ws/connection.ts | 46 ++- .../src/ws/handlers/client-turn-receipt.ts | 20 ++ packages/ui-server/src/ws/handlers/index.ts | 2 + packages/ui-server/src/ws/run-session.ts | 8 +- packages/ui-server/src/ws/session-run/slot.ts | 4 +- .../ui-server/src/ws/session-run/teardown.ts | 13 +- packages/ui-server/src/ws/session-run/turn.ts | 4 +- .../ui-server/src/ws/session-run/types.ts | 2 + .../tests/client-turn-completion.test.ts | 109 +++++++ .../tests/client-turn-isolation.test.ts | 279 ++++++++++++++++++ .../tests/client-turn-read-snapshot.test.ts | 56 ++++ .../tests/client-turn-receipt.test.ts | 135 +++++++++ .../tests/client-turn-stream-race.test.ts | 122 ++++++++ .../fixtures/client-turn-writer-probe.ts | 17 ++ .../fixtures/previous-client-turn-schema.ts | 102 +++++++ 48 files changed, 2031 insertions(+), 73 deletions(-) create mode 100644 .changeset/client-turn-arrival-receipts.md create mode 100644 packages/ui-react/src/ws-client/turn-clock.ts create mode 100644 packages/ui-react/tests/browser/client-turn-receipt.offline.tsx create mode 100644 packages/ui-react/tests/browser/client-turn-server-command.ts create mode 100644 packages/ui-react/tests/client-turn-clock.test.ts create mode 100644 packages/ui-react/tests/fixtures/client-turn-browser-server.ts create mode 100644 packages/ui-sdk/tests/client-turn-receipt.test.ts create mode 100644 packages/ui-server/migrations/095_client_turn_receipts.sql create mode 100644 packages/ui-server/src/ws/client-turn-receipts.ts create mode 100644 packages/ui-server/src/ws/handlers/client-turn-receipt.ts create mode 100644 packages/ui-server/tests/client-turn-completion.test.ts create mode 100644 packages/ui-server/tests/client-turn-isolation.test.ts create mode 100644 packages/ui-server/tests/client-turn-read-snapshot.test.ts create mode 100644 packages/ui-server/tests/client-turn-receipt.test.ts create mode 100644 packages/ui-server/tests/client-turn-stream-race.test.ts create mode 100644 packages/ui-server/tests/fixtures/client-turn-writer-probe.ts create mode 100644 packages/ui-server/tests/fixtures/previous-client-turn-schema.ts diff --git a/.changeset/client-turn-arrival-receipts.md b/.changeset/client-turn-arrival-receipts.md new file mode 100644 index 0000000000..8f093adff6 --- /dev/null +++ b/.changeset/client-turn-arrival-receipts.md @@ -0,0 +1,15 @@ +--- +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +--- + +Record client-monotonic turn frame-arrival timings once after host cleanup sends its final idle. Store the first owner-authorized report separately and join it onto lifecycle reads without modifying completed host records. Disconnects and lost reports leave only the measurement absent. Receipt transport has its own bounded routing and rate budget, malformed stored samples degrade only their own measurement, and existing Activity store implementers need not provide receipt support. + +Capture composer Send before snapshot-save waits, retain early lifecycle arrivals, and meter before JSON decoding. Final host idle follows cleanup; it does not wait for a timing commit. Preserve unknown server timing fields and surface stored corruption even after embedded NUL bytes. + +Keep lifecycle timing persistence off the turn's idle path. Only the client that actually dispatches a request may report its saved Send timing. Correlate queue-start announcements before backend identity, read lifecycle snapshots with their sequence consistently, and validate the original stored receipt byte length. Older Activity store implementations remain supported. + +Determine receipt eligibility from in-memory cleanup state without lifecycle I/O on idle. Defer receipt storage behind the turn's persistence queue off the turn path so successful file-backed commits cannot lose their client report. Disqualify a shared request acknowledged before local dispatch, and enforce owner/duplicate and revocation checks while deferred. + +Keep consistent Activity read snapshots off the application writer turn, so even an empty stream pump remains responsive while a file-backed write is pending. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index f275885772..bd100653cf 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -147,6 +147,8 @@ export "." (./src/index.ts) type ClientSessionResume type ClientToolApproval type ClientToolDenial + type ClientTurnReceipt + type ClientTurnTiming type ConfigurationCoverageRead type ConfiguredModule type ConflictVersionSelection @@ -740,6 +742,8 @@ export "./client" (./src/client/index.ts) type ClientSessionResume type ClientToolApproval type ClientToolDenial + type ClientTurnReceipt + type ClientTurnTiming type CompleteShareInput type CompleteShareResult type ComputeHealthToolInput @@ -1787,6 +1791,8 @@ export "./protocol" (./src/protocol.ts) type ClientSessionResume type ClientToolApproval type ClientToolDenial + type ClientTurnReceipt + type ClientTurnTiming type ConfigurationCoverageRead type ConflictVersionSelection type ConsumerServerMessage @@ -2168,6 +2174,7 @@ export "./render" (./src/render.ts) export "./schemas" (./src/schemas.ts) MAX_CLIENT_FRAME_BYTES + MAX_CLIENT_TURN_RECEIPT_BYTES MAX_PROMPT_CHARS MAX_SERVER_FRAME_BYTES type ParseFrameResult @@ -2214,6 +2221,7 @@ export "./schemas" (./src/schemas.ts) clientSessionResumeSchema clientToolApprovalSchema clientToolDenialSchema + clientTurnTimingSchema conversationAudioFormatSchema conversationCapabilitiesSchema conversationDisclosureSchema @@ -2621,6 +2629,8 @@ export "./server" (./src/server/index.ts) type ClientSessionResume type ClientToolApproval type ClientToolDenial + type ClientTurnReceipt + type ClientTurnTiming type CoastlineConfig type CoastlineRequest type CoastlineResult @@ -4482,6 +4492,8 @@ signatures (every public export and the types it is made of) export type ActivitySpanOutcome = "success" | "error" | "timeout" | "cancelled" | "denied" | "interrupted"; ActivityTurnLifecycle (packages/ui-sdk/src/protocol.ts) export interface ActivityTurnLifecycle { + clientTiming?: ClientTurnTiming; + clientTimingUnavailable?: "invalid_receipt"; hostEvents: Array<{ principalId: string; kind: "turn_cancelled" | "ask_user_cancelled" | "principal_revoked" | "follow_up"; @@ -7440,7 +7452,7 @@ signatures (every public export and the types it is made of) turnId?: string; } ClientMessage (packages/ui-sdk/src/protocol.ts) - export type ClientMessage = ClientSafetyRead | ClientSafetySubscribe | ClientSafetyUnsubscribe | ClientScopeDecision | ClientHello | ClientRetryTurn | ClientRetryStatus | ClientChatMessage | ClientToolApproval | ClientToolDenial | ClientCancelRequest | ClientSessionResume | ClientAskUserResponse | ClientAskUserCancel | ClientAskUserListResponse | ClientAskUserRankResponse | ClientAskUserFormResponse | ClientAskAnswerStatus | ClientPing | ClientLocationResponse | ClientLocationError | ClientMaskResponse | ClientMaskError | ClientMarkupError | ClientActivitySubscribe | ClientActivityUnsubscribe | ClientLocalExchange | ClientHandoffPrepare | ClientHandoffPrepareCancel | ClientHandoffStatus | ClientInboxResolve | ClientInboxSnooze | ClientInboxSubscribe | ClientInboxUnsubscribe | ClientDialogueRead | ClientConversationStart | ClientConversationAudio | ClientConversationEndpoint | ClientConversationCommit | ClientConversationPlayback | ClientConversationStop; + export type ClientMessage = ClientSafetyRead | ClientSafetySubscribe | ClientSafetyUnsubscribe | ClientScopeDecision | ClientHello | ClientTurnReceipt | ClientRetryTurn | ClientRetryStatus | ClientChatMessage | ClientToolApproval | ClientToolDenial | ClientCancelRequest | ClientSessionResume | ClientAskUserResponse | ClientAskUserCancel | ClientAskUserListResponse | ClientAskUserRankResponse | ClientAskUserFormResponse | ClientAskAnswerStatus | ClientPing | ClientLocationResponse | ClientLocationError | ClientMaskResponse | ClientMaskError | ClientMarkupError | ClientActivitySubscribe | ClientActivityUnsubscribe | ClientLocalExchange | ClientHandoffPrepare | ClientHandoffPrepareCancel | ClientHandoffStatus | ClientInboxResolve | ClientInboxSnooze | ClientInboxSubscribe | ClientInboxUnsubscribe | ClientDialogueRead | ClientConversationStart | ClientConversationAudio | ClientConversationEndpoint | ClientConversationCommit | ClientConversationPlayback | ClientConversationStop; ClientPing (packages/ui-sdk/src/protocol.ts) export interface ClientPing { type: "ping"; @@ -7496,6 +7508,19 @@ signatures (every public export and the types it is made of) channel?: ApprovalChannel; turnId?: string; } + ClientTurnReceipt (packages/ui-sdk/src/protocol.ts) + export interface ClientTurnReceipt { + type: "client_turn_receipt"; + turnId: string; + timing: ClientTurnTiming; + } + ClientTurnTiming (packages/ui-sdk/src/protocol.ts) + export interface ClientTurnTiming { + sendToFirstHostFrameMs: number; + sendToFirstContentFrameMs?: number; + lastContentFrameToIdleMs?: number; + sendToFirstPhaseStatusFrameMs?: number; + } CoastlineConfig (packages/geo/src/coastline.ts) recorded in api-report/geo.txt CoastlineRequest (packages/geo/src/coastline.ts) recorded in api-report/geo.txt CoastlineResult (packages/geo/src/coastline.ts) recorded in api-report/geo.txt @@ -11051,6 +11076,8 @@ signatures (every public export and the types it is made of) }, z.core.$strip>; MAX_CLIENT_FRAME_BYTES (packages/ui-sdk/src/schemas.ts) const MAX_CLIENT_FRAME_BYTES: 12000000; + MAX_CLIENT_TURN_RECEIPT_BYTES (packages/ui-sdk/src/schemas.ts) + const MAX_CLIENT_TURN_RECEIPT_BYTES: 4096; MAX_IMAGES_PER_MESSAGE (packages/ui-sdk/src/protocol.ts) const MAX_IMAGES_PER_MESSAGE: 4; MAX_IMAGE_BYTES (packages/ui-sdk/src/protocol.ts) @@ -11300,6 +11327,7 @@ signatures (every public export and the types it is made of) } | { ok: false; error: string; + frameType?: "client_turn_receipt"; }; PasskeySummary (packages/ui-sdk/src/protocol.ts) export interface PasskeySummary { @@ -13816,6 +13844,7 @@ signatures (every public export and the types it is made of) } ServerStatus (packages/ui-sdk/src/protocol.ts) export interface ServerStatus extends SessionScoped { + hostTurnComplete?: true; type: "status"; status: "thinking" | "tool_executing" | "idle" | "cancelled" | "queued"; detail?: string; @@ -16019,6 +16048,15 @@ signatures (every public export and the types it is made of) submissionId: z.ZodString; turnId: z.ZodString; type: z.ZodLiteral<"scope_decision">; + }, z.core.$strict>, z.ZodObject<{ + timing: z.ZodObject<{ + lastContentFrameToIdleMs: z.ZodOptional; + sendToFirstContentFrameMs: z.ZodOptional; + sendToFirstHostFrameMs: z.ZodNumber; + sendToFirstPhaseStatusFrameMs: z.ZodOptional; + }, z.core.$strict>; + turnId: z.ZodString; + type: z.ZodLiteral<"client_turn_receipt">; }, z.core.$strict>, z.ZodObject<{ failedTurnId: z.ZodString; requestId: z.ZodString; @@ -16512,6 +16550,13 @@ signatures (every public export and the types it is made of) turnId: z.ZodOptional; type: z.ZodLiteral<"tool_denial">; }, z.core.$loose>; + clientTurnTimingSchema (packages/ui-sdk/src/schemas.ts) + const clientTurnTimingSchema: z.ZodObject<{ + lastContentFrameToIdleMs: z.ZodOptional; + sendToFirstContentFrameMs: z.ZodOptional; + sendToFirstHostFrameMs: z.ZodNumber; + sendToFirstPhaseStatusFrameMs: z.ZodOptional; + }, z.core.$strict>; clipLine (packages/geo/src/coastline.ts) recorded in api-report/geo.txt closeAgainstViewport (packages/geo/src/coastline.ts) recorded in api-report/geo.txt closedRings (packages/geo/src/coastline.ts) recorded in api-report/geo.txt @@ -22077,6 +22122,13 @@ signatures (every public export and the types it is made of) budgetAdmissionMs: z.ZodNullable; budgetAdmittedAt: z.ZodNullable; budgetStartedAt: z.ZodNullable; + clientTiming: z.ZodOptional; + sendToFirstContentFrameMs: z.ZodOptional; + sendToFirstHostFrameMs: z.ZodNumber; + sendToFirstPhaseStatusFrameMs: z.ZodOptional; + }, z.core.$loose>>; + clientTimingUnavailable: z.ZodOptional>; dequeuedAt: z.ZodNullable; endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; @@ -22212,6 +22264,13 @@ signatures (every public export and the types it is made of) budgetAdmissionMs: z.ZodNullable; budgetAdmittedAt: z.ZodNullable; budgetStartedAt: z.ZodNullable; + clientTiming: z.ZodOptional; + sendToFirstContentFrameMs: z.ZodOptional; + sendToFirstHostFrameMs: z.ZodNumber; + sendToFirstPhaseStatusFrameMs: z.ZodOptional; + }, z.core.$loose>>; + clientTimingUnavailable: z.ZodOptional>; dequeuedAt: z.ZodNullable; endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; @@ -24323,6 +24382,7 @@ signatures (every public export and the types it is made of) activeSessionId: z.ZodOptional; detail: z.ZodOptional; effectiveThinkingLevel: z.ZodCatch>>; + hostTurnComplete: z.ZodOptional>; requestId: z.ZodOptional; retry: z.ZodCatch; budgetAdmittedAt: z.ZodNullable; budgetStartedAt: z.ZodNullable; + clientTiming: z.ZodOptional; + sendToFirstContentFrameMs: z.ZodOptional; + sendToFirstHostFrameMs: z.ZodNumber; + sendToFirstPhaseStatusFrameMs: z.ZodOptional; + }, z.core.$loose>>; + clientTimingUnavailable: z.ZodOptional>; dequeuedAt: z.ZodNullable; endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; @@ -25363,6 +25430,13 @@ signatures (every public export and the types it is made of) budgetAdmissionMs: z.ZodNullable; budgetAdmittedAt: z.ZodNullable; budgetStartedAt: z.ZodNullable; + clientTiming: z.ZodOptional; + sendToFirstContentFrameMs: z.ZodOptional; + sendToFirstHostFrameMs: z.ZodNumber; + sendToFirstPhaseStatusFrameMs: z.ZodOptional; + }, z.core.$loose>>; + clientTimingUnavailable: z.ZodOptional>; dequeuedAt: z.ZodNullable; endedAt: z.ZodNullable; failureObservedAt: z.ZodNullable; @@ -28683,6 +28757,7 @@ signatures (every public export and the types it is made of) activeSessionId: z.ZodOptional; detail: z.ZodOptional; effectiveThinkingLevel: z.ZodCatch>>; + hostTurnComplete: z.ZodOptional>; requestId: z.ZodOptional; retry: z.ZodCatch; lifecycle(turnId: string): ActivityTurnLifecycle | null; lifecycles(sessionId?: string, limit?: number): ActivityTurnLifecycle[]; + snapshotLifecycles?(scope: { + turnId?: string; + sessionId?: string; + limit?: number; + }): { + lifecycles: ActivityTurnLifecycle[]; + highWaterSeq: Record; + }; readonly writer: string; startSpan(input: StartSpanInput): SpanRow; endSpan(spanId: string, input: EndSpanInput): boolean; @@ -174,7 +183,7 @@ signatures (every public export and the types it is made of) close(): void; } ActivityWriteMethod (packages/ui-server/src/activity/store.ts) - export type ActivityWriteMethod = "writeLifecycle" | "startSpan" | "endSpan" | "patchSpan" | "appendEvent" | "heartbeat" | "cascadeClose" | "sweepOwnOrphans" | "sweepStale" | "rollupRun" | "prune"; + export type ActivityWriteMethod = "writeClientReceipt" | "writeLifecycle" | "startSpan" | "endSpan" | "patchSpan" | "appendEvent" | "heartbeat" | "cascadeClose" | "sweepOwnOrphans" | "sweepStale" | "rollupRun" | "prune"; AgentConfig (packages/ui-server/src/config/env.ts) export interface AgentConfig { backend: string | null; @@ -241,7 +250,9 @@ signatures (every public export and the types it is made of) type Awaitable = T | Promise; AwaitableActivityStore (packages/ui-server/src/activity/store.ts) export type AwaitableActivityStore = Omit & { - [K in ActivityWriteMethod]: (...args: Parameters) => Awaitable>; + [K in Exclude]: (...args: Parameters) => Awaitable>; + } & { + writeClientReceipt?: (...args: Parameters>) => Awaitable>>; }; BackendBootFailure (packages/ui-server/src/agent/backend.ts) export interface BackendBootFailure { diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 6af13c6e44..facc2f97da 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -471,7 +471,7 @@ into them. billing now stays unknown for every origin; server credentials and an observed runtime version cannot establish a child's billing. The recorded root-span attribute is the source of truth - (`const attrBilling`, `packages/ui-server/src/activity/store.ts:554-555`); + (`const attrBilling`, `packages/ui-server/src/activity/store.ts:566-567`); [cost-tracking.md](cost-tracking.md#recorded-billing-is-the-rollup-source-of-truth-293) records the 2026-09-30 ruling and frozen-history semantics. - **Model discovery prefers the API key** and describes that as "mirroring the diff --git a/docs/decisions/cost-tracking.md b/docs/decisions/cost-tracking.md index 6bd625bbcd..b62cdfaea2 100644 --- a/docs/decisions/cost-tracking.md +++ b/docs/decisions/cost-tracking.md @@ -128,7 +128,7 @@ math and authoritative backend cost remain available independently; aggregates exclude unknown effective costs from their sum and count the runs as unpriced. Explicit valid subscription/API classifications keep their existing behavior. The rollup reads the root attribute and prices child usage for cron locally -(`const attrBilling`, `packages/ui-server/src/activity/store.ts:554-555`). +(`const attrBilling`, `packages/ui-server/src/activity/store.ts:566-567`). This is a change to the evidence used for new computations, not a historical backfill. First non-null billing, list cost, effective cost and estimate values diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 61e3df6d20..1cd1159c9d 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1843,7 +1843,7 @@ own configuration does, and that needs a maintainer ruling first. **Why.** Every governed turn queues an automatic index refresh after it (`host.governedTurns?.refresh(host.workerLock)`, -`packages/ui-server/src/ws/session-run/teardown.ts:73`). The refresh usually finishes +`packages/ui-server/src/ws/session-run/teardown.ts:74`). The refresh usually finishes while the next turn runs, so that turn's finish observation found a rewritten `brain.db` and copied a whole new version of it into retained objects, inside the observation's worker hold. #2831 measured 36 versions of a ~120 MB index in diff --git a/docs/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index abfd985d6b..da0d4abd4c 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -141,7 +141,7 @@ usage stay unknown; never infer tokens from payload bytes or vector length. The current shared inference/egress counter measures application or opaque transport bytes. These units stay separate from provider token, character, image or time units. Activity's current token pricing uses input/output/cache -classes (`priceUsage`, `packages/ui-server/src/activity/store.ts:1075-1105`); +classes (`priceUsage`, `packages/ui-server/src/activity/store.ts:1134-1164`); it cannot silently price image modalities or enterprise billable characters as ordinary tokens. Image model-table costs remain estimates; unknown model/rate combinations remain unknown. No live invoice or price validation is implied by diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 30add9d3b6..8369a9d305 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5293,6 +5293,17 @@ settle after their commit. An `ActivityStore`, whose writes all commit before they return, satisfies it. Refusal classes and transaction order are unchanged. These shapes change at a pre-1.0 minor under that ruling. +### Consistent Activity lifecycle snapshots + +`ActivityStore` adds optional `snapshotLifecycles({ turnId?, sessionId?, limit? })`, +returning `{ lifecycles, highWaterSeq }` from one read transaction. Each lifecycle +includes its separately stored client receipt, and each sequence belongs to that +same database snapshot. `AwaitableActivityStore` inherits this synchronous read. +Prior store implementations need not provide it: the Activity stream reads a +conservative sequence floor before re-reading lifecycle data, permitting replay +without losing a receipt delta. Existing methods and factory return shapes remain +compatible. This additive API ships in a minor release. + ### Late Activity session association `ActivityStore.patchSpan` accepts an optional `sessionId` to bind an unnamed diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 25b499a5ea..39b304db7d 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -562,6 +562,87 @@ The whole envelope is host-only: `query_activity` never includes it in a provider-facing tool result, including on recent, full, pruned or lifecycle-only run queries. The owner-facing Activity API and stream retain the envelope. +#### Client frame-arrival receipt (additive, #4282) + +A host whose Activity store supports receipt writes advertises the optional boolean capability +`server_hello.capabilities.clientTurnReceipts: true`. Without this flag the +client sends no receipt, so an older host never receives an unknown message. +Negotiation resets with each socket. After receiving the host's final +`status: idle` with optional `hostTurnComplete: true`, the initiating client may +send exactly one best-effort `{ type: "client_turn_receipt", turnId, timing }` frame. +Backend idle frames do not carry this marker; the host strips any backend-supplied +marker. It describes completed host cleanup, decided only from in-memory state, +not a lifecycle database commit. Final idle performs no lifecycle read and never +waits for timing persistence or a writer lock. A receipt that arrives before its +terminal commits is held by the receipt handler, off the turn path, until that +turn's queued lifecycle writes settle. The atomic storage guard still checks +completion and ownership; a failed commit loses only the optional measurement. +The host retains at most 256 pending persistence gates, accepts only one waiting +owner report per gate, and refuses a report whose authorization expires or is +revoked while it waits. Full gate capacity drops only new optional samples and +recovers automatically as writes settle. +Initial thinking, accepted retry acknowledgements, and `session_queue.started` +correlate by `requestId` before `session_info`. Pending queue entries can establish +the first acknowledgement without binding a turn identity. `timing` contains non-negative finite millisecond pairs measured entirely on +the client's monotonic clock: + +- `sendToFirstHostFrameMs`: send to the first received host frame for this turn + (including its queued acknowledgement and lifecycle Activity frames received before + request-to-turn correlation). Send begins at the composer action, before snapshot + persistence or upload waits, and stays on that same monotonic clock until dispatch. + Capturing Send alone never authorizes a receipt: this client must successfully + dispatch that request on its own socket. A peer acknowledgement carrying the + same request id before local dispatch disqualifies that saved Send, including + queued entries and starts; later local dispatch cannot adopt the peer's turn. + Earlier uncorrelated turn arrivals also cannot become its first host frame. +- Optional `sendToFirstContentFrameMs`: send to the first non-empty + `thinking_delta` or `text_delta` frame received. +- Optional `lastContentFrameToIdleMs`: last such content frame received to + the host's final `status: idle` received. +- Optional `sendToFirstPhaseStatusFrameMs`: reserved for the first phase status + frame received; absent until phase-specific statuses are supported (#4311). + +These measure frame arrival, not presentation or paint. No host timestamp is +subtracted from a client timestamp. Missing content boundaries are absent, not +zero. A request without correlation, or a client disconnected during the turn, +reports nothing; reconnect/history replay cannot reconstruct arrival evidence. +The React client caps pending request observations and turn-arrival correlations +at 256 entries each. If eviction loses a possible first arrival, affected pending +requests lose their measurement rather than reporting a later frame as first. +A snapshot dispatched without its original Send boundary also reports nothing; +dispatch after reload or eviction cannot invent a new Send timestamp. A failed/lost report is never retried and never affects the turn. + +Receipt frames are capped at 4096 encoded bytes and have an independent rate +bucket. A bounded lexical routing probe identifies their message kind before +JSON decoding; only metered frames are decoded. A rejected or +schema-invalid receipt is recorded in diagnostics without a chat error or a voice +capture gap. Unidentifiable or oversized transport input retains the general +transport guard. Only `turnId` and `timing` are accepted; unknown envelope/timing fields and +negative or non-finite values are refused. The host binds ownership to the +accepting principal, independently of the session's creator. A report for a +missing, unfinished, unowned or differently owned turn is refused. The first +accepted report wins atomically; all later reports, even identical ones, are +refused without changing it. The host records refusals in its inbound-frame +rejection diagnostics; this telemetry message has no reply or turn-control effect. +Server-read `clientTiming` objects preserve unknown optional keys, while incoming +receipt timing remains strict. + +The receipt is separate from the host envelope, keyed by turn id, and joined +as optional `ActivityTurnLifecycle.clientTiming` on single, list and stream +reads. Receipt acceptance advances the lifecycle's stream sequence without +changing its completed host record. Lifecycle snapshots read the joined record +and its sequence in one read transaction, so a racing receipt delta cannot be +marked as already included in an older snapshot. Legacy store readers capture a +conservative sequence floor before reading data; replay is safe. Its owner binding and receipt are deleted +with the lifecycle record. Older records without an owner binding accept no +report and remain readable. Stored receipts are bounded by the original UTF-8 byte length, including bytes +after any embedded NUL or beyond the bounded read slice. A malformed stored receipt remains retained, omits its +pairs and exposes optional `clientTimingUnavailable: "invalid_receipt"` on that +record; the host envelope and other records remain readable. Client pairs and +receipt diagnostics never enter provider history, inference usage or cost accounting. + +#### Host milestones + `acceptedAt` is the observed host acceptance time, before routing/admission. Queued requests retain their observed queue acceptance and `dequeuedAt`; `queueWaitMs` is null when no queue interval was observed. Milestones are diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 63eb3dfda3..865e79f2c9 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -150,7 +150,7 @@ Stated before the requirements because five of them derive from it. thread_id, item_id, seq)` **carries `thread_id` explicitly** — activity stores its scope in the change row for exactly this reason ((`CREATE TABLE IF NOT EXISTS activity_changes (`, `packages/ui-server/migrations/007_activity.sql:58-66`), - (`snapshotRun(runId) {`, `packages/ui-server/src/activity/store.ts:894-923`)), and deriving scope through a join on a + (`snapshotRun(runId) {`, `packages/ui-server/src/activity/store.ts:953-980`)), and deriving scope through a join on a mutable item is weaker and breaks tombstones. `change_id` is the global cursor, `seq` is per-thread order. Append-only checkpoints, unique resolution records, scheduler heartbeats and budget reservations also need explicit durable storage. The four diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 2925d2ac39..84c3a5813b 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -125,7 +125,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. ### Relevant Code and Patterns - **Cursors and transactional snapshots:** (`CREATE TABLE IF NOT EXISTS activity_changes (`, `packages/ui-server/migrations/007_activity.sql:58-66`) - and (`snapshotRun(runId) {`, `packages/ui-server/src/activity/store.ts:894-923`). Reuse the algorithm; the + and (`snapshotRun(runId) {`, `packages/ui-server/src/activity/store.ts:953-980`). Reuse the algorithm; the activity stream is bound to activity store methods and frame types. - **Runtime lifecycle:** (`export function createActivityRuntime(`, `packages/ui-server/src/activity/runtime.ts:66-246`). Cron's scheduler owns manual triggers/history; it does not tick the inbox. @@ -717,7 +717,7 @@ recovered tick after killing the interval model-bearing operation; folded compaction is included in its existing call. **Patterns to follow:** the frozen-at-first-computation discipline of effective cost -(`function rollupRunInTx(runId: string) {`, `packages/ui-server/src/activity/store.ts:535-637`); env descriptor array for the new configuration values +(`function rollupRunInTx(runId: string) {`, `packages/ui-server/src/activity/store.ts:547-649`); env descriptor array for the new configuration values **Test scenarios:** - Covers AE11: two claims that would each fit but jointly exceed the cap — the second is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index e1f61f8818..90d0514bce 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -297,7 +297,7 @@ Concrete entry points include `readSessionRecovery` and both handoff stages (`startHandoff`, `packages/ui-server/src/ws/handoff.ts:100-110`; `prepareHandoff`, `packages/ui-server/src/ws/handoff.ts:273-285`). Draft autosave belongs to `createDraftClient` (`createDraftClient`, -`packages/ui-react/src/lib/draft-client.ts:54-66`); browser reloadable work belongs +`packages/ui-react/src/lib/draft-client.ts:55-67`); browser reloadable work belongs to `createLocalWork` (`createLocalWork`, `packages/ui-react/src/lib/local-work.ts:227-245`). The paired WS dispatcher is `packages/ui-server/src/ws/dispatch.ts`, with one handler per frame under `ws/handlers/`; gating its resume handler alone would leave HTTP, background readers and provider startup open. diff --git a/docs/process/test-waits.md b/docs/process/test-waits.md index 71fb309bce..cdb50b2253 100644 --- a/docs/process/test-waits.md +++ b/docs/process/test-waits.md @@ -318,7 +318,7 @@ be added to these windows. For real IME start and commit, input also arms the **800 ms host debounce** (`SAVE_DELAY_MS`, `packages/ui-react/src/lib/draft-client.ts:36-38`; -`schedule`, `packages/ui-react/src/lib/draft-client.ts:80-84`). The native horizon +`schedule`, `packages/ui-react/src/lib/draft-client.ts:81-85`). The native horizon is 1000 ms: that 800 ms opportunity plus 200 ms (25%) dispatch/IO/render headroom and the original two frames. The parallel 250 ms device debounce is inside this horizon. The final exact committed draft still has to reach the host. Returning diff --git a/packages/ui-kit/vitest.config.ts b/packages/ui-kit/vitest.config.ts index 55e4aaaa1a..bd751e3c51 100644 --- a/packages/ui-kit/vitest.config.ts +++ b/packages/ui-kit/vitest.config.ts @@ -1,3 +1,4 @@ +import { clientTurnServer } from "../ui-react/tests/browser/client-turn-server-command.ts"; import { recordingProof } from "../ui-react/tests/browser/offline/recording-proof.ts"; import { conversationServer } from "../ui-react/tests/browser/conversation-server-command.ts"; import { diagramArtifact, diagramFontStyles, diagramRasterComparison, diagramRepaintParity, fullRasterChromiumArgs } from "../ui-react/tests/browser/diagram-export-command.ts"; @@ -175,7 +176,7 @@ export default mergeConfig( browser: { enabled: true, screenshotFailures: false, - commands: { safetyServer, recordingProof, rankTap, conversationServer, mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, hygieneLifecycle, hygieneContextLifecycle, hygieneLifecycleCleanup, hygieneLifecycleFailures, dispatchActions, safetyGapChats, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, + commands: { clientTurnServer, safetyServer, recordingProof, rankTap, conversationServer, mermaidMedia, mermaidOutput, mermaidScreenComparison, buttonCapture, overlayMouse, dictationMotion, policyServer, storageServer, hygieneLoop, hygieneServer, hygieneLifecycle, hygieneContextLifecycle, hygieneLifecycleCleanup, hygieneLifecycleFailures, dispatchActions, safetyGapChats, sheetInput, focusCapture, formViewport, formConsumerStyles, rankFooterFonts, codeHighlightFailure, codeHighlightFailureCount, offlineScene, coldCapture, shareReview, transcriptionHttp, startRequestLog, requestLog, grantMicrophone }, // The fake microphone plays the generated 10-second fixture // (#1016). Chromium reads the file at launch, so it is written // when this config loads; the fake UI grants the permission. diff --git a/packages/ui-react/src/components/chat/composer.tsx b/packages/ui-react/src/components/chat/composer.tsx index 75442ef053..9ac3c2e4d5 100644 --- a/packages/ui-react/src/components/chat/composer.tsx +++ b/packages/ui-react/src/components/chat/composer.tsx @@ -1,3 +1,4 @@ +import { noteTurnSend } from "../../ws-client/turn-clock.js"; import { useStore } from "zustand"; import { ConversationUnassigned } from "../voice/conversation-unassigned.js"; import { ConversationField } from "../voice/conversation-field.js"; @@ -231,6 +232,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void // A send pressed while tracks upload is held for the draft it was pressed // in, by id: another draft opened meanwhile is never sent for it (#951). const [heldFor, setHeldFor] = useState(null); + const heldSendOrigin = useRef<{ draftId: string; at: number } | null>(null); const heldSend = heldFor !== null && heldFor === draftId; const setHeldSend = (held: boolean) => setHeldFor(held ? draftId : null); @@ -583,6 +585,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void draftIdRef.current = draftId; function handleSubmit() { + const sentAt = heldSend && heldSendOrigin.current?.draftId === draftId ? heldSendOrigin.current.at : performance.now(); // Dictated words are in the field by now (D6), so the field is the draft. const text = input.trim(); const currentTracks = trackUploads.files; @@ -597,7 +600,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void // in the save that clears the composer. A draft with legacy inline // images keeps the tab-local path below: a snapshot cannot hold them. if (snapshotsOn && chatRequestAck && attachments.length === 0 && currentTracks.length === 0) { - submitSnapshot(text, hasAttachments); + submitSnapshot(text, hasAttachments, sentAt); return; } @@ -606,10 +609,10 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void setEffortNotice("Your draft is kept. Retry or remove the failed track before sending."); return; } - if (currentTracks.some(trackPending)) { setHeldSend(true); return; } + if (currentTracks.some(trackPending)) { heldSendOrigin.current = { draftId, at: sentAt }; setHeldSend(true); return; } const fileHold = composerFilesHold(); if (fileHold.blocked) { setHeldSend(false); setEffortNotice(fileHold.blocked); return; } - if (fileHold.pending) { setHeldSend(true); return; } + if (fileHold.pending) { heldSendOrigin.current = { draftId, at: sentAt }; setHeldSend(true); return; } const readyFiles = currentTracks.filter(trackReady).map(track => track.meta!); // A send while a question is pending is the ANSWER to it, not a new @@ -642,6 +645,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void const chat = root.stores.chat.getState(); const source = dictated ? "voice-dictate" : "typed"; const requestId = chatRequestAck ? crypto.randomUUID() : undefined; + if (requestId) noteTurnSend(root.stores, requestId, sentAt); // A send while the session is busy is a follow-up the host queues. On a // host that reports its queue it waits as a pending pill, not in the // chat, and enters the transcript when its own turn starts (#1002). @@ -755,7 +759,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void * host acknowledges the save that creates it: that save is the slot's * reservation, and a full chat refuses it with nothing sent. */ - function submitSnapshot(text: string, hasAttachments: boolean) { + function submitSnapshot(text: string, hasAttachments: boolean, sentAt: number) { const store = root.stores.drafts.getState(); if (outgoingFull) { setEffortNotice(""); @@ -775,6 +779,7 @@ export function Composer({ send, handle }: { send: (msg: ClientMessage) => void } if (text) setLastPrompt(text); const requestId = crypto.randomUUID(); + noteTurnSend(root.stores, requestId, sentAt); const pending = own.filter(queuedPending); const files = current ? bindableFiles(current) : []; const message: Extract = { diff --git a/packages/ui-react/src/connection.ts b/packages/ui-react/src/connection.ts index d095a5755d..fc25ccc8d6 100644 --- a/packages/ui-react/src/connection.ts +++ b/packages/ui-react/src/connection.ts @@ -1,3 +1,4 @@ +import { bindTurnClock, createTurnClock } from "./ws-client/turn-clock.js"; import { attachTranscriptTimeline } from "./lib/transcript-timeline.js"; import { createConversationClient } from "./voice/conversation-client.js"; import { takeComposerTextAsAnswer } from "./lib/ask-user-typed.js"; @@ -30,12 +31,15 @@ export function createWebSocketClient(root: BrainUiServices) { let disposed = false; const isActive = () => root.authLock.state.getState().phase === "active"; + const turnClock = createTurnClock(send); + const unbindTurnClock = bindTurnClock(root.stores, turnClock); + const lease = createSocketLease({ url: () => root.wsUrl(), disposed: () => disposed, active: isActive, noteSocketOpen: () => root.stores.connection.getState().noteSocketOpen(), - onMessage: (message) => inbound.handleServerMessage(message), + onMessage: (message) => { turnClock.frame(message); inbound.handleServerMessage(message); }, onStatusChange: (status) => handleStatusChange(status), onClose: (close) => handleSocketClose(root, close, services.trackers), onProtocolError: (err) => { @@ -48,7 +52,10 @@ export function createWebSocketClient(root: BrainUiServices) { /** The one gated path every client frame takes. */ function send(message: ClientMessage): boolean { - return outbound(message); + const at = turnClock.now(); + const sent = outbound(message); + if (sent) turnClock.sent(message, at); + return sent; } const restoration = createRestorationDriver(root, { send, disposed: () => disposed }); @@ -58,7 +65,7 @@ export function createWebSocketClient(root: BrainUiServices) { loadDialogue: (sessionId) => conversation.loadDialogue(sessionId), restoration, }); - const services = createAccountServices(root, { send, socket: lease.client }); + const services = createAccountServices(root, { send, socket: lease.client, noteTurnSend: requestId => turnClock.started(requestId) }); const conversation = createConversationClient(root, send, (sessionId, text) => takeComposerTextAsAnswer(root.stores.chat.getState(), sessionId, text, (answer) => { void services.answers.submit(answer).then((result) => { @@ -97,7 +104,7 @@ export function createWebSocketClient(root: BrainUiServices) { function handleStatusChange(status: ConnectionStatus): void { root.stores.connection.getState().setWsStatus(status); - if (status !== "connected") services.socketDown(); + if (status !== "connected") { services.socketDown(); turnClock.disconnected(); } if (status === "connected") { inbound.resetTurns(); root.stores.connection.getState().noteSocketOpen(); @@ -171,6 +178,7 @@ export function createWebSocketClient(root: BrainUiServices) { inbound.resetTurns(); if (disposed) return; disposed = true; + unbindTurnClock(); timeline.dispose(); conversation.dispose(); retries.clearTimers(); diff --git a/packages/ui-react/src/lib/draft-client.ts b/packages/ui-react/src/lib/draft-client.ts index 8f29d2d288..765affb293 100644 --- a/packages/ui-react/src/lib/draft-client.ts +++ b/packages/ui-react/src/lib/draft-client.ts @@ -48,6 +48,7 @@ const UNCORRELATED = ["RATE_LIMITED", "PARSE_ERROR", "INTERNAL_ERROR"]; interface DraftClientOptions { send: (msg: ClientMessage) => boolean; + noteTurnSend?: (requestId: string) => void; api?: DraftApi; } @@ -771,6 +772,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt const held = store.sends[requestId]; if (!held || held.state !== "unconfirmed") return false; if (held.sessionId === null) openOwnNewChat(held); + options.noteTurnSend?.(nextRequestId); const next = drafts.getState().resend(requestId, nextRequestId); if (!next) return false; // The session's tracker waits on the request now sent, not the one replaced. @@ -850,6 +852,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt if (!send?.snapshotId || send.state !== "unconfirmed") return false; const draftId = store.sendDraftId(requestId) ?? send.draftId; const nextRequestId = crypto.randomUUID(); + options.noteTurnSend?.(nextRequestId); const { draftRef: _r, attachmentRefs: _a, ...template } = send.message; store.resendSnapshot(draftId, send.snapshotId, { snapshotId: crypto.randomUUID(), requestId: nextRequestId, message: { ...template, requestId: nextRequestId } }); root.stores.trackers.setState((s) => { @@ -909,6 +912,7 @@ export function createDraftClient(root: BrainUiServices, options: DraftClientOpt const d = drafts.getState().drafts[draftId]; const s = d && draftSnapshots(d).find((x) => x.snapshotId === snapshotId); if (!d || !s || s.state !== "held" || !s.paused) return; + options.noteTurnSend?.(s.requestId); drafts.getState().patchSnapshot(draftId, snapshotId, { paused: false, state: "dispatched", dispatch: "due", message: s.message ?? frameFor(d, s) }); schedule(draftId, 0); }, diff --git a/packages/ui-react/src/ws-client/account.ts b/packages/ui-react/src/ws-client/account.ts index 0b3dfbc2ab..7f90c0fbad 100644 --- a/packages/ui-react/src/ws-client/account.ts +++ b/packages/ui-react/src/ws-client/account.ts @@ -26,7 +26,7 @@ export function registerAuthLifecycle(root: Pick, lif */ export function createAccountServices( root: BrainUiServices, - deps: { send: (message: ClientMessage) => boolean; socket: () => BrainUiClient | null }, + deps: { send: (message: ClientMessage) => boolean; socket: () => BrainUiClient | null; noteTurnSend?: (requestId: string) => void }, ) { /** * The current connection's hello is known (received, or absent because the @@ -49,7 +49,7 @@ export function createAccountServices( .getState() .reportError("ANSWER_QUEUE_CORRUPT", "A saved answer on this device could not be read and was discarded."), }); - const makeDrafts = () => createDraftClient(root, { send: (message) => deps.send(message) }); + const makeDrafts = () => createDraftClient(root, { send: (message) => deps.send(message), noteTurnSend: deps.noteTurnSend }); const answers = makeAnswers(); void answers.start(); diff --git a/packages/ui-react/src/ws-client/turn-clock.ts b/packages/ui-react/src/ws-client/turn-clock.ts new file mode 100644 index 0000000000..4ea11b1f5e --- /dev/null +++ b/packages/ui-react/src/ws-client/turn-clock.ts @@ -0,0 +1,135 @@ +import type { ClientMessage, ClientTurnTiming, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; + +interface Observation { + sentAt: number; + dispatchedAt?: number; + disqualified?: true; + turnId?: string; + firstHostAt?: number; + firstContentAt?: number; + lastContentAt?: number; +} + +function isDispatched(value: Observation | undefined): value is Observation & { dispatchedAt: number } { + return value?.dispatchedAt !== undefined && value.disqualified !== true; +} + +/** Arrival evidence only, before rendering/delta buffering. Nothing survives a + * socket gap: a resumed client cannot establish the missing boundaries. */ +export function createTurnClock(report: (message: ClientMessage) => boolean, clock = () => performance.now()) { + let supported = false; + const requests = new Map(); + const arrivals = new Map>(); + return { + started(requestId: string, sentAt = clock()) { + if (requests.has(requestId)) return; + if (requests.size >= 256) requests.delete(requests.keys().next().value!); + requests.set(requestId, { sentAt }); + }, + sent(message: ClientMessage, sentAt: number) { + if ((message.type !== "chat_message" && message.type !== "retry_turn") || !message.requestId) return; + // A durable snapshot cannot reconstruct a lost Send after a reload + // or eviction. Its origin must have been captured by this live root. + if (message.type === "chat_message" && message.draftRef && !requests.has(message.requestId)) return; + if (requests.get(message.requestId)?.disqualified) return; + // Preserve the Send boundary captured before snapshot persistence. + this.started(message.requestId, sentAt); + requests.get(message.requestId)!.dispatchedAt ??= sentAt; + }, + now: clock, + disconnected() { supported = false; requests.clear(); arrivals.clear(); }, + frame(message: ServerMessage) { + if (message.type === "server_hello") { supported = message.capabilities?.clientTurnReceipts === true; return; } + if (!requests.size) return; + const at = clock(); + const { turnId, requestId } = (message.type === "session_queue" ? message.started : message) as { turnId?: string; requestId?: string } | undefined ?? {}; + // A known request acknowledged before this client's dispatch belongs + // to a peer. Retain that loss even if this tab later dispatches the id. + const acknowledged = message.type === "session_queue" + ? [...message.followUps.map(entry => entry.requestId), message.started?.requestId, ...(message.dropped ?? []).map(entry => entry.requestId)] + : message.type === "session_info" || message.type === "status" || message.type === "error" || message.type === "retry_receipt" && message.state === "accepted" + ? [requestId] : []; + for (const id of acknowledged) { + const observation = id ? requests.get(id) : undefined; + if (observation && observation.dispatchedAt === undefined) observation.disqualified = true; + } + if (![...requests.values()].some(isDispatched)) return; + if (message.type === "session_queue") { + for (const entry of message.followUps) { + const pending = entry.requestId ? requests.get(entry.requestId) : undefined; + if (isDispatched(pending)) pending.firstHostAt ??= at; + } + for (const entry of message.dropped ?? []) { const dropped = entry.requestId ? requests.get(entry.requestId) : undefined; if (dropped) dropped.disqualified = true; } + } + // Activity can announce acceptance before session_info identifies the + // initiating request. Only retain arrivals; never infer ownership. + const lifecycleIds = message.type === "activity_delta" ? [message.lifecycle?.turnId] + : message.type === "activity_snapshot" ? message.lifecycles?.map(value => value.turnId) ?? [] : []; + for (const id of lifecycleIds) if (id) remember(id, at); + + // A backend may emit a turn-scoped frame before session_info supplies + // its request correlation. Retain that arrival, never infer by session. + const arrival = turnId ? arrivals.get(turnId) ?? { firstHostAt: at } : undefined; + if (arrival && (message.type === "text_delta" || message.type === "thinking_delta") && message.text.length > 0) { + arrival.firstContentAt ??= at; arrival.lastContentAt = at; + } + if (turnId && arrival) { + remember(turnId, at, arrival); + } + function remember(id: string, at: number, value = arrivals.get(id) ?? { firstHostAt: at }) { + if (!arrivals.has(id) && arrivals.size >= 256) { + const evicted = arrivals.keys().next().value!; + const lost = arrivals.get(evicted)!; + arrivals.delete(evicted); + // An unbound request may own the lost first arrival. Keep only + // requests whose complete evidence is still provably retained. + for (const [id, pending] of requests) if ((!pending.turnId && lost.firstHostAt! >= pending.sentAt) || pending.turnId === evicted) requests.delete(id); + } + arrivals.set(id, value); + } + const correlates = message.type === "session_queue" || message.type === "session_info" || message.type === "status" || message.type === "error" || (message.type === "retry_receipt" && message.state === "accepted"); + let observation = correlates && requestId ? requests.get(requestId) : undefined; + if (!isDispatched(observation)) observation = undefined; + if (observation) { + observation.firstHostAt ??= at; + if (turnId) observation.turnId ??= turnId; + if (message.type === "error" && !turnId) { requests.delete(requestId!); return; } + } + if (!observation && turnId) observation = [...requests.values()].find(value => isDispatched(value) && value.turnId === turnId); + if (!isDispatched(observation) || !turnId || observation.turnId !== turnId) return; + if (arrival?.firstHostAt !== undefined && arrival.firstHostAt < observation.dispatchedAt) { + // Evidence from another tab before this dispatch cannot become our + // first frame. Drop this optional sample rather than infer a start. + for (const [id, value] of requests) if (value === observation) requests.delete(id); + return; + } + observation.firstHostAt = Math.min(observation.firstHostAt ?? at, arrival?.firstHostAt ?? at); + observation.firstContentAt ??= arrival?.firstContentAt; + observation.lastContentAt = arrival?.lastContentAt; + if (message.type !== "status" || message.status !== "idle" || message.hostTurnComplete !== true) return; + arrivals.delete(turnId); + for (const [id, value] of requests) if (value === observation) requests.delete(id); + const timing: ClientTurnTiming = { + sendToFirstHostFrameMs: Math.max(0, observation.firstHostAt - observation.sentAt), + ...(observation.firstContentAt === undefined ? {} : { sendToFirstContentFrameMs: Math.max(0, observation.firstContentAt - observation.sentAt) }), + ...(observation.lastContentAt === undefined ? {} : { lastContentFrameToIdleMs: Math.max(0, at - observation.lastContentAt) }), + }; + if (!supported) return; + // One attempt, no retry or retained outgoing queue. Loss affects only this measurement. + try { report({ type: "client_turn_receipt", turnId, timing }); } + catch { /* A transport exception must not interrupt idle handling. */ } + }, + }; +} + + +// Like the connection's account lifecycle registry, this stays private to +// the concrete root. Composer timing never enters a draft or wire message. +const rootClocks = new WeakMap>(); +export function bindTurnClock(owner: object, clock: ReturnType): () => void { + rootClocks.set(owner, clock); + return () => { if (rootClocks.get(owner) === clock) rootClocks.delete(owner); }; +} +export function noteTurnSend(owner: object, requestId: string, at: number): void { + rootClocks.get(owner)?.started(requestId, at); +} diff --git a/packages/ui-react/tests/browser/client-turn-receipt.offline.tsx b/packages/ui-react/tests/browser/client-turn-receipt.offline.tsx new file mode 100644 index 0000000000..0e75920e50 --- /dev/null +++ b/packages/ui-react/tests/browser/client-turn-receipt.offline.tsx @@ -0,0 +1,185 @@ +import { afterEach, expect, test } from "vitest"; +import { commands, page, userEvent } from "vitest/browser"; +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { BrainUiProvider } from "../../src/root-context.js"; +import { Composer } from "../../src/components/chat/composer.js"; +import { snapshotHost } from "../snapshot-host.js"; +import { createBrainUiRoot, type BrainUiRoot } from "../../src/root.js"; +import type { ActivityTurnLifecycle } from "@schlessera/brain-ui-sdk/protocol"; + +let fixture: { id: string; url: string } | undefined; +let ui: BrainUiRoot | undefined; +let peer: BrainUiRoot | undefined; +let socketDescriptor: PropertyDescriptor | undefined; +let renderer: Root | undefined; +let mount: HTMLDivElement | undefined; +let onLine: PropertyDescriptor | undefined; +let onlineChanged = false; +let releaseSave: (() => void) | undefined; +afterEach(async () => { + releaseSave?.(); releaseSave = undefined; + if (renderer) flushSync(() => renderer!.unmount()); renderer = undefined; + mount?.remove(); mount = undefined; + if (onlineChanged) { + if (onLine) Object.defineProperty(navigator, "onLine", onLine); + else Reflect.deleteProperty(navigator, "onLine"); + onlineChanged = false; + } + ui?.dispose(); ui = undefined; + peer?.dispose(); peer = undefined; + if (socketDescriptor) Object.defineProperty(globalThis, "WebSocket", socketDescriptor); socketDescriptor = undefined; + if (fixture) await commands.clientTurnServer({ op: "stop", id: fixture.id }); + fixture = undefined; +}); +const read = () => commands.clientTurnServer({ op: "read", id: fixture!.id }) as Promise<{ lifecycles: ActivityTurnLifecycle[]; held: boolean; earlyIdleHeld: boolean; reportsReceived: number; drained: string[] }>; +async function scene(request?: (url: string, init?: RequestInit) => Promise) { + fixture = await commands.clientTurnServer({ op: "start" }) as typeof fixture; + ui = createBrainUiRoot({ storage: null, config: { backendUrl: fixture!.url }, ...(request ? { request } : {}) }); + ui.connection.connect(); + await expect.poll(() => ui!.stores.connection.getState().wsStatus).toBe("connected"); +} + +test("a real browser turn stores frame-arrival pairs including the backend's known content delay", async () => { + await scene(); + expect(ui!.connection.send({ type: "chat_message", text: "Plan Ithaca", requestId: "voyage" })).toBe(true); + await expect.poll(async () => (await read()).lifecycles[0]?.clientTiming).toBeDefined(); + const lifecycle = (await read()).lifecycles[0]!; + expect(lifecycle.outcome).toBe("success"); + const timing = lifecycle.clientTiming!; + console.info("CLIENT_TURN_ARRIVAL_PAIRS", JSON.stringify(timing)); + expect(timing.sendToFirstHostFrameMs).toBeGreaterThanOrEqual(0); + expect(timing.sendToFirstContentFrameMs).toBeGreaterThanOrEqual(0); + expect(timing.lastContentFrameToIdleMs).toBeGreaterThanOrEqual(0); + expect(timing.sendToFirstPhaseStatusFrameMs).toBeUndefined(); + // Setup ends at session_info; the fixture waits 250ms before content. A + // 100ms tolerance covers loopback dispatch and browser scheduling, not paint. + expect(timing.sendToFirstContentFrameMs! - timing.sendToFirstHostFrameMs).toBeGreaterThanOrEqual(150); + expect(timing.sendToFirstContentFrameMs! - timing.sendToFirstHostFrameMs).toBeLessThanOrEqual(350); + expect(ui!.stores.chat.getState().buffers.ithaca?.messages.at(-1)?.content).toContain("Sail at dawn"); +}); + +test("a turn finishing after its initiating browser disconnects keeps its host outcome without client pairs", async () => { + await scene(); + expect(ui!.connection.send({ type: "chat_message", text: "Hold the voyage", requestId: "held-voyage" })).toBe(true); + await expect.poll(async () => (await read()).held).toBe(true); + ui!.dispose(); ui = undefined; + await commands.clientTurnServer({ op: "release", id: fixture!.id }); + await expect.poll(async () => (await read()).lifecycles[0]?.outcome).toBe("success"); + const lifecycle = (await read()).lifecycles[0]!; + expect(lifecycle.clientTiming).toBeUndefined(); + expect(lifecycle.backendRunId).toBe(lifecycle.turnId); +}); + + +test("backend idle and result before delayed teardown cannot send the once-only receipt early", async () => { + await scene(); + expect(ui!.connection.send({ type: "chat_message", text: "Delay host idle", requestId: "closing-voyage" })).toBe(true); + await expect.poll(async () => (await read()).earlyIdleHeld).toBe(true); + await expect.poll(() => ui!.stores.chat.getState().buffers.ithaca?.messages.at(-1)?.content).toContain("Sail at dawn"); + await expect.poll(async () => (await read()).lifecycles[0]?.outcome).toBeNull(); + const before = await read(); + expect(before.lifecycles[0]?.outcome).toBeNull(); + expect(before.reportsReceived).toBe(0); + expect(before.lifecycles[0]?.clientTiming).toBeUndefined(); + await commands.clientTurnServer({ op: "release", id: fixture!.id }); + await expect.poll(async () => (await read()).lifecycles[0]?.clientTiming).toBeDefined(); + const after = await read(); + expect(after.reportsReceived).toBe(1); + expect(after.lifecycles[0]?.outcome).toBe("success"); + expect(after.lifecycles[0]?.clientTiming?.lastContentFrameToIdleMs).toBeGreaterThanOrEqual(0); +}); + + +test("composer Send includes the snapshot-save wait in both send-based arrival pairs", async () => { + const drafts = await snapshotComposer(); + await userEvent.fill(page.getByRole("textbox"), "Plan Ithaca"); + releaseSave = drafts.holdSaves(); + const sentAt = performance.now(); + await userEvent.click(page.getByRole("button", { name: /^Send/ })); + const heldAt = performance.now(); + await expect.poll(() => drafts.calls.some(call => call.startsWith("PUT "))).toBe(true); + expect(ui!.stores.drafts.getState().snapshotsOn).toBe(true); + expect((await read()).lifecycles).toEqual([]); + // A controlled save barrier, released after a measured 500ms. This is an + // input delay to the product, not a watchdog or a fixed scheduling sleep. + await expect.poll(() => performance.now() - heldAt).toBeGreaterThanOrEqual(500); + const savedAt = performance.now(); + releaseSave(); releaseSave = undefined; + await expect.poll(async () => (await read()).lifecycles[0]?.clientTiming).toBeDefined(); + const timing = (await read()).lifecycles[0]!.clientTiming!; + console.info("COMPOSER_SEND_ARRIVAL_PAIRS", JSON.stringify({ savedWaitMs: savedAt - sentAt, ...timing })); + expect(timing.sendToFirstHostFrameMs).toBeGreaterThanOrEqual(450); + expect(timing.sendToFirstContentFrameMs).toBeGreaterThanOrEqual(700); +}); + +async function snapshotComposer() { + const drafts = snapshotHost(); + await scene(drafts.request); + onLine = Object.getOwnPropertyDescriptor(navigator, "onLine"); + onlineChanged = true; + Object.defineProperty(navigator, "onLine", { configurable: true, get: () => true }); + // The snapshot REST fixture supplies its real persistence protocol; the + // turn itself crosses the real socket and host, as in the other cases. + ui!.stores.drafts.getState().setSupport(true, + { maxTextBytes: 65536, maxDraftBytes: 8388608, maxDrafts: 100, maxTotalBytes: 268435456, maxOutgoingSnapshots: 10 }, + { maxFiles: 10, maxFileBytes: 25000000, maxTotalBytes: 50000000, poolBytes: 1073741824 }, true); + mount = document.createElement("div"); document.body.append(mount); + renderer = createRoot(mount); + flushSync(() => renderer!.render( ui!.connection.send(message)} />)); + return drafts; +} + + +test("only the browser that dispatches a shared snapshot reports its receipt", async () => { + const NativeSocket = globalThis.WebSocket; + const sockets: WebSocket[] = []; + socketDescriptor = Object.getOwnPropertyDescriptor(globalThis, "WebSocket")!; + Object.defineProperty(globalThis, "WebSocket", { ...socketDescriptor, value: class extends NativeSocket { + constructor(url: string | URL, protocols?: string | string[]) { super(url, protocols); if (new URL(String(url), location.href).pathname === "/ws") sockets.push(this); } + } }); + const drafts = await snapshotComposer(); + await userEvent.fill(page.getByRole("textbox"), "Plan Ithaca"); + releaseSave = drafts.holdSaves(); + await userEvent.click(page.getByRole("button", { name: /^Send/ })); + await expect.poll(() => drafts.calls.some(call => call.startsWith("PUT "))).toBe(true); + const state = ui!.stores.drafts.getState(); + const snapshot = Object.values(state.drafts).flatMap(draft => draft.snapshots ?? [])[0]!; + expect(snapshot).toBeDefined(); + expect((await read()).lifecycles).toEqual([]); + peer = createBrainUiRoot({ storage: null, request: drafts.request, config: { backendUrl: fixture!.url } }); + peer.connection.connect(); + await expect.poll(() => peer!.stores.connection.getState().wsStatus).toBe("connected"); + const completed = new Set(); + sockets.forEach((socket, index) => socket.addEventListener("message", event => { + const message = JSON.parse(String(event.data)); + if (message.type === "status" && message.hostTurnComplete === true) completed.add(index); + })); + expect(sockets).toHaveLength(2); + expect(peer.connection.send({ type: "chat_message", text: snapshot.text, requestId: snapshot.requestId })).toBe(true); + await expect.poll(() => completed.size).toBe(2); + // Each ping follows that socket's idle handler, so server-side FIFO proves + // every possible receipt was observed before the count is asserted. + ui!.connection.send({ type: "ping", probeId: "observer-drained" }); + peer.connection.send({ type: "ping", probeId: "sender-drained" }); + await expect.poll(async () => (await read()).drained.sort()).toEqual(["observer-drained", "sender-drained"]); + // Socket FIFO proves receipt arrival, not the off-loop persistence commit. + await expect.poll(async () => (await read()).lifecycles[0]?.clientTiming).toBeDefined(); + const result = await read(); + expect(result.reportsReceived).toBe(1); + expect(result.lifecycles[0]?.clientTiming).toBeDefined(); +}); + + +test("six turns on one socket retain every receipt with the real file-backed writer", async () => { + await scene(); + for (let index = 0; index < 6; index++) { + expect(ui!.connection.send({ type: "chat_message", text: "Plan Ithaca", requestId: `voyage-${index}`, + ...(index ? { sessionId: "ithaca" } : {}) })).toBe(true); + await expect.poll(async () => (await read()).lifecycles.filter(record => record.clientTiming).length).toBe(index + 1); + } + const result = await read(); + expect(result.reportsReceived).toBe(6); + expect(result.lifecycles).toHaveLength(6); + expect(result.lifecycles.every(record => record.outcome === "success" && record.clientTiming !== undefined)).toBe(true); +}); diff --git a/packages/ui-react/tests/browser/client-turn-server-command.ts b/packages/ui-react/tests/browser/client-turn-server-command.ts new file mode 100644 index 0000000000..8e22fe6e61 --- /dev/null +++ b/packages/ui-react/tests/browser/client-turn-server-command.ts @@ -0,0 +1,50 @@ +/// +import { spawn, type ChildProcess } from "node:child_process"; +import { once } from "node:events"; +import { resolve } from "node:path"; +import type { BrowserCommand } from "vitest/node"; +import { watchdogMs } from "../../../../scripts/test-deadlines.ts"; +type Op = { op: "start" } | { op: "read" | "release" | "stop"; id: string }; +const servers = new Map string }>(); +export const clientTurnServer: BrowserCommand<[Op], unknown> = async (_ctx, input) => { + if (input.op === "start") { + const child = spawn(process.env.BUN_BIN ?? "bun", ["--preload", resolve("../../scripts/test-network-child-preload.ts"), resolve("../ui-react/tests/fixtures/client-turn-browser-server.ts")], + { cwd: resolve("../.."), env: process.env, stdio: ["ignore", "pipe", "pipe"] }); + let stdout = "", stderr = ""; + child.stderr!.on("data", bytes => { stderr += String(bytes); }); + try { + const url = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`Turn fixture startup timed out: ${stderr}`)), watchdogMs(30_000)); + child.once("error", error => { clearTimeout(timer); reject(error); }); + child.once("exit", (code, signal) => { clearTimeout(timer); reject(new Error(`Turn fixture exited ${code}/${signal}: ${stderr}`)); }); + child.stdout!.on("data", bytes => { + stdout += String(bytes); + if (!stdout.includes("\n")) return; + clearTimeout(timer); + try { resolve(JSON.parse(stdout.split("\n")[0]!).url); } catch (error) { reject(error); } + }); + }); + const id = crypto.randomUUID(); servers.set(id, { child, url, diagnostics: () => stderr }); + return { id, url }; + } catch (error) { + if (child.pid && child.exitCode === null && child.signalCode === null) { + const ended = once(child, "exit"); child.kill(); await ended; + } + throw error; + } + } + const server = servers.get(input.id); + if (!server) throw new Error("Unknown turn fixture"); + if (input.op === "stop") { + const outcome = server.child.exitCode !== null || server.child.signalCode !== null + ? [server.child.exitCode, server.child.signalCode] + : await (async () => { const ended = once(server.child, "exit"); server.child.kill("SIGTERM"); return await ended; })(); + const [code, signal] = outcome; servers.delete(input.id); + if (code !== 0 || signal !== null) throw new Error(`Turn fixture cleanup failed ${code}/${signal}: ${server.diagnostics()}`); + return; + } + const response = await fetch(server.url, { method: input.op === "release" ? "POST" : "GET" }); + if (!response.ok) throw new Error(`Turn fixture failed ${response.status}: ${server.diagnostics()}`); + return response.json(); +}; +declare module "vitest/browser" { interface BrowserCommands { clientTurnServer: (input: Op) => Promise } } diff --git a/packages/ui-react/tests/client-turn-clock.test.ts b/packages/ui-react/tests/client-turn-clock.test.ts new file mode 100644 index 0000000000..03f0f1a7c1 --- /dev/null +++ b/packages/ui-react/tests/client-turn-clock.test.ts @@ -0,0 +1,229 @@ +import { expect, test } from "bun:test"; +import type { ClientMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { createTurnClock } from "../src/ws-client/turn-clock.js"; + +function scene(supported = true) { + let now = 1000; + const reports: ClientMessage[] = []; + const clock = createTurnClock(message => { reports.push(message); return true; }, () => now); + clock.frame({ type: "server_hello", protocolRev: 5, capabilities: supported ? { clientTurnReceipts: true } : {} }); + const send = (requestId = "voyage") => clock.sent({ type: "chat_message", text: "Plan Ithaca", requestId }, clock.now()); + const frame = (at: number, message: Parameters[0] & { turnId?: string }) => { now = at; clock.frame(message); }; + return { reports, clock, send, frame }; +} +test("queued first host, thinking/text content and idle use one monotonic client clock and report once", () => { + const s = scene(); s.send(); + s.frame(1004, { type: "status", status: "queued", requestId: "voyage", sessionId: "ithaca" }); + s.frame(1020, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1050, { type: "text_delta", text: "Other turn", turnId: "turn-troy", sessionId: "troy" }); + s.frame(1100, { type: "thinking_delta", text: "", turnId: "turn-ithaca" }); + s.frame(1204, { type: "thinking_delta", text: "Check the winds", turnId: "turn-ithaca" }); + s.frame(1300, { type: "text_delta", text: "Sail at dawn", turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + s.frame(1308, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + s.frame(1400, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { + sendToFirstHostFrameMs: 4, sendToFirstContentFrameMs: 204, lastContentFrameToIdleMs: 8, + } }]); +}); +test("disconnect discards incomplete evidence and a later turn can still report", () => { + const s = scene(); s.send(); + s.frame(1010, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.clock.disconnected(); + s.frame(1200, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + s.frame(1200, { type: "server_hello", protocolRev: 5, capabilities: { clientTurnReceipts: true } }); + s.send("return"); + s.frame(1210, { type: "session_info", isNew: false, requestId: "return", turnId: "turn-return", sessionId: "ithaca" }); + s.frame(1220, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-return" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-return", timing: { sendToFirstHostFrameMs: 10 } }]); +}); + +test("frames before the request's identity are measured without adopting another client's turn", () => { + const s = scene(); s.send(); + s.frame(1001, { type: "status", status: "thinking", turnId: "turn-troy" }); + s.frame(1005, { type: "status", status: "thinking", turnId: "turn-ithaca" }); + s.frame(1100, { type: "thinking_delta", text: "Check the winds", turnId: "turn-ithaca" }); + s.frame(1105, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1120, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { + sendToFirstHostFrameMs: 5, sendToFirstContentFrameMs: 100, lastContentFrameToIdleMs: 20, + } }]); +}); + +test("a lost report is attempted once even when the socket throws, and later turns still report", () => { + const attempts: ClientMessage[] = []; + const clock = createTurnClock(message => { attempts.push(message); throw new Error("Socket closed"); }, () => 1100); + clock.frame({ type: "server_hello", protocolRev: 5, capabilities: { clientTurnReceipts: true } }); + clock.sent({ type: "chat_message", text: "Plan Ithaca", requestId: "voyage" }, 1000); + const identity = { type: "session_info" as const, isNew: true, sessionId: "ithaca", turnId: "turn-ithaca", requestId: "voyage" }; + clock.frame(identity); + const idle = { type: "status" as const, status: "idle" as const, hostTurnComplete: true as const, turnId: "turn-ithaca" }; + expect(() => clock.frame(idle)).not.toThrow(); + clock.frame(idle); + expect(attempts).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 100 } }]); + clock.sent({ type: "chat_message", text: "Return to Ithaca", requestId: "return" }, 1000); + const returnIdentity = { ...identity, turnId: "turn-return", requestId: "return" }; + clock.frame(returnIdentity); + clock.frame({ ...idle, turnId: "turn-return" }); + expect(attempts).toHaveLength(2); +}); + + +test("a host that does not advertise receipt support receives no unknown timing message", () => { + const s = scene(false); s.send(); + s.frame(1010, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1200, { type: "text_delta", text: "Sail at dawn", turnId: "turn-ithaca" }); + s.frame(1220, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + s.clock.disconnected(); + s.frame(1230, { type: "server_hello", protocolRev: 5, capabilities: { clientTurnReceipts: true } }); + s.send("return"); + s.frame(1240, { type: "session_info", isNew: false, requestId: "return", turnId: "turn-return", sessionId: "ithaca" }); + s.frame(1250, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-return" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-return", timing: { sendToFirstHostFrameMs: 10 } }]); +}); + +test("backend idle cannot complete the measurement before host teardown", () => { + const s = scene(); s.send(); + s.frame(1010, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1100, { type: "text_delta", text: "Sail at dawn", turnId: "turn-ithaca" }); + s.frame(1110, { type: "status", status: "idle", turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + s.frame(1300, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { + sendToFirstHostFrameMs: 10, sendToFirstContentFrameMs: 100, lastContentFrameToIdleMs: 200, + } }]); +}); + +test("accepted retry acknowledgement is the first host frame before retry dispatch", () => { + const s = scene(); + s.clock.sent({ type: "retry_turn", sessionId: "ithaca", failedTurnId: "turn-troy", requestId: "voyage" }, 1000); + s.frame(1005, { type: "retry_receipt", state: "accepted", sessionId: "ithaca", requestId: "voyage" }); + s.frame(1090, { type: "session_info", isNew: false, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1200, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 5 } }]); +}); + +test("evicting an uncorrelated arrival invalidates the pending request rather than inventing a later first frame", () => { + const s = scene(); s.send(); + s.frame(1001, { type: "text_delta", text: "Check the winds", turnId: "turn-ithaca" }); + for (let index = 0; index < 256; index++) s.frame(1002 + index, { type: "text_delta", text: "Other voyage", turnId: `turn-troy-${index}` }); + s.frame(1259, { type: "text_delta", text: "Sail at dawn", turnId: "turn-ithaca" }); + s.frame(1260, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1270, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + s.send("return"); + s.frame(1280, { type: "session_info", isNew: false, requestId: "return", turnId: "turn-return", sessionId: "ithaca" }); + s.frame(1290, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-return" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-return", timing: { sendToFirstHostFrameMs: 10 } }]); +}); + +test("initial thinking acknowledgement is correlated before an existing session's new turn identity", () => { + const s = scene(); s.send(); + s.frame(1010, { type: "status", status: "thinking", requestId: "voyage", sessionId: "ithaca" }); + s.frame(1090, { type: "session_info", isNew: false, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1200, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 10 } }]); +}); + +test("lifecycle arrivals before identity count as first host frames for deltas and snapshots", () => { + for (const type of ["activity_delta", "activity_snapshot"] as const) { + const s = scene(); s.send(); + const lifecycle = { turnId: "turn-ithaca" } as import("@schlessera/brain-ui-sdk/protocol").ActivityTurnLifecycle; + s.frame(1005, type === "activity_delta" + ? { type, runId: "lifecycle:turn-ithaca", seq: 1, lifecycle } + : { type, view: "index", spans: [], events: [], highWaterSeq: {}, lifecycles: [lifecycle] }); + s.frame(1080, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1100, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 5 } }]); + } +}); + +test("a Send boundary survives snapshot persistence and is not reset by socket dispatch", () => { + const s = scene(); + s.clock.started("voyage", 500); + s.send(); + s.frame(1010, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1200, { type: "text_delta", text: "Sail at dawn", turnId: "turn-ithaca" }); + s.frame(1220, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { + sendToFirstHostFrameMs: 510, sendToFirstContentFrameMs: 700, lastContentFrameToIdleMs: 20, + } }]); +}); + +test("a snapshot whose Send boundary was lost cannot invent one at later dispatch", () => { + for (const lost of ["eviction", "reload"] as const) { + const s = scene(); + s.clock.started("voyage", 500); + if (lost === "eviction") { + for (let index = 0; index < 256; index++) s.clock.started(`other-voyage-${index}`, 1000 + index); + } else { + s.clock.disconnected(); + s.frame(1300, { type: "server_hello", protocolRev: 5, capabilities: { clientTurnReceipts: true } }); + } + s.clock.sent({ type: "chat_message", text: "Plan Ithaca", requestId: "voyage", draftRef: { draftId: "draft-ithaca", revision: 1 } }, 1300); + s.frame(1310, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1400, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + } +}); + +test("saving Send in one tab does not authorize a receipt for another tab's dispatch", () => { + const observer = scene(), sender = scene(); + observer.send("other-local"); // An unrelated local dispatch must not admit the held send either. + observer.clock.started("voyage", 0); + sender.clock.sent({ type: "chat_message", text: "Plan Ithaca", requestId: "voyage" }, 990); + for (const s of [observer, sender]) { + s.frame(1000, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1010, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + } + expect(observer.reports).toEqual([]); + expect(sender.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 10 } }]); +}); + +test("session_queue started identifies a queued turn that fails before session_info", () => { + const s = scene(); s.send(); + s.frame(1002, { type: "status", status: "queued", requestId: "voyage", sessionId: "ithaca" }); + s.frame(1010, { type: "session_queue", sessionId: "ithaca", followUps: [], started: { + id: "queued-voyage", requestId: "voyage", turnId: "turn-ithaca", text: "Plan Ithaca", queuedAt: 0, + } }); + s.frame(1020, { type: "result", sessionId: "ithaca", turnId: "turn-ithaca", outcome: "error", isError: true, costUsd: 0, durationMs: 0, numTurns: 0 }); + s.frame(1030, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 2 } }]); +}); + +test("pre-dispatch arrivals retained for another request cannot become a later sender's first frame", () => { + const s = scene(); s.send("other-local"); s.clock.started("voyage", 0); + s.frame(1000, { type: "status", status: "thinking", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.clock.sent({ type: "chat_message", text: "Plan Ithaca", requestId: "voyage" }, 1010); + s.frame(1015, { type: "session_info", isNew: true, requestId: "voyage", turnId: "turn-ithaca", sessionId: "ithaca" }); + s.frame(1020, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); +}); + +test("a pending session_queue entry is itself the first correlated host acknowledgement", () => { + const s = scene(); s.send(); + const entry = { id: "queued-voyage", requestId: "voyage", text: "Plan Ithaca", queuedAt: 0 }; + s.frame(1002, { type: "session_queue", sessionId: "ithaca", followUps: [entry] }); + s.frame(1010, { type: "session_queue", sessionId: "ithaca", followUps: [], started: { ...entry, turnId: "turn-ithaca" } }); + s.frame(1030, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 2 } }]); +}); + +for (const kind of ["status", "session_queue"] as const) { + test(`a peer's ${kind} acknowledgement before local dispatch disqualifies the shared request`, () => { + const s = scene(); s.clock.started("voyage", 1000); + const entry = { id: "queued-voyage", requestId: "voyage", text: "Plan Ithaca", queuedAt: 0 }; + s.frame(1005, kind === "status" ? { type: "status", status: "queued", sessionId: "ithaca", requestId: "voyage" } + : { type: "session_queue", sessionId: "ithaca", followUps: [entry] }); + s.clock.sent({ type: "chat_message", text: "Plan Ithaca", requestId: "voyage" }, 1010); + s.frame(1030, { type: "session_queue", sessionId: "ithaca", followUps: [], started: { ...entry, turnId: "turn-ithaca" } }); + s.frame(1040, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-ithaca" }); + expect(s.reports).toEqual([]); + s.send("return"); + s.frame(1050, { type: "session_info", isNew: false, requestId: "return", turnId: "turn-return", sessionId: "ithaca" }); + s.frame(1060, { type: "status", status: "idle", hostTurnComplete: true, turnId: "turn-return" }); + expect(s.reports).toEqual([{ type: "client_turn_receipt", turnId: "turn-return", timing: { sendToFirstHostFrameMs: 10 } }]); + }); +} diff --git a/packages/ui-react/tests/fixtures/client-turn-browser-server.ts b/packages/ui-react/tests/fixtures/client-turn-browser-server.ts new file mode 100644 index 0000000000..dea623c88f --- /dev/null +++ b/packages/ui-react/tests/fixtures/client-turn-browser-server.ts @@ -0,0 +1,76 @@ +/** Keyless turn path: real socket parser, host/coordinator, lifecycle and receipt storage. */ +import { workerHostBoundary } from "../../../ui-sdk/src/server/worker-launcher.js"; +// The fixture backend has no worker process; native containment has its own proof. +workerHostBoundary.probe = () => ({ ok: true }); +import { mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { openSqliteWriter } from "../../../ui-server/src/db/write-worker.js"; +import { createModelPricing } from "../../../ui-server/src/pricing/model-pricing.js"; +import { createUiDb } from "../../../ui-server/src/db/client.js"; +import { createActivityRuntime } from "../../../ui-server/src/activity/runtime.js"; +import { createStaticBackendRegistry } from "../../../ui-server/src/agent/backend.js"; +import { createSessionCatalog } from "../../../ui-server/src/ws/session-catalog.js"; +import { createWsHandlers } from "../../../ui-server/src/ws/connection.js"; +import { WsHost } from "../../../ui-server/src/ws/host.js"; +import type { WSContext } from "../../../ui-server/src/ws/clients.js"; +import { makeFakeBackend } from "../../../ui-server/tests/helpers/fake-backend.js"; +import { testPrincipal } from "../../../ui-server/tests/helpers/principal.js"; +import type { Logger } from "@opentelemetry/api-logs"; + +const temporary = mkdtempSync(join(tmpdir(), "client-turn-ithaca-")); +const db = createUiDb(join(temporary, "ui.db")); +const writer = openSqliteWriter(db); +const pricingConfig = { brainPath: temporary, enabled: false }; +const pricing = createModelPricing(pricingConfig); +const log = { emit() {} } as unknown as Logger; +const activity = createActivityRuntime(db, { log, writer, pricing, pricingConfig }); +let release: (() => void) | undefined; +let earlyIdleHeld = false, reportsReceived = 0; +const drained = new Set(); +const backend = makeFakeBackend({ id: "odyssey", startTurn: async request => { + const sessionId = request.sessionId ?? "ithaca"; + request.bridge.emit({ type: "session_info", sessionId, isNew: !request.sessionId, providerId: "odyssey" }); + if (request.prompt === "Hold the voyage") await new Promise(resolve => { release = resolve; }); + else await Bun.sleep(250); // Deliberate product-input delay, observed in the client's frame-arrival pair. + request.bridge.emit({ type: "thinking_delta", text: "Check the winds", sessionId }); + request.bridge.emit({ type: "text_delta", text: "Sail at dawn", sessionId }); + // Both production backends emit an early idle; a backend cannot spoof host completion. + request.bridge.emit({ type: "status", status: "idle", hostTurnComplete: true, sessionId }); + request.bridge.emit({ type: "result", sessionId, outcome: "success", costUsd: 0, durationMs: 250, numTurns: 1, isError: false }); + if (request.prompt === "Delay host idle") { + earlyIdleHeld = true; + await new Promise(resolve => { release = resolve; }); + earlyIdleHeld = false; + } +} }); +const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog: createSessionCatalog(() => db, log, undefined, { pricing, store: activity.store, governance: activity.governanceWrites, writer, pricingConfig }), activity }); +type SocketData = { handlers: ReturnType; context: WSContext }; +const server = Bun.serve({ hostname: "127.0.0.1", port: 0, + async fetch(request, server) { + if (new URL(request.url).pathname === "/ws") { + const handlers = createWsHandlers(host, testPrincipal("odysseus")); + if (server.upgrade(request, { data: { handlers } as SocketData })) return; + return new Response(null, { status: 400 }); + } + if (request.method === "POST") { release?.(); release = undefined; } + return Response.json({ lifecycles: activity.store.lifecycles(), held: !!release, earlyIdleHeld, reportsReceived, drained: [...drained] }); + }, + websocket: { + open(socket) { + const context: WSContext = { send: data => socket.send(data), close: (code, reason) => socket.close(code, reason), raw: socket }; + socket.data.context = context; + void socket.data.handlers.onOpen(undefined as never, context); + }, + message(socket, data) { + const message = JSON.parse(String(data)); + if (message.type === "client_turn_receipt") reportsReceived++; + if (message.type === "ping" && typeof message.probeId === "string") drained.add(message.probeId); + socket.data.handlers.onMessage({ data: String(data) } as MessageEvent, socket.data.context); }, + close(socket, code, reason) { socket.data.handlers.onClose({ code, reason } as CloseEvent, socket.data.context); }, + }, +}); +process.on("SIGTERM", async () => { + release?.(); await host.close(); await activity.close(); await writer.close(); db.close(); server.stop(true); rmSync(temporary, { recursive: true, force: true }); process.exit(0); +}); +console.log(JSON.stringify({ url: `http://127.0.0.1:${server.port}` })); diff --git a/packages/ui-sdk/src/protocol.ts b/packages/ui-sdk/src/protocol.ts index 405f5bd137..fe5ee6ba08 100644 --- a/packages/ui-sdk/src/protocol.ts +++ b/packages/ui-sdk/src/protocol.ts @@ -123,6 +123,7 @@ export type ClientMessage = | ClientSafetyRead | ClientSafetySubscribe | ClientSafetyUnsubscribe | ClientScopeDecision | ClientHello + | ClientTurnReceipt | ClientRetryTurn | ClientRetryStatus | ClientChatMessage @@ -160,6 +161,22 @@ export type ClientMessage = | ClientConversationPlayback | ClientConversationStop; +/** Client-monotonic frame-arrival pairs, in milliseconds; never presentation timings. */ +export interface ClientTurnTiming { + sendToFirstHostFrameMs: number; + sendToFirstContentFrameMs?: number; + lastContentFrameToIdleMs?: number; + /** Absent until phase-specific status frames are supported. */ + sendToFirstPhaseStatusFrameMs?: number; +} + +/** Best-effort, once after idle; cannot update the host lifecycle. */ +export interface ClientTurnReceipt { + type: "client_turn_receipt"; + turnId: string; + timing: ClientTurnTiming; +} + /** * Client → Server. First frame a client sends after the socket opens (rev 3, * additive). @@ -1024,7 +1041,8 @@ export interface ServerHello { * advertises resumable stop plus start/open/close request identity echoes. * `sessionDrafts: true` means the `/api/drafts` routes store drafts; * `sessionDraftLimits` then carries their bounds. `sessionRecovery: true` - * means `GET /api/sessions/:id/recovery` answers (#964). */ + * means `GET /api/sessions/:id/recovery` answers (#964). + * `clientTurnReceipts: true` accepts best-effort client frame-arrival reports. */ capabilities?: Record; /** * Draft storage bounds (additive; #979). Present exactly when @@ -1583,6 +1601,8 @@ export interface ServerError extends SessionScoped { } export interface ServerStatus extends SessionScoped { + /** Host-only final idle after cleanup; receipt persistence may finish later. Never a backend idle. */ + hostTurnComplete?: true; type: "status"; status: "thinking" | "tool_executing" | "idle" | "cancelled" | "queued"; detail?: string; @@ -3905,6 +3925,10 @@ export interface ActivityTurnOpenSubPhase extends Omit; skippedPhases: Array<"governed" | "budget" | "journal">; lifecycleId: string; diff --git a/packages/ui-sdk/src/schemas.ts b/packages/ui-sdk/src/schemas.ts index 890047ed39..bd692f7694 100644 --- a/packages/ui-sdk/src/schemas.ts +++ b/packages/ui-sdk/src/schemas.ts @@ -180,6 +180,8 @@ import { /** Cap on one client→server WS frame (must fit a max-attachment chat message). */ export const MAX_CLIENT_FRAME_BYTES = 12_000_000; +/** Receipt routing has a small bounded discriminator probe and an independent meter. */ +export const MAX_CLIENT_TURN_RECEIPT_BYTES = 4096; /** Cap on a chat message's text (characters). */ export const MAX_PROMPT_CHARS = 200_000; /** Cap on any short id (sessionId, toolUseId, requestId, turnId, providerId). */ @@ -930,8 +932,18 @@ export const clientConversationStopSchema = z.looseObject({ const clientScopeDecisionSchema = z.strictObject({ type: z.literal("scope_decision"), sessionId: id, turnId: id, eventId: id, submissionId: id, action: z.enum(["continue", "stop", "readback"]) }) satisfies z.ZodType; +export const clientTurnTimingSchema = z.strictObject({ + sendToFirstHostFrameMs: z.number().nonnegative(), + sendToFirstContentFrameMs: z.number().nonnegative().optional(), + lastContentFrameToIdleMs: z.number().nonnegative().optional(), + sendToFirstPhaseStatusFrameMs: z.number().nonnegative().optional(), +}) satisfies z.ZodType; +const clientTurnReceiptSchema = z.strictObject({ + type: z.literal("client_turn_receipt"), turnId: id, timing: clientTurnTimingSchema, +}) satisfies z.ZodType; export const clientMessageSchema = z.discriminatedUnion("type", [ clientScopeDecisionSchema, + clientTurnReceiptSchema, clientRetryTurnSchema, clientRetryStatusSchema, clientHelloSchema, @@ -986,7 +998,7 @@ function utf8ByteLength(text: string): number { export type ParseFrameResult = | { ok: true; message: T } - | { ok: false; error: string }; + | { ok: false; error: string; frameType?: "client_turn_receipt" }; /** * Parse + validate one inbound client frame. The single entry point a server @@ -1019,11 +1031,15 @@ export function parseClientMessage( } catch { return { ok: false, error: "Frame is not valid JSON" }; } + const frameType = json && typeof json === "object" && (json as { type?: unknown }).type === "client_turn_receipt" + ? { frameType: "client_turn_receipt" as const } : {}; + if (frameType.frameType && utf8ByteLength(text) > MAX_CLIENT_TURN_RECEIPT_BYTES) + return { ok: false, error: `Receipt exceeds ${MAX_CLIENT_TURN_RECEIPT_BYTES} bytes`, ...frameType }; // Bun's JSON.parse is iterative, so a 500k-deep document parses fine and // only explodes later when something re-serializes it (unknown keys are // RETAINED by looseObject, so depth survives the boundary). if (exceedsDepth(json, MAX_JSON_DEPTH)) { - return { ok: false, error: `Frame nesting exceeds ${MAX_JSON_DEPTH} levels` }; + return { ok: false, error: `Frame nesting exceeds ${MAX_JSON_DEPTH} levels`, ...frameType }; } const parsed = clientMessageSchema.safeParse(json); if (!parsed.success) { @@ -1034,6 +1050,7 @@ export function parseClientMessage( return { ok: false, error: `Invalid frame${first ? `: ${where} ${first.message}` : ""}`, + ...frameType, }; } return { ok: true, message: parsed.data as ClientMessage }; @@ -1448,6 +1465,7 @@ export const serverErrorSchema = z.looseObject({ }) satisfies z.ZodType; export const serverStatusSchema = z.looseObject({ + hostTurnComplete: z.literal(true).optional(), type: z.literal("status"), status: z.enum(["thinking", "tool_executing", "idle", "cancelled", "queued"]), detail: z.string().optional(), @@ -1620,6 +1638,8 @@ const activitySpanEventSchema = z.looseObject({ }) satisfies z.ZodType; const activityTurnLifecycleSchema = z.looseObject({ + clientTiming: z.looseObject(clientTurnTimingSchema.shape).optional(), + clientTimingUnavailable: z.literal("invalid_receipt").optional(), hostEvents: z.array(z.looseObject({principalId: id, kind: z.enum(["turn_cancelled", "ask_user_cancelled", "principal_revoked", "follow_up"]), observedAt: z.number()})), skippedPhases: z.array(z.enum(["governed", "budget", "journal"])), lifecycleId: id, turnId: id, sessionId: id.nullable(), backendRunId: id.nullable(), diff --git a/packages/ui-sdk/tests/client-turn-receipt.test.ts b/packages/ui-sdk/tests/client-turn-receipt.test.ts new file mode 100644 index 0000000000..a2546f0b40 --- /dev/null +++ b/packages/ui-sdk/tests/client-turn-receipt.test.ts @@ -0,0 +1,23 @@ +import { expect, test } from "bun:test"; +import { parseClientMessage, parseServerMessage } from "../src/schemas.js"; + +const receipt = { type: "client_turn_receipt" as const, turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 5 } }; + +test("receipt parsing retains its kind on a schema refusal without accepting the bad timing", () => { + expect(parseClientMessage(JSON.stringify(receipt))).toEqual({ ok: true, message: receipt }); + expect(parseClientMessage(JSON.stringify({ ...receipt, timing: { sendToFirstHostFrameMs: -1 } }))).toMatchObject({ ok: false, frameType: "client_turn_receipt" }); +}); + +test("the small receipt byte cap does not restrict an ordinary chat message", () => { + expect(parseClientMessage(" ".repeat(4096) + JSON.stringify(receipt))).toEqual({ ok: false, + frameType: "client_turn_receipt", error: "Receipt exceeds 4096 bytes" }); + const chat = { type: "chat_message" as const, text: "Sail at dawn. ".repeat(400) }; + expect(parseClientMessage(JSON.stringify(chat))).toEqual({ ok: true, message: chat }); +}); + +test("the final idle marker is an optional field on the existing status frame", () => { + const idle = { type: "status" as const, status: "idle" as const, sessionId: "ithaca", turnId: "turn-ithaca" }; + expect(parseServerMessage(JSON.stringify(idle))).toEqual({ ok: true, message: idle }); + expect(parseServerMessage(JSON.stringify({ ...idle, hostTurnComplete: true }))).toEqual({ ok: true, + message: { ...idle, hostTurnComplete: true } }); +}); diff --git a/packages/ui-server/migrations/095_client_turn_receipts.sql b/packages/ui-server/migrations/095_client_turn_receipts.sql new file mode 100644 index 0000000000..38093dd042 --- /dev/null +++ b/packages/ui-server/migrations/095_client_turn_receipts.sql @@ -0,0 +1,7 @@ +-- Bound at host acceptance, independent of backend/session ownership. +-- A NULL receipt means no report was accepted. Removing the lifecycle removes it. +CREATE TABLE activity_turn_clients ( + turn_id TEXT PRIMARY KEY REFERENCES activity_turn_lifecycles(turn_id) ON DELETE CASCADE, + principal_id TEXT NOT NULL, + receipt TEXT +); diff --git a/packages/ui-server/src/activity/store-writes.ts b/packages/ui-server/src/activity/store-writes.ts index b74f1b885d..9a49f94489 100644 --- a/packages/ui-server/src/activity/store-writes.ts +++ b/packages/ui-server/src/activity/store-writes.ts @@ -14,7 +14,7 @@ import { createActivityStore, MAX_EVENT_PAYLOAD_BYTES, type ActivityStore, type export const url = import.meta.url; -export const ACTIVITY_WRITE_METHODS = ["writeLifecycle", "startSpan", "endSpan", "patchSpan", "appendEvent", "heartbeat", +export const ACTIVITY_WRITE_METHODS = ["writeClientReceipt", "writeLifecycle", "startSpan", "endSpan", "patchSpan", "appendEvent", "heartbeat", "cascadeClose", "sweepOwnOrphans", "sweepStale", "rollupRun", "prune"] as const satisfies readonly ActivityWriteMethod[]; /** The app's pricing configuration; the worker prices rollups from the same cache and snapshot. */ diff --git a/packages/ui-server/src/activity/store.ts b/packages/ui-server/src/activity/store.ts index f4971a7af1..deee3919ea 100644 --- a/packages/ui-server/src/activity/store.ts +++ b/packages/ui-server/src/activity/store.ts @@ -1,3 +1,4 @@ +import { clientTurnTimingSchema, MAX_CLIENT_TURN_RECEIPT_BYTES } from "@schlessera/brain-ui-sdk/schemas"; import type { ActivityTurnLifecycle } from "@schlessera/brain-ui-sdk/protocol"; import { lifecycleTiming } from "./turn-lifecycle.js"; import { settleInboxBudgetRun } from "../inbox/budget.js"; @@ -33,7 +34,7 @@ import { settleInboxBudgetRun } from "../inbox/budget.js"; * on programmer error, because a silent half-written record is worse than a * loud one. */ -import type { Database } from "bun:sqlite"; +import { Database } from "bun:sqlite"; import { isBillingMode, isFailureOutcome, @@ -289,10 +290,15 @@ export interface PruneOptions { export const MAX_EVENT_PAYLOAD_BYTES = 16_384; export interface ActivityStore { - writeLifecycle(record: ActivityTurnLifecycle): void; + writeLifecycle(record: ActivityTurnLifecycle, principalId?: string): void; + writeClientReceipt?(turnId: string, principalId: string, timing: import("@schlessera/brain-ui-sdk/protocol").ClientTurnTiming): boolean; lifecycleChangesSince(cursor: number, limit?: number): Array<{ changeId: number; runId: string; seq: number; kind: "lifecycle"; lifecycle: ActivityTurnLifecycle }>; lifecycle(turnId: string): ActivityTurnLifecycle | null; lifecycles(sessionId?: string, limit?: number): ActivityTurnLifecycle[]; + /** Joined lifecycle data and its sequence from one read transaction. */ + snapshotLifecycles?(scope: { turnId?: string; sessionId?: string; limit?: number }): { + lifecycles: ActivityTurnLifecycle[]; highWaterSeq: Record; + }; readonly writer: string; startSpan(input: StartSpanInput): SpanRow; @@ -368,7 +374,7 @@ export interface ActivityStore { type Awaitable = T | Promise; /** The writes a store may commit off the event loop (#2814). */ -export type ActivityWriteMethod = "writeLifecycle" | "startSpan" | "endSpan" | "patchSpan" | "appendEvent" | "heartbeat" +export type ActivityWriteMethod = "writeClientReceipt" | "writeLifecycle" | "startSpan" | "endSpan" | "patchSpan" | "appendEvent" | "heartbeat" | "cascadeClose" | "sweepOwnOrphans" | "sweepStale" | "rollupRun" | "prune"; /** @@ -380,7 +386,9 @@ export type ActivityWriteMethod = "writeLifecycle" | "startSpan" | "endSpan" | " * return. */ export type AwaitableActivityStore = Omit & { - [K in ActivityWriteMethod]: (...args: Parameters) => Awaitable>; + [K in Exclude]: (...args: Parameters) => Awaitable>; +} & { + writeClientReceipt?: (...args: Parameters>) => Awaitable>>; }; /** @@ -425,6 +433,10 @@ export function createActivityStore( // bun:sqlite transactions: `.immediate` takes the write lock up front, so a // concurrent writer waits (busy_timeout) instead of failing mid-upgrade. const inWrite = (fn: () => T): T => db.transaction(fn).immediate(); + // Read-only WAL snapshots bypass the app writer turn. The instance's + // transaction wrapper serializes writes and can block in Atomics.wait. + const readSnapshot = (read: () => T): T => db.inTransaction ? read() + : Database.prototype.transaction.call(db, read).deferred() as T; function nextSeq(runId: string): number { const row = db @@ -636,9 +648,33 @@ export function createActivityStore( if (root.endedAt !== null) settleInboxBudgetRun(db, runId, "settled", Date.now(), getPricing()); } + const joinClient = (record: ActivityTurnLifecycle): ActivityTurnLifecycle => { + const row = db.query("SELECT CAST(substr(CAST(receipt AS BLOB), 1, ?) AS TEXT) AS receipt, length(CAST(receipt AS BLOB)) AS receiptBytes FROM activity_turn_clients WHERE turn_id = ?").get(MAX_CLIENT_TURN_RECEIPT_BYTES + 1, record.turnId) as { receipt: string | null; receiptBytes: number | null } | null; + const { clientTiming: _timing, clientTimingUnavailable: _unavailable, ...hostRecord } = record; + const host = lifecycleTiming(hostRecord); + if (!row || row.receipt === null) return host; + if (row.receiptBytes === null || row.receiptBytes > MAX_CLIENT_TURN_RECEIPT_BYTES) return { ...host, clientTimingUnavailable: "invalid_receipt" }; + try { + const timing = clientTurnTimingSchema.safeParse(JSON.parse(row.receipt)); + if (timing.success) return { ...host, clientTiming: timing.data }; + } catch { /* Retain the corrupt row; only its optional measurement is unavailable. */ } + return { ...host, clientTimingUnavailable: "invalid_receipt" }; + }; const lifecycle = (id: string): ActivityTurnLifecycle | null => { - const row = db.query("SELECT record FROM activity_turn_lifecycles WHERE turn_id = ?").get(id) as { record: string } | null; - return row ? lifecycleTiming(JSON.parse(row.record)) : null; + const read = () => { + const row = db.query("SELECT record FROM activity_turn_lifecycles WHERE turn_id = ?").get(id) as { record: string } | null; + return row ? joinClient(JSON.parse(row.record)) : null; + }; + return readSnapshot(read); + }; + const lifecycles = (sessionId?: string, limit = 100): ActivityTurnLifecycle[] => { + const read = () => { + const rows = sessionId === undefined + ? db.query("SELECT record FROM activity_turn_lifecycles ORDER BY accepted_at DESC LIMIT ?").all(limit) + : db.query("SELECT record FROM activity_turn_lifecycles WHERE session_id = ? ORDER BY accepted_at DESC LIMIT ?").all(sessionId, limit); + return (rows as { record: string }[]).map(row => joinClient(JSON.parse(row.record))); + }; + return readSnapshot(read); }; return { writer, @@ -656,26 +692,49 @@ export function createActivityStore( return gap ? null : prior; }, lifecycle, - lifecycles(sessionId, limit = 100) { - const rows = sessionId === undefined - ? db.query("SELECT record FROM activity_turn_lifecycles ORDER BY accepted_at DESC LIMIT ?").all(limit) - : db.query("SELECT record FROM activity_turn_lifecycles WHERE session_id = ? ORDER BY accepted_at DESC LIMIT ?").all(sessionId, limit); - return (rows as { record: string }[]).map(row => lifecycleTiming(JSON.parse(row.record))); + lifecycles, + snapshotLifecycles(scope) { + return readSnapshot(() => { + const records = scope.turnId ? [lifecycle(scope.turnId)].filter((record): record is ActivityTurnLifecycle => record !== null) + : lifecycles(scope.sessionId, scope.limit); + return { lifecycles: records, highWaterSeq: Object.fromEntries(records.map(record => [record.lifecycleId, runHighWaterSeqRaw(record.lifecycleId)])) }; + }); }, lifecycleChangesSince(cursor, limit = 500) { - const rows = db.query(`SELECT c.change_id,c.run_id,c.seq,l.record FROM activity_changes c - JOIN activity_turn_lifecycles l ON l.turn_id = substr(c.run_id, 11) AND c.span_id = c.run_id - WHERE c.change_id > ? ORDER BY c.change_id LIMIT ?`).all(cursor, limit) as any[]; - return rows.map(r => ({changeId:r.change_id,runId:r.run_id,seq:r.seq,kind:"lifecycle" as const,lifecycle:lifecycleTiming(JSON.parse(r.record))})); + return readSnapshot(() => { + const rows = db.query(`SELECT c.change_id,c.run_id,c.seq,l.record FROM activity_changes c + JOIN activity_turn_lifecycles l ON l.turn_id = substr(c.run_id, 11) AND c.span_id = c.run_id + WHERE c.change_id > ? ORDER BY c.change_id LIMIT ?`).all(cursor, limit) as any[]; + return rows.map(r => ({changeId:r.change_id,runId:r.run_id,seq:r.seq,kind:"lifecycle" as const,lifecycle:joinClient(JSON.parse(r.record))})); + }); }, - writeLifecycle(record) { + writeClientReceipt(turnId, principalId, timing) { + // Strict projection at the storage boundary too: callers cannot smuggle + // host fields through a cast. First accepted report wins atomically. + const parsed = clientTurnTimingSchema.safeParse(timing); + if (!parsed.success) return false; + return inWrite(() => { + const changed = db.query(`UPDATE activity_turn_clients SET receipt = ? + WHERE turn_id = ? AND principal_id = ? AND receipt IS NULL + AND EXISTS (SELECT 1 FROM activity_turn_lifecycles WHERE turn_id = ? AND ended_at IS NOT NULL)`) + .run(JSON.stringify(parsed.data), turnId, principalId, turnId).changes; + if (!changed) return false; + const id = `lifecycle:${turnId}`; + logChange(id, nextSeq(id), id); + return true; + }); + }, + writeLifecycle(record, principalId) { inWrite(() => { const previous = lifecycle(record.turnId); if (previous?.endedAt !== null && previous !== null) return; - const value = lifecycleTiming(record); + // Client data is never part of the completed host envelope. + const { clientTiming: _clientTiming, clientTimingUnavailable: _unavailable, ...hostRecord } = record; + const value = lifecycleTiming(hostRecord); db.query(`INSERT INTO activity_turn_lifecycles VALUES (?, ?, ?, ?, ?) ON CONFLICT(turn_id) DO UPDATE SET session_id=excluded.session_id, ended_at=excluded.ended_at, record=excluded.record`) .run(value.turnId, value.sessionId, value.acceptedAt, value.endedAt, JSON.stringify(value)); + if (principalId) db.query("INSERT INTO activity_turn_clients (turn_id, principal_id) VALUES (?, ?) ON CONFLICT DO NOTHING").run(value.turnId, principalId); logChange(value.lifecycleId, nextSeq(value.lifecycleId), value.lifecycleId); }); }, @@ -895,7 +954,7 @@ export function createActivityStore( // A read transaction so spans, events, high-water seq, and the global // cursor are one consistent picture — the poller baseline is pinned to // exactly this moment (no gap between snapshot and first delta). - return db.transaction(() => { + return readSnapshot(() => { const spans = ( db .query(ACTIVITY_SQL.spansByRun) @@ -917,7 +976,7 @@ export function createActivityStore( highWaterSeq: runHighWaterSeqRaw(runId), changeCursor: cursor.hi, }; - })(); + }); }, runHighWaterSeq: runHighWaterSeqRaw, diff --git a/packages/ui-server/src/activity/stream.ts b/packages/ui-server/src/activity/stream.ts index 211d725917..6c6093fd1d 100644 --- a/packages/ui-server/src/activity/stream.ts +++ b/packages/ui-server/src/activity/stream.ts @@ -9,10 +9,10 @@ * out as an `activity_delta` to matching subscribers, so ordering is the * change log's and a delta can never precede its commit (persist-then-emit). * - * The subscribe handler answers with a snapshot whose per-run high-water seq - * and pump baseline come from ONE store read transaction — there is no gap - * window between snapshot and first delta, and no duplication the client's - * seq-discard rule cannot handle. + * Run snapshots and joined lifecycle snapshots read their data and sequence + * together. Prior store implementations and the open-root index capture a + * conservative sequence floor before reading data: a racing change may be + * replayed, but cannot be discarded as already present in older data. * * This is deliberately the only place broadcast is per-connection filtered; * every other frame keeps the host's broadcast-to-all semantics. @@ -294,18 +294,31 @@ export function createActivityStream(store: AwaitableActivityStore, log?: Logger } } else { // Index view: open roots only — history is the REST activity API's job. + const sequences = Object.fromEntries(store.openRootSpans().map(root => [root.runId, store.runHighWaterSeq(root.runId)])); for (const root of store.openRootSpans()) { if (!shown(root.runId)) continue; spans.push(root); - highWater[root.runId] = store.runHighWaterSeq(root.runId); + highWater[root.runId] = sequences[root.runId] ?? 0; } } for (const span of spans) noteSpan(span); - const lifecycles = sub.view === "run" && sub.runId - ? [store.lifecycle(sub.runId)].filter((x): x is NonNullable => x !== null) - : store.lifecycles(sub.view === "session" ? sub.sessionId : undefined); - for (const lifecycle of lifecycles) highWater[lifecycle.lifecycleId] = store.runHighWaterSeq(lifecycle.lifecycleId); + const scope = sub.view === "run" && sub.runId ? { turnId: sub.runId } + : sub.view === "session" ? { sessionId: sub.sessionId } : {}; + const readLifecycles = () => "turnId" in scope && scope.turnId + ? [store.lifecycle(scope.turnId)].filter((record): record is NonNullable => record !== null) + : store.lifecycles("sessionId" in scope ? scope.sessionId : undefined); + const snapshot = store.snapshotLifecycles?.(scope) ?? (() => { + // Prior store implementations remain supported. Capture sequences + // before reading the data, so a racing change can only be replayed, + // never discarded as already included in an older snapshot. + const sequences = Object.fromEntries(readLifecycles().map(record => [record.lifecycleId, store.runHighWaterSeq(record.lifecycleId)])); + const records = readLifecycles(); + for (const record of records) sequences[record.lifecycleId] ??= 0; + return { lifecycles: records, highWaterSeq: sequences }; + })(); + const lifecycles = snapshot.lifecycles; + Object.assign(highWater, snapshot.highWaterSeq); const base: Omit = { lifecycles, type: "activity_snapshot", diff --git a/packages/ui-server/src/activity/turn-lifecycle.ts b/packages/ui-server/src/activity/turn-lifecycle.ts index ff1ef88134..0b8a0a222c 100644 --- a/packages/ui-server/src/activity/turn-lifecycle.ts +++ b/packages/ui-server/src/activity/turn-lifecycle.ts @@ -13,7 +13,7 @@ export type PhaseTimer = (name: string) => () => void; type LifecycleMilestone = "dequeuedAt" | "governedStartedAt" | "governedAcquiredAt" | "budgetStartedAt" | "budgetAdmittedAt" | "journalStartedAt" | "journalBeganAt" | "backendInvokedAt" | "firstFrameAt" | "failureObservedAt"; export function createTurnLifecycle(store: AwaitableActivityStore, turnId: string, sessionId: string | null, - acceptedAt: number, onWrite: () => void, clock: () => number = Date.now) { + acceptedAt: number, onWrite: () => void, clock: () => number = Date.now, principalId?: string) { const record: ActivityTurnLifecycle = { hostEvents: [], skippedPhases: [], lifecycleId: `lifecycle:${turnId}`, turnId, sessionId, backendRunId: null, acceptedAt, dequeuedAt: null, governedStartedAt: null, governedAcquiredAt: null, budgetStartedAt: null, budgetAdmittedAt: null, @@ -24,7 +24,7 @@ export function createTurnLifecycle(store: AwaitableActivityStore, turnId: strin // Observability, including fanout, must never fail the observed turn. Each // write carries the record as it is now and fans out once committed (#2814). const writes = orderedWrites(store, () => { /* best effort */ }); - const persist = () => { writes.store.writeLifecycle(structuredClone(record)); writes.after(onWrite); }; + const persist = () => { writes.store.writeLifecycle(structuredClone(record), principalId); writes.after(onWrite); }; persist(); const recordHostEvent = (kind: ActivityTurnLifecycle["hostEvents"][number]["kind"], principalId: string) => { if (record.endedAt !== null) return; @@ -81,6 +81,7 @@ export function createTurnLifecycle(store: AwaitableActivityStore, turnId: strin return { startupTiming, recordHostEvent, + settled: writes.settled, recordCancellation(principalId: string, kind: "turn" | "ask_user" = "turn") { recordHostEvent(kind === "turn" ? "turn_cancelled" : "ask_user_cancelled", principalId); }, diff --git a/packages/ui-server/src/ws/bridge-capabilities/emission.ts b/packages/ui-server/src/ws/bridge-capabilities/emission.ts index 5feabeef86..e7cbafcb37 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/emission.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/emission.ts @@ -65,6 +65,11 @@ function captureFrameFields(ctx: BridgeContext) { function normalizeFrame(ctx: BridgeContext, thinkingLevel: ReturnType["thinkingLevel"], message: Frame): Frame { const { host, turn, turnId, requestId, backendId, signal } = ctx; let msg = message; + if (msg.type === "status") { + // A backend cannot attest host teardown, even if it supplies this field. + const { hostTurnComplete: _hostTurnComplete, ...backendStatus } = msg; + msg = backendStatus; + } // Pi preserves a bare acquisition error for direct SDK callers without // inventing a session. The hosted request has its own cancellation and // correlation, so preserve that terminal UI state only for this exact diff --git a/packages/ui-server/src/ws/client-turn-receipts.ts b/packages/ui-server/src/ws/client-turn-receipts.ts new file mode 100644 index 0000000000..1e76840315 --- /dev/null +++ b/packages/ui-server/src/ws/client-turn-receipts.ts @@ -0,0 +1,31 @@ +import type { WsHost } from "./host.js"; + +type PendingReceipt = { principalId: string; ready: Promise; claimed: boolean }; +const pending = new WeakMap>(); +const MAX_PENDING_RECEIPTS = 256; + +/** Host cleanup is complete in memory. Persistence may finish later, without + * holding idle or the next turn. Keep only a bounded number of pending gates. */ +export function prepareClientTurnReceipt(host: WsHost, turnId: string, principalId: string, settled: () => Promise): boolean { + if (typeof host.activity?.store.writeClientReceipt !== "function") return false; + let gates = pending.get(host); + if (!gates) { gates = new Map(); pending.set(host, gates); } + const existing = gates.get(turnId); + if (existing) return existing.principalId === principalId; + if (gates.size >= MAX_PENDING_RECEIPTS) return false; + const entry: PendingReceipt = { principalId, claimed: false, ready: Promise.resolve().then(settled).catch(() => {}) }; + gates.set(turnId, entry); + const retained = gates; + void entry.ready.then(() => { if (retained.get(turnId) === entry) retained.delete(turnId); }); + return true; +} + +/** A first owner report may await timing persistence; duplicates and other + * principals cannot accumulate waiting handlers or consume that owner's slot. */ +export function claimClientTurnReceipt(host: WsHost, turnId: string, principalId: string): Promise | false | undefined { + const entry = pending.get(host)?.get(turnId); + if (!entry) return undefined; + if (entry.principalId !== principalId || entry.claimed) return false; + entry.claimed = true; + return entry.ready; +} diff --git a/packages/ui-server/src/ws/connection.ts b/packages/ui-server/src/ws/connection.ts index 1ee41ea33b..281037c3e3 100644 --- a/packages/ui-server/src/ws/connection.ts +++ b/packages/ui-server/src/ws/connection.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { upgradeWebSocket, websocket } from "hono/bun"; import type { MiddlewareHandler } from "hono"; import { ASK_RECEIPTS_CAPABILITY, ATTACHMENT_READS_CAPABILITY, CHAT_DELETION_CAPABILITY, COMPOSER_FILES_CAPABILITY, LIVENESS_CAPABILITY, PROTOCOL_REV, SESSION_RECOVERY_CAPABILITY } from "@schlessera/brain-ui-sdk/protocol"; -import { parseClientMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { parseClientMessage, MAX_CLIENT_TURN_RECEIPT_BYTES } from "@schlessera/brain-ui-sdk/schemas"; import { withTurnScope } from "./frames.js"; import { resendPendingInteractive } from "./resend.js"; import { supportsSessionRecovery } from "./recovery.js"; @@ -47,6 +47,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { // One bucket per connection, created here so it lives and dies with the // socket rather than in a map keyed by something a peer controls. const limiter = host.newRateLimiter(); + const receiptLimiter = host.newRateLimiter(); // Authentication can await before it reaches this handler. Re-read durable // validity as the coordinator constructs and synchronously registers the // context, so there is no unregistered authorization state to lose. @@ -106,7 +107,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { location: true, // Advertised only when this host records activity — a client on an // activity-less host knows subscribing would be pointless. - ...(host.activity ? { activity: true } : {}), + ...(host.activity ? { activity: true, ...(host.activity.store.writeClientReceipt ? { clientTurnReceipts: true } : {}) } : {}), ...(host.inbox ? { inbox: true } : {}), // Offered to clients that declare it in client_hello (#957). toolResolution: true, @@ -228,10 +229,14 @@ export function createWsHandlers(host: WsHost, principal: Principal) { // underlying POOLED ArrayBuffer (byteOffset/byteLength discarded), so a // binary frame cannot be decoded correctly here. The protocol is JSON // text; reject anything else rather than parse a slab. - // Metered BEFORE parsing: the point is to bound work an unmetered peer - // can make this process do, and parsing is most of that work. - if (limiter && !limiter.take().allowed) { - host.reportDroppedFrame("rate_limited"); + // Full payload/schema parsing stays metered. A bounded lexical + // discriminator probe puts optional receipts on a separate bucket; + // they cannot consume voice/chat credit or trigger voice gap handling. + const receipt = isClientReceipt(evt.data); + const bucket = receipt ? receiptLimiter : limiter; + if (bucket && !bucket.take().allowed) { + host.reportDroppedFrame(receipt ? "client_turn_receipt_rate_limited" : "rate_limited"); + if (receipt) return; // A metered-away frame may have been audio: a live conversation // must not continue on an incomplete record (#957). host.conversations?.frameDropped(connection); @@ -258,6 +263,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { // The reason is the parser's own bounded message, never the frame: // the payload is caller-supplied and capped at 12 MB. host.reportDroppedFrame("parse_error", parsed.error); + if (receipt || parsed.frameType === "client_turn_receipt") return; host.sendMessage(ws, { type: "error", code: "PARSE_ERROR", message: parsed.error }); return; } @@ -282,6 +288,7 @@ export function createWsHandlers(host: WsHost, principal: Principal) { error: err instanceof Error ? err.message : String(err), }, }); + if (parsed.message.type === "client_turn_receipt") return; host.sendMessage(ws, { type: "error", code: "INTERNAL_ERROR", @@ -362,3 +369,30 @@ export function createWsUpgrade(host: WsHost): MiddlewareHandler { } }; } + +/** Routing only, never schema acceptance: the full parser still validates it. + * Unidentifiable/oversized frames retain the conservative general guard. */ +function isClientReceipt(raw: unknown): boolean { + // This bounds lexical work in UTF-16 units; parseClientMessage separately + // enforces the receipt acceptance limit in encoded bytes, after metering. + if (typeof raw !== "string" || raw.length > MAX_CLIENT_TURN_RECEIPT_BYTES) return false; + // Scan only top-level string tokens. Never JSON-decode unmetered input; + // nested or quoted type text cannot borrow the receipt bucket. The full + // parser alone decides whether the frame is valid, after metering. + const tokens = raw.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\]:,]|[^\s{}\[\]:,"]+/g); + let depth = 0, key = "", expectsKey = false, expectsValue = false, receipt = false; + const ascii = (token: string) => token.slice(1, -1).replace(/\\u([0-9a-fA-F]{4})/g, (_, hex: string) => String.fromCharCode(parseInt(hex, 16))); + for (const [token] of tokens) { + if (token === "{" || token === "[") { depth++; if (depth === 1) expectsKey = token === "{"; continue; } + if (token === "}" || token === "]") { depth--; continue; } + if (depth !== 1) continue; + if (token === ",") { expectsKey = true; expectsValue = false; continue; } + if (token === ":") { expectsValue = true; continue; } + if (expectsKey) { key = token.startsWith('"') ? ascii(token) : ""; expectsKey = false; continue; } + if (expectsValue) { + if (key === "type") receipt = token.startsWith('"') && ascii(token) === "client_turn_receipt"; + expectsValue = false; + } + } + return receipt; +} diff --git a/packages/ui-server/src/ws/handlers/client-turn-receipt.ts b/packages/ui-server/src/ws/handlers/client-turn-receipt.ts new file mode 100644 index 0000000000..57444499f3 --- /dev/null +++ b/packages/ui-server/src/ws/handlers/client-turn-receipt.ts @@ -0,0 +1,20 @@ +import { claimClientTurnReceipt } from "../client-turn-receipts.js"; +import type { ClientMessageHandler } from "./context.js"; + +export const handleClientTurnReceipt: ClientMessageHandler<"client_turn_receipt"> = async ({ host, connection }, msg) => { + try { + const persistence = claimClientTurnReceipt(host, msg.turnId, connection.authorization.principalId); + if (persistence === false) { host.reportDroppedFrame("client_turn_receipt_refused"); return; } + await persistence; + if (!connection.authorization.valid || connection.authorization.expiresAt <= Date.now()) { + host.reportDroppedFrame("client_turn_receipt_refused"); return; + } + const accepted = await host.activity?.store.writeClientReceipt?.(msg.turnId, connection.authorization.principalId, msg.timing); + if (accepted) { + try { host.activity?.stream.pump(); } catch { /* Fanout loss does not undo acceptance. */ } + return; + } + } catch { /* Losing telemetry never changes the turn or connection. */ } + // Deliberately identical for an unknown turn, wrong owner and duplicate. + host.reportDroppedFrame("client_turn_receipt_refused"); +}; diff --git a/packages/ui-server/src/ws/handlers/index.ts b/packages/ui-server/src/ws/handlers/index.ts index caf2d56cab..e4500c749e 100644 --- a/packages/ui-server/src/ws/handlers/index.ts +++ b/packages/ui-server/src/ws/handlers/index.ts @@ -1,3 +1,4 @@ +import { handleClientTurnReceipt } from "./client-turn-receipt.js"; import { handleSafetyRead, handleSafetySubscribe, handleSafetyUnsubscribe } from "./safety.js"; import type { ClientMessageHandlers } from "./context.js"; import { handleActivitySubscribe, handleActivityUnsubscribe } from "./activity.js"; @@ -33,6 +34,7 @@ import { handleToolApproval, handleToolDenial } from "./tool-permission.js"; export const CLIENT_MESSAGE_HANDLERS: ClientMessageHandlers = { safety_read: handleSafetyRead, safety_subscribe: handleSafetySubscribe, safety_unsubscribe: handleSafetyUnsubscribe, client_hello: handleClientHello, + client_turn_receipt: handleClientTurnReceipt, chat_message: handleChatMessageFrame, handoff_status: handleHandoffStatus, handoff_prepare: handleHandoffPrepare, diff --git a/packages/ui-server/src/ws/run-session.ts b/packages/ui-server/src/ws/run-session.ts index f79d4ddf50..58368968af 100644 --- a/packages/ui-server/src/ws/run-session.ts +++ b/packages/ui-server/src/ws/run-session.ts @@ -64,7 +64,7 @@ export async function runSession(host: WsHost, initial: RunSessionInput): Promis const turnId = crypto.randomUUID(); if(initial.historyOwnerId && initial.authorization.valid) host.dialogue.adoptTurn(turnId,initial.historyOwnerId,initial.authorization.principalId); const releaseAuthorization = initial.authorization.retain(); - const lifecycle = host.activity ? createTurnLifecycle(host.activity.store, turnId, initial.sessionId ?? null, Date.now(), () => host.activity!.stream.pump()) : undefined; + const lifecycle = host.activity ? createTurnLifecycle(host.activity.store, turnId, initial.sessionId ?? null, Date.now(), () => host.activity!.stream.pump(), undefined, initial.authorization.principalId) : undefined; const task = runRetainedSession(host, initial, turnId, lifecycle); host.turnTasks.add(task); try { @@ -142,7 +142,7 @@ async function runRetainedSession( next = dequeueRequest(turn); continue; } - publishTurnStatus(slot, result.outcome); + publishTurnStatus({ ...slot, clientReceiptEligible: result.clientReceiptEligible }, result.outcome); // Subsequent (queued) turns resume the now-known session and keep its // pin. turn.providerId is the resolved profile (set from initial routing @@ -253,7 +253,7 @@ function queueFollowUp(host: WsHost, ws: WSContext, sessionId: string, slot: { q entry.queuedAt = Date.now(); if (host.activity && !entry.lifecycle) { entry.lifecycleTurnId = crypto.randomUUID(); - entry.lifecycle = createTurnLifecycle(host.activity.store, entry.lifecycleTurnId, sessionId, entry.queuedAt, () => host.activity!.stream.pump()); + entry.lifecycle = createTurnLifecycle(host.activity.store, entry.lifecycleTurnId, sessionId, entry.queuedAt, () => host.activity!.stream.pump(), undefined, entry.principalId); const release = entry.releaseAuthorization; entry.releaseAuthorization = () => { entry.lifecycle?.finish("cancelled", "Removed from the queue before completion"); release(); }; } @@ -494,7 +494,7 @@ export async function handleChatMessage( // Accepted for a known session: it takes the next revision now, before // routing, so anything sent after it orders after it (#964). revision = acceptRequest(host, sessionId, requestId, host.catalog.getStoredBackendId(sessionId)); - host.sendToClients(withSessionId({ type: "status", status: "thinking" }, sessionId)); + host.sendToClients(withSessionId({ type: "status", status: "thinking", ...(requestId ? { requestId } : {}) }, sessionId)); } const running = runSession(host, { authorization, diff --git a/packages/ui-server/src/ws/session-run/slot.ts b/packages/ui-server/src/ws/session-run/slot.ts index b79f4f631c..e12d686302 100644 --- a/packages/ui-server/src/ws/session-run/slot.ts +++ b/packages/ui-server/src/ws/session-run/slot.ts @@ -85,6 +85,8 @@ export function registerSessionSlot( host.sendToClients({ type: "status", status: "thinking", + turnId: initialTurnId, + ...(initial.requestId ? { requestId: initial.requestId } : {}), detail: `Pinned model "${target.droppedPin}" is unavailable — running on the default.`, ...(initial.sessionId ? { sessionId: initial.sessionId } : {}), }); @@ -155,7 +157,7 @@ export function requestLifecycle( const { host, turn } = slot; if (turn.turnId === slot.firstTurnId) return initialLifecycle; return current.lifecycle ?? (host.activity - ? createTurnLifecycle(host.activity.store, turn.turnId, turn.sessionId, current.queuedAt ?? Date.now(), () => host.activity!.stream.pump()) + ? createTurnLifecycle(host.activity.store, turn.turnId, turn.sessionId, current.queuedAt ?? Date.now(), () => host.activity!.stream.pump(), undefined, current.principalId) : undefined); } diff --git a/packages/ui-server/src/ws/session-run/teardown.ts b/packages/ui-server/src/ws/session-run/teardown.ts index 7be02140b6..c7089f07de 100644 --- a/packages/ui-server/src/ws/session-run/teardown.ts +++ b/packages/ui-server/src/ws/session-run/teardown.ts @@ -1,6 +1,7 @@ import { lstatSync } from "node:fs"; import { createHash } from "node:crypto"; import { isEnvName, PROTECTED_TIER_A } from "@schlessera/brain-ui-sdk/internal"; +import { prepareClientTurnReceipt } from "../client-turn-receipts.js"; import { withTurnScope } from "../frames.js"; import type { TurnOutcome } from "./outcome.js"; import { releaseActive } from "./slot.js"; @@ -81,6 +82,7 @@ export async function teardownTurn(run: TurnRun, outcome: TurnOutcome): Promise< turn.backendStarted = false; await failureRecording.finish(turn.sessionId); lifecycle?.finish(outcome.lifecycle, outcome.reason ?? null); + run.clientReceiptEligible = !!lifecycle && prepareClientTurnReceipt(host, run.turnId, current.principalId, lifecycle.settled); clearTimeout(timeoutHandle); turn.recorder = undefined; work?.settle(outcome.work, { sessionId: turn.sessionId, ...(outcome.reason ? { reason: outcome.reason } : {}) }); @@ -90,6 +92,9 @@ export async function teardownTurn(run: TurnRun, outcome: TurnOutcome): Promise< // (#2814); recovery must see them before the final idle notification, // which the slot publishes with {@link publishTurnStatus}. await recorder?.settled(); + // Lifecycle timing is best-effort: pending or failed telemetry must not + // hold idle or the next queued turn. The receipt handler waits for any + // pending timing commit separately from this cleanup path. } /** @@ -99,9 +104,13 @@ export async function teardownTurn(run: TurnRun, outcome: TurnOutcome): Promise< * backend result can precede asynchronous journal finalization, so recovery * reads the committed terminal from `idle`, before a successor starts. */ -export function publishTurnStatus(run: Pick, outcome: Pick): void { +export function publishTurnStatus(run: Pick, outcome: Pick): void { const { host, turn } = run; if (outcome.cancelledBeforeStart) host.sendToClients(withTurnScope({ type: "status", status: "cancelled", detail: "Cancelled before starting", ...(turn.requestId ? { requestId: turn.requestId } : {}) }, turn)); - else if (turn.sessionId) host.sendToClients(withTurnScope({ type: "status", status: "idle" }, turn)); + else if (turn.sessionId) { + // The marker describes completed host cleanup, not a database commit. + // Eligibility was captured in memory; idle never reads lifecycle storage. + host.sendToClients(withTurnScope({ type: "status", status: "idle", ...(run.clientReceiptEligible ? { hostTurnComplete: true as const } : {}) }, turn)); + } } diff --git a/packages/ui-server/src/ws/session-run/turn.ts b/packages/ui-server/src/ws/session-run/turn.ts index aef5e0e74c..eacb9b24c9 100644 --- a/packages/ui-server/src/ws/session-run/turn.ts +++ b/packages/ui-server/src/ws/session-run/turn.ts @@ -16,7 +16,7 @@ import type { SessionSlot, TurnLifecycle, TurnRun } from "./types.js"; * synchronous run as its next dequeue or its close. */ type SlotTurnResult = - | { readonly kind: "ran"; readonly outcome: TurnOutcome } + | { readonly kind: "ran"; readonly outcome: TurnOutcome; readonly clientReceiptEligible?: boolean } | { readonly kind: "revoked" } | { readonly kind: "denied"; readonly error: unknown }; @@ -81,7 +81,7 @@ export async function runSlotTurn(slot: SessionSlot, current: QueuedFollowUp, li stops: {}, budgetWrites: new Set(), held: { referenceViews: null, referenceTurn: false, enteredBackend: false }, }; announceTurnStart(slot, current, run.startedAt); - return { kind: "ran", outcome: await executeTurn(run) }; + return { kind: "ran", outcome: await executeTurn(run), ...(run.clientReceiptEligible ? { clientReceiptEligible: true } : {}) }; } /** Admit, enter the backend, classify the outcome and tear the turn down. */ diff --git a/packages/ui-server/src/ws/session-run/types.ts b/packages/ui-server/src/ws/session-run/types.ts index 4aeade1543..bfa0550997 100644 --- a/packages/ui-server/src/ws/session-run/types.ts +++ b/packages/ui-server/src/ws/session-run/types.ts @@ -120,6 +120,8 @@ export interface TurnRun { /** The turn's identity as it started; the slot re-mints it for the next request. */ readonly turnId: string; readonly lifecycle: TurnLifecycle | undefined; + /** Host cleanup is complete; receipt persistence may still be pending. */ + clientReceiptEligible?: boolean; readonly abortController: AbortController; readonly timeoutHandle: ReturnType; readonly billing: RunBilling; diff --git a/packages/ui-server/tests/client-turn-completion.test.ts b/packages/ui-server/tests/client-turn-completion.test.ts new file mode 100644 index 0000000000..2583ad7e52 --- /dev/null +++ b/packages/ui-server/tests/client-turn-completion.test.ts @@ -0,0 +1,109 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { prepareClientTurnReceipt } from "../src/ws/client-turn-receipts.js"; +import { createOffloopActivityStore } from "../src/activity/store-writes.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { publishTurnStatus, teardownTurn } from "../src/ws/session-run/teardown.js"; +import { handleClientMessage } from "../src/ws/dispatch.js"; +import type { WsHost } from "../src/ws/host.js"; +import type { TurnRun } from "../src/ws/session-run/types.js"; +import { testAuthorization, testPrincipal } from "./helpers/principal.js"; +import * as probe from "./fixtures/client-turn-writer-probe.js"; + +test("idle eligibility never reads lifecycle storage", () => { + let reads = 0; + const frames: unknown[] = []; + const host = { activity: { store: { lifecycle() { reads++; throw new Error("Lifecycle I/O on idle"); } } }, + sendToClients: (frame: unknown) => frames.push(frame), log: { emit() {} } } as unknown as WsHost; + publishTurnStatus({ host, turn: { turnId: "turn-ithaca", sessionId: "ithaca" } as never, clientReceiptEligible: true }, { cancelledBeforeStart: false }); + expect(reads).toBe(0); + expect(frames[0]).toMatchObject({ type: "status", status: "idle", hostTurnComplete: true }); +}); + +test("file-backed writer cannot hold idle and a receipt waits for its late terminal commit", async () => { + const folder = mkdtempSync(join(tmpdir(), "client-turn-ithaca-")); + const db = createUiDb(join(folder, "ui.db")), writer = openSqliteWriter(db); + const store = createOffloopActivityStore(db, writer); + const gate = new Int32Array(new SharedArrayBuffer(12)); + const release = () => { Atomics.store(gate, 1, 1); Atomics.notify(gate, 1); }; + const timeoutHandle = setTimeout(() => {}, watchdogMs(30000)); + let held: Promise | undefined, receipt: Promise | undefined; + const rejected: Promise[] = []; + let lifecycle: ReturnType | undefined; + const frames: unknown[] = [], refused: string[] = []; + const host = { activity: { store, stream: { pump() {} } }, dialogue: { retireTurn() {} }, log: { emit() {} }, + sendToClients: (frame: unknown) => frames.push(frame), reportDroppedFrame: (reason: string) => refused.push(reason) } as unknown as WsHost; + try { + expect(writer.offloop).toBe(true); + const channel = writer.channel(probe, {}); await channel.ready; + held = channel.call("hold", gate, watchdogMs(10000)); + const entering = Atomics.waitAsync(gate, 0, 0); if (entering.async) await entering.value; + lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100, "odysseus"); + const run = { host, turnId: "turn-ithaca", turn: { turnId: "turn-ithaca", sessionId: "ithaca" }, slot: { releaseActive() {} }, + current: { principalId: "odysseus" }, held: {}, stops: {}, failureRecording: { async finish() {} }, lifecycle, timeoutHandle } as unknown as TurnRun; + await teardownTurn(run, { lifecycle: "success", work: "completed", cancelledBeforeStart: false }); + publishTurnStatus(run, { cancelledBeforeStart: false }); + expect(Atomics.load(gate, 2), "IDLE_PRECEDES_HELD_WRITER_RELEASE").toBe(0); + expect(frames[0]).toMatchObject({ type: "status", status: "idle", hostTurnComplete: true }); + const report = (principal: string, ms: number) => handleClientMessage(host, {} as never, + { type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: ms } }, + { principal: testPrincipal(principal), authorization: testAuthorization(principal) }); + let wrongOwnerDone = false, duplicateDone = false; + rejected.push(report("eurylochus", 99).then(() => { wrongOwnerDone = true; })); + await new Promise(resolve => setImmediate(resolve)); + expect(wrongOwnerDone).toBe(true); + receipt = report("odysseus", 7); + rejected.push(report("odysseus", 99).then(() => { duplicateDone = true; })); + await new Promise(resolve => setImmediate(resolve)); + expect(duplicateDone).toBe(true); + release(); await held; await receipt; await lifecycle.settled(); await writer.idle(); + expect(refused).toEqual(["client_turn_receipt_refused", "client_turn_receipt_refused"]); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual({ sendToFirstHostFrameMs: 7 }); + } finally { + release(); await held; await receipt; await Promise.allSettled(rejected); await lifecycle?.settled(); clearTimeout(timeoutHandle); + await writer.close(); db.close(); rmSync(folder, { recursive: true, force: true }); + } +}); + +test("revocation during deferred persistence refuses only that report", async () => { + const db = createUiDb(":memory:"), store = createActivityStore(db); + const ready = Promise.withResolvers(); + const refused: string[] = []; + const host = { activity: { store, stream: { pump() {} } }, reportDroppedFrame: (reason: string) => refused.push(reason) } as unknown as WsHost; + const life = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100, "odysseus"); life.finish("success"); + const authorization = testAuthorization("odysseus"); + let waiting: Promise | undefined; + try { + expect(prepareClientTurnReceipt(host, "turn-ithaca", "odysseus", () => ready.promise)).toBe(true); + waiting = handleClientMessage(host, {} as never, { type: "client_turn_receipt", turnId: "turn-ithaca", timing: { sendToFirstHostFrameMs: 7 } }, + { principal: testPrincipal("odysseus"), authorization }); + await new Promise(resolve => setImmediate(resolve)); + (authorization as { valid: boolean }).valid = false; + ready.resolve(); await waiting; + expect(store.lifecycle("turn-ithaca")?.clientTiming).toBeUndefined(); + expect(refused).toEqual(["client_turn_receipt_refused"]); + const other = createTurnLifecycle(store, "turn-troy", "ithaca", 1000, () => {}, () => 1100, "odysseus"); other.finish("success"); + await handleClientMessage(host, {} as never, { type: "client_turn_receipt", turnId: "turn-troy", timing: { sendToFirstHostFrameMs: 9 } }, + { principal: testPrincipal("odysseus"), authorization: testAuthorization("odysseus") }); + expect(store.lifecycle("turn-troy")?.clientTiming).toEqual({ sendToFirstHostFrameMs: 9 }); + } finally { ready.resolve(); await waiting; db.close(); } +}); + + +test("pending receipt capacity drops only new samples and recovers after persistence", async () => { + const ready = Promise.withResolvers(); + const host = { activity: { store: { writeClientReceipt() {} } } } as unknown as WsHost; + try { + for (let index = 0; index < 256; index++) expect(prepareClientTurnReceipt(host, `turn-ithaca-${index}`, "odysseus", () => ready.promise)).toBe(true); + expect(prepareClientTurnReceipt(host, "turn-troy", "odysseus", () => ready.promise)).toBe(false); + ready.resolve(); + await new Promise(resolve => setImmediate(resolve)); + expect(prepareClientTurnReceipt(host, "turn-troy", "odysseus", () => Promise.resolve())).toBe(true); + } finally { ready.resolve(); } +}); diff --git a/packages/ui-server/tests/client-turn-isolation.test.ts b/packages/ui-server/tests/client-turn-isolation.test.ts new file mode 100644 index 0000000000..1e92d3c1ff --- /dev/null +++ b/packages/ui-server/tests/client-turn-isolation.test.ts @@ -0,0 +1,279 @@ +import { expect, test } from "bun:test"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { createActivityStream } from "../src/activity/stream.js"; +import { runActivityQuery } from "../src/activity/query.js"; +import { WsHost } from "../src/ws/host.js"; +import { createWsHandlers } from "../src/ws/connection.js"; +import { FrameRateLimiter } from "../src/ws/rate-limit.js"; +import { createStaticBackendRegistry } from "../src/agent/backend.js"; +import { createSessionCatalog } from "../src/ws/session-catalog.js"; +import { makeFakeBackend } from "./helpers/fake-backend.js"; +import { testPrincipal } from "./helpers/principal.js"; +import type { WSContext } from "../src/ws/clients.js"; + +const timing = { sendToFirstHostFrameMs: 5 }; +function completed(store: ReturnType, turnId: string, at = 1000) { + const lifecycle = createTurnLifecycle(store, turnId, "ithaca", at, () => {}, () => at + 100, "odysseus"); + lifecycle.finish("success"); +} + +test("one malformed client receipt leaves host records, other receipts and Activity deltas usable", () => { + const db = createUiDb(":memory:"); + const store = createActivityStore(db); + completed(store, "turn-ithaca"); completed(store, "turn-troy"); + const stream = createActivityStream(store); + try { + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", timing)).toBe(true); + expect(store.writeClientReceipt!("turn-troy", "odysseus", timing)).toBe(true); + db.query("UPDATE activity_turn_clients SET receipt = ? WHERE turn_id = ?").run("{broken", "turn-ithaca"); + expect(store.lifecycle("turn-ithaca")).toMatchObject({ outcome: "success", clientTimingUnavailable: "invalid_receipt" }); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toBeUndefined(); + expect(store.lifecycles()).toHaveLength(2); + const frames: Array<{ type: string; lifecycle?: { turnId: string; clientTiming?: unknown } }> = []; + const ws: WSContext = { send: text => frames.push(JSON.parse(text)) }; + stream.handleSubscribe(ws, { type: "activity_subscribe", view: "index" }, "odysseus"); + stream.pump(); + expect(frames.filter(frame => frame.type === "activity_delta").map(frame => frame.lifecycle?.turnId)).toEqual(["turn-ithaca", "turn-troy"]); + expect(frames.at(-1)?.lifecycle).toMatchObject({ turnId: "turn-troy", clientTiming: timing }); + db.query("UPDATE activity_turn_clients SET receipt = ? WHERE turn_id = ?").run('{"sendToFirstHostFrameMs":-1}', "turn-ithaca"); + expect(store.lifecycleChangesSince(0).at(-2)?.lifecycle).toMatchObject({ turnId: "turn-ithaca", clientTimingUnavailable: "invalid_receipt" }); + db.query("UPDATE activity_turn_clients SET receipt = ? WHERE turn_id = ?").run(" ".repeat(5000) + JSON.stringify(timing), "turn-ithaca"); + expect(store.lifecycle("turn-ithaca")?.clientTimingUnavailable).toBe("invalid_receipt"); + expect(store.lifecycle("turn-troy")?.clientTiming).toEqual(timing); + } finally { stream.close(); db.close(); } +}); + +for (const stage of ["lifecycle-only", "snapshot", "pruned"] as const) { + test(`client receipt never enters provider-facing ${stage} Activity tool results`, () => { + const db = createUiDb(":memory:"); + const store = createActivityStore(db); + const descriptor = Object.getOwnPropertyDescriptor(Date, "now")!; + const at = Date.UTC(2026, 6, 12); + Object.defineProperty(Date, "now", { ...descriptor, value: () => at + 1000 }); + try { + completed(store, "turn-ithaca", at); + if (stage !== "lifecycle-only") { + store.startSpan({ spanId: "root", runId: "turn-ithaca", name: "invoke_agent", kind: "turn", origin: "session", startedAt: at }); + store.endSpan("root", { outcome: "success", endedAt: at + 100 }); store.rollupRun("turn-ithaca"); + } + if (stage === "pruned") store.prune({ digestFloorAt: at + 1000, detailRetentionMs: 0, hardCeilingMs: 0, now: at + 1000 }); + const read = () => JSON.stringify([ + runActivityQuery(db, store, { scope: "run", runId: "turn-ithaca" }), + runActivityQuery(db, store, { scope: "recent" }), + ]); + const before = read(); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", timing)).toBe(true); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual(timing); + expect(read()).toBe(before); + expect(read()).not.toContain("clientTiming"); + db.query("UPDATE activity_turn_clients SET receipt = ? WHERE turn_id = ?").run("{broken", "turn-ithaca"); + expect(store.lifecycle("turn-ithaca")?.clientTimingUnavailable).toBe("invalid_receipt"); + expect(read()).toBe(before); + expect(read()).not.toContain("clientTimingUnavailable"); + } finally { Object.defineProperty(Date, "now", descriptor); db.close(); } + }); +} + + +for (const invalid of [false, true]) { + test(`${invalid ? "schema-invalid" : "rate-limited"} receipt never interrupts voice or emits a draft-affecting error`, async () => { + const db = createUiDb(":memory:"); + const backend = makeFakeBackend({ id: "odyssey" }); + const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog: createSessionCatalog(() => db) }); + host.newRateLimiter = () => new FrameRateLimiter({ ratePerSecond: 1, burst: 1, clock: { now: () => 0 } }); + let voiceActive = true; + Object.defineProperty(host, "conversations", { value: { frameDropped() { voiceActive = false; }, closeAll() {} } }); + const sent: unknown[] = []; + const pong = Promise.withResolvers(); + const ws: WSContext = { send: text => { const message = JSON.parse(text); sent.push(message); if (message.type === "pong") pong.resolve(); } }; + const handlers = createWsHandlers(host, testPrincipal("odysseus")); + const message = { type: "client_turn_receipt", turnId: "turn-ithaca", timing: invalid ? { sendToFirstHostFrameMs: -1 } : timing }; + try { + handlers.onMessage({ data: JSON.stringify(message) } as MessageEvent, ws); + if (!invalid) handlers.onMessage({ data: JSON.stringify(message) } as MessageEvent, ws); + expect(sent).toEqual([]); + expect(voiceActive).toBe(true); + handlers.onMessage({ data: JSON.stringify({ type: "ping", probeId: "return-to-ithaca" }) } as MessageEvent, ws); + await pong.promise; + expect(sent).toEqual([{ type: "pong", probeId: "return-to-ithaca" }]); + } finally { await host.close(); db.close(); } + }); +} + +test("a prior ActivityStore implementation remains assignable and does not advertise receipt support", async () => { + const { createActivityRuntime } = await import("../src/activity/runtime.js"); + const { createSilentObservability } = await import("../src/observability/index.js"); + const db = createUiDb(":memory:"); + const { writeClientReceipt: _receipt, snapshotLifecycles: _snapshot, ...prior } = createActivityStore(db); + // This assignment is also compile-time proof for consumers implementing the previous interface. + const compatible: import("../src/activity/store.js").ActivityStore = prior; + const observability = createSilentObservability(); + const activity = createActivityRuntime(db, { log: observability.logger("test") }); + activity.store = compatible; + const backend = makeFakeBackend({ id: "odyssey" }); + const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog: createSessionCatalog(() => db), activity }); + const frames: Array<{ type: string; capabilities?: Record }> = []; + const ws: WSContext = { send: text => frames.push(JSON.parse(text)) }; + try { + await createWsHandlers(host, testPrincipal("odysseus")).onOpen(undefined as never, ws); + expect(frames.find(frame => frame.type === "server_hello")?.capabilities?.clientTurnReceipts).toBeUndefined(); + expect(compatible.lifecycle("turn-missing")).toBeNull(); + } finally { await host.close(); await activity.close(); db.close(); } +}); + +test("the initial thinking for an accepted existing session carries its request correlation", async () => { + const { handleChatMessage } = await import("../src/ws/run-session.js"); + const { testAuthorization } = await import("./helpers/principal.js"); + const db = createUiDb(":memory:"); + const catalog = createSessionCatalog(() => db); + const backend = makeFakeBackend({ id: "odyssey" }); + catalog.persistSessionStub("ithaca", "Plan Ithaca", null, backend.id); + await catalog.settled?.(); + const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog }); + const frames: unknown[] = []; + const ws: WSContext = { send: text => frames.push(JSON.parse(text)) }; + host.clients.add(ws, "odysseus"); + try { + await handleChatMessage(host, ws, { text: "Return to Ithaca", sessionId: "ithaca", requestId: "voyage", attachments: [], authorization: testAuthorization("odysseus") }); + expect(frames[0]).toMatchObject({ type: "status", status: "thinking", sessionId: "ithaca", requestId: "voyage" }); + } finally { await host.close(); await Promise.allSettled([...host.turnTasks]); db.close(); } +}); + +test("embedded NUL and damaged suffix never turn corrupt storage into valid timing", () => { + const db = createUiDb(":memory:"); + const store = createActivityStore(db); + try { + completed(store, "turn-ithaca"); completed(store, "turn-troy"); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", timing)).toBe(true); + expect(store.writeClientReceipt!("turn-troy", "odysseus", timing)).toBe(true); + for (const suffix of ["\u0000damaged", "\u0000" + "x".repeat(5000)]) { + db.query("UPDATE activity_turn_clients SET receipt = ? WHERE turn_id = ?").run(JSON.stringify(timing) + suffix, "turn-ithaca"); + expect(store.lifecycle("turn-ithaca")).toMatchObject({ outcome: "success", clientTimingUnavailable: "invalid_receipt" }); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toBeUndefined(); + expect(store.lifecycleChangesSince(0).at(-2)?.lifecycle.clientTimingUnavailable).toBe("invalid_receipt"); + expect(store.lifecycle("turn-troy")?.clientTiming).toEqual(timing); + } + } finally { db.close(); } +}); + +test("server timing reads preserve unknown optional keys while client writes reject them", async () => { + const { parseServerMessage, parseClientMessage } = await import("@schlessera/brain-ui-sdk/schemas"); + const db = createUiDb(":memory:"); + const store = createActivityStore(db); + try { + completed(store, "turn-ithaca"); + const futureTiming = { ...timing, futureArrivalMs: 7 }; + const lifecycle = { ...store.lifecycle("turn-ithaca")!, clientTiming: futureTiming }; + for (const frame of [ + { type: "activity_delta" as const, runId: "lifecycle:turn-ithaca", seq: 1, lifecycle }, + { type: "activity_snapshot" as const, view: "index" as const, spans: [], events: [], highWaterSeq: {}, lifecycles: [lifecycle] }, + ]) expect(parseServerMessage(JSON.stringify(frame))).toEqual({ ok: true, message: frame }); + expect(parseClientMessage(JSON.stringify({ type: "client_turn_receipt", turnId: "turn-ithaca", timing: futureTiming })).ok).toBe(false); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", futureTiming)).toBe(false); + } finally { db.close(); } +}); + +for (const asynchronous of [false, true]) { + test(`${asynchronous ? "asynchronous" : "synchronous"} terminal timing failure cannot change in-memory host completion`, async () => { + const { publishTurnStatus } = await import("../src/ws/session-run/teardown.js"); + const db = createUiDb(":memory:"); + const store = createActivityStore(db); + const frames: unknown[] = []; + try { + const writes = Object.create(store) as import("../src/activity/store.js").AwaitableActivityStore; + writes.writeLifecycle = (record, owner) => { + if (record.endedAt !== null) { + if (asynchronous) return Promise.reject(new Error("terminal write refused")); + throw new Error("terminal write refused"); + } + return store.writeLifecycle(record, owner); + }; + const lifecycle = createTurnLifecycle(writes, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100, "odysseus"); + lifecycle.finish("success"); await lifecycle.settled(); + const host = { activity: { store }, sendToClients: (frame: unknown) => frames.push(frame), log: { emit() {} } } as unknown as WsHost; + const run = { host, turn: { turnId: "turn-ithaca", sessionId: "ithaca" } as never, clientReceiptEligible: true }; + publishTurnStatus(run, { cancelledBeforeStart: false }); + expect(store.lifecycle("turn-ithaca")?.endedAt).toBeNull(); + expect(frames).toEqual([expect.objectContaining({ type: "status", status: "idle" })]); + expect(frames[0]).toHaveProperty("hostTurnComplete", true); + completed(store, "turn-troy"); + publishTurnStatus({ ...run, turn: { turnId: "turn-troy", sessionId: "ithaca" } as never }, { cancelledBeforeStart: false }); + expect(frames[1]).toHaveProperty("hostTurnComplete", true); + } finally { db.close(); } + }); +} + +test("exhausted ordinary and receipt buckets do not JSON-decode another payload", async () => { + const db = createUiDb(":memory:"); + const backend = makeFakeBackend({ id: "odyssey" }); + const host = new WsHost({ registry: createStaticBackendRegistry([backend], backend.id), catalog: createSessionCatalog(() => db) }); + host.newRateLimiter = () => new FrameRateLimiter({ ratePerSecond: 1, burst: 1, clock: { now: () => 0 } }); + const handlers = createWsHandlers(host, testPrincipal("odysseus")); + const ws: WSContext = { send() {} }; + const ordinary = JSON.stringify({ type: "ping" }); + const receipt = JSON.stringify({ timing, turnId: "turn-ithaca", type: "client_turn_receipt" }); + const descriptor = Object.getOwnPropertyDescriptor(JSON, "parse")!; + const parse = JSON.parse; + const decoded: string[] = []; + try { + handlers.onMessage({ data: ordinary } as MessageEvent, ws); + handlers.onMessage({ data: receipt } as MessageEvent, ws); + Object.defineProperty(JSON, "parse", { ...descriptor, value: (text: string, ...args: unknown[]) => { decoded.push(text); return Reflect.apply(parse, JSON, [text, ...args]); } }); + handlers.onMessage({ data: ordinary } as MessageEvent, ws); + handlers.onMessage({ data: receipt } as MessageEvent, ws); + expect(decoded).toEqual([]); + } finally { Object.defineProperty(JSON, "parse", descriptor); await host.close(); db.close(); } +}); + +test("receipt corruption limits count bytes rather than UTF-16 characters", () => { + const db = createUiDb(":memory:"), store = createActivityStore(db); + try { + completed(store, "turn-ithaca"); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", timing)).toBe(true); + // The overwritten duplicate leaves a valid numeric object after JSON.parse, + // while its original UTF-8 bytes still count toward the storage boundary. + const head = '{"sendToFirstHostFrameMs":"' + "é".repeat(2000) + '","sendToFirstHostFrameMs":7}'; + const padded = (bytes: number) => head + " ".repeat(bytes - Buffer.byteLength(head)); + for (const [value, valid] of [[padded(4096), true], [padded(4097), false], [padded(4097) + "damaged", false]] as const) { + db.query("UPDATE activity_turn_clients SET receipt = ? WHERE turn_id = ?").run(value, "turn-ithaca"); + const record = store.lifecycle("turn-ithaca")!; + expect(record.clientTiming).toEqual(valid ? { sendToFirstHostFrameMs: 7 } : undefined); + expect(record.clientTimingUnavailable).toBe(valid ? undefined : "invalid_receipt"); + } + } finally { db.close(); } +}); + +test("stalled lifecycle timing cannot hold final idle or the next queued turn", async () => { + const { teardownTurn, publishTurnStatus } = await import("../src/ws/session-run/teardown.js"); + const db = createUiDb(":memory:"), store = createActivityStore(db); + const terminal = Promise.withResolvers(), entered = Promise.withResolvers(); + const frames: unknown[] = []; + let done = false, nextStarted = false, released = false; + const writes = Object.create(store) as import("../src/activity/store.js").AwaitableActivityStore; + writes.writeLifecycle = (record, owner) => { + if (record.endedAt !== null) { entered.resolve(); return terminal.promise.then(() => store.writeLifecycle(record, owner)); } + return store.writeLifecycle(record, owner); + }; + // Missing receipt support is deliberate: telemetry cannot delay either host. + Object.defineProperty(writes, "writeClientReceipt", { value: undefined }); + const lifecycle = createTurnLifecycle(writes, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100, "odysseus"); + const host = { activity: { store: writes }, dialogue: { retireTurn() {} }, log: { emit() {} }, sendToClients: (frame: unknown) => frames.push(frame) } as unknown as WsHost; + const { watchdogMs } = await import("../../../scripts/test-deadlines.ts"); + const timeoutHandle = setTimeout(() => {}, watchdogMs(30000)); + const run = { host, turn: { turnId: "turn-ithaca", sessionId: "ithaca" }, slot: { releaseActive() { released = true; } }, + current: {}, held: {}, stops: {}, failureRecording: { async finish() {} }, lifecycle, timeoutHandle } as unknown as import("../src/ws/session-run/types.js").TurnRun; + const task = teardownTurn(run, { lifecycle: "success", work: "completed", cancelledBeforeStart: false }).then(() => { + publishTurnStatus(run, { cancelledBeforeStart: false }); done = true; nextStarted = true; + }); + try { + await entered.promise; + await new Promise(resolve => setImmediate(resolve)); + expect(released).toBe(true); + expect(done).toBe(true); + expect(nextStarted).toBe(true); + expect(frames[0]).toMatchObject({ type: "status", status: "idle" }); + expect(frames[0]).not.toHaveProperty("hostTurnComplete"); + } finally { terminal.resolve(); await task; await lifecycle.settled(); clearTimeout(timeoutHandle); db.close(); } +}); diff --git a/packages/ui-server/tests/client-turn-read-snapshot.test.ts b/packages/ui-server/tests/client-turn-read-snapshot.test.ts new file mode 100644 index 0000000000..a0b54e5e43 --- /dev/null +++ b/packages/ui-server/tests/client-turn-read-snapshot.test.ts @@ -0,0 +1,56 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { watchdogMs } from "../../../scripts/test-deadlines.ts"; +import { createActivityStream } from "../src/activity/stream.js"; +import { createOffloopActivityStore } from "../src/activity/store-writes.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { createUiDb } from "../src/db/client.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import * as probe from "./fixtures/client-turn-writer-probe.js"; + +for (const reader of ["empty pump", "single lifecycle", "lifecycle list", "lifecycle snapshot", "lifecycle deltas", "span snapshot"] as const) { + test(`${reader} reads its snapshot while the file-backed writer remains held`, async () => { + const folder = mkdtempSync(join(tmpdir(), "client-turn-ithaca-read-")); + const db = createUiDb(join(folder, "ui.db")), writer = openSqliteWriter(db); + const store = createOffloopActivityStore(db, writer); + const gate = new Int32Array(new SharedArrayBuffer(12)); + const release = () => { Atomics.store(gate, 1, 1); Atomics.notify(gate, 1); }; + let held: Promise | undefined; + let stream: ReturnType | undefined; + try { + expect(writer.offloop).toBe(true); + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100, "odysseus"); + lifecycle.finish("success"); await lifecycle.settled(); + const timing = { sendToFirstHostFrameMs: 7 }; + expect(await store.writeClientReceipt!("turn-ithaca", "odysseus", timing)).toBe(true); + const frames: string[] = []; + if (reader === "empty pump") { + stream = createActivityStream(store); + stream.handleSubscribe({ send: frame => { frames.push(frame); } }, { type: "activity_subscribe", view: "index" }, "odysseus"); + expect(stream.subscriptionCount()).toBe(1); + } + const frameCount = frames.length; + const channel = writer.channel(probe, {}); await channel.ready; + held = channel.call("hold", gate, watchdogMs(10000)); + const entering = Atomics.waitAsync(gate, 0, 0); if (entering.async) await entering.value; + switch (reader) { + case "empty pump": stream!.pump(); expect(frames).toHaveLength(frameCount); break; + case "single lifecycle": expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual(timing); break; + case "lifecycle list": expect(store.lifecycles("ithaca")[0]?.clientTiming).toEqual(timing); break; + case "lifecycle snapshot": { + const snapshot = store.snapshotLifecycles!({ turnId: "turn-ithaca" }); + expect(snapshot.lifecycles[0]?.clientTiming).toEqual(timing); + expect(snapshot.highWaterSeq["lifecycle:turn-ithaca"]).toBeGreaterThan(0); + break; + } + case "lifecycle deltas": expect(store.lifecycleChangesSince(0).at(-1)?.lifecycle.clientTiming).toEqual(timing); break; + case "span snapshot": expect(store.snapshotRun("turn-ithaca")).toBeNull(); break; + } + expect(Atomics.load(gate, 2), "READ_PRECEDES_HELD_WRITER_RELEASE").toBe(0); + } finally { + release(); await held; stream?.close(); await writer.close(); db.close(); rmSync(folder, { recursive: true, force: true }); + } + }); +} diff --git a/packages/ui-server/tests/client-turn-receipt.test.ts b/packages/ui-server/tests/client-turn-receipt.test.ts new file mode 100644 index 0000000000..a143e62ce1 --- /dev/null +++ b/packages/ui-server/tests/client-turn-receipt.test.ts @@ -0,0 +1,135 @@ +import { expect, test } from "bun:test"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; +import { handleClientMessage } from "../src/ws/dispatch.js"; +import type { WsHost } from "../src/ws/host.js"; +import type { WSContext } from "../src/ws/clients.js"; +import { testAuthorization, testPrincipal } from "./helpers/principal.js"; + +const pairs = { sendToFirstHostFrameMs: 4, sendToFirstContentFrameMs: 204, lastContentFrameToIdleMs: 8 }; +test("an owner receipt joins completed lifecycle reads without changing the host record", async () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1300, "odysseus"); + lifecycle.finish("success"); + const raw = () => db.query("SELECT record FROM activity_turn_lifecycles").get(); + const before = raw(); + const host = { activity: { store, stream: { pump() {} } }, reportDroppedFrame() {} } as unknown as WsHost; + await handleClientMessage(host, {} as WSContext, { type: "client_turn_receipt", turnId: "turn-ithaca", timing: pairs }, + { principal: testPrincipal("odysseus"), authorization: testAuthorization("odysseus") }); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual(pairs); + expect(raw()).toEqual(before); + expect(store.lifecycles()[0]?.clientTiming).toEqual(pairs); + expect(store.lifecycleChangesSince(0).at(-1)?.lifecycle.clientTiming).toEqual(pairs); + } finally { db.close(); } +}); + +test("wrong owner, duplicates and unknown or unfinished turns are refused without affecting another turn", async () => { + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); + const finish = (id: string, owner: string) => { + const lifecycle = createTurnLifecycle(store, id, "ithaca", 1000, () => {}, () => 1300, owner); + lifecycle.finish("success"); + }; + finish("turn-ithaca", "odysseus"); finish("turn-troy", "eurylochus"); + createTurnLifecycle(store, "turn-open", "ithaca", 1000, () => {}, () => 1300, "odysseus"); + const replies: unknown[] = []; + const host = { activity: { store, stream: { pump() {} } }, reportDroppedFrame(reason: string) { replies.push(reason); } } as unknown as WsHost; + const report = (id: string, principalId: string, timing = pairs) => handleClientMessage(host, {} as WSContext, + { type: "client_turn_receipt", turnId: id, timing }, { principal: testPrincipal(principalId), authorization: testAuthorization(principalId) }); + await report("turn-ithaca", "eurylochus"); + await report("turn-open", "odysseus"); + await report("turn-missing", "odysseus"); + expect(replies).toHaveLength(3); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toBeUndefined(); + await report("turn-ithaca", "odysseus"); + await report("turn-ithaca", "odysseus", { ...pairs, sendToFirstHostFrameMs: 999 }); + expect(replies).toHaveLength(4); + expect(replies).toEqual(Array.from({ length: 4 }, () => "client_turn_receipt_refused")); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual(pairs); + await report("turn-troy", "eurylochus"); + expect(store.lifecycle("turn-troy")?.clientTiming).toEqual(pairs); + db.query("DELETE FROM activity_turn_lifecycles WHERE turn_id = ?").run("turn-ithaca"); + expect(db.query("SELECT * FROM activity_turn_clients WHERE turn_id = ?").get("turn-ithaca")).toBeNull(); + expect(store.lifecycle("turn-troy")?.clientTiming).toEqual(pairs); + } finally { db.close(); } +}); + +test("wire and storage reject host fields, non-finite and negative timing values", async () => { + const { clientMessageSchema } = await import("@schlessera/brain-ui-sdk/schemas"); + const valid = { type: "client_turn_receipt", turnId: "turn-ithaca", timing: pairs }; + expect(clientMessageSchema.safeParse(valid).success).toBe(true); + for (const frame of [ + { ...valid, outcome: "success" }, + { ...valid, timing: { ...pairs, acceptedAt: 0 } }, + { ...valid, timing: { ...pairs, sendToFirstHostFrameMs: -1 } }, + { ...valid, timing: { ...pairs, sendToFirstContentFrameMs: Infinity } }, + ]) expect(clientMessageSchema.safeParse(frame).success).toBe(false); + const db = createUiDb(":memory:"); + try { + const store = createActivityStore(db); + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1300, "odysseus"); + lifecycle.finish("success"); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", { ...pairs, acceptedAt: 0 } as typeof pairs)).toBe(false); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toBeUndefined(); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", pairs)).toBe(true); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual(pairs); + } finally { db.close(); } +}); + +test("offloop completion settles ownership before the once-only receipt commits", async () => { + const { mkdtempSync, rmSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { openSqliteWriter } = await import("../src/db/write-worker.js"); + const { createOffloopActivityStore } = await import("../src/activity/store-writes.js"); + const root = mkdtempSync(join(tmpdir(), "client-turn-ithaca-")); + const db = createUiDb(join(root, "ui.db")); + const writer = openSqliteWriter(db); + try { + const store = createOffloopActivityStore(db, writer); + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1300, "odysseus"); + lifecycle.finish("success"); + await lifecycle.settled(); + expect(await store.writeClientReceipt!("turn-ithaca", "odysseus", pairs)).toBe(true); + expect(await store.writeClientReceipt!("turn-ithaca", "odysseus", pairs)).toBe(false); + expect(store.lifecycle("turn-ithaca")?.clientTiming).toEqual(pairs); + } finally { await writer.close(); db.close(); rmSync(root, { recursive: true, force: true }); } +}); + +test("the previous SDK schema parses receipt-enriched lifecycle snapshots and deltas", async () => { + const { previousActivityFrameSchema } = await import("./fixtures/previous-client-turn-schema.js"); + const { createActivityStream } = await import("../src/activity/stream.js"); + const db = createUiDb(":memory:"); + const store = createActivityStore(db); + let now = 1000; + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", now, () => {}, () => now, "odysseus"); + const stop = lifecycle.timer("governed")("inference_origin"); + now = 1100; stop(); lifecycle.finish("success"); + const stream = createActivityStream(store); + try { + const frames: Array<{ type: string; lifecycle?: unknown; lifecycles?: unknown[] }> = []; + const ws: WSContext = { send: text => frames.push(JSON.parse(text)) }; + stream.handleSubscribe(ws, { type: "activity_subscribe", view: "session", sessionId: "ithaca" }, "odysseus"); + expect(frames).toHaveLength(1); + expect(store.writeClientReceipt!("turn-ithaca", "odysseus", pairs)).toBe(true); + stream.pump(); + stream.handleSubscribe(ws, { type: "activity_subscribe", view: "session", sessionId: "ithaca" }, "odysseus"); + const delta = frames.find(frame => frame.type === "activity_delta"); + const snapshot = frames.at(-1)!; + expect(delta).toMatchObject({ lifecycle: { clientTiming: pairs } }); + expect(snapshot).toMatchObject({ type: "activity_snapshot", lifecycles: [{ clientTiming: pairs }] }); + expect(previousActivityFrameSchema.safeParse(delta)).toMatchObject({ success: true, data: delta }); + expect(previousActivityFrameSchema.safeParse(snapshot)).toMatchObject({ success: true, data: snapshot }); + // Negative control: the pinned old validator really retains its closed + // phase enum. A new enum value would make this compatibility test red. + const record = store.lifecycle("turn-ithaca")!; + expect(record.subPhases).toHaveLength(1); + expect(previousActivityFrameSchema.safeParse({ ...snapshot, lifecycles: [{ ...record, + subPhases: [{ ...record.subPhases![0], phase: "terminal" }], + }] }).success).toBe(false); + } finally { stream.close(); db.close(); } +}); diff --git a/packages/ui-server/tests/client-turn-stream-race.test.ts b/packages/ui-server/tests/client-turn-stream-race.test.ts new file mode 100644 index 0000000000..df168276dc --- /dev/null +++ b/packages/ui-server/tests/client-turn-stream-race.test.ts @@ -0,0 +1,122 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; +import { createUiDb } from "../src/db/client.js"; +import { createActivityStore } from "../src/activity/store.js"; +import { createActivityStream } from "../src/activity/stream.js"; +import { createTurnLifecycle } from "../src/activity/turn-lifecycle.js"; + +for (const legacy of [false, true]) for (const view of ["index", "session", "run"] as const) { + test(`${view} lifecycle snapshot cannot hide a racing receipt delta${legacy ? " on a prior store" : ""}`, () => { + const folder = mkdtempSync(join(tmpdir(), "brain-client-receipt-")); + const db = createUiDb(join(folder, "ui.db")), foreign = createUiDb(join(folder, "ui.db")); + const store = createActivityStore(db), writer = createActivityStore(foreign); + if (legacy) Object.defineProperty(store, "snapshotLifecycles", { value: undefined }); + const lifecycle = createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1100, "odysseus"); + lifecycle.finish("success"); + const stream = createActivityStream(store); + const query = db.query.bind(db), own = Object.getOwnPropertyDescriptor(db, "query"); + let raced = false; + const timing = { sendToFirstHostFrameMs: 7 }; + Object.defineProperty(db, "query", { configurable: true, value: ((sql: string, ...args: unknown[]) => { + const statement = Reflect.apply(query, db, [sql, ...args]); + if (!sql.includes("CAST(substr(CAST(receipt AS BLOB)")) return statement; + return new Proxy(statement, { get(target, property) { + if (property === "get") return (...bindings: unknown[]) => { + const row = Reflect.apply(target.get, target, bindings); + if (!raced) { raced = true; expect(writer.writeClientReceipt!("turn-ithaca", "odysseus", timing)).toBe(true); } + return row; + }; + const value = Reflect.get(target, property); + return typeof value === "function" ? value.bind(target) : value; + } }); + }) as typeof db.query }); + try { + const frames: ServerMessage[] = []; + const ws = { send: (text: string) => frames.push(JSON.parse(text)) }; + stream.handleSubscribe(ws, { type: "activity_subscribe", view, + ...(view === "session" ? { sessionId: "ithaca" } : view === "run" ? { runId: "turn-ithaca" } : {}) }, "odysseus"); + stream.pump(); + expect(raced).toBe(true); + const snapshot = frames.find(frame => frame.type === "activity_snapshot")!; + const delta = frames.find(frame => frame.type === "activity_delta" && frame.lifecycle?.turnId === "turn-ithaca")!; + expect(snapshot.type).toBe("activity_snapshot"); + expect(delta.type).toBe("activity_delta"); + if (snapshot.type !== "activity_snapshot" || delta.type !== "activity_delta") throw new Error("Missing Activity frames"); + const atSnapshot = snapshot.lifecycles?.find(record => record.turnId === "turn-ithaca")?.clientTiming; + // This is the shipped client's sequence rule: a delta at or below the + // snapshot watermark is discarded. The receipt must be visible in one. + const visible = atSnapshot ?? (delta.seq > (snapshot.highWaterSeq[delta.runId] ?? 0) ? delta.lifecycle?.clientTiming : undefined); + expect(visible).toEqual(timing); + if (!atSnapshot) expect(delta.seq).toBeGreaterThan(snapshot.highWaterSeq[delta.runId]!); + } finally { + if (own) Object.defineProperty(db, "query", own); else Reflect.deleteProperty(db, "query"); + stream.close(); foreign.close(); db.close(); rmSync(folder, { recursive: true, force: true }); + } + }); +} + +test("index span data cannot acquire a sequence that already includes a later patch", () => { + const folder = mkdtempSync(join(tmpdir(), "brain-client-receipt-")); + const db = createUiDb(join(folder, "ui.db")), foreign = createUiDb(join(folder, "ui.db")); + const store = createActivityStore(db), writer = createActivityStore(foreign); + store.startSpan({ spanId: "ithaca-root", runId: "turn-ithaca", kind: "turn", origin: "session", name: "invoke_agent", startedAt: 1000 }); + const stream = createActivityStream(store); + const read = store.openRootSpans.bind(store); + let raced = false; + store.openRootSpans = () => { + const roots = read(); + if (!raced) { raced = true; expect(writer.patchSpan("ithaca-root", { attrs: { voyage: "sailing" } })).toBe(true); } + return roots; + }; + try { + const frames: ServerMessage[] = []; + const ws = { send: (text: string) => frames.push(JSON.parse(text)) }; + stream.handleSubscribe(ws, { type: "activity_subscribe", view: "index" }, "odysseus"); stream.pump(); + const snapshot = frames.find(frame => frame.type === "activity_snapshot")!; + const delta = frames.find(frame => frame.type === "activity_delta")!; + if (snapshot.type !== "activity_snapshot" || delta.type !== "activity_delta") throw new Error("Missing Activity frames"); + const visible = snapshot.spans[0]?.attrs?.voyage ?? (delta.seq > (snapshot.highWaterSeq[delta.runId] ?? 0) ? delta.span?.attrs?.voyage : undefined); + expect(visible).toBe("sailing"); + } finally { stream.close(); foreign.close(); db.close(); rmSync(folder, { recursive: true, force: true }); } +}); + +for (const list of [false, true]) { + test(`${list ? "list" : "single"} lifecycle joins do not combine an unfinished host record with a later receipt`, () => { + const folder = mkdtempSync(join(tmpdir(), "brain-client-receipt-")); + const db = createUiDb(join(folder, "ui.db")), foreign = createUiDb(join(folder, "ui.db")); + const store = createActivityStore(db), writer = createActivityStore(foreign); + createTurnLifecycle(store, "turn-ithaca", "ithaca", 1000, () => {}, () => 1000, "odysseus"); + const query = db.query.bind(db), own = Object.getOwnPropertyDescriptor(db, "query"); + let raced = false; + Object.defineProperty(db, "query", { configurable: true, value: ((sql: string, ...args: unknown[]) => { + const statement = Reflect.apply(query, db, [sql, ...args]); + if (!sql.startsWith("SELECT record FROM activity_turn_lifecycles")) return statement; + return new Proxy(statement, { get(target, property) { + if (property === "get" || property === "all") return (...bindings: unknown[]) => { + const rows = Reflect.apply(target[property], target, bindings); + if (!raced) { + raced = true; + writer.writeLifecycle({ ...writer.lifecycle("turn-ithaca")!, endedAt: 1100, outcome: "success" }, "odysseus"); + expect(writer.writeClientReceipt!("turn-ithaca", "odysseus", { sendToFirstHostFrameMs: 7 })).toBe(true); + } + return rows; + }; + const value = Reflect.get(target, property); + return typeof value === "function" ? value.bind(target) : value; + } }); + }) as typeof db.query }); + try { + const record = list ? store.lifecycles()[0]! : store.lifecycle("turn-ithaca")!; + expect(raced).toBe(true); + expect(record.endedAt).toBeNull(); + expect(record.clientTiming).toBeUndefined(); + expect(writer.lifecycle("turn-ithaca")?.clientTiming).toEqual({ sendToFirstHostFrameMs: 7 }); + } finally { + if (own) Object.defineProperty(db, "query", own); else Reflect.deleteProperty(db, "query"); + foreign.close(); db.close(); rmSync(folder, { recursive: true, force: true }); + } + }); +} diff --git a/packages/ui-server/tests/fixtures/client-turn-writer-probe.ts b/packages/ui-server/tests/fixtures/client-turn-writer-probe.ts new file mode 100644 index 0000000000..d120effbcb --- /dev/null +++ b/packages/ui-server/tests/fixtures/client-turn-writer-probe.ts @@ -0,0 +1,17 @@ +import type { Database } from "bun:sqlite"; +export const url = import.meta.url; +export function setup(db: Database) { + db.exec("CREATE TABLE IF NOT EXISTS ithaca_receipt_barrier (value INTEGER)"); + return { + // An unrelated write: idle and read snapshots must finish before release. + hold(gate: Int32Array, watchdogMs: number) { + try { + db.transaction(() => { + db.query("INSERT INTO ithaca_receipt_barrier VALUES (1)").run(); + Atomics.store(gate, 0, 1); Atomics.notify(gate, 0); + Atomics.wait(gate, 1, 0, watchdogMs); + }).immediate(); + } finally { Atomics.store(gate, 2, 1); Atomics.notify(gate, 2); } + }, + }; +} diff --git a/packages/ui-server/tests/fixtures/previous-client-turn-schema.ts b/packages/ui-server/tests/fixtures/previous-client-turn-schema.ts new file mode 100644 index 0000000000..316cb3ed75 --- /dev/null +++ b/packages/ui-server/tests/fixtures/previous-client-turn-schema.ts @@ -0,0 +1,102 @@ +/** Frozen pre-receipt Activity schemas from commit 134c0eee9, schemas.ts. + * Only TypeScript `satisfies` annotations were removed; runtime validators, + * including every closed enum and required field, are copied verbatim. */ +import { z } from "zod"; +const MAX_ID_CHARS = 256; +const id = z.string().min(1).max(MAX_ID_CHARS); +const activityView = z.enum(["index", "session", "run"]); +const modelUsageSchema = z.looseObject({ + inputTokens: z.number().optional(), + outputTokens: z.number().optional(), + cacheReadTokens: z.number().optional(), + cacheCreationTokens: z.number().optional(), + costUsd: z.number().optional(), +}); + +const activitySpanSchema = z.looseObject({ + spanId: id, + runId: id, + parentSpanId: id.optional(), + name: z.string(), + toolName: z.string().optional(), + kind: z.enum(["turn", "tool", "subagent", "cron"]), + origin: z.enum(["session", "cron", "autonomous", "compute"]), + sessionId: id.optional(), + jobName: z.string().optional(), + principalId: id.optional(), + startedAt: z.number(), + waitUntil: z.number().optional(), + endedAt: z.number().optional(), + outcome: z.enum(["success", "error", "timeout", "cancelled", "denied", "interrupted"]).optional(), + outcomeReason: z.string().optional(), + usage: modelUsageSchema.extend({ model: z.string().optional() }).optional(), + subagent: z + .looseObject({ + type: z.string().optional(), + description: z.string().optional(), + summary: z.string().optional(), + totalTokens: z.number().optional(), + }) + .optional(), + attrs: z.record(z.string(), z.unknown()).optional(), +}); + +const activitySpanEventSchema = z.looseObject({ + spanId: id, + eventIndex: z.number(), + ts: z.number(), + eventType: z.string(), + payload: z.unknown().optional(), + truncated: z.boolean().optional(), +}); + +const activityTurnLifecycleSchema = z.looseObject({ + hostEvents: z.array(z.looseObject({principalId: id, kind: z.enum(["turn_cancelled", "ask_user_cancelled", "principal_revoked", "follow_up"]), observedAt: z.number()})), + skippedPhases: z.array(z.enum(["governed", "budget", "journal"])), + lifecycleId: id, turnId: id, sessionId: id.nullable(), backendRunId: id.nullable(), + acceptedAt: z.number(), + dequeuedAt: z.number().nullable(), + governedStartedAt: z.number().nullable(), + governedAcquiredAt: z.number().nullable(), + budgetStartedAt: z.number().nullable(), + budgetAdmittedAt: z.number().nullable(), + journalStartedAt: z.number().nullable(), + journalBeganAt: z.number().nullable(), + backendInvokedAt: z.number().nullable(), + firstFrameAt: z.number().nullable(), + failureObservedAt: z.number().nullable(), + endedAt: z.number().nullable(), + totalElapsedMs: z.number().nullable(), + timeToFirstFrameMs: z.number().nullable(), + queueWaitMs: z.number().nullable(), + governedAdmissionMs: z.number().nullable(), + budgetAdmissionMs: z.number().nullable(), + journalBeginMs: z.number().nullable(), + backendStartupMs: z.number().nullable(), + subPhases: z.array(z.looseObject({ phase: z.enum(["governed", "journal"]), name: z.string(), startedAt: z.number(), + endedAt: z.number().nullable(), elapsedMs: z.number().nullable() })).optional(), + outcome: z.enum(["success", "error", "timeout", "cancelled", "denied", "interrupted"]).nullable(), reason: z.string().nullable(), +}); + +const serverActivitySnapshotSchema = z.looseObject({ + type: z.literal("activity_snapshot"), + lifecycles: z.array(activityTurnLifecycleSchema).optional(), + view: activityView, + sessionId: id.optional(), + runId: id.optional(), + spans: z.array(activitySpanSchema), + events: z.array(activitySpanEventSchema), + highWaterSeq: z.record(z.string(), z.number()), + append: z.boolean().optional(), +}); + +const serverActivityDeltaSchema = z.looseObject({ + type: z.literal("activity_delta"), + lifecycle: activityTurnLifecycleSchema.optional(), + runId: id, + seq: z.number(), + span: activitySpanSchema.optional(), + event: activitySpanEventSchema.optional(), +}); + +export const previousActivityFrameSchema = z.discriminatedUnion("type", [serverActivitySnapshotSchema, serverActivityDeltaSchema]); From c8eae01b8b58c77d39380beb93b3f708557eb344 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 06:33:03 +0100 Subject: [PATCH 04/18] CONTRACT: feat(ui-server): inspect workspaces read-only by default (#4317) * CONTRACT: feat(ui-server): inspect workspaces read-only unless a session enables code changes * CONTRACT: fix(ui-server): enforce workspace ownership and isolation * CONTRACT: fix(ui-sdk): preserve governed writes and skip sealed workspace traversal * CONTRACT: fix(ui-sdk): close workspace attribution and admission gaps * CONTRACT: fix(ui-server): preserve inspection across host and tool paths * CONTRACT: fix(ui-server): enforce workspace boundaries across read aliases and per-turn policy * CONTRACT: fix(ui-sdk): mask staged areas and give conditional workspace remedies * CONTRACT: fix(ui-sdk): separate native request and control response bounds --- .changeset/quiet-workspace-inspection.md | 25 +++ api-report/common.txt | 2 + api-report/ui-sdk.txt | 2 + api-report/ui-server.txt | 5 + docs/decisions/governed-writable-workers.md | 74 +++++-- docs/decisions/reference-worktrees.md | 25 ++- docs/decisions/worker-writable-areas.md | 105 ++++++++- docs/hosting/agent-workers.md | 33 +-- docs/http-api-coverage.md | 4 + docs/http-api.md | 14 ++ docs/integration-contract/http.md | 61 ++++++ docs/integration-contract/package-api.md | 15 ++ docs/supported-inputs.md | 2 +- packages/common/src/worker-areas.ts | 5 + .../ui-backend-claude/src/permission-hooks.ts | 16 +- packages/ui-backend-claude/src/sdk-options.ts | 11 +- .../src/tool-availability.ts | 2 +- .../tests/fixtures/provider-history-probe.ts | 4 +- .../tests/helpers/sdk-options-snapshot.ts | 23 +- .../tests/permission-wiring-units.test.ts | 29 +++ .../tests/provider-history.test.ts | 16 ++ .../tests/sdk-options-snapshot.test.ts | 46 +++- packages/ui-backend-pi/src/tool-safety.ts | 10 +- packages/ui-backend-pi/src/worker-entry.ts | 5 +- packages/ui-backend-pi/src/worker-launch.ts | 4 +- packages/ui-backend-pi/src/worker-protocol.ts | 4 +- packages/ui-backend-pi/src/worker-rpc.ts | 16 +- packages/ui-backend-pi/src/worker-session.ts | 2 +- .../tests/fixtures/provider-history-probe.ts | 4 +- .../tests/provider-history.test.ts | 16 ++ .../ui-backend-pi/tests/worker-rpc.test.ts | 47 +++- .../tests/worker-session.test.ts | 27 ++- packages/ui-sdk/src/internal.ts | 4 +- .../server/native-brain-manager-protocol.ts | 22 +- .../ui-sdk/src/server/native-brain-manager.ts | 23 +- .../src/server/native-checkpoint-reader.ts | 17 +- packages/ui-sdk/src/server/worker-launcher.ts | 122 +++++++++-- .../ui-sdk/src/server/worker-protection.ts | 29 ++- packages/ui-sdk/src/server/worker-sandbox.ts | 43 ++-- .../ui-sdk/src/server/workspace-refusal.ts | 12 + .../ui-sdk/tests/native-brain-manager.test.ts | 43 +++- .../native-checkpoint-path-bounds.test.ts | 11 + .../ui-sdk/tests/native-worker-view.test.ts | 2 +- .../ui-sdk/tests/worker-data-tree.test.ts | 37 +++- .../ui-sdk/tests/worker-output-budget.test.ts | 2 +- packages/ui-sdk/tests/worker-sandbox.test.ts | 207 +++++++++++++++--- .../ui-sdk/tests/worker-startup-view.test.ts | 8 +- .../ui-sdk/tests/workspace-refusal.test.ts | 21 ++ .../migrations/095_session_code_changes.sql | 3 + packages/ui-server/src/brain/application.ts | 8 + packages/ui-server/src/brain/governed-turn.ts | 9 +- packages/ui-server/src/brain/host-boundary.ts | 32 ++- packages/ui-server/src/brain/journal-store.ts | 4 +- .../ui-server/src/brain/markup-application.ts | 8 +- .../ui-server/src/brain/mask-application.ts | 8 +- .../src/brain/native-journal-capture.ts | 90 ++++---- .../src/brain/native-journal-observer.ts | 121 +++++++--- .../src/brain/native-journal-policy.ts | 17 +- .../ui-server/src/brain/protected-target.ts | 8 +- .../ui-server/src/brain/turn-data-tree.ts | 5 + packages/ui-server/src/brain/turn-journal.ts | 33 +-- packages/ui-server/src/inbox/bridge-tools.ts | 3 +- packages/ui-server/src/inbox/intake.ts | 4 +- .../ui-server/src/routes/session-profiles.ts | 9 +- .../src/ws/bridge-capabilities/activity.ts | 4 +- .../src/ws/bridge-capabilities/application.ts | 4 +- .../src/ws/bridge-capabilities/context.ts | 2 + .../ws/bridge-capabilities/location-mask.ts | 3 +- .../src/ws/bridge-capabilities/markup.ts | 3 +- packages/ui-server/src/ws/bridge.ts | 7 +- packages/ui-server/src/ws/chat-lifecycle.ts | 6 +- .../src/ws/session-profile-writes.ts | 35 ++- packages/ui-server/src/ws/session-profiles.ts | 40 +++- .../ui-server/src/ws/session-run/admission.ts | 5 +- .../src/ws/session-run/backend-entry.ts | 1 + .../tests/app-writes-offloop.test.ts | 4 + .../ui-server/tests/brain-application.test.ts | 16 ++ .../tests/brain-markup-application.test.ts | 25 ++- .../tests/brain-mask-application.test.ts | 25 ++- .../ui-server/tests/governance-policy.test.ts | 206 ++++++++++++++++- .../tests/helpers/http-mount-lifetimes.ts | 4 + .../tests/helpers/native-journal-fixture.ts | 11 +- .../ui-server/tests/helpers/scope-fixture.ts | 4 +- .../tests/http-supported-mounts.test.ts | 8 +- .../tests/journal-index-metadata-only.test.ts | 2 +- .../tests/journal-kept-files.test.ts | 2 +- .../ui-server/tests/journal-snapshot.test.ts | 9 +- .../tests/native-journal-fixture.test.ts | 144 +++++++++++- .../tests/native-journal-observer.test.ts | 47 +++- .../tests/native-journal-policy.test.ts | 19 ++ .../tests/protected-host-writers.test.ts | 8 + .../tests/reference-worktree-journal.test.ts | 2 +- .../ui-server/tests/turn-data-tree.test.ts | 47 ++++ packages/ui-server/tests/turn-journal.test.ts | 133 ++++++++++- .../tests/worker-host-status.test.ts | 56 ++++- tests/fixtures/policy-boundary-probe.ts | 3 + 96 files changed, 2140 insertions(+), 364 deletions(-) create mode 100644 .changeset/quiet-workspace-inspection.md create mode 100644 packages/ui-sdk/src/server/workspace-refusal.ts create mode 100644 packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts create mode 100644 packages/ui-sdk/tests/workspace-refusal.test.ts create mode 100644 packages/ui-server/migrations/095_session_code_changes.sql diff --git a/.changeset/quiet-workspace-inspection.md b/.changeset/quiet-workspace-inspection.md new file mode 100644 index 0000000000..81bb3a16b9 --- /dev/null +++ b/.changeset/quiet-workspace-inspection.md @@ -0,0 +1,25 @@ +--- +"@schlessera/brain-common": minor +"@schlessera/brain-backend-claude": minor +"@schlessera/brain-backend-pi": minor +"@schlessera/brain-ui-sdk": minor +"@schlessera/brain-ui-server": minor +--- + +Restrict workspace access in default governed and strict turns to read-only inspection. These turns no longer scan writable workspace aliases, read checkout ignore policy, retain workspace change rows or charge workspace bytes. Existing retained history remains readable. + +Add an authenticated per-session (and draft) code-changes preference API. Enabling it takes effect at the next admission and preserves the previous writable mounts, alias scan and per-file journal. The worker learns its mode through append-only turn context; read-only guidance names the session switch and managed worktree alternatives for edits, installs and builds. + +Keep governed note writes live when the optional workspace is absent, retaining and charging newly created content until the next default admission seals it. Skip mounted checkout metadata traversal in inspection turns, preserve handoff prompts through actual preparation, and return actionable install refusals without denying checkout reads. + +Preserve ordinary note history when Btrfs reports an update through an inspected hard-link alias. Keep unbound interactive backends read-only, qualify workspace existence before protected-parent preparation, and omit inspected checkouts from strict/private-index data copies. Preserve ordinary ignore rules for absent areas, honour policy in status, keep inspection commits independent of brain size, cancel writer inventories with admission, and preserve read-only package verification. + + +Keep overlapping turns’ retained versions separate, and charge retained checkpoints independently of journal exclusions. Restore strict Pi repo-relative checkout reads through a sealed source overlay with provider masks. Preserve explicit owner symlink protections and guard privileged application routes even without governed admission. Keep both backends’ handoff prompts stable using the resolved sandbox, append workspace remedies only after filesystem permission failures, and make status protection inspection read-only. + + +Reapply secret symlink-target masks to strict checkout read aliases, qualify the actual checkpoint source and preserve scratch-cleanup ordering for writable scans. Keep steering classification and ordinary journal scope per turn, including retained predecessors across excluded directory renames. Align private metadata transport and fixed-reader request bounds for escaped long paths. Distinguish markup source reads from destination writes, explain failed mask writes, give read-only failures a fixed conditional workspace remedy without attributing their path, and recognize Pi bash exit codes. Preserve historically refused handoff notes and report unresolved status type qualification without guessing or writing live paths. + +Repeat provider folder masks on all staged writable area aliases, preserving secret-mask dominance and unmasked writes. Use the same conditional remedy for read-only bash/file/host failures, including mkdir and Git diagnostics and writes outside the checkout; no command or path parser denies execution. + +Keep native control replies, intent files and stage rows at their existing 64 KiB limit independently of the larger escaped-path request bound. Large worktree growth replies again omit unflagged details while preserving their flags. diff --git a/api-report/common.txt b/api-report/common.txt index 2bab8b012d..46e9843cd2 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -272,6 +272,8 @@ export "./internal/worker-areas" (./src/worker-areas.ts) READ_ONLY_BRAIN_RULE TURN_TEMP_PLACES TURN_TEMP_RULE + WORKSPACES_READ_ONLY_REASON + WORKSPACES_WRITE_REFUSAL brainWorkerPath linkRule turnTempRule diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index bd100653cf..15321f03e3 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1586,6 +1586,7 @@ export "./internal" (./src/internal.ts) resolveWebSearchConfigPath resolveWorkerProtection resolveWorkerStateLimits + resolveWorkspacesMount restrictedReadPaths retainWorkerStartupView rewriteWorkerRtk @@ -1621,6 +1622,7 @@ export "./internal" (./src/internal.ts) workerProviderCredentials workerSandboxNote workerSandboxWarnings + workspaceWriteRefusal export "./internal/client" (./src/internal-client.ts) type FrontmatterBlock diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index a8170b2c7e..f7e9cf331f 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1394,6 +1394,7 @@ signatures (every public export and the types it is made of) } GovernedTurnRoute (packages/ui-server/src/brain/governed-turn.ts) export interface GovernedTurnRoute { + readonly codeChanges?: boolean; readonly inferenceOrigin?: string; readonly sessionId?: string; readonly inherit?: readonly string[]; @@ -2382,6 +2383,7 @@ signatures (every public export and the types it is made of) writable: false; reason: string; missing?: true; + readOnlyPath?: string; }; WorkerOutwardRule (packages/ui-sdk/src/server/outward-policy.ts) export interface WorkerOutwardRule { @@ -2406,6 +2408,7 @@ signatures (every public export and the types it is made of) }; readonly commandPolicy?: import("./command-policy.js").WorkerCommandPolicy; readonly brain: string; + readonly codeChanges?: boolean; readonly restricted: boolean; readonly profile?: WorkerProfile; readonly fallbackReason?: string; @@ -2645,6 +2648,8 @@ signatures (every public export and the types it is made of) policyHash: null | string; profile: "governed" | "strict"; sessionId: null | string; + workspaceMissing?: boolean; + workspaceReadOnly?: boolean; }, stop: (error: Error) => void, signal?: AbortSignal, timing?: PhaseTimer): Promise; bindModel(turnId: string, sessionId: null | string, model: string): boolean; bindSession(turnId: string, sessionId: string): Promise; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 1cd1159c9d..fba76f80ab 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -207,7 +207,7 @@ server and a read-only `brain policy check --json` command share it. **Why that location:** - `context/policies/` is already denied to the application route - (`if (folded[0] === "context"`, `packages/ui-server/src/brain/application.ts:42`). + (`if (folded[0] === "context"`, `packages/ui-server/src/brain/application.ts:44`). - R34 already placed policy there. - Scheduled-task definitions set the precedent of host-parsed Markdown under `context/`. @@ -690,7 +690,7 @@ lists the keys each first-party command reads. The launcher withholds every provider credential in the subprocess descriptor from a governed or strict turn worker, except what its backend declares for its own inference and what an operator admits (`const turnProfile`, -`packages/ui-sdk/src/server/worker-launcher.ts:708-718`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:733-743`). A relayed turn keeps no key. An unrelayed one keeps only its runtime's own inference credential, under the 2026-10-22 ruling that hosts without managed native storage keep today's inference credentials; pi resolves its own credentials there, so it keeps all @@ -1179,7 +1179,7 @@ worker's command starts, the server opens that tmpfs from outside through the sandbox's `/proc//root`. It waits until the path is a tmpfs of exactly the allowance on another device than the server's own `/tmp`, and keeps the descriptor -(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1175-1203`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1226-1254`). Every later read goes through that descriptor, after the worker's namespace is gone as well, and never enters another mount, so runtime state below `/tmp` is never read as turn temp. The allowance (256 MiB by default, @@ -1364,6 +1364,44 @@ Ignored, incomplete, Git metadata and unsupported entries are named exclusions; missing or changed parents conflict. No unobserved empty-directory metadata is invented. +**2026-11-20 workspace amendment (#4295).** Default governed and strict +turns bind `workspaces/` read-only after the existing root, symlink and mount +checks, without the writable-alias walk. A per-session code-changes switch is +stored with operational session preferences and frozen before admission's +first await. It survives resume; a save affects only the next turn. Enabled +sessions retain the existing writable alias scan and per-file journaling. + +Default turns exclude workspace paths from capture, retained rows, ignore +policy and observed-byte charges. Shared observations apply that exclusion +per turn: an overlapping opted-in writer keeps workspace versions and their +byte charges; notes keep their existing before-images, durability and caps. +This narrows the older coverage statements below; retained old history stays +readable. The mode and refusal alternatives reach the worker only in the new +turn's tail when first applicable or changed, preserving earlier provider +history. An absent optional workspace keeps the governed writable brain, +without a workspace overlay or live mountpoint. Creation beneath that absent +name remains ordinary retained and charged content for the whole turn; the +next default admission seals it. Exclusion requires a qualified read-only +workspace mount. Metadata readers omit checkout inventories; bounded delta inode probes recover +ordinary hard-link aliases before workspace exclusion. Strict and private-index +data copies leave a qualified inspection workspace on its sealed source. Workspace sealing precedes protected child masks, and its +ancestor pins remain read-only, preserving quarantine and provider masks. +Host applications keep workspace protection until a writable mount qualifies, +even when the saved switch requests one. Inspect participants do not change a +writer's frozen ignores or participate in workspace conflict attribution. +Installing or building requires the switch or a managed worktree +([the install ruling](reference-worktrees.md)). + + +Workspace inspection keeps source-read and destination-write authority separate. +Strict data roots overlay only a qualified sealed source and reapply every secret +and provider mask; the copied data tree's exclusions cannot be restored through +that alias. Status qualifies literal provider folder pins without creating paths. +If type folder translation still requires checkpoint configuration, its optional +profile and configuration-view fields remain unknown with an explanatory fallback. +Each turn keeps its own ignore-based steering classification and journal scope, +including ordinary root scope for content created beneath an absent workspace. + **Snapshots.** At turn start and at turn end, the server snapshots the brain's working tree itself. It runs no git and imports no repository code: @@ -1700,8 +1738,10 @@ observation's facts. `files_changed` counts only changed paths outside `workspaces/`, by path containment rather than a string prefix, so `workspaces-old/` still counts. A reference clone fetched or checked out there touches hundreds of files without changing the brain, and that alone paused -interactive turns. `turn_bytes` and the free-space floor still count every -workspace write, and the journal summary still reports every changed path +interactive turns. `turn_bytes` still counts workspace writes for opted-in change turns; +default inspection turns have no workspace rows or byte charges. The +free-space floor remains filesystem-wide. The journal summary reports the +paths covered by that turn (#3793). A proven read changes nothing, so it cannot cross a limit. A writer's result is still observed, so its own crossing is detected there. After an unproven call every result is observed, so a limit that a background @@ -1759,7 +1799,7 @@ worker does: - **Only interactive turns are journaled, and they load project configuration.** Evidence is wired only into the session-run turn request for a governed turn with a journal (`export function turnRequest`, - `packages/ui-server/src/ws/session-run/backend-entry.ts:218-233`). That turn + `packages/ui-server/src/ws/session-run/backend-entry.ts:219-234`). That turn is never a restricted autonomous one. It runs with `settingSources: ["project"]` and without `strictMcpConfig` (`const sdkOptions: Options`, `packages/ui-backend-claude/src/sdk-options.ts:406-422`). @@ -2621,7 +2661,7 @@ a filesystem socket that is visible through the read-only host root: a Docker socket, a session bus, an SSH agent or a host proxy. Each of those is an unrecorded way out, and some reach privileged host effects. The launcher already masks `.git` in restricted workers for exactly this reason -(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:252`). +(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:266`). `governed` and `strict` workers therefore mask the host's runtime and state directories with empty read-only tmpfs mounts. Maintenance workers share the @@ -2639,7 +2679,7 @@ The worker's private `/tmp` and the other host masks remain in place. After the masks, the launcher re-binds only the explicit runtime inputs the worker needs, read-only, with the same resolution the restricted envelope uses -(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1972`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:2023`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2663,7 +2703,7 @@ such ancestor with empty tmpfs instead; it never binds that ancestor's real contents. Search permission uses the helper's primary shared group class when that group owns the directory, including when only the other class has execute permission. Existing canonical aliases and nested masks fold into that cover -(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:411-470`). +(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:429-488`). This supports disjoint private-state layouts, including a nested operational database below a server-owned `0700` parent. New ancestor coverage that would @@ -2739,9 +2779,9 @@ and subdirectories through retained aliases. It does not restore unrelated host-temp siblings or make runtime bytes writable. The concrete checks and mounts are in (`validateRuntimePlacement`, -`packages/ui-sdk/src/server/worker-launcher.ts:637-643`), -(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:664-703`) -and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:665-683`). +`packages/ui-sdk/src/server/worker-launcher.ts:667-673`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:702-741`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:703-721`). Alias restoration recognizes names already supplied by a read-only bind or an explicit system-view symlink. It does not mount a canonical executable over an existing alias such as `/bin/sh`; missing owned temporary paths still receive @@ -3773,7 +3813,7 @@ before mounting them: both belong to the server, helper mode uses its primary GID and exact `0750`/`0660` modes, and no-helper mode retains exact `0700`/`0600`. Missing endpoints, aliases, non-sockets, foreign ownership and wider modes refuse before payload execution -(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:276-310`). +(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:290-324`). This compatibility check does not change default autonomous admission or add another route. @@ -3911,11 +3951,11 @@ An ordinary group-shared directory was accessible, but the worker's private mount and namespace links through `/proc/` were denied. Changing the private directory to `0770` did not remove that process-access barrier. The current launcher opens mounts directly (`function openPrivateState`, -`packages/ui-sdk/src/server/worker-launcher.ts:1138-1166`; +`packages/ui-sdk/src/server/worker-launcher.ts:1189-1217`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1175-1201`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1226-1252`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1364-1452`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1415-1503`). Group modes and a uid switch alone therefore cannot implement the selected cross-uid lifecycle. **Authority and launch.** One trusted external supervisor owns each worker @@ -4923,7 +4963,7 @@ and the enforcement cannot drift. The delivered host note (#1654) receives history availability through the existing resolved sandbox. The shared renderer is -(`workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:592-657`). +(`workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:625-690`). Journaling is stated as active only after this turn's real observation window is admitted; user restoration additionally requires the concrete mounted history service and a non-voice turn. Missing diff --git a/docs/decisions/reference-worktrees.md b/docs/decisions/reference-worktrees.md index 4bc99287cf..35cd9a6b02 100644 --- a/docs/decisions/reference-worktrees.md +++ b/docs/decisions/reference-worktrees.md @@ -21,8 +21,29 @@ The [persistent-cache ruling](https://github.com/schlessera/brain-kit/issues/239 places application-managed reference source outside brain content, indexing, capture and sync. Ordinary readers share source rather than receiving a full copy per agent or step. Reference source is read-only to agents. This creates -no blanket `workspaces/` journal exemption and does not authorize changes to -user-owned custom skills or automatic cleanup of arbitrary workspace repos. +no exemption for writable workspaces. **Amended 2026-11-20 (#4295):** +read-only inspection turns exclude `workspaces/` from their journal, policy +freeze and observed-byte accounting; a concurrent opted-in writer retains its +coverage. This does not authorize changes to user-owned custom skills or +automatic cleanup of arbitrary workspace repos. + +**Install ruling, 2026-11-20 (#4298, Option A).** Inspecting source never +writes. A turn that needs to install or build asks for a managed worktree, or +for the session's code-changes switch. Under the approved Git receipt policy, +tracked changes and untracked files Git does not ignore are protected; ignored +install/build output is neither recorded nor restored because it can be +regenerated. The initial workspace opt-in retains per-file journaling until +that separate Git receipt transition. A default turn's read-only note names +both routes to writable checkout access. Commands run against the read-only +mount, so verification and dry runs that leave it unchanged remain usable. A +read-only failure in a turn with an inspected workspace receives a fixed +conditional remedy after execution; command names alone do not deny a call. +The result makes no path attribution and may advise an outside write too: + +> If this write was under workspaces/, the checkout is read-only in this turn: switch on code changes for this session (applies from the next message) or use a managed worktree. + +Reading a source image +for a scratch markup layer likewise requires no workspace write grant. ## Authority and credential isolation diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 7d338a913d..7ad88a675a 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -43,9 +43,11 @@ built and measured, and the alternatives they replaced. (`brain render --scratch`, `brain image --scratch`, `brain scratch prune`, a link for the reader) works unchanged. The per-turn `BRAIN_WORKER_SCRATCH` tmpfs stays as it is. -2. **Workspaces.** The index-excluded workspace directory is bound read-write - only when it exists, and never the brain root, an ancestor of it or - anything holding authoritative documents. +2. **Workspaces.** **Amended 2026-11-20 (#4295):** the index-excluded + workspace directory is read-only in default governed and strict turns. + A durable per-session code-changes switch, frozen at admission, opts in to + the previous writable mount and its alias scan. The directory must already + exist and cannot be the brain root, an ancestor or an authoritative area. 3. **A writable `$HOME` for the turn.** A per-turn `bwrap --tmp-overlay` over `$HOME`: existing configuration such as `.gitconfig` still reads, and every write is discarded when the turn ends. Where the overlay is unavailable, @@ -81,15 +83,15 @@ on the transcript persist path and is not part of this record. **One resolution, two consumers.** `prepareWorkerSandbox` resolves the areas and per-turn XDG layout once per worker -(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:935-976`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:1015-1082`). The backend passes the result both to the launcher, which turns it into bubblewrap arguments, and to `workerSandboxNote`, which renders the agent's -note (`export function workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:592-657`). +note (`export function workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:625-690`). The launcher re-checks the resolved layout against the actual launch: the same brain and envelope, each writable area still a real directory at its own path in the brain. The backend selects runtime HOME separately. A mismatch refuses the launch instead of binding something the note does not -describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:857-887`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:916-957`). A launch without a resolved layout keeps the 0.41 view: only the per-turn scratch is writable. @@ -101,13 +103,13 @@ brain, as core's `isGitRepo` counts it) it is bound only while git ignores it, as core's own scratch writes already require; otherwise a file written there by any tool could be committed. Git runs with the server's `HOME`, so the operator's `safe.directory` applies -(`export function resolveScratchMount`, `packages/ui-sdk/src/server/worker-sandbox.ts:437-456`). +(`export function resolveScratchMount`, `packages/ui-sdk/src/server/worker-sandbox.ts:468-487`). **Workspaces.** The directory is `workspaces/`, a fixed name. Core excludes it from the index in every brain: `exclude.dirs` adds to the defaults and cannot remove `workspaces`, so it never holds an indexed document. Its -existence is the opt-in: someone creates it outside a hosted turn, and every -later turn binds it (`export function resolveWorkspacesMount`, `packages/ui-sdk/src/server/worker-sandbox.ts:470-481`). +existence permits a mount; since the 2026-11-20 ruling, only a session +whose code-changes switch is on binds it writable at its next admission (`export function resolveWorkspacesMount`, `packages/ui-sdk/src/server/worker-sandbox.ts:502-513`). It needs no gitignore line, unlike scratch: the ruling's condition is the index exclusion, and committing a clone or a work file from `workspaces/` is the user's choice, as it was before 0.41, not something a turn's output @@ -117,12 +119,15 @@ lands in by default. creating a new hard link, rename or symlink write into the rest of the brain. It does not stop a link that already exists on the host: `git clone --local` of the brain into `workspaces/`, or a hand-made link, would make that brain -file writable through the mount. So each area is walked with `lstat` before +file writable through the mount. Since the 2026-11-20 ruling (#4295), a +qualified read-only workspace mount needs no writable-alias walk: reads cannot +change either name. Root, symlink and mount-topology checks remain. Scratch +and opted-in writable workspaces still run the existing `lstat` walk before the launch, counting the names each regular file's inode has inside the area. A file is offending only when its link count is higher than the names found inside: links wholly within the area (local clones between workspace repositories, package-manager stores) are harmless -(`export function scanForOutsideLinks`, `packages/ui-sdk/src/server/worker-sandbox.ts:291-301`). +(`export function scanForOutsideLinks`, `packages/ui-sdk/src/server/worker-sandbox.ts:295-305`). An offending scratch name is unlinked, because scratch is disposable and the other name keeps the data. An offending workspace file, or a walk over 200 000 entries, leaves `workspaces/` read-only for that turn, named in the note and @@ -153,7 +158,7 @@ through the roadblock path. This is a worker write boundary, not an immutable view: host-side changes to that directory remain visible. A backend may select a different runtime HOME as described below; it does not make the host home writable. `prepareWorkerSandbox` resolves this same XDG mode on every eligible host (`export function prepareWorkerSandbox`, -`packages/ui-sdk/src/server/worker-launcher.ts:935-976`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:1015-1082`). Host-backed overlay uppers cannot live on the worker's private tmpfs; keeping them would leave an unbounded write area. Tools reading XDG config see the per-turn directory, while direct reads of real HOME retain the read-only host view. @@ -398,6 +403,82 @@ directory it cannot search, and the server reads only the nested foreign owners and changed identities refuse. The bounds and the rationale are in the [governed-writable-workers record](governed-writable-workers.md), under "Server-owned strict output". +## Workspace inspection amendment, 2026-11-20 (#4295, #4298) + +Default governed and strict turns inspect an existing `workspaces/` read-only. They exclude +its paths from journal content capture, retained rows, ignore-policy reads and +observed-byte charges. The exclusion belongs to each turn, so a concurrent +session with code changes enabled keeps its own workspace retention and byte +accounting. Captured versions remain per turn through storage: an overlapping +writer cannot replace another turn’s ignored metadata with retained bytes. +Previously retained workspace history remains readable. Checkpoint-release +accounting is independent of journal coverage: excluded checkout predecessors +still count while a superseded checkpoint remains retained. + +**Absent optional area (clarified during #4295 review):** if `workspaces/` +is absent at launch, keep the ordinary governed writable brain. Create no +live mountpoint and install no workspace overlay. Exclusion is not in force +for that turn: anything it creates beneath `workspaces/` is ordinary brain +content, using root scope, ordinary Git-internal exclusions and the brain's +frozen root ignore rules, and journaled with retained +versions and charged bytes and paths. The +next default turn sees the directory and binds it read-only. The switch alone +permits a writable existing workspace. Journal exclusion keys the qualified +read-only workspace mount, never the path name or the saved preference alone. +The existing-directory qualification precedes protected-parent preparation, +including with the switch enabled: preparation cannot mint its own writable +workspace prerequisite. If absence changes before launch, retry admission rather than using a stale +mount/coverage plan. An explicitly protected missing ancestor still needs the +strict view when its protection cannot be enforced without creating content. + +Inspection metadata readers omit the mounted checkout from initial inventory +and subtree expansion. Delta paths receive bounded single-path inode probes +before exclusion, so an update reported through a workspace hard link cannot +hide a change to its ordinary note alias. These probes never inventory the +checkout. Shared observations include the +checkout only while a participant covers it; a new writer inventories its +baseline from the current sealed root with the admission cancellation signal. +Only a transition from writer coverage removes indexed checkout entries; +unchanged inspection commits never scan the whole brain index. A failed writer-only inventory leaves +an inspection turn usable. + +The authenticated code-changes preference survives resume and applies at the +next admission. Changing it cannot change a running worker's mounts. Enabling +it retains the existing alias scan and per-file journaling; the Git receipt +transition is separate work. The worker's sandbox note names the mode and both +ways to obtain writable checkout access: the session's code-changes switch or +a managed worktree. Arbitrary tools still return the kernel's read-only error; +failed tool results carrying `EROFS` or a read-only diagnostic receive the +fixed conditional sentence below whenever the turn has an inspected workspace. +There is no path, operand or shell-directory attribution; the sentence may also +appear for a failure outside the checkout. + +> If this write was under workspaces/, the checkout is read-only in this turn: switch on code changes for this session (applies from the next message) or use a managed worktree. + +Pi bash failures use the tool's actual nonzero exit-code details. +No package command is refused pre-emptively: verification and dry runs may +succeed without writes. The kernel enforces the mount. Inspecting source never writes, +including dependency installation and builds. This information travels once +in new-turn context when it first applies or changes, using the existing +append-only prompt context; tools, fixed system append and earlier messages +are never rewritten. Nonpersistent read-only handoffs retain legacy prompt +rendering from separately qualified historical facts, including a refused +alias or bounded-scan qualification, without preparing the sandbox twice or +granting writes. Async preparation resolves those legacy facts off the host +event loop. Writable qualification follows scratch alias cleanup. Strict data +trees omit checkout copies, qualify the actual sealed source and overlay it +at the repo-relative read path. Every read alias repeats secret targets and +provider masks; a second mount cannot restore anything excluded from the copy. +Strict staged writable area aliases repeat every overlapping provider folder +mask as well, including a provider mask covering the entire area. Explicit +owner protections keep both their configured names and symlink destinations; +the implicit inspection guard covers only its namespace. Status inspection +never prepares or creates paths on the live brain. It includes required literal +provider roots and leaves its optional profile/view fields unknown while type +folder qualification requires checkpoint taxonomy. Image markup may read an +inspected checkout source while publishing its layer under scratch; image mask +and markup restrictions apply to write destinations independently of source reads. + ## State boundaries and root dependencies — 2026-11-20 A filesystem boundary may replace an alias walk only when current evidence diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index b6f42ad3ab..39919db8ac 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -101,7 +101,7 @@ owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before the payload starts (`if (input.egress)`, -`packages/ui-sdk/src/server/worker-launcher.ts:580-595`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:599-614`). This does not select the ordinary inference route or enable the proxy by default. Native output stages use the existing manager's active stage identity. The @@ -420,7 +420,7 @@ write verified scratch/workspace copies through the aliases below. | Place | Paths | Lifetime | Link it for the reader? | | --- | --- | --- | --- | | Turn temp | `$BRAIN_WORKER_SCRATCH`, `/tmp` and the XDG directories in it | Deleted when the turn ends | Never: the reader cannot open it. A file the answer links there anyway is copied into `.brain/scratch/turns//` and a host-owned display mapping makes history show the promoted link; runtime transcript bytes stay unchanged. | -| Persistent scratch/workspaces | Governed: `.brain/scratch/` and `workspaces/`; strict: `/tmp/brain-worker-areas/scratch` and `/tmp/brain-worker-areas/workspaces` | Governed writes persist directly; strict writes persist after validated publication. Scratch is pruned after 7 days, oldest first past 1 GB | Yes: link the canonical brain destinations, not the strict aliases | +| Persistent scratch/workspaces | Governed: `.brain/scratch/` and `workspaces/`; strict: `/tmp/brain-worker-areas/scratch` and `/tmp/brain-worker-areas/workspaces` | Existing workspace writes require the session code-changes switch. Governed writes persist directly; strict writes persist after validated publication. Scratch is pruned after 7 days, oldest first past 1 GB | Yes: link the canonical brain destinations, not the strict aliases | | The brain | Everything else | Canonical | Yes, as documents | - **The brain** is writable under `governed`, except the resolved protected @@ -456,16 +456,22 @@ write verified scratch/workspace copies through the aliases below. and `brain scratch prune` work inside a turn, and the reader opens the path the command prints. The server never follows a symlink under `.brain/` when it serves, previews or lists a scratch path. -- **`workspaces/`** is made writable only when it already exists as a real - directory in the brain root. Core always excludes it from the index. - Creating it outside a hosted turn is the opt-in; the name is fixed. Governed - uses its canonical path; strict uses a private copy at - `/tmp/brain-worker-areas/workspaces` with validated publication after exit. It - stays read-only for a turn when it holds a file hard-linked to something - outside it, sits on or contains a mount point, holds more than 200 000 - entries, or holds a directory the server cannot read (scratch too); the - agent's note and the server log name the reason. Links wholly - inside it, such as local clones between workspace repositories, are fine. +- **`workspaces/`** is read-only in default governed and strict turns when present at admission. An absent optional area leaves governed note writes live, creates no mountpoint, and any content created beneath that name is retained and charged as ordinary content for that turn. The next default turn seals it. Core + always excludes it from the index. The host checks its root, symlinks and + mount topology but skips the writable-alias walk. Inspecting source does + not capture checkout content, read checkout ignore policy, retain workspace + change rows or charge workspace bytes to that turn. A write, install or + build needs the session's code-changes switch or a managed worktree; the + worker's note names both alternatives. The preference is per session, + survives resume and applies at the next admission, leaving a running + worker unchanged. When enabled, the existing real directory gets the + previous writable mount, alias scan, per-file journal and byte accounting: + governed uses its canonical path; strict uses a private copy at + `/tmp/brain-worker-areas/workspaces` with validated publication after exit. + Writable qualification still refuses outside hard links, mount points, + unreadable directories or more than 200 000 entries. Contained links are + allowed. An overlapping default turn never inherits that writer's workspace + rows or byte charge. - **The real host home** is not a writable host escape. The resolved profile may mask its contents; only the selected runtime inputs restored by that layout are available. A write into a read-only home fails and is retained as a roadblock. @@ -807,7 +813,8 @@ host timeout, resource limits and bounded storage still apply, including paused time; the picker and capabilities note state the actual enforced inputs. The shared raw journal observes each tool completion and every 15 seconds, -including brain, scratch and workspaces, and the monitor reads `statfs` at each +including brain and scratch, plus workspaces for sessions with code changes +enabled, and the monitor reads `statfs` at each observation. It freezes a running worker on a reached cap or below free space max(5% of filesystem capacity, 2 GiB). A delegated cgroup confirms its freezer; otherwise the parent verifies the worker PID namespace and stops its process diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index 919cddbd3b..600cb6d9b3 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -84,6 +84,8 @@ row's real mounting check. They do not establish mounting by themselves. | `GET /api/brain/stats/history` | `mounted supported handler: GET /api/brain/stats/history` | B | | `POST /api/brain/sync` | `mounted supported handler: POST /api/brain/sync` | B, Y | | `GET /api/drafts` | `mounted supported handler: GET /api/drafts` | X | +| `GET /api/drafts/:id/code-changes` | `mounted supported handler: GET /api/drafts/:id/code-changes` | S | +| `PUT /api/drafts/:id/code-changes` | `mounted supported handler: PUT /api/drafts/:id/code-changes` | S | | `GET /api/drafts/:id/profile` | `mounted supported handler: GET /api/drafts/:id/profile` | X | | `PUT /api/drafts/:id/profile` | `mounted supported handler: PUT /api/drafts/:id/profile` | X | | `GET /api/drafts/:draftId` | `mounted supported handler: GET /api/drafts/:draftId` | X | @@ -113,6 +115,8 @@ row's real mounting check. They do not establish mounting by themselves. | `POST /api/push/unsubscribe` | `mounted supported handler: POST /api/push/unsubscribe` | U | | `POST /api/render` | `mounted supported handler: POST /api/render` | E | | `GET /api/sessions` | `mounted supported handler: GET /api/sessions` | S | +| `GET /api/sessions/:id/code-changes` | `mounted supported handler: GET /api/sessions/:id/code-changes` | S | +| `PUT /api/sessions/:id/code-changes` | `mounted supported handler: PUT /api/sessions/:id/code-changes` | S | | `GET /api/sessions/:id/profile` | `mounted supported handler: GET /api/sessions/:id/profile` | S | | `PUT /api/sessions/:id/profile` | `mounted supported handler: PUT /api/sessions/:id/profile` | S | | `GET /api/sessions/:id` | `mounted supported handler: GET /api/sessions/:id` | S | diff --git a/docs/http-api.md b/docs/http-api.md index b538c1dca1..b71641f761 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -80,6 +80,8 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/brain/stats/history` | S | Read recorded corpus-stat series | Independent corpus clients; preserve CLI pass-through, capture recovery and sync lifetime promises. | | POST | `/api/brain/sync` | S | Stream a serialized repository sync | Independent corpus clients; preserve CLI pass-through, capture recovery and sync lifetime promises. | | GET | `/api/drafts` | S | List live session drafts | Paired composer and independent clients (#979, D52); preserve revisions, receipts, tombstones, limits and the no-execution boundary. | +| GET | `/api/drafts/:id/code-changes` | S | Read the durable next-admission workspace write preference | Authenticated session clients; defaults off, principal-scoped drafts (#4295). | +| PUT | `/api/drafts/:id/code-changes` | S | Save `{ enabled: boolean }` for workspace changes | Durable before acknowledgement; no active-turn effect; preserves profile restrictions (#4295). | | GET | `/api/drafts/:id/profile` | S | Read confirmed worker profile and enforced facts | Independent session clients; preserve policy lower bounds, principal scope and truthful unknown limits (#1663). | | PUT | `/api/drafts/:id/profile` | S | Save a next-turn tightening preference | Independent session clients; preserve confirmed saves, current-turn profile and voice read-only authority (#1663). | | GET | `/api/drafts/:draftId` | S | Read a draft's text and images | Paired composer and independent clients (#979, D52); preserve revisions, receipts, tombstones, limits and the no-execution boundary. | @@ -143,6 +145,8 @@ client code has a gap. Source owners are listed after the table. | POST | `/api/push/unsubscribe` | S | Remove caller-owned subscription | SDK push renewal and custom PWA clients; preserve principal ownership and private-key exclusion. | | POST | `/api/render` | S | Render supplied document to PNG or PDF | Independent share/render clients; preserve RenderRequest, renderer seam and 501 without renderer. | | GET | `/api/sessions` | S | List backend sessions with partial availability | Independent session clients; preserve SDK ChatSession/history shapes and partial-backend availability behavior. | +| GET | `/api/sessions/:id/code-changes` | S | Read the durable next-admission workspace write preference | Authenticated session clients; defaults off, principal-scoped drafts (#4295). | +| PUT | `/api/sessions/:id/code-changes` | S | Save `{ enabled: boolean }` for workspace changes | Durable before acknowledgement; no active-turn effect; preserves profile restrictions (#4295). | | GET | `/api/sessions/:id/profile` | S | Read confirmed worker profile and enforced facts | Independent session clients; preserve policy lower bounds, principal scope and truthful unknown limits (#1663). | | PUT | `/api/sessions/:id/profile` | S | Save a next-turn tightening preference | Independent session clients; preserve confirmed saves, current-turn profile and voice read-only authority (#1663). | | GET | `/api/sessions/:id` | S | Read owning-backend session transcript | Independent session clients; preserve SDK ChatSession/history shapes and partial-backend availability behavior. | @@ -2439,3 +2443,13 @@ inferred from matching policy bytes. Owner-scope review explicitly covers future repositories currently in that namespace. Runtime trust remains disabled. Removal/readback remain available for existing rules. Revision exhaustion refuses before protected publication. No historical trigger is resolved by these routes. + +### Session code changes (#4295) + +The session/draft `code-changes` GET/PUT routes are specified in the +[integration contract](integration-contract/http.md#default-workspace-inspection-and-code-changes-preference-4295). +They use the same authenticated identity and principal-scoped draft binding as +profile preferences. PUT accepts exactly `{ enabled: boolean }`; all replies +are `Cache-Control: no-store`. Existing sessions default to false. Saves +survive resume and apply only to the next admission; enabled sessions retain +the existing writable-workspace protections and per-file journal. diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 8b145790bf..417f2fd93e 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -39,6 +39,67 @@ hash directly. Missing/expired raw details never grant a download bypass. links use the embedding root's configured API base. Those read helpers do not execute mutations. +### Default workspace inspection and code-changes preference (#4295) + +**Breaking narrowing, authorized 2026-11-20:** default governed and strict +turns bind an existing `workspaces/` read-only. Their retained journal coverage excludes +workspace paths, checkout ignore-policy reads and observed workspace bytes. +Notes keep their existing coverage. This applies per turn even during shared +observations with an opted-in writer. Retained history from earlier turns +remains readable with its existing routes and shapes. If the optional area +is absent at launch, governed note writes stay live, no mountpoint is created, +and workspace exclusion does not apply: new content under that name is +retained and charged as ordinary brain content for that turn, including the +brain's frozen root ignore rules, root journal scope and ordinary Git-internal +exclusions. Steering references and unavailable markers also remain per turn; +an overlapping writer cannot donate its ignore policy. The next default +turn binds the new directory read-only. Status describes the same default +qualification, including an unqualified workspace root or unenforceable policy-protected +parent selecting strict. An unqualified workspace symlink protects only its +namespace; it never makes unrelated note destinations protected. Explicit +owner protections still cover their symlink destinations. Status inspection +never creates protection prerequisites on the live brain. It includes literal +provider folder pins. When provider type folders still require checkpoint taxonomy +qualification, the optional `profile` and `configurationView` are omitted and the +existing `profileFallback` explains the uncertainty; status does not execute +brain configuration or report a guessed profile. Captured versions +remain per turn through storage, so one participant’s retained hash never +replaces another participant’s ignored metadata. Superseded checkpoint +accounting includes excluded checkout bytes until release succeeds. + +**Additive API:** authenticated `GET` and `PUT` +`/api/sessions/:id/code-changes` and `/api/drafts/:id/code-changes` return +`{ enabled: boolean }`, default false. PUT accepts exactly that JSON object; +unknown fields or a non-boolean give 400, non-JSON gives 415, an oversized +body gives 413, an unknown session or one without proven ownership by the +authenticated principal gives 404, and unusable authentication gives 401. +Session reads, writes and enabled draft binds all require proven ownership; +legacy ownership gaps cannot grant writable admission. Drafts are scoped to +the authenticated principal and share the existing bounded profile-draft +storage (507 when full). Successful saves are durable before acknowledgement. All responses are `Cache-Control: no-store`. + +The switch is independent of the worker profile, preserves that preference, +and cannot weaken strict or provider restrictions. A first-send profile draft +carries its code-changes preference into the named session. Saves survive +resume and are frozen before admission awaits; changing a save never changes +an active turn. Enabled turns retain writable workspace qualification, the +alias scan, per-file journaling and byte charges. The saved switch is intent: +host application writes remain protected unless admission actually qualifies +a writable mount. Mode changes reach the worker through append-only new-turn context, without altering tools, the +system prompt or earlier messages. The refusal note names both writable +alternatives: the session's code-changes switch and a managed worktree. Read-only tool failures in +an inspected turn receive the fixed conditional sentence quoted in the +[workspace decision](../decisions/worker-writable-areas.md#workspace-inspection-amendment-2026-11-20-4295-4298), +without path attribution. Explicit host workspace refusals use that same text. +Result codes, record fields and closed HTTP/WS enums remain unchanged. +Commands execute against the read-only mount; read-only failures receive the +conditional remedy after execution, including failures outside the checkout. +Verification and dry runs are never denied by command name. Strict Pi tools +keep repo-relative checkout reads through a sealed source overlay beneath +provider masks. Privileged host applications enforce inspection even without +a governed admission service. +This adds no value to an existing wire/HTTP enum or required response field. + ### Untrusted file marks (additive, #2673) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 8369a9d305..22c5af2b13 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -24,6 +24,15 @@ This is internal compatibility wiring under the internal-entry classification below. It changes no ordinary package signature, CLI/MCP/HTTP envelope, frontmatter meaning or credential authority, and requires a patch changeset. + +Workspace inspection adds optional `legacyWorkspaceNote` preparation and +`WorkerNoteFacts.legacyWorkspaces` qualification facts for first-party read-only +handoffs (#4295). The historical note retains refused alias/scan-limit results; +it never fabricates a writable mount or grants authority. Asynchronous +preparation resolves this compatibility scan off the host event loop, within +its existing preparation, and ordinary callers explicitly default to inspection. +These are internal rendering facts, not provider input or a new extension seam. + ## Native maintenance preparation (internal #2300 / #2343) The SDK's `/internal` entry adds `prepareMaintenanceWorker` and @@ -4740,6 +4749,12 @@ and returns `NativePoolGrowth`: - `omitted` counts comparisons, groups or flags left out to keep one reply within the 64 KiB control bound. Unflagged detail goes first. +The private request parser has a separate 512 KiB bound for worst-case escaped +stat paths. It does not change the 64 KiB control reply, intent-file, stage-row +or paginated-list limits. Metadata read operations return a small fixed-reader +ticket over HTTP; stat/list data travels over the existing separately bounded +reader stream, rather than being embedded in a control reply. + The status is read-only. It neither reconciles, deletes, resets nor reserves anything, and nothing in it forecasts savings or freed capacity. It is unavailable in these cases: diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index 9301decc05..b02e60945a 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -64,7 +64,7 @@ objects merge per field. No value grants authority to autonomous turns. | `protect` | Array of canonical brain-relative paths | Adds protection. No absolute, home, drive, backslash, empty/dot/parent segment or control-character forms. Default `[]`. | | `release` | Array of exact built-in tier B paths | Default `[]`; tier A and `.env*` cannot be released. See [the protected tiers](decisions/governed-writable-workers.md#protected-paths). | | `budgets` | `turn`, `session`, `day`, each with optional `warn_usd`, `block_usd`, `warn_tokens`, `block_tokens` | USD amounts are finite/nonnegative; tokens are nonnegative safe integers. Turn warn/block $100/$200 with 512,000,000 fallback tokens; session/day $2,000/$4,000 with 8,000,000,000 fallback tokens. Day is UTC calendar day; session is retained lifetime. | -| `scope` | `max_files_changed`, `max_minutes`, `max_tool_calls`, `max_bytes_written` | Nonnegative safe integers, except finite minutes. Defaults: 1,000 paths, 120 minutes, 500 calls, 4 GiB. `max_files_changed` counts changed paths outside `workspaces/`; `max_bytes_written` counts workspace writes too. Path/byte defaults are provisional approved values, not measured distributions. | +| `scope` | `max_files_changed`, `max_minutes`, `max_tool_calls`, `max_bytes_written` | Nonnegative safe integers, except finite minutes. Defaults: 1,000 paths, 120 minutes, 500 calls, 4 GiB. `max_files_changed` counts changed paths outside admitted workspace areas; `max_bytes_written` counts opted-in workspace writes. If the optional workspace is absent at launch, content the turn creates under that name counts as ordinary brain paths and bytes, with root journal scope, root ignore rules and ordinary Git-internal exclusions. Default inspection turns exclude workspace capture, policy, rows and observed bytes, independently of overlapping opted-in writers. Path/byte defaults are provisional approved values, not measured distributions. | | `commands` | `deny`, `confirm`: arrays of `{ pattern: string, reason?: string }` | Additions to existing permissions, default `[]`. Regex sources preserve their literal anchors and compile case-insensitively under [confirmation rules](decisions/confirm-patterns.md). Mixed lists retain valid entries in order and report skipped sources; nonempty entirely invalid lists refuse. | | `egress` | `mode`: `record`/`allowlist`; `allow`, `deny`: string arrays; `max_bytes_per_turn`: nonnegative safe integer | `record`, empty lists and no byte cap by default. This reader does not establish network enforcement. | | `outward` | `allow`: array of `{ command: string, remotes: string[] }`; `hosts`: string array; `github`: `{ repositories: string[] }` (at most 256) | Default empty additions to the existing outward-action rules and built-in destination list. Parsing grants no action. `github.repositories` (additive, #3798) lists the repositories the host GitHub write tools may write to: each entry is `owner/repo` exactly or `owner/*` for every repository of one owner, with GitHub's name grammar (owner `[A-Za-z0-9-]{1,39}`, repository `[A-Za-z0-9._-]{1,100}`, not `.` or `..`). Owner and repository compare without case. No other pattern exists, and one malformed entry, or an unknown key in `github`, makes the policy invalid rather than being skipped. Absent or empty, the default, no GitHub write is admitted. A listed repository still needs a per-use approval card for each write; see [the MCP contract](integration-contract/mcp.md#github-writes-additive-0450-3798). `hosts` extends the built-in outward destinations: the GitHub API hosts `api.github.com` and `uploads.github.com`, mail submission ports and mail-send APIs. A connection to one of them that no visible read or approved outward action covers waits on a per-use `Network` card ([#3799](integration-contract/mcp.md#raw-connections-to-githubs-api-0450-3799)). | diff --git a/packages/common/src/worker-areas.ts b/packages/common/src/worker-areas.ts index 4784525c0e..f6c2eae1f5 100644 --- a/packages/common/src/worker-areas.ts +++ b/packages/common/src/worker-areas.ts @@ -46,3 +46,8 @@ export function linkRule(scratchDir: string | undefined): string { /** Why a direct write into a read-only brain fails, and the way to change it instead. */ export const READ_ONLY_BRAIN_RULE = "The brain is read-only here: change it through `write_file`, `edit_file` and the curated brain tools."; + +/** Inspection never writes source, including installs/builds (#4295, #4298). */ +export const WORKSPACES_READ_ONLY_REASON = "inspect mode; enable this session’s code-changes switch or request a managed worktree to write, install or build"; +/** Conditional tool-result advice; it deliberately makes no path attribution. */ +export const WORKSPACES_WRITE_REFUSAL = "If this write was under workspaces/, the checkout is read-only in this turn: switch on code changes for this session (applies from the next message) or use a managed worktree."; diff --git a/packages/ui-backend-claude/src/permission-hooks.ts b/packages/ui-backend-claude/src/permission-hooks.ts index 98499c0ec2..a6c26fc419 100644 --- a/packages/ui-backend-claude/src/permission-hooks.ts +++ b/packages/ui-backend-claude/src/permission-hooks.ts @@ -1,3 +1,4 @@ +import { workspaceWriteRefusal } from "@schlessera/brain-ui-sdk/internal"; import { toolAvailabilityRefusal } from "./tool-availability.js"; import { createHash } from "node:crypto"; import { relative, resolve } from "node:path"; @@ -294,7 +295,7 @@ export function enforcementHookFor(ctx: PermissionContext): HookCallback { return async (hookInput) => { const snapshot = req.bridge.admissionSafety?.read(); if (hookInput.hook_event_name === "PreToolUse") { - const unavailable = toolAvailabilityRefusal(req, hookInput.tool_name); + const unavailable = toolAvailabilityRefusal(req, hookInput.tool_name, hookInput.tool_input, hookInput.cwd); if (unavailable) return { continue: true, hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: unavailable, } }; @@ -353,7 +354,7 @@ export function canUseToolFor(ctx: PermissionContext): NonNullable 0 && req.workerSandbox?.areas.some(area => area.name === "workspaces" && !area.mount.writable && !area.mount.missing) ? { PostToolUse: [...(!req.autonomous ? [{ matcher: "^(Read|Write|Edit|NotebookEdit)$", hooks: [finishNativeFile] }] : []),{ hooks: [safetyResult] }], PostToolUseFailure: [...(!req.autonomous ? [{ matcher: "^(Read|Write|Edit|NotebookEdit)$", hooks: [finishNativeFile] }] : []),{ hooks: [safetyResult] }], } : {}), diff --git a/packages/ui-backend-claude/src/sdk-options.ts b/packages/ui-backend-claude/src/sdk-options.ts index 337d752c9e..ac8111edcb 100644 --- a/packages/ui-backend-claude/src/sdk-options.ts +++ b/packages/ui-backend-claude/src/sdk-options.ts @@ -333,9 +333,11 @@ function prepareSandboxNote( const { backend, req, confirmPatterns, log } = options; // One resolution of the worker's writable areas feeds both its mounts and // the note the agent reads, so the two cannot disagree (#1626). + const legacySummary = req.autonomous?.persistence === "none" && !req.autonomous.containment + && req.autonomous.allowedTools.every(name => ["Read", "Glob", "Grep"].includes(name)); const sandbox = envelope ? { ...prepareWorkerSandbox(backend.brainPath, { restricted: true, maintenance: backend.maintenance }), ...(req.workerProviderMasks ? { providerMasks: req.workerProviderMasks } : {}), ...(req.workerDataTree ? { dataTree: req.workerDataTree } : {}) } - : req.workerSandbox ?? prepareWorkerSandbox(backend.brainPath, { maintenance: backend.maintenance }); + : req.workerSandbox ?? prepareWorkerSandbox(backend.brainPath, { maintenance: backend.maintenance, codeChanges: false, legacyWorkspaceNote: legacySummary }); for (const warning of workerSandboxWarnings(sandbox)) log("warn", warning); // The same for its resource limits (#1660). const limits = launchLimits({}); @@ -344,9 +346,11 @@ function prepareSandboxNote( const stateLimits = resolveWorkerStateLimits(backend.workerState ?? {}); // And so is turn temp's, next to the tool that frees it (#1703). const turnTempLimits = resolveTurnTempLimits(backend.turnTemp ?? {}); + // Only the nonpersistent read-only summary keeps its historical prompt text. + // This rendering plan never becomes the launched sandbox or a write grant. const sandboxNote = [workerSandboxNote(sandbox, { ...(options.identity ? { identity: options.identity } : {}), ...(options.hostInference ? { egress: true } : {}), providerKeys, hardTimeoutMs: req.turnBudgetMs, limits: [...workerNoteLimits(limits.status), workerStateLimit(stateLimits), turnTempLimit(turnTempLimits.allowanceBytes, turnTempTool ? TURN_TEMP_TOOL_NAME : undefined), - outputStagingLimit()] }), workerCommandPolicyNote(req.autonomous ? undefined : sandbox.commandPolicy, confirmPatterns), req.autonomous ? "" : workerOutwardNote(Boolean(options.hostInference), sandbox.commandPolicy?.taint?.())].filter(Boolean).join("\n\n"); + outputStagingLimit()] }, legacySummary), workerCommandPolicyNote(req.autonomous ? undefined : sandbox.commandPolicy, confirmPatterns), req.autonomous ? "" : workerOutwardNote(Boolean(options.hostInference), sandbox.commandPolicy?.taint?.())].filter(Boolean).join("\n\n"); return { sandbox, limits, stateLimits, turnTempLimits, sandboxNote }; } @@ -752,6 +756,7 @@ async function* buildAttachmentPrompt( export async function prepareClaudeTurnSandbox(options: Pick) { const { backend, req } = options; if (req.workerSandbox || options.hostInference || req.autonomous?.containment === "restricted") return undefined; + const legacySummary = req.autonomous?.persistence === "none" && !req.autonomous.containment && req.autonomous.allowedTools.every(name => ["Read", "Glob", "Grep"].includes(name)); const turnEnvironment = options.turnEnvironment ?? turnEnv(options.profile); - return { turnEnvironment, workerSandbox: await prepareWorkerSandboxAsync(backend.brainPath, { maintenance: backend.maintenance }) }; + return { turnEnvironment, workerSandbox: await prepareWorkerSandboxAsync(backend.brainPath, { maintenance: backend.maintenance, codeChanges: false, legacyWorkspaceNote: legacySummary }) }; } diff --git a/packages/ui-backend-claude/src/tool-availability.ts b/packages/ui-backend-claude/src/tool-availability.ts index e92e4d549e..daca5bd8d3 100644 --- a/packages/ui-backend-claude/src/tool-availability.ts +++ b/packages/ui-backend-claude/src/tool-availability.ts @@ -22,7 +22,7 @@ const interactive = new Set(["propose_policy_change", "inbox_add", "resolve_acti GITHUB_TOOL_NAMES.create, GITHUB_TOOL_NAMES.comment]); /** Registration is stable; these live facts are authority only at call time. */ -export function toolAvailabilityRefusal(req: StartTurnRequest, toolName: string): string | undefined { +export function toolAvailabilityRefusal(req: StartTurnRequest, toolName: string, _input?: unknown, _cwd?: string): string | undefined { if (req.autonomous) return undefined; const name = toolName.replace(/^mcp__brain-ui__/, ""); if (["Write", "Edit", "NotebookEdit"].includes(name) diff --git a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts index 544be25c85..9d3e836f75 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -65,6 +65,7 @@ const restore = replaceNativeStartupAcquisitionForFixture(); try { for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { brain = fixtureBrain(scratch, scenario); + if (scenario === "facts") mkdirSync(join(brain, "workspaces/ithaca"), { recursive: true }); capture = captures[scenario] = { sessions: [], exchanges: [], appends: [] }; const home = join(scratch, `home-${scenario}`); mkdirSync(join(home, ".claude"), { recursive: true }); @@ -75,7 +76,7 @@ try { if (scenario === "repository" && turnIndex) changeRepository(brain, turnIndex); const facts = scenario === "facts" ? turnIndex : 0; const controller = new AbortController(); - const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", ...(scenario === "promotion" ? {} : { areas: [] }) }); + const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", ...(scenario === "facts" ? { areas: ["workspaces"], codeChanges: turnIndex === 1 } : scenario === "promotion" ? {} : { areas: [] }) }); const view = createFixtureWorkerStartupView(brain); const turn = createClaudeSdkTurn({ backend: { brainPath: brain, ...(scenario === "safety" ? { systemPromptAppend: turnIndex === 0 ? "Legacy safety policy: this session stays restricted." : "Reviewed safety policy: finalized individual verdicts may restore normal." } : {}) }, req: { prompt: `Odysseus checks voyage step ${turnIndex}.`, sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, @@ -139,6 +140,7 @@ try { } scenario = "budget"; brain = fixtureBrain(scratch, scenario); + if (scenario === "facts") mkdirSync(join(brain, "workspaces/ithaca"), { recursive: true }); capture = captures[scenario] = { sessions: [], exchanges: [], appends: [] }; sequence = 0; const home = join(scratch, "home-budget"); diff --git a/packages/ui-backend-claude/tests/helpers/sdk-options-snapshot.ts b/packages/ui-backend-claude/tests/helpers/sdk-options-snapshot.ts index d7b16fc933..0f24b3ab67 100644 --- a/packages/ui-backend-claude/tests/helpers/sdk-options-snapshot.ts +++ b/packages/ui-backend-claude/tests/helpers/sdk-options-snapshot.ts @@ -9,14 +9,14 @@ * session id are replaced by placeholders before comparison. */ import { createHash } from "node:crypto"; -import { mkdtempSync, rmSync } from "node:fs"; +import { linkSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import type { Options } from "@anthropic-ai/claude-agent-sdk"; -import { createClaudeSdkTurn } from "../../src/sdk-options.js"; +import { createClaudeSdkTurn, prepareClaudeTurnSandbox } from "../../src/sdk-options.js"; export const SNAPSHOT_MODES = ["hosted-typed", "voice", "unhosted", "relayed", "autonomous-summary", "restricted"] as const; export type SnapshotMode = (typeof SNAPSHOT_MODES)[number]; @@ -69,21 +69,25 @@ function hooksShape(hooks: Options["hooks"]): Record> { +export async function sdkOptionsSnapshot(mode: SnapshotMode, inputs: { populatedWorkspace?: boolean; prepareSandbox?: boolean; withoutHostSandbox?: boolean; aliasWorkspace?: boolean } = {}): Promise> { const previous = process.env.BRAIN_UI_WORKER_LIMITS; process.env.BRAIN_UI_WORKER_LIMITS = PINNED_WORKER_LIMITS; - try { return await snapshotOnce(mode); } finally { + try { return await snapshotOnce(mode, inputs); } finally { if (previous === undefined) delete process.env.BRAIN_UI_WORKER_LIMITS; else process.env.BRAIN_UI_WORKER_LIMITS = previous; } } -async function snapshotOnce(mode: SnapshotMode): Promise> { +async function snapshotOnce(mode: SnapshotMode, inputs: { populatedWorkspace?: boolean; prepareSandbox?: boolean; withoutHostSandbox?: boolean; aliasWorkspace?: boolean }): Promise> { const brain = mkdtempSync(join(tmpdir(), "odysseus-sdk-options-")); + if (inputs.populatedWorkspace) mkdirSync(join(brain, "workspaces/ithaca"), { recursive: true }); + if(inputs.aliasWorkspace){mkdirSync(join(brain,"notes"));writeFileSync(join(brain,"notes/raft.md"),"Athena");linkSync(join(brain,"notes/raft.md"),join(brain,"workspaces/ithaca/alias.md"));} const restricted = mode === "restricted"; - const turn = createClaudeSdkTurn({ + const request=requestFor(mode,brain); + if(inputs.withoutHostSandbox)delete request.workerSandbox; + const options: Parameters[0] = { backend: { brainPath: brain } as never, - req: requestFor(mode, brain) as never, + req: request as never, ...(restricted ? {} : { turnEnvironment: {} }), ...(mode === "relayed" ? { hostInference: { proxyDir: brain, baseUrl: "http://localhost" } } : {}), profile: (restricted @@ -96,7 +100,9 @@ async function snapshotOnce(mode: SnapshotMode): Promise confirmPatterns: [/\brm\s+-rf\b/], turnLock: { acquireForTool: async () => ({ ok: true }), releaseForTool() {} } as never, log: () => undefined, - }); + }; + const own = inputs.prepareSandbox ? await prepareClaudeTurnSandbox(options) : undefined; + const turn = createClaudeSdkTurn({ ...options, ...(own ? { turnEnvironment: own.turnEnvironment, req: { ...options.req, workerSandbox: own.workerSandbox } } : {}) }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "sdk-options-snapshot", version: "1" }); try { @@ -122,6 +128,7 @@ async function snapshotOnce(mode: SnapshotMode): Promise subscriptionOnly: turn.subscriptionOnly, pinnedSettingsEnv: turn.pinnedSettingsEnv ?? null, promptIsStream: typeof turn.prompt !== "string", + ...(inputs.withoutHostSandbox ? { contextTail: typeof turn.prompt === "string" ? turn.prompt : await Array.fromAsync(turn.prompt) } : {}), }; return JSON.parse(JSON.stringify(snapshot).replaceAll(brain, "")); } finally { diff --git a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts index a7c182bbdf..6c94a12107 100644 --- a/packages/ui-backend-claude/tests/permission-wiring-units.test.ts +++ b/packages/ui-backend-claude/tests/permission-wiring-units.test.ts @@ -223,3 +223,32 @@ describe("native edit versions", () => { expect(remembered).toEqual([["loom.md", createHash("sha256").update(literal, "utf8").digest("hex")]]); }); }); + +test.each([false,true])("inspection commands run before filesystem failures receive remedies (autonomous=%s)", async autonomous => { + const {ctx}=contextFor({allowedTools:["Bash"]}); + ctx.req.workerSandbox={brain:"/srv/odysseus-brain",profile:"governed",restricted:false,scratchAliasesRemoved:[],areas:[{name:"workspaces",rel:"workspaces",mount:{writable:false,readOnlyPath:"/srv/odysseus-brain/workspaces",reason:"inspection"}}]}; + if(autonomous)ctx.req.autonomous={origin:"autonomous",persistence:"none",allowedTools:["Bash"],systemPromptAppend:""}; + const {hooks}=createPermissionWiring({req:ctx.req,allowedTools:["Bash"],confirmPatterns:[],brainPath:"/srv/odysseus-brain",turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{},log(){}}); + const post=hooks!.PostToolUseFailure!.flatMap(group=>group.hooks).at(-1)!; + for(const command of ["npm install --dry-run","bun test","npm help install","npm ls build","npm install","npm i","npm ci","npm clean-install","mkdir workspaces/ithaca/build","mkdir -p workspaces/ithaca/build","git add raft.md","pnpm add ithaca","yarn run build","bun run build"]){ + const tool_input={command:`cd workspaces/ithaca && ${command}`}; + expect(await enforcementHookFor(ctx)(...hookCall("Bash",tool_input)),`EXECUTION_REACHES_KERNEL_${command}`).toEqual({continue:true}); + const failure={hook_event_name:"PostToolUseFailure",tool_name:"Bash",tool_input,tool_use_id:"oar-1",cwd:"/srv/odysseus-brain",error:"EROFS: Read-only file system, open '/srv/odysseus-brain/workspaces/ithaca/package-lock.json'"}; + const answer=await post(failure as never,undefined,{signal:new AbortController().signal}); + expect(JSON.stringify(answer),`FAILED_CHECKOUT_NAMES_REMEDIES_${command}`).toContain("switch on code changes for this session"); + expect(JSON.stringify(answer)).toContain("managed worktree"); + expect(await post({...failure,error:"test assertion failed"} as never,undefined,{signal:new AbortController().signal}),"ORDINARY_TEST_FAILURE_HAS_NO_PERMISSION_NOTE").toEqual({continue:true}); + } + expect(JSON.stringify(await post({hook_event_name:"PostToolUseFailure",tool_name:"Bash",tool_use_id:"npm",tool_input:{command:"npm ci"},error:"npm error code EROFS\nnpm error path /srv/odysseus-brain/workspaces/ithaca/package-lock.json"} as never,undefined,{signal:new AbortController().signal})),"NPM_DIAGNOSTIC_PATH_HAS_PERMISSION_CONTEXT").toContain("switch on code changes for this session"); + expect(JSON.stringify(await post({hook_event_name:"PostToolUseFailure",tool_name:"Bash",tool_use_id:"touch",tool_input:{command:"touch workspaces/ithaca/raft.md"},error:"touch: cannot touch '/srv/odysseus-brain/workspaces/ithaca/raft.md': Read-only file system"} as never,undefined,{signal:new AbortController().signal})),"TOUCH_DIAGNOSTIC_OWNS_THE_INSPECTED_DESTINATION").toContain("switch on code changes for this session"); + for(const command of ["cat workspaces/ithaca/README.md > /tmp/readonly/raft.md","cd workspaces/ithaca && cat README.md > /tmp/readonly/raft.md","cd workspaces/ithaca && touch /tmp/readonly/raft.md"]){ + expect(await post({hook_event_name:"PostToolUseFailure",tool_name:"Bash",tool_use_id:"outside",tool_input:{command},cwd:"/srv/odysseus-brain",error:"open '/srv/odysseus-brain/workspaces/ithaca/README.md'\n/bin/bash: /tmp/readonly/raft.md: Permission denied"} as never,undefined,{signal:new AbortController().signal}),"CHECKOUT_READ_CANNOT_ATTRIBUTE_AN_OUTSIDE_WRITE_FAILURE").toEqual({continue:true}); + } + for(const [tool_name,tool_response] of [["Bash",{exitCode:1,stderr:"mkdir: cannot create directory '/outside/raft': Read-only file system"}],["Write",{isError:true,content:[{type:"text",text:"EROFS"}]}],["mcp__brain__brain_write",{isError:true,content:[{type:"text",text:JSON.stringify({ok:false,message:"workspaces/ is read-only"})}]}]] as const){ + const result=await hooks!.PostToolUse!.flatMap(group=>group.hooks).at(-1)!({hook_event_name:"PostToolUse",tool_name,tool_use_id:"conditional",tool_input:{},tool_response} as never,undefined,{signal:new AbortController().signal}); + expect(result,"CLAUDE_CONDITIONAL_ADVICE_COVERS_SHELL_FILE_AND_HOST_FAILURES").toMatchObject({hookSpecificOutput:{additionalContext:"If this write was under workspaces/, the checkout is read-only in this turn: switch on code changes for this session (applies from the next message) or use a managed worktree."}}); + } + const success=hooks!.PostToolUse!.flatMap(group=>group.hooks).at(-1)!; + expect(await success({hook_event_name:"PostToolUse",tool_name:"Bash",tool_use_id:"oar-1",tool_input:{command:"cd workspaces/ithaca && bun test"},tool_response:{stdout:"pass",exitCode:0}} as never,undefined,{signal:new AbortController().signal})).toEqual({continue:true}); + expect(await post({hook_event_name:"PostToolUseFailure",tool_name:"Bash",tool_use_id:"oar-1",tool_input:{command:"cd /tmp/brain-reference/public/ithaca && npm install"},error:"EROFS: Read-only file system",cwd:"/srv/odysseus-brain"} as never,undefined,{signal:new AbortController().signal})).toMatchObject({hookSpecificOutput:{additionalContext:expect.stringContaining("managed worktree")}}); +}); diff --git a/packages/ui-backend-claude/tests/provider-history.test.ts b/packages/ui-backend-claude/tests/provider-history.test.ts index b8935e2c71..8a03b58e07 100644 --- a/packages/ui-backend-claude/tests/provider-history.test.ts +++ b/packages/ui-backend-claude/tests/provider-history.test.ts @@ -210,3 +210,19 @@ test("retained legacy policy wording and earlier taint facts stay byte-identical expect(exchanges.at(-1)!.raw, "SAFETY_REVIEW_NEVER_REWRITES_EARLIER_FACTS").toContain("This session is tainted"); expect(JSON.stringify(messages(exchanges.at(-1)!).at(-1)), "SAFETY_REVIEW_CHANGES_ONLY_NEW_TAIL_FACTS").not.toContain("This session is tainted"); }); + + +test("workspace mode changes appear only in the new tail and preserve the provider prefix (#4295)", () => { + const capture = captures.facts!; + const first = main(capture).find(exchange => exchange.turn === 0)!; + expect(first.raw, "INSPECT_FIRST_TAIL_NAMES_WRITE_OPT_IN").toContain("code-changes switch"); + for (const [a, b] of pairs(capture)) { + identical(body(a).tools, body(b).tools, "WORKSPACE_MODE_TOOLS_STABLE"); + identical(system(a), system(b), "WORKSPACE_MODE_SYSTEM_STABLE"); + history(a, b); + } + const changed = main(capture).find(exchange => exchange.turn === 1)!; + expect(JSON.stringify(messages(changed).at(-1)), "CHANGE_MODE_IN_NEW_TAIL").toContain("is writable: clone, fetch and commit"); + const inspect = main(capture).find(exchange => exchange.turn === 2)!; + expect(JSON.stringify(messages(inspect).at(-1)), "INSPECT_MODE_RETURNS_IN_NEW_TAIL").toContain("code-changes switch"); +}); diff --git a/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts b/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts index 82160c79c7..7cb5773b0b 100644 --- a/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts +++ b/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts @@ -1,4 +1,9 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import * as worker from "@schlessera/brain-ui-sdk/internal"; +import { mkdtempSync, mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { prepareClaudeTurnSandbox } from "../src/sdk-options.js"; +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { installTestHome } from "../../../scripts/test-home"; import expected from "./fixtures/sdk-options-snapshot.json" with { type: "json" }; @@ -49,3 +54,42 @@ for (const mode of SNAPSHOT_MODES) test(`the SDK options for a fixed ${mode} req expect(JSON.stringify(actual, null, 2), `SDK_OPTIONS_DRIFT_${mode}`) .toBe(JSON.stringify((expected as Record)[mode], null, 2)); }); + + +test("the real handoff preparation preserves its populated-workspace system prompt", async () => { + const direct = await sdkOptionsSnapshot("autonomous-summary", { populatedWorkspace: true }); + const prepared = await sdkOptionsSnapshot("autonomous-summary", { populatedWorkspace: true, prepareSandbox: true }); + expect(JSON.stringify(prepared.systemPrompt), "HANDOFF_STILL_DESCRIBES_THE_LEGACY_WRITABLE_AREA").toContain("is writable: clone, fetch and commit"); + expect(JSON.stringify(prepared.systemPrompt)).not.toContain("code-changes switch"); + expect(prepared.systemPrompt, "HANDOFF_PREPARATION_DOES_NOT_CHANGE_SYSTEM_PROMPT").toEqual(direct.systemPrompt); +}); + + +test("an interactive caller without a host switch prepares inspection, never writable code", async () => { + const brain=mkdtempSync(join(tmpdir(),"odysseus-default-sandbox-"));mkdirSync(join(brain,"workspaces/ithaca"),{recursive:true}); + try { + const own=await prepareClaudeTurnSandbox({backend:{brainPath:brain} as never,req:{prompt:"Read Ithaca source.",bridge:{emit(){}},signal:new AbortController().signal} as never,profile:{} as never,turnEnvironment:{}}); + expect(own!.workerSandbox.areas.find(area=>area.name==="workspaces")!.mount.writable,"HOSTLESS_CALLER_CANNOT_GRANT_CODE_WRITES").toBe(false); + expect(own!.workerSandbox.codeChanges).toBe(false); + }finally{rmSync(brain,{recursive:true,force:true});} +}); + + +test("direct interactive assembly without a host grant describes inspection", async () => { + const snapshot=await sdkOptionsSnapshot("hosted-typed",{populatedWorkspace:true,withoutHostSandbox:true}); + expect(JSON.stringify(snapshot.systemPrompt),"HOSTLESS_ASSEMBLY_HAS_NO_WRITABLE_WORKSPACE").not.toContain("is writable: clone, fetch and commit"); + expect(JSON.stringify(snapshot.contextTail)).toContain("code-changes switch"); + expect(JSON.stringify(snapshot.contextTail),"HOSTLESS_CONTEXT_USES_THE_READ_ONLY_MOUNT").not.toContain("is writable: clone, fetch and commit"); +}); + + +test("prepared handoff rendering never prepares the worker synchronously again",async()=>{ + const preparation=spyOn(worker,"prepareWorkerSandbox"); + try{const snapshot=await sdkOptionsSnapshot("autonomous-summary",{populatedWorkspace:true,prepareSandbox:true});expect(JSON.stringify(snapshot.systemPrompt)).toContain("is writable: clone, fetch and commit");expect(preparation,"HANDOFF_REUSES_THE_PREPARED_SANDBOX").not.toHaveBeenCalled();}finally{preparation.mockRestore();} +}); + + +test("Claude handoff retains an actually refused legacy workspace qualification",async()=>{ + const snapshot=await sdkOptionsSnapshot("autonomous-summary",{populatedWorkspace:true,aliasWorkspace:true,prepareSandbox:true}); + expect(JSON.stringify(snapshot.systemPrompt),"HANDOFF_PRESERVES_LEGACY_ALIAS_REFUSAL").toContain("hard-linked to files outside workspaces/");expect(JSON.stringify(snapshot.systemPrompt)).not.toContain("is writable: clone, fetch and commit"); +}); diff --git a/packages/ui-backend-pi/src/tool-safety.ts b/packages/ui-backend-pi/src/tool-safety.ts index 327f57ade4..b926d8f6b8 100644 --- a/packages/ui-backend-pi/src/tool-safety.ts +++ b/packages/ui-backend-pi/src/tool-safety.ts @@ -6,7 +6,7 @@ import {PiInputSafetyUnavailableError} from "./worker-protocol.js"; type Content = import("@earendil-works/pi-agent-core").AfterToolCallContext["result"]["content"]; export interface PiToolSafety { permission(name:string,id:string,input:Record):Promise; - result(name:string,id:string,content:Content,complete?:boolean):Promise; + result(name:string,id:string,content:Content,complete?:boolean,failed?:boolean):Promise; unavailable?():Promise; stop():void; } @@ -69,10 +69,12 @@ export function installPiToolSafety(agent:Agent,safety:PiToolSafety,hasUnqualifi // replace this content with an error; do not qualify the original read. // Structured payloads are programmatic output, outside this text-only wire. const structured=final?.structuredContent??(final?.content?undefined:context.result.structuredContent); - const complete=!failure&&!(final?.isError??context.isError)&&structured===undefined; - try{await safety.result(context.toolCall.name,context.toolCall.id,final?.content??context.result.content,complete);} + const failed = (final?.isError ?? context.isError) || (context.toolCall.name === "bash" && typeof context.result.details?.exitCode === "number" && context.result.details.exitCode !== 0); + const complete=!failure&&!failed&&structured===undefined; + let workspaceNote: void | string; + try{workspaceNote=await safety.result(context.toolCall.name,context.toolCall.id,final?.content??context.result.content,complete,failed);} catch(error){stop();throw error;} if(failure){stop();throw failure.error;} - return final; + return workspaceNote ? { ...final, content: [...(final?.content??context.result.content), {type:"text" as const,text:workspaceNote}] } : final; }; } diff --git a/packages/ui-backend-pi/src/worker-entry.ts b/packages/ui-backend-pi/src/worker-entry.ts index 744ec29325..d98c563483 100644 --- a/packages/ui-backend-pi/src/worker-entry.ts +++ b/packages/ui-backend-pi/src/worker-entry.ts @@ -202,8 +202,9 @@ async function initialize(init: Init): Promise { // Initialization is awaited by the same loop that consumes RPC answers. // Refuse startup one-way; the typed error makes the host retain loss. unavailable: async()=>{if(initialized)await rpc("safetyUnavailable","","",{});}, - result: (name,id,content,complete) => { - return rpc("safetyResult",name,id,safetyResultInput(name,content,complete)); + result: async (name,id,content,complete,failed) => { + const result = await rpc("safetyResult",name,id,safetyResultInput(name,content,complete,failed)); + return result.workspaceNote; }, stop: () => controller.abort(), }, diff --git a/packages/ui-backend-pi/src/worker-launch.ts b/packages/ui-backend-pi/src/worker-launch.ts index b4053b8b99..b1d8c99f4a 100644 --- a/packages/ui-backend-pi/src/worker-launch.ts +++ b/packages/ui-backend-pi/src/worker-launch.ts @@ -213,7 +213,7 @@ export async function launchPiWorker(request: PiWorkerLaunchRequest): Promise ["read_file", "grep", "find", "ls"].includes(name)) }); if (hostInference) sandbox = { ...sandbox, maskPaths: [...sandbox.maskPaths ?? [], ...hostInference.maskPaths] }; if (cachedNpmModules) { if (sandbox.maskPaths?.some(path => { try { const actual = realpathSync(path); return isWithin(cachedNpmModules, actual); } catch { return false; } })) { @@ -226,7 +226,7 @@ export async function launchPiWorker(request: PiWorkerLaunchRequest): Promise ["read_file", "grep", "find", "ls"].includes(name))), workerCommandPolicyNote(env.autonomous ? undefined : sandbox.commandPolicy, confirmPatterns), env.autonomous ? "" : workerOutwardNote(Boolean(hostInference), sandbox.commandPolicy?.taint?.())].filter(Boolean).join("\n\n"); if (resumeId && !restricted && stateRoomWarning(admissionObservation)) { sandboxNote += `\n\n${stateRoomCopy(admissionObservation)} Continue in a new conversation before it is full. This one stays available.`; } diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 21825ff1e1..6fcc8c64f3 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -89,13 +89,13 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ export type PiWorkerMessage = z.infer; /** Text delivered to the host's safety collector, separate from provider history. */ -export function safetyResultInput(tool: string, content: readonly { type: string; text?: unknown }[], complete = true): { output: string; segments?: string[] } { +export function safetyResultInput(tool: string, content: readonly { type: string; text?: unknown }[], complete = true, failed = false): { output: string; segments?: string[]; failed?: true } { const segments = content.filter(part => part.type === "text").map(part => part.text as string); // Omitted segments mean unprovable read delivery. Filtering an image or // resource out must not turn mixed content into one verified text part. if (tool === "reference_read" && (!complete || content.some(part => part.type !== "text" || typeof part.text !== "string"))) return { output: segments.join("\n") }; - return { output: segments.join("\n"), segments }; + return { output: segments.join("\n"), segments, ...(failed ? {failed:true as const} : {}) }; } export function sendPipe(pipe: Pick, value: unknown): void { diff --git a/packages/ui-backend-pi/src/worker-rpc.ts b/packages/ui-backend-pi/src/worker-rpc.ts index f8f6868b48..74cdc210f9 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -15,7 +15,7 @@ import type { SessionCaps } from "./backend-options.js"; import { createPiBridgeTools, REQUEST_IMAGE_MASK_INPUT_SCHEMA } from "./bridge-tools.js"; import { decidePiToolPermission } from "./permission-gate.js"; import { revalidatePiAdmission } from "./tool-admission.js"; -import { safetyAdmissionRefusal } from "@schlessera/brain-ui-sdk/internal"; +import { workspaceWriteRefusal, safetyAdmissionRefusal } from "@schlessera/brain-ui-sdk/internal"; import { syncPiAuth } from "./session-storage.js"; import type { TurnContext } from "./turn-context.js"; import type { PiWorkerMessage } from "./worker-protocol.js"; @@ -43,7 +43,7 @@ export interface PiWorkerRpcContext { autonomous: boolean; canFinalizeSafety?(toolName:string,toolId:string):boolean; /** The worker's resolved sandbox; native file observations require a governed one. */ - sandbox: Pick; + sandbox: Pick & Partial; /** The host-supplied sandbox, if any; a governed one keeps the native write and edit tools. */ workerSandbox: WorkerSandbox | undefined; observeFile(path: string): ReturnType>; @@ -174,7 +174,7 @@ async function permit(msg: PiWorkerRpc, bridge: BackendBridge, context: PiWorker context.live(); const refused = refusal(); if (refused) return { behavior: "deny", message: refused }; - if (grant) context.grants.set(msg.toolCallId, grant); + if (grant) { context.grants.set(msg.toolCallId, grant); context.executed(msg).input = JSON.parse(grant.input); } return decision; } @@ -283,11 +283,15 @@ export const PI_WORKER_RPC_HANDLERS: Readonly{ - if(Object.keys(msg.input).some(key=>!["output","segments"].includes(key))||typeof msg.input.output!=="string"||msg.input.segments!==undefined&&(!Array.isArray(msg.input.segments)||(msg.input.segments as unknown[]).some(v=>typeof v!=="string")))throw resultLoss(new Error("Malformed safety result")); + if(Object.keys(msg.input).some(key=>!["output","segments","failed"].includes(key))||msg.input.failed!==undefined&&typeof msg.input.failed!=="boolean"||typeof msg.input.output!=="string"||msg.input.segments!==undefined&&(!Array.isArray(msg.input.segments)||(msg.input.segments as unknown[]).some(v=>typeof v!=="string")))throw resultLoss(new Error("Malformed safety result")); const execution=context.executed(msg); const bounded=execution.name===msg.toolName&&context.canFinalizeSafety?.(msg.toolName,msg.toolCallId)===true; - await bridge.inputSafety?.result(msg.toolCallId,msg.toolName,msg.input.output,bounded,msg.input.segments as string[]|undefined); - context.live();return {ok:true}; + const workspaceNote = msg.input.failed === true && context.sandbox.brain && context.sandbox.areas + ? workspaceWriteRefusal(context.sandbox as WorkerSandbox, msg.toolName, execution.input, undefined, msg.input.output) : undefined; + const output = workspaceNote ? `${msg.input.output}\n\n${workspaceNote}` : msg.input.output; + const segments = msg.input.segments as string[] | undefined; + await bridge.inputSafety?.result(msg.toolCallId,msg.toolName,output,bounded,workspaceNote && segments ? [...segments,workspaceNote] : segments); + context.live();return {ok:true,...(workspaceNote ? {workspaceNote} : {})}; }, }; diff --git a/packages/ui-backend-pi/src/worker-session.ts b/packages/ui-backend-pi/src/worker-session.ts index bc6e5ee3d5..45d3ac4dab 100644 --- a/packages/ui-backend-pi/src/worker-session.ts +++ b/packages/ui-backend-pi/src/worker-session.ts @@ -21,7 +21,7 @@ import { discoversPiExtensions } from "./extension-inspection.js"; export { savedModel } from "./worker-launch.js"; /** What the host saw one call do: the RPCs it made, under the name it ran as (#2834). */ -export type CallExecution = { name: string; host: boolean; lock: boolean; phases: Set }; +export type CallExecution = { name: string; host: boolean; lock: boolean; phases: Set; input?: Record }; /** * The execution path one completed call proved, from the host's own record of * its RPCs. Only an extension-free worker's calls are ever passed here: its diff --git a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts index d6aef4ef97..d93bbf775b 100644 --- a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts @@ -65,6 +65,7 @@ process.env.BRAIN_UI_PI_CREDENTIAL_ORIGINS = `openai=${server.url.origin}`; try { for (scenario of ["control", "repository", "facts", "promotion", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { brain = fixtureBrain(scratch, scenario); + if (scenario === "facts") mkdirSync(join(brain, "workspaces/ithaca"), { recursive: true }); capture = captures[scenario] = { sessions: [], exchanges: [], appends: [] }; let backend = createPiBackend({ brainPath: brain, sessionDir: join(scratch, `sessions-${scenario}`), loadExtensions: false, profiles: [{ id: "fixture", label: "Fixture", vendor: "openai", model: "gpt-4o-mini", thinkingLevel: "off" }], confirmBashPatterns: [] }); @@ -78,7 +79,7 @@ try { if (scenario === "repository" && turnIndex) changeRepository(brain, turnIndex); const facts = scenario === "facts" ? turnIndex : 0; const controller = new AbortController(); - const sandbox = prepareFixtureWorkerSandbox(brain, { profile: "strict", ...(scenario === "promotion" ? {} : { areas: [] }) }); + const sandbox = prepareFixtureWorkerSandbox(brain, { profile: "strict", ...(scenario === "facts" ? { areas: ["workspaces"], codeChanges: turnIndex === 1 } : scenario === "promotion" ? {} : { areas: [] }) }); const frames: ServerMessage[] = []; const timer = setTimeout(() => controller.abort(), 30_000); try { @@ -135,6 +136,7 @@ try { voiceCapture.voiceRefusal = { message, before, after: requestCount() }; scenario = "budget"; brain = fixtureBrain(scratch, scenario); + if (scenario === "facts") mkdirSync(join(brain, "workspaces/ithaca"), { recursive: true }); capture = captures[scenario] = { sessions: [], exchanges: [], appends: [] }; sequence = 0; const hosted = historyHost(brain, createPiBackend({ brainPath: brain, sessionDir: join(scratch, "sessions-budget"), loadExtensions: false, diff --git a/packages/ui-backend-pi/tests/provider-history.test.ts b/packages/ui-backend-pi/tests/provider-history.test.ts index 867c20f61a..1cfb2aef4d 100644 --- a/packages/ui-backend-pi/tests/provider-history.test.ts +++ b/packages/ui-backend-pi/tests/provider-history.test.ts @@ -174,3 +174,19 @@ test("retained legacy policy wording and earlier taint facts stay byte-identical expect(exchanges.at(-1)!.raw, "SAFETY_REVIEW_NEVER_REWRITES_EARLIER_FACTS").toContain("This session is tainted"); expect(JSON.stringify(messages(exchanges.at(-1)!).at(-1)), "SAFETY_REVIEW_CHANGES_ONLY_NEW_TAIL_FACTS").not.toContain("This session is tainted"); }); + + +test("workspace mode changes appear only in the new tail and preserve the provider prefix (#4295)", () => { + const capture = captures.facts!; + const first = main(capture).find(exchange => exchange.turn === 0)!; + expect(first.raw, "INSPECT_FIRST_TAIL_NAMES_WRITE_OPT_IN").toContain("code-changes switch"); + for (const [a, b] of pairs(capture)) { + identical(body(a).tools, body(b).tools, "WORKSPACE_MODE_TOOLS_STABLE"); + identical(system(a), system(b), "WORKSPACE_MODE_SYSTEM_STABLE"); + history(a, b); + } + const changed = main(capture).find(exchange => exchange.turn === 1)!; + expect(JSON.stringify(messages(changed).at(-1)), "CHANGE_MODE_IN_NEW_TAIL").toContain("is writable: clone, fetch and commit"); + const inspect = main(capture).find(exchange => exchange.turn === 2)!; + expect(JSON.stringify(messages(inspect).at(-1)), "INSPECT_MODE_RETURNS_IN_NEW_TAIL").toContain("code-changes switch"); +}); diff --git a/packages/ui-backend-pi/tests/worker-rpc.test.ts b/packages/ui-backend-pi/tests/worker-rpc.test.ts index bd023b68b3..cdfdc42a3e 100644 --- a/packages/ui-backend-pi/tests/worker-rpc.test.ts +++ b/packages/ui-backend-pi/tests/worker-rpc.test.ts @@ -4,7 +4,7 @@ * End-to-end refusals from a real worker stay in tests/pi-worker-runtime. */ import { afterEach, beforeEach, expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import type { NativeFileVersions } from "@schlessera/brain-ui-sdk/internal"; @@ -151,7 +151,7 @@ test("permission denies an application tool without a server route, and gates ev expect(decision.behavior).toBe("allow"); expect(context.grants.get("call-1")).toEqual({ name: "read_file", input: JSON.stringify({ path: "notes/ithaca.md" }) }); // A governed host sandbox keeps native write_file: it is gated, not routed. - const governed = harness({ workerSandbox: { profile: "governed" } as PiWorkerRpcContext["workerSandbox"] }, { applyBrain: async () => ({ ok: true }) as never }); + const governed = harness({ workerSandbox: { brain: root, restricted: false, profile: "governed", areas: [], scratchAliasesRemoved: [] } }, { applyBrain: async () => ({ ok: true }) as never }); await governed.dispatch(rpc("permission", "write_file", { path: "notes/ithaca.md", content: "home" })); expect(governed.context.grants.get("call-1")?.name).toBe("write_file"); }); @@ -249,3 +249,46 @@ test("an allow the collector's last check refuses is denied, and its grant never expect(context.grants.has("call-refused"), "PI_UNCHECKED_ALLOW_LEAVES_NO_GRANT").toBe(false); expect(refused, "PI_UNCHECKED_ALLOW_IS_REFUSED").toEqual([["call-refused", true]]); }); + +test.each([true,false])("post-failure remedies use the resolved Pi sandbox (host supplied=%s)", async supplied => { + const sandbox={brain:root,profile:"governed" as const,restricted:false,scratchAliasesRemoved:[],areas:[{name:"workspaces" as const,rel:"workspaces",mount:{writable:false as const,readOnlyPath:join(root,"workspaces"),reason:"inspection"}}]}; + const recorded:string[]=[]; + const {dispatch}=harness({sandbox,workerSandbox:supplied?sandbox:undefined},{inputSafety:{ready:async()=>{},begin:async()=>{},allowed:async()=>{},result:async(_id:string,_name:string,output:string)=>{recorded.push(output);}} as never}); + for(const command of ["npm install --dry-run","bun test","npm help install","npm ls build","npm install","npm i","npm ci","npm clean-install","mkdir workspaces/ithaca/build","mkdir -p workspaces/ithaca/build","git add raft.md","pnpm add ithaca","yarn run build","bun run build"]){ + const id=command; + expect(await dispatch(rpc("permission","bash",{command:`cd workspaces/ithaca && ${command}`},id)),"PI_VERIFICATION_RUNS_BEFORE_ANY_REFUSAL").toMatchObject({behavior:"allow"}); + const answer=await dispatch(rpc("safetyResult","bash",{output:`EROFS: Read-only file system, open '${root}/workspaces/ithaca/package-lock.json'`,failed:true},id)); + expect(answer,"SELF_RESOLVED_SANDBOX_HAS_BOTH_REMEDIES").toMatchObject({workspaceNote:expect.stringContaining("managed worktree")}); + expect(await dispatch(rpc("safetyResult","bash",{output:"mkdir: cannot create directory '/outside/raft': Read-only file system",failed:true},id)),"PI_OUTSIDE_READ_ONLY_FAILURE_HAS_CONDITIONAL_ADVICE").toMatchObject({workspaceNote:"If this write was under workspaces/, the checkout is read-only in this turn: switch on code changes for this session (applies from the next message) or use a managed worktree."}); + expect(recorded.at(-1),"NOTE_RECORDED_BEFORE_DELIVERY").toContain("switch on code changes for this session"); + expect(await dispatch(rpc("safetyResult","bash",{output:`open '${root}/workspaces/ithaca/README.md'\n/bin/bash: /tmp/readonly/raft.md: Permission denied`,failed:true},id)),"PLAIN_PERMISSION_FAILURE_IS_NOT_A_READ_ONLY_DIAGNOSTIC").toEqual({ok:true}); + expect(await dispatch(rpc("safetyResult","bash",{output:"all tests passed"},id)),"SUCCESSFUL_VERIFICATION_HAS_NO_REFUSAL").toEqual({ok:true}); + expect(await dispatch(rpc("safetyResult","bash",{output:"assertion failed",failed:true},id)),"NORMAL_TEST_FAILURE_HAS_NO_REFUSAL").toEqual({ok:true}); + } +}); + + +test.each([ + ["mkdir", "mkdir: cannot create directory 'workspaces/ithaca/build': Read-only file system"], + ["mkdir -p", "mkdir: cannot create directory 'workspaces/ithaca/build': Read-only file system"], + ["git add", "fatal: Unable to create 'workspaces/ithaca/.git/index.lock': Read-only file system"], + ["npm install", "npm error code EROFS"], + ["outside write", "touch: cannot touch '/outside/raft': Read-only file system"], +])("Pi's installed Agent hook appends and records the post-failure remedy once: %s",async(_command,diagnostic)=>{ + const {Agent}=await import("@earendil-works/pi-agent-core"),{installPiToolSafety}=await import("../src/tool-safety.js"),{safetyResultInput}=await import("../src/worker-protocol.js"); + const sandbox={brain:root,profile:"strict" as const,restricted:false,scratchAliasesRemoved:[],areas:[{name:"workspaces" as const,rel:"workspaces",mount:{writable:false as const,readOnlyPath:join(root,"workspaces"),reason:"inspection"}}]}; + const recorded:string[]=[];const {dispatch}=harness({sandbox},{inputSafety:{begin:async()=>{},allowed:async()=>{},result:async(_id:string,_name:string,output:string)=>{recorded.push(output);}} as never}); + const agent=new Agent({streamFn:()=>{throw new Error("No inference in this hook test");}}); + installPiToolSafety(agent,{permission:(name,id,input)=>dispatch(rpc("permission",name,input,id)) as never,result:async(name,id,content,complete,failed)=>{const answer=await dispatch(rpc("safetyResult",name,safetyResultInput(name,content,complete,failed),id)) as {workspaceNote?:string};return answer.workspaceNote;},stop(){}},()=>false); + const {createBrainToolKit}=await import("../src/tool-kit.js"),{createBrainAccess}=await import("../src/brain-access.js"),{bashTool}=await import("../src/file-tools.js"),{toolLockFromKeyed}=await import("../src/tools.js"),{createKeyedLock}=await import("@schlessera/brain-ui-sdk/server"); + mkdirSync(join(root,"workspaces/ithaca"),{recursive:true}); + const kit=createBrainToolKit({brain:createBrainAccess(root),turn:createTurnContext(),lock:toolLockFromKeyed(createKeyedLock()),exec:{}}); + const args={command:`printf %s ${"'"+diagnostic.replaceAll("'", "'\"'\"'")+"'"} >&2; exit 1`}; + const result=await bashTool(kit).execute("verify",args,undefined,undefined,{} as never); + expect((result.details as {exitCode: number}).exitCode,"REAL_BASH_USES_EXIT_CODE_DETAILS").toBe(1); + const context={toolCall:{id:"verify",name:"bash"},args,result,isError:false} as never; + expect(await agent.beforeToolCall!(context),"INSTALLED_AGENT_ADMITS_VERIFICATION").toBeUndefined(); + const answer=await agent.afterToolCall!(context); + expect(answer!.content,"INSTALLED_AGENT_DELIVERS_REMEDY_AFTER_BASH_EXIT_FAILURE").toEqual([...result.content,{type:"text",text:expect.stringContaining("switch on code changes for this session")}]); + expect(recorded).toHaveLength(1);expect(recorded[0]).toContain("managed worktree"); +}); diff --git a/packages/ui-backend-pi/tests/worker-session.test.ts b/packages/ui-backend-pi/tests/worker-session.test.ts index 7f14b75629..6c0f7ec84a 100644 --- a/packages/ui-backend-pi/tests/worker-session.test.ts +++ b/packages/ui-backend-pi/tests/worker-session.test.ts @@ -1,6 +1,6 @@ import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; -import { mkdtempSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, mkdirSync, linkSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; import { PassThrough, Readable, Writable } from "node:stream"; @@ -594,3 +594,28 @@ test("Pi reports a stranded launch charge once without scheduling an impossible bytes: 0, turnTempBytes: ledger.turnTempHeld, errorClass: "Error", message: String(failure) }); } finally { cleanup.close(); stderr.mockRestore(); owner.mockRestore(); ledgerSpy.mockRestore(); } }); + + +test("Pi handoff preparation keeps its legacy provider append without granting code writes",async()=>{ + mkdirSync(join(brain,"workspaces/ithaca"),{recursive:true}); + const autonomous={origin:"autonomous" as const,persistence:"none" as const,allowedTools:[],systemPromptAppend:"Summarise the voyage so far."}; + await createPiBackend({brainPath:brain,sessionDir,loadExtensions:false}).startTurn({prompt:"Summarise Ithaca.",signal:new AbortController().signal,autonomous,enforceAllowedTools:true,noGrantSurface:true,bridge:{emit(){},checkpointPermission(){},requestPermission:async()=>({behavior:"deny",message:"no tools"})}}); + expect(receivedInit.sandboxNote,"PI_HANDOFF_PRESERVES_LEGACY_AREA_TEXT").toContain("is writable: clone, fetch and commit"); + expect(receivedInit.sandboxNote).not.toContain("code-changes switch"); + expect(launch.mock.calls.at(-1)![0].sandbox.areas.find((area:any)=>area.name==="workspaces").mount.writable,"RENDERING_COMPATIBILITY_CANNOT_GRANT_WRITES").toBe(false); + const {createSessionResources}=await import("../src/session-resources.js"),{createBrainAccess}=await import("../src/brain-access.js"),{toolLockFromKeyed}=await import("../src/tools.js"),{createKeyedLock}=await import("@schlessera/brain-ui-sdk/server"); + const caps=receivedInit.env.caps,resources=createSessionResources({backend:{brainPath:brain,loadExtensions:false},brain:createBrainAccess(brain),lock:toolLockFromKeyed(createKeyedLock()),allowedTools:new Set(),confirmPatterns:[],loadExtensions:false,sandboxNote:receivedInit.sandboxNote}); + const {loader}=await resources.build(resources.buildToolkit(caps),{caps,autonomous}); + expect(loader.getAppendSystemPrompt(),"PI_REAL_RESOURCE_LOADER_KEEPS_HANDOFF_PROMPT").toContain(`${autonomous.systemPromptAppend}\n\n${receivedInit.sandboxNote}`); +}); + + +test("ordinary hostless Pi describes absent workspaces as inspection in later turns",async()=>{ + await turn(null);expect(receivedInit.sandboxNote,"HOSTLESS_PI_NEVER_PROMISES_FUTURE_CODE_WRITES").not.toContain("makes it writable in later turns");expect(receivedInit.sandboxNote).toContain("ordinary retained and charged brain content");expect(receivedInit.sandboxNote).toContain("code-changes switch"); +}); + +test("Pi handoff keeps legacy alias refusal without inventing a writable area",async()=>{ + mkdirSync(join(brain,"workspaces/ithaca"),{recursive:true});writeFileSync(join(brain,"raft.md"),"Athena");linkSync(join(brain,"raft.md"),join(brain,"workspaces/ithaca/alias.md")); + await createPiBackend({brainPath:brain,sessionDir,loadExtensions:false}).startTurn({prompt:"Summarise Ithaca.",signal:new AbortController().signal,enforceAllowedTools:true,noGrantSurface:true,autonomous:{origin:"autonomous",persistence:"none",allowedTools:[],systemPromptAppend:"Summarise the voyage."},bridge:{emit(){},checkpointPermission(){},requestPermission:async()=>({behavior:"deny",message:"no tools"})}}); + expect(receivedInit.sandboxNote,"PI_HANDOFF_PRESERVES_ACTUAL_LEGACY_REFUSAL").toContain("hard-linked to files outside workspaces/");expect(receivedInit.sandboxNote).not.toContain("is writable: clone, fetch and commit"); +}); diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index d6a4ecb9ac..833430ea12 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -28,7 +28,7 @@ export { hostProviderCredential, hostComputeCredential } from "./config/env.js"; export type { EgressDestinationPolicy, EgressRecord, EgressRefusal } from "./server/egress-proxy.js"; export { restrictedReadPaths } from "./server/worker-launcher.js"; export { prepareWorkerSandbox, prepareWorkerSandboxAsync } from "./server/worker-launcher.js"; -export { workerProfile, workerSandboxNote, workerSandboxWarnings, mountPointsUnder, BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR, WORKER_XDG_DIRS } from "./server/worker-sandbox.js"; +export { resolveWorkspacesMount, workerProfile, workerSandboxNote, workerSandboxWarnings, mountPointsUnder, BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR, WORKER_XDG_DIRS } from "./server/worker-sandbox.js"; export type { WorkerSandbox, WorkerNoteFacts, WorkerNoteLimit, WorkerProviderMasks, WorkerDataTree } from "./server/worker-sandbox.js"; export { createLimitTracker, limitFailureMessage, mergeLimitReports, workerLimitsPlan, workerLimitsStatus, workerNoteLimits } from "./server/worker-limits.js"; export type { WorkerLimitReport, WorkerLimitsPlan, WorkerLimitsStatus } from "./server/worker-limits.js"; @@ -101,3 +101,5 @@ export { nativeObservationIdentity } from "./server/native-observation-storage.j export { createCleanupReconciler, processCleanupReconciler, CLEANUP_RETRY_ATTEMPTS, CLEANUP_RETRY_BASE_MS, CLEANUP_RETRY_MAX_MS } from "./server/cleanup-reconciler.js"; export type { CleanupNotice, CleanupReconciler, CleanupReconcilerOptions, RetainedCleanup } from "./server/cleanup-reconciler.js"; + +export { workspaceWriteRefusal } from "./server/workspace-refusal.js"; diff --git a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts index bfb9b44c30..94af1423bc 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -1,6 +1,9 @@ /** Concrete host-only protocol. No request accepts host paths, commands, caller-selected UIDs or mount authority. */ import { z } from "zod"; +/** Worst-case JSON escaping of the longest accepted metadata path plus fixed identities. */ +export const NATIVE_REQUEST_BYTES = 512 * 1024; + export const nativeCheckpointId = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); /** One published entry in a view: a plain lowercase name that can never be a root identity or a hidden or relative entry. */ export const nativePoolName = z.string().regex(/^[a-z0-9][a-z0-9._@+-]{0,127}$/).refine(name => !nativeCheckpointId.safeParse(name).success); @@ -15,15 +18,15 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ z.object({ operation: z.literal("inspectStage"), id: nativeCheckpointId }).strict(), z.object({ operation: z.literal("releaseStage"), id: nativeCheckpointId }).strict(), z.object({ operation: z.literal("readCheckpoint"), id: nativeCheckpointId, - action: z.enum(["file", "stat", "list"]), path: z.string().max(4096).refine(path => !path.startsWith("/") && !path.includes("\0") && - (!path || path.split("/").length <= 256 && path.split("/").every(part => part && part !== "." && part !== ".."))), + action: z.enum(["file", "stat", "list"]), path: z.string().max(65535).refine(path => !path.startsWith("/") && !path.includes("\0") && + (!path || path.split("/").length <= 32768 && path.split("/").every(part => part && part !== "." && part !== ".."))), maximum: z.number().int().nonnegative(), - }).strict(), + }).strict().refine(request => request.action === "stat" || request.path.length <= 4096 && request.path.split("/").length <= 256), z.object({ operation: z.literal("readStage"), id: nativeCheckpointId, - action: z.enum(["file", "stat", "list"]), path: z.string().max(4096).refine(path => !path.startsWith("/") && !path.includes("\0") && - (!path || path.split("/").length <= 256 && path.split("/").every(part => part && part !== "." && part !== ".."))), + action: z.enum(["file", "stat", "list"]), path: z.string().max(65535).refine(path => !path.startsWith("/") && !path.includes("\0") && + (!path || path.split("/").length <= 32768 && path.split("/").every(part => part && part !== "." && part !== ".."))), maximum: z.number().int().nonnegative(), - }).strict(), + }).strict().refine(request => request.action === "stat" || request.path.length <= 4096 && request.path.split("/").length <= 256), z.object({ operation: z.literal("cancelCheckpointRead"), id: nativeCheckpointId }).strict(), // Turn data trees (#2911): one app-owned directory per turn on the managed // volume, outside the live brain and every checkpoint. The manager alone @@ -55,10 +58,10 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ z.object({ operation: z.literal("poolCheckpoint"), id: nativeCheckpointId, from: nativeCheckpointId }).strict(), z.object({ operation: z.literal("poolDelta"), from: nativeCheckpointId, to: nativeCheckpointId }).strict(), z.object({ operation: z.literal("poolReadCheckpoint"), id: nativeCheckpointId, - action: z.enum(["file", "stat", "list"]), path: z.string().max(4096).refine(path => !path.startsWith("/") && !path.includes("\0") && - (!path || path.split("/").length <= 256 && path.split("/").every(part => part && part !== "." && part !== ".."))), + action: z.enum(["file", "stat", "list"]), path: z.string().max(65535).refine(path => !path.startsWith("/") && !path.includes("\0") && + (!path || path.split("/").length <= 32768 && path.split("/").every(part => part && part !== "." && part !== ".."))), maximum: z.number().int().nonnegative(), - }).strict(), + }).strict().refine(request => request.action === "stat" || request.path.length <= 4096 && request.path.split("/").length <= 256), z.object({ operation: z.literal("poolAccessOpen"), access: nativeCheckpointId }).strict(), z.object({ operation: z.literal("poolAccess"), id: nativeCheckpointId, access: nativeCheckpointId }).strict(), z.object({ operation: z.literal("poolPark"), id: nativeCheckpointId, expectedAccess: nativeCheckpointId.optional() }).strict(), @@ -279,6 +282,7 @@ export interface NativePoolGrowth { } /** The privileged helper inspects only its bounded upper layer after the worker exits. */ export interface NativeStageChange { pathHex: string; kind: "entry" | "whiteout" | "opaque" } +/** Control replies, intents and stage rows retain their independent 64 KiB bound. */ export const NATIVE_CONTROL_BYTES = 64 * 1024; export const NATIVE_DATA_CHUNK_BYTES = 64 * 1024; /** Transport work bounds, configurable; neither is a history/object/change quota. */ diff --git a/packages/ui-sdk/src/server/native-brain-manager.ts b/packages/ui-sdk/src/server/native-brain-manager.ts index a5946cc983..ad0c2dc799 100644 --- a/packages/ui-sdk/src/server/native-brain-manager.ts +++ b/packages/ui-sdk/src/server/native-brain-manager.ts @@ -9,7 +9,7 @@ import { constants, openSync, closeSync, fsyncSync, fstatSync, writeFileSync, re mkdirSync, chmodSync, chownSync, readdirSync, realpathSync, existsSync, unlinkSync, ftruncateSync } from "node:fs"; import { dirname, isAbsolute, join, relative } from "node:path"; import { nativeCheckpointId, nativeManagerRequest, nativeManagerFrame, NativeBrainManagerError, NATIVE_CONTROL_BYTES, NATIVE_DATA_CHUNK_BYTES, NATIVE_MANAGER_OPERATION_TIMEOUT_MS, NATIVE_MANAGER_MAX_DELTA_BYTES, - type NativeCheckpoint, type NativeManagerReady, type NativeManagerRequest, type NativeRecoveryRecord, type NativeTurnTree } from "./native-brain-manager-protocol.js"; + NATIVE_REQUEST_BYTES, type NativeCheckpoint, type NativeManagerReady, type NativeManagerRequest, type NativeRecoveryRecord, type NativeTurnTree } from "./native-brain-manager-protocol.js"; import { NATIVE_TREE_REMOVAL, nativeTurnTreeReaders } from "./native-turn-trees.js"; import { startNativeStage } from "./native-brain-stage.js"; import { randomUUID } from "node:crypto"; @@ -894,18 +894,14 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, }; } -/** Unix socket only; filesystem ownership is authentication, and workers must mask the endpoint. */ -export async function serveNativeBrainManager(config: NativeBrainManagerConfig, options: NativeBrainManagerOptions = {}) { - const fixed = Object.freeze({ ...config }), manager = await createNativeBrainManager(fixed, options); - if (existsSync(fixed.socketPath)) { await manager.close(); throw new NativeBrainManagerError("unsupported", "Native manager socket already exists; reconcile its service ownership before starting."); } - let server: ReturnType; - try { - server = Bun.serve({ unix: fixed.socketPath, maxRequestBodySize: 1024, +/** The fixed bounded Unix transport; trusted boot owns socket authentication and native qualification. */ +export function serveNativeBrainRequests(socketPath: string, manager: Pick>, "run">) { + return Bun.serve({ unix: socketPath, maxRequestBodySize: NATIVE_REQUEST_BYTES, async fetch(request) { try { if (request.method !== "POST" || new URL(request.url).pathname !== "/native-brain" || request.headers.get("content-type") !== "application/json") throw new NativeBrainManagerError("invalid", "Native manager accepts fixed JSON operations only."); - const raw = await request.text(); if (Buffer.byteLength(raw) > 1024) throw new NativeBrainManagerError("invalid", "Native request exceeded its bound."); + const raw = await request.text(); if (Buffer.byteLength(raw) > NATIVE_REQUEST_BYTES) throw new NativeBrainManagerError("invalid", "Native request exceeded its bound."); const parsed = nativeManagerRequest.safeParse(JSON.parse(raw)); if (!parsed.success) throw new NativeBrainManagerError("invalid", "Native manager operation or identity is invalid."); const response = await manager.run(parsed.data, request.signal); @@ -915,6 +911,15 @@ export async function serveNativeBrainManager(config: NativeBrainManagerConfig, } catch (error) { const known = plainError(error); return Response.json({ code: known.code, message: known.message }, { status: known.code === "invalid" ? 400 : 503 }); } }, }); +} + +/** Unix socket only; filesystem ownership is authentication, and workers must mask the endpoint. */ +export async function serveNativeBrainManager(config: NativeBrainManagerConfig, options: NativeBrainManagerOptions = {}) { + const fixed = Object.freeze({ ...config }), manager = await createNativeBrainManager(fixed, options); + if (existsSync(fixed.socketPath)) { await manager.close(); throw new NativeBrainManagerError("unsupported", "Native manager socket already exists; reconcile its service ownership before starting."); } + let server: ReturnType; + try { + server = serveNativeBrainRequests(fixed.socketPath, manager); chownSync(fixed.socketPath, 0, fixed.appGid); chmodSync(fixed.socketPath, 0o660); } catch (error) { await manager.close(); throw error; } return { socketPath: fixed.socketPath, async close() { server.stop(true); await manager.close(); } }; diff --git a/packages/ui-sdk/src/server/native-checkpoint-reader.ts b/packages/ui-sdk/src/server/native-checkpoint-reader.ts index f113b3f59b..a884c00218 100644 --- a/packages/ui-sdk/src/server/native-checkpoint-reader.ts +++ b/packages/ui-sdk/src/server/native-checkpoint-reader.ts @@ -1,6 +1,6 @@ /** Short-lived root control/FD transfer; file access happens only after dropping UID. */ import { dirname, join } from "node:path"; -import { NativeBrainManagerError } from "./native-brain-manager-protocol.js"; +import { NativeBrainManagerError, NATIVE_REQUEST_BYTES } from "./native-brain-manager-protocol.js"; import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs"; export interface NativeCheckpointReadRequest { @@ -30,7 +30,11 @@ channel,token,app_uid,worker_uid,gid,timeout,request,*root_descriptor=sys.argv[1 if root_descriptor: original=int(root_descriptor[0]);os.dup2(original,3) if original!=3:os.close(original) -app_uid=int(app_uid);worker_uid=int(worker_uid);gid=int(gid);timeout=float(timeout);request=json.loads(request) +app_uid=int(app_uid);worker_uid=int(worker_uid);gid=int(gid);timeout=float(timeout) +if request=="-": + request=sys.stdin.buffer.read(${NATIVE_REQUEST_BYTES + 1}) + if len(request)>${NATIVE_REQUEST_BYTES}:raise RuntimeError("checkpoint request exceeds transport bound") +request=json.loads(request) if os.geteuid()!=0 or worker_uid in (0,app_uid):raise RuntimeError("fixed separate reader identity required") if not stat.S_ISDIR(os.fstat(3).st_mode):raise RuntimeError("authorized root descriptor required") libc=ctypes.CDLL(None,use_errno=True);manager_pid=os.getppid();helper_pid=os.getpid() @@ -67,7 +71,7 @@ def read_child(output): root_mount=mount_identity(3) def parts(value): result=value.split("/") if value else [] - if value.startswith("/") or "\0" in value or len(result)>256 or any(p in ("",".","..") for p in result):raise ValueError("invalid relative checkpoint path") + if value.startswith("/") or "\0" in value or len(result)>(32768 if action=="stat" else 256) or any(p in ("",".","..") for p in result):raise ValueError("invalid relative checkpoint path") return result def directory(names): fd=os.dup(3) @@ -228,8 +232,8 @@ export async function startNativeCheckpointRead(options: NativeCheckpointReadTic request: NativeCheckpointReadRequest | { action: "authority"; authority: NativeStageAuthorityMetadata }; }) { const child = Bun.spawn(["/usr/bin/python3", "-I", "-S", "-c", NATIVE_CHECKPOINT_READER_PROGRAM, - options.socketPath, options.token, String(options.appUid), String(options.workerUid), String(options.appGid), String(options.timeoutMs / 1000), JSON.stringify(options.request)], { - cwd: "/", env: {}, stdio: ["ignore", "pipe", "pipe", options.rootFd], + options.socketPath, options.token, String(options.appUid), String(options.workerUid), String(options.appGid), String(options.timeoutMs / 1000), "-"], { + cwd: "/", env: {}, stdio: ["pipe", "pipe", "pipe", options.rootFd], }); const errors = new Response(child.stderr as ReadableStream).text(); const finished = child.exited.then(async code => { @@ -238,10 +242,13 @@ export async function startNativeCheckpointRead(options: NativeCheckpointReadTic }); void finished.catch(() => {}); try { + child.stdin.write(JSON.stringify(options.request)); + await child.stdin.end(); const reader = (child.stdout as ReadableStream).getReader(); let ready = ""; while (!ready.endsWith("\n")) { const first = await reader.read(); + if (first.done) await finished; // Preserve the fixed helper's refusal cause. if (first.done || ready.length + first.value.byteLength > 1024) throw new NativeBrainManagerError("unavailable", "Checkpoint reader did not establish its control channel."); ready += new TextDecoder().decode(first.value); diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 2a4d66ec73..36b517302e 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -12,7 +12,7 @@ import { BackendRequestError } from "./backend.js"; import { createWorkerFreezer } from "./worker-freezer.js"; import { createWorkerFileObserver, type ObservedWorkerFile } from "./worker-file-observer.js"; import { createWorkerPipes, createWorkerPipesSteps } from "./worker-pipes.js"; -import { runWorkerStepsAsync, runWorkerStepsSync, workerStepSleep, workerStepSpawn, type WorkerSteps } from "./worker-steps.js"; +import { runWorkerStepsAsync, runWorkerStepsSync, workerStep, workerStepSleep, workerStepSpawn, type WorkerSteps } from "./worker-steps.js"; import { hostOutputStagingLimits, DEFAULT_MAINTENANCE_TEMP_BYTES, type WorkerStateLimits, validWorkerStateBytes } from "./worker-state-limits.js"; import { WORKER_INFERENCE_DIR } from "./inference-relay.js"; import { WORKER_EGRESS_DIR } from "./egress-proxy.js"; @@ -640,9 +640,20 @@ export function workerCommand(input: WorkerLaunch): string[] { if (!within(TURN_TEMP_ROOT, scratch) || scratch === TURN_TEMP_ROOT) throw new WorkerHostError("maintenance scratch must be inside its size-limited /tmp"); } const sized = tempBytes !== undefined; - const dataTree = !maintenance && !transport ? input.sandbox?.dataTree : undefined; + const requestedDataTree = !maintenance && !transport ? input.sandbox?.dataTree : undefined; + // Both mask owners apply at the new read alias, even for a direct caller + // whose copied-tree descriptor omits the provider mask list. + const dataTree = requestedDataTree && input.sandbox?.providerMasks ? { ...requestedDataTree, + masked: [...new Set([...(requestedDataTree.masked ?? []), ...input.sandbox.providerMasks.folders])] } : requestedDataTree; if (input.sandbox?.dataTree && (maintenance || transport || workerProfile(input.sandbox) === "governed" || !input.startupView)) throw new WorkerHostError("a turn data tree belongs only to a worker on an immutable startup view"); + let workspaceSource: string | undefined; + if (dataTree && input.startupView && input.sandbox?.areas.some(area => area.name === "workspaces" && !area.mount.writable && area.mount.readOnlyPath)) { + const sealed = resolveWorkspacesMount(input.startupView.root); + if (sealed.writable || !sealed.readOnlyPath || sealed.readOnlyPath !== join(input.startupView.root, "workspaces")) + throw new WorkerHostError("The immutable workspace source is absent or unqualified; retry admission with a refreshed checkpoint."); + workspaceSource = sealed.readOnlyPath; + } const emptyHome = !input.restricted && input.env.HOME === WORKER_EMPTY_HOME; const reservedRuntimePaths = ["/proc", "/dev", scratch, WORKER_STATE, ...(emptyHome ? [WORKER_EMPTY_HOME] : []), WORKER_AREA_ROOT, WORKER_DATA_ROOT, WORKER_WORKTREE_ROOT, WORKER_REFERENCE_ROOT, WORKER_XDG_HOME, WORKER_INFERENCE_DIR, WORKER_EGRESS_DIR, WORKER_PROVIDER_RELAY_DIR, WORKER_MODULE_GITHUB_DIR, MAINTENANCE_HOME, ...Object.values(MAINTENANCE_XDG_DIRS), "/tmp/brain-maintenance-output", @@ -656,6 +667,14 @@ export function workerCommand(input: WorkerLaunch): string[] { validateRuntimePlacement(path, reservedRuntimePaths); } const writable = sandboxMounts(input, brain, scratch, input.stateBytes !== undefined ? WORKER_STATE : undefined); + // A strict writer has a second alias for every staged writable area. Repeat + // folder masks there too, including a mask that covers the whole area. + const stagedProviderMaskRoots = input.areaOutput && input.sandbox && workerProfile(input.sandbox) === "strict" + ? [...new Set(input.sandbox.areas.filter(area => area.mount.writable).flatMap(area => { + const target = `${WORKER_AREA_ROOT}/${area.name}`; + return (input.sandbox?.providerMasks?.folders ?? []).flatMap(folder => isWithin(folder, area.rel) ? [target] + : isWithin(area.rel, folder) ? [join(target, folder.slice(area.rel.length + 1))] : []); + }))].filter((path, _at, roots) => !roots.some(other => other !== path && isWithin(other, path))) : []; const runtimeViewMounts = [ ...(input.restricted ? restrictedMounts(input.restricted, brain) : []), ...(transport ? transportMounts(transport, brain) : maintenance ? maintenanceMounts(maintenance, brain) : input.sandbox?.profile ? maintenanceMounts({ @@ -700,24 +719,40 @@ export function workerCommand(input: WorkerLaunch): string[] { }), ] : []), ...(sized ? ["--dir", scratch] : ["--tmpfs", scratch]), ...writable.binds, - ...(input.sandbox?.profile === "governed" && input.sandbox.protection ? protectedWorkerMounts(brain, input.sandbox.protection, input.sandbox.retainedFolders) : []), + ...writable.readOnlyBinds, + // Workspace ancestor pins stay read-only; quarantine child masks come last. + ...(input.sandbox?.profile === "governed" && input.sandbox.protection ? protectedWorkerMounts(brain, input.sandbox.protection, input.sandbox.retainedFolders, + writable.workspaceReadOnly ? ["workspaces"] : []) : []), ...(input.sandbox?.providerMasks && !maintenance && !transport ? providerMaskMounts(brain, input.startupView?.root ?? brain, input.sandbox.providerMasks) : []), + ...stagedProviderMaskRoots.flatMap(path => ["--tmpfs", path, "--remount-ro", path]), // The turn's data tree: brain tools read documents and the index there, // configuration from the frozen view above (#2848). - ...(dataTree ? dataTreeMounts(brain, WORKER_DATA_ROOT, dataTree) : []), + ...(dataTree ? dataTreeMounts(brain, WORKER_DATA_ROOT, dataTree, workspaceSource) : []), "--clearenv"]; // Last: neither a complete view nor a protected-path bind may restore a // secret over an earlier mask. The masks are about reads, not writes. if (!maintenance) { const clear = argv.pop(); - const copies = input.areaOutput && input.sandbox?.profile === "strict" + const copies = input.areaOutput && input.sandbox && workerProfile(input.sandbox) === "strict" ? input.sandbox.areas.filter(area => area.mount.writable).map(area => ({ from: join(brain, area.rel), to: `${WORKER_AREA_ROOT}/${area.name}` })) : []; + if (workspaceSource) copies.push({ from: join(brain, "workspaces"), to: join(WORKER_DATA_ROOT, "workspaces") }); // An agent worker's host view covers the host files too (#4259); a restricted or transport root has none of them. const hostFiles = input.restricted || transport ? [] : HOST_FILE_MASKS.flatMap(path => { try { return statSync(path).isFile() ? ["--ro-bind", "/dev/null", path] : []; } catch { return []; } }); - argv.push(...maintenanceEnvMasks(input.startupView?.root ?? brain, brain, copies), ...hostFiles, clear!); + const envMasks = maintenanceEnvMasks(input.startupView?.root ?? brain, brain, copies); + const hidden = [...stagedProviderMaskRoots, ...(input.sandbox?.providerMasks?.folders ?? []).map(rel => join(brain, rel)), + ...(dataTree?.masked ?? []).map(rel => join(WORKER_DATA_ROOT, rel))]; + // A provider mask already hides the target. Do not create a secret-mask + // mountpoint inside its empty read-only tree; every other alias is masked. + for (let at = 0; at < envMasks.length;) { + const directory = envMasks[at] === "--tmpfs", count = directory ? 4 : 3; + const target = envMasks[at + (directory ? 1 : 2)]!; + if (!hidden.some(root => isWithin(root, target))) argv.push(...envMasks.slice(at, at + count)); + at += count; + } + argv.push(...hostFiles, clear!); } // A private tmpfs of exactly the allowance. Nothing on the host backs it, @@ -879,7 +914,7 @@ const gated = (input: Pick) => inp * `home` input does not select or validate it. */ function sandboxMounts(input: WorkerLaunch, brain: string, scratch: string, state: string | undefined) { - const out = { binds: [] as string[], env: [] as string[] }; + const out = { binds: [] as string[], readOnlyBinds: [] as string[], env: [] as string[], workspaceReadOnly: false }; const sandbox = input.sandbox; if (!sandbox) return out; if (sandbox.brain !== brain || sandbox.restricted !== Boolean(input.restricted)) { @@ -888,10 +923,27 @@ function sandboxMounts(input: WorkerLaunch, brain: string, scratch: string, stat if (sandbox.restricted && (sandbox.areas.length || sandbox.home)) { throw new WorkerHostError("a restricted worker has no writable areas or home"); } - for (const { name, rel, mount } of sandbox.areas) { + // Direct callers must receive the same sealing as resolver-produced plans. + const areas = sandbox.profile === "governed" && !sandbox.areas.some(area => area.name === "workspaces") + ? [...sandbox.areas, { name: "workspaces" as const, rel: WORKER_AREAS.workspaces, mount: resolveWorkspacesMount(brain) }] : sandbox.areas; + for (const { name, rel, mount } of areas) { // The note names each area by `rel`; it must be the area's own path. if (rel !== WORKER_AREAS[name]) throw new WorkerHostError(`the ${name} area is not at ${WORKER_AREAS[name]}/`); - if (!mount.writable) continue; + if (!mount.writable) { + if (name === "workspaces" && sandbox.profile === "governed") { + const qualified = resolveWorkspacesMount(brain); + if (mount.missing) { + // Absence needs no overlay. Creation remains ordinary journaled content. + if (qualified.writable || !qualified.missing) throw new WorkerHostError("workspaces/ appeared before launch; retry admission"); + } else { + if (!mount.readOnlyPath || qualified.writable || qualified.readOnlyPath !== mount.readOnlyPath) + throw new WorkerHostError("the read-only workspaces area could not be qualified at launch"); + out.readOnlyBinds.push("--ro-bind", mount.readOnlyPath, join(brain, rel)); + out.workspaceReadOnly = true; + } + } + continue; + } const path = mount.path; const info = lstatSync(path, { throwIfNoEntry: false }); if (path !== join(brain, rel) || !info?.isDirectory() || realpathSync(path) !== path @@ -949,6 +1001,10 @@ export interface PrepareWorkerSandboxOptions { home?: string; /** Which writable areas this worker gets. Default: all of them. */ areas?: readonly WorkerAreaName[]; + /** Opt in to writable workspace mounts and their alias scan. Default: inspection only. */ + codeChanges?: boolean; + /** Preserve separately qualified historical wording for toolless/read-only handoffs. */ + legacyWorkspaceNote?: boolean; } /** @@ -978,20 +1034,50 @@ function* prepareWorkerSandboxSteps(brainPath: string, options: PrepareWorkerSan ...(options.restricted ? {} : { home: { mode: "xdg" } }) }; } if (options.restricted) return { brain, restricted: true, areas: [], scratchAliasesRemoved: [] }; + // Freeze the existing-directory qualification before protection can prepare parents. + let workspaceMount: ReturnType; + try { workspaceMount = resolveWorkspacesMount(brain); } + catch (error) { workspaceMount = { writable: false, reason: `workspaces/ could not be checked (${(error as Error).message})` }; } + let preparedScratch: Awaited> | undefined; + const wantsScratch = options.areas?.includes("scratch") ?? true; + if (wantsScratch) { + try { preparedScratch = yield* resolveScratchMountSteps(brain, options.maintenance); } + catch (error) { preparedScratch = { mount: { writable: false, reason: `.brain/scratch/ could not be checked (${(error as Error).message})` }, removed: [] }; } + } + // Qualification never creates its own prerequisite. Scratch cleanup precedes + // the original writer alias scan, as before inspection became the default. + if (options.codeChanges && !workspaceMount.writable && workspaceMount.readOnlyPath && (options.areas?.includes("workspaces") ?? true)) workspaceMount = resolveWorkspacesMount(brain, undefined, true); + let legacyWorkspaces: typeof workspaceMount | undefined; + if (options.legacyWorkspaceNote) { + legacyWorkspaces = yield* workerStep(() => resolveWorkspacesMount(brain, undefined, true), async () => { + const module = Bun.resolveSync("./worker-sandbox", import.meta.dir); + const program = `import {resolveWorkspacesMount} from ${JSON.stringify(module)}; console.log(JSON.stringify(resolveWorkspacesMount(process.argv[1],undefined,true)));`; + const process = Bun.spawn([globalThis.process.execPath, "--no-env-file", "--eval", program, brain], { cwd: "/", env: {}, stdout: "pipe", stderr: "pipe" }); + const [output, error, exit] = await Promise.all([new Response(process.stdout).text(), new Response(process.stderr).text(), process.exited]); + if (exit !== 0) throw new WorkerHostError(`Historical workspace qualification failed: ${error}`); + return JSON.parse(output) as typeof workspaceMount; + }); + } const resolved = options.profile === "governed" ? resolveWorkerProtection(brain, { paths: options.protectedPaths, appeared: options.appearedPaths, folderPaths: options.folderPaths, + readOnlyRoots: workspaceMount.writable ? [] : ["workspaces"], }) : undefined; const areas: WorkerArea[] = []; let removed: string[] = []; - for (const name of options.areas ?? (Object.keys(WORKER_AREAS) as WorkerAreaName[])) { + const requestedAreas = options.areas ?? (Object.keys(WORKER_AREAS) as WorkerAreaName[]); + // A governed brain stays writable elsewhere even with an empty writable-area + // list. Always seal its workspace root unless that area was explicitly requested. + const areaNames = options.profile === "governed" && !requestedAreas.includes("workspaces") + ? [...requestedAreas, "workspaces" as const] : requestedAreas; + for (const name of areaNames) { // A check that fails unexpectedly (EACCES on the way, an unreadable mount // table) leaves the area read-only for the turn rather than failing it. try { if (name === "scratch") { - const scratch = yield* resolveScratchMountSteps(brain, options.maintenance); + const scratch = preparedScratch!; removed = scratch.removed; areas.push({ name, rel: WORKER_AREAS[name], mount: scratch.mount }); - } else areas.push({ name, rel: WORKER_AREAS[name], mount: resolveWorkspacesMount(brain) }); + } else areas.push({ name, rel: WORKER_AREAS[name], mount: workspaceMount }); } catch (error) { const code = (error as NodeJS.ErrnoException).code ?? (error instanceof Error ? error.message : String(error)); areas.push({ name, rel: WORKER_AREAS[name], mount: { writable: false, reason: `${WORKER_AREAS[name]}/ could not be checked (${code})` } }); @@ -1000,11 +1086,17 @@ function* prepareWorkerSandboxSteps(brainPath: string, options: PrepareWorkerSan // No per-turn home overlay: bubblewrap resolves an overlay's upper // directory on the host, where no size-limited mount can hold it (#1703). const home: WorkerHome = { mode: "xdg" }; - return { brain, restricted: false, areas, scratchAliasesRemoved: removed, + const workspace = areas.find(area => area.name === "workspaces"); + // An unqualified root cannot be restored over a writable brain. Keep the + // entire immutable view when a symlink or mount topology prevents sealing it. + const workspaceFallback = options.profile === "governed" && workspace && !workspace.mount.writable + && !workspace.mount.missing && !workspace.mount.readOnlyPath ? workspace.mount.reason : undefined; + return { brain, restricted: false, codeChanges: options.codeChanges === true, areas, scratchAliasesRemoved: removed, + ...(legacyWorkspaces ? { noteFacts: { legacyWorkspaces } } : {}), ...(options.folderPaths?.length ? { retainedFolders: Object.freeze([...options.folderPaths]) } : {}), - ...(options.profile ? { profile: resolved?.reason ? "strict" as const : options.profile, + ...(options.profile ? { profile: resolved?.reason || workspaceFallback ? "strict" as const : options.profile, ...(resolved ? { protection: resolved.protection } : {}), - ...(resolved?.reason ? { fallbackReason: resolved.reason } : {}), + ...(resolved?.reason || workspaceFallback ? { fallbackReason: resolved?.reason ?? workspaceFallback } : {}), readPaths: options.readPaths, maskPaths: options.maskPaths } : {}), // Profile workers never restore the host home over its mask. home }; diff --git a/packages/ui-sdk/src/server/worker-protection.ts b/packages/ui-sdk/src/server/worker-protection.ts index 21bcccc3d2..e1055b087c 100644 --- a/packages/ui-sdk/src/server/worker-protection.ts +++ b/packages/ui-sdk/src/server/worker-protection.ts @@ -59,6 +59,10 @@ function checkTree(fd: number, rel: string, count: { value: number }, brain: str /** Prepare missing directories through descriptors; never create placeholder files. */ export function resolveWorkerProtection(brain: string, options: { paths?: readonly string[]; appeared?: readonly string[]; folderPaths?: readonly string[]; + /** Do not create protected ancestors inside an inspection mount. */ + readOnlyRoots?: readonly string[]; + /** Inspect status without preparing any path on the live brain. */ + prepare?: boolean; } = {}): { protection: WorkerProtection; reason?: string } { const paths: ProtectedWorkerPath[] = []; const ancestors = new Set(); @@ -77,21 +81,30 @@ export function resolveWorkerProtection(brain: string, options: { throw new Error(scan.unverified ?? (scan.outside.length ? `the brain has hardlinks outside it: ${scan.outside.slice(0, 3).join(", ")}` : "the brain's aliases could not be verified")); } } - for (const rel of names) { + protectedName: for (const rel of names) { if (!rel || rel.startsWith("/") || rel.split("/").some(part => !part || part === "." || part === "..")) throw new Error("invalid protected path"); const segments = rel.split("/"); let fd = openDirectory(at(root, ".")); try { for (let i = 0; i < segments.length - 1; i++) { const path = at(fd, segments[i]!); - if (!lstatSync(path, { throwIfNoEntry: false })) mkdirSync(path, { mode: 0o755 }); + if (!lstatSync(path, { throwIfNoEntry: false })) { + const ancestor = segments.slice(0, i + 1).join("/"); + if (options.readOnlyRoots?.some(area => isWithin(area, ancestor))) + throw new Error(`${ancestor} is read-only; cannot create a protected-path ancestor`); + if (options.prepare === false) { + paths.push({ rel, mode: "absent", reason: "protected path is absent; prepared at admission" }); + continue protectedName; + } + mkdirSync(path, { mode: 0o755 }); + } const next = openDirectory(path); closeSync(fd); fd = next; ancestors.add(segments.slice(0, i + 1).join("/")); } const path = at(fd, segments.at(-1)!); let info = lstatSync(path, { throwIfNoEntry: false }); - if (!info && DIRECTORIES.has(rel)) { mkdirSync(path, { mode: 0o755 }); info = lstatSync(path); } + if (!info && DIRECTORIES.has(rel) && options.prepare !== false) { mkdirSync(path, { mode: 0o755 }); info = lstatSync(path); } let mode: ProtectedWorkerPath["mode"] = "absent"; if (info) { if (appeared.has(rel)) mode = info.isDirectory() ? "mask_directory" : "mask_file"; @@ -149,7 +162,7 @@ export function resolveWorkerProtection(brain: string, options: { } /** Fixed order: ancestor mount points first, then the protected names. */ -export function protectedWorkerMounts(brain: string, protection: WorkerProtection, retainedFolders: readonly string[] = []): string[] { +export function protectedWorkerMounts(brain: string, protection: WorkerProtection, retainedFolders: readonly string[] = [], readOnlyRoots: readonly string[] = []): string[] { const qualified = qualifiedFolders.get(protection); if (retainedFolders.some(root => !qualified?.roots.includes(root))) throw new Error("provider folder topology was not qualified by the resolver"); @@ -167,7 +180,7 @@ export function protectedWorkerMounts(brain: string, protection: WorkerProtectio } const pins = [...new Set([...protection.ancestors, ...folderPins.map(pin => pin.rel)])] .sort((a,b) => a.split("/").length - b.split("/").length); - const argv = pins.flatMap(rel => ["--bind", join(brain, rel), join(brain, rel)]); + const argv = pins.flatMap(rel => [readOnlyRoots.some(root => isWithin(root, rel)) ? "--ro-bind" : "--bind", join(brain, rel), join(brain, rel)]); for (const { rel, mode } of protection.paths) { const path = join(brain, rel); if (mode === "read_only") argv.push("--ro-bind", path, path); @@ -306,7 +319,7 @@ const outsideOf = (dir: string, path: string) => !isWithin(dir, path) && !isWith * reads as empty: the legacy root-level caches under any provider rule, and * `.brain-cache/` while any folder is masked (#2725). */ -export function dataTreeMounts(brain: string, target: string, tree: WorkerDataTree): string[] { +export function dataTreeMounts(brain: string, target: string, tree: WorkerDataTree, workspaceSource?: string): string[] { for (const dir of [tree.root, tree.index]) { const info = lstatSync(dir, { throwIfNoEntry: false }); if (!isAbsolute(dir) || normalize(dir) !== dir || !info?.isDirectory() || info.isSymbolicLink() || !outsideOf(brain, dir) || !outsideOf(dir, target)) @@ -316,6 +329,7 @@ export function dataTreeMounts(brain: string, target: string, tree: WorkerDataTr const index = lstatSync(join(tree.root, INDEX_DIR), { throwIfNoEntry: false }); if (!index?.isDirectory() || index.isSymbolicLink()) throw new Error(`${INDEX_DIR} is missing from the turn's data tree`); const argv = ["--ro-bind", tree.root, target, tree.indexWritable ? "--bind" : "--ro-bind", tree.index, join(target, INDEX_DIR)]; + if (workspaceSource) argv.push("--ro-bind", workspaceSource, join(target, "workspaces")); for (const name of PROVIDER_CACHE_FILES) { const info = lstatSync(join(tree.root, name), { throwIfNoEntry: false }); if (info && tree.masked) argv.push("--ro-bind", "/dev/null", join(target, name)); @@ -325,7 +339,8 @@ export function dataTreeMounts(brain: string, target: string, tree: WorkerDataTr ? ["--tmpfs", join(target, CACHE_DIR), "--remount-ro", join(target, CACHE_DIR)] : ["--ro-bind", "/dev/null", join(target, CACHE_DIR)])); for (const rel of [...new Set(tree.masked ?? [])].sort()) { if (invalidFolder(rel) || isWithin(INDEX_DIR, rel)) throw new Error("invalid provider mask folder"); - const info = lstatSync(join(tree.root, rel), { throwIfNoEntry: false }); + const source = workspaceSource && isWithin("workspaces", rel) ? join(workspaceSource, rel.slice("workspaces".length)) : join(tree.root, rel); + const info = lstatSync(source, { throwIfNoEntry: false }); if (info?.isDirectory() && !info.isSymbolicLink()) argv.push("--tmpfs", join(target, rel), "--remount-ro", join(target, rel)); else if (info) argv.push("--ro-bind", "/dev/null", join(target, rel)); } diff --git a/packages/ui-sdk/src/server/worker-sandbox.ts b/packages/ui-sdk/src/server/worker-sandbox.ts index b94f814aee..b13c21ec92 100644 --- a/packages/ui-sdk/src/server/worker-sandbox.ts +++ b/packages/ui-sdk/src/server/worker-sandbox.ts @@ -1,6 +1,6 @@ /** * The writable areas of an interactive agent worker (#1626): the brain's own - * scratch area and its repository workspaces, bound read-write over the + * scratch area and opted-in repository workspaces, bound read-write over the * read-only brain, and per-turn XDG directories in turn temp. Everything here is * resolved once per worker by `prepareWorkerSandbox` * (`packages/ui-sdk/src/server/worker-launcher.ts`), which both builds the @@ -18,7 +18,7 @@ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync } from "node:fs"; import { join, relative } from "node:path"; -import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR, linkRule, READ_ONLY_BRAIN_RULE, TURN_TEMP_RULE } from "@schlessera/brain-common/internal/worker-areas"; +import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR, linkRule, READ_ONLY_BRAIN_RULE, TURN_TEMP_RULE, WORKSPACES_READ_ONLY_REASON } from "@schlessera/brain-common/internal/worker-areas"; import { brainGitSteps } from "./maintenance-worker.js"; import { MaintenanceTempBusyError } from "./maintenance-temp-budget.js"; import { runWorkerStepsSync, workerStep, type WorkerSteps } from "./worker-steps.js"; @@ -41,7 +41,7 @@ export const WORKER_MOUNT_SCAN_LIMIT = 200_000; export type WorkerHome = { mode: "xdg" }; /** One writable area: bound read-write, or named with why it is not. `missing`: the directory does not exist. */ -export type WorkerMount = { writable: true; path: string } | { writable: false; reason: string; missing?: true }; +export type WorkerMount = { writable: true; path: string } | { writable: false; reason: string; missing?: true; readOnlyPath?: string }; /** * The named writable areas a worker may receive inside the read-only brain. @@ -141,6 +141,8 @@ export interface WorkerSandbox { readonly noteFacts?: WorkerNoteFacts; /** Canonical brain path the layout was resolved for. */ readonly brain: string; + /** Frozen at admission; changing a saved preference never changes this turn. */ + readonly codeChanges?: boolean; readonly restricted: boolean; /** Resolved filesystem profile. Omitted legacy layouts are strict. */ readonly profile?: WorkerProfile; @@ -490,22 +492,24 @@ export function* resolveScratchMountSteps(brain: string, maintenance?: import(". } /** - * `/workspaces`, bound read-write only when it already exists as a - * real directory: creating it outside a hosted turn is the opt-in. Core + * `/workspaces` is inspected read-only by default. The session must + * opt in to code changes before the writable alias scan runs. A writable + * mount also requires an existing real directory. Core * always excludes it from the index, so it holds no authoritative document. * Any file in it with a name outside it, a mount below it or a walk past the * limit leaves it read-only for the turn. */ -export function resolveWorkspacesMount(brain: string, limit = WORKER_MOUNT_SCAN_LIMIT): WorkerMount { +export function resolveWorkspacesMount(brain: string, limit = WORKER_MOUNT_SCAN_LIMIT, codeChanges = false): WorkerMount { const dir = realBrainDirectory(brain, BRAIN_WORKSPACES_DIR, false); if (dir === null) return { writable: false, reason: "workspaces/ does not exist", missing: true }; if (typeof dir === "object") return { writable: false, reason: dir.refused }; if (mountPointsUnder(dir).length) return { writable: false, reason: "workspaces/ is or contains a mount point" }; + if (!codeChanges) return { writable: false, readOnlyPath: dir, reason: WORKSPACES_READ_ONLY_REASON }; const scan = scanForOutsideLinks(brain, dir, limit); - if (scan.overLimit) return { writable: false, reason: `workspaces/ holds more than ${limit} entries, too many to verify` }; - if (scan.unverified) return { writable: false, reason: `workspaces/ could not be verified: ${scan.unverified}` }; - if (scan.brainInside) return { writable: false, reason: "workspaces/ contains the brain itself" }; - if (scan.outside.length) return { writable: false, reason: `hard-linked to files outside workspaces/: ${shown(scan.outside)}` }; + if (scan.overLimit) return { writable: false, readOnlyPath: dir, reason: `workspaces/ holds more than ${limit} entries, too many to verify` }; + if (scan.unverified) return { writable: false, readOnlyPath: dir, reason: `workspaces/ could not be verified: ${scan.unverified}` }; + if (scan.brainInside) return { writable: false, readOnlyPath: dir, reason: "workspaces/ contains the brain itself" }; + if (scan.outside.length) return { writable: false, readOnlyPath: dir, reason: `hard-linked to files outside workspaces/: ${shown(scan.outside)}` }; return { writable: true, path: dir }; } @@ -547,6 +551,8 @@ export interface WorkerNoteLimit { /** Facts resolved outside the mount list that the note states with it. */ export interface WorkerNoteFacts { + /** Historical qualification only; never mount or write authority. */ + readonly legacyWorkspaces?: WorkerMount; /** Actual successful host qualification, never a configured helper path alone. */ readonly identity?: { readonly kind: "separate_uid"; readonly workerUid: number }; readonly limits?: readonly WorkerNoteLimit[]; @@ -593,14 +599,16 @@ const PROFILE_LINES: Record, (sandbox: Work }; /** The line for each state an area's mount can be in, naming the area by its resolved path. */ -const AREA_LINES: Record string> = { +const AREA_LINES: Record string> = { scratch: ({ rel, mount }, target) => mount.writable ? ` - \`${target}/\` is writable. Write the file there, then link its repo-relative destination, such as \`${rel}/.pdf\`.` : ` - \`${rel}/\` is read-only this turn: ${mount.reason}. There is nowhere to put a file for the reader; say so instead of linking a turn-temp file.`, - workspaces: ({ rel, mount }, target) => mount.writable + workspaces: ({ rel, mount }, target, codeChanges) => mount.writable ? ` - \`${target}/\` is writable: clone, fetch and commit other repositories there, never in \`/tmp\`.` : mount.missing - ? ` - There is no \`${rel}/\` directory, so a repository clone is lost at turn end. Creating \`${rel}/\` in the brain outside a hosted turn makes it writable in later turns.` + ? codeChanges === undefined + ? ` - There is no \`${rel}/\` directory, so a repository clone is lost at turn end. Creating \`${rel}/\` in the brain outside a hosted turn makes it writable in later turns.` + : ` - There is no \`${rel}/\` directory at admission. Anything created there this turn is ordinary retained and charged brain content. The next default turn inspects it read-only; enable this session’s code-changes switch or request a managed worktree for later edits, installs or builds.` : ` - \`${rel}/\` is read-only this turn: ${mount.reason}.`, }; @@ -618,7 +626,10 @@ function turnTempPlaces(): string { * to. Both backends inject this text unchanged. The restricted (autonomous) * variant is the envelope's own and keeps its wording. */ -export function workerSandboxNote(sandbox: WorkerSandbox, facts: WorkerNoteFacts = {}): string { +export function workerSandboxNote(sandbox: WorkerSandbox, facts: WorkerNoteFacts = {}, legacyWorkspace = false): string { + if (!legacyWorkspace && sandbox.codeChanges === undefined) sandbox = { ...sandbox, codeChanges: false }; + if (legacyWorkspace) sandbox = { ...sandbox, codeChanges: undefined, areas: sandbox.areas.map(area => area.name === "workspaces" && sandbox.noteFacts?.legacyWorkspaces + ? { ...area, mount: sandbox.noteFacts.legacyWorkspaces } : area) }; const lines: string[] = []; const resolvedFacts = { ...sandbox.noteFacts, ...facts }; const profile = workerProfile(sandbox); @@ -643,7 +654,7 @@ export function workerSandboxNote(sandbox: WorkerSandbox, facts: WorkerNoteFacts sandbox.areas.some(area => area.mount.writable) ? "2. **Persistent areas: kept across turns.**" : "2. **Persistent areas: none writable this turn.**", - ...sandbox.areas.map(area => AREA_LINES[area.name](area, profile === "governed" ? area.rel : `${WORKER_AREA_ROOT}/${area.name}`)), + ...sandbox.areas.map(area => AREA_LINES[area.name](area, profile === "governed" ? area.rel : `${WORKER_AREA_ROOT}/${area.name}`, sandbox.codeChanges)), ...(profile === "strict" ? ["Configuration executes from an immutable startup view, including imported helpers and absent names.", ...sandbox.areas.filter(area => area.mount.writable).map(area => `Write \`${area.rel}/\` through \`${WORKER_AREA_ROOT}/${area.name}/\`, outside that view; link the repo-relative destination.`), @@ -680,7 +691,7 @@ export function workerSandboxNote(sandbox: WorkerSandbox, facts: WorkerNoteFacts } if (profile !== "restricted" && sandbox.scopePolicy) { const scope = sandbox.scopePolicy; - lines.push("", `Scope limits per turn: ${scope.max_tool_calls} tool calls, ${scope.max_minutes} wall minutes, ${scope.max_files_changed} distinct observed changed paths and ${scope.max_bytes_written} observed written bytes in brain, scratch and workspaces${sandbox.worktrees ? ", and managed worktrees" : ""}.`, + lines.push("", `Scope limits per turn: ${scope.max_tool_calls} tool calls, ${scope.max_minutes} wall minutes, ${scope.max_files_changed} distinct observed changed paths and ${scope.max_bytes_written} observed written bytes in ${sandbox.codeChanges === undefined ? "brain, scratch and workspaces" : `brain and scratch${sandbox.codeChanges ? ", and workspaces" : ""}`}${sandbox.worktrees ? ", and managed worktrees" : ""}.`, "One finite Continue grant per dimension adds its original cap. A second hit and the free-space floor max(5%, 2 GiB) allow Stop only. Voice stops without a grant. Observations cannot capture writes overwritten between snapshots.", ...(resolvedFacts.hardTimeoutMs === undefined ? [] : [`The independent host hard timeout is ${resolvedFacts.hardTimeoutMs / 60_000} minutes, including paused time. Resource and storage limits remain binding.`])); } diff --git a/packages/ui-sdk/src/server/workspace-refusal.ts b/packages/ui-sdk/src/server/workspace-refusal.ts new file mode 100644 index 0000000000..ca7b3ceba7 --- /dev/null +++ b/packages/ui-sdk/src/server/workspace-refusal.ts @@ -0,0 +1,12 @@ +/** Explain a failed tool result; the kernel and host routes enforce writes. */ +import { WORKSPACES_WRITE_REFUSAL } from "@schlessera/brain-common/internal/worker-areas"; +import type { WorkerSandbox } from "./worker-sandbox.js"; + +export function workspaceWriteRefusal(sandbox: WorkerSandbox | undefined, _toolName: string, _input: unknown, _cwd?: string, failure?: unknown): string | undefined { + if (!sandbox?.areas.some(area => area.name === "workspaces" && !area.mount.writable && area.mount.readOnlyPath) || failure == null) return; + const detail = failure as { code?: unknown; stderr?: unknown; error?: unknown; message?: unknown; content?: unknown }; + const parts = Array.isArray(detail.content) ? detail.content.flatMap(part => part?.type === "text" && typeof part.text === "string" ? [part.text] : []) : []; + const text = typeof failure === "string" ? failure : [...parts, detail.code, detail.stderr, detail.error, detail.message].filter(value => typeof value === "string").join("\n"); + if (text.includes(WORKSPACES_WRITE_REFUSAL) || !/\bEROFS\b|read[- ]only/iu.test(text)) return; + return WORKSPACES_WRITE_REFUSAL; +} diff --git a/packages/ui-sdk/tests/native-brain-manager.test.ts b/packages/ui-sdk/tests/native-brain-manager.test.ts index de0ea63c22..236f241fed 100644 --- a/packages/ui-sdk/tests/native-brain-manager.test.ts +++ b/packages/ui-sdk/tests/native-brain-manager.test.ts @@ -1,10 +1,10 @@ import { afterEach, expect, test } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; +import { closeSync, mkdtempSync, openSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createNativeBrainManagerClient, decodeNativeDelta } from "../src/server/native-brain-manager-client"; -import { createNativeBrainManager, nativeStoreMount, validateNativeBrainManagerConfig } from "../src/server/native-brain-manager"; -import { nativeManagerFrame, nativeManagerRequest, type NativeBrainManagerError, type NativeManagerRequest } from "../src/server/native-brain-manager-protocol"; +import { createNativeBrainManager, nativeStoreMount, serveNativeBrainRequests, validateNativeBrainManagerConfig } from "../src/server/native-brain-manager"; +import { nativeManagerFrame, nativeManagerRequest, NATIVE_REQUEST_BYTES, type NativeBrainManagerError, type NativeManagerRequest } from "../src/server/native-brain-manager-protocol"; const ID = "11111111-1111-4111-8111-111111111790"; const SECOND = "22222222-2222-4222-8222-222222221790"; @@ -205,3 +205,40 @@ test("stage metadata binds its lower checkpoint and requires framed completion", expect(receipt.checkpointId).toBe(SECOND);expect(await receipt.completed).toEqual({exitCode:0,bytes:row.length}); expect(seen).toEqual([{operation:"inspectStage",id:ID}]); }); + + +test("the actual Unix endpoint accepts bounded long escaped stat paths and rejects oversized bodies",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-native-long-stat-")),socketPath=join(root,"manager.sock");cleanups.push(()=>rmSync(root,{recursive:true,force:true})); + const seen:string[]=[];const service=serveNativeBrainRequests(socketPath,{run:async (request: NativeManagerRequest)=>{if(request.operation!=="readCheckpoint")throw Error("unexpected operation");seen.push(request.path);return Response.json({id:SECOND,token:ID,socketPath:join(root,"reader.sock"),workerUid:31000,maximum:request.maximum});}} as never);cleanups.push(()=>service.stop(true)); + const {request}=await import("node:http"); + const send=(body:string)=>new Promise<{status:number;body:string}>((resolve,reject)=>{const req=request({socketPath,path:"/native-brain",method:"POST",headers:{"content-type":"application/json"}},response=>{let text="";response.setEncoding("utf8");response.on("data",part=>{text+=part;});response.on("end",()=>resolve({status:response.statusCode!,body:text}));});req.on("error",reject);req.end(body);}); + for(const path of [Array.from({length:260},()=>"ithaca").join("/"),Array.from({length:200},()=>String.fromCharCode(34)+"Ω").join("/"),Array.from({length:10000},()=>String.fromCharCode(1,2,34)+"Ω").join("/")]){ + expect(nativeManagerRequest.safeParse({operation:"readCheckpoint",id:ID,path,action:"stat",maximum:0}).success).toBe(true); + const answer=await send(JSON.stringify({operation:"readCheckpoint",id:ID,path,action:"stat",maximum:0}));expect(answer.status,"SCHEMA_ACCEPTED_STAT_REACHES_ACTUAL_UNIX_ENDPOINT").toBe(200);expect(JSON.parse(answer.body).id).toBe(SECOND);expect(seen.at(-1),"LONG_PATH_IS_A_REQUEST_NOT_A_CONTROL_REPLY").toBe(path); + } + expect(seen).toHaveLength(3); + let refused=false;try{const oversized=await send(JSON.stringify({operation:"readCheckpoint",id:ID,path:"x".repeat(NATIVE_REQUEST_BYTES),action:"stat",maximum:0}));refused=oversized.status>=400;}catch(error){refused=["EPIPE","ECONNRESET"].includes((error as NodeJS.ErrnoException).code??"");}expect(refused,"OVERSIZED_BODY_IS_REFUSED_BEFORE_ENGINE").toBe(true);expect(seen).toHaveLength(3); +}); + + +test("the fixed reader receives escaped long metadata requests over stdin before its identity guard",async()=>{ + const {startNativeCheckpointRead}=await import("../src/server/native-checkpoint-reader.js"); + const root=mkdtempSync(join(tmpdir(),"odysseus-reader-stdin-")),fd=openSync(root,"r"),uid=process.getuid!(); + const path=Array.from({length:10000},()=>String.fromCharCode(1,2,34)+"Ω").join("/"); + const request={action:"stat" as const,path,maximum:0};expect(Buffer.byteLength(JSON.stringify(request))).toBeGreaterThan(128*1024); + try{ + // An intentionally identical identity must be refused on root and unprivileged + // hosts alike. Reaching this guard proves the real helper parsed bounded stdin + // without attempting an over-limit single argv; no private read is claimed. + await expect(startNativeCheckpointRead({id:ID,socketPath:join(root,"reader.sock"),token:"ithaca",workerUid:uid,appUid:uid,appGid:process.getgid!(),rootFd:fd,timeoutMs:1000,maximum:0,request}),"LONG_REQUEST_REACHES_FIXED_READER_IDENTITY_GUARD").rejects.toThrow("fixed separate reader identity required"); + }finally{closeSync(fd);rmSync(root,{recursive:true,force:true});} +}); + + +test("the Unix client refuses a control reply above 64 KiB independently of request capacity",async()=>{ + const root=mkdtempSync(join(tmpdir(),"odysseus-control-reply-")),socketPath=join(root,"manager.sock");cleanups.push(()=>rmSync(root,{recursive:true,force:true})); + let calls=0;const server=Bun.serve({unix:socketPath,fetch:()=>Response.json(++calls===1?{padding:"x".repeat(64*1024)}:{id:ID,state:"deleted"})});cleanups.push(()=>server.stop(true)); + const client=createNativeBrainManagerClient({socketPath}); + await expect(client.ready(),"CONTROL_REPLY_BOUND_DOES_NOT_INHERIT_REQUEST_CAPACITY").rejects.toThrow("control response exceeded its bound"); + expect(await client.release(ID),"OVERSIZED_REPLY_DOES_NOT_LATCH_THE_CLIENT").toEqual({id:ID,state:"deleted"}); +}); diff --git a/packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts b/packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts new file mode 100644 index 0000000000..880c73a89b --- /dev/null +++ b/packages/ui-sdk/tests/native-checkpoint-path-bounds.test.ts @@ -0,0 +1,11 @@ +import { expect, test } from "bun:test"; +import { nativeManagerRequest } from "../src/server/native-brain-manager-protocol.js"; + +// A single inode probe never inventories the directory. Keep file/list bounds. +test.each(["readCheckpoint", "readStage", "poolReadCheckpoint"])("%s admits deep bounded stat probes without widening inventories", operation => { + const input = { operation, id: "11111111-1111-4111-8111-111111111111", path: Array.from({length:260},()=>"x").join("/"), maximum:0 }; + expect(nativeManagerRequest.safeParse({...input,action:"stat"}).success,"DEEP_ALIAS_STAT_CAN_BE_QUALIFIED").toBe(true); + for(const action of ["file","list"]) expect(nativeManagerRequest.safeParse({...input,action}).success,"DEEP_INVENTORY_AND_CONTENT_BOUNDS_STAY_CLOSED").toBe(false); + for(const path of ["../notes/raft.md","workspaces/../notes/raft.md","/notes/raft.md","workspaces/\0x"]) + expect(nativeManagerRequest.safeParse({...input,path,action:"stat"}).success,"STAT_PROBE_CANNOT_TRAVERSE_OR_ESCAPE").toBe(false); +}); diff --git a/packages/ui-sdk/tests/native-worker-view.test.ts b/packages/ui-sdk/tests/native-worker-view.test.ts index 0d8ac3c8b9..b40e7e13a8 100644 --- a/packages/ui-sdk/tests/native-worker-view.test.ts +++ b/packages/ui-sdk/tests/native-worker-view.test.ts @@ -13,7 +13,7 @@ test("native observation matches a real strict worker's frozen reads and private mkdirSync(join(brain, "workspaces"), { recursive: true }); writeFileSync(join(brain, "helper.ts"), 'export default "Frozen voyage";'); const path = join(brain, "workspaces/loom.md"); writeFileSync(path, "Penelope weaves.\n"); - const sandbox = prepareWorkerSandbox(brain, { profile: "strict", areas: ["workspaces"] }); + const sandbox = prepareWorkerSandbox(brain, { profile: "strict", codeChanges: true, areas: ["workspaces"] }); const worker = launchAgentWorker({ brainPath: brain, sandbox, env: {}, command: ["/bin/sh", "-c", 'printf "ready\\n"; IFS= read -r go; cat helper.ts; printf "\\n"; printf "Athena charts.\\n" > /tmp/brain-worker-areas/workspaces/loom.md; printf "written\\n"; IFS= read -r end'] }); void worker.exited.catch(() => {}); diff --git a/packages/ui-sdk/tests/worker-data-tree.test.ts b/packages/ui-sdk/tests/worker-data-tree.test.ts index ed02857c4d..cd3eb4e0d2 100644 --- a/packages/ui-sdk/tests/worker-data-tree.test.ts +++ b/packages/ui-sdk/tests/worker-data-tree.test.ts @@ -5,12 +5,12 @@ * configuration stays at the frozen brain path. */ import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { dataTreeMounts } from "../src/server/worker-protection"; import { prepareWorkerSandbox, workerCommand } from "../src/server/worker-launcher"; -import { WORKER_DATA_ROOT, workerSandboxNote, type WorkerDataTree } from "../src/server/worker-sandbox"; +import { WORKER_AREA_ROOT, WORKER_DATA_ROOT, workerSandboxNote, type WorkerDataTree } from "../src/server/worker-sandbox"; import { createFixtureWorkerStartupView } from "./helpers/worker-startup-view-fixture"; const roots: string[] = []; @@ -88,3 +88,36 @@ test("the sandbox note names the data path, and a masked turn's index is read-on expect(note, "NOTE_SAYS_THE_PRIVATE_INDEX_IS_READ_ONLY").toContain("It is read-only: the host adds this turn's own applications to it"); expect(note).not.toContain("write to it"); }); + + +test("strict data-tree launch overlays inspected source before its provider masks",()=>{ + const {brain,tree,index}=layout();mkdirSync(join(brain,"workspaces/ithaca"),{recursive:true});writeFileSync(join(brain,"workspaces/ithaca/README.md"),"Athena inspects Ithaca.");mkdirSync(join(tree,"workspaces"),{recursive:true}); + const view=createFixtureWorkerStartupView(brain); + try{ + const sandbox={...prepareWorkerSandbox(brain,{profile:"strict",codeChanges:false}),dataTree:{root:tree,index,masked:["workspaces/ithaca"]}}; + const argv=workerCommand({brainPath:brain,startupView:view,sandbox,env:{},command:["/bin/true"]}); + const text=argv.join(" "),overlay=`--ro-bind ${join(view.root,"workspaces")} ${WORKER_DATA_ROOT}/workspaces`,mask=`--tmpfs ${WORKER_DATA_ROOT}/workspaces/ithaca`; + expect(text,"PI_REPO_RELATIVE_READS_REACH_THE_SEALED_CHECKOUT").toContain(overlay); + expect(text.indexOf(mask),"PROVIDER_MASKS_OVERRIDE_THE_INSPECTION_OVERLAY").toBeGreaterThan(text.indexOf(overlay)); + }finally{view.cleanup();} +}); + + +test.each(["absent","symlink"])("strict overlay refuses an unqualified %s checkpoint source",state=>{ + const {brain,tree,index}=layout();const view=createFixtureWorkerStartupView(brain); + mkdirSync(join(brain,"workspaces/ithaca"),{recursive:true});mkdirSync(join(tree,"workspaces")); + if(state==="symlink")symlinkSync(join(view.root,"notes"),join(view.root,"workspaces")); + try{const sandbox={...prepareWorkerSandbox(brain,{profile:"strict",codeChanges:false}),dataTree:{root:tree,index}};expect(()=>workerCommand({brainPath:brain,startupView:view,sandbox,env:{},command:["/bin/true"]}),"LIVE_QUALIFICATION_CANNOT_AUTHORIZE_A_STALE_SOURCE").toThrow("immutable workspace source");}finally{view.cleanup();} +}); + + +test.each([["strict","workspaces/ithaca/private"],["strict","workspaces"],[undefined,"workspaces/ithaca/private"],[undefined,"workspaces"]] as const)("strict staged writable areas repeat provider masks through every alias (profile=%s, mask=%s)",(profile,folder)=>{ + const {root,brain,tree,index}=layout();mkdirSync(join(brain,".brain-index"));mkdirSync(join(brain,"workspaces/ithaca/private"),{recursive:true});writeFileSync(join(brain,"workspaces/ithaca/private/secret.md"),"ATHENA_PROVIDER_MASK_CONTROL\n");writeFileSync(join(brain,"workspaces/ithaca/public.md"),"Odysseus inspects.");writeFileSync(join(brain,"workspaces/ithaca/private/env-secret.md"),"ATHENA_ENV_MASK_CONTROL");symlinkSync("workspaces/ithaca/private/env-secret.md",join(brain,".env.athena")); + const sandbox=prepareWorkerSandbox(brain,{profile,areas:["workspaces"],codeChanges:true});expect(sandbox.areas[0]!.mount.writable,"CONTROL_HAS_A_REAL_WRITABLE_GRANT").toBe(true); + const view=createFixtureWorkerStartupView(brain),stage=join(root,"stage");cpSync(join(view.root,"workspaces"),join(stage,"workspaces"),{recursive:true});cpSync(join(view.root,"workspaces"),join(tree,"workspaces"),{recursive:true}); + const roots=[join(brain,"workspaces"),join(WORKER_DATA_ROOT,"workspaces"),join(WORKER_AREA_ROOT,"workspaces")]; + const command=["/bin/sh","-c",roots.map(path=>`if test -r '${path}/ithaca/private/secret.md'; then IFS= read -r bytes < '${path}/ithaca/private/secret.md'; echo "$bytes"; echo 'STAGED_PROVIDER_MASK_LEAK: ${path}'; exit 41; fi; test -d '${path}' || exit 42`).join("; ")+`; printf 'Odysseus writes.' > '${WORKER_AREA_ROOT}/workspaces/public-write.md'`]; + // A whole-workspace policy mask also hides this otherwise writable destination. + if(folder==="workspaces")command[2]=command[2]!.replace(/; printf.*$/u,""); + try{const run=Bun.spawnSync(workerCommand({brainPath:brain,startupView:view,sandbox:{...sandbox,providerMasks:{folders:[folder],index},dataTree:{root:tree,index}},areaOutput:{source:stage},env:{},command}),{env:{},stdout:"pipe",stderr:"pipe"});expect(run.exitCode,`ALL_WORKSPACE_ALIASES_KEEP_PROVIDER_MASKS: ${run.stdout} ${run.stderr}`).toBe(0);}finally{view.cleanup();} +}); diff --git a/packages/ui-sdk/tests/worker-output-budget.test.ts b/packages/ui-sdk/tests/worker-output-budget.test.ts index 5c3c6f1ca0..411c8a78e3 100644 --- a/packages/ui-sdk/tests/worker-output-budget.test.ts +++ b/packages/ui-sdk/tests/worker-output-budget.test.ts @@ -26,7 +26,7 @@ for (const profile of ["strict", "maintenance"] as const) test(`${profile} refus console.log(fs.statfsSync(${JSON.stringify(path.replace("/proof.bin", ""))}).blocks * fs.statfsSync(${JSON.stringify(path.replace("/proof.bin", ""))}).bsize);`]; const worker = launchAgentWorker({ brainPath: brain, env: {}, command, ...(outputs ? { startupView: outputs.view, maintenance: { network: false, credentials: false, readPaths: [process.execPath], output: outputs.output } } - : { startupView: createWorkerStartupView(brain), sandbox: prepareWorkerSandbox(brain, { profile: "strict", areas: ["workspaces"], readPaths: [process.execPath] }), turnTempBytes: 1024 ** 2 }) }); + : { startupView: createWorkerStartupView(brain), sandbox: prepareWorkerSandbox(brain, { profile: "strict", codeChanges: true, areas: ["workspaces"], readPaths: [process.execPath] }), turnTempBytes: 1024 ** 2 }) }); cleanup.push(() => worker.kill("SIGKILL")); let stdout = "", stderr = ""; worker.stdout.on("data", data => { stdout += String(data); }); worker.stderr.on("data", data => { stderr += String(data); }); diff --git a/packages/ui-sdk/tests/worker-sandbox.test.ts b/packages/ui-sdk/tests/worker-sandbox.test.ts index 2101dd3e65..ea3883ab36 100644 --- a/packages/ui-sdk/tests/worker-sandbox.test.ts +++ b/packages/ui-sdk/tests/worker-sandbox.test.ts @@ -1,10 +1,14 @@ -import { launchFixtureAgentWorker as launchAgentWorker, prepareFixtureWorkerSandbox as prepareWorkerSandbox, createFixtureMaintenanceHost } from "./helpers/worker-startup-view-fixture.js"; +import { launchFixtureAgentWorker as launchAgentWorker, prepareFixtureWorkerSandbox, createFixtureMaintenanceHost } from "./helpers/worker-startup-view-fixture.js"; import { describe, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { workerCommand } from "../src/server/worker-launcher"; -import { resolveScratchMount, WORKER_XDG_DIRS, workerSandboxNote, workerSandboxWarnings, type WorkerSandbox } from "../src/server/worker-sandbox"; +import { resolveScratchMount, resolveWorkspacesMount, WORKER_XDG_DIRS, workerSandboxNote, workerSandboxWarnings, type WorkerSandbox } from "../src/server/worker-sandbox"; + +// The historical writable-area cases exercise the explicit code-changes mode. +const prepareCodeChangesSandbox = (brain: string, options: Parameters[1] = {}) => + prepareFixtureWorkerSandbox(brain, { codeChanges: true, ...options }); const GOLDEN = "Odysseus: only the server owns policy writes.\n"; const ROOT = resolve(import.meta.dir, "../../.."); @@ -45,7 +49,7 @@ describe("worker sandbox writable areas (#1626)", () => { test("scratch and workspaces persist; the rest of the brain survives write, rename, hardlink and symlink escapes", async () => { const f = fixture(); try { - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); expect(sandbox.areas.map(a => [a.name, a.mount.writable])).toEqual([["scratch", true], ["workspaces", true]]); const program = `import * as fs from "node:fs"; const brain=${JSON.stringify(f.brain)}, policy=${JSON.stringify(f.policy)}; @@ -90,7 +94,7 @@ describe("worker sandbox writable areas (#1626)", () => { test("the home stays read-only and per-turn XDG directories are writable (#1703)", async () => { const f = fixture(); try { - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); expect(sandbox.home).toEqual({ mode: "xdg" }); const program = `import * as fs from "node:fs"; const attempt=(fn)=>{try{fn();return "ok"}catch(e){return e.code}}; @@ -106,10 +110,10 @@ describe("worker sandbox writable areas (#1626)", () => { test("every interactive home is the XDG fallback, without probing the home", () => { const f = fixture(); try { - expect(prepareWorkerSandbox(f.brain, { home: f.home }).home).toEqual({ mode: "xdg" }); + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).home).toEqual({ mode: "xdg" }); expect(readdirSync(f.home)).toEqual([".gitconfig"]); - expect(prepareWorkerSandbox(f.brain, { home: join(f.brain, "notes") }).home?.mode).toBe("xdg"); - expect(prepareWorkerSandbox(f.brain, {}).home?.mode).toBe("xdg"); + expect(prepareCodeChangesSandbox(f.brain, { home: join(f.brain, "notes") }).home?.mode).toBe("xdg"); + expect(prepareCodeChangesSandbox(f.brain, {}).home?.mode).toBe("xdg"); } finally { f.cleanup(); } }); @@ -119,11 +123,11 @@ describe("worker sandbox writable areas (#1626)", () => { const repo = join(f.brain, "workspaces/ithaca/palace"); writeFileSync(join(repo, "object"), "loom"); linkSync(join(repo, "object"), join(f.brain, "workspaces/ithaca/object-clone")); - expect(prepareWorkerSandbox(f.brain, { home: f.home }).areas[1], "CONTAINED_LINK").toEqual({ name: "workspaces", rel: "workspaces", + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[1], "CONTAINED_LINK").toEqual({ name: "workspaces", rel: "workspaces", mount: { writable: true, path: join(f.brain, "workspaces") } }); linkSync(f.policy, join(repo, "policy-alias.md")); - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); - expect(sandbox.areas[1], "OUTSIDE_LINK").toEqual({ name: "workspaces", rel: "workspaces", mount: { writable: false, + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); + expect(sandbox.areas[1], "OUTSIDE_LINK").toEqual({ name: "workspaces", rel: "workspaces", mount: { writable: false, readOnlyPath: join(f.brain, "workspaces"), reason: "hard-linked to files outside workspaces/: workspaces/ithaca/palace/policy-alias.md" } }); expect(mountsIn(workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox })).binds) .toEqual([join(f.brain, ".brain/scratch")]); @@ -139,7 +143,7 @@ describe("worker sandbox writable areas (#1626)", () => { mkdirSync(scratch, { recursive: true }); writeFileSync(join(scratch, "draft.pdf"), "draft"); linkSync(join(scratch, "draft.pdf"), join(scratch, "draft-copy.pdf")); linkSync(f.policy, join(scratch, "policy-alias.md")); - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); expect(sandbox.scratchAliasesRemoved, "SCRATCH_ALIAS").toEqual([".brain/scratch/policy-alias.md"]); expect(sandbox.areas[0]?.mount.writable).toBe(true); expect(readdirSync(scratch).sort()).toEqual(["draft-copy.pdf", "draft.pdf"]); @@ -156,10 +160,10 @@ describe("worker sandbox writable areas (#1626)", () => { mkdirSync(hidden); mkdirSync(scratchHidden, { recursive: true }); linkSync(f.policy, join(hidden, "policy-alias.md")); linkSync(f.policy, join(scratchHidden, "policy-alias.md")); chmodSync(hidden, 0o100); chmodSync(scratchHidden, 0o100); - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); expect(sandbox.areas, "UNREADABLE_DIR").toEqual([ { name: "scratch", rel: ".brain/scratch", mount: { writable: false, reason: ".brain/scratch/ could not be verified: .brain/scratch/hidden cannot be opened (EACCES)" } }, - { name: "workspaces", rel: "workspaces", mount: { writable: false, reason: "workspaces/ could not be verified: workspaces/ithaca/hidden cannot be opened (EACCES)" } }, + { name: "workspaces", rel: "workspaces", mount: { writable: false, readOnlyPath: join(f.brain, "workspaces"), reason: "workspaces/ could not be verified: workspaces/ithaca/hidden cannot be opened (EACCES)" } }, ]); expect(mountsIn(workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox })).binds).toEqual([]); } finally { chmodSync(hidden, 0o700); chmodSync(scratchHidden, 0o700); f.cleanup(); } @@ -216,7 +220,7 @@ describe("worker sandbox writable areas (#1626)", () => { const odd = Buffer.concat([Buffer.from(join(f.brain, "workspaces/")), Buffer.from([0xff])]); mkdirSync(odd); linkSync(f.policy, Buffer.concat([odd, Buffer.from("/b"), Buffer.from([0xfe])])); - const mount = prepareWorkerSandbox(f.brain, { home: f.home }).areas[1]?.mount; + const mount = prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[1]?.mount; expect(mount?.writable, "BYTE_NAMES").toBe(false); expect(mount && !mount.writable && mount.reason).toStartWith("hard-linked to files outside workspaces/: workspaces/"); } finally { f.cleanup(); } @@ -237,7 +241,7 @@ describe("worker sandbox writable areas (#1626)", () => { try { linkSync(f.policy, join(f.brain, "workspaces/ithaca/palace/alias.md")); const { resolveWorkspacesMount } = require("../src/server/worker-sandbox") as typeof import("../src/server/worker-sandbox"); - expect(resolveWorkspacesMount(f.brain), "MOVED_ALIAS").toEqual({ writable: false, + expect(resolveWorkspacesMount(f.brain, undefined, true), "MOVED_ALIAS").toEqual({ writable: false, readOnlyPath: join(f.brain, "workspaces"), reason: "hard-linked to files outside workspaces/: workspaces/alias.md" }); expect(moved).toBe(true); } finally { spy.mockRestore(); f.cleanup(); } @@ -249,8 +253,8 @@ describe("worker sandbox writable areas (#1626)", () => { for (let i = 0; i < 5; i++) writeFileSync(join(f.brain, `workspaces/ithaca/f${i}`), "x"); const { resolveWorkspacesMount, scanForOutsideLinks } = require("../src/server/worker-sandbox") as typeof import("../src/server/worker-sandbox"); expect(scanForOutsideLinks(f.brain, join(f.brain, "workspaces"), 3).overLimit).toBe(true); - expect(resolveWorkspacesMount(f.brain, 3), "OVER_LIMIT").toEqual({ writable: false, reason: "workspaces/ holds more than 3 entries, too many to verify" }); - expect(resolveWorkspacesMount(f.brain).writable).toBe(true); + expect(resolveWorkspacesMount(f.brain, 3, true), "OVER_LIMIT").toEqual({ writable: false, readOnlyPath: join(f.brain, "workspaces"), reason: "workspaces/ holds more than 3 entries, too many to verify" }); + expect(resolveWorkspacesMount(f.brain, undefined, true).writable).toBe(true); } finally { f.cleanup(); } }); @@ -260,7 +264,7 @@ describe("worker sandbox writable areas (#1626)", () => { const target = join(f.root, "elsewhere"); mkdirSync(target); if (link === ".brain/scratch") mkdirSync(join(f.brain, ".brain")); symlinkSync(target, join(f.brain, link)); - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); expect(sandbox.areas[0]).toEqual({ name: "scratch", rel: ".brain/scratch", mount: { writable: false, reason: `${link} is a symlink` } }); expect(readdirSync(target)).toEqual([]); expect(mountsIn(workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox })).binds) @@ -272,7 +276,7 @@ describe("worker sandbox writable areas (#1626)", () => { const f = fixture({ workspaces: false }); try { mkdirSync(join(f.root, "repos")); symlinkSync(join(f.root, "repos"), join(f.brain, "workspaces")); - expect(prepareWorkerSandbox(f.brain, { home: f.home }).areas[1]).toEqual({ name: "workspaces", rel: "workspaces", + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[1]).toEqual({ name: "workspaces", rel: "workspaces", mount: { writable: false, reason: "workspaces is a symlink" } }); } finally { f.cleanup(); } }); @@ -281,10 +285,10 @@ describe("worker sandbox writable areas (#1626)", () => { const f = fixture(); try { expect(Bun.spawnSync(["git", "init", "-q", f.brain]).exitCode).toBe(0); - expect(prepareWorkerSandbox(f.brain, { home: f.home }).areas[0]?.mount, "SCRATCH_IGNORED").toMatchObject({ writable: false, + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[0]?.mount, "SCRATCH_IGNORED").toMatchObject({ writable: false, reason: expect.stringContaining("not gitignored") }); writeFileSync(join(f.brain, ".gitignore"), ".brain/scratch/\n"); - expect(prepareWorkerSandbox(f.brain, { home: f.home }).areas[0]?.mount.writable).toBe(true); + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[0]?.mount.writable).toBe(true); } finally { f.cleanup(); } }); @@ -292,10 +296,10 @@ describe("worker sandbox writable areas (#1626)", () => { const f = fixture(); try { expect(Bun.spawnSync(["git", "init", "-q", f.root]).exitCode).toBe(0); - expect(prepareWorkerSandbox(f.brain, { home: f.home }).areas[0]?.mount, "PARENT_REPO").toMatchObject({ writable: false, + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[0]?.mount, "PARENT_REPO").toMatchObject({ writable: false, reason: expect.stringContaining("not gitignored") }); writeFileSync(join(f.brain, ".gitignore"), ".brain/scratch/\n"); - expect(prepareWorkerSandbox(f.brain, { home: f.home }).areas[0]?.mount.writable).toBe(true); + expect(prepareCodeChangesSandbox(f.brain, { home: f.home }).areas[0]?.mount.writable).toBe(true); } finally { f.cleanup(); } }); @@ -303,14 +307,14 @@ describe("worker sandbox writable areas (#1626)", () => { const f = fixture({ workspaces: false }); try { const variants: WorkerSandbox[] = [ - prepareWorkerSandbox(f.brain, { home: f.home }), - prepareWorkerSandbox(f.brain, { home: f.home, areas: [] }), + prepareCodeChangesSandbox(f.brain, { home: f.home }), + prepareCodeChangesSandbox(f.brain, { home: f.home, areas: [] }), ]; mkdirSync(join(f.brain, "workspaces")); - variants.push(prepareWorkerSandbox(f.brain, { home: f.home, areas: ["workspaces"] }), prepareWorkerSandbox(f.brain, { home: f.home })); + variants.push(prepareCodeChangesSandbox(f.brain, { home: f.home, areas: ["workspaces"] }), prepareCodeChangesSandbox(f.brain, { home: f.home })); // A repository that does not ignore scratch: the scratch area stays read-only. expect(Bun.spawnSync(["git", "init", "-q", f.brain]).exitCode).toBe(0); - variants.push(prepareWorkerSandbox(f.brain, { home: f.home })); + variants.push(prepareCodeChangesSandbox(f.brain, { home: f.home })); expect(variants.at(-1)!.areas[0]?.mount.writable).toBe(false); for (const sandbox of variants) { const mounts = mountsIn(workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox })); @@ -330,7 +334,7 @@ describe("worker sandbox writable areas (#1626)", () => { expect(note).toContain("**Profile: `strict`.** The brain is read-only here"); expect(note).toContain("3. **The brain: canonical and versioned.**"); } - const restricted = prepareWorkerSandbox(f.brain, { restricted: true }); + const restricted = prepareCodeChangesSandbox(f.brain, { restricted: true }); expect(restricted).toEqual({ brain: f.brain, restricted: true, areas: [], scratchAliasesRemoved: [] }); expect(workerSandboxNote(restricted)).toContain("restricted (autonomous) turn"); // A restricted worker's argv is unchanged by its (empty) sandbox. @@ -348,7 +352,7 @@ describe("worker sandbox writable areas (#1626)", () => { test("a sandbox resolved for another brain, envelope or home refuses the launch", () => { const f = fixture(), g = fixture(); try { - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); expect(() => workerCommand({ brainPath: g.brain, command: [process.execPath], env: { HOME: f.home }, sandbox })).toThrow("another brain"); rmSync(join(f.brain, "workspaces"), { recursive: true }); symlinkSync(g.brain, join(f.brain, "workspaces")); expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox }), "RELAUNCH_RECHECK") @@ -430,7 +434,7 @@ describe("the sandbox note's wording (#1654)", () => { // The launcher binds an area only at its own path, so a moved area never reaches a worker. const f = fixture(); try { - const resolved = prepareWorkerSandbox(f.brain, { home: f.home }); + const resolved = prepareCodeChangesSandbox(f.brain, { home: f.home }); const relabelled = { ...resolved, areas: resolved.areas.map(area => area.name === "scratch" ? { ...area, rel: ".brain/loom" } : area) }; expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox: relabelled })) .toThrow("the scratch area is not at .brain/scratch/"); @@ -481,7 +485,7 @@ describe("managed worktree generations (#2430)", () => { test("a generation is bound whole, only into an interactive worker, and only from a root-owned directory outside the brain", async () => { const f = fixture(); try { - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); const owned = join(f.root, "generation"); mkdirSync(owned); chmodSync(owned, 0o755); // The pool's access generation is root-owned. A host directory such as // /usr is not a stand-in: an unprivileged user namespace (the CI unit @@ -509,7 +513,7 @@ describe("managed worktree generations (#2430)", () => { // The same directory, owned by this unprivileged uid, is refused. expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox: generation }), "REFERENCE_WORKTREE_GENERATION_MUST_BE_ROOT_OWNED").toThrow("root-owned directory outside the brain"); - const restricted = prepareWorkerSandbox(f.brain, { restricted: true }); + const restricted = prepareCodeChangesSandbox(f.brain, { restricted: true }); expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: {}, restricted: { readPaths: [process.execPath], inferenceDir: f.root }, sandbox: { ...restricted, worktrees: { source: "/usr" } } }), "REFERENCE_WORKTREE_NEVER_IN_A_RESTRICTED_WORKER").toThrow("only an interactive governed or strict worker"); } finally { f.cleanup(); } @@ -521,7 +525,7 @@ describe("shared reference source views (#2432)", () => { test("each view is bound whole and read-only, only into an interactive worker, and only from a root-owned directory outside the brain", async () => { const f = fixture(); try { - const sandbox = prepareWorkerSandbox(f.brain, { home: f.home }); + const sandbox = prepareCodeChangesSandbox(f.brain, { home: f.home }); const publicView = join(f.root, "public-view"), privateView = join(f.root, "private-view"); for (const view of [publicView, privateView]) { mkdirSync(view); chmodSync(view, 0o755); } const inBrain = join(f.brain, "notes"); chmodSync(inBrain, 0o755); @@ -548,7 +552,7 @@ describe("shared reference source views (#2432)", () => { } expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: { HOME: f.home }, sandbox: { ...sandbox, references: { public: publicView } } }), "REFERENCE_VIEW_MUST_BE_ROOT_OWNED").toThrow("root-owned directory outside the brain"); - const restricted = prepareWorkerSandbox(f.brain, { restricted: true }); + const restricted = prepareCodeChangesSandbox(f.brain, { restricted: true }); expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: {}, restricted: { readPaths: [process.execPath], inferenceDir: f.root }, sandbox: { ...restricted, references: { public: "/usr" } } }), "REFERENCE_VIEW_NEVER_IN_A_RESTRICTED_WORKER").toThrow("only an interactive governed or strict worker"); } finally { f.cleanup(); } @@ -583,3 +587,138 @@ describe("managed worktree guidance (#2430)", () => { expect(first, `REFERENCE_WORKTREE_GUIDANCE ${phrase}`).toContain(phrase); }); }); + + +describe("workspace inspect default (#4295, #4298)", () => { + test("inspection skips the alias walk even past its entry limit and names both write alternatives", () => { + const f = fixture(); + try { + const { resolveWorkspacesMount } = require("../src/server/worker-sandbox") as typeof import("../src/server/worker-sandbox"); + for (let i = 0; i < 5; i++) writeFileSync(join(f.brain, `workspaces/ithaca/file-${i}`), "Ithaca"); + const mount = resolveWorkspacesMount(f.brain, 3); + expect(mount.writable, "INSPECT_DOES_NOT_REQUIRE_WRITABLE_SCAN").toBe(false); + expect(mount).toHaveProperty("readOnlyPath", join(f.brain, "workspaces")); + expect(mount).not.toHaveProperty("reason", "workspaces/ holds more than 3 entries, too many to verify"); + const note = workerSandboxNote(prepareFixtureWorkerSandbox(f.brain, { codeChanges: false, areas: ["workspaces"] })); + expect(note, "REFUSAL_NAMES_SESSION_OPT_IN").toContain("code-changes switch"); + expect(note, "INSTALL_REFUSAL_NAMES_MANAGED_WORKTREE").toContain("managed worktree"); + expect(note).toContain("write, install or build"); + } finally { f.cleanup(); } + }); + + test.each(["strict", "governed"] as const)("%s default reads workspaces and refuses a pre-existing hard-link write", async profile => { + const f = fixture(); + try { + const note = join(f.brain, "notes/voyage.md"); + writeFileSync(note, GOLDEN); + linkSync(note, join(f.brain, "workspaces/ithaca/policy-alias.md")); + writeFileSync(join(f.brain, "workspaces/ithaca/pinned.md"), "Athena protects this file."); + const sandbox = prepareFixtureWorkerSandbox(f.brain, { profile, areas: ["workspaces"], + // Pinning a protected child's ancestors must not reopen its workspace. + ...(profile === "governed" ? { protectedPaths: ["workspaces/ithaca/pinned.md"] } : {}) }); + expect(sandbox.profile, "REQUESTED_WORKSPACE_PROFILE_ACTUALLY_RUNS").toBe(profile); + // No alias scan: this is the qualified inspect mount, not a scan refusal. + expect(sandbox.areas[0]!.mount, "DEFAULT_WORKSPACE_INSPECT_MOUNT").toMatchObject({ writable: false, readOnlyPath: join(f.brain, "workspaces") }); + const program = `import * as fs from "node:fs"; + const path=${JSON.stringify(join(f.brain, "workspaces/ithaca/policy-alias.md"))}; + const read=fs.readFileSync(path,"utf8");let error="";try{fs.writeFileSync(path,"attack")}catch(e){error=e.code} + console.log(JSON.stringify({read,error}));`; + expect(await run(f.brain, sandbox, program, f.home), "INSPECT_HARDLINK_WRITE_REFUSED").toEqual({ read: GOLDEN, error: "EROFS" }); + expect(readFileSync(note, "utf8"), "OUTSIDE_ALIAS_UNCHANGED").toBe(GOLDEN); + } finally { f.cleanup(); } + }); +}); + +test("governed inspection still seals workspaces when the writable area list is empty", async () => { + const f = fixture(); + try { + const sandbox = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", areas: [] }); + expect(sandbox.profile).toBe("governed"); + const program = `import * as fs from "node:fs";let error="";try{fs.writeFileSync(${JSON.stringify(join(f.brain, "workspaces/ithaca/new.md"))},"attack")}catch(e){error=e.code}console.log(JSON.stringify({error}));`; + expect(await run(f.brain, sandbox, program, f.home), "OMITTED_WORKSPACE_AREA_STILL_READ_ONLY").toEqual({ error: "EROFS" }); + } finally { f.cleanup(); } +}); + +test("missing workspaces stay absent on the live brain after an actual worker", async () => { + const f = fixture({ workspaces: false }); + try { + const sandbox = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", codeChanges: false, areas: ["workspaces"] }); + expect(sandbox.profile, "ABSENT_OPTIONAL_WORKSPACE_KEEPS_GOVERNED").toBe("governed"); + expect(await run(f.brain, sandbox, 'require("node:fs").writeFileSync("notes/voyage.md","Athena");console.log(JSON.stringify({ok:true}));', f.home)).toEqual({ ok: true }); + expect(readFileSync(join(f.brain, "notes/voyage.md"), "utf8"), "MISSING_AREA_KEEPS_NOTE_WRITES_LIVE").toBe("Athena"); + expect(existsSync(join(f.brain, "workspaces")), "NO_LIVE_WORKSPACE_MOUNTPOINT_CREATED").toBe(false); + } finally { f.cleanup(); } +}); + +test("workspace sealing preserves quarantine child masks and ordinary child write protection", async () => { + const f = fixture(); + try { + writeFileSync(join(f.brain, "workspaces/ithaca/quarantined.md"), "Hidden crew instructions"); + const sandbox = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", codeChanges: false, areas: ["workspaces"], + appearedPaths: ["workspaces/ithaca/quarantined.md"] }); + expect(sandbox.profile).toBe("governed"); + const program = `const fs=require("node:fs");let error="";try{fs.writeFileSync("workspaces/ithaca/new.md","attack")}catch(e){error=e.code}console.log(JSON.stringify({hidden:(()=>{try{return fs.readFileSync("workspaces/ithaca/quarantined.md","utf8")}catch(e){return e.code}})(),error}));`; + const result = await run(f.brain, sandbox, program, f.home); + expect(["", "EACCES"], "WORKSPACE_QUARANTINE_STAYS_HIDDEN").toContain(result.hidden); + expect(result.error, "WORKSPACE_ANCESTOR_STAYS_READ_ONLY").toBe("EROFS"); + } finally { f.cleanup(); } +}); + + +test.each([false, true])("workspace inspection never creates protected ancestors (existing root=%s)", async existing => { + const f = fixture({ workspaces: existing }); + try { + const path = join(f.brain, "workspaces/troy"); + const sandbox = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", codeChanges: false, areas: ["workspaces"], + protectedPaths: ["workspaces/troy/protected.md"] }); + expect(sandbox.profile, "MISSING_PROTECTED_ANCESTOR_USES_STRICT_VIEW").toBe("strict"); + expect(existsSync(path), "PREPARATION_DOES_NOT_CREATE_CHECKOUT_DIRECTORIES").toBe(false); + expect(await run(f.brain, sandbox, 'console.log(JSON.stringify({ok:true}));', f.home)).toEqual({ ok: true }); + expect(existsSync(path), "WORKER_DOES_NOT_CREATE_CHECKOUT_DIRECTORIES").toBe(false); + expect(existsSync(join(f.brain, "workspaces")), "ROOT_EXISTENCE_UNCHANGED").toBe(existing); + } finally { f.cleanup(); } +}); + + +test("a direct empty-area governed sandbox seals an existing checkout", async () => { + const f = fixture(); + try { + const prepared = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", areas: [] }); + const direct = { ...prepared, areas: [] }; + expect(await run(f.brain, direct, 'const fs=require("node:fs");let error="";try{fs.writeFileSync("workspaces/ithaca/new.md","attack")}catch(e){error=e.code}console.log(JSON.stringify({error}));', f.home), "DIRECT_SANDBOX_STILL_SEALS_WORKSPACE").toEqual({ error: "EROFS" }); + } finally { f.cleanup(); } +}); + +test("a workspace created in an absent-area turn is read-only on the next default turn", async () => { + const f = fixture({ workspaces: false }); + try { + const first = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", codeChanges: false }); + expect(first.profile).toBe("governed"); + expect(await run(f.brain, first, 'const fs=require("node:fs");fs.mkdirSync("workspaces/ithaca",{recursive:true});fs.writeFileSync("workspaces/ithaca/source.md","Athena");console.log(JSON.stringify({ok:true}));', f.home)).toEqual({ok:true}); + const next = prepareFixtureWorkerSandbox(f.brain, { profile: "governed", codeChanges: false }); + expect(await run(f.brain, next, 'const fs=require("node:fs");let error="";try{fs.writeFileSync("workspaces/ithaca/source.md","attack")}catch(e){error=e.code}console.log(JSON.stringify({read:fs.readFileSync("workspaces/ithaca/source.md","utf8"),error}));', f.home), "NEXT_TURN_SEALS_NEW_WORKSPACE").toEqual({ read: "Athena", error: "EROFS" }); + } finally { f.cleanup(); } +}); + + +test("a saved code-change switch cannot create its missing workspace prerequisite", () => { + const f=fixture({workspaces:false}); + try { + const sandbox=prepareFixtureWorkerSandbox(f.brain,{profile:"governed",codeChanges:true,protectedPaths:["workspaces/ithaca/protected.md"]}); + expect(existsSync(join(f.brain,"workspaces")),"PROTECTION_NEVER_MINTS_A_WORKSPACE").toBe(false); + expect(sandbox.areas.find(area=>area.name==="workspaces")!.mount.writable,"MISSING_WORKSPACE_NEVER_BECOMES_WRITABLE").toBe(false); + }finally{f.cleanup();} +}); + + +test("writer qualification follows scratch alias cleanup",()=>{ + const f=fixture();try{mkdirSync(join(f.brain,".brain/scratch"),{recursive:true});writeFileSync(join(f.brain,".gitignore"),".brain/scratch/\n");writeFileSync(join(f.brain,"workspaces/ithaca/source.ts"),"Athena");linkSync(join(f.brain,"workspaces/ithaca/source.ts"),join(f.brain,".brain/scratch/alias.ts")); + const plan=prepareCodeChangesSandbox(f.brain);expect(plan.scratchAliasesRemoved).toContain(".brain/scratch/alias.ts");expect(plan.areas.find(area=>area.name==="workspaces")!.mount.writable,"WRITER_RETAINS_PRE_INSPECTION_ALIAS_ORDER").toBe(true); + }finally{f.cleanup();} +}); + +test("legacy handoff rendering preserves an over-limit qualification without a write grant",()=>{ + const f=fixture();try{const plan=prepareFixtureWorkerSandbox(f.brain,{codeChanges:false,areas:["workspaces"]});const legacy=resolveWorkspacesMount(f.brain,1,true);expect(legacy.writable).toBe(false); + const note=workerSandboxNote({...plan,noteFacts:{legacyWorkspaces:legacy}},{},true);expect(note,"LEGACY_REFUSAL_IS_NOT_FABRICATED_AS_WRITABLE").toContain("more than 1 entries");expect(note).not.toContain("is writable: clone, fetch and commit");expect(plan.areas[0]!.mount.writable).toBe(false); + }finally{f.cleanup();} +}); diff --git a/packages/ui-sdk/tests/worker-startup-view.test.ts b/packages/ui-sdk/tests/worker-startup-view.test.ts index acb40a57c0..0167300bb9 100644 --- a/packages/ui-sdk/tests/worker-startup-view.test.ts +++ b/packages/ui-sdk/tests/worker-startup-view.test.ts @@ -73,13 +73,13 @@ test("strict persistent-area aliases cannot expose a governed peer's later confi mkdirSync(join(brain, "workspaces")); writeFileSync(join(brain, "workspaces/helper.ts"), 'export default "Odysseus before launch";'); writeFileSync(join(brain, "brain.config.ts"), 'export {default} from "/tmp/brain-worker-areas/workspaces/helper.ts";'); - const sandbox = prepareWorkerSandbox(brain, { profile: "strict", areas: ["workspaces"], readPaths: [process.execPath] }); + const sandbox = prepareWorkerSandbox(brain, { profile: "strict", codeChanges: true, areas: ["workspaces"], readPaths: [process.execPath] }); const worker = launchAgentWorker({ brainPath: brain, startupView: createWorkerStartupView(brain), sandbox, env: {}, command: ["/bin/sh", "-c", 'printf "ready\\n"; IFS= read -r go; exec "$1" --no-env-file -e \'console.log((await import("./brain.config.ts")).default)\'', "odysseus-reader", process.execPath] }); try { const [ready] = await once(worker.stdout, "data"); expect(String(ready)).toBe("ready\n"); - const peer = prepareWorkerSandbox(brain, { profile: "governed", areas: [] }); + const peer = prepareWorkerSandbox(brain, { profile: "governed", codeChanges: true, areas: ["workspaces"] }); const writer = Bun.spawnSync(workerCommand({ brainPath: brain, sandbox: peer, env: {}, command: ["/bin/sh", "-c", `printf '%s' 'export default "Odysseus during launch";' > workspaces/helper.ts`] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(writer.exitCode, writer.stderr.toString()).toBe(0); @@ -120,7 +120,7 @@ test("strict output publication holds the same path lock as a governed native wr const brain = fixture(); mkdirSync(join(brain, "workspaces")); const destination = join(brain, "workspaces/shared.md"); writeFileSync(destination, "before"); const lock = createKeyedLock(); const release = await lock.acquire(`path:${destination}`); - const sandbox = prepareWorkerSandbox(brain, { profile: "strict", areas: ["workspaces"] }); + const sandbox = prepareWorkerSandbox(brain, { profile: "strict", codeChanges: true, areas: ["workspaces"] }); const worker = launchAgentWorker({ brainPath: brain, startupView: createWorkerStartupView(brain), sandbox, outputLock: lock, env: {}, command: ["/bin/sh", "-c", "printf staged > /tmp/brain-worker-areas/workspaces/shared.md"] }); let settled = false; @@ -219,7 +219,7 @@ for (const link of ["relative", "absolute", "area-root"] as const) test(`strict writeFileSync(join(brain, "workspaces/harbor.txt"), "BRAIN_DOTENV_MARK=Odysseus\n"); fs.symlinkSync(link === "relative" ? "workspaces/harbor.txt" : link === "absolute" ? join(brain, "workspaces/harbor.txt") : `${WORKER_AREA_ROOT}/workspaces/harbor.txt`, join(brain, ".env")); - const sandbox = prepareWorkerSandbox(brain, { profile: "strict", areas: ["workspaces"], readPaths: [process.execPath] }); + const sandbox = prepareWorkerSandbox(brain, { profile: "strict", codeChanges: true, areas: ["workspaces"], readPaths: [process.execPath] }); const worker = launchAgentWorker({ brainPath: brain, startupView: createWorkerStartupView(brain), sandbox, env: {}, command: [process.execPath, "--no-env-file", "-e", `const fs=require("node:fs"),root=${JSON.stringify(WORKER_AREA_ROOT + "/workspaces")},read=p=>{try{return fs.readFileSync(p,"utf8")}catch(e){return e.code}};fs.writeFileSync(root+"/voyage.md","Odysseus keeps writing.");console.log(JSON.stringify({alias:read(".env"),copy:read(root+"/harbor.txt"),public:read("helper.ts")}));`] }); try { diff --git a/packages/ui-sdk/tests/workspace-refusal.test.ts b/packages/ui-sdk/tests/workspace-refusal.test.ts new file mode 100644 index 0000000000..5125d15626 --- /dev/null +++ b/packages/ui-sdk/tests/workspace-refusal.test.ts @@ -0,0 +1,21 @@ +import {expect,test} from "bun:test"; +import {workspaceWriteRefusal} from "../src/server/workspace-refusal.js"; +import type {WorkerSandbox} from "../src/server/worker-sandbox.js"; +const sentence="If this write was under workspaces/, the checkout is read-only in this turn: switch on code changes for this session (applies from the next message) or use a managed worktree."; +const sandbox:WorkerSandbox={brain:"/srv/odysseus-brain",profile:"strict",restricted:false,scratchAliasesRemoved:[],areas:[{name:"workspaces",rel:"workspaces",mount:{writable:false,readOnlyPath:"/srv/odysseus-brain/workspaces",reason:"inspection"}}]}; +test.each([ + ["mkdir workspaces/ithaca/build","mkdir: cannot create directory 'workspaces/ithaca/build': Read-only file system"], + ["mkdir -p workspaces/ithaca/build","mkdir: cannot create directory 'workspaces/ithaca/build': Read-only file system"], + ["git add raft.md","fatal: Unable to create 'workspaces/ithaca/.git/index.lock': Read-only file system"], + ["npm install","npm error code EROFS\nnpm error syscall mkdir"], + ["touch /outside/raft.md","touch: cannot touch '/outside/raft.md': Read-only file system"], +])("inspection remedy is conditional and independent of operands: %s",(command,error)=>{ + expect(workspaceWriteRefusal(sandbox,"bash",{command},undefined,error),"EXACT_CONDITIONAL_REMEDY_FOR_EVERY_READ_ONLY_FAILURE").toBe(sentence); +}); +test.each(["Write","write_file","mcp__brain__brain_write"])("file and host results receive the same conditional remedy: %s",tool=>{ + expect(workspaceWriteRefusal(sandbox,tool,{},undefined,{isError:true,content:[{type:"text",text:JSON.stringify({ok:false,message:"workspaces/ is read-only"})}]}),"STRUCTURED_FILE_AND_HOST_FAILURES_USE_THE_FIXED_SENTENCE").toBe(sentence); +}); +test("remedy needs inspection and a read-only failure, and is appended once",()=>{ + for(const areas of [[],[{name:"workspaces" as const,rel:"workspaces",mount:{writable:false as const,missing:true as const,reason:"absent"}}],[{name:"workspaces" as const,rel:"workspaces",mount:{writable:true as const,path:"/srv/odysseus-brain/workspaces"}}]])expect(workspaceWriteRefusal({...sandbox,areas},"bash",{},undefined,"EROFS")).toBeUndefined(); + expect(workspaceWriteRefusal(sandbox,"bash",{},undefined,"assertion failed")).toBeUndefined();expect(workspaceWriteRefusal(sandbox,"bash",{},undefined,sentence)).toBeUndefined(); +}); diff --git a/packages/ui-server/migrations/095_session_code_changes.sql b/packages/ui-server/migrations/095_session_code_changes.sql new file mode 100644 index 0000000000..d3546f5424 --- /dev/null +++ b/packages/ui-server/migrations/095_session_code_changes.sql @@ -0,0 +1,3 @@ +-- Code changes are a next-admission preference, independent of the profile. +ALTER TABLE session_worker_profiles ADD COLUMN code_changes INTEGER NOT NULL DEFAULT 0 CHECK (code_changes IN (0,1)); +ALTER TABLE draft_worker_profiles ADD COLUMN code_changes INTEGER NOT NULL DEFAULT 0 CHECK (code_changes IN (0,1)); diff --git a/packages/ui-server/src/brain/application.ts b/packages/ui-server/src/brain/application.ts index 230a5f93eb..d7c84fb954 100644 --- a/packages/ui-server/src/brain/application.ts +++ b/packages/ui-server/src/brain/application.ts @@ -1,4 +1,6 @@ /** One privileged Markdown application boundary, owned by the server. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { WORKSPACES_WRITE_REFUSAL } from "@schlessera/brain-common/internal/worker-areas"; import { closeSync, constants, existsSync, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, rmdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync, @@ -233,6 +235,8 @@ export function createBrainApplication(options: { policy: BrainApplicationPolicy; /** Captured host admission facts, never a worker-selected list. */ protectedPaths?: readonly string[]; + /** Frozen workspace inspection mode; privileged Markdown writes obey it too. */ + workspaceReadOnly?: boolean; /** The admitted turn's provider masks (#2690); `tool` names an operation as the agent called it. */ providerMasks?: { guard: ProviderMaskGuard; tool(operation: BrainApplicationInput["operation"]): string }; signal: AbortSignal; @@ -272,11 +276,15 @@ export function createBrainApplication(options: { beforeCommit?: () => void; }) { const root = realpathSync(options.root); + // Direct/approved host applications also need a frozen default when no + // governed bridge supplied mount facts. Absence stays ordinary this turn. + const workspaceReadOnly = options.workspaceReadOnly ?? Boolean(lstatSync(join(root, "workspaces"), { throwIfNoEntry: false })); // A protected path that is a link protects where it leads (#2876); a target // reached through a link refuses as an alias where it is opened. const isProtected = options.protectedPaths ? createProtectedTargetCheck(root, options.protectedPaths, { links: "refused" }) : undefined; const validateTarget = (path: string): void => { validatePath(path); + if (workspaceReadOnly && isWithin("workspaces", path)) refuse("policy_denied", WORKSPACES_WRITE_REFUSAL); if (isProtected?.(path)) refuse("policy_denied", PROTECTED_TARGET_REFUSAL); }; const planner = options.planner ?? boundaryPlanner(createHostBoundary({ brainPath: root })); diff --git a/packages/ui-server/src/brain/governed-turn.ts b/packages/ui-server/src/brain/governed-turn.ts index 1d82d2e8f5..36526c8615 100644 --- a/packages/ui-server/src/brain/governed-turn.ts +++ b/packages/ui-server/src/brain/governed-turn.ts @@ -43,6 +43,8 @@ export interface GovernedTurnHold { } /** Who a turn's inference reaches and which conversation it continues (#2695). */ export interface GovernedTurnRoute { + /** Session preference frozen before the first admission await. */ + readonly codeChanges?: boolean; /** * The exact origin the turn's host inference relay will forward to, from * its backend. It names the recipient only on managed native storage, where @@ -235,11 +237,11 @@ export function createGovernedTurns(options: { try { ensureRetainedDirectories(options.brainPath, folderPaths); } catch { /* resolver refuses */ } const requested = options.profile === "strict" || (origin === "interactive" && preference === "strict") ? "strict" : policy.policy.profiles[origin]; const selected = requested === "governed" && !availability.available ? "strict" : requested; - const resolveSandbox = () => prepareWorkerSandboxAsync(options.brainPath, { profile: selected, + const resolveSandbox = () => prepareWorkerSandboxAsync(options.brainPath, { profile: selected, codeChanges: route?.codeChanges === true, protectedPaths: protectedPaths(policy.policy), folderPaths, maskPaths: options.maskPaths, maintenance: { ...options.execution.boundary.maintenance, startupView } }); let resolved = await step("sandbox_resolve", resolveSandbox); - const missingWritableRoot = () => resolved.areas.find(area => area.mount.writable + const missingWritableRoot = () => resolved.areas.find(area => (area.mount.writable || area.mount.readOnlyPath) && !lstatSync(join(startupView!.root, area.rel), { throwIfNoEntry: false })?.isDirectory()); // Host setup may create scratch after the initial admission checkpoint. // Refresh only those first-turn sealed consumers, then validate against @@ -249,7 +251,7 @@ export function createGovernedTurns(options: { startupView = await step("startup_checkpoint_refresh", () => prepareNativeWorkerStartupView(options.brainPath, options.nativeManager, signal)); signal.throwIfAborted(); resolved = await step("sandbox_resolve_refresh", resolveSandbox); const missing = missingWritableRoot(); - if (missing) throw new Error(`The immutable worker checkpoint does not include writable ${missing.rel} after host setup; retry admission once concurrent setup has settled.`); + if (missing) throw new Error(`The immutable worker checkpoint does not include qualified ${missing.rel} after host setup; retry admission once concurrent setup has settled.`); // The turn runs on this newer checkpoint, so its types are judged // again there; retention was planned for the first translation. if (types.length) { @@ -307,6 +309,7 @@ export function createGovernedTurns(options: { // index current from it (#2846). Built from this final checkpoint. if (workerProfile(resolved) !== "governed" || privateIndex) { dataTree = await step("data_tree", () => createTurnDataTree({ brainPath: options.brainPath, view: startupView!, maskPaths: options.maskPaths, mount: workerProfile(resolved) !== "governed", signal, + inspectWorkspaces: resolved.areas.some(area => area.name === "workspaces" && !area.mount.writable && Boolean(area.mount.readOnlyPath)), ...(privateIndex ? { index: privateIndex, masks: { folders: maskedFolders, buildFolders: privateIndexBuildFolders(maskedFolders, startupView!.root), types: providerDeniedTypes(policy.policy, recipient) } } : {}), // A recipient allowed every folder still never sees the generated-text caches. diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 99a4a6a2cb..bc92f91307 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -1,3 +1,4 @@ +import { protectedPaths } from "@schlessera/brain-common/internal/protected-paths"; /** * The host execution boundary (#1648; docs/decisions/governed-writable-workers.md, * "The host execution boundary"). @@ -23,7 +24,7 @@ */ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { brainWorkerPath } from "@schlessera/brain-common/internal/worker-areas"; -import { existsSync, realpathSync } from "node:fs"; +import { existsSync, lstatSync, realpathSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; import type { Logger } from "@opentelemetry/api-logs"; import { @@ -35,11 +36,11 @@ import { } from "@schlessera/brain-ui-sdk/internal"; import { createKeyedLock, type KeyedLock, killWrapped, wrapCommand, type ExecWrapperConfig } from "@schlessera/brain-ui-sdk/server"; import { markUnpinnedHostWriter, refuseHostFallback, type GateHold, type GateMode, type WriterGate } from "./writer-gate.js"; -import { createGovernancePolicyReader } from "./governance-policy.js"; +import { governancePolicyReaderFor, retainedFolderRoots, providerTypeSelectors } from "./governance-policy.js"; import type { GovernedStatus, GovernedUnavailableReason } from "@schlessera/brain-ui-sdk/protocol"; import { runMirrorSync, syncMirrorPath } from "./sync-mirror.js"; import { moduleRepositoryWorkerAccess, type ModuleRepositoryAccess } from "./module-repositories.js"; -import { resolveWorkerProtection } from "@schlessera/brain-ui-sdk/internal"; +import { resolveWorkspacesMount, resolveWorkerProtection } from "@schlessera/brain-ui-sdk/internal"; import { prepareMaintenanceOutput } from "./maintenance-output.js"; import { operationalStateMasks, operationalStateRefusal, workerIdentitySentinelDirectory, type OperationalStateLayout, type WorkerProbeState } from "./operational-state.js"; import { prepareMaintenanceGit } from "./maintenance-git.js"; @@ -535,7 +536,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { // A gated host writer is refused inside its gate transaction. An ungated // one (`gate: none`, runSync) still checks every active writer's retained // plan when a gate exists; with no gate at all, only the policy is known. - const policyReader = createGovernancePolicyReader(brain); + const policyReader = governancePolicyReaderFor(brain); // Each settles once its check has committed (#2850); nothing spawns before. const admitHost = async (hold: GateHold | null) => { if (hold) return markUnpinnedHostWriter(hold); @@ -610,12 +611,25 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { const identity = ordinary.ok && ordinary.identity === "separate_uid" ? { identity: "separate_uid" as const, workerUid: ordinary.workerUid } : configuredIdentity ? {} : { identity: "shared_uid" as const }; - const protection = resolveWorkerProtection(brain); - const profile = options.profile === "strict" || !availability.available || protection.reason ? "strict" : "governed"; - return { hostExecution: isolated() ? "worker" : "host", ...availability, profile, + const policy = policyReader.load(); + const folderPaths = retainedFolderRoots(policy.policy).filter(path => { + if (![".brain-index", ".brain-cache"].includes(path)) return true; + try { return lstatSync(join(brain, path), { throwIfNoEntry: false }) !== undefined; } catch { return true; } + }); + const protection = resolveWorkerProtection(brain, { paths: protectedPaths(policy.policy), readOnlyRoots: ["workspaces"], folderPaths, prepare: false }); + let workspaceFallback: string | undefined; + try { + const workspace = resolveWorkspacesMount(brain); + if (!workspace.writable && !workspace.missing && !workspace.readOnlyPath) workspaceFallback = workspace.reason; + } catch { workspaceFallback = "workspaces/ could not be qualified"; } + const fallback = protection.reason ?? workspaceFallback; + const unresolvedTypes = providerTypeSelectors(policy.policy).length > 0; + const profile = options.profile === "strict" || policy.policy.profiles.interactive === "strict" || !availability.available || fallback ? "strict" : "governed"; + const qualifiedProfile = profile === "strict" || !unresolvedTypes ? profile : undefined; + return { hostExecution: isolated() ? "worker" : "host", ...availability, ...(qualifiedProfile ? { profile: qualifiedProfile } : {}), protectedPaths: protection.protection.paths.map(({ rel, mode, reason }) => ({ path: rel, mode, reason })), - ...(protection.reason ? { profileFallback: protection.reason } : {}), - ...identity, configurationView: profile === "governed" ? "live" : "startup", + ...(fallback ? { profileFallback: fallback } : unresolvedTypes && !qualifiedProfile ? { profileFallback: "Provider type folder qualification is unresolved in read-only status; each admission resolves it on its checkpoint." } : {}), + ...identity, ...(qualifiedProfile ? { configurationView: qualifiedProfile === "governed" ? "live" as const : "startup" as const } : {}), egress: hasManagedNativeStorage(brain) ? { active: true, detail: `${TURN_EGRESS_ACTIVE} ${options.providerRelay ? PROVIDERS_RELAYED : PROVIDERS_NOT_RELAYED}` } : { active: false, detail: TURN_EGRESS_INACTIVE } }; }, diff --git a/packages/ui-server/src/brain/journal-store.ts b/packages/ui-server/src/brain/journal-store.ts index 3d2614c52d..a605e58def 100644 --- a/packages/ui-server/src/brain/journal-store.ts +++ b/packages/ui-server/src/brain/journal-store.ts @@ -89,6 +89,8 @@ export interface ObservationRecord { steeringPaths: string[]; /** Every turn observing this window, this one included. */ overlaps: string[]; + /** Only turns whose frozen coverage includes this path participate in its conflicts. */ + pathObservers?: Record; /** Changes of this turn's managed worktrees, already in journal path form. */ worktree: { path: string; scope: string; before: JournalVersion | null; after: JournalVersion | null }[]; steeringUnavailable: string[]; @@ -252,7 +254,7 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur const actor = approvedPolicy || metadata.kind === "revert" ? "user" : "agent"; const restricted = classification === "steering" && actor === "agent" && taint !== null; const source = restricted && taint!.eventId > 0 ? taint!.eventId : null; - const overlappingTurnIds = record.overlaps.filter(id => id !== turnId); + const overlappingTurnIds = (record.pathObservers?.[item.path] ?? record.overlaps).filter(id => id !== turnId); db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps,taint_source_event_id,effective_taint) VALUES (?,?,?,?,?,?,?,?,?,?,?)") .run(turnId, sequence, item.path, item.scope, item.before ? JSON.stringify(item.before) : null, item.after ? JSON.stringify(item.after) : null, classification, actor, JSON.stringify(overlappingTurnIds), source, restricted ? 1 : 0); if (classification === "steering") recordGovernanceEvent(db, { kind: "steering_change", sessionId: metadata.session_id, turnId, diff --git a/packages/ui-server/src/brain/markup-application.ts b/packages/ui-server/src/brain/markup-application.ts index d181867e3e..580ea2c20b 100644 --- a/packages/ui-server/src/brain/markup-application.ts +++ b/packages/ui-server/src/brain/markup-application.ts @@ -8,6 +8,8 @@ * the policy-protected targets, live turn authority and membership. A layer * never replaces an earlier one: each submission takes the first free name. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { WORKSPACES_WRITE_REFUSAL } from "@schlessera/brain-common/internal/worker-areas"; import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, unlinkSync, writeFileSync } from "node:fs"; import { inflateSync } from "node:zlib"; import { join } from "node:path"; @@ -242,6 +244,7 @@ export function createMarkupApplication(options: { lock: Pick; /** Immutable admitted host facts; not a browser or worker permission. */ protectedPaths?: readonly string[]; + workspaceReadOnly?: boolean; /** Whether the layer may commit now; false while a `hold` is active as well as once authority is gone. */ isAuthorized(): boolean; hold?: AuthorityHold; @@ -254,9 +257,10 @@ export function createMarkupApplication(options: { }) { const root = realpathSync(options.root); const protectedPaths = [...(options.protectedPaths ?? [])]; - const isProtected = options.protectedPaths ? createProtectedTargetCheck(root, protectedPaths, { links: "refused" }) : undefined; + const isProtected = (options.protectedPaths || options.workspaceReadOnly) ? createProtectedTargetCheck(root, protectedPaths, { links: "refused" }) : undefined; const validateTarget = (path: string, what: "image" | "layer"): void => { validatePath(path, what); + if (what === "layer" && options.workspaceReadOnly && isWithin("workspaces", path)) refuse("policy_denied", WORKSPACES_WRITE_REFUSAL); if (isProtected?.(path)) refuse("policy_denied", "This markup target is protected by the policy admitted for this turn; no change was applied."); }; const authority = (principalId: string, turnId: string) => { @@ -364,7 +368,7 @@ export function createMarkupApplication(options: { // The layer this operation just wrote is protected from its own // cleanup; later passes apply the usual scratch policy. const pruned = core.pruneScratch(root, Date.now(), { pinnedPaths: new Set([markupPath!]), - protectedPaths: options.protectedPaths ? protectedPlaces(root, protectedPaths) : protectedPaths }); + protectedPaths: (options.protectedPaths || options.workspaceReadOnly) ? protectedPlaces(root, protectedPaths, options.workspaceReadOnly) : protectedPaths }); for (const removal of pruned.removed) { changes.push({ path: removal.path, contentHash: null }); effects.push({ path: removal.path, content: null, base: null }); diff --git a/packages/ui-server/src/brain/mask-application.ts b/packages/ui-server/src/brain/mask-application.ts index 0e1c53d457..fa5ccb3230 100644 --- a/packages/ui-server/src/brain/mask-application.ts +++ b/packages/ui-server/src/brain/mask-application.ts @@ -1,4 +1,6 @@ /** Server-owned PNG mask application. No worker-selected binary kind or command. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { WORKSPACES_WRITE_REFUSAL } from "@schlessera/brain-common/internal/worker-areas"; import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { createHash } from "node:crypto"; @@ -103,6 +105,7 @@ export function createMaskApplication(options: { lock: Pick; /** Immutable admitted host facts; not a browser or worker permission. */ protectedPaths?: readonly string[]; + workspaceReadOnly?: boolean; /** Whether the mask may commit now; false while a `hold` is active as well as once authority is gone. */ isAuthorized(): boolean; /** Holds that stop changes without revoking authority (#2853); the mask waits for them, bounded. */ @@ -120,9 +123,10 @@ export function createMaskApplication(options: { }) { const root = realpathSync(options.root); const protectedPaths = [...(options.protectedPaths ?? [])]; - const isProtected = options.protectedPaths ? createProtectedTargetCheck(root, protectedPaths, { links: "refused" }) : undefined; + const isProtected = (options.protectedPaths || options.workspaceReadOnly) ? createProtectedTargetCheck(root, protectedPaths, { links: "refused" }) : undefined; const validateTarget = (path: string): void => { validatePath(path); + if (options.workspaceReadOnly && isWithin("workspaces", path)) refuse("policy_denied", WORKSPACES_WRITE_REFUSAL); if (isProtected?.(path)) refuse("policy_denied", "This mask target is protected by the policy admitted for this turn; no change was applied."); }; const authority = (principalId: string, turnId: string) => { @@ -200,7 +204,7 @@ export function createMaskApplication(options: { // own cleanup (#1691); later passes apply the usual policy. // Prune retains what protection covers now, where links lead included (#2876). const pruned = core.pruneScratch(root, Date.now(), { pinnedPaths: new Set([input.maskPath]), - protectedPaths: options.protectedPaths ? protectedPlaces(root, protectedPaths) : protectedPaths }); + protectedPaths: (options.protectedPaths || options.workspaceReadOnly) ? protectedPlaces(root, protectedPaths, options.workspaceReadOnly) : protectedPaths }); for (const removal of pruned.removed) { changes.push({ path: removal.path, contentHash: null }); effects.push({ path: removal.path, content: null, base: null }); diff --git a/packages/ui-server/src/brain/native-journal-capture.ts b/packages/ui-server/src/brain/native-journal-capture.ts index 4917ead2f0..f325f7dec4 100644 --- a/packages/ui-server/src/brain/native-journal-capture.ts +++ b/packages/ui-server/src/brain/native-journal-capture.ts @@ -1,7 +1,7 @@ /** Changed versions only; checkpoint advancement follows the journal commit. */ import { JournalObjectQuarantined } from "./journal-accounting.js"; import { createNativeJournalObserver, type NativeJournalManager, type NativeJournalMetadata, type NativeJournalUnreadable } from "./native-journal-observer.js"; -import { freezeNativeJournalPolicy, journalMetadataOnlyPath, journalPathScope } from "./native-journal-policy.js"; +import { freezeNativeJournalPolicy, journalMetadataOnlyPath } from "./native-journal-policy.js"; import { nativeJournalPermissionDenied, readNativeJournalFile, withNativeJournalFile, type NativeJournalReadContext } from "./native-journal-read.js"; import { verifiedWorkerIdentity, workerIdentityHelper } from "@schlessera/brain-ui-sdk/internal"; import { isJournalSteeringPath, nativeJournalSteeringInputs, type JournalSteeringOptions } from "./journal-steering.js"; @@ -32,23 +32,24 @@ export function createNativeJournalCapture(manager: NativeJournalManager, retain }; const observer = createNativeJournalObserver(manager, workerUid, releaseFailed); const entry = (metadata: NativeJournalMetadata, policy: NativeJournalPolicy): JournalSnapshotEntry | undefined => { - const scope = journalPathScope(metadata.path); - if (!scope || metadata.kind === "directory") return undefined; + const scope = policy.location(metadata.path); + if (policy.excluded(metadata.path) || !scope || metadata.kind === "directory") return undefined; return { ...metadata, kind: metadata.kind, scope: scope.scope, ignored: policy.ignored(metadata.path), ...(rootScope.index && journalMetadataOnlyPath(metadata.path) ? { metadataOnly: true as const } : {}) }; }; /** Ignored and metadata-only versions keep their observed facts and never their bytes. */ const retained = (entry: JournalSnapshotEntry) => entry.kind === "file" && !entry.ignored && !entry.metadataOnly; return { - async initialize(signal?: AbortSignal) { await observer.initialize(signal); }, - async policy(covered: readonly string[] = []): Promise { + async initialize(signal?: AbortSignal, options: { workspaces?: boolean } = {}) { await observer.initialize(signal, options); }, + async policy(covered: readonly string[] = [], options: { workspaces?: boolean; ordinaryWorkspaces?: boolean } = {}, signal?: AbortSignal): Promise { + if (options.workspaces !== false) await observer.includeWorkspaces(signal); const root = observer.currentRoot(); - return freezeNativeJournalPolicy(observer.ignoreEntries(), (path, maximum) => readNativeJournalFile(root.path, path, maximum, context(root)), covered); + return freezeNativeJournalPolicy(observer.ignoreEntries(), (path, maximum) => readNativeJournalFile(root.path, path, maximum, context(root, signal)), covered, { ordinaryWorkspaces: !rootScope.index, ...options, signal }); }, - allowed(path: string, policy: NativeJournalPolicy): boolean { return !!journalPathScope(path) && !policy.ignored(path) && !(rootScope.index && journalMetadataOnlyPath(path)); }, + allowed(path: string, policy: NativeJournalPolicy): boolean { return !policy.excluded(path) && !!policy.location(path) && !policy.ignored(path) && !(rootScope.index && journalMetadataOnlyPath(path)); }, eligible(path: string, policy: NativeJournalPolicy): boolean { const metadata = observer.get(path); - return !!metadata && metadata.kind === "file" && metadata.bytes <= 64 * 1024 * 1024 && !policy.ignored(path) && !!journalPathScope(path) && !(rootScope.index && journalMetadataOnlyPath(path)); + return !policy.excluded(path) && !!metadata && metadata.kind === "file" && metadata.bytes <= 64 * 1024 * 1024 && !policy.ignored(path) && !!policy.location(path) && !(rootScope.index && journalMetadataOnlyPath(path)); }, /** Exact current sealed before-version; the caller keeps the ordinary policy and storage owner. */ async retainBefore(path: string, policy: NativeJournalPolicy, signal?: AbortSignal): Promise { @@ -64,7 +65,7 @@ export function createNativeJournalCapture(manager: NativeJournalManager, retain return { ...result, hash }; }, async observe(policies: ReadonlyMap, signal?: AbortSignal, timing?: PhaseTimer) { - const observation = await observer.observe(signal, timing); + const observation = await observer.observe(signal, timing, { workspaces: [...policies.values()].some(policy => !policy.excluded("workspaces")) }); const end = timing?.("observe_capture"); try { const captured = new Map(); @@ -109,46 +110,49 @@ export function createNativeJournalCapture(manager: NativeJournalManager, retain // Classification retains no unchanged bytes. Its metadata inventory is // shared; bounded configuration reads come from the two pinned roots. const changed = new Map(observation.changes.map(change => [change.path, change.after])); - const snapshots: { entries: JournalSnapshotEntry[]; missing: never[] }[] = []; - const roots = new Map(); - const included = { ignored(path: string) { return [...policies.values()].every(policy => policy.ignored(path)); } } as NativeJournalPolicy; - const classified = (metadata: NativeJournalMetadata, root: typeof observation.beforeRoot) => { - const value = entry(metadata, included); - if (!value) return undefined; - const stamp = `${root.id}:${value.stamp}`; - roots.set(stamp, root); - return { ...value, stamp }; - }; - if (rootScope.steering && policies.size && observation.changes.length) { - for (const [root, after] of [[observation.beforeRoot, false], [observation.afterRoot, true]] as const) { - const entries: JournalSnapshotEntry[] = []; - const append = (metadata: NativeJournalMetadata) => { - const value = classified(metadata, root); if (value) entries.push(value); - }; - for (const metadata of observer.steeringEntries()) { - const replacement = after && changed.has(metadata.path) ? changed.get(metadata.path) : metadata; - if (replacement) append(replacement); + const steering = new Map> & { inventoried: boolean }>(); + for (const [turnId, policy] of policies) { + const snapshots: { entries: JournalSnapshotEntry[]; missing: never[] }[] = []; + const roots = new Map(); + const classified = (metadata: NativeJournalMetadata, root: typeof observation.beforeRoot) => { + const value = entry(metadata, policy); + if (!value) return undefined; + const stamp = `${root.id}:${value.stamp}`; + roots.set(stamp, root); + return { ...value, stamp }; + }; + if (rootScope.steering && observation.changes.length) { + for (const [root, after] of [[observation.beforeRoot, false], [observation.afterRoot, true]] as const) { + const entries: JournalSnapshotEntry[] = []; + const append = (metadata: NativeJournalMetadata) => { + const value = classified(metadata, root); if (value) entries.push(value); + }; + for (const metadata of observer.steeringEntries()) { + const replacement = after && changed.has(metadata.path) ? changed.get(metadata.path) : metadata; + if (replacement) append(replacement); + } + if (after) for (const change of observation.changes) + if (!change.before && change.after && isJournalSteeringPath(change.path)) append(change.after); + snapshots.push({ entries, missing: [] }); } - if (after) for (const change of observation.changes) - if (!change.before && change.after && isJournalSteeringPath(change.path)) append(change.after); - snapshots.push({ entries, missing: [] }); } + const classifiedSteering = await nativeJournalSteeringInputs(snapshots, + (item, maximum) => { const root = roots.get(item.stamp)!; return readNativeJournalFile(root.path, item.path, maximum, context(root, signal)); }, + path => { + // Match the before/after inventory union without cloning the full + // metadata map. Deleted references remain classifiable from before. + const after = changed.get(path); + if (after) return classified(after, observation.afterRoot); + const before = observer.get(path); + return before ? classified(before, changed.has(path) ? observation.beforeRoot : observation.afterRoot) : undefined; + }, steeringOptions); + for (const item of unreadable.values()) if (item.kind === "directory" || item.bytes === null) classifiedSteering.unavailable.push(item.path); + steering.set(turnId, { ...classifiedSteering, inventoried: snapshots.length > 0 }); } - const steering = await nativeJournalSteeringInputs(snapshots, - (item, maximum) => { const root = roots.get(item.stamp)!; return readNativeJournalFile(root.path, item.path, maximum, context(root, signal)); }, - path => { - // Match the before/after inventory union without cloning the full - // metadata map. Deleted references remain classifiable from before. - const after = changed.get(path); - if (after) return classified(after, observation.afterRoot); - const before = observer.get(path); - return before ? classified(before, changed.has(path) ? observation.beforeRoot : observation.afterRoot) : undefined; - }, steeringOptions); - for (const item of unreadable.values()) if (item.kind === "directory" || item.bytes === null) steering.unavailable.push(item.path); end?.(); // Without a change the inventory is not taken: an empty set then says // nothing about the brain's configuration (#3257). - return { changes, steering: { ...steering, inventoried: snapshots.length > 0 }, unreadable: [...unreadable.values()], stats: observation.stats, commit: observation.commit, abort: observation.abort }; + return { changes, steering, unreadable: [...unreadable.values()], stats: observation.stats, commit: observation.commit, abort: observation.abort }; } catch (error) { await observation.abort().catch(() => {}); throw error; } }, releases() { return observer.releases(); }, diff --git a/packages/ui-server/src/brain/native-journal-observer.ts b/packages/ui-server/src/brain/native-journal-observer.ts index 5c4c34ef4a..909d91bcfe 100644 --- a/packages/ui-server/src/brain/native-journal-observer.ts +++ b/packages/ui-server/src/brain/native-journal-observer.ts @@ -79,11 +79,12 @@ class MetadataIndex { readonly entries = new Map(); readonly children = new Map>(); readonly inodes = new Map>(); + readonly workspacePaths = new Set(); readonly ignoreInputs = new Map(); readonly steeringInputs = new Map(); remove(path: string): void { const entry = this.entries.get(path); if (!entry) return; - this.entries.delete(path); this.ignoreInputs.delete(path); this.steeringInputs.delete(path); + this.entries.delete(path); this.workspacePaths.delete(path); this.ignoreInputs.delete(path); this.steeringInputs.delete(path); const directory = parent(path), children = this.children.get(directory); children?.delete(path); if (!children?.size) this.children.delete(directory); const names = this.inodes.get(entry.inode); names?.delete(path); @@ -91,6 +92,7 @@ class MetadataIndex { } put(entry: NativeJournalMetadata): void { this.remove(entry.path); this.entries.set(entry.path, entry); + if (isWithin("workspaces", entry.path)) this.workspacePaths.add(entry.path); if (entry.path.split("/").at(-1) === ".gitignore") this.ignoreInputs.set(entry.path, entry); if (isJournalSteeringPath(entry.path)) this.steeringInputs.set(entry.path, entry); const directory = parent(entry.path), children = this.children.get(directory) ?? new Set(); @@ -112,18 +114,19 @@ class RootMetadataReader { private constructor(private readonly root: FileHandle | undefined, private readonly signal: AbortSignal, private readonly checkpointId: string, private readonly manager: NativeJournalManager, private readonly workerUid?: () => number | undefined, private readonly known: (path: string) => NativeJournalMetadata | undefined = () => undefined, + private readonly workspaces = true, readonly stats = { readEntries: 0, walkedDirectories: 0 }) {} static async create(root: NativeJournalCheckpoint, signal: AbortSignal, manager: NativeJournalManager, workerUid?: () => number | undefined, - known?: (path: string) => NativeJournalMetadata | undefined) { + known?: (path: string) => NativeJournalMetadata | undefined, workspaces = true) { signal.throwIfAborted(); if (root.readOnly !== true) unavailable("Native metadata requires a sealed checkpoint."); let descriptor: FileHandle; try { descriptor = await open(root.path, DIRECTORY); } catch (error) { if (!nativeJournalPermissionDenied(error) || workerUid?.() === undefined) throw error; - return new RootMetadataReader(undefined, signal, root.id, manager, workerUid, known); + return new RootMetadataReader(undefined, signal, root.id, manager, workerUid, known, workspaces); } - try { signal.throwIfAborted(); return new RootMetadataReader(descriptor, signal, root.id, manager, workerUid, known); } + try { signal.throwIfAborted(); return new RootMetadataReader(descriptor, signal, root.id, manager, workerUid, known, workspaces); } catch (error) { await descriptor.close(); throw error; } } private markUnreadable(path: string, known = this.known(path), ms = 0): undefined { @@ -137,30 +140,32 @@ class RootMetadataReader { try { return await this.manager.statCheckpoint(this.checkpointId, path, uid, this.signal); } catch (error) { if (nativeJournalPermissionDenied(error)) return this.markUnreadable(path, this.known(path), Math.max(0, Math.round(performance.now() - started))); throw error; } } - private async child(parentFd: number, name: string, path: string): Promise { + private async child(parentFd: number, name: string, path: string, bounded = true): Promise { this.signal.throwIfAborted(); this.stats.readEntries++; const info = await lstat(at(parentFd, name), { bigint: true }); - if (info.isDirectory() && path.split("/").length > 256) unavailable("Native metadata directory depth exceeds the supported bound."); + if (bounded && info.isDirectory() && path.split("/").length > 256) unavailable("Native metadata directory depth exceeds the supported bound."); const target = info.isSymbolicLink() ? rawText(await readlink(at(parentFd, name), { encoding: "buffer" })) : undefined; this.signal.throwIfAborted(); return metadata(path, info, target); } - async get(path: string): Promise { + async get(path: string, aliasProbe = false): Promise { + if (!aliasProbe && !this.workspaces && isWithin("workspaces", path)) return null; const parts = path.split("/"); if (!path || parts.some(part => !part || part === "." || part === ".." || part.includes("\0"))) unavailable("Invalid native metadata path."); - if (parts.length > 257) unavailable("Native metadata directory depth exceeds the supported bound."); + if (!aliasProbe && parts.length > 257) unavailable("Native metadata directory depth exceeds the supported bound."); if (!this.root) { const uid = this.workerUid?.(); if (uid === undefined || !this.manager.statCheckpoint) throw new NativeJournalObservationError("Private checkpoint metadata requires the qualified fixed worker-UID reader."); return this.privateStat(path, uid); } - const chain: FileHandle[] = []; - let fd = this.root.fd; + // A single path probe retains only one parent descriptor, including deep + // excluded aliases. It never inventories a checkout directory. + let cursor: FileHandle | undefined; try { for (const name of parts.slice(0, -1)) { - this.signal.throwIfAborted(); const child = await open(at(fd, name), DIRECTORY); - chain.push(child); fd = child.fd; + this.signal.throwIfAborted(); const child = await open(at(cursor?.fd ?? this.root.fd, name), DIRECTORY); + await cursor?.close(); cursor = child; } - return await this.child(fd, parts.at(-1)!, path); + return await this.child(cursor?.fd ?? this.root.fd, parts.at(-1)!, path, !aliasProbe); } catch (error) { if (missing(error)) return null; const uid = nativeJournalPermissionDenied(error) ? this.workerUid?.() : undefined; @@ -168,9 +173,10 @@ class RootMetadataReader { if (!this.manager.statCheckpoint) unavailable("Private checkpoint metadata requires the fixed worker-UID reader."); return this.privateStat(path, uid); } - finally { for (const child of chain.reverse()) await child.close(); } + finally { await cursor?.close(); } } async *walk(path = ""): AsyncGenerator { + if (!this.workspaces && isWithin("workspaces", path)) return; const parts = path ? path.split("/") : [], chain: FileHandle[] = []; if (!this.root) { const uid = this.workerUid?.(); @@ -204,6 +210,7 @@ class RootMetadataReader { const name = rawText(bytes); if (!name || name.includes("/") || name.includes("\0") || name === "." || name === "..") unavailable("Invalid native directory entry."); const rel = path ? `${path}/${name}` : name; + if (!this.workspaces && isWithin("workspaces", rel)) continue; let entry: NativeJournalMetadata; try { entry = await this.child(fd, name, rel); } catch (error) { @@ -234,6 +241,7 @@ class RootMetadataReader { try { entries = await this.manager.listCheckpoint(this.checkpointId, path, uid, this.signal); } catch (error) { if (nativeJournalPermissionDenied(error)) { this.markUnreadable(path, known, Math.max(0, Math.round(performance.now() - started))); return; } throw error; } for (const entry of entries) { + if (!this.workspaces && isWithin("workspaces", entry.path)) continue; this.signal.throwIfAborted(); this.stats.readEntries++; yield entry; if (entry.kind === "directory") yield* this.walkPrivate(entry.path, depth + 1, uid, true, entry); @@ -281,6 +289,7 @@ export interface NativeJournalReleaseAccounting { * observation committed, outside the caller's hold. */ export function createNativeJournalObserver(native: NativeJournalManager, workerUid?: () => number | undefined, releaseFailed?: (error: unknown, checkpointId: string) => void, releaseRetryMs = 30_000) { + let inventoryWorkspaces = true; let index = new MetadataIndex(), root: NativeJournalCheckpoint | undefined; let missingInventory = new Map(); const uncertain = (path: string) => { @@ -374,7 +383,7 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker if (entry) entry.state = "pending"; else outstanding.set(id, { bytes, state: "pending" }); releaseNext(); } - async function initialize(signal?: AbortSignal): Promise { + async function initialize(signal?: AbortSignal, options: { workspaces?: boolean } = {}): Promise { if (closed) unavailable("Native observer is closed."); if (root) return; if (initializing) return initializing; @@ -382,17 +391,35 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker initializing = (async () => { let captured: NativeJournalCheckpoint | undefined, reader: RootMetadataReader | undefined; try { - captured = await checkpoint(active); reader = await RootMetadataReader.create(captured, active, native, workerUid); + captured = await checkpoint(active); reader = await RootMetadataReader.create(captured, active, native, workerUid, undefined, options.workspaces !== false); const initial = new MetadataIndex(); for await (const entry of reader.walk()) initial.put(entry); - active.throwIfAborted(); index = initial; root = captured; missingInventory = new Map(reader.unreadable); + active.throwIfAborted(); inventoryWorkspaces = options.workspaces !== false; index = initial; root = captured; missingInventory = new Map(reader.unreadable); } catch (error) { if (captured) await release(captured).catch(() => {}); throw error; } finally { await reader?.close(); initializing = undefined; } })(); return initializing; } - async function prepare(signal?: AbortSignal, timing?: PhaseTimer): Promise { - await initialize(signal); + // A newly admitted writer needs a baseline from the current sealed root; + // inspect-only turns never pay for this inventory. + async function includeWorkspaces(signal?: AbortSignal): Promise { + if (!root || inventoryWorkspaces) return; + const active = signalFor(signal), reader = await RootMetadataReader.create(root, active, native, workerUid); + try { + const workspace = await reader.get("workspaces"), entries: NativeJournalMetadata[] = []; + if (workspace) { + entries.push(workspace); + if (workspace.kind === "directory") for await (const entry of reader.walk("workspaces")) entries.push(entry); + } + active.throwIfAborted(); + for (const entry of entries) index.put(entry); + for (const [path, value] of reader.unreadable) missingInventory.set(path, value); + inventoryWorkspaces = true; + } finally { await reader.close(); } + } + async function prepare(signal?: AbortSignal, timing?: PhaseTimer, workspaces = true): Promise { + await initialize(signal, { workspaces }); + if (workspaces) await includeWorkspaces(signal); // The wait for room behind earlier releases (#2915), before any checkpoint. let end = timing?.("observe_reserve"); await reserveRelease(); @@ -407,13 +434,19 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker // Observe an early transport failure without an unhandled rejection. void job.completed.catch(() => {}); const paths = new Set(), prefixes = new Set(); + const excludedAliases = new Map(); + const renames: { from: string; to: string }[] = []; try { for await (const candidate of parseNativeBrainDelta(job.stream, { before: { uuid: before.uuid, transaction: BigInt(before.transaction) }, after: { uuid: after.uuid, transaction: BigInt(after.transaction) }, signal: active, })) { - for (const path of candidate.paths) paths.add(path); - if (candidate.rename) { prefixes.add(candidate.rename.from); prefixes.add(candidate.rename.to); } + for (const path of candidate.paths) { + if (workspaces || !isWithin("workspaces", path)) paths.add(path); + else { const at = renames.length + (candidate.rename?.to === path ? 1 : 0); excludedAliases.set(`${at}:${path}`, {path, at}); } + } + if (candidate.rename) renames.push(candidate.rename); + if (candidate.rename) for (const path of [candidate.rename.from, candidate.rename.to]) if (workspaces || !isWithin("workspaces", path)) prefixes.add(path); } const outcome = await job.completed; if (outcome.exitCode !== 0) unavailable("Native delta helper did not exit successfully."); @@ -423,9 +456,32 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker await job.completed.catch(() => {}); throw error; } end?.(); end = timing?.("observe_metadata"); + // A send update may name only an excluded alias of an ordinary note. + // Recover its inode from both sealed roots before dropping the namespace. + let aliasEntries = 0; + const excludedBefore = new Map(), excludedAfter = new Map(); + if (excludedAliases.size) for (const checkpoint of [before, after]) { + const aliases = await RootMetadataReader.create(checkpoint, active, native, workerUid); + try { + for (const {path, at} of excludedAliases.values()) { + // Each name belongs to its stream operation's namespace, not the + // final tree. Preserve that point across reused names and cycles. + let original = path; + if (checkpoint === before) { + for (const rename of renames.slice(0, at).reverse()) if (isWithin(rename.to, original)) original = rename.from + original.slice(rename.to.length); + } else for (const rename of renames.slice(at)) if (isWithin(rename.from, original)) original = rename.to + original.slice(rename.from.length); + const entry = await aliases.get(original, true); + if (entry === undefined) unavailable("Excluded alias metadata is unavailable for note attribution."); + if (entry?.kind === "file") (checkpoint === before ? excludedBefore : excludedAfter).set(original, entry); + if (entry?.kind === "file") for (const alias of index.inodes.get(entry.inode) ?? []) + if (!isWithin("workspaces", alias)) paths.add(alias); + } + aliasEntries += aliases.stats.readEntries; + } finally { await aliases.close(); } + } const patches = new Map(); reader = await RootMetadataReader.create(after, active, native, workerUid, - path => patches.has(path) ? patches.get(path) ?? undefined : index.entries.get(path)); + path => patches.has(path) ? patches.get(path) ?? undefined : index.entries.get(path), workspaces); const read = async (path: string) => { if (!patches.has(path)) patches.set(path, await reader!.get(path)); return patches.get(path)!; @@ -445,6 +501,7 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker } } for (const missing of missingInventory.keys()) { + if (!workspaces && isWithin("workspaces", missing)) continue; if (missing === ".") { newDirectories.add(""); oldDirectories.add(""); continue; } const current = await read(missing); if (current?.kind === "directory") { newDirectories.add(missing); oldDirectories.add(missing); paths.add(missing); } @@ -454,7 +511,7 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker if (index.entries.get(prefix)?.kind === "directory") oldDirectories.add(prefix); if ((await read(prefix))?.kind === "directory") newDirectories.add(prefix); } - for (const prefix of outerPrefixes(oldDirectories)) for (const path of index.descendants(prefix)) paths.add(path); + for (const prefix of outerPrefixes(oldDirectories)) for (const path of index.descendants(prefix)) if (workspaces || !isWithin("workspaces", path)) paths.add(path); for (const prefix of outerPrefixes(newDirectories)) { for await (const entry of reader.walk(prefix)) { paths.add(entry.path); patches.set(entry.path, entry); } } @@ -463,7 +520,7 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker for (const path of paths) { const previous = index.entries.get(path), current = await read(path); for (const entry of [previous, current]) if (entry?.kind === "file") { - for (const alias of index.inodes.get(entry.inode) ?? []) paths.add(alias); + for (const alias of index.inodes.get(entry.inode) ?? []) if (workspaces || !isWithin("workspaces", alias)) paths.add(alias); } } active.throwIfAborted(); @@ -476,14 +533,19 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker } const next = after; // Content the previous root alone keeps once this observation commits. - let replacedBytes = 0; - for (const change of changes) if (change.before?.kind === "file" && change.before.stamp !== change.after?.stamp) replacedBytes += change.before.bytes; + const replaced = new Map(); + const excludedCurrentInodes = new Map([...excludedAfter.values()].map(entry => [entry.inode, entry])); + for (const entry of excludedBefore.values()) if (entry.stamp !== excludedCurrentInodes.get(entry.inode)?.stamp) replaced.set(entry.inode, entry.bytes); + for (const change of changes) if (change.before?.kind === "file" && change.before.stamp !== change.after?.stamp) replaced.set(change.before.inode, change.before.bytes); + const replacedBytes = [...replaced.values()].reduce((sum, bytes) => sum + bytes, 0); let state: "pending" | "committed" | "aborted" = "pending"; const observation: NativeJournalObservation = { - beforeRoot: before, afterRoot: next, changes, stats: { ...reader.stats }, unreadable: [...reader.unreadable.values()], + beforeRoot: before, afterRoot: next, changes, stats: { ...reader.stats, readEntries: reader.stats.readEntries + aliasEntries }, unreadable: [...reader.unreadable.values()], async commit() { if (state === "aborted") unavailable("Native observation was already aborted."); if (state === "pending") { + if (!workspaces && inventoryWorkspaces) for (const path of index.workspacePaths) index.remove(path); + inventoryWorkspaces = workspaces; for (const [path, entry] of patches) { if (entry) index.put(entry); else if (entry === null) index.remove(path); } missingInventory = new Map(reader!.unreadable); root = next; state = "committed"; pending = undefined; @@ -504,6 +566,7 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker } return { initialize, + includeWorkspaces, /** Borrowed until the next committed observation; never an independent lease. */ currentRoot(): NativeJournalCheckpoint { if (closed || !root) return unavailable("Native observer is not initialized or is closed."); return root; }, entries(): IterableIterator { if (closed) return unavailable("Native observer is closed."); return visible(index.entries.values()); }, @@ -511,9 +574,9 @@ export function createNativeJournalObserver(native: NativeJournalManager, worker ignoreEntries(): IterableIterator { if (closed) return unavailable("Native observer is closed."); return visible(index.ignoreInputs.values()); }, unreadableEntries(): NativeJournalUnreadable[] { return [...missingInventory.values()]; }, get(path: string): NativeJournalMetadata | undefined { if (closed) return unavailable("Native observer is closed."); return uncertain(path) ? undefined : index.entries.get(path); }, - async observe(signal?: AbortSignal, timing?: PhaseTimer): Promise { + async observe(signal?: AbortSignal, timing?: PhaseTimer, options: { workspaces?: boolean } = {}): Promise { if (closed || inFlight || pending) unavailable("Native observation must be serialized and reconciled."); - const operation = prepare(signal, timing); inFlight = operation; + const operation = prepare(signal, timing, options.workspaces !== false); inFlight = operation; try { return await operation; } finally { inFlight = undefined; } }, /** Accounting of previous checkpoints whose release left the observation. */ diff --git a/packages/ui-server/src/brain/native-journal-policy.ts b/packages/ui-server/src/brain/native-journal-policy.ts index a29d26a4cd..236b24b4cd 100644 --- a/packages/ui-server/src/brain/native-journal-policy.ts +++ b/packages/ui-server/src/brain/native-journal-policy.ts @@ -38,9 +38,9 @@ type Rule = { directory: string; matcher: Ignore }; const prefix = (path: string, directory: string) => !directory || isWithin(directory, path, { includeRoot: false }); /** Git internals are excluded except the existing raw HEAD/refs coverage. */ -export function journalPathScope(path: string): { scope: string; local: string; refs: boolean } | null { +export function journalPathScope(path: string, ordinaryWorkspaces = false): { scope: string; local: string; refs: boolean } | null { const segments = path.split("/"); - const scope = segments[0] === "workspaces" && segments.length > 1 ? segments.slice(0, 2).join("/") : ""; + const scope = !ordinaryWorkspaces && segments[0] === "workspaces" && segments.length > 1 ? segments.slice(0, 2).join("/") : ""; const local = scope ? segments.slice(2).join("/") : path; const parts = local.split("/"); const git = parts.indexOf(".git"); @@ -49,13 +49,17 @@ export function journalPathScope(path: string): { scope: string; local: string; return { scope, local, refs: true }; } -export async function freezeNativeJournalPolicy(entries: Iterable, read: (path: string, maximum: number) => Promise, covered: readonly string[] = []) { +export async function freezeNativeJournalPolicy(entries: Iterable, read: (path: string, maximum: number) => Promise, covered: readonly string[] = [], options: { workspaces?: boolean; ordinaryWorkspaces?: boolean; signal?: AbortSignal } = {}) { + const excluded = (path: string) => options.workspaces === false && isWithin("workspaces", path); const rules = new Map(); const admitted = new Set(covered); // Metadata is already indexed. Only ignore files are read here; no baseline // content, object hashes or per-turn content manifest is produced. + const locationOf = (path: string) => journalPathScope(path, options.ordinaryWorkspaces); for (const entry of entries) { - const location = journalPathScope(entry.path); + options.signal?.throwIfAborted(); + if (excluded(entry.path)) continue; + const location = locationOf(entry.path); if (!location || location.refs) continue; if (location.local.split("/").at(-1) !== ".gitignore") continue; if (entry.kind !== "file" || entry.bytes > 1024 * 1024) throw new Error("Native journal ignore rules require a bounded regular file."); @@ -63,9 +67,10 @@ export async function freezeNativeJournalPolicy(entries: Iterable, read: group.push({ directory: location.local.includes("/") ? location.local.slice(0, location.local.lastIndexOf("/")) : "", matcher: ignore().add((await read(entry.path, 1024 * 1024)).toString("utf8")) }); rules.set(location.scope, group); } + options.signal?.throwIfAborted(); for (const group of rules.values()) group.sort((a, b) => a.directory.split("/").length - b.directory.split("/").length || a.directory.localeCompare(b.directory)); function ignored(path: string): boolean { - const location = journalPathScope(path); + const location = locationOf(path); if (!location) return true; if (location.refs || admitted.has(path)) return false; const components = location.local.split("/"); @@ -86,5 +91,5 @@ export async function freezeNativeJournalPolicy(entries: Iterable, read: } return false; } - return { ignored, cover(paths: readonly string[]) { for (const path of paths) admitted.add(path); } }; + return { ignored, excluded, location: locationOf, cover(paths: readonly string[]) { for (const path of paths) admitted.add(path); } }; } diff --git a/packages/ui-server/src/brain/protected-target.ts b/packages/ui-server/src/brain/protected-target.ts index 973a4a7e40..df4c73c35e 100644 --- a/packages/ui-server/src/brain/protected-target.ts +++ b/packages/ui-server/src/brain/protected-target.ts @@ -61,11 +61,11 @@ function places(brain: string, path: string): string[] { * path as named and where its links lead, and the same for each `.env*` name * at the brain root, which is protected by prefix rather than listed. */ -export function protectedPlaces(root: string, protectedPaths: readonly string[]): string[] { +export function protectedPlaces(root: string, protectedPaths: readonly string[], workspaceReadOnly = false): string[] { const brain = realpathSync(root); let env: string[] = []; try { env = readdirSync(brain).filter(isEnvName); } catch { /* An unreadable root lists no names. */ } - return [...protectedPaths, ...env].flatMap(path => places(brain, path)); + return [...protectedPaths, ...env].flatMap(path => places(brain, path)).concat(workspaceReadOnly ? [join(brain, "workspaces")] : []); } /** @@ -82,12 +82,12 @@ export function protectedPlaces(root: string, protectedPaths: readonly string[]) * that refusal for it. */ export function createProtectedTargetCheck(root: string, protectedPaths: readonly string[], - { links = "followed" }: { links?: "followed" | "refused" } = {}): (path: string) => boolean { + { links = "followed", workspaceReadOnly = false }: { links?: "followed" | "refused"; workspaceReadOnly?: boolean } = {}): (path: string) => boolean { const brain = realpathSync(root), admitted = [...protectedPaths]; return path => { const targets = links === "followed" ? places(brain, path) : [join(brain, path)]; if (targets.some(target => within(target, brain) && isEnvName(relative(brain, target).split(sep)[0]!))) return true; - const covered = protectedPlaces(brain, admitted); + const covered = protectedPlaces(brain, admitted, workspaceReadOnly); return targets.some(target => covered.some(place => within(target, place) || within(place, target))); }; } diff --git a/packages/ui-server/src/brain/turn-data-tree.ts b/packages/ui-server/src/brain/turn-data-tree.ts index c0d194b804..6863bae392 100644 --- a/packages/ui-server/src/brain/turn-data-tree.ts +++ b/packages/ui-server/src/brain/turn-data-tree.ts @@ -410,6 +410,8 @@ export async function createTurnDataTree(options: { brainPath: string; view: WorkerStartupView; maskPaths: readonly string[]; /** Mount it for the worker: false for a governed turn, which reads the live brain. */ mount: boolean; + /** Qualified read-only source stays on its checkpoint, outside the note/index copy. */ + inspectWorkspaces?: boolean; masks?: TurnTreeMasks; index?: string; pending?: readonly string[]; /** * The turn is under provider rules (#2692, #2695): the legacy root-level @@ -433,6 +435,7 @@ export async function createTurnDataTree(options: { const hidden = [...(masks?.buildFolders ?? []), ...envMaskedPaths(options.view.root, options.brainPath)]; const copyPlan = planCopy(options.view.root, rel => { const top = !rel.includes("/"); + if (options.inspectWorkspaces && isWithin("workspaces", rel)) return true; if (top && (OMITTED.has(rel) || isEnvName(rel) || (caches && PROVIDER_CACHE_FILES.includes(rel)) || (masks && rel === PROVIDER_CACHE_DIR))) return true; return hidden.some(folder => isWithin(folder, rel)); }); @@ -450,6 +453,8 @@ export async function createTurnDataTree(options: { throw error; } copy.finish(); + // A mountpoint on this private copy preserves repo-relative tool reads. + if (options.inspectWorkspaces && options.mount) mkdirSync(join(root, "workspaces"), { mode: 0o755 }); settleIndex(index, separateIdentity); } catch (error) { await placed.remove(); diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 6342fb7640..0dea097614 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -165,7 +165,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { return work; } /** Active turns; `sessionId` is the binding their record holds once earlier writes commit. */ - const active = new Map void; sequence: number; sessionId: string | null }>(); + const active = new Map void; sequence: number; sessionId: string | null; ordinaryWorkspaces: boolean }>(); const retainVersion = async (source: number, bytes: number, signal?: AbortSignal) => { const hash = await retain(() => objects.putFileAsync(source, bytes, signal)); // Pin the shared observation before another admission can collect objects. @@ -395,7 +395,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (closing || active.size || holds) return Promise.resolve(); return maintaining ??= serialize(async () => { if (closing || active.size) return; - await capture.initialize(shutdown.signal); + await capture.initialize(shutdown.signal, { workspaces: false }); await observe(false, undefined, shutdown.signal); await expireBacklog(); }).catch(() => {}).finally(() => { maintaining = undefined; }); @@ -432,7 +432,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { await releaseReads(); released?.(); const overlaps = [...active.keys()]; - const changed = new Map(); + const changedPaths = new Set(); const stopActive = async (error: unknown) => { const recorded: Promise[] = []; for (const [id, turn] of active) { @@ -466,11 +466,10 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { try { for (const changes of observation.changes.values()) for (const item of changes) { if (identity(item.before) === identity(item.after)) continue; - const value = { path: item.path, scope: item.after?.scope ?? item.before?.scope ?? "", before: version(item.before), after: version(item.after) }; - changed.set(JSON.stringify(value), value); + changedPaths.add(item.path); } - const steering = observation.steering; for (const [turnId, turn] of active) { + const steering = observation.steering.get(turnId)!; const worktree = separate.filter(root => root.turnId === turnId).flatMap(root => (root.observation.changes.get(turnId) ?? []) .filter(change => identity(change.before) !== identity(change.after)) .map(change => ({ path: referenceWorktreeJournalPath(root.worktreeId, change.path), scope: REFERENCE_WORKTREE_JOURNAL_SCOPE, before: version(change.before), after: version(change.after) }))); @@ -478,8 +477,9 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { .map(item => ({ ...item, path: referenceWorktreeJournalPath(root.worktreeId, item.path === "." ? "" : item.path) })))]; let step = timing?.("observe_record"); turn.sequence = await retain(() => call("recordObservation", { - turnId, sequence: turn.sequence, at: now(), userPolicy, changed: [...changed.values()], steeringPaths: [...steering.paths], - overlaps, worktree, steeringUnavailable: [...steering.unavailable], steeringInventoried: steering.inventoried === true, unreadable, + turnId, sequence: turn.sequence, at: now(), userPolicy, changed: (observation.changes.get(turnId) ?? []).filter(item => identity(item.before) !== identity(item.after)).map(item => ({ path: item.path, scope: item.after?.scope ?? item.before?.scope ?? "", before: version(item.before), after: version(item.after) })), steeringPaths: [...steering.paths].filter(path => !turn.policy.excluded(path)), + overlaps, pathObservers: Object.fromEntries([...changedPaths].map(path => [path, [...active].filter(([, peer]) => !peer.policy.excluded(path)).map(([id]) => id)])), + worktree, steeringUnavailable: [...steering.unavailable].filter(path => !turn.policy.excluded(path)), steeringInventoried: steering.inventoried === true, unreadable: unreadable.filter(item => !turn.policy.excluded(item.path)), })); step?.(); step = timing?.("observe_publish"); publish(turnId); @@ -503,7 +503,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { WHERE turn_id=? AND NOT (path GLOB ? AND (SELECT after_json FROM turn_journal_changes WHERE turn_id=change.turn_id AND path=change.path ORDER BY sequence DESC LIMIT 1) IS NULL)) GROUP BY path )`).get(`${BRAIN_WORKSPACES_DIR}*`, DISPOSABLE_INDEX_PATHS, turnId, INDEX_PUBLICATION_COPY) as { changedPaths: number; observedBytes: number; workspaceCandidates: string }; - const workspacePaths = (JSON.parse(facts.workspaceCandidates) as string[]).filter(path => isWithin(BRAIN_WORKSPACES_DIR, path, { includeRoot: false })).length; + const workspacePaths = turn.ordinaryWorkspaces ? 0 : (JSON.parse(facts.workspaceCandidates) as string[]).filter(path => isWithin(BRAIN_WORKSPACES_DIR, path, { includeRoot: false })).length; for (const observer of observers) observer(turnId, { changedPaths: facts.changedPaths, observedBytes: facts.observedBytes, workspacePaths, partial: summary(turnId).state === "partial" }); step?.(); } @@ -523,19 +523,20 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { return { /** * @internal Host scope monitor consumes this same observation window. - * `changedPaths` counts every changed path; `workspacePaths` is how many - * of them lie below `workspaces/` (#3793). + * `changedPaths` counts every changed path; `workspacePaths` counts paths + * exempted as an admitted workspace (#3793). Content created beneath an + * absent optional area is ordinary content, so it receives no exemption. */ onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; partial: boolean }) => void, periodic?: { before(): void; after(completed: boolean): void }) { observers.add(observer); if (periodic) periodicObservers.add(periodic); return () => { if (periodic) periodicObservers.delete(periodic); return observers.delete(observer); }; }, - begin(turnId: string, metadata: { sessionId: string | null; actor: "interactive" | "voice" | "user"; model: string | null; profile: "strict" | "governed"; policyHash: string | null; coveredPaths?: readonly string[] }, stop: (error: Error) => void, signal?: AbortSignal, + begin(turnId: string, metadata: { sessionId: string | null; actor: "interactive" | "voice" | "user"; model: string | null; profile: "strict" | "governed"; policyHash: string | null; coveredPaths?: readonly string[]; workspaceReadOnly?: boolean; workspaceMissing?: boolean }, stop: (error: Error) => void, signal?: AbortSignal, /** Each step of the admission (#3355); a failed step is left unended. */ timing?: PhaseTimer) { return held(async steps => { signal?.throwIfAborted(); let end = steps?.("initialize"); - try { await capture.initialize(signal); } + try { await capture.initialize(signal, { workspaces: false }); } catch (error) { if (signal?.aborted) throw error; throw storageError(error); } end?.(); if (failedAdmissions.size) { end = steps?.("refused_admissions"); for (const refused of failedAdmissions) await finalizeRefusedAdmission(refused); end?.(); } @@ -551,10 +552,10 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { end?.(); try { end = steps?.("policy"); - const policy = await capture.policy(metadata.coveredPaths); + const policy = await capture.policy(metadata.coveredPaths, { workspaces: metadata.workspaceReadOnly !== true || metadata.actor === "user", ordinaryWorkspaces: metadata.workspaceMissing === true }, signal); end?.(); signal?.throwIfAborted(); - active.set(turnId, { policy, stop, sequence: 0, sessionId: metadata.sessionId }); publish(turnId); + active.set(turnId, { policy, stop, sequence: 0, sessionId: metadata.sessionId, ordinaryWorkspaces: metadata.workspaceMissing === true }); publish(turnId); if (!scopeTimer) { scopeTimer = setInterval(() => { void held(timing => observe(false, timing), false, options.observationTrace?.("periodic", null)).catch(error => { @@ -631,7 +632,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const root = createNativeJournalCapture(referenceWorktreeJournalManager(options.referencePool, worktreeId, options.referenceCheckpoints), retainVersion, {}, readIdentity, { steering: false, index: false }, releaseFailed); try { await root.initialize(signal); - const policy = await root.policy(); + const policy = await root.policy([], {}, signal); signal?.throwIfAborted(); worktrees.set(worktreeId, { turnId, capture: root, policy }); } catch (error) { await retireWorktree(root); throw signal?.aborted ? error : storageError(error); } diff --git a/packages/ui-server/src/inbox/bridge-tools.ts b/packages/ui-server/src/inbox/bridge-tools.ts index be39a7a77f..e48d861d78 100644 --- a/packages/ui-server/src/inbox/bridge-tools.ts +++ b/packages/ui-server/src/inbox/bridge-tools.ts @@ -30,6 +30,7 @@ export interface InboxBridgeContext { * compensation refuse a protected target, as the turn's application does. */ protectedPaths?: readonly string[]; + workspaceReadOnly?: boolean; /** * The turn's write boundary (#2869): a journal observation or a scope pause * that begins during an `inbox_add` holds its writes rather than revoking it. @@ -104,7 +105,7 @@ export function createInboxBridgeTools(db: Database, intake: InboxIntake, resolv // Reuse compensated, principal-checked intake; never accept a model // source/trust field. The turn is this bridge's own: its host lineage // alone decides what the item can qualify for (#2816). - const result = await intake.conversation({ text: parsed.text, files: [] }, `bridge:${principalId}:${turnId}:${parsed.idempotencyKey}`, principal, turnId, () => { authorize(true); return true; }, context.protectedPaths, context.holds); + const result = await intake.conversation({ text: parsed.text, files: [] }, `bridge:${principalId}:${turnId}:${parsed.idempotencyKey}`, principal, turnId, () => { authorize(true); return true; }, context.protectedPaths, context.holds, context.workspaceReadOnly); return { created: result.created, threadId: result.threadId, itemId: result.itemId }; }, resolveAction: async input => { diff --git a/packages/ui-server/src/inbox/intake.ts b/packages/ui-server/src/inbox/intake.ts index d474482461..b7d431d4dd 100644 --- a/packages/ui-server/src/inbox/intake.ts +++ b/packages/ui-server/src/inbox/intake.ts @@ -209,8 +209,8 @@ export function createInboxIntake(db: Database, brainRoot: string, log?: Logger) * names the turn. With the turn's admitted protection set, every staging * effect refuses a protected target as the turn's application does (#2876). */ - conversation: (input: ShareInput, key: string, principal: Principal, turnId: string, isCurrent: () => boolean, protectedPaths?: readonly string[], holds?: IntakeHolds) => { - const isProtected = protectedPaths ? createProtectedTargetCheck(brainRoot, protectedPaths) : undefined; + conversation: (input: ShareInput, key: string, principal: Principal, turnId: string, isCurrent: () => boolean, protectedPaths?: readonly string[], holds?: IntakeHolds, workspaceReadOnly = false) => { + const isProtected = protectedPaths || workspaceReadOnly ? createProtectedTargetCheck(brainRoot, protectedPaths ?? [], { workspaceReadOnly }) : undefined; const guard = isProtected && ((path: string) => { if (isProtected(path)) throw new ProtectedTargetRefusedError(); }); return tracked(() => ingest("cli", input, principal, key, isCurrent, { conversationTurn: turnId }, guard, holds)); }, diff --git a/packages/ui-server/src/routes/session-profiles.ts b/packages/ui-server/src/routes/session-profiles.ts index 6a89284f73..79da7405fe 100644 --- a/packages/ui-server/src/routes/session-profiles.ts +++ b/packages/ui-server/src/routes/session-profiles.ts @@ -6,14 +6,14 @@ import { SessionProfileError, type SessionProfiles } from "../ws/session-profile export function createSessionProfileRoutes(profiles: SessionProfiles) { const app = new Hono(); for (const [prefix, kind] of [["sessions", "session"], ["drafts", "draft"]] as const) { - app.on(["GET", "PUT"], `/${prefix}/:id/profile`, async c => { + for (const setting of ["profile", "code-changes"] as const) app.on(["GET", "PUT"], `/${prefix}/:id/${setting}`, async c => { c.header("Cache-Control", "no-store"); try { const principal = c.get("principal"); if (!principal) throw new SessionProfileError(401, "Authentication required."); const id = c.req.param("id"); if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(id)) throw new SessionProfileError(400, "Invalid chat identity."); - if (c.req.method === "GET" || c.req.method === "HEAD") return c.json(profiles.read(principal.id, kind, id)); + if (c.req.method === "GET" || c.req.method === "HEAD") return c.json(setting === "code-changes" ? profiles.readCodeChanges(principal.id, kind, id) : profiles.read(principal.id, kind, id)); if (c.req.header("content-type")?.split(";", 1)[0] !== "application/json") return c.json({ error: "Use JSON." }, 415); const reader = c.req.raw.body?.getReader(); const chunks: Uint8Array[] = []; let length = 0; @@ -26,6 +26,11 @@ export function createSessionProfileRoutes(profiles: SessionProfiles) { let body: unknown; try { body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))); } catch { throw new SessionProfileError(400, "Invalid JSON."); } + if (setting === "code-changes") { + if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).length !== 1 + || typeof (body as { enabled?: unknown }).enabled !== "boolean") throw new SessionProfileError(400, "Choose enabled true or false."); + return c.json(await profiles.saveCodeChanges(principal.id, kind, id, (body as { enabled: boolean }).enabled)); + } if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).some(key => key !== "preference") || !["governed", "strict"].includes((body as { preference: string }).preference)) throw new SessionProfileError(400, "Choose governed or strict."); return c.json(await profiles.save(principal.id, kind, id, (body as { preference: "governed" | "strict" }).preference)); diff --git a/packages/ui-server/src/ws/bridge-capabilities/activity.ts b/packages/ui-server/src/ws/bridge-capabilities/activity.ts index ebd635453a..54ada8160c 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/activity.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/activity.ts @@ -15,13 +15,13 @@ type InboxSlice = ReturnType !!host.journal?.isHeld() || scopePaused(), settled: () => hold.settled() }; return host.inboxTools?.forTurn({ principalId, turnId, isCurrent: () => !signal.aborted && isAuthorized(), sessionId: () => turn.sessionId ?? undefined, - origin: "interactive", membership: work?.posture === "voice" ? "voice" : "interactive", ...(protectedPaths ? { protectedPaths } : {}), + workspaceReadOnly, origin: "interactive", membership: work?.posture === "voice" ? "voice" : "interactive", ...(protectedPaths ? { protectedPaths } : {}), holds: { hold, writes, signal }, ...(maskGuard ? { requalify: () => assertStagingUnmasked(ctx, maskGuard) } : {}) }); } diff --git a/packages/ui-server/src/ws/bridge-capabilities/application.ts b/packages/ui-server/src/ws/bridge-capabilities/application.ts index 4f83b71fa9..1f1c529523 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/application.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/application.ts @@ -17,14 +17,14 @@ function operationToolNames(backendId: string) { * batch the turn's applications queue into. */ export function createApplication(ctx: BridgeContext, self: () => BackendBridge, root: string, applicationPolicy: BrainApplicationPolicy, - options: Pick): { slice: BridgeSlice<"readBrainBase" | "applyBrain"> & Partial>; indexBatch: IndexBatch } { + options: Pick): { slice: BridgeSlice<"readBrainBase" | "applyBrain"> & Partial>; indexBatch: IndexBatch } { const { host, turn, turnId, principalId, authorization, signal, work, backendId, recorder, maskGuard, toolName, isAuthorized, recordingAvailable, hold, afterHolds, current } = ctx; const { protectedPaths, turnData } = options; const operationTools = operationToolNames(backendId); const effectCurrent = () => current() && recordingAvailable(); const apply = createBrainApplication({ root, principalId, turnId, signal, policy: applicationPolicy, - protectedPaths, + protectedPaths, workspaceReadOnly: options.workspaceReadOnly, ...(maskGuard ? { providerMasks: { guard: maskGuard, tool: operation => operationTools[operation] } } : {}), ...(host.applicationPlanner ? { planner: host.applicationPlanner } : {}), isAuthorized, hold, diff --git a/packages/ui-server/src/ws/bridge-capabilities/context.ts b/packages/ui-server/src/ws/bridge-capabilities/context.ts index 1c2c1d37ed..b226781b7e 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/context.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/context.ts @@ -28,6 +28,8 @@ export interface MakeBridgeOptions { applicationPolicy?: BrainApplicationPolicy | undefined; /** Frozen policy protection captured after this turn's gate admission. */ protectedPaths?: readonly string[] | undefined; + /** Frozen workspace mode for privileged tools that run outside the worker mount. */ + workspaceReadOnly?: boolean; workerProfile?: WorkerProfileBinding | undefined; onUsage?: ((usage: TurnUsage, backstop?: boolean) => TurnUsage | void) | undefined; pricingContext?: { billingMode?: BillingMode; pricingRoute?: PricingRoute } | undefined; diff --git a/packages/ui-server/src/ws/bridge-capabilities/location-mask.ts b/packages/ui-server/src/ws/bridge-capabilities/location-mask.ts index e9b969736f..c5f1075347 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/location-mask.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/location-mask.ts @@ -71,7 +71,7 @@ export function createLocationAndMask(ctx: BridgeContext): BridgeSlice<"getLocat * `createLocationAndMask` returned. */ export function createMaskApplicationSlice(ctx: BridgeContext, root: string, applicationPolicy: BrainApplicationPolicy, - requestMask: NonNullable["requestMask"]>, options: Pick): BridgeSlice<"requestMask" | "applyImageMask"> { + requestMask: NonNullable["requestMask"]>, options: Pick): BridgeSlice<"requestMask" | "applyImageMask"> { const { host, turnId, principalId, signal, work, backendId, recorder, maskGuard, toolName, isAuthorized, hold, afterHolds, assertAuthority, principalIsAuthorized } = ctx; const { protectedPaths, turnData } = options; // Composed only for a Claude or pi turn. @@ -79,6 +79,7 @@ export function createMaskApplicationSlice(ctx: BridgeContext, root: string, app const pendingMasks = new Map(); // The scratch prune that follows a mask never removes a masked folder's files. const applyMask = createMaskApplication({ maintenance: host.maintenance, root, backend, principalId, turnId, signal, + workspaceReadOnly: options.workspaceReadOnly, protectedPaths: maskGuard ? [...(protectedPaths ?? []), ...maskGuard.folders] : protectedPaths, lock: applicationPolicy.lock, isAuthorized, hold, isAvailable: () => work?.posture !== "voice", ...(turnData ? { turnTree: turnData.tree } : {}), diff --git a/packages/ui-server/src/ws/bridge-capabilities/markup.ts b/packages/ui-server/src/ws/bridge-capabilities/markup.ts index 358a815687..713606e9dd 100644 --- a/packages/ui-server/src/ws/bridge-capabilities/markup.ts +++ b/packages/ui-server/src/ws/bridge-capabilities/markup.ts @@ -20,12 +20,13 @@ const NOTE = "Pass this layer to `brain image --ref --markup ): BridgeSlice<"requestImageMarkup"> { + options: Pick): BridgeSlice<"requestImageMarkup"> { const { host, turn, turnId, principalId, signal, work, recorder, maskGuard, toolName, isAuthorized, hold, assertAuthority } = ctx; const { coordinator } = host; const { protectedPaths, turnData } = options; const apply = createMarkupApplication({ maintenance: host.maintenance, root, principalId, turnId, signal, // The scratch prune that follows a layer never removes a masked folder's files. + workspaceReadOnly: options.workspaceReadOnly, protectedPaths: maskGuard ? [...(protectedPaths ?? []), ...maskGuard.folders] : protectedPaths, lock: applicationPolicy.lock, isAuthorized, hold, isAvailable: () => work?.posture !== "voice", ...(turnData ? { turnTree: turnData.tree } : {}), diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index b1835b58a3..6c9bccbff9 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -1,3 +1,5 @@ +import { lstatSync } from "node:fs"; +import { join } from "node:path"; import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import { readsIndex, type IndexBatch } from "../brain/index-batch.js"; import { staleReadRefusal } from "../brain/turn-data-tree.js"; @@ -40,12 +42,15 @@ export function settleTurnIndex(bridge: BackendBridge): Promise { * capability, composed in a fixed order, with the live-authority wrapper last. */ export async function makeBridge(host: WsHost, turn: RunningTurn, options: MakeBridgeOptions): Promise { + // Hosts without governed admission still expose privileged applications. + // Freeze their ordinary default here, before any bridge capability opens. + if (options.workspaceReadOnly === undefined && host.brainPath) options = { ...options, workspaceReadOnly: Boolean(lstatSync(join(host.brainPath, "workspaces"), { throwIfNoEntry: false })) }; const applicationPolicy = options.applicationPolicy ? { ...options.applicationPolicy, lock: host.workerLock } : undefined; const ctx = createBridgeContext(host, turn, options); const transcript = createTurnTranscript(ctx); // Captures the turn's draft and retry fields now, with its identity. const emission = createEmission(ctx, transcript, options); - const inbox = openInbox(ctx, options.protectedPaths); + const inbox = openInbox(ctx, options.protectedPaths, options.workspaceReadOnly); if (ctx.work?.posture !== "voice") await host.inboxTools?.shares?.start(ctx.principalId, ctx.turnId, turn.sessionId ?? undefined, turn.shareId, ctx.current); // Capabilities that ask for a permission read the composed bridge when they // ask, so they reach the wrapped `requestPermission` installed below. diff --git a/packages/ui-server/src/ws/chat-lifecycle.ts b/packages/ui-server/src/ws/chat-lifecycle.ts index 35309f8d85..b14faa4668 100644 --- a/packages/ui-server/src/ws/chat-lifecycle.ts +++ b/packages/ui-server/src/ws/chat-lifecycle.ts @@ -82,9 +82,9 @@ type OwnerRow = { principal_id: string | null; principal_account: string | null * joined), recorded voice conversation epochs and the typed session-creation * binding (#3337). A chat with no such record has unknown ownership. Records * naming different logins are returned as they are; whether they are one - * account is `chatOwnedBy`'s question (#4138). + * account is `chatOwnedBy`'s question (#4138). Ownership-only mode omits task/request inventories. */ -export function resolveChat(db: Database, target: ChatTarget): Resolved | { refused: "unavailable" | "stale" } { +export function resolveChat(db: Database, target: ChatTarget, options: { ownershipOnly?: boolean } = {}): Resolved | { refused: "unavailable" | "stale" } { const owners = new Set(), conversations = new Set(), records = new Map(); // A record without a principal is unknown ownership, kept so it refuses. const record = (row: OwnerRow) => { records.set(JSON.stringify([row.principal_id, row.principal_account]), { principalId: row.principal_id, account: row.principal_account }); }; @@ -135,7 +135,7 @@ export function resolveChat(db: Database, target: ChatTarget): Resolved | { refu } if (!records.size) return { refused: "unavailable" }; const tasks: string[] = [], requests: string[] = [], nativeTasks: string[] = []; - for (const conversation of conversations) { + if (!options.ownershipOnly) for (const conversation of conversations) { for (const row of db.query("SELECT epoch,native_handle,task_id,request_id FROM conversation_tasks WHERE conversation_id=? ORDER BY rowid").all(conversation) as { epoch: number; native_handle: string; task_id: string; request_id: string }[]) { tasks.push(row.task_id); requests.push(row.request_id); nativeTasks.push(nativeTaskKey(conversation, row.epoch, row.native_handle)); } diff --git a/packages/ui-server/src/ws/session-profile-writes.ts b/packages/ui-server/src/ws/session-profile-writes.ts index d2928e875b..7ecc760640 100644 --- a/packages/ui-server/src/ws/session-profile-writes.ts +++ b/packages/ui-server/src/ws/session-profile-writes.ts @@ -8,6 +8,7 @@ import type { Database } from "bun:sqlite"; import type { WireError, WriteProcedures } from "../db/write-worker.js"; +import { resolveChat, chatOwnedBy } from "./chat-lifecycle.js"; import { SESSION_DRAFT_LIMITS } from "@schlessera/brain-ui-sdk/protocol"; import { isUsablePrincipal, resolvePrincipal } from "../db/principals.js"; @@ -24,8 +25,16 @@ export function authorizeProfile(db: Database, principalId: string, now: number) if (!principal || !isUsablePrincipal(principal, now)) throw new SessionProfileError(401, "Authentication required."); } +/** A preference may grant writes only to the proven owner of this chat. */ +export function authorizeCodeChanges(db: Database, principalId: string, sessionId: string): void { + authorizeProfile(db, principalId, Date.now()); + const chat = resolveChat(db, { sessionId }, { ownershipOnly: true }); + if ("refused" in chat || !chatOwnedBy(db, chat, principalId)) + throw new SessionProfileError(404, "This chat is not available to this principal."); +} + export function draftProfile(db: Database, principalId: string, id: string) { - return db.query("SELECT preference FROM draft_worker_profiles WHERE principal_id = ? AND draft_id = ?").get(principalId, id) as { preference: Profile } | null; + return db.query("SELECT preference, code_changes AS codeChanges FROM draft_worker_profiles WHERE principal_id = ? AND draft_id = ?").get(principalId, id) as { preference: Profile; codeChanges: number } | null; } /** @@ -38,10 +47,11 @@ export function bindDraftProfile(db: Database, principalId: string, draftId: str authorizeProfile(db, principalId, Date.now()); if (!db.query("SELECT 1 FROM sessions WHERE id = ?").get(sessionId)) throw new SessionProfileError(404, "This chat is not known to the host."); const row = draftProfile(db, principalId, draftId); + if (row?.codeChanges === 1) authorizeCodeChanges(db, principalId, sessionId); if (!row) throw new SessionProfileError(409, "This draft preference is unavailable."); // A save during the first turn is for its NEXT admission; the running profile stays frozen. - db.query("INSERT INTO session_worker_profiles (session_id, preference, updated_at, updated_by) VALUES (?, ?, ?, ?) ON CONFLICT(session_id) DO NOTHING") - .run(sessionId, row.preference, now, principalId); + db.query("INSERT INTO session_worker_profiles (session_id, preference, updated_at, updated_by, code_changes) VALUES (?, ?, ?, ?, ?) ON CONFLICT(session_id) DO NOTHING") + .run(sessionId, row.preference, now, principalId, row.codeChanges); db.query("DELETE FROM draft_worker_profiles WHERE principal_id = ? AND draft_id = ?").run(principalId, draftId); }).immediate(); } @@ -85,6 +95,24 @@ export function saveProfile(db: Database, principalId: string, kind: "session" | }).immediate(); } +/** An authenticated session/draft switch, committed before the API acknowledges it. */ +export function saveCodeChanges(db: Database, principalId: string, kind: "session" | "draft", id: string, enabled: boolean, now: number) { + db.transaction(() => { + authorizeProfile(db, principalId, Date.now()); + if (kind === "session") { + authorizeCodeChanges(db, principalId, id); + db.query("INSERT INTO session_worker_profiles (session_id,preference,updated_at,updated_by,code_changes) VALUES (?,'governed',?,?,?) ON CONFLICT(session_id) DO UPDATE SET code_changes=excluded.code_changes,updated_at=excluded.updated_at,updated_by=excluded.updated_by") + .run(id, now, principalId, Number(enabled)); + } else { + db.query("DELETE FROM draft_worker_profiles WHERE principal_id NOT IN (SELECT id FROM principals WHERE revoked_at IS NULL AND expires_at > ?)").run(now); + if (!draftProfile(db, principalId, id) && (db.query("SELECT COUNT(*) AS n FROM draft_worker_profiles").get() as { n: number }).n >= SESSION_DRAFT_LIMITS.maxDrafts) + throw new SessionProfileError(507, "The host cannot keep another draft preference yet."); + db.query("INSERT INTO draft_worker_profiles (principal_id,draft_id,preference,updated_at,code_changes) VALUES (?,?,'governed',?,?) ON CONFLICT(principal_id,draft_id) DO UPDATE SET code_changes=excluded.code_changes,updated_at=excluded.updated_at") + .run(principalId, id, now, Number(enabled)); + } + }).immediate(); +} + /** A refusal keeps its class and status across the worker. */ export function reviveProfileError(error: WireError): Error | undefined { return error.name === "SessionProfileError" ? new SessionProfileError(error.fields.status as SessionProfileError["status"], error.message) : undefined; @@ -92,6 +120,7 @@ export function reviveProfileError(error: WireError): Error | undefined { export function setup(db: Database): WriteProcedures { return { + saveCodeChanges: (principalId: string, kind: "session" | "draft", id: string, enabled: boolean, now: number) => saveCodeChanges(db, principalId, kind, id, enabled, now), save: (principalId: string, kind: "session" | "draft", id: string, preference: Profile, policyProfiles: Record<"interactive" | "voice", Profile>, now: number) => saveProfile(db, principalId, kind, id, preference, policyProfiles, now), bind: (principalId: string, draftId: string, sessionId: string, now: number) => bindDraftProfile(db, principalId, draftId, sessionId, now), diff --git a/packages/ui-server/src/ws/session-profiles.ts b/packages/ui-server/src/ws/session-profiles.ts index d03f123f26..2e159f85e3 100644 --- a/packages/ui-server/src/ws/session-profiles.ts +++ b/packages/ui-server/src/ws/session-profiles.ts @@ -5,13 +5,13 @@ import type { SessionWorkerProfile } from "@schlessera/brain-ui-sdk/protocol"; import type { GovernedTurns } from "../brain/governed-turn.js"; import { procedureCaller, type SqliteWriter } from "../db/write-worker.js"; import * as writes from "./session-profile-writes.js"; -import { authorizeProfile, draftProfile, SessionProfileError } from "./session-profile-writes.js"; +import { authorizeCodeChanges, authorizeProfile, draftProfile, SessionProfileError } from "./session-profile-writes.js"; export { SessionProfileError }; type Profile = "governed" | "strict"; -type SessionRow = { preference: Profile; actualProfile: Profile | null; origin: "interactive" | "voice" }; -type Effect = { bind: Profile } | { record: { origin: "interactive" | "voice"; actualProfile: Profile } }; +type SessionRow = { preference: Profile; codeChanges: number; actualProfile: Profile | null; origin: "interactive" | "voice" }; +type Effect = { bind: Profile; codeChanges: number } | { record: { origin: "interactive" | "voice"; actualProfile: Profile } }; export function createSessionProfiles(db: Database, turns: GovernedTurns, budgets?: import("../brain/turn-budgets.js").TurnBudgets, limits?: { hardTimeoutMs: () => number }, /** @@ -43,10 +43,10 @@ export function createSessionProfiles(db: Database, turns: GovernedTurns, budget const exists = (id: string) => options.catalog?.hasSession?.(id) ?? db.query("SELECT 1 FROM sessions WHERE id = ?").get(id) !== null; const session = (id: string) => { if (!exists(id)) throw new SessionProfileError(404, "This chat is not known to the host."); - let row = db.query("SELECT preference, actual_profile AS actualProfile, origin FROM session_worker_profiles WHERE session_id = ?").get(id) as SessionRow | null; + let row = db.query("SELECT preference, code_changes AS codeChanges, actual_profile AS actualProfile, origin FROM session_worker_profiles WHERE session_id = ?").get(id) as SessionRow | null; for (const effect of pending.get(id) ?? []) { - if ("bind" in effect) row ??= { preference: effect.bind, actualProfile: null, origin: "interactive" }; - else row = row ? { ...row, ...effect.record } : { preference: "governed", ...effect.record }; + if ("bind" in effect) row ??= { preference: effect.bind, codeChanges: effect.codeChanges, actualProfile: null, origin: "interactive" }; + else row = row ? { ...row, ...effect.record } : { preference: "governed", codeChanges: 0, ...effect.record }; } return row; }; @@ -85,6 +85,32 @@ export function createSessionProfiles(db: Database, turns: GovernedTurns, budget return { read, settled, + readCodeChanges(principalId: string, kind: "session" | "draft", id: string): { enabled: boolean } { + authorize(principalId); + if (kind === "session") authorizeCodeChanges(db, principalId, id); + return { enabled: (kind === "session" ? session(id)?.codeChanges : draft(principalId, id)?.codeChanges) === 1 }; + }, + async saveCodeChanges(principalId: string, kind: "session" | "draft", id: string, enabled: boolean) { + await settled(); + await submit("saveCodeChanges", principalId, kind, id, enabled, Date.now()); + return this.readCodeChanges(principalId, kind, id); + }, + codeChanges(principalId: string, sessionId?: string, draftId?: string): boolean { + authorize(principalId); + if (sessionId) { + if (session(sessionId)?.codeChanges !== 1) return false; + // Legacy/foreign ownership cannot carry a saved write grant into admission. + try { authorizeCodeChanges(db, principalId, sessionId); } catch (error) { + if (error instanceof SessionProfileError && error.status === 404) return false; + throw error; + } + return session(sessionId)?.codeChanges === 1; + } + if (!draftId) return false; + const row = draft(principalId, draftId); + if (!row) throw new SessionProfileError(409, "This draft preference is unavailable. Refresh before sending."); + return row.codeChanges === 1; + }, // A saved preference commits on the write worker too (#2850), after // what it reads has settled; the answer is read once it has. async save(principalId: string, kind: "session" | "draft", id: string, preference: Profile) { @@ -108,7 +134,7 @@ export function createSessionProfiles(db: Database, turns: GovernedTurns, budget if (!row) throw new SessionProfileError(409, "This draft preference is unavailable."); const key = JSON.stringify([principalId, draftId]); consumed.add(key); - const done = write(sessionId, { bind: row.preference }, "bind", principalId, draftId, sessionId, Date.now()); + const done = write(sessionId, { bind: row.preference, codeChanges: row.codeChanges }, "bind", principalId, draftId, sessionId, Date.now()); void done.then(() => {}, () => {}).then(() => consumed.delete(key)); return done; }, diff --git a/packages/ui-server/src/ws/session-run/admission.ts b/packages/ui-server/src/ws/session-run/admission.ts index 377d58ae0a..c0e920d115 100644 --- a/packages/ui-server/src/ws/session-run/admission.ts +++ b/packages/ui-server/src/ws/session-run/admission.ts @@ -148,6 +148,7 @@ export async function admitGovernedTurn(run: TurnRun): Promise area.name === "workspaces" && !area.mount.writable && area.mount.missing), workspaceReadOnly: governedHold.sandbox.areas.some(area => area.name === "workspaces" && !area.mount.writable && Boolean(area.mount.readOnlyPath)), policyHash: governedHold.policy.hash }, error => { // A real timeout/cancel already won; never relabel that terminal. if (abortController.signal.aborted || turn.cancelled) return; diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index 7776b79cf3..98d12b7451 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -99,6 +99,7 @@ export async function openTurnBridge( applicationPolicy: backend.brainApplicationPolicy?.({ profileId, ...(work?.posture === "voice" ? { posture: "voice", noGrantSurface: true, enforceAllowedTools: true } : {}) }), protectedPaths: governedHold ? protectedPaths(governedHold.policy.policy) : undefined, + workspaceReadOnly: governedHold ? !governedHold.sandbox.areas.some(area => area.name === "workspaces" && (area.mount.writable || area.mount.missing)) : undefined, workerProfile: governedHold ? { origin, actualProfile: heldProfile(run), ...(initial.profileDraftId && !resumeId && preference ? { draftId: initial.profileDraftId, preference } : {}) } : undefined, onUsage: budget?.observeUsage, diff --git a/packages/ui-server/tests/app-writes-offloop.test.ts b/packages/ui-server/tests/app-writes-offloop.test.ts index b6bc9bb0ed..0c271c7f46 100644 --- a/packages/ui-server/tests/app-writes-offloop.test.ts +++ b/packages/ui-server/tests/app-writes-offloop.test.ts @@ -338,6 +338,10 @@ test("a saved worker preference commits on the write worker, and its refusals ke const profiles = createSessionProfiles(f.db, profileFacts, undefined, undefined, { writer: f.writer, catalog }); expect((await profiles.save(athena.id, "session", "troy", "strict")).preference, "PROFILE_SAVE_ANSWERS_COMMITTED_ROW").toBe("strict"); expect((await profiles.save(athena.id, "draft", "troy-draft", "strict")).preference, "PROFILE_DRAFT_SAVE_COMMITS").toBe("strict"); + f.db.query("INSERT INTO chat_session_owners(session_id,principal_id,principal_account,created_at) VALUES ('troy',?,'owner',0)").run(athena.id); + expect(await profiles.saveCodeChanges(athena.id, "session", "troy", true), "CODE_CHANGES_SAVE_ANSWERS_COMMITTED_ROW").toEqual({ enabled: true }); + expect(await profiles.saveCodeChanges(athena.id, "draft", "troy-draft", true), "CODE_CHANGES_DRAFT_SAVE_COMMITS").toEqual({ enabled: true }); + expect(profiles.read(athena.id, "session", "troy").preference, "CODE_CHANGES_KEEP_PROFILE_PREFERENCE").toBe("strict"); const refusal = await expectRejection(profiles.save(athena.id, "session", "ithaca", "strict"), SessionProfileError, "PROFILE_REFUSAL_CLASS_KEPT") as SessionProfileError; expect(refusal.status, "PROFILE_REFUSAL_STATUS_KEPT").toBe(409); expect(new Set(await sites.log()), "PROFILE_SAVES_WRITTEN_ON_WORKER").toEqual(new Set(["session_worker_profiles", "draft_worker_profiles"])); diff --git a/packages/ui-server/tests/brain-application.test.ts b/packages/ui-server/tests/brain-application.test.ts index 95223b52f5..1b0b599697 100644 --- a/packages/ui-server/tests/brain-application.test.ts +++ b/packages/ui-server/tests/brain-application.test.ts @@ -303,3 +303,19 @@ describe("server-owned application boundary", () => { } finally { release(); } }); }); + +test("workspace inspection also refuses privileged Markdown applications with both writable alternatives", async () => { + const target = "workspaces/ithaca/readme.md"; + mkdirSync(join(root, "workspaces/ithaca"), { recursive: true }); + const apply = createBrainApplication({ root, planner: boundaryPlanner(createFixtureHostBoundary({ brainPath: root })), + principalId: "odysseus", turnId: "turn-raft", signal: signal.signal, workspaceReadOnly: true, + isAuthorized: () => true, policy: { autoAllowed: ["write"], available: ["write"], lock }, + approve: async () => true, record() {}, + }); + const result = await apply(request(write(target, "Athena changes the source.\n", null))); + expect(result.ok, "INSPECT_HOST_APPLICATION_REFUSED").toBe(false); + expect(result.code).toBe("policy_denied"); + expect(result.message).toContain("switch on code changes for this session"); + expect(result.message).toContain("managed worktree"); + expect(existsSync(join(root, target)), "INSPECT_HOST_APPLICATION_HAS_NO_BYTES").toBe(false); +}); diff --git a/packages/ui-server/tests/brain-markup-application.test.ts b/packages/ui-server/tests/brain-markup-application.test.ts index b7fa170e0a..2120eaec67 100644 --- a/packages/ui-server/tests/brain-markup-application.test.ts +++ b/packages/ui-server/tests/brain-markup-application.test.ts @@ -34,10 +34,10 @@ beforeEach(() => { }); afterEach(() => { for (const host of maintenanceOwners.splice(0)) host.cleanup(); rmSync(root, { recursive: true, force: true }); }); -function app(protectedPaths?: string[]) { +function app(protectedPaths?: string[], workspaceReadOnly = false) { const maintenance = createFixtureMaintenanceHost(root); maintenanceOwners.push(maintenance); return createMarkupApplication({ root, maintenance, principalId: "odysseus", turnId: "raft-turn", signal: controller.signal, - lock: createKeyedLock(), isAuthorized: () => authorized, isAvailable: () => available, ...(protectedPaths ? { protectedPaths } : {}), + workspaceReadOnly, lock: createKeyedLock(), isAuthorized: () => authorized, isAvailable: () => available, ...(protectedPaths ? { protectedPaths } : {}), record: result => records.push(result), beforeCommit: () => beforeCommit?.(), afterLink: () => afterLink?.() }); } function request(overrides: Record = {}) { @@ -291,3 +291,24 @@ test("cancellation and revocation recheck immediately before the layer is linked beforeCommit = () => { authorized = false; }; await refused(request(), "authority_revoked"); }); + + +test("workspace inspection protection cannot be bypassed by a scratch markup alias", async () => { + mkdirSync(join(root, "workspaces/ithaca"), { recursive: true }); + symlinkSync(join(root, "workspaces/ithaca"), join(root, dir)); + const result = await app(undefined,true)(request()); + expect(result.ok, "INSPECT_MARKUP_ALIAS_REFUSED").toBe(false); + expect(result.changes).toEqual([]); + expect(readdirSync(join(root, "workspaces/ithaca")), "INSPECT_MARKUP_ALIAS_HAS_NO_BYTES").toEqual([]); +}); + + +test("inspection permits reading a checkout image for a scratch markup layer",async()=>{ + const checkout="workspaces/ithaca/raft.png";mkdirSync(join(root,"workspaces/ithaca"),{recursive:true});writeFileSync(join(root,checkout),source); + const result=await app(undefined,true)(request({imagePath:checkout,base:readMarkupBase(root,checkout)})); + expect(result.ok,"INSPECTION_RESTRICTS_LAYER_WRITES_NOT_SOURCE_READS").toBe(true); + expect(result.changes.every(change=>change.path.startsWith(".brain/scratch/markup/"))).toBe(true); + expect(readFileSync(join(root,checkout))).toEqual(source); + const explicit=await app(["workspaces"],false)(request({imagePath:checkout,base:readMarkupBase(root,checkout)}));expect(explicit.code).toBe("policy_denied"); + symlinkSync(checkout,join(root,".env.athena"));const secret=await app(undefined,true)(request({imagePath:checkout,base:readMarkupBase(root,checkout)}));expect(secret.code,"INSPECTION_SOURCE_READ_STILL_HONOURS_SECRET_TARGETS").toBe("policy_denied"); +}); diff --git a/packages/ui-server/tests/brain-mask-application.test.ts b/packages/ui-server/tests/brain-mask-application.test.ts index 06843f0ec3..e4a9cc042c 100644 --- a/packages/ui-server/tests/brain-mask-application.test.ts +++ b/packages/ui-server/tests/brain-mask-application.test.ts @@ -19,10 +19,10 @@ beforeEach(() => { controller = new AbortController(); authorized = true; available = true; records = []; beforeCommit = undefined; }); afterEach(() => { for (const host of maintenanceOwners.splice(0)) host.cleanup(); rmSync(root, { recursive: true, force: true }); }); -function app() { +function app(protectedPaths?: string[], workspaceReadOnly = false) { const maintenance = createFixtureMaintenanceHost(root); maintenanceOwners.push(maintenance); return createMaskApplication({ root, maintenance, principalId: "odysseus", turnId: "raft-turn", signal: controller.signal, - lock: createKeyedLock(), isAuthorized: () => authorized, isAvailable: () => available, + protectedPaths, workspaceReadOnly, lock: createKeyedLock(), isAuthorized: () => authorized, isAvailable: () => available, record: result => records.push(result), beforeCommit: () => beforeCommit?.() }); } function request(overrides: Record = {}) { @@ -221,3 +221,24 @@ test.each(["directory", "image", "mask", "authority", "cancel"] as const)("scrat if (kind === "authority") expect(result.code).toBe("authority_revoked"); if (kind === "cancel") expect(result.code).toBe("cancelled"); }); + + +test("workspace inspection protection refuses the host mask write", async () => { + const imagePath = "workspaces/ithaca/raft.png", maskPath = "workspaces/ithaca/raft-mask.png"; + mkdirSync(join(root, "workspaces/ithaca"), { recursive: true }); + writeFileSync(join(root, imagePath), png); + const result = await app(undefined,true)({ principalId: "odysseus", turnId: "raft-turn", + base: readMaskBase(root, imagePath), input: { imagePath, maskPath, png } }); + expect(result.message,"IMPLICIT_INSPECTION_WRITE_NAMES_REMEDIES").toContain("switch on code changes for this session");expect(result.message).toContain("managed worktree"); + expect(result.code, "INSPECT_HOST_MASK_REFUSED").toBe("policy_denied"); + expect(result.changes).toEqual([]); + expect(existsSync(join(root, maskPath)), "INSPECT_HOST_MASK_HAS_NO_BYTES").toBe(false); + expect(readFileSync(join(root, imagePath))).toEqual(png); +}); + + +test("implicit inspection preserves secret target protection outside the checkout",async()=>{ + const imagePath="assets/raft.png",maskPath="assets/raft-mask.png";mkdirSync(join(root,"assets"),{recursive:true});writeFileSync(join(root,imagePath),png);symlinkSync(maskPath,join(root,".env.athena")); + const result=await app(undefined,true)({principalId:"odysseus",turnId:"raft-turn",base:readMaskBase(root,imagePath),input:{imagePath,maskPath,png}}); + expect(result.code,"IMPLICIT_INSPECTION_RETAINS_SECRET_TARGET_GUARD").toBe("policy_denied");expect(existsSync(join(root,maskPath))).toBe(false); +}); diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index c57f62611f..5dd116a298 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -1,14 +1,17 @@ +import * as startupViews from "../../ui-sdk/src/server/worker-startup-view.js"; +import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; import { frontmatterEngineSentinel } from "../../../tests/helpers/frontmatter-engine-sentinel.js"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; import { installFixtureNativeStartupViews } from "./helpers/fixture-native-startup.js"; installFixtureNativeStartupViews(); import { Hono } from "hono"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; import type { AppEnv } from "../src/app-env"; import { createPrincipal, revokePrincipal } from "../src/db/principals"; import { createSessionProfiles } from "../src/ws/session-profiles"; import { createSessionProfileRoutes } from "../src/routes/session-profiles"; import { afterEach, expect, spyOn, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { launchAgentWorker, prepareWorkerSandbox, workerCommand } from "../../ui-sdk/src/server/worker-launcher"; @@ -521,3 +524,204 @@ test("a strict turn's policy record has committed when admission settles, and a expect((f.db.query("SELECT ended_at FROM governed_turn_manifests WHERE turn_id = 'ithaca-close'").get() as { ended_at: number | null }).ended_at, "MANIFEST_CLOSE_SETTLES_AFTER_ITS_RECORD").not.toBeNull(); await slow; }); + +test("code changes API persists a session preference without changing an admitted worker", async () => { + const f = fixture(); + mkdirSync(join(f.brain, "workspaces/ithaca"), { recursive: true }); + const principal = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const catalog = createSessionCatalog(() => f.db); + catalog.persistSessionStub("ithaca-code", "Odysseus inspects source.", "claude", "claude", principal.id); + const profiles = createSessionProfiles(f.db, f.turns); + const app = new Hono().use("*", (c, next) => { c.set("principal", principal); return next(); }).route("/api", createSessionProfileRoutes(profiles)); + const path = "/api/sessions/ithaca-code/code-changes"; + expect(await (await app.request(path)).json(), "CODE_CHANGES_DEFAULT_OFF").toEqual({ enabled: false }); + const observations: boolean[] = []; + const inboxProtections: { protectedPaths?: readonly string[]; workspaceReadOnly?: boolean }[] = []; + let refusedWrite: import("@schlessera/brain-ui-sdk/server").BrainApplicationResult | undefined; + const backend = makeFakeBackend({ id: "claude", startTurn: async request => { + observations.push(request.workerSandbox!.areas.find(area => area.name === "workspaces")!.mount.writable); + if (observations.length === 1 || observations.length === 3) { + refusedWrite = await request.bridge.applyBrain!({ operation: "write", path: "workspaces/ithaca/readme.md", content: "Athena changes source.", expectedBaseHash: null }); + const saved = await app.request(path, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ enabled: true }) }); + expect(saved.status).toBe(200); + expect(request.workerSandbox!.areas.find(area => area.name === "workspaces")!.mount.writable, "RUNNING_MOUNT_STAYS_FROZEN").toBe(false); + } + request.bridge.emit({ type: "session_info", sessionId: "ithaca-code", isNew: false }); + request.bridge.emit({ type: "result", sessionId: "ithaca-code", durationMs: 1, numTurns: 1, isError: false }); + } }); + backend.brainApplicationPolicy = () => ({ autoAllowed: ["write"], available: ["write"], lock: createKeyedLock() }); + const host = new WsHost({ brainPath: f.brain, governedTurns: f.turns, sessionProfiles: profiles, catalog, isPrincipalAuthorized: id => id === principal.id, + inboxTools: { forTurn(context: { protectedPaths?: readonly string[]; workspaceReadOnly?: boolean }) { inboxProtections.push({ protectedPaths: context.protectedPaths, workspaceReadOnly: context.workspaceReadOnly }); return {}; } } as never, + registry: createStaticBackendRegistry([backend], backend.id) }); + host.clients.add({ send() {} }, principal.id); + try { + const input = { authorization: testAuthorization(principal.id), sessionId: "ithaca-code", text: "Odysseus inspects the source.", attachments: [] }; + await runSession(host, input); await runSession(host, input); + expect(refusedWrite?.code, "INSPECT_SESSION_BRIDGE_REFUSES_CHECKOUT_WRITE").toBe("policy_denied"); + expect(refusedWrite?.message).toContain("switch on code changes for this session"); + expect(observations, "NEXT_ADMISSION_USES_SAVED_CODE_MODE").toEqual([false, true]); + expect(inboxProtections[0]?.workspaceReadOnly, "INSPECT_INBOX_INTAKE_GETS_WORKSPACE_PROTECTION").toBe(true); + expect(inboxProtections[0]?.protectedPaths, "IMPLICIT_INSPECTION_IS_NOT_AN_EXPLICIT_OWNER_PROTECTION").not.toContain("workspaces"); + expect(inboxProtections[1]?.workspaceReadOnly, "WRITER_INBOX_INTAKE_KEEPS_EXISTING_POLICY").toBe(false); + expect(inboxProtections[1]?.protectedPaths).toEqual(inboxProtections[0]?.protectedPaths); + const begin = f.turns.begin.bind(f.turns); + f.turns.begin = async (...args) => { + const hold = await begin(...args); + return { ...hold, sandbox: { ...hold.sandbox, areas: hold.sandbox.areas.map(area => area.name === "workspaces" + ? { ...area, mount: { writable: false as const, reason: "over-limit scan", readOnlyPath: join(f.brain, "workspaces") } } : area) } }; + }; + await runSession(host, input); + expect(refusedWrite?.code, "REFUSED_WRITABLE_MOUNT_KEEPS_HOST_WRITE_GUARD").toBe("policy_denied"); + expect(inboxProtections[2]?.workspaceReadOnly, "REFUSED_WRITABLE_MOUNT_KEEPS_ALL_HOST_GUARDS").toBe(true); + const reloaded = createSessionProfiles(f.db, f.turns); + expect(reloaded.codeChanges(principal.id, "ithaca-code"), "CODE_MODE_SURVIVES_RESUME").toBe(true); + catalog.persistSessionStub("troy-code", "Athena inspects source.", "claude", "claude", principal.id); + expect(reloaded.codeChanges(principal.id, "troy-code"), "CODE_MODE_IS_SESSION_LOCAL").toBe(false); + revokePrincipal(f.db, principal.id, Date.now()); + expect((await app.request(path)).status, "CODE_MODE_RECHECKS_AUTH").toBe(401); + } finally { host.close(); } +}); + +test("draft code changes are principal scoped, bind to a new session, and preserve independent profile saves", async () => { + const f = fixture(); + const principal = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const other = createPrincipal(f.db, { authMethod: "password", label: "Penelope device", ttlSeconds: 3600 }); + const profiles = createSessionProfiles(f.db, f.turns); + const app = new Hono().use("*", (c, next) => { c.set("principal", principal); return next(); }).route("/api", createSessionProfileRoutes(profiles)); + const save = (body: unknown) => app.request("/api/drafts/ithaca-draft/code-changes", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + for (const body of [null, [], {}, { enabled: "true" }, { enabled: true, profile: "governed" }]) + expect((await save(body)).status, "CODE_MODE_REJECTS_MALFORMED_INPUT").toBe(400); + expect(await (await save({ enabled: true })).json()).toEqual({ enabled: true }); + await profiles.save(principal.id, "draft", "ithaca-draft", "strict"); + expect(profiles.codeChanges(principal.id, undefined, "ithaca-draft"), "PROFILE_SAVE_PRESERVES_CODE_MODE").toBe(true); + expect(profiles.readCodeChanges(other.id, "draft", "ithaca-draft"), "FOREIGN_DRAFT_HAS_NO_CODE_GRANT").toEqual({ enabled: false }); + const catalog = createSessionCatalog(() => f.db); + catalog.persistSessionStub("ithaca-bound", "Odysseus changes source.", "claude", "claude", principal.id); + await profiles.bind(principal.id, "ithaca-draft", "ithaca-bound"); + expect(profiles.codeChanges(principal.id, "ithaca-bound"), "DRAFT_CODE_MODE_BINDS_TO_SESSION").toBe(true); + expect(profiles.read(principal.id, "session", "ithaca-bound").preference).toBe("strict"); + await profiles.saveCodeChanges(principal.id, "session", "ithaca-bound", false); + expect(profiles.read(principal.id, "session", "ithaca-bound").preference, "CODE_SAVE_PRESERVES_PROFILE").toBe("strict"); + expect(profiles.readCodeChanges(principal.id, "draft", "ithaca-draft")).toEqual({ enabled: false }); +}); + +test("code changes require proven chat ownership for saves, reads, draft binds and admission", async () => { + const f = fixture(); + const owner = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const otherLogin = createPrincipal(f.db, { authMethod: "password", label: "Athena tablet", ttlSeconds: 3600 }); + f.db.query("INSERT INTO principals(id,kind,auth_method,label,created_at,expires_at) VALUES ('telemachus','agent','delegated','Telemachus',0,?)").run(Date.now() + 3600_000); + const profiles = createSessionProfiles(f.db, f.turns), catalog = createSessionCatalog(() => f.db); + catalog.persistSessionStub("owned-source", "Odysseus inspects source.", "claude", "claude", owner.id); + catalog.persistSessionStub("legacy-source", "Ithaca source.", "claude", "claude"); + await expect(profiles.saveCodeChanges("telemachus", "session", "owned-source", true)).rejects.toThrow("not available"); + await expect(profiles.saveCodeChanges(owner.id, "session", "legacy-source", true)).rejects.toThrow("not available"); + expect(() => profiles.readCodeChanges("telemachus", "session", "owned-source")).toThrow("not available"); + await profiles.saveCodeChanges(owner.id, "session", "owned-source", true); + expect(profiles.codeChanges("telemachus", "owned-source"), "FOREIGN_ADMISSION_CANNOT_INHERIT_WRITE_GRANT").toBe(false); + expect(profiles.codeChanges(otherLogin.id, "owned-source"), "SAME_ACCOUNT_RESUME_KEEPS_WRITE_GRANT").toBe(true); + await profiles.saveCodeChanges("telemachus", "draft", "foreign-draft", true); + await expect(profiles.bind("telemachus", "foreign-draft", "owned-source")).rejects.toThrow("not available"); +}); + + +test("resume code-change checks never resolve task deletion inventories", async () => { + const f = fixture(); + const owner = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const catalog = createSessionCatalog(() => f.db), profiles = createSessionProfiles(f.db, f.turns); + catalog.persistSessionStub("resume-source", "Ithaca source.", "claude", "claude", owner.id); + f.db.query("INSERT INTO conversation_epochs(id,principal_id,principal_account,epoch,session_id,updated_at) VALUES(?,?,NULL,1,?,0)").run("resume-epoch", owner.id, "resume-source"); + const query = f.db.query.bind(f.db); + const reads: string[] = []; + let refuseTasks = false; + const spy = spyOn(f.db, "query").mockImplementation((sql: string) => { + reads.push(sql); + if (refuseTasks && sql.includes("conversation_tasks")) throw new Error("Deletion inventory must not run on admission"); + return query(sql); + }); + try { + expect(profiles.codeChanges(owner.id, "resume-source")).toBe(false); + expect(reads.some(sql => sql.includes("dialogue_owners")), "DEFAULT_RESUME_READS_ONLY_ITS_SAVED_SWITCH").toBe(false); + await profiles.saveCodeChanges(owner.id, "session", "resume-source", true); + reads.length = 0; refuseTasks = true; + expect(profiles.codeChanges(owner.id, "resume-source"), "ENABLED_RESUME_PROVES_OWNERSHIP_WITHOUT_TASK_INVENTORY").toBe(true); + expect(reads.some(sql => sql.includes("conversation_tasks"))).toBe(false); + } finally { spy.mockRestore(); } +}); + + +test("an absent-area admission permits ordinary host writes before the next turn seals the workspace", async () => { + const f = fixture(); + const principal = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const catalog = createSessionCatalog(() => f.db); + catalog.persistSessionStub("absent-source", "Ithaca source.", "claude", "claude", principal.id); + const profiles = createSessionProfiles(f.db, f.turns); + const results: import("@schlessera/brain-ui-sdk/server").BrainApplicationResult[] = []; + const backend = makeFakeBackend({ id: "claude", startTurn: async request => { + if (!results.length) mkdirSync(join(f.brain, "workspaces/ithaca"), { recursive: true }); + results.push(await request.bridge.applyBrain!({ operation: "write", path: `workspaces/ithaca/${results.length ? "second" : "first"}.md`, content: "Athena inspects source.", expectedBaseHash: null })); + request.bridge.emit({ type: "session_info", sessionId: "absent-source", isNew: false }); + request.bridge.emit({ type: "result", sessionId: "absent-source", durationMs: 1, numTurns: 1, isError: false }); + } }); + backend.brainApplicationPolicy = () => ({ autoAllowed: ["write"], available: ["write"], lock: createKeyedLock() }); + const host = new WsHost({ brainPath: f.brain, governedTurns: f.turns, sessionProfiles: profiles, catalog, isPrincipalAuthorized: id => id === principal.id, + registry: createStaticBackendRegistry([backend], backend.id) }); + host.clients.add({ send() {} }, principal.id); + try { + const input = { authorization: testAuthorization(principal.id), sessionId: "absent-source", text: "Odysseus inspects source.", attachments: [] }; + await runSession(host, input); await runSession(host, input); + expect(results[0], "ABSENT_AREA_HOST_WRITE_IS_ORDINARY_CONTENT").toMatchObject({ ok: true }); + expect(results[1], "NEXT_ADMISSION_HOST_WRITE_MEETS_READ_ONLY_MOUNT").toMatchObject({ ok: false, code: "policy_denied" }); + } finally { host.close(); } +}); + + +test("a workspace symlink cannot protect unrelated ordinary Markdown applications", async () => { + const f = fixture(); + mkdirSync(join(f.brain, "notes")); symlinkSync(f.brain, join(f.brain, "workspaces")); + const principal = createPrincipal(f.db, { authMethod: "password", label: "Athena device", ttlSeconds: 3600 }); + const catalog = createSessionCatalog(() => f.db); + catalog.persistSessionStub("symlink-source", "Ithaca source.", "claude", "claude", principal.id); + const profiles = createSessionProfiles(f.db, f.turns); + const results: import("@schlessera/brain-ui-sdk/server").BrainApplicationResult[] = []; + const backend = makeFakeBackend({ id: "claude", startTurn: async request => { + results.push(await request.bridge.applyBrain!({ operation: "write", path: results.length ? "workspaces/notes/raft.md" : "notes/raft.md", content: "Athena inspects source.", expectedBaseHash: null })); + request.bridge.emit({ type: "session_info", sessionId: "symlink-source", isNew: false }); + request.bridge.emit({ type: "result", sessionId: "symlink-source", durationMs: 1, numTurns: 1, isError: false }); + } }); + backend.brainApplicationPolicy = () => ({ autoAllowed: ["write"], available: ["write"], lock: createKeyedLock() }); + const host = new WsHost({ brainPath: f.brain, governedTurns: f.turns, sessionProfiles: profiles, catalog, isPrincipalAuthorized: id => id === principal.id, + registry: createStaticBackendRegistry([backend], backend.id) }); + host.clients.add({ send() {} }, principal.id); + try { + const input = { authorization: testAuthorization(principal.id), sessionId: "symlink-source", text: "Odysseus inspects source.", attachments: [] }; + await runSession(host, input); await runSession(host, input); + expect(results[0], "WORKSPACE_LINK_DOES_NOT_PROTECT_THE_WHOLE_BRAIN").toMatchObject({ ok: true }); + expect(results[1], "WORKSPACE_NAMESPACE_STILL_REFUSES_WRITES").toMatchObject({ ok: false, code: "policy_denied" }); + } finally { host.close(); } +}); + + +test("an owner explicitly protecting the workspace symlink also protects its destination",async()=>{ + const f=fixture();mkdirSync(join(f.brain,"notes"));symlinkSync(f.brain,join(f.brain,"workspaces"));f.write("protect: [workspaces]"); + const principal=createPrincipal(f.db,{authMethod:"password",label:"Athena device",ttlSeconds:3600});const catalog=createSessionCatalog(()=>f.db);catalog.persistSessionStub("owner-source","Ithaca source.","claude","claude",principal.id); + let result:unknown;const backend=makeFakeBackend({id:"claude",startTurn:async request=>{result=await request.bridge.applyBrain!({operation:"write",path:"notes/raft.md",content:"Athena protects this destination.",expectedBaseHash:null});request.bridge.emit({type:"result",sessionId:"owner-source",durationMs:1,numTurns:1,isError:false});}}); + backend.brainApplicationPolicy=()=>({autoAllowed:["write"],available:["write"],lock:createKeyedLock()}); + const host=new WsHost({brainPath:f.brain,governedTurns:f.turns,catalog,isPrincipalAuthorized:id=>id===principal.id,registry:createStaticBackendRegistry([backend],backend.id)});host.clients.add({send(){}},principal.id); + try{await runSession(host,{authorization:testAuthorization(principal.id),sessionId:"owner-source",text:"Inspect the raft.",attachments:[]});expect(result,"EXPLICIT_OWNER_PROTECTION_RETAINS_SYMLINK_DESTINATION").toMatchObject({ok:false,code:"policy_denied"});expect(existsSync(join(f.brain,"notes/raft.md"))).toBe(false);}finally{host.close();} +}); + +test("a host without governedTurns still seals privileged checkout applications",async()=>{ + const f=fixture();mkdirSync(join(f.brain,"notes"));mkdirSync(join(f.brain,"workspaces/ithaca"),{recursive:true}); + const principal=createPrincipal(f.db,{authMethod:"password",label:"Athena device",ttlSeconds:3600});const catalog=createSessionCatalog(()=>f.db);catalog.persistSessionStub("hostless-source","Ithaca source.","claude","claude",principal.id); + const results:unknown[]=[];const backend=makeFakeBackend({id:"claude",startTurn:async request=>{for(const path of ["notes/raft.md","workspaces/ithaca/source.md"])results.push(await request.bridge.applyBrain!({operation:"write",path,content:"Athena inspects.",expectedBaseHash:null}));request.bridge.emit({type:"result",sessionId:"hostless-source",durationMs:1,numTurns:1,isError:false});}}); + backend.brainApplicationPolicy=()=>({autoAllowed:["write"],available:["write"],lock:createKeyedLock()}); + const host=new WsHost({brainPath:f.brain,catalog,isPrincipalAuthorized:id=>id===principal.id,registry:createStaticBackendRegistry([backend],backend.id)});host.clients.add({send(){}},principal.id); + try{await runSession(host,{authorization:testAuthorization(principal.id),sessionId:"hostless-source",text:"Inspect the raft.",attachments:[]});expect(results[0],"HOSTLESS_NOTES_STAY_USABLE").toMatchObject({ok:true});expect(results[1],"HOSTLESS_APPLICATION_CANNOT_BYPASS_INSPECTION").toMatchObject({ok:false,code:"policy_denied",message:expect.stringContaining("switch on code changes for this session")});expect(existsSync(join(f.brain,"workspaces/ithaca/source.md"))).toBe(false);}finally{host.close();} +}); + + +test.each(["absent","symlink"])("admission refreshes an inspected %s checkpoint source",async state=>{ + const f=fixture();f.write("profiles: {interactive: strict}");mkdirSync(join(f.brain,"workspaces/ithaca"),{recursive:true});mkdirSync(join(f.brain,"notes"));mkdirSync(join(f.brain,".brain/scratch"),{recursive:true});let checkpoints=0; + const acquisition=spyOn(startupViews,"prepareNativeWorkerStartupView").mockImplementation(async brain=>{const view=createFixtureWorkerStartupView(brain);if(++checkpoints===1){rmSync(join(view.root,"workspaces"),{recursive:true});if(state==="symlink")symlinkSync(join(view.root,"notes"),join(view.root,"workspaces"));}return view;}); + try{const hold=await f.turns.begin("stale-inspection",new AbortController().signal);try{expect(checkpoints,"INSPECTION_REFRESHES_THE_SOURCE_IT_ACTUALLY_MOUNTS").toBe(2);expect(hold.startupView).toBeDefined();expect(hold.sandbox.areas.find(area=>area.name==="workspaces")!.mount.writable).toBe(false);}finally{await hold.end();}}finally{acquisition.mockRestore();} +}); diff --git a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts index 3a0d663ac0..09ac6a30bc 100644 --- a/packages/ui-server/tests/helpers/http-mount-lifetimes.ts +++ b/packages/ui-server/tests/helpers/http-mount-lifetimes.ts @@ -67,6 +67,10 @@ export const mountLifetimes: Record