Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand All @@ -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 } : {}),
Expand Down Expand Up @@ -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);
Expand Down
27 changes: 23 additions & 4 deletions packages/ui-backend-claude/tests/provider-history.test.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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)", () => {
Expand Down Expand Up @@ -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");
});
26 changes: 26 additions & 0 deletions packages/ui-backend-claude/tests/taint-note.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand Down Expand Up @@ -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 }); }
});
10 changes: 7 additions & 3 deletions packages/ui-backend-pi/tests/fixtures/provider-history-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 }; },
Expand Down
22 changes: 21 additions & 1 deletion packages/ui-backend-pi/tests/provider-history.test.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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");
});
Loading
Loading