From b57ad7a2fd89695b322c97cc12c30fac14dc39a4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 20:24:10 +0000 Subject: [PATCH 1/2] feat(backends): prove a discovering pi worker extension-free from what its loader loaded (#2874) A managed pi worker now counts the extensions, extension load errors and runner paths its session loaded (loadedPiExtensions) and sends the count in its ready frame, before the prompt. The host's execution proof accepts zero as extension-free and any other count as unproven, whatever the configuration said; no report keeps the configuration's answer. The set cannot change mid-turn: pi changes it only in AgentSession.reload(), which a managed worker reaches only through a loaded extension's ctx.reload(). Co-Authored-By: Claude Opus 5.5 --- .changeset/2874-pi-loaded-extensions.md | 5 ++ docs/decisions/governed-writable-workers.md | 39 +++++++++++++-- .../src/native-session-runtime.ts | 32 +++++++----- packages/ui-backend-pi/src/worker-entry.ts | 4 +- packages/ui-backend-pi/src/worker-protocol.ts | 4 +- packages/ui-backend-pi/src/worker-reader.ts | 3 +- packages/ui-backend-pi/src/worker-session.ts | 28 ++++++++--- .../tests/extension-inspection.test.ts | 50 +++++++++++++++++++ .../tests/fixtures/tool-execution-worker.ts | 7 ++- .../tests/fixtures/worker-snapshot-probe.ts | 3 +- .../tests/tool-execution-evidence.test.ts | 31 +++++++++++- .../tests/worker-session-units.test.ts | 4 +- .../tests/worker-snapshot.test.ts | 1 + 13 files changed, 178 insertions(+), 33 deletions(-) create mode 100644 .changeset/2874-pi-loaded-extensions.md diff --git a/.changeset/2874-pi-loaded-extensions.md b/.changeset/2874-pi-loaded-extensions.md new file mode 100644 index 0000000000..c6361954c9 --- /dev/null +++ b/.changeset/2874-pi-loaded-extensions.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-backend-pi": patch +--- + +A pi worker with extension discovery on now proves its curated reads, writes and host bridge calls when its own loader loaded no extension. The worker reports that count before its prompt; any loaded extension or load error, or no report, keeps every result observed as before. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index be94561c15..3aa652f56a 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1504,12 +1504,43 @@ evidence is unproven. The pi backend reports evidence only from its own record of each call's RPCs. A call that names two tools, takes the write lock as a read, or reports only part of its read proves nothing (`export function provenToolExecution`, -`packages/ui-backend-pi/src/worker-session.ts:29-37`). It reports nothing at +`packages/ui-backend-pi/src/worker-session.ts:30-38`). It reports nothing at all for a worker that loads extensions. Extension handlers run on every tool event, bridge reads included, and can write at any time -(`const extensionFree`, `packages/ui-backend-pi/src/worker-session.ts:139`). -With extensions loaded, which is pi's default, every result is observed as -before. The worker's reports are evidence only while it has run nothing but +(`const extensionFree`, `packages/ui-backend-pi/src/worker-session.ts:143`). +With extensions loaded every result is observed as before. + +Whether a worker loaded any is read from the worker's own loader, not only +from its configuration (#2874). The curated default +(`export function discoversPiExtensions`, +`packages/ui-backend-pi/src/extension-inspection.ts:64-66`) loads none. A +worker with discovery on counts every extension, extension load error and +extension runner path its session holds (`export function loadedPiExtensions`, +`packages/ui-backend-pi/src/native-session-runtime.ts:136-139`) and sends +that count in its `ready` frame, before the prompt and before any +model-directed code runs. The host accepts a count of zero as extension-free +and any other count as unproven, whatever the configuration said; a worker +that sends no count keeps the configuration's answer +(`function createExecutionProof`, +`packages/ui-backend-pi/src/worker-session.ts:253-259`). An installed or +repo-local extension is counted, and the managed worker then refuses the turn +anyway (`function unqualifiedResources`, +`packages/ui-backend-pi/src/native-session-runtime.ts:143-145`). + +The count cannot change during the turn. In pi 0.99.2 the loaded set changes +only in `AgentSession.reload()`, which reloads the settings and the resource +loader and builds a new extension runner. Its only callers are pi's +interactive `/reload` and an extension command's `ctx.reload()`, which pi's +modes bind through `bindExtensions`. A managed worker runs no pi mode and +binds nothing, and a `/` prompt reaches only commands that loaded extensions +registered. With none loaded nothing can reach `reload()`. A turn that writes `.pi/extensions/`, a +settings file or a package changes only what a later worker loads. A worker +whose set can change, which is any worker with an extension loaded, proves +nothing. The guard before each model request rechecks the set as a backstop +(`export function installPiToolSafety`, +`packages/ui-backend-pi/src/tool-safety.ts:27-42`). + +The worker's reports are evidence only while it has run nothing but curated code. Once it admits a call outside the provable set (`bash`, `grep`, an index tool that loads `brain.config.ts`, an application tool), or starts a call under a running call's identity, it reports nothing more until it exits. diff --git a/packages/ui-backend-pi/src/native-session-runtime.ts b/packages/ui-backend-pi/src/native-session-runtime.ts index 608706d8a0..f79f00f6c6 100644 --- a/packages/ui-backend-pi/src/native-session-runtime.ts +++ b/packages/ui-backend-pi/src/native-session-runtime.ts @@ -17,15 +17,12 @@ import { resolveModelSpec, toModel } from "./profiles.js"; import type { TurnContext } from "./turn-context.js"; import type { createSessionResources } from "./session-resources.js"; +/** An opened session, and what its loader loaded (`loadedPiExtensions`, #2874). */ +export interface OpenedNativeSession { session: PiSessionLike; turnContext: TurnContext; loadedExtensions: number } + export interface SessionRuntime { - newSession( - profileId: string | undefined, - env: SessionEnv - ): Promise<{ session: PiSessionLike; turnContext: TurnContext }>; - openSession( - sessionId: string, - env: SessionEnv - ): Promise<{ session: PiSessionLike; turnContext: TurnContext }>; + newSession(profileId: string | undefined, env: SessionEnv): Promise; + openSession(sessionId: string, env: SessionEnv): Promise; } export function createSessionRuntime(options: { @@ -86,7 +83,7 @@ export function createSessionRuntime(options: { ...(spec?.thinkingLevel ? { thinkingLevel: spec.thinkingLevel } : {}), }); installPiToolSafety(session.agent,options.toolSafety,()=>unqualifiedResources(loaded.loader,session)); - return { session, turnContext: toolkit.turnContext }; + return { session, turnContext: toolkit.turnContext, loadedExtensions: loadedPiExtensions(loaded.loader, session) }; }, async openSession(sessionId, env) { @@ -124,14 +121,25 @@ export function createSessionRuntime(options: { ); } installPiToolSafety(session.agent,options.toolSafety,()=>unqualifiedResources(loaded.loader,session)); - return { session, turnContext: toolkit.turnContext }; + return { session, turnContext: toolkit.turnContext, loadedExtensions: loadedPiExtensions(loaded.loader, session) }; }, }; } +/** + * What a session's loader loaded: every extension, every extension load error + * and every path its extension runner holds (#2874). The worker reports this + * count before its prompt. Pi changes the set only in `AgentSession.reload()`, + * which a managed worker reaches only through a loaded extension's + * `ctx.reload()`, so zero stays zero for the worker's lifetime. + */ +export function loadedPiExtensions(loader: ResourceLoader, session?: AgentSession): number { + const result = loader.getExtensions(); + return result.extensions.length + result.errors.length + (session?.extensionRunner.getExtensionPaths().length ?? 0); +} + /** No extension identity/name/path is exempt: all extension code can add input * outside the collector. Failed extension loading is unknown coverage too. */ function unqualifiedResources(loader: ResourceLoader,session?:AgentSession):boolean { - const result=loader.getExtensions(); - return result.extensions.length>0||result.errors.length>0||(session?.extensionRunner.getExtensionPaths().length??0)>0; + return loadedPiExtensions(loader, session) > 0; } diff --git a/packages/ui-backend-pi/src/worker-entry.ts b/packages/ui-backend-pi/src/worker-entry.ts index ac4202117f..66072137e1 100644 --- a/packages/ui-backend-pi/src/worker-entry.ts +++ b/packages/ui-backend-pi/src/worker-entry.ts @@ -227,7 +227,9 @@ async function initialize(init: Init): Promise { }); send({ type: "ready", sessionId: session.sessionId, append: renderedAppend, ...(session.model ? { model: session.model } : {}), ...(session.thinkingLevel ? { thinkingLevel: session.thinkingLevel } : {}), - levels: session.getAvailableThinkingLevels?.() ?? [], cost: session.getSessionStats().cost }); + levels: session.getAvailableThinkingLevels?.() ?? [], cost: session.getSessionStats().cost, + // Before any model-directed code runs: the host's evidence for an extension-free worker (#2874). + loadedExtensions: opened.loadedExtensions }); } async function syncAuth(): Promise { diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 9a953ad870..be894288ef 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -75,8 +75,10 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ gitStatusIncluded: z.boolean().nullable(), coverage: z.literal("assembled_inputs"), }).strict() }).strict(), z.object({ type: z.literal("startup_timing"), phase: z.enum(["worker_started", "resources", "session", "initialize"]), durationMs: usageNumber }).strict(), + // `loadedExtensions`: what the worker's own loader loaded, extensions and + // load errors, counted before the prompt (#2874). Absent is no evidence. z.object({ type: z.literal("ready"), sessionId: z.string().uuid(), append: z.string().optional(), model: input.optional(), - thinkingLevel: text.optional(), levels: z.array(text), cost: usageNumber }).strict(), + thinkingLevel: text.optional(), levels: z.array(text), cost: usageNumber, loadedExtensions: z.number().int().nonnegative().optional() }).strict(), z.object({ type: z.literal("event"), event: piWorkerEvent }).strict(), z.object({ type: z.literal("rpc"), id, method: z.enum(["permission", "admission", "bridge", "apply", "readBase", "syncAuth", "lock", "unlock", "fileObservation", "safetyResult", "safetyUnavailable"]), toolCallId: text, toolName: text, input }).strict(), diff --git a/packages/ui-backend-pi/src/worker-reader.ts b/packages/ui-backend-pi/src/worker-reader.ts index 0e614203fb..29612de7a6 100644 --- a/packages/ui-backend-pi/src/worker-reader.ts +++ b/packages/ui-backend-pi/src/worker-reader.ts @@ -52,7 +52,7 @@ export interface PiWorkerReader { resumedIds: ReadonlySet; listeners: ReadonlySet<(event: AgentSessionEvent) => void>; /** Execution proof: a call's start, and the path its end proved, if any. */ - proof: { started(toolCallId: string): void; ended(toolName: string, toolCallId: string): ReturnType }; + proof: { loaded(count: number | undefined): void; started(toolCallId: string): void; ended(toolName: string, toolCallId: string): ReturnType }; toolExecution: SessionEnv["toolExecution"]; dispatch(msg: PiWorkerRpc): Promise; send(value: unknown): void; @@ -78,6 +78,7 @@ export async function readPiWorkerProtocol(reader: PiWorkerReader): Promise | undefined; state.cost = msg.cost; state.thinkingLevel = msg.thinkingLevel as ThinkingLevel; state.levels = msg.levels as ThinkingLevel[]; + proof.loaded(msg.loadedExtensions); ready.resolve(); } else if (msg.type === "prompt_prefix") { if (!state.active) throw new Error("Pi worker emitted a prefix outside the turn"); diff --git a/packages/ui-backend-pi/src/worker-session.ts b/packages/ui-backend-pi/src/worker-session.ts index 213212533f..f849e36db2 100644 --- a/packages/ui-backend-pi/src/worker-session.ts +++ b/packages/ui-backend-pi/src/worker-session.ts @@ -133,11 +133,13 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi child.kill("SIGKILL"); } // Extension code runs on every tool event and can write at any time (#2834): - // only a worker that loads none can prove a call's execution path. Proof - // also ends, for the worker's lifetime, once it admits a call that can run - // other code (bash, grep, brain-owned configuration through an index tool, - // an application tool) or starts a call under a running call's identity: - // from then on the worker's own reports are no evidence. + // only a worker that loads none can prove a call's execution path. A + // configuration without discovery loads none; with discovery on, the + // worker's own loader reports what it loaded before the prompt (#2874). + // Proof also ends, for the worker's lifetime, once it admits a call that + // can run other code (bash, grep, brain-owned configuration through an + // index tool, an application tool) or starts a call under a running call's + // identity: from then on the worker's own reports are no evidence. const extensionFree = envelope !== undefined || !discoversPiExtensions(backend); const proof = createExecutionProof(extensionFree, new Set(["read_file", "write_file", "edit_file", "brain_read_base", ...bridgeTools.map(tool => tool.name)])); const dispatch = createPiWorkerRpcDispatcher({ brainPath: backend.brainPath, turn: turnContext, live, grants, releases, workerLock, @@ -239,12 +241,22 @@ export async function openPiWorkerSession(backend: CreatePiBackendOptions, sessi * as and which RPCs it made. Proof ends, for the worker's lifetime, once it * admits a tool outside the provable set or starts a call under a running * call's identity. + * + * `extensionFree` is what the configuration proves. A discovering worker + * becomes extension-free only when its own loader reports none loaded in its + * `ready` frame (#2874), which the reader accepts once, before the prompt. + * Any loaded extension or load error ends proof, whatever the configuration + * said; no report leaves the configuration's answer. The set cannot change + * after that report: only `AgentSession.reload()` reloads it, and a managed + * worker reaches that only through a loaded extension's `ctx.reload()`. */ function createExecutionProof(extensionFree: boolean, provableTools: ReadonlySet) { - let provable = extensionFree; + let loadedNone = extensionFree, provable = true; const running = new Set(); const executions = new Map(); + const proves = () => loadedNone && provable; return { + loaded: (count: number | undefined): void => { if (count !== undefined) loadedNone = count === 0; }, executed: (msg: PiWorkerRpc): CallExecution => { let seen = executions.get(msg.toolCallId); if (!seen) executions.set(msg.toolCallId, seen = { name: msg.toolName, host: false, lock: false, phases: new Set() }); @@ -252,7 +264,7 @@ function createExecutionProof(extensionFree: boolean, provableTools: ReadonlySet else if (seen.name !== msg.toolName) seen.name = ""; return seen; }, - canFinalize: (toolName:string,toolCallId:string):boolean => provable&&running.has(toolCallId)&&provenToolExecution(toolName,executions.get(toolCallId))!==undefined, + canFinalize: (toolName:string,toolCallId:string):boolean => proves()&&running.has(toolCallId)&&provenToolExecution(toolName,executions.get(toolCallId))!==undefined, admit: (toolName: string): void => { if (!provableTools.has(toolName)) provable = false; }, started: (toolCallId: string): void => { if (running.has(toolCallId)) provable = false; @@ -260,7 +272,7 @@ function createExecutionProof(extensionFree: boolean, provableTools: ReadonlySet }, ended: (toolName: string, toolCallId: string): ReturnType => { const started = running.delete(toolCallId); - const proven = provable && started ? provenToolExecution(toolName, executions.get(toolCallId)) : undefined; + const proven = proves() && started ? provenToolExecution(toolName, executions.get(toolCallId)) : undefined; executions.delete(toolCallId); return proven; }, diff --git a/packages/ui-backend-pi/tests/extension-inspection.test.ts b/packages/ui-backend-pi/tests/extension-inspection.test.ts index 2a835d2507..091f7ec1fe 100644 --- a/packages/ui-backend-pi/tests/extension-inspection.test.ts +++ b/packages/ui-backend-pi/tests/extension-inspection.test.ts @@ -8,6 +8,8 @@ import { createBrainAccess } from "../src/brain-access"; import { discoversPiExtensions, gateUnsupportedConfiguration, inspectPiExtensions, type PiExtensionInspection } from "../src/extension-inspection"; import { backendModule } from "../src/module"; import { createSessionResources } from "../src/session-resources"; +import { createSessionRuntime, loadedPiExtensions } from "../src/native-session-runtime"; +import { PiInputSafetyUnavailableError } from "../src/worker-protocol"; import { toolLockFromKeyed } from "../src/tools"; /** @@ -177,3 +179,51 @@ test("in the curated default only a missing package or an inspection failure blo await expect(unknown.startTurn(turn().req), "PI_CURATED_UNKNOWN_REFUSES").rejects.toBeInstanceOf(BackendRequestError); expect(started.length, "PI_CURATED_UNKNOWN_NEVER_RUNS").toBe(1); }); + +/** + * #2874: a discovering worker reports what its own loader loaded. An + * installed (user) or repo-local extension is counted, so the host proves + * nothing for it; only an empty directory set reports zero. + */ +test("a discovering worker's loader counts each installed or repo-local extension it loaded", async () => { + const caps = { askUser: false, askUserList: false, askUserRank: false, location: false, activity: false, mask: false }; + const count = async (loadExtensions: boolean) => { + const resources = createSessionResources({ + backend: { brainPath: brain }, brain: createBrainAccess(brain), lock: toolLockFromKeyed(createKeyedLock()), + allowedTools: new Set(), confirmPatterns: [], loadExtensions, managedToolSafety: true, + }); + return loadedPiExtensions((await resources.build(resources.buildToolkit(caps), { caps })).loader); + }; + expect(await count(false), "PI_CURATED_REPORTS_NONE").toBe(0); + rmSync(join(agent, "extensions/aeolus.ts")); + expect(await count(true), "PI_REPO_LOCAL_EXTENSION_COUNTED").toBe(1); + rmSync(join(brain, ".pi/extensions/loom.ts")); + writeFileSync(join(agent, "extensions/aeolus.ts"), "export default function () {}\n"); + expect(await count(true), "PI_INSTALLED_EXTENSION_COUNTED").toBe(1); + rmSync(join(agent, "extensions/aeolus.ts")); + expect(await count(true), "PI_DISCOVERY_WITH_NONE_REPORTS_NONE").toBe(0); +}); + +test("a discovering worker's session reports zero only when it loaded no extension, and refuses one", async () => { + const caps = { askUser: false, askUserList: false, askUserRank: false, location: false, activity: false, mask: false }; + const open = () => { + const backend = { brainPath: brain, loadExtensions: true }; + const resources = createSessionResources({ backend, brain: createBrainAccess(brain), lock: toolLockFromKeyed(createKeyedLock()), + allowedTools: new Set(), confirmPatterns: [], loadExtensions: true, managedToolSafety: true }); + const stopped: string[] = []; + const runtime = createSessionRuntime({ backend, sessionDir: join(root, "sessions"), resources, + toolSafety: { permission: async () => { throw new Error("Construction-only fixture cannot execute tools"); }, + result: async () => { throw new Error("Construction-only fixture cannot deliver results"); }, stop() { stopped.push("stop"); } }, + sessionId: "11111111-1111-4111-8111-111111111111", observeManager: () => {}, + modelRuntimeOptions: { authPath: join(root, "auth.json"), modelsPath: join(root, "models.json"), modelsStorePath: join(root, "models-cache.json") } }); + return { opened: runtime.newSession(undefined, { caps }), stopped }; + }; + rmSync(join(agent, "extensions/aeolus.ts")); + const loaded = open(); + expect(await loaded.opened.catch(error => error), "PI_LOADED_EXTENSION_REFUSED").toBeInstanceOf(PiInputSafetyUnavailableError); + expect(loaded.stopped, "PI_LOADED_EXTENSION_STOPPED").toEqual(["stop"]); + rmSync(join(brain, ".pi/extensions/loom.ts")); + const { session, loadedExtensions } = await open().opened; + try { expect(loadedExtensions, "PI_EXTENSION_FREE_SESSION_REPORTS_NONE").toBe(0); } + finally { session.dispose(); } +}); diff --git a/packages/ui-backend-pi/tests/fixtures/tool-execution-worker.ts b/packages/ui-backend-pi/tests/fixtures/tool-execution-worker.ts index 7921219981..5773805804 100644 --- a/packages/ui-backend-pi/tests/fixtures/tool-execution-worker.ts +++ b/packages/ui-backend-pi/tests/fixtures/tool-execution-worker.ts @@ -76,7 +76,12 @@ async function run(prompt: string) { } for await (const message of pipeMessages(process.stdin)) { const value = message as any; - if (value.type === "init") { init = value; send({ type: "ready", sessionId: value.sessionId, levels: [], cost: 0 }); } + if (value.type === "init") { + init = value; + // What this worker's loader loaded, as the real entry reports it (#2874); unset sends no report. + const loaded = process.env.ODYSSEUS_LOADED_EXTENSIONS; + send({ type: "ready", sessionId: value.sessionId, levels: [], cost: 0, ...(loaded === undefined ? {} : { loadedExtensions: Number(loaded) }) }); + } else if (value.type === "prompt") void run(value.text.split("\n", 1)[0]).catch(error => { send({ type: "error", message: error.message }); }); else if (value.type === "answer") { const waiter = pending.get(value.id); pending.delete(value.id); diff --git a/packages/ui-backend-pi/tests/fixtures/worker-snapshot-probe.ts b/packages/ui-backend-pi/tests/fixtures/worker-snapshot-probe.ts index e4d2957a21..e6310007a4 100644 --- a/packages/ui-backend-pi/tests/fixtures/worker-snapshot-probe.ts +++ b/packages/ui-backend-pi/tests/fixtures/worker-snapshot-probe.ts @@ -20,7 +20,8 @@ mock.module("../../src/native-session-runtime.js", () => ({ }, async abort() {}, dispose() {}, getSessionStats: () => ({ cost: 0 }), }; - return { newSession: async () => ({ session }) }; + // A count no real worker reaches: the ready frame must carry the runtime's own (#2874). + return { newSession: async () => ({ session, loadedExtensions: 3 }) }; }, })); await import("../../src/worker-entry.js"); diff --git a/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts b/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts index 6a5ec83c58..7b2502572b 100644 --- a/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts +++ b/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts @@ -11,14 +11,16 @@ import { createPiBackend } from "../src/backend"; * #2834: the host's own record of each call's RPCs, not its name, decides * the evidence a governed turn reports before the call's result. */ -async function evidence(loadExtensions: boolean | undefined, modes: string[]) { +async function evidence(loadExtensions: boolean | undefined, modes: string[], loadedExtensions?: number) { const root = mkdtempSync(join(tmpdir(), "odysseus-pi-evidence-")), brain = join(root, "brain"); mkdirSync(brain); writeFileSync(join(brain, "loom.md"), "Penelope weaves.\n"); const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = join(root, "agent"); const probe = spyOn(worker.workerHostBoundary, "probe").mockReturnValue({ ok: true }); const launch = spyOn(worker, "launchAgentWorkerAsync").mockImplementation(async () => { - const child = spawn(process.execPath, [join(import.meta.dir, "fixtures/tool-execution-worker.ts")], { stdio: ["pipe", "pipe", "pipe"] }); + const env = { ...process.env }; + if (loadedExtensions === undefined) delete env.ODYSSEUS_LOADED_EXTENSIONS; else env.ODYSSEUS_LOADED_EXTENSIONS = String(loadedExtensions); + const child = spawn(process.execPath, [join(import.meta.dir, "fixtures/tool-execution-worker.ts")], { stdio: ["pipe", "pipe", "pipe"], env }); const exited = new Promise((resolve, reject) => { child.once("exit", code => resolve(code ?? 0)); child.once("error", reject); }); return { stdin: child.stdin!, stdout: child.stdout!, stderr: child.stderr!, exited, kill: () => child.kill(), observeFile: worker.createWorkerFileObserver({ brain, configurationRoot: brain, areas: [] }), @@ -86,3 +88,28 @@ test("the default worker is extension-free and proves its curated calls (#3658)" const { reported } = await evidence(undefined, ["read", "base"]); expect(reported, "PI_DEFAULT_WORKER_IS_EXTENSION_FREE").toEqual({ read: { "0_read": ["worker_read"] }, base: { "0_base": ["host_bridge"] } }); }, 30_000); + +/** + * #2874: with discovery on, a worker whose own loader loaded no extension, + * reported before its prompt, proves what a curated worker proves. The set + * cannot change afterwards: only `AgentSession.reload()` reloads it, and a + * managed worker reaches that only through a loaded extension's `ctx.reload()`. + */ +test("a discovering worker that reports no loaded extension proves what a curated worker proves", async () => { + const modes = ["read", "edit", "write", "base", "grep", "locked-read", "silent-read", "half-read", "read,grep,read", "forged,base", "read,dup-read,base"]; + const curated = await evidence(false, modes), reported = await evidence(true, modes, 0); + expect(reported.reported, "PI_REPORTED_EXTENSION_FREE_MATCHES_CURATED").toEqual(curated.reported); + expect(reported.reported.read, "PI_REPORTED_EXTENSION_FREE_PROVES_READS").toEqual({ "0_read": ["worker_read"] }); +}, 60_000); + +test("a worker that reports a loaded extension, or reports nothing, proves no call", async () => { + // One loaded extension can reload the set mid-turn and runs on every tool event. + const loaded = await evidence(true, ["read", "base"], 1); + expect(loaded.reported, "PI_LOADED_EXTENSION_PROVES_NOTHING").toEqual({ read: { "0_read": [null] }, base: { "0_base": [null] } }); + // A curated configuration contradicted by its worker's own loader proves nothing either. + const contradicted = await evidence(false, ["read"], 1); + expect(contradicted.reported, "PI_CONTRADICTED_CURATED_PROVES_NOTHING").toEqual({ read: { "0_read": [null] } }); + // Discovery on with no report is unproven, as before. + const silent = await evidence(true, ["read"]); + expect(silent.reported, "PI_UNREPORTED_DISCOVERY_PROVES_NOTHING").toEqual({ read: { "0_read": [null] } }); +}, 60_000); diff --git a/packages/ui-backend-pi/tests/worker-session-units.test.ts b/packages/ui-backend-pi/tests/worker-session-units.test.ts index 52e9f4ff5d..662b1f9326 100644 --- a/packages/ui-backend-pi/tests/worker-session-units.test.ts +++ b/packages/ui-backend-pi/tests/worker-session-units.test.ts @@ -73,7 +73,7 @@ test("the reader binds the worker's ready frame and refuses a protocol that clos const reading = readPiWorkerProtocol({ child, state, ready, done: Promise.withResolvers(), sessionId: SESSION, backend: { brainPath: brain }, startupStarted: 0, promptContext: undefined, sessionBudgetLimits: undefined, autonomous: false, resumed: false, turnContext: createTurnContext(), nativeVersions: {} as NativeFileVersions, receipts: receipts(), resumedIds: new Set(), listeners: new Set(), - proof: { started: () => {}, ended: () => undefined }, toolExecution: undefined, dispatch: async () => undefined, send: () => {}, + proof: { loaded: () => {}, started: () => {}, ended: () => undefined }, toolExecution: undefined, dispatch: async () => undefined, send: () => {}, fail: () => {}, reportLimitHits: () => {}, limitEnded: async () => undefined, diagnostic: () => "" }); sendPipe(stdout, { type: "ready", sessionId: SESSION, levels: ["low", "high"], cost: 0.25 }); stdout.end(); @@ -87,7 +87,7 @@ test("startup collector loss crosses the real pipe reader without an active-turn const state:PiWorkerTurnState={active:false,initialized:false,ended:false,error:undefined,cost:0,thinkingLevel:undefined,levels:[],model:undefined,ownedPrompt:undefined}; const reading=readPiWorkerProtocol({child,state,ready:Promise.withResolvers(),done:Promise.withResolvers(),sessionId:SESSION,backend:{brainPath:brain}, startupStarted:0,promptContext:undefined,sessionBudgetLimits:undefined,autonomous:false,resumed:false,turnContext:createTurnContext(), - nativeVersions:{} as NativeFileVersions,receipts:receipts(),resumedIds:new Set(),listeners:new Set(),proof:{started(){},ended(){return undefined;}}, + nativeVersions:{} as NativeFileVersions,receipts:receipts(),resumedIds:new Set(),listeners:new Set(),proof:{loaded(){},started(){},ended(){return undefined;}}, toolExecution:undefined,dispatch:async()=>{rpcs++;throw new Error("No active turn");},send(){answers++;},fail(){},reportLimitHits(){},limitEnded:async()=>undefined,diagnostic:()=>""}); sendPipe(stdout,{type:"error",errorClass:"input_safety_unavailable",message:"Unqualified voyage extension"});stdout.end(); const refusal=await reading.then(()=>undefined,error=>error); diff --git a/packages/ui-backend-pi/tests/worker-snapshot.test.ts b/packages/ui-backend-pi/tests/worker-snapshot.test.ts index 59dceaf5ff..07b9573df1 100644 --- a/packages/ui-backend-pi/tests/worker-snapshot.test.ts +++ b/packages/ui-backend-pi/tests/worker-snapshot.test.ts @@ -30,6 +30,7 @@ for (const mode of ["subscriber", "queued"]) test(`worker snapshot overflow send .toEqual(["worker_started", "session", "initialize"]); const frames = received.filter(frame => frame.type !== "startup_timing"); expect(frames[0].type).toBe("ready"); + expect(frames[0].loadedExtensions, "PI_READY_REPORTS_RUNTIME_LOADED_EXTENSIONS").toBe(3); expect(frames.filter(f => ["error", "done", "snapshot"].includes(f.type))).toEqual([ { type: "error", errorClass: "session_too_large", message: "This conversation exceeds the pi worker session size limit. Continue in a new conversation." }, From 0aee0905c56c41f5156ee1826f9bc3acc5114824 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 21:10:18 +0000 Subject: [PATCH 2/2] fix(backends): name the pi package in the #2874 changeset Co-Authored-By: Claude Opus 5.5 --- .changeset/2874-pi-loaded-extensions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/2874-pi-loaded-extensions.md b/.changeset/2874-pi-loaded-extensions.md index c6361954c9..57a27bb156 100644 --- a/.changeset/2874-pi-loaded-extensions.md +++ b/.changeset/2874-pi-loaded-extensions.md @@ -1,5 +1,5 @@ --- -"@schlessera/brain-ui-backend-pi": patch +"@schlessera/brain-backend-pi": patch --- A pi worker with extension discovery on now proves its curated reads, writes and host bridge calls when its own loader loaded no extension. The worker reports that count before its prompt; any loaded extension or load error, or no report, keeps every result observed as before.