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 dc098dc0f7..544be25c85 100644 --- a/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/provider-history-probe.ts @@ -63,7 +63,7 @@ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) } }); const restore = replaceNativeStartupAcquisitionForFixture(); try { - for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute"]) { + for (scenario of ["control", "repository", "facts", "posture", "promotion", "title", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { brain = fixtureBrain(scratch, scenario); capture = captures[scenario] = { sessions: [], exchanges: [], appends: [] }; const home = join(scratch, `home-${scenario}`); @@ -77,9 +77,10 @@ try { const controller = new AbortController(); const sandbox = prepareFixtureWorkerSandbox(brain, { home, profile: "strict", ...(scenario === "promotion" ? {} : { areas: [] }) }); const view = createFixtureWorkerStartupView(brain); - const turn = createClaudeSdkTurn({ backend: { brainPath: brain }, req: { + 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}`, - workerStartupView: view, workerSandbox: { ...sandbox, noteFacts: { history: { journal: facts !== 1, userRevert: facts === 2 } }, + workerStartupView: view, workerSandbox: { ...sandbox, ...(scenario === "safety" ? { commandPolicy: { hash: null, deny: [], confirm: [], outwardAllow: [], + taint: () => turnIndex === 2 ? null : { eventId: 7, source: "web_fetch" } } } : {}), noteFacts: { history: { journal: facts !== 1, userRevert: facts === 2 } }, ...(scenario === "datatree" ? { dataTree: turnDataTree(scratch, brain, scenario, turnIndex) } : {}) }, client: { formFactor: facts === 1 ? "phone" : "tablet", viewportWidth: 800 + facts * 100, camera: facts !== 1 }, turnBudgetMs: 60_000 + facts * 1000, ...((scenario === "posture" || scenario === "compute") && turnIndex === 1 ? { posture: "voice" as const, enforceAllowedTools: true, noGrantSurface: true } : {}), @@ -142,12 +143,21 @@ try { sequence = 0; const home = join(scratch, "home-budget"); mkdirSync(join(home, ".claude"), { recursive: true }); - const hosted = historyHost(brain, createClaudeBackend({ brainPath: brain, allowedTools: ["Read", "Bash"], confirmBashPatterns: [], + const budgetBackend = createClaudeBackend({ brainPath: brain, allowedTools: ["Read", "Bash"], confirmBashPatterns: [], profiles: [{ id: "fixture", label: "Fixture", model: "claude-sonnet-4-6", billing: "api", requiredEnvKeys: [], buildEnv: () => ({ HOME: home, CLAUDE_CONFIG_DIR: join(home, ".claude"), ANTHROPIC_BASE_URL: server.url.origin, ANTHROPIC_API_KEY: "offline-odysseus", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1", }) }], log() {}, - })); + }); + // Hosted budget turns do not expose the turn object to this fixture. Capture + // the production fingerprint of that exact SDK systemPrompt option instead + // of leaving their option check vacuous behind the CLI's replayed system. + const hosted = historyHost(brain, { ...budgetBackend, async startTurn(req) { + return budgetBackend.startTurn({ ...req, bridge: { ...req.bridge, activity(event) { + if (event.kind === "prompt_prefix") capture.appends.push(event.prefix.system); + req.bridge.activity?.(event); + } } }); + } }); try { for (turnIndex = 0; turnIndex < 3; turnIndex++) { if (turnIndex) changeRepository(brain, turnIndex); diff --git a/packages/ui-backend-claude/tests/provider-history.test.ts b/packages/ui-backend-claude/tests/provider-history.test.ts index 2c789fc4b8..b8935e2c71 100644 --- a/packages/ui-backend-claude/tests/provider-history.test.ts +++ b/packages/ui-backend-claude/tests/provider-history.test.ts @@ -1,6 +1,6 @@ import { beforeAll, expect, test } from "bun:test"; import { join } from "node:path"; -import { body, captureOffline, history, identical, main, messages, noInternalNotes, pairs, system, type Captures } from "../../../tests/helpers/provider-history.js"; +import { body, captureOffline, history, identical, identicalSystemPromptOptions, main, messages, noInternalNotes, pairs, system, type Captures } from "../../../tests/helpers/provider-history.js"; let captures: Captures; beforeAll(async () => { captures = await captureOffline(join(import.meta.dir, "fixtures/provider-history-probe.ts")); }, 180_000); @@ -60,9 +60,8 @@ test("Claude system stays identical across device and sandbox changes on resume // append at the provider boundary. The SDK documents that recording as // account-gated, so the guard also holds the option brain-kit hands it. test("Claude system-prompt option stays identical on resume", () => { - for (const name of ["control", "repository", "promotion", "budget", "datatree"]) { - const [first, ...rest] = captures[name]!.appends; - for (const next of rest) identical(first, next, `systemPrompt option ${name}`); + for (const [name, capture] of Object.entries(captures)) { + identicalSystemPromptOptions(capture.appends, `systemPrompt option ${name}`); } }); test("Claude system-prompt option stays identical across device and sandbox changes (#2047)", () => { @@ -191,3 +190,23 @@ test("Claude immutable reference reads carry actual call identity and preserve p for (const [index, name] of ["Odysseus", "Penelope", "Telemachus"].entries()) expect(results[index]!.raw).toContain(name); for (const exchange of main(capture)) { expect(exchange.raw).not.toContain("responseDigest"); expect(exchange.raw).not.toContain("acquisitionId"); } }); + +test("retained legacy policy wording and earlier taint facts stay byte-identical after individual review", () => { + const capture = captures.safety!; + for (const [a, b] of pairs(capture)) { + identical(body(a).tools, body(b).tools, "SAFETY_UPGRADE_RETAINS_TOOLS"); + identical(system(a), system(b), "SAFETY_UPGRADE_RETAINS_SYSTEM"); + history(a, b); + } + const exchanges = main(capture); + for (const exchange of exchanges) { + expect(JSON.stringify(system(exchange)), "SAFETY_UPGRADE_RETAINS_LEGACY_WORDING").toContain("Legacy safety policy: this session stays restricted."); + expect(JSON.stringify(system(exchange))).not.toContain("Reviewed safety policy:"); + } + expect(exchanges[0]!.raw, "SAFETY_UPGRADE_RECORDS_ORIGINAL_TAINT_FACT").toContain("This session is tainted"); + // The final request retains that earlier fact as history, while the new + // turn's live policy no longer states it. The provider-prefix guard above + // asserts every old message, including that note, remains unchanged. + 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"); +}); diff --git a/packages/ui-backend-claude/tests/taint-note.test.ts b/packages/ui-backend-claude/tests/taint-note.test.ts index f5017fe2fb..5d5d30e4cd 100644 --- a/packages/ui-backend-claude/tests/taint-note.test.ts +++ b/packages/ui-backend-claude/tests/taint-note.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import { prepareWorkerSandbox } from "@schlessera/brain-ui-sdk/internal"; import { createClaudeSdkTurn } from "../src/sdk-options"; +import { identicalSystemPromptOptions } from "../../../tests/helpers/provider-history"; import { DEFAULT_ALLOWED_TOOLS } from "../src/tool-policy"; /** The owned new-tail context the next turn sends carries the host's recorded taint (G6). */ @@ -34,3 +35,28 @@ test("Claude's capabilities note states the session taint and that tainted egres expect(tainted, "CLAUDE_NOTE_UNPROXIED_TAINT_EGRESS").toContain("Tainted egress is not enforced for this turn"); expect(await contextText(null)).not.toContain("This session is tainted"); }); + +// The installed local CLI can replay its original system bytes even when the +// caller changes its SDK option. Exercise the real option assembly without +// that replay, so an offline mutation can prove the upgrade guard itself. +test("Claude retained safety wording stays identical in SDK options across an upgrade", async () => { + const scratch = mkdtempSync(join(tmpdir(), "odysseus-safety-options-")), root = join(scratch, "brain"); + mkdirSync(root); + const captured: unknown[] = []; + try { + for (let index = 0; index < 3; index++) { + const controller = new AbortController(); + const turn = createClaudeSdkTurn({ backend: { brainPath: root, + systemPromptAppend: index === 0 ? "Legacy safety policy: this session stays restricted." : "Reviewed safety policy: finalized individual verdicts may restore normal." }, + req: { prompt: "Odysseus plans the next leg.", sessionId: "voyage", signal: controller.signal, + bridge: { emit() {}, requestPermission: async () => ({ behavior: "deny", message: "Odysseus declines." }) }, + workerSandbox: { ...prepareWorkerSandbox(root, { home: join(scratch, "home") }), + commandPolicy: { hash: null, deny: [], confirm: [], outwardAllow: [], taint: () => index === 2 ? null : { eventId: 7, source: "web_fetch" } } } }, + profile: { requiredEnvKeys: [], buildEnv: () => ({}) } as never, abortController: controller, + allowedTools: DEFAULT_ALLOWED_TOOLS, confirmPatterns: [], turnLock: { acquire() {}, release() {} } as never, log() {} }); + try { captured.push(turn.options.systemPrompt); } finally { await turn.finishWorker(); } + } + expect(JSON.stringify(captured[0]), "SAFETY_SDK_OPTIONS_RETAIN_LEGACY_WORDING").toContain("Legacy safety policy: this session stays restricted."); + identicalSystemPromptOptions(captured, "SAFETY_UPGRADE_RETAINS_SDK_OPTIONS"); + } finally { rmSync(scratch, { recursive: true, force: true }); } +}); 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 a8bcb949b7..d6aef4ef97 100644 --- a/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts @@ -63,14 +63,17 @@ writeFileSync(join(process.env.PI_CODING_AGENT_DIR!, "models.json"), JSON.string // credential only to an origin the operator lists for it: here, the loopback stub. 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"]) { + for (scenario of ["control", "repository", "facts", "promotion", "reference", "renewal", "freshness", "immutable", "datatree", "compute", "safety"]) { brain = fixtureBrain(scratch, scenario); capture = captures[scenario] = { sessions: [], exchanges: [], appends: [] }; - const backend = createPiBackend({ brainPath: brain, sessionDir: join(scratch, `sessions-${scenario}`), loadExtensions: false, + 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: [] }); let sessionId: string | undefined; sequence = 0; for (turnIndex = 0; turnIndex < 3; turnIndex++) { + if (scenario === "safety") backend = createPiBackend({ brainPath: brain, sessionDir: join(scratch, `sessions-${scenario}`), loadExtensions: false, + systemPromptAppend: turnIndex === 0 ? "Legacy safety policy: this session stays restricted." : "Reviewed safety policy: finalized individual verdicts may restore normal.", + profiles: [{ id: "fixture", label: "Fixture", vendor: "openai", model: "gpt-4o-mini", thinkingLevel: "off" }], confirmBashPatterns: [] }); turnOpen = true; if (scenario === "repository" && turnIndex) changeRepository(brain, turnIndex); const facts = scenario === "facts" ? turnIndex : 0; @@ -81,7 +84,8 @@ try { try { await startFixtureTurn(backend, brain, { prompt: `Odysseus checks voyage step ${turnIndex}.`, profileId: "fixture", sessionId, signal: controller.signal, turnId: `odysseus-${turnIndex}`, - workerSandbox: { ...sandbox, noteFacts: { history: { journal: facts !== 1, userRevert: facts === 2 } }, + workerSandbox: { ...sandbox, ...(scenario === "safety" ? { commandPolicy: { hash: null, deny: [], confirm: [], outwardAllow: [], + taint: () => turnIndex === 2 ? null : { eventId: 7, source: "web_fetch" } } } : {}), noteFacts: { history: { journal: facts !== 1, userRevert: facts === 2 } }, ...(scenario === "datatree" ? { dataTree: turnDataTree(scratch, brain, scenario, turnIndex) } : {}) }, client: { formFactor: facts === 1 ? "phone" : "tablet", viewportWidth: 800 + facts * 100, camera: facts !== 1 }, turnBudgetMs: 60_000 + facts * 1000, bridge: { emit(frame) { frames.push(frame); }, async requestPermission() { return { behavior: "allow" as const }; }, diff --git a/packages/ui-backend-pi/tests/provider-history.test.ts b/packages/ui-backend-pi/tests/provider-history.test.ts index 7fa4761da1..867c20f61a 100644 --- a/packages/ui-backend-pi/tests/provider-history.test.ts +++ b/packages/ui-backend-pi/tests/provider-history.test.ts @@ -1,6 +1,6 @@ import { beforeAll, expect, test } from "bun:test"; import { join } from "node:path"; -import { body, captureOffline, history, identical, main, noInternalNotes, pairs, system, type Captures } from "../../../tests/helpers/provider-history.js"; +import { body, captureOffline, history, identical, main, messages, noInternalNotes, pairs, system, type Captures } from "../../../tests/helpers/provider-history.js"; let captures: Captures; beforeAll(async () => { captures = await captureOffline(join(import.meta.dir, "fixtures/provider-history-probe.ts")); }, 180_000); @@ -154,3 +154,23 @@ test("Pi immutable reference reads carry actual call identity and preserve provi for (const [index, name] of ["Odysseus", "Penelope", "Telemachus"].entries()) expect(results[index]!.raw).toContain(name); for (const exchange of main(capture)) { expect(exchange.raw).not.toContain("responseDigest"); expect(exchange.raw).not.toContain("acquisitionId"); } }); + +test("retained legacy policy wording and earlier taint facts stay byte-identical after individual review", () => { + const capture = captures.safety!; + for (const [a, b] of pairs(capture)) { + identical(body(a).tools, body(b).tools, "SAFETY_UPGRADE_RETAINS_TOOLS"); + identical(system(a), system(b), "SAFETY_UPGRADE_RETAINS_SYSTEM"); + history(a, b); + } + const exchanges = main(capture); + for (const exchange of exchanges) { + expect(JSON.stringify(system(exchange)), "SAFETY_UPGRADE_RETAINS_LEGACY_WORDING").toContain("Legacy safety policy: this session stays restricted."); + expect(JSON.stringify(system(exchange))).not.toContain("Reviewed safety policy:"); + } + expect(exchanges[0]!.raw, "SAFETY_UPGRADE_RECORDS_ORIGINAL_TAINT_FACT").toContain("This session is tainted"); + // The final request retains that earlier fact as history, while the new + // turn's live policy no longer states it. The provider-prefix guard above + // asserts every old message, including that note, remains unchanged. + 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"); +}); diff --git a/packages/ui-react/tests/browser/safety-review.layout.tsx b/packages/ui-react/tests/browser/safety-review.layout.tsx index a4d78007ac..a1cec2975d 100644 --- a/packages/ui-react/tests/browser/safety-review.layout.tsx +++ b/packages/ui-react/tests/browser/safety-review.layout.tsx @@ -23,7 +23,7 @@ const noop=()=>{}; const message:ChatMessage={id:'odysseus-answer',turnId:'voyage',role:'assistant',content:'Voyage notes retained.',isStreaming:false,timestamp:Date.UTC(2026,6,12,10), toolCalls:[{id:'tool_a',name:'WebFetch',inputJson:'{}',input:{url:'https://example.com/odyssey'},output:'Odysseus voyage notes',status:'complete'},{id:'tool_c',name:'WebFetch',inputJson:'{}',input:{url:'https://example.com/odyssey'},output:'Penelope voyage notes',status:'complete'}], parts:[{kind:'tool',toolIndex:0},{kind:'tool',toolIndex:1},{kind:'text',text:'Voyage notes retained.'}]}; -async function view(){ +async function view(independentSocket=false){ const f=fixture!; ui=createBrainUiRoot({storage:null,config:{backendUrl:f.url},request:async(url,init)=>{ if(!String(url).includes('/safety/reviews/'))return Response.json({providers:[]}); @@ -34,14 +34,14 @@ async function view(){ current.stores.connection.getState().setWsStatus('connected'); socket=new WebSocket(f.url.replace('http:','ws:')+'/ws');const ws=socket; current.connection.send=(m:ClientMessage)=>{sent.push(m);if(ws.readyState!==WebSocket.OPEN)return false;ws.send(JSON.stringify(m));return true;}; - const client=safetyClient=createSafetyClient(current,m=>{sent.push(m);if(socket?.readyState!==WebSocket.OPEN)return false;socket.send(JSON.stringify(m));return true;}); + const client=safetyClient=createSafetyClient(current,m=>{sent.push(m);const target=independentSocket?ws:socket;if(target?.readyState!==WebSocket.OPEN)return false;target.send(JSON.stringify(m));return true;}); ws.onopen=()=>ws.send(JSON.stringify({type:'client_hello',protocolRev:5,capabilities:{sessionSafetyHistory:true,chatDeletion:true}})); ws.onmessage=e=>{frames.push(JSON.parse(String(e.data)));const parsed=parseServerMessage(String(e.data));if(!parsed.ok)throw new Error(parsed.error);client.frame(parsed.message);}; host=document.createElement('div');host.style.maxWidth='100%';document.body.append(host);renderer=createRoot(host); flushSync(()=>renderer!.render()); try{await expect.poll(()=>current.stores.safety.getState().status,{timeout:5000}).toBe('ready');}catch(error){throw new Error(`${String(error)} Frames:${JSON.stringify(frames)} Sent:${JSON.stringify(sent)} Safety:${JSON.stringify(current.stores.safety.getState())} Session:${current.stores.chat.getState().activeSessionId}`);} } -async function scene(width:number,theme:string){await page.viewport(width,900);document.documentElement.dataset.theme=theme;fixture=await commands.safetyServer({op:'start'}) as typeof fixture;await view();} +async function scene(width:number,theme:string,independentSocket=false){await page.viewport(width,900);document.documentElement.dataset.theme=theme;fixture=await commands.safetyServer({op:'start'}) as typeof fixture;await view(independentSocket);} function buttonForTool(){const all=[...host!.querySelectorAll('[data-safety-indicator] button')];return all.find(b=>b.getAttribute('aria-label')?.includes('2 unresolved'))!;} for(const width of [320,1280])for(const theme of ['light','dark'])test(`${width} ${theme}: collapsed counts, native touch, exact scope, A/B/C and reload`,async()=>{ @@ -130,3 +130,34 @@ test('same-owner disconnect and replay keep read-only evidence geometry without expect(document.querySelector('[data-safety-details]')!.textContent,'RECONNECT_DISCARDS_UNSUBMITTED_SCOPE_CHOICE').not.toContain('Mark this trigger as safe'); expect((await patch()).commits,'RECONNECT_DOES_NOT_SEND_A_DECISION').toBe(0); }); + +test('two live owner views keep independent review scope and converge after every verdict',async()=>{ + await scene(320,'light',true); + const first={ui:ui!,socket:socket!,renderer:renderer!,host:host!,client:safetyClient!}; + // A second root and socket, with separate caches and UI state, read the same + // real writer. Disposal restores ownership so every resource is closed. + ui=undefined;socket=undefined;renderer=undefined;host=undefined;safetyClient=undefined; + try{ + await view(true);const second={ui:ui!,host:host!}; + for(let remaining=3;remaining>0;remaining--){ + const active=remaining%2===1?first:second; + const indicator=[...active.host.querySelectorAll('[data-safety-indicator] button')].find(button=>button.getClientRects().length>0&&button.getAttribute('aria-label')?.startsWith('Safety restrictions'))!; + await userEvent.click(indicator); + await userEvent.click(page.getByRole('button',{name:'Mark as safe',exact:true}).first()); + await userEvent.click(page.getByRole('button',{name:'Mark this trigger as safe',exact:true})); + for(const current of [first,second]){ + await expect.poll(()=>current.ui.stores.safety.getState().status==='ready'&¤t.ui.stores.safety.getState().projection?.unresolvedCount===remaining-1,{timeout:5000}).toBe(true); + expect(current.host.textContent?.includes('Normal policy restored'),'TWO_VIEWS_RESTORE_ONLY_AFTER_LAST_VERDICT').toBe(remaining===1); + } + await userEvent.keyboard('{Escape}'); + } + expect((await patch()).commits,'TWO_VIEWS_COMMIT_EXACTLY_ONE_VERDICT_PER_TRIGGER').toBe(3); + await patch({action:'add',id:'tool_d',finalized:false}); + for(const current of [first,second]){ + await expect.poll(()=>current.ui.stores.safety.getState().projection?.unresolvedCount,{timeout:5000}).toBe(1); + expect(current.host.textContent,'TWO_VIEWS_FUTURE_INPUT_RESTRICTS_AGAIN').not.toContain('Normal policy restored'); + } + }finally{ + await disposeView();ui=first.ui;socket=first.socket;renderer=first.renderer;host=first.host;safetyClient=first.client; + } +}); diff --git a/packages/ui-server/tests/helpers/safety-history-fixture.ts b/packages/ui-server/tests/helpers/safety-history-fixture.ts index aff64315ac..de230b899e 100644 --- a/packages/ui-server/tests/helpers/safety-history-fixture.ts +++ b/packages/ui-server/tests/helpers/safety-history-fixture.ts @@ -73,6 +73,6 @@ export async function safetyHistoryFixture(bound=true,review=false,mode:AuthMode return {root,path,url:`ws://127.0.0.1:${server.port}/ws`,cookie,db,writer,writes,principal,history,reviews,brainKey,auth,host,bindingId,add,bind,get,connect,cookieFor,starts:()=>starts, advance(ms:number){clock+=ms;}, hold(){let release!:()=>void;wait=new Promise(r=>{release=r;});const arrived=new Promise(r=>{entered=r;});return {arrived,release(){wait=undefined;entered=undefined;release();}};}, - async close(){for(const s of sockets)s.close();server.stop(true);await host.close();await writer.close();db.close();rmSync(root,{recursive:true,force:true});}, + async close(retainFiles=false){for(const s of sockets)s.close();server.stop(true);await host.close();await writer.close();db.close();if(!retainFiles)rmSync(root,{recursive:true,force:true});}, }; } diff --git a/packages/ui-server/tests/safety-recovery-journey.test.ts b/packages/ui-server/tests/safety-recovery-journey.test.ts new file mode 100644 index 0000000000..8643135223 --- /dev/null +++ b/packages/ui-server/tests/safety-recovery-journey.test.ts @@ -0,0 +1,265 @@ +/** Offline joined journey: detector + real streaming proxy + FULL writer + owner HTTP + two WS views. */ +import { expectRejection } from "./helpers/expect-rejection"; +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createUiDb } from "../src/db/client"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { SafetyHistory } from "../src/governance/safety-history"; +import { resolvePrincipal, isUsablePrincipal } from "../src/db/principals"; +import { join } from "node:path"; +import { createEffectiveSafety } from "../src/governance/effective-safety"; +import { decidePiToolPermission } from "../../ui-backend-pi/src/permission-gate"; +import { createTurnContext } from "../../ui-backend-pi/src/turn-context"; +import { createGovernanceWrites } from "../src/governance/event-writes"; +import * as held from "./fixtures/held-publication-writer"; +import { request } from "node:http"; +import { createSafetyCollector } from "../src/governance/safety-collector"; +import { prepareTurnEgress } from "../src/brain/turn-egress"; +import { resolveGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { queryGovernanceEvents } from "../src/governance/events"; +import { createSafetyStore } from "../../ui-react/src/stores/safety-state"; +import { safetyHistoryFixture } from "./helpers/safety-history-fixture"; + +type Fixture = Awaited>; +async function postReview(f: Fixture, suffix: string, input: ReturnType) { + const origin = f.url.replace("ws:", "http:").replace("/ws", ""); + const response = await fetch(`${origin}/api/sessions/ithaca/safety/reviews/${suffix}`, { + method: "POST", headers: { cookie: f.cookie, origin, "content-type": "application/json" }, body: JSON.stringify(input), + }); + return { status: response.status, result: await response.json() }; +} +async function review(f: Fixture, id: string, value?: ReturnType) { + const input = value ?? body(f, id), prepared = await postReview(f, "prepare", input); + if (prepared.status !== 200) return prepared; + return postReview(f, `${prepared.result.receipt.requestId}/commit`, input); +} +function liveSafety(f: Fixture) { + return createEffectiveSafety(f.db, { turnId: "voyage", sessionId: () => "ithaca", policyHash: null, writes: f.writes, + authority: () => ({ current: isUsablePrincipal(resolvePrincipal(f.db, f.principal.id)!, Date.now()), epoch: "0" }) }); +} +/** A standing outward allowance must produce a real process effect only when + * current admission permits it. The fake Git executable cannot contact a host. */ +async function admit(f: Fixture, safety: ReturnType, expected: boolean, assertion: string) { + const command = "git push https://github.com/odysseus/voyage.git main"; + const decision = await decidePiToolPermission({ turn: { ...createTurnContext(), signal: new AbortController().signal, + bridge: { emit() {}, admissionSafety: safety, requestPermission: async () => ({ behavior: "deny", message: "Odysseus declines." }) }, + commandPolicy: { hash: null, deny: [], confirm: [], outwardAllow: [{ command: "^git push ", remotes: ["github.com/odysseus/*"], index: 0 }], + taint: () => f.writes.taint("voyage", "ithaca") } }, allowedTools: new Set(["bash"]), confirmPatterns: [] }, "bash", { command }, crypto.randomUUID()); + const bin = join(f.root, "bin"), marker = join(f.root, "outward-effect"); + mkdirSync(bin, { recursive: true }); + writeFileSync(join(bin, "git"), `#!/bin/sh\nprintf 'Ithaca\\n' >> '${marker}'\n`, { mode: 0o755 }); + const before = existsSync(marker) ? readFileSync(marker, "utf8") : ""; + if (decision.behavior === "allow") { + const child = Bun.spawn(["/bin/sh", "-c", command], { cwd: f.root, env: { PATH: bin }, stdout: "pipe", stderr: "pipe" }); + expect(await child.exited, await new Response(child.stderr).text()).toBe(0); + } + expect((existsSync(marker) ? readFileSync(marker, "utf8") : "") !== before, assertion).toBe(expected); +} +async function holdWriter(f: Fixture) { + const channel = f.writer.channel(held, undefined); await channel.ready; + expect(await channel.call("level")).toBe(2); + const entered = new Int32Array(new SharedArrayBuffer(4)), release = new Int32Array(new SharedArrayBuffer(4)); + const pending = channel.call("hold", entered, release), waiting = Atomics.waitAsync(entered, 0, 0, 5000); + if (waiting.async) await waiting.value; + expect(Atomics.load(entered, 0)).toBe(1); + return { pending, release() { Atomics.store(release, 0, 1); Atomics.notify(release, 0); } }; +} +function body(f: Fixture, id: string) { + const state = f.writes.safety(null, "ithaca"); + return { version: 1 as const, session: state.session!, occurrenceId: id, expectedEvidenceRevision: state.evidenceRevision, verdict: "safe" as const }; +} +async function view(f: Fixture) { + const socket = await f.connect(), store = createSafetyStore(); + const refresh = async () => { + const requestId = crypto.randomUUID(); + store.getState().reset(true); store.getState().begin(requestId); + socket.send({ type: "safety_read", version: 1, requestId, target: { sessionId: "ithaca" } }); + const frame = await socket.until(m => m.type === "safety_history" && m.requestId === requestId); + if (frame.type !== "safety_history") throw new Error("Missing safety page"); + expect(store.getState().page(requestId, frame.page)).toBe(true); + return frame.page; + }; + return { store, refresh }; +} + +test("two owner views review A/B/C independently across real streaming and delayed detector delivery", async () => { + const f = await safetyHistoryFixture(true, true), controller = new AbortController(); + const collector = createSafetyCollector(f.db, f.writes, { turnId: "voyage", bindingId: f.bindingId, backendId: "claude", + sessionId: () => "ithaca", shellProxied: () => true, signal: controller.signal }); + const safety = liveSafety(f); + let stream!: ReadableStreamDefaultController; + const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(new ReadableStream({ + start(value) { stream = value; value.enqueue(new TextEncoder().encode("Odysseus")); }, + })) }); + const proxy = await prepareTurnEgress({ policy: resolveGovernancePolicy({ schema_version: 1 }), + bridge: { emit() {}, admissionSafety: safety, requestPermission: async () => ({ behavior: "allow" as const }) }, controller, + turnId: "voyage", sessionId: () => "ithaca", model: () => null, profile: "governed", origin: "interactive", + governanceDb: f.db, governanceWrites: f.writes, record: event => f.writes.record(event) }); + try { + await collector.begin("A", "WebFetch", { url: "https://example.com/odyssey" }); + await collector.result("A", "WebFetch", "Voyage notes", true); + const response = await new Promise((resolve, reject) => { + const req = request({ socketPath: proxy.socketPath, path: origin.url.href }, resolve); req.on("error", reject); req.end(); + }); + const drained = new Promise((resolve, reject) => { response.on("end", resolve); response.on("error", reject); response.resume(); }); + // Teardown can interrupt the response after a failed assertion. Observe + // that cleanup rejection without masking the awaited healthy completion. + void drained.catch(() => {}); + await collector.begin("C", "WebFetch", { url: "https://example.com/odyssey" }); + const events = queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint"], limit: 100 }); + expect(events, "JOURNEY_THREE_INDEPENDENT_BOUNDARIES").toHaveLength(3); + const ids = events.map(event => (event.payload.occurrence as { id: string }).id), [a, b, c] = ids as [string, string, string]; + expect(new Set(ids).size).toBe(3); + const one = await view(f), two = await view(f), stale = await two.refresh(); + await one.refresh(); + expect((await review(f, b)).result.receipt.reason, "JOURNEY_STREAM_CANNOT_BE_REVIEWED").toBe("not_finalized"); + expect((await review(f, c)).result.receipt.reason, "JOURNEY_DELAYED_INPUT_CANNOT_BE_REVIEWED").toBe("not_finalized"); + expect((await review(f, a)).result.currentProjection.unresolvedCount, "JOURNEY_A_LEAVES_B_C").toBe(2); + await admit(f, safety, false, "JOURNEY_A_CANNOT_RESTORE_ADMISSION"); + expect((await review(f, c, { ...body(f, c), expectedEvidenceRevision: stale.highWater })).status, "JOURNEY_STALE_TAB_REFUSES").toBe(409); + stream.close(); await drained; await proxy.settled(); + expect((await review(f, b)).result.currentProjection.unresolvedCount, "JOURNEY_B_LEAVES_DELAYED_C").toBe(1); + await admit(f, safety, false, "JOURNEY_B_CANNOT_RESTORE_ADMISSION"); + for (const client of [one, two]) { + await client.refresh(); + expect(client.store.getState().normal, "JOURNEY_BOTH_VIEWS_STAY_RESTRICTED").toBe(false); + expect(client.store.getState().projection?.earliestUnresolvedId).toBe(c); + } + await collector.result("C", "WebFetch", "Later voyage notes", true); + expect((await review(f, c)).result.currentProjection.restriction, "JOURNEY_ONLY_FINAL_C_RESTORES_NORMAL").toBe("normal"); + await admit(f, safety, true, "JOURNEY_FINAL_C_RESTORES_REAL_ADMISSION"); + for (const client of [one, two]) { + const page = await client.refresh(); + expect(client.store.getState().normal, "JOURNEY_BOTH_VIEWS_RESTORE_NORMAL").toBe(true); + expect(page.records.filter(row => row.kind === "safe_decision").map(row => row.occurrenceId).sort()).toEqual([...ids].sort()); + } + // A future same-source call never inherits C's committed verdict. + await collector.begin("D", "WebFetch", { url: "https://example.com/odyssey" }); + for (const client of [one, two]) { + await client.refresh(); + expect(client.store.getState().projection?.unresolvedCount, "JOURNEY_FUTURE_INPUT_HAS_NO_INHERITED_VERDICT").toBe(1); + expect(client.store.getState().normal).toBe(false); + } + await admit(f, safety, false, "JOURNEY_D_RESTRICTS_REAL_ADMISSION_AGAIN"); + await collector.result("D", "WebFetch", "Future voyage notes", true); + await f.writes.safetyEnd("voyage"); + } finally { proxy.stop(); await proxy.settled(); origin.stop(true); await f.close(); } +}); + +for (const failed of [false, true]) test(`late collector write after an owner verdict ${failed ? "fails closed through recovery and restart" : "blocks admission before COMMIT and stays independent"}`, async () => { + const f = await safetyHistoryFixture(true, true), safety = liveSafety(f); + const collector = createSafetyCollector(f.db, f.writes, { turnId: "voyage", bindingId: f.bindingId, backendId: "claude", + sessionId: () => "ithaca", shellProxied: () => true, signal: new AbortController().signal }); + let barrier: Awaited> | undefined, closed = false; + let input: Promise | undefined, retry: ReturnType | undefined; + try { + await collector.begin("A", "WebFetch", { url: "https://example.com/odyssey" }); + await collector.result("A", "WebFetch", "Voyage notes", true); + const a = queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint"], limit: 100 })[0]!.payload.occurrence as { id: string }; + const value = body(f, a.id), prepared = await postReview(f, "prepare", value); + expect(prepared.status).toBe(200); + const handle = prepared.result.receipt.requestId as string, original = await postReview(f, `${handle}/commit`, value); + expect(original.result.receipt.verdict).toBe("committed"); + await admit(f, safety, true, "JOURNEY_BASELINE_REVIEW_PERMITS_REAL_ADMISSION"); + const clients = [await view(f), await view(f)]; + for (const client of clients) { await client.refresh(); expect(client.store.getState().normal).toBe(true); } + if (failed) f.db.exec("CREATE TRIGGER fail_late_occurrence BEFORE INSERT ON governance_events WHEN NEW.kind='taint' BEGIN SELECT RAISE(ABORT,'Odysseus late recording failure'); END"); + // Pause the real FULL writer immediately before the detector's occurrence + // reservation. The real facade registers its pending input while SQLite + // still contains only the already-reviewed A. No timing sleep is an oracle. + const submitted = Promise.withResolvers(), firstTaint = f.writes.firstTaint.bind(f.writes); + f.writes.firstTaint = async (...args) => { + barrier = await holdWriter(f); + const pending = firstTaint(...args); submitted.resolve(); return pending; + }; + input = collector.begin("B", "WebFetch", { url: "https://example.com/odyssey" }); + void input.catch(() => {}); + await submitted.promise; + expect(queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint"], limit: 100 })).toHaveLength(1); + await admit(f, safety, false, "JOURNEY_PENDING_ADD_BLOCKS_REAL_ADMISSION"); + // A second device retries the earlier successful verdict while B's write + // is delayed. Its original receipt cannot become a standing permission. + retry = postReview(f, `${handle}/commit`, value); + const reads = clients.map(client => client.refresh()); + for (const client of clients) expect(client.store.getState().normal, "JOURNEY_WAITING_VIEWS_CANNOT_CLAIM_NORMAL").toBe(false); + barrier!.release(); await barrier!.pending; + if (failed) await expectRejection(input, "Odysseus late recording failure"); else await input; + f.writes.firstTaint = firstTaint; + const replayed = await retry; + expect(replayed.result.receipt, "JOURNEY_LATE_WRITE_NEVER_REWRITES_EARLIER_VERDICT").toEqual(original.result.receipt); + expect(replayed.result.currentProjection.restriction, "JOURNEY_ORIGINAL_RECEIPT_CANNOT_AUTHORIZE_LATE_INPUT").toBe("restricted"); + const pages = await Promise.all(reads); + for (const page of pages) expect(page.projection.restriction).toBe("restricted"); + if (!failed) { + await collector.result("B", "WebFetch", "Later voyage notes", true); + await admit(f, safety, false, "JOURNEY_LATE_COMMIT_REMAINS_RESTRICTED"); + const b = queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint"], limit: 100 })[1]!.payload.occurrence as { id: string }; + expect((await review(f, b.id)).result.receipt.verdict).toBe("committed"); + await admit(f, safety, true, "JOURNEY_LATE_TRIGGER_NEEDS_ITS_OWN_VERDICT"); + for (const client of clients) { await client.refresh(); expect(client.store.getState().normal).toBe(true); } + await f.writes.safetyEnd("voyage"); + } else { + expect(f.writes.safety(null, "ithaca").reasons).toContain("recording_failed"); + expect(createGovernanceWrites(f.db, f.writer).recordingAvailable("voyage", "ithaca")).toBe(false); + await admit(f, safety, false, "JOURNEY_FAILURE_LATCH_BLOCKS_REAL_ADMISSION"); + for (const client of clients) { + const page = await client.refresh(); + expect(page.projection.reasons, "JOURNEY_BOTH_VIEWS_DISCLOSE_RECORDING_LOSS").toContain("recording_failed"); + expect(client.store.getState().normal).toBe(false); + } + // Removing the injected SQL fault does not repair the lost input. End + // and reopen the actual database with a new writer/facade/admission path. + f.db.exec("DROP TRIGGER fail_late_occurrence"); + await f.writes.safetyEnd("voyage"); + await f.close(true); closed = true; + const db = createUiDb(f.path), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); + try { + const restarted = { ...f, db, writer, writes }, current = writes.safety(null, "ithaca"); + expect(current.coverage.state, "JOURNEY_FAILED_LATE_WRITE_SURVIVES_RESTART").toBe("incomplete"); + expect(current.restriction).toBe("restricted"); + await admit(restarted, liveSafety(restarted), false, "JOURNEY_RESTARTED_FAILURE_BLOCKS_REAL_ADMISSION"); + } finally { await writer.close(); db.close(); } + } + } finally { + barrier?.release(); await input?.catch(() => {}); await retry?.catch(() => {}); + if (!closed) await f.close(); else rmSync(f.root, { recursive: true, force: true }); + } +}); + +for (const unfinished of [false, true]) test(`real database restart replays ${unfinished ? "unfinished delivery as an honest gap" : "committed single-trigger verdicts"}`, async () => { + const f = await safetyHistoryFixture(true, true); + let closed = false; + try { + const collector = createSafetyCollector(f.db, f.writes, { turnId: "voyage", bindingId: f.bindingId, backendId: "claude", + sessionId: () => "ithaca", shellProxied: () => true, signal: new AbortController().signal }); + await collector.begin("A", "WebFetch", { url: "https://example.com/odyssey" }); + await collector.result("A", "WebFetch", "Voyage notes", true); + const a = queryGovernanceEvents(f.db, { sessionId: "ithaca", kinds: ["taint"], limit: 100 })[0]!.payload.occurrence as { id: string }; + expect((await review(f, a.id)).result.receipt.verdict).toBe("committed"); + if (unfinished) await collector.begin("C", "WebFetch", { url: "https://example.com/odyssey" }); + else await f.writes.safetyEnd("voyage"); + const before = f.writes.safety(null, "ithaca"); + await f.close(true); closed = true; + // A fresh FULL writer and history service on the same WAL file, with no + // inherited in-memory collector, pending latch, cursor or projection. + const db = createUiDb(f.path), writer = openSqliteWriter(db); + const history = new SafetyHistory(db, principal => { + const current = resolvePrincipal(db, principal.id); return !!current && isUsablePrincipal(current, Date.now()); + }, () => writer.idle()); + try { + const page = await history.read(f.principal, { sessionId: "ithaca" }); + const store = createSafetyStore(); store.getState().reset(true); store.getState().begin("restart"); + expect(store.getState().page("restart", page)).toBe(true); + expect(page.records.filter(row => row.kind === "safe_decision").map(row => row.occurrenceId), "JOURNEY_RESTART_RETAINS_INDIVIDUAL_VERDICT").toEqual([a.id]); + expect(page.projection.unresolvedCount).toBe(unfinished ? 1 : 0); + expect(store.getState().normal, "JOURNEY_RESTART_NEVER_INVENTS_COMPLETENESS").toBe(!unfinished); + expect(page.projection.coverage.state).toBe(unfinished ? "incomplete" : "complete"); + expect(BigInt(page.projection.evidenceRevision)).toBeGreaterThanOrEqual(BigInt(before.evidenceRevision)); + const writes = createGovernanceWrites(db, writer); + await expectRejection(writes.firstTaint({ kind: "taint", turnId: "voyage", sessionId: "ithaca", actor: "interactive", model: null, + profile: "governed", payload: { source: "web_fetch", tool: "WebFetch", detail: null } }), "collection ended", + "JOURNEY_RESTART_REFUSES_LATE_OLD_COLLECTION_WRITE"); + + } finally { history.close(); await writer.close(); db.close(); } + } finally { if (!closed) await f.close(); else rmSync(f.root, { recursive: true, force: true }); } +}); diff --git a/tests/helpers/provider-history.ts b/tests/helpers/provider-history.ts index cccf2d40e9..788923b3d7 100644 --- a/tests/helpers/provider-history.ts +++ b/tests/helpers/provider-history.ts @@ -31,6 +31,16 @@ export function bytes(value: unknown): string { export function identical(expected: unknown, actual: unknown, label: string): void { compareBytes(bytes(expected), bytes(actual), label); } +/** The local Claude CLI may replay old system bytes; also hold the actual + * SDK systemPrompt option (or its production fingerprint for hosted turns). */ +export function identicalSystemPromptOptions(appends: readonly unknown[], label: string): void { + expect(appends, `${label}: capture every turn`).toHaveLength(3); + const [first, ...rest] = appends; + expect(first, `${label}: present capture`).not.toBeNull(); + expect(first, `${label}: defined capture`).not.toBeUndefined(); + for (const next of rest) identical(first, next, label); +} + function compareBytes(expected: string, actual: string, label: string): void { const left = Buffer.from(expected), right = Buffer.from(actual); let offset = 0;