From a609e53a89cd74161813b7d589dfc19fd17a5c79 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:01:21 +0000 Subject: [PATCH 01/23] fix(ui-server): retain exact and ambiguous input evidence --- .changeset/session-safety-input-evidence.md | 5 ++ .../ui-server/src/activity/ingestion-taint.ts | 42 +++++++----- .../src/governance/safety-collector.ts | 10 ++- .../ui-server/tests/safety-ledger.test.ts | 66 +++++++++++++++++++ .../tests/safety-result-exits.test.ts | 38 +++++++++++ 5 files changed, 140 insertions(+), 21 deletions(-) create mode 100644 .changeset/session-safety-input-evidence.md diff --git a/.changeset/session-safety-input-evidence.md b/.changeset/session-safety-input-evidence.md new file mode 100644 index 0000000000..f93d01d685 --- /dev/null +++ b/.changeset/session-safety-input-evidence.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Retain unknown delivery when concurrent tool calls reuse one ID. Preserve exact structured search filenames containing colons, and recognize the shipped Pi grep empty-result format without creating a spurious safety trigger. diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 9a8da03783..5a26e7f288 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -115,12 +115,12 @@ export function inputTaintSource(tool: string, input: unknown, brainPath?: strin /** A search from an ancestor directory taints when its output names a file in an untrusted area or a marked file. */ export function outputTaintSource(tool: string, output: string, brainPath?: string, marked?: MarkedLookup): IngestionSource | null { - if (!SEARCH_TOOLS.has(tool)) return null; - for (const line of output.split("\n")) { - const source = fileSource(line.trim().split(":")[0]!, brainPath, marked); - if (source) return source; - } - return null; + // Legacy scalar callers report a known source, not collection completeness. + // Reuse exact path parsing; the collector retains the separate unknown signal. + const signals = outputTaintSignals(tool, output, brainPath, marked); + const known = signals.find( + signal => signal.source !== "legacy_unknown"); + return known?.source ?? null; } /** Independent detector signals; `key` is local correlation, never persisted raw. */ @@ -180,28 +180,34 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(Buffer.byteLength(output)>1048576)throw new Error("Safety search output capacity exceeded"); const result: IngestionSignal[] = [], seen = new Set(); let unknown = false; - let lines:string[]=[]; + let lines:Array<{text:string;path:boolean;structured?:boolean}>=[]; try{ - const parsed=JSON.parse(output);const collect=(value:unknown,depth:number):void=>{ + const parsed=JSON.parse(output);const collect=(value:unknown,depth:number,path=false):void=>{ if(depth>8){unknown=true;return;} - if(typeof value==="string"){lines.push(...value.split("\n"));return;} - if(Array.isArray(value)){for(const item of value)collect(item,depth+1);return;} + if(typeof value==="string"){if(path)lines.push({text:value,path:true,structured:true});else lines.push(...value.split("\n").map(text=>({text,path:false})));return;} + if(Array.isArray(value)){for(const item of value)collect(item,depth+1,path);return;} if(value&&typeof value==="object"){ let recognized=false; for(const [key,item] of Object.entries(value)){ if(["truncated","has_more"].includes(key)&&item===true||key==="omitted"&&typeof item==="number"&&item>0)unknown=true; - if(["filenames","files","paths","matches","content","text","output","file_path","filePath","path"].includes(key)){recognized=true;collect(item,depth+1);} + if(["filenames","files","paths","matches","content","text","output","file_path","filePath","path"].includes(key)){recognized=true;collect(item,depth+1,["filenames","files","paths","file_path","filePath","path"].includes(key));} } if(!recognized)unknown=true; - } + }else unknown=true; };collect(parsed,0); - }catch{ lines=output.split("\n"); /* Plain runtime output uses the same path detector. */ } + }catch{ lines=output.split("\n").map(text=>({text,path:tool==="Glob"})); /* Plain runtime output uses the same path detector. */ } for (const line of lines) { - const text = line.trim(); - if (!text) continue; - const path = text.split(":")[0]!; - if (/truncat|omitted|\.\.\./i.test(text)) unknown = true; - if (!/^(?:[^\s:]+\/[^:]+|[^\s:]+\.[A-Za-z0-9_-]+)$/.test(path)) { unknown = true; continue; } + const text = line.path ? line.text : line.text.trim(); + if (!text) { if(line.structured)unknown=true; continue; } + if (!line.path && tool === "grep" && text === "No matches.") continue; + if (!line.path && /truncat|omitted|\.\.\./i.test(text)) unknown = true; + const match = !line.path && /^(.+?):[0-9]+:/.exec(text); + const path = match ? match[1]! : text; + if (match && /:[0-9]+:/.test(text.slice(match[0].length))) unknown = true; + // Structured path fields and Glob filenames are exact values, not grep + // excerpts. Ambiguous plain output never silently trusts a split prefix. + if (!line.path && !match && text.includes(":")) unknown = true; + if (/[\r\n\0]/.test(path) || !line.structured && !/^(?:[^\s]+\/[^\r\n]+|[^\s]+\.[A-Za-z0-9_-]+)$/.test(path)) { unknown = true; continue; } for (const signal of fileSignals(path, brainPath, marked, "tool_search_output")) { const id = JSON.stringify([signal.detector, signal.key]); if (seen.has(id)) continue; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index b900fd40d5..e5e855a470 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -30,6 +30,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option const calls=new Map;allowed:boolean}>(); // A refusal can prove the call never ran only for an id admitted once, // under one tool name, and never allowed. + const ambiguous=(call:{tools:Map}|undefined)=>!!call&&(call.tools.size>1||[...call.tools.values()].some(n=>n>1)); const once=(call:{tools:Map;allowed:boolean}|undefined)=>!!call&&!call.allowed&&call.tools.size===1&&[...call.tools.values()][0]===1; const operation=(tool:string):Operation=>({tool,inputHashes:new Set(),id:crypto.randomUUID(),occurrences:[],done:false,admitted:false,signals:[],owed:false,refused:false,uncertain:false}); const base=()=>({turnId:options.turnId,sessionId:options.sessionId(),actor:options.actor??"interactive" as const,model:null,profile:null}); @@ -114,6 +115,9 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(previous&&(previous.tool!==tool||previous.done))throw new Error("Safety operation identity already completed or changed tool"); if(!previous&&operations.size>=2000)throw new Error("Safety tool operation capacity exceeded"); const op=previous??operation(tool); + // One result cannot identify which of several logical admissions ended. + // Repeated hooks of one admission do not increase the runtime's count. + if(ambiguous(calls.get(toolUseId)))op.uncertain=true; if(!op.inputHashes.has(inputHash)&&op.inputHashes.size>=16)throw new Error("Safety input revision capacity exceeded"); op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ @@ -152,12 +156,12 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } await options.referenceReads?.observeResult(options.turnId,toolUseId,tool,output,finalized&&!op.uncertain,segments); - const state=finalized&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; + const state=finalized&&!op.uncertain&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; // The last exposure commits with the call's discharge, in one // transaction: no end and no restart can find the record durable and // the call still owed between them, and gap a recorded result. for(const [index,id] of op.occurrences.entries()){ - const last=index===op.occurrences.length-1&&op.owed; + const last=index===op.occurrences.length-1&&op.owed&&!op.uncertain; const stored=await writes.record({...base(),kind:"taint_exposure",dedupeKey:id,payload:{occurrenceId:id,state}},last?{discharge:op.id}:undefined); if(last&&stored.discharged)op.owed=false; } @@ -165,7 +169,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // A result with nothing to record is recorded by its discharge alone. A // discharge that cannot commit stays owed, which only gaps the chat; it // is no loss of this record. - await discharge(op); + if(!op.uncertain)await discharge(op); }catch(error){return reject(error);} },true,reject));}, // The runtime asks to admit one call under this id, for this tool. Counted diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index bcf2099f70..f0478ea643 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -500,3 +500,69 @@ for(const boundary of ["rows","bytes"] as const)for(const admission of ["collect expect(sum.rows).toBeLessThanOrEqual(1000000);expect(sum.bytes).toBeLessThanOrEqual(536870912); expect(f.writes.safety("voyage","ithaca").restriction).toBe("restricted"); }finally{await peerWriter?.close();peer?.close();await f.close();}}); + +test("concurrent same-tool admissions cannot let one result discharge an interrupted reused ID",async()=>{ + const f=fixture();try{const {collector}=await fresh(f); + for(const url of ['https://example.com/odyssey','https://example.com/loom']){ + collector.admitting!('reused_fetch','WebFetch'); + await collector.begin('reused_fetch','WebFetch',{url}); + await collector.allowed!('reused_fetch'); + } + await collector.result('reused_fetch','WebFetch','Odysseus retained the first notice.',true); + await f.writes.safetyEnd('voyage'); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get(),'REUSED_ID_INTERRUPTED_CALL_REMAINS_A_DURABLE_GAP').toEqual({failure:'recording_failed'}); + expect(f.writes.safety(null,'ithaca').coverage.state).toBe('incomplete'); + const exposures=safetyRecords(f.db,'ithaca').filter(r=>r.kind==='exposure'); + expect(exposures.every(r=>r.kind==='exposure'&&(r.payload as {state:string}).state!=='finalized'),'AMBIGUOUS_RESULT_CANNOT_FINALIZE_REUSED_ID_EXPOSURES').toBe(true); + }finally{await f.close();} +}); + +test("structured Glob paths preserve a marked colon filename",async()=>{ + const f=fixture();try{const {collector}=await fresh(f); + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + untrustedMarkOperations(f.db).mark('notes/voyage:home.md',null,Date.UTC(2026,6,12)); + await collector.begin('colon_glob','Glob',{path:'.'}); + await collector.result('colon_glob','Glob',JSON.stringify({filenames:['notes/voyage:home.md']}),true); + expect(triggers(f).map(r=>(r.payload as {source:string}).source),'STRUCTURED_COLON_PATH_RETAINS_EXPLICIT_MARK').toContain('user_marked'); + }finally{await f.close();} +}); + +test("the Pi grep known empty result does not manufacture unknown input",async()=>{ + const f=fixture();try{const {collector}=await fresh(f); + await collector.begin('empty_grep','grep',{path:'.',pattern:'sirens'}); + await collector.result('empty_grep','grep','No matches.',true); + expect(triggers(f),'PI_EMPTY_GREP_CREATES_NO_SPURIOUS_TRIGGER').toHaveLength(0); + expect(f.writes.safety(null,'ithaca').restriction).toBe('normal'); + }finally{await f.close();} +}); + +test('one logical admission retains input revisions without inventing concurrent calls',async()=>{ + const f=fixture();try{const {collector}=await fresh(f); + collector.admitting!('revised_fetch','WebFetch'); + await collector.begin('revised_fetch','WebFetch',{url:'https://example.com/odyssey'}); + await collector.begin('revised_fetch','WebFetch',{url:'https://example.com/loom'}); + await collector.result('revised_fetch','WebFetch','Odysseus retained the revised notice.',true); + expect(f.db.query('SELECT COUNT(*) n FROM safety_obligations').get()).toEqual({n:0}); + const exposures=safetyRecords(f.db,'ithaca').filter(r=>r.kind==='exposure'); + expect(exposures).toHaveLength(2); + expect(exposures.every(r=>(r.payload as {state:string}).state==='finalized')).toBe(true); + await f.writes.safetyEnd('voyage');expect(f.writes.safety(null,'ithaca').coverage.state).toBe('complete'); + }finally{await f.close();} +}); + +for(const [name,tool,output,expected] of [ + ['structured numeric colon','Glob',JSON.stringify({filenames:['notes/voyage:2:home.md']}),['user_marked']], + ['structured spaced colon','Glob',JSON.stringify({filenames:['notes/voyage home:map.md']}),['user_marked']], + ['plain colon grep','grep','notes/voyage:home.md:7: Odysseus',['user_marked']], + ['ambiguous numeric colon','grep','notes/voyage:2:home.md:7: Odysseus',['legacy_unknown']], + ['malformed structured path','Glob',JSON.stringify({filenames:[123]}),['legacy_unknown']], + ['unsupported empty wording','Grep','No matches.',['legacy_unknown']], + ['empty plus malformed remainder','grep','No matches.\nunknown remainder',['legacy_unknown']], +] as const)test(`search evidence format: ${name}`,async()=>{ + const f=fixture();try{const {collector}=await fresh(f); + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + for(const path of ['notes/voyage:home.md','notes/voyage:2:home.md','notes/voyage home:map.md'])untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + await collector.begin('format_search',tool,{path:'.'});await collector.result('format_search',tool,output,true); + expect(triggers(f).map(r=>(r.payload as {source:string}).source),'EXACT_PATH_OR_UNKNOWN_REMAINDER_IS_RETAINED').toEqual([...expected]); + }finally{await f.close();} +}); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 8fbb0e49f3..9260971665 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -455,3 +455,41 @@ test("a Pi grant is unusable until the collector's last check passes, and a call expect(f.chat().coverage.state, "SAFETY_PI_REFUSED_ADMITTED_READ_NEVER_LOOKS_COMPLETE").toBe("incomplete"); } finally { release(); await f.close(); } }); + +for(const binding of ['pi','claude'] as const)test(`${binding}: two allowed searches reusing an ID cannot share one result discharge`,async()=>{ + const f=await voyage();try{ + const input={pattern:'sirens'},id='reused_search'; + let admit:()=>Promise; + if(binding==='pi'){ + const turn=createTurnContext();turn.bridge={inputSafety:f.collector,emit(){},requestPermission:async()=>({behavior:'allow'})} as never;turn.signal=f.controller.signal; + let handler:((event:unknown)=>Promise)|undefined; + const gate=createPermissionGate({turn,allowedTools:new Set(['grep']),confirmPatterns:[]}); + (typeof gate==='function'?gate:gate.factory)({on:(name:string,callback:unknown)=>{if(name==='tool_call')handler=callback as typeof handler;}} as never); + admit=async()=>{const result=await handler!({toolName:'grep',toolCallId:id,input});expect(result,'PI_REUSED_ID_CALL_REACHES_EXECUTION').toBeUndefined();}; + }else{ + const wiring=createPermissionWiring({req:{prompt:'Listen for the sirens.',signal:f.controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:'allow'}),inputSafety:f.collector}} as never, + allowedTools:['Grep'],confirmPatterns:[],brainPath:f.brain,childEnv:{PATH:'/usr/bin:/bin'},log(){},turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never}); + const hook=wiring.hooks!.PreToolUse!.find(group=>!group.matcher)!.hooks[0]!; + admit=async()=>{const result=await hook({hook_event_name:'PreToolUse',tool_name:'Grep',tool_input:input,tool_use_id:id} as never,id,{signal:f.controller.signal});expect((result as {hookSpecificOutput?:{permissionDecision?:string}}).hookSpecificOutput?.permissionDecision,'CLAUDE_REUSED_ID_CALL_REACHES_EXECUTION').not.toBe('deny');}; + } + await admit();const first=await searchRuns(f,id,input); + await admit();expect(await searchRuns(f,id,input),'SECOND_SAME_ID_SEARCH_ACTUALLY_EXECUTES').toContain('Sail past the sirens'); + await f.collector.result(id,binding==='pi'?'grep':'Grep',first,true); + expect(f.owed(),'ONE_RESULT_CANNOT_DISCHARGE_TWO_LOGICAL_CALLS').toBe(1); + await f.writes.safetyEnd('voyage'); + expect(f.failure(),'RUNTIME_REUSED_ID_RESULT_LOSS_IS_DURABLE').toBe('recording_failed'); + const reopened=createUiDb(f.path);try{expect(reopened.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:'recording_failed'});}finally{reopened.close();} + }finally{await f.close();} +}); + +test('real Pi grep empty output stays empty when the collector records its result',async()=>{ + const f=await voyage();try{ + const input={pattern:'no_cyclops_matches_here'}; + await f.collector.begin('empty_search','grep',input); + const output=await searchRuns(f,'empty_search',input); + expect(JSON.parse(output),'SHIPPED_PI_EMPTY_SEARCH_FORMAT').toEqual([{type:'text',text:'No matches.'}]); + await f.collector.result('empty_search','grep',output,true); + expect(f.recorded(),'REAL_EMPTY_SEARCH_CREATES_NO_OCCURRENCE').toEqual([]); + expect(f.chat().restriction).toBe('normal'); + }finally{await f.close();} +}); From 2416782c49c529e8673d0209040a013e2d397603 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:35:27 +0000 Subject: [PATCH 02/23] fix: parse search evidence by admitted backend format --- .../ui-server/src/activity/ingestion-taint.ts | 85 +++++++++++++------ packages/ui-server/src/activity/recorder.ts | 8 +- .../ui-server/src/brain/turn-extraction.ts | 4 +- .../src/governance/safety-collector.ts | 7 +- .../ui-server/tests/ingestion-taint.test.ts | 14 +++ .../ui-server/tests/safety-ledger.test.ts | 66 +++++++++++--- .../tests/safety-result-exits.test.ts | 2 +- 7 files changed, 138 insertions(+), 48 deletions(-) diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 5a26e7f288..84f831bb07 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -175,46 +175,77 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri /** Each distinct returned normalized path contributes independently of the input. * Unparseable/truncated search output is a separate unknown-provenance signal. * This is conservative text observation, not a claim of verified source bytes. */ -export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup): IngestionSignal[] { +export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: {backendId?: string; outputMode?: string}): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; if(Buffer.byteLength(output)>1048576)throw new Error("Safety search output capacity exceeded"); + // These are the installed backend tool formats, not guesses from a line. + // Claude Grep's mode is retained from its admitted input; Glob text is paths. + const format = tool === "Glob" ? "files_with_matches" : tool === "grep" + ? context === undefined || context.backendId === "pi" ? "pi-grep" : "unknown" : context?.outputMode ?? "unknown"; const result: IngestionSignal[] = [], seen = new Set(); - let unknown = false; - let lines:Array<{text:string;path:boolean;structured?:boolean}>=[]; - try{ - const parsed=JSON.parse(output);const collect=(value:unknown,depth:number,path=false):void=>{ + const paths: string[] = [], texts: string[] = []; + let unknown = !["files_with_matches", "content", "count", "pi-grep"].includes(format); + try { + const collect = (value: unknown, depth: number, path = false): void => { if(depth>8){unknown=true;return;} - if(typeof value==="string"){if(path)lines.push({text:value,path:true,structured:true});else lines.push(...value.split("\n").map(text=>({text,path:false})));return;} + if(typeof value==="string"){(path?paths:texts).push(value);return;} if(Array.isArray(value)){for(const item of value)collect(item,depth+1,path);return;} if(value&&typeof value==="object"){ let recognized=false; for(const [key,item] of Object.entries(value)){ if(["truncated","has_more"].includes(key)&&item===true||key==="omitted"&&typeof item==="number"&&item>0)unknown=true; - if(["filenames","files","paths","matches","content","text","output","file_path","filePath","path"].includes(key)){recognized=true;collect(item,depth+1,["filenames","files","paths","file_path","filePath","path"].includes(key));} + if(["filenames","files","paths","matches","content","text","output","file_path","filePath","path"].includes(key)){ + recognized=true;collect(item,depth+1,["filenames","files","paths","file_path","filePath","path"].includes(key)); + } } if(!recognized)unknown=true; }else unknown=true; - };collect(parsed,0); - }catch{ lines=output.split("\n").map(text=>({text,path:tool==="Glob"})); /* Plain runtime output uses the same path detector. */ } - for (const line of lines) { - const text = line.path ? line.text : line.text.trim(); - if (!text) { if(line.structured)unknown=true; continue; } - if (!line.path && tool === "grep" && text === "No matches.") continue; - if (!line.path && /truncat|omitted|\.\.\./i.test(text)) unknown = true; - const match = !line.path && /^(.+?):[0-9]+:/.exec(text); - const path = match ? match[1]! : text; - if (match && /:[0-9]+:/.test(text.slice(match[0].length))) unknown = true; - // Structured path fields and Glob filenames are exact values, not grep - // excerpts. Ambiguous plain output never silently trusts a split prefix. - if (!line.path && !match && text.includes(":")) unknown = true; - if (/[\r\n\0]/.test(path) || !line.structured && !/^(?:[^\s]+\/[^\r\n]+|[^\s]+\.[A-Za-z0-9_-]+)$/.test(path)) { unknown = true; continue; } - for (const signal of fileSignals(path, brainPath, marked, "tool_search_output")) { - const id = JSON.stringify([signal.detector, signal.key]); - if (seen.has(id)) continue; - if(result.length>=256)throw new Error("Safety search signal capacity exceeded"); - seen.add(id); result.push(signal); + }; + collect(JSON.parse(output),0); + }catch{ texts.push(output); } + // Pi emits this only as the entire text of an empty result. Neither line + // trimming nor a sentinel mixed with other content establishes emptiness. + if(format==="pi-grep"&&!unknown&&!paths.length&&texts.length===1&&texts[0]==="No matches.")return []; + const entries=[...paths.map(text=>({text,path:true})),...texts.flatMap(text=>text.split("\n").map(line=>({text:line,path:false})))]; + for(const entry of entries){ + const text=entry.text; + // Check every path line, including exact fields and Glob content blocks. + if(/truncat|omitted|\.\.\.|…/i.test(text))unknown=true; + if(!text){if(entry.path)unknown=true;continue;} + let candidates:string[]; + if(entry.path||format==="files_with_matches")candidates=[text]; + else if(format==="count"){ + const count=/:([0-9]+)$/.exec(text);candidates=count?[text.slice(0,count.index)]:[text];if(!count)unknown=true; + }else{ + // Zero-width matches retain overlapping delimiters in `file:2:7:text`. + // Every possible filename is checked; ambiguity remains restrictive. + candidates=[]; + for(const split of text.matchAll(/(?=:[1-9][0-9]*:)/g)){ + if(candidates.length>=256)throw new Error("Safety search candidate capacity exceeded"); + const path=text.slice(0,split.index); + if(Buffer.byteLength(path)>1024)throw new Error("Safety path capacity exceeded"); + candidates.push(path); + } + if(!candidates.length){unknown=true;candidates.push(text);} + else {if(candidates.length>1)unknown=true;if(format==="unknown")candidates.push(text);} + } + for(const path of candidates){ + if(!path||/[\r\n\0]/.test(path)){unknown=true;continue;} + for(const signal of fileSignals(path,brainPath,marked,"tool_search_output")){ + const id=JSON.stringify([signal.detector,signal.key]);if(seen.has(id))continue; + if(result.length>=256)throw new Error("Safety search signal capacity exceeded"); + seen.add(id);result.push(signal); + } } } - if (unknown) result.push({ source: "legacy_unknown", detector: "tool_search_output", key: "unknown_remainder" }); + if(unknown){if(result.length>=256)throw new Error("Safety search signal capacity exceeded");result.push({source:"legacy_unknown",detector:"tool_search_output",key:"unknown_remainder"});} return result; } + +/** Installed backend formats, from the admitted tool input rather than result text. */ +export function searchOutputContext(tool: string, input: unknown, backendId = tool === "grep" ? "pi" : "claude"): {backendId: string; outputMode?: string} { + if(tool!=="Grep")return {backendId}; + const requested=input&&typeof input==="object"?(input as Record).output_mode:undefined; + const mode=requested??"files_with_matches"; + return {backendId,outputMode:typeof mode==="string"&&["content","files_with_matches","count"].includes(mode)?mode:"unknown"}; +} diff --git a/packages/ui-server/src/activity/recorder.ts b/packages/ui-server/src/activity/recorder.ts index 1baaf2e802..34a8e531fd 100644 --- a/packages/ui-server/src/activity/recorder.ts +++ b/packages/ui-server/src/activity/recorder.ts @@ -44,7 +44,7 @@ import { occurrence } from "../governance/occurrence.js"; import { recordFirstTaint } from "../governance/session-taint.js"; import { redactCredentials, type RuntimeStatus } from "./runtime-status.js"; -import { inputTaintSignals, outputTaintSignals, type IngestionSignal, type MarkedLookup } from "./ingestion-taint.js"; +import { inputTaintSignals, outputTaintSignals, searchOutputContext, type IngestionSignal, type MarkedLookup } from "./ingestion-taint.js"; import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { MAX_PROVIDER_UNAVAILABLE_PER_TURN, providerUnavailablePayloads } from "../governance/provider-unavailable.js"; import type { AwaitableActivityStore, SpanOutcome, SpanUsage } from "./store.js"; @@ -193,7 +193,7 @@ export function createTurnRecorder( // roadblock trace. Record only after a result, when content was ingested. let safetyHooked = false; const collectionEpoch = crypto.randomUUID(); - const ingestions = new Map(); + const ingestions = new Map }>(); const usageSamples: UsageSample[] = []; let outcomeDetail: string | null = null; let cancelledAt: number | null = null; @@ -355,7 +355,7 @@ export function createTurnRecorder( break; } if (!safetyHooked && turn.origin !== "autonomous") { - try { ingestions.set(msg.toolUseId, { signals: inputTaintSignals(msg.toolName, msg.input, deps.brainPath, marked, shellProxied), tool: msg.toolName, operationId: crypto.randomUUID() }); } + try { ingestions.set(msg.toolUseId, { signals: inputTaintSignals(msg.toolName, msg.input, deps.brainPath, marked, shellProxied), tool: msg.toolName, operationId: crypto.randomUUID(), searchContext: searchOutputContext(msg.toolName,msg.input) }); } catch { deps.abort?.(new Error("Safety input detection failed; the turn was stopped."));if(governanceWrites)writes.after(()=>governanceWrites.safetyFail(runId)); } } const traced = traceCall(msg.toolUseId, msg.toolName); @@ -382,7 +382,7 @@ export function createTurnRecorder( ingestions.delete(msg.toolUseId); let signals:IngestionSignal[]=[]; if(!safetyHooked&&ingestion){ - try { signals=[...ingestion.signals,...outputTaintSignals(ingestion.tool,msg.output,deps.brainPath,marked)]; } + try { signals=[...ingestion.signals,...outputTaintSignals(ingestion.tool,msg.output,deps.brainPath,marked,ingestion.searchContext)]; } catch { deps.abort?.(new Error("Safety result detection failed; the turn was stopped."));if(governanceWrites)writes.after(()=>governanceWrites.safetyFail(runId)); } } if (!safetyHooked && ingestion && signals.length && !traced?.denied && firstTaint && deps.governance) { diff --git a/packages/ui-server/src/brain/turn-extraction.ts b/packages/ui-server/src/brain/turn-extraction.ts index 5b839a84ef..4e171d776f 100644 --- a/packages/ui-server/src/brain/turn-extraction.ts +++ b/packages/ui-server/src/brain/turn-extraction.ts @@ -29,7 +29,7 @@ */ import { prepareOutwardPlan } from "@schlessera/brain-ui-sdk/internal"; import { requestToolPermission, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; -import { inputTaintSignals, outputTaintSignals } from "../activity/ingestion-taint.js"; +import { inputTaintSignals, outputTaintSignals, searchOutputContext } from "../activity/ingestion-taint.js"; import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { existsSync } from "node:fs"; import { posix } from "node:path"; @@ -189,7 +189,7 @@ export function createTurnExtraction(options: { // (its connections taint the session at the proxy), another MCP server, // an untrusted area or a marked file. const tainting = !localTool(tool) || inputTaintSignals(tool, input, options.brainPath, options.marked, true).length > 0 - || outputTaintSignals(tool, output, options.brainPath, options.marked).length > 0; + || outputTaintSignals(tool, output, options.brainPath, options.marked, searchOutputContext(tool,input)).length > 0; if (tainting) current.tainting(namedHosts(output)); } catch { state.complete = false; } }; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index e5e855a470..481059d0fd 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -1,7 +1,7 @@ /** Concrete turn-bound pre-delivery collector. All decisions remain restrictive. */ import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import type { Database } from "bun:sqlite"; -import { inputTaintSignals, outputTaintSignals, type IngestionSignal } from "../activity/ingestion-taint.js"; +import { inputTaintSignals, outputTaintSignals, searchOutputContext, type IngestionSignal } from "../activity/ingestion-taint.js"; import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { occurrence } from "./occurrence.js"; import type { GovernanceWrites } from "./event-writes.js"; @@ -17,7 +17,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // cannot be recorded faithfully. `owed`: its obligation is durable (#3812). // `refused`: the backend refused a call with this id, so nothing more for // that id is admitted or let run. - type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean;uncertain:boolean}; + type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean;uncertain:boolean;searchOutputMode?:string}; const operations=new Map(); // What the backend reported about each id: how many times the runtime asked // to admit a call under it, for each tool name it came under, and whether @@ -120,6 +120,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(ambiguous(calls.get(toolUseId)))op.uncertain=true; if(!op.inputHashes.has(inputHash)&&op.inputHashes.size>=16)throw new Error("Safety input revision capacity exceeded"); op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); + op.searchOutputMode=searchOutputContext(tool,input,options.backendId).outputMode; for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ if(op.signals.some(prior=>prior.detector===signal.detector&&prior.key===signal.key))continue; const item=observed(toolUseId,signal.detector,op.id); @@ -151,7 +152,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option } // Record output independently, before the backend releases it to the // model. Its bytes already exist, so a refusal here is never "before delivery". - for(const signal of outputTaintSignals(tool,output,options.brainPath,marked)){ + for(const signal of outputTaintSignals(tool,output,options.brainPath,marked,{backendId:options.backendId,outputMode:op.searchOutputMode})){ const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index 564a495611..e557b174e6 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -122,3 +122,17 @@ test("a collected external compute job's output is a taint source on both backen expect(queryGovernanceEvents(db, { turnId: "t-1", kinds: ["taint"], limit: 5 }).map(event => event.payload), "COMPUTE_OUTPUT_TAINT_RECORDED").toEqual([{ source: "compute_output", tool: "brain_compute_collect", detail: null }]); } finally { db.close(); } }); + +test('the display recorder uses admitted Claude filename mode for colon paths',async()=>{ + const db=createUiDb(':memory:'); + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + const sessionId='odysseus-colon-search';db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES(?,'Voyage',0,0)").run(sessionId); + untrustedMarkOperations(db).mark('notes/voyage:2:home.md',null,Date.UTC(2026,6,12)); + const recorder=createTurnRecorder({store:createActivityStore(db,{writer:'test'}),governanceDb:db,brainPath:brain,governance:event=>{recordGovernanceEvent(db,event);}},{turnId:'colon-search',sessionId,profile:'governed'}); + try{ + recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'colon_grep',toolName:'Grep'}); + recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'colon_grep',toolName:'Grep',input:{path:'.',pattern:'sirens',output_mode:'files_with_matches'}}); + recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'colon_grep',isError:false,output:JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}])}); + expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source),'RECORDER_PRESERVES_ADMITTED_SEARCH_FORMAT').toEqual(['user_marked']); + }finally{recorder.finish('success');db.close();} +}); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index f0478ea643..8a34eb1250 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -16,14 +16,14 @@ import { openDialogue, bindDialogue } from "../src/ws/dialogue-storage"; function fixture(){const root=mkdtempSync(join(tmpdir(),"odysseus-safety-ledger-")),path=join(root,"ui.db"); const db=createUiDb(path),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); return {root,path,db,writer,writes,async close(){await writer.close();db.close();rmSync(root,{recursive:true,force:true});}};} -async function fresh(f:ReturnType,turnId="voyage",sessionId="ithaca"){ - const bindingId=crypto.randomUUID();await f.writes.safetyBegin({turnId,bindingId,sessionId:null,principalId:"odysseus",backendId:"claude",at:0}); - f.db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES(?,0,0,'claude')").run(sessionId); +async function fresh(f:ReturnType,turnId="voyage",sessionId="ithaca",backendId="claude"){ + const bindingId=crypto.randomUUID();await f.writes.safetyBegin({turnId,bindingId,sessionId:null,principalId:"odysseus",backendId,at:0}); + f.db.query("INSERT INTO sessions(id,created_at,last_active_at,backend_id) VALUES(?,0,0,?)").run(sessionId,backendId); f.db.query("INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES(?,'odysseus',0)").run(sessionId); safetyCatalogCreated(f.db,sessionId,"odysseus",turnId); await f.writes.bind(turnId,sessionId); - const collector=createSafetyCollector(f.db,f.writes,{turnId,bindingId,sessionId:()=>sessionId,backendId:"claude",signal:new AbortController().signal,shellProxied:()=>true,brainPath:"/srv/ithaca"}); - await collector.ready("claude",1);return {bindingId,collector}; + const collector=createSafetyCollector(f.db,f.writes,{turnId,bindingId,sessionId:()=>sessionId,backendId,signal:new AbortController().signal,shellProxied:()=>true,brainPath:"/srv/ithaca"}); + await collector.ready(backendId,1);return {bindingId,collector}; } const triggers=(f:ReturnType,sid="ithaca")=>safetyRecords(f.db,sid).filter(r=>r.kind==="occurrence"); @@ -361,7 +361,7 @@ test("an imported provisional alias binds its actual owner and generation withou for(const excerpt of ["Odysseus omitted the mast.","Odysseus repairs the truncated mast.\n... results truncated ..."])test(`search path signals survive excerpt ${excerpt.split(".")[0]}`,async()=>{ const f=fixture();try{const {collector}=await fresh(f); const {untrustedMarkOperations}=await import("../src/files/untrusted-marks");untrustedMarkOperations(f.db).mark("workspaces/voyage/raft.md",null,0); - await collector.begin("excerpt","Grep",{path:"notes"}); + await collector.begin("excerpt","Grep",{path:"notes",output_mode:"content"}); await collector.result("excerpt","Grep",`workspaces/voyage/raft.md:1: ${excerpt}`,true); const sources=triggers(f).map(r=>(r.payload as {source:string}).source); expect(sources,"SAFETY_EXCERPT_NEVER_SUPPRESSES_PATH_SIGNALS").toEqual(expect.arrayContaining(["workspace_read","user_marked"])); @@ -528,7 +528,7 @@ test("structured Glob paths preserve a marked colon filename",async()=>{ }); test("the Pi grep known empty result does not manufacture unknown input",async()=>{ - const f=fixture();try{const {collector}=await fresh(f); + const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca','pi'); await collector.begin('empty_grep','grep',{path:'.',pattern:'sirens'}); await collector.result('empty_grep','grep','No matches.',true); expect(triggers(f),'PI_EMPTY_GREP_CREATES_NO_SPURIOUS_TRIGGER').toHaveLength(0); @@ -551,18 +551,62 @@ test('one logical admission retains input revisions without inventing concurrent }); for(const [name,tool,output,expected] of [ + ['three overlapping delimiters','grep','notes/voyage:2:7:9:sirens',['user_marked','user_marked','legacy_unknown']], + ['zero line number','grep','notes/voyage:0:sirens',['legacy_unknown']], + ['padded wrapped Pi sentinel','grep',JSON.stringify([{type:'text',text:' No matches. '}]),['legacy_unknown']], + ['multiple Pi text blocks','grep',JSON.stringify([{type:'text',text:'No matches.'},{type:'text',text:''}]),['legacy_unknown']], + ['truncated Pi empty metadata','grep',JSON.stringify({content:[{type:'text',text:'No matches.'}],truncated:true}),['legacy_unknown']], + ['empty numeric candidate','grep',':2:7:sirens',['user_marked','legacy_unknown']], + ['overlapping numeric delimiters','grep','notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], + ['Glob text content colon','Glob',JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['user_marked']], + ['clipped plain Glob path','Glob','notes/voy...',['legacy_unknown']], + ['clipped structured Glob text','Glob',JSON.stringify([{type:'text',text:'notes/voy...'}]),['legacy_unknown']], + ['padded Pi empty sentinel','grep',' No matches. ',['legacy_unknown']], + ['mixed Pi match and empty sentinel','grep','notes/voyage.md:1: sirens\nNo matches.',['legacy_unknown']], + ['wrapped mixed Pi match and empty sentinel','grep',JSON.stringify([{type:'text',text:'notes/voyage.md:1: sirens\nNo matches.'}]),['legacy_unknown']], ['structured numeric colon','Glob',JSON.stringify({filenames:['notes/voyage:2:home.md']}),['user_marked']], ['structured spaced colon','Glob',JSON.stringify({filenames:['notes/voyage home:map.md']}),['user_marked']], ['plain colon grep','grep','notes/voyage:home.md:7: Odysseus',['user_marked']], - ['ambiguous numeric colon','grep','notes/voyage:2:home.md:7: Odysseus',['legacy_unknown']], + ['ambiguous numeric colon','grep','notes/voyage:2:home.md:7: Odysseus',['user_marked','legacy_unknown']], ['malformed structured path','Glob',JSON.stringify({filenames:[123]}),['legacy_unknown']], ['unsupported empty wording','Grep','No matches.',['legacy_unknown']], ['empty plus malformed remainder','grep','No matches.\nunknown remainder',['legacy_unknown']], ] as const)test(`search evidence format: ${name}`,async()=>{ - const f=fixture();try{const {collector}=await fresh(f); + const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca',tool==='grep'?'pi':'claude'); const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); - for(const path of ['notes/voyage:home.md','notes/voyage:2:home.md','notes/voyage home:map.md'])untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); - await collector.begin('format_search',tool,{path:'.'});await collector.result('format_search',tool,output,true); + for(const path of [':2','notes/voyage:home.md','notes/voyage:2','notes/voyage:2:7','notes/voyage:2:home.md','notes/voyage home:map.md'])untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + await collector.begin('format_search',tool,{path:'.',output_mode:'content'});await collector.result('format_search',tool,output,true); expect(triggers(f).map(r=>(r.payload as {source:string}).source),'EXACT_PATH_OR_UNKNOWN_REMAINDER_IS_RETAINED').toEqual([...expected]); }finally{await f.close();} }); + +for(const [name,backend,tool,mode,output,expected] of [ + ['Claude filename mode','claude','Grep','files_with_matches',JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['user_marked']], + ['Claude count mode','claude','Grep','count','notes/voyage:2:7',['user_marked']], + ['invalid Claude mode','claude','Grep','unsupported','notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], + ['Pi sentinel cannot cross backend','claude','grep','content','No matches.',['legacy_unknown']], +] as const)test(`search parser identity: ${name}`,async()=>{ + const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca',backend); + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + for(const path of ['notes/voyage:2','notes/voyage:2:home.md'])untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + await collector.begin('mode_search',tool,{path:'.',output_mode:mode});await collector.result('mode_search',tool,output,true); + expect(triggers(f).map(r=>(r.payload as {source:string}).source),'PARSER_FOLLOWS_ADMITTED_TOOL_AND_MODE').toEqual([...expected]); + }finally{await f.close();} +}); + +test('Pi empty output never suppresses an independent untrusted input signal',async()=>{ + const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca','pi'); + await collector.begin('empty_workspace','grep',{path:'workspaces',pattern:'sirens'}); + await collector.result('empty_workspace','grep','No matches.',true); + expect(triggers(f).map(r=>(r.payload as {source:string}).source)).toEqual(['workspace_read']); + }finally{await f.close();} +}); + +test('excessive grep delimiter ambiguity refuses recording and retains a durable gap',async()=>{ + const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca','pi'); + await collector.begin('bounded_search','grep',{path:'.',pattern:'sirens'}); + await expectRejection(collector.result('bounded_search','grep',`notes/voyage${':1'.repeat(300)}:sirens`,true),'Safety search candidate capacity exceeded','SEARCH_AMBIGUITY_CAPACITY_STOPS_RECORDING'); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:'recording_failed'}); + expect(f.writes.safety(null,'ithaca').restriction).toBe('restricted'); + }finally{await f.close();} +}); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 9260971665..d3acd1da75 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -458,7 +458,7 @@ test("a Pi grant is unusable until the collector's last check passes, and a call for(const binding of ['pi','claude'] as const)test(`${binding}: two allowed searches reusing an ID cannot share one result discharge`,async()=>{ const f=await voyage();try{ - const input={pattern:'sirens'},id='reused_search'; + const input=binding==='claude'?{pattern:'sirens',output_mode:'content'}:{pattern:'sirens'},id='reused_search'; let admit:()=>Promise; if(binding==='pi'){ const turn=createTurnContext();turn.bridge={inputSafety:f.collector,emit(){},requestPermission:async()=>({behavior:'allow'})} as never;turn.signal=f.controller.signal; From a2d5e2c022a9788d2c7cea57d064eb397ecee7d4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:46:39 +0000 Subject: [PATCH 03/23] fix: require recognized complete search output schemas --- docs/plans/reviewable-session-safety.md | 4 +- .../ui-server/src/activity/ingestion-taint.ts | 140 +++++++++--------- .../src/governance/safety-collector.ts | 6 +- .../tests/ingestion-taint-schema.test.ts | 40 +++++ .../ui-server/tests/ingestion-taint.test.ts | 10 +- .../ui-server/tests/safety-ledger.test.ts | 20 +-- .../tests/safety-result-exits.test.ts | 5 +- .../ui-server/tests/untrusted-marks.test.ts | 2 +- 8 files changed, 136 insertions(+), 91 deletions(-) create mode 100644 packages/ui-server/tests/ingestion-taint-schema.test.ts diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 5f57f1cc9e..cabf3d7ad0 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -29,8 +29,8 @@ public design or its fixtures. Fictional examples use the Odysseus world. their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, - `packages/ui-server/src/activity/ingestion-taint.ts:155`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:178`). + `packages/ui-server/src/activity/ingestion-taint.ts:156`; + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:189`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery; display frames alone never prove finalized delivery or complete coverage. diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 84f831bb07..e6fc274f14 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -1,5 +1,6 @@ /** Which completed tool calls ingested untrusted content (G6); this grants no tool authority. */ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { z } from "zod"; import { posix } from "node:path"; import { WORKER_AREA_ROOT, WORKER_REFERENCE_ROOT, WORKER_WORKTREE_ROOT } from "@schlessera/brain-ui-sdk/internal"; import { commandTaintSource } from "./command-taint.js"; @@ -117,7 +118,7 @@ export function inputTaintSource(tool: string, input: unknown, brainPath?: strin export function outputTaintSource(tool: string, output: string, brainPath?: string, marked?: MarkedLookup): IngestionSource | null { // Legacy scalar callers report a known source, not collection completeness. // Reuse exact path parsing; the collector retains the separate unknown signal. - const signals = outputTaintSignals(tool, output, brainPath, marked); + const signals = outputTaintSignals(tool, output, brainPath, marked, searchOutputContext(tool, {})); const known = signals.find( signal => signal.source !== "legacy_unknown"); return known?.source ?? null; @@ -172,80 +173,83 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri return [{ source, detector, key: "input" }]; } -/** Each distinct returned normalized path contributes independently of the input. - * Unparseable/truncated search output is a separate unknown-provenance signal. - * This is conservative text observation, not a claim of verified source bytes. */ -export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: {backendId?: string; outputMode?: string}): IngestionSignal[] { +/** Admitted format only. Invalid or incomplete output always retains unknown coverage. */ +interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number } +// Installed SDK: GlobInput/GrepInput and GlobOutput/GrepOutput in +// @anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:905-983,3506-3545. Pi's shipped grep and text +// envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:52-91) +// and `textResult` (packages/ui-backend-pi/src/tool-kit.ts:25-27). +const natural = z.number().int().nonnegative().safe(); +const globOutput = z.object({ durationMs: z.number().finite().nonnegative(), numFiles: natural, + filenames: z.array(z.string()), truncated: z.boolean(), totalMatches: natural.optional(), countIsComplete: z.boolean().optional() }).strict(); +const grepOutput = z.object({ mode: z.enum(['content','files_with_matches','count']).optional(), numFiles: natural, + filenames: z.array(z.string()), content: z.string().optional(), numLines: natural.optional(), numMatches: natural.optional(), + totalFiles: natural.optional(), totalLines: natural.optional(), appliedLimit: natural.optional(), appliedOffset: natural.optional() }).strict(); + +export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: SearchOutputContext): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; - if(Buffer.byteLength(output)>1048576)throw new Error("Safety search output capacity exceeded"); - // These are the installed backend tool formats, not guesses from a line. - // Claude Grep's mode is retained from its admitted input; Glob text is paths. - const format = tool === "Glob" ? "files_with_matches" : tool === "grep" - ? context === undefined || context.backendId === "pi" ? "pi-grep" : "unknown" : context?.outputMode ?? "unknown"; - const result: IngestionSignal[] = [], seen = new Set(); - const paths: string[] = [], texts: string[] = []; - let unknown = !["files_with_matches", "content", "count", "pi-grep"].includes(format); - try { - const collect = (value: unknown, depth: number, path = false): void => { - if(depth>8){unknown=true;return;} - if(typeof value==="string"){(path?paths:texts).push(value);return;} - if(Array.isArray(value)){for(const item of value)collect(item,depth+1,path);return;} - if(value&&typeof value==="object"){ - let recognized=false; - for(const [key,item] of Object.entries(value)){ - if(["truncated","has_more"].includes(key)&&item===true||key==="omitted"&&typeof item==="number"&&item>0)unknown=true; - if(["filenames","files","paths","matches","content","text","output","file_path","filePath","path"].includes(key)){ - recognized=true;collect(item,depth+1,["filenames","files","paths","file_path","filePath","path"].includes(key)); - } - } - if(!recognized)unknown=true; - }else unknown=true; - }; - collect(JSON.parse(output),0); - }catch{ texts.push(output); } - // Pi emits this only as the entire text of an empty result. Neither line - // trimming nor a sentinel mixed with other content establishes emptiness. - if(format==="pi-grep"&&!unknown&&!paths.length&&texts.length===1&&texts[0]==="No matches.")return []; - const entries=[...paths.map(text=>({text,path:true})),...texts.flatMap(text=>text.split("\n").map(line=>({text:line,path:false})))]; - for(const entry of entries){ - const text=entry.text; - // Check every path line, including exact fields and Glob content blocks. + if(Buffer.byteLength(output)>1048576)throw new Error('Safety search output capacity exceeded'); + const result:IngestionSignal[]=[],seen=new Set();let unknown=false; + const add=(path:string)=>{ + if(!path||/[\r\n\0]/.test(path)){unknown=true;return;} + if(/truncat|omitted|\.\.\.|…/i.test(path))unknown=true; + for(const signal of fileSignals(path,brainPath,marked,'tool_search_output')){ + const key=JSON.stringify([signal.detector,signal.key]);if(seen.has(key))continue; + if(result.length>=256)throw new Error('Safety search signal capacity exceeded');seen.add(key);result.push(signal); + } + }; + const content=(text:string,numbers:boolean)=>{ if(/truncat|omitted|\.\.\.|…/i.test(text))unknown=true; - if(!text){if(entry.path)unknown=true;continue;} - let candidates:string[]; - if(entry.path||format==="files_with_matches")candidates=[text]; - else if(format==="count"){ - const count=/:([0-9]+)$/.exec(text);candidates=count?[text.slice(0,count.index)]:[text];if(!count)unknown=true; - }else{ - // Zero-width matches retain overlapping delimiters in `file:2:7:text`. - // Every possible filename is checked; ambiguity remains restrictive. - candidates=[]; - for(const split of text.matchAll(/(?=:[1-9][0-9]*:)/g)){ - if(candidates.length>=256)throw new Error("Safety search candidate capacity exceeded"); - const path=text.slice(0,split.index); - if(Buffer.byteLength(path)>1024)throw new Error("Safety path capacity exceeded"); - candidates.push(path); + for(const line of text.split('\n')){ + if(!line){unknown=true;continue;} + let count=0; + // No line numbers: every colon could separate the filename and content. + // With numbers: lookahead preserves overlapping `:2:7:` candidates. + for(const split of line.matchAll(numbers?/(?=:[1-9][0-9]*:)/g:/(?=:)/g)){ + if(count++>=256)throw new Error('Safety search candidate capacity exceeded');add(line.slice(0,split.index)); } - if(!candidates.length){unknown=true;candidates.push(text);} - else {if(candidates.length>1)unknown=true;if(format==="unknown")candidates.push(text);} + if(count!==1)unknown=true; } - for(const path of candidates){ - if(!path||/[\r\n\0]/.test(path)){unknown=true;continue;} - for(const signal of fileSignals(path,brainPath,marked,"tool_search_output")){ - const id=JSON.stringify([signal.detector,signal.key]);if(seen.has(id))continue; - if(result.length>=256)throw new Error("Safety search signal capacity exceeded"); - seen.add(id);result.push(signal); + }; + let parsed:unknown;try{parsed=JSON.parse(output);}catch{/* Pi returns raw text; Claude requires its structured schema. */} + if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ + // `safetyResultInput` (packages/ui-backend-pi/src/worker-protocol.ts:92-99) + // joins the shipped tool's text. No JSON envelope is part of this format. + if(/^[\s]*[\[{\"]/.test(output))unknown=true; + else if(output!=='No matches.')content(output,true); + }else if((context?.backendId??'claude')==='claude'&&tool==='Glob'){ + const checked=globOutput.safeParse(parsed); + if(!checked.success)unknown=true; + else {const value=checked.data;for(const path of value.filenames)add(path); + if(value.numFiles!==value.filenames.length||value.truncated||value.countIsComplete===false|| + value.totalMatches!==undefined&&value.totalMatches!==value.numFiles)unknown=true;} + }else if((context?.backendId??'claude')==='claude'&&tool==='Grep'){ + const checked=grepOutput.safeParse(parsed),mode=context?.outputMode; + if(!checked.success||!['files_with_matches','content','count'].includes(mode??''))unknown=true; + else {const value=checked.data;for(const path of value.filenames)add(path); + if(value.mode!==undefined&&value.mode!==mode||value.numFiles!==value.filenames.length|| + value.totalFiles!==undefined&&value.totalFiles!==value.numFiles|| + (value.appliedOffset??0)>0||(context?.offset??0)>0)unknown=true; + if(mode==='files_with_matches'){if(value.content!==undefined&&value.content!=='')unknown=true;} + else if(value.content===undefined)unknown=true; + else { + if(value.content) { + if(mode==='content')content(value.content,context?.lineNumbers!==false); + else for(const line of value.content.split('\n')){const split=/:([0-9]+)$/.exec(line);if(split)add(line.slice(0,split.index));else unknown=true;} + } + const lines=value.content?value.content.split('\n').length:0; + if(value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines)unknown=true; } } - } - if(unknown){if(result.length>=256)throw new Error("Safety search signal capacity exceeded");result.push({source:"legacy_unknown",detector:"tool_search_output",key:"unknown_remainder"});} + }else unknown=true; + if(unknown){if(result.length>=256)throw new Error('Safety search signal capacity exceeded');result.push({source:'legacy_unknown',detector:'tool_search_output',key:'unknown_remainder'});} return result; } -/** Installed backend formats, from the admitted tool input rather than result text. */ -export function searchOutputContext(tool: string, input: unknown, backendId = tool === "grep" ? "pi" : "claude"): {backendId: string; outputMode?: string} { - if(tool!=="Grep")return {backendId}; - const requested=input&&typeof input==="object"?(input as Record).output_mode:undefined; - const mode=requested??"files_with_matches"; - return {backendId,outputMode:typeof mode==="string"&&["content","files_with_matches","count"].includes(mode)?mode:"unknown"}; +/** Retain only validated format selectors, never raw input. */ +export function searchOutputContext(tool:string,input:unknown,backendId=tool==='grep'?'pi':'claude'):SearchOutputContext { + if(tool!=='Grep')return {backendId}; + const value=input&&typeof input==='object'?input as Record:{}; + const mode=value.output_mode??'files_with_matches',numbers=value['-n']??true,offset=value.offset??0; + return {backendId,outputMode:typeof mode==='string'&&['content','files_with_matches','count'].includes(mode)&&typeof numbers==='boolean'&&Number.isSafeInteger(offset)&&Number(offset)>=0?mode:'unknown',lineNumbers:numbers===true,offset:typeof offset==='number'?offset:0}; } diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 481059d0fd..8782866166 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -17,7 +17,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // cannot be recorded faithfully. `owed`: its obligation is durable (#3812). // `refused`: the backend refused a call with this id, so nothing more for // that id is admitted or let run. - type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean;uncertain:boolean;searchOutputMode?:string}; + type Operation={tool:string;inputHashes:Set;id:string;occurrences:string[];done:boolean;admitted:boolean;signals:IngestionSignal[];outputHash?:string;owed:boolean;refused:boolean;uncertain:boolean;searchContext?:ReturnType}; const operations=new Map(); // What the backend reported about each id: how many times the runtime asked // to admit a call under it, for each tool name it came under, and whether @@ -120,7 +120,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(ambiguous(calls.get(toolUseId)))op.uncertain=true; if(!op.inputHashes.has(inputHash)&&op.inputHashes.size>=16)throw new Error("Safety input revision capacity exceeded"); op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); - op.searchOutputMode=searchOutputContext(tool,input,options.backendId).outputMode; + op.searchContext=searchOutputContext(tool,input,options.backendId); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ if(op.signals.some(prior=>prior.detector===signal.detector&&prior.key===signal.key))continue; const item=observed(toolUseId,signal.detector,op.id); @@ -152,7 +152,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option } // Record output independently, before the backend releases it to the // model. Its bytes already exist, so a refusal here is never "before delivery". - for(const signal of outputTaintSignals(tool,output,options.brainPath,marked,{backendId:options.backendId,outputMode:op.searchOutputMode})){ + for(const signal of outputTaintSignals(tool,output,options.brainPath,marked,op.searchContext)){ const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts new file mode 100644 index 0000000000..32dafbc96c --- /dev/null +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -0,0 +1,40 @@ +import {expect,test} from 'bun:test'; +import {outputTaintSignals,searchOutputContext} from '../src/activity/ingestion-taint'; +const glob=(filenames:string[],extra={})=>JSON.stringify({durationMs:1,numFiles:filenames.length,filenames,truncated:false,...extra}); +const grep=(filenames:string[],extra={})=>JSON.stringify({numFiles:filenames.length,filenames,...extra}); +for(const [name,tool,input,output,expected] of [ + ['overlapping numeric delimiters','grep',{},'notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], + ['Glob text block rejected','Glob',{},JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['legacy_unknown']], + ['plain clipped Glob rejected','Glob',{},'notes/voy...',['legacy_unknown']], + ['padded Pi sentinel','grep',{},' No matches. ',['legacy_unknown']], + ['mixed Pi sentinel','grep',{},'notes/voyage.md:1:sirens\nNo matches.',['user_marked','legacy_unknown']], + ['Claude pagination','Grep',{},grep(['notes/loom.md'],{totalFiles:2}),['legacy_unknown']], + ['arbitrary Pi JSON sentinel','grep',{},JSON.stringify({matches:'No matches.'}),['legacy_unknown']], + ['clipped Glob JSON','Glob',{},'{"filenames":["notes/voyage.md"',['legacy_unknown']], + ['Claude no line numbers','Grep',{output_mode:'content','-n':false},grep([],{content:'notes/voyage.md:signal:2:echo',numLines:1}),['user_marked','legacy_unknown']], + ['marked exact Glob','Glob',{},glob(['notes/voyage:2:home.md']),['user_marked']], + ['complete Glob','Glob',{},glob(['notes/loom.md']),[]], + ['Glob total omitted','Glob',{},glob(['notes/loom.md'],{totalMatches:2}),['legacy_unknown']], + ['Glob lower bound','Glob',{},glob(['notes/loom.md'],{countIsComplete:false}),['legacy_unknown']], + ['Glob truncated flag','Glob',{},glob(['notes/loom.md'],{truncated:true}),['legacy_unknown']], + ['Glob clipped filename','Glob',{},glob(['notes/voy...']),['legacy_unknown']], + ['Glob unknown key','Glob',{},glob([],{unexpected:true}),['legacy_unknown']], + ['Glob invalid count','Glob',{},glob(['notes/loom.md'],{numFiles:0}),['legacy_unknown']], + ['Glob missing fields','Glob',{},JSON.stringify({filenames:['notes/voyage.md']}),['legacy_unknown']], + ['Grep wrong mode','Grep',{},grep([],{mode:'content'}),['legacy_unknown']], + ['Grep omitted lines','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',numLines:1,totalLines:2}),['legacy_unknown']], + ['Grep offset','Grep',{offset:1},grep([]),['legacy_unknown']], + ['Grep count colon filename','Grep',{output_mode:'count'},grep([],{content:'notes/voyage:2:7'}),['user_marked']], + ['Grep numbered content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked']], + ['Grep ambiguous content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage:2:7:sirens',numLines:1}),['user_marked','legacy_unknown']], + ['Pi exact sentinel','grep',{},'No matches.',[]], + ['Pi transport sentinel','grep',{},JSON.stringify([{type:'text',text:'No matches.'}]),['legacy_unknown']], + ['Pi multiple blocks','grep',{},JSON.stringify([{type:'text',text:'No matches.'},{type:'text',text:''}]),['legacy_unknown']], + ['Pi unknown transport key','grep',{},JSON.stringify([{type:'text',text:'No matches.',other:true}]),['legacy_unknown']], + ['Pi malformed JSON','grep',{},'{"matches":',['legacy_unknown']], + ['Pi quoted sentinel','grep',{},JSON.stringify('No matches.'),['legacy_unknown']], +] as const)test(`recognized search shape: ${name}`,()=>{ + const marked=(path:string)=>['notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); + const signals=outputTaintSignals(tool,output,'/srv/odysseus/brain',marked,searchOutputContext(tool,input)); + expect(signals.map(s=>s.source),'ONLY_RECOGNIZED_COMPLETE_SHAPES_CAN_REMAIN_HEALTHY').toEqual([...expected]); +}); diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index e557b174e6..ebd5027d82 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -12,7 +12,7 @@ test("unqualified managed reference and worktree file reads retain ordinary work "/tmp/brain-worktrees/ithaca/README.md", "/tmp/brain-reference/public/ithaca/../loom/README.md"]) { expect(inputTaintSource("Read", { file_path: path }, brain), "REFERENCE_PATH_IS_NOT_A_TRUST_EXEMPTION").toBe("workspace_read"); expect(inputTaintSource("read_file", { path }, brain)).toBe("workspace_read"); - expect(outputTaintSource("Grep", `${path}:1: Odysseus`, brain)).toBe("workspace_read"); + expect(outputTaintSource("grep", `${path}:1: Odysseus`, brain)).toBe("workspace_read"); } expect(inputTaintSource("Read", { file_path: "/tmp/brain-reference-other/README.md" }, brain)).toBeNull(); }); @@ -62,7 +62,7 @@ test("a brain whose own path contains an area name does not taint its ordinary r }); test("a search from an ancestor directory taints only when its output names an untrusted-area file", () => { - expect(outputTaintSource("Grep", `${brain}/notes/a.md\n${brain}/workspaces/voyage/b.md`, brain), "G6_GREP_OUTPUT_WORKSPACE").toBe("workspace_read"); + expect(outputTaintSource("Grep", JSON.stringify({numFiles:2,filenames:[`${brain}/notes/a.md`,`${brain}/workspaces/voyage/b.md`]}), brain), "G6_GREP_OUTPUT_WORKSPACE").toBe("workspace_read"); expect(outputTaintSource("grep", "notes/a.md:3: Ithaca\n.brain-ui/inbox/share-1/n.md:1: Ithaca", brain)).toBe("staged_share"); expect(outputTaintSource("Glob", `${brain}/notes/a.md`, brain)).toBeNull(); expect(outputTaintSource("Read", "workspaces/voyage/b.md", brain), "G6_OUTPUT_ONLY_FOR_SEARCH").toBeNull(); @@ -83,9 +83,9 @@ test("the real recorder keeps independent sources and excludes a denied fetch", const events = () => queryGovernanceEvents(db, { sessionId, kinds: ["taint"], limit: 10 }); try { call("denied", "WebFetch", { url: "https://ithaca.invalid" }, "Denied", true); - call("clean", "Grep", { pattern: "Ithaca" }, `${brain}/notes/a.md`); + call("clean", "Grep", { pattern: "Ithaca" }, JSON.stringify({numFiles:1,filenames:[`${brain}/notes/a.md`]})); expect(events(), "G6_DENIED_FETCH_CLEAN").toHaveLength(0); - call("search", "Grep", { pattern: "Ithaca" }, `${brain}/workspaces/voyage/a.md`); + call("search", "Grep", { pattern: "Ithaca" }, JSON.stringify({numFiles:1,filenames:[`${brain}/workspaces/voyage/a.md`]})); call("fetch", "WebFetch", { url: "https://ithaca.invalid" }, "A fictional harbour notice."); expect(events().map(event => [event.payload.source, event.payload.tool, event.payload.detail]), "G6_RECORDER_EVERY_TOOL_SOURCE") .toEqual([["workspace_read", "Grep", null], ["web_fetch", "WebFetch", null]]); @@ -132,7 +132,7 @@ test('the display recorder uses admitted Claude filename mode for colon paths',a try{ recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'colon_grep',toolName:'Grep'}); recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'colon_grep',toolName:'Grep',input:{path:'.',pattern:'sirens',output_mode:'files_with_matches'}}); - recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'colon_grep',isError:false,output:JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}])}); + recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'colon_grep',isError:false,output:JSON.stringify({numFiles:1,filenames:['notes/voyage:2:home.md']})}); expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source),'RECORDER_PRESERVES_ADMITTED_SEARCH_FORMAT').toEqual(['user_marked']); }finally{recorder.finish('success');db.close();} }); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 8a34eb1250..b93cef8c06 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -259,7 +259,7 @@ test("imported and legacy provisional histories remain unknown after new detecto test("detector overflow stops collection rather than silently truncating later paths",async()=>{ const f=fixture();try{const {collector}=await fresh(f); await collector.begin("many","Grep",{path:"notes"}); - const output=Array.from({length:257},(_,i)=>`workspaces/voyage/map-${i}.md`).join("\n"); + const output=JSON.stringify({numFiles:257,filenames:Array.from({length:257},(_,i)=>`workspaces/voyage/map-${i}.md`)}); await expectRejection(collector.result("many","Grep",output,true),"signal capacity"); expect(f.writes.safety(null,"ithaca").reasons,"SAFETY_DETECTOR_OVERFLOW_LATCHED").toContain("recording_failed"); }finally{await f.close();}}); @@ -331,7 +331,7 @@ test("a clean search input cannot suppress mixed JSON paths, an explicit mark or const f=fixture();try{const {collector}=await fresh(f); const {untrustedMarkOperations}=await import("../src/files/untrusted-marks");untrustedMarkOperations(f.db).mark("notes/voyage.md",null,0); await collector.begin("mixed","Grep",{path:"notes"}); - await collector.result("mixed","Grep",JSON.stringify({filenames:["workspaces/voyage/map.md","notes/voyage.md"],truncated:true}),true); + await collector.result("mixed","Grep",JSON.stringify({numFiles:2,filenames:["workspaces/voyage/map.md","notes/voyage.md"],totalFiles:3}),true); expect(triggers(f).map(r=>(r.payload as {source:string}).source),"SAFETY_CLEAN_INPUT_CANNOT_HIDE_UNTRUSTED_JSON_OUTPUT").toEqual(["workspace_read","user_marked","legacy_unknown"]); }finally{await f.close();}}); @@ -362,7 +362,7 @@ for(const excerpt of ["Odysseus omitted the mast.","Odysseus repairs the truncat const f=fixture();try{const {collector}=await fresh(f); const {untrustedMarkOperations}=await import("../src/files/untrusted-marks");untrustedMarkOperations(f.db).mark("workspaces/voyage/raft.md",null,0); await collector.begin("excerpt","Grep",{path:"notes",output_mode:"content"}); - await collector.result("excerpt","Grep",`workspaces/voyage/raft.md:1: ${excerpt}`,true); + await collector.result("excerpt","Grep",JSON.stringify({numFiles:0,filenames:[],content:`workspaces/voyage/raft.md:1: ${excerpt}`}),true); const sources=triggers(f).map(r=>(r.payload as {source:string}).source); expect(sources,"SAFETY_EXCERPT_NEVER_SUPPRESSES_PATH_SIGNALS").toEqual(expect.arrayContaining(["workspace_read","user_marked"])); if(excerpt.includes("..."))expect(sources).toContain("legacy_unknown"); @@ -522,7 +522,7 @@ test("structured Glob paths preserve a marked colon filename",async()=>{ const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); untrustedMarkOperations(f.db).mark('notes/voyage:home.md',null,Date.UTC(2026,6,12)); await collector.begin('colon_glob','Glob',{path:'.'}); - await collector.result('colon_glob','Glob',JSON.stringify({filenames:['notes/voyage:home.md']}),true); + await collector.result('colon_glob','Glob',JSON.stringify({durationMs:1,numFiles:1,filenames:['notes/voyage:home.md'],truncated:false}),true); expect(triggers(f).map(r=>(r.payload as {source:string}).source),'STRUCTURED_COLON_PATH_RETAINS_EXPLICIT_MARK').toContain('user_marked'); }finally{await f.close();} }); @@ -558,14 +558,14 @@ for(const [name,tool,output,expected] of [ ['truncated Pi empty metadata','grep',JSON.stringify({content:[{type:'text',text:'No matches.'}],truncated:true}),['legacy_unknown']], ['empty numeric candidate','grep',':2:7:sirens',['user_marked','legacy_unknown']], ['overlapping numeric delimiters','grep','notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], - ['Glob text content colon','Glob',JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['user_marked']], + ['Glob text content colon','Glob',JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['legacy_unknown']], ['clipped plain Glob path','Glob','notes/voy...',['legacy_unknown']], ['clipped structured Glob text','Glob',JSON.stringify([{type:'text',text:'notes/voy...'}]),['legacy_unknown']], ['padded Pi empty sentinel','grep',' No matches. ',['legacy_unknown']], ['mixed Pi match and empty sentinel','grep','notes/voyage.md:1: sirens\nNo matches.',['legacy_unknown']], ['wrapped mixed Pi match and empty sentinel','grep',JSON.stringify([{type:'text',text:'notes/voyage.md:1: sirens\nNo matches.'}]),['legacy_unknown']], - ['structured numeric colon','Glob',JSON.stringify({filenames:['notes/voyage:2:home.md']}),['user_marked']], - ['structured spaced colon','Glob',JSON.stringify({filenames:['notes/voyage home:map.md']}),['user_marked']], + ['structured numeric colon','Glob',JSON.stringify({durationMs:1,numFiles:1,filenames:['notes/voyage:2:home.md'],truncated:false}),['user_marked']], + ['structured spaced colon','Glob',JSON.stringify({durationMs:1,numFiles:1,filenames:['notes/voyage home:map.md'],truncated:false}),['user_marked']], ['plain colon grep','grep','notes/voyage:home.md:7: Odysseus',['user_marked']], ['ambiguous numeric colon','grep','notes/voyage:2:home.md:7: Odysseus',['user_marked','legacy_unknown']], ['malformed structured path','Glob',JSON.stringify({filenames:[123]}),['legacy_unknown']], @@ -581,9 +581,9 @@ for(const [name,tool,output,expected] of [ }); for(const [name,backend,tool,mode,output,expected] of [ - ['Claude filename mode','claude','Grep','files_with_matches',JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['user_marked']], - ['Claude count mode','claude','Grep','count','notes/voyage:2:7',['user_marked']], - ['invalid Claude mode','claude','Grep','unsupported','notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], + ['Claude filename mode','claude','Grep','files_with_matches',JSON.stringify({numFiles:1,filenames:['notes/voyage:2:home.md']}),['user_marked']], + ['Claude count mode','claude','Grep','count',JSON.stringify({numFiles:0,filenames:[],content:'notes/voyage:2:7'}),['user_marked']], + ['invalid Claude mode','claude','Grep','unsupported','notes/voyage:2:7:sirens',['legacy_unknown']], ['Pi sentinel cannot cross backend','claude','grep','content','No matches.',['legacy_unknown']], ] as const)test(`search parser identity: ${name}`,async()=>{ const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca',backend); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index d3acd1da75..2929cc38d5 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -1,3 +1,4 @@ +import { safetyResultInput } from "../../ui-backend-pi/src/worker-protocol"; /** Every exit between a tool running and its result's record either records * the result or leaves its chat a permanent gap, in both backends (#3812). * Every call `begin()` admits owes its result until the record is durable, @@ -280,7 +281,7 @@ test("a call still owed when the host dies leaves its chat a permanent gap at bo async function searchRuns(f: Voyage, toolCallId: string, input: Record): Promise { const grep = createBrainTools({ brain: createBrainAccess(f.brain), turn: createTurnContext(), exec: {}, lock: { withKey: async (_key: string, run: () => Promise) => run() } } as never).find(tool => tool.name === "grep")!; - return JSON.stringify((await grep.execute(toolCallId, input as never, f.controller.signal, undefined, undefined as never)).content); + return safetyResultInput("grep",(await grep.execute(toolCallId, input as never, f.controller.signal, undefined, undefined as never)).content).output; } /** What stands for a call that ran and was never reported: its obligation, then its chat's gap. */ @@ -487,7 +488,7 @@ test('real Pi grep empty output stays empty when the collector records its resul const input={pattern:'no_cyclops_matches_here'}; await f.collector.begin('empty_search','grep',input); const output=await searchRuns(f,'empty_search',input); - expect(JSON.parse(output),'SHIPPED_PI_EMPTY_SEARCH_FORMAT').toEqual([{type:'text',text:'No matches.'}]); + expect(output,'SHIPPED_PI_EMPTY_SEARCH_FORMAT').toBe('No matches.'); await f.collector.result('empty_search','grep',output,true); expect(f.recorded(),'REAL_EMPTY_SEARCH_CREATES_NO_OCCURRENCE').toEqual([]); expect(f.chat().restriction).toBe('normal'); diff --git a/packages/ui-server/tests/untrusted-marks.test.ts b/packages/ui-server/tests/untrusted-marks.test.ts index f600805131..3423376086 100644 --- a/packages/ui-server/tests/untrusted-marks.test.ts +++ b/packages/ui-server/tests/untrusted-marks.test.ts @@ -46,7 +46,7 @@ test("a file tool or search that reads a marked file is a user_marked source; ot // An untrusted area still names its own source first. expect(inputTaintSource("Read", { file_path: `${brain}/workspaces/${MESSAGE}` }, brain, () => true)).toBe("workspace_read"); // A search from an ancestor directory taints when its output names the marked file. - expect(outputTaintSource("Grep", `${brain}/notes/a.md\n${brain}/${MESSAGE}`, brain, marked), "MARKED_SEARCH_OUTPUT").toBe("user_marked"); + expect(outputTaintSource("Grep", JSON.stringify({numFiles:2,filenames:[`${brain}/notes/a.md`,`${brain}/${MESSAGE}`]}), brain, marked), "MARKED_SEARCH_OUTPUT").toBe("user_marked"); expect(outputTaintSource("grep", `${MESSAGE}:3: Ithaca`, brain, marked)).toBe("user_marked"); expect(outputTaintSource("Glob", `${brain}/${LETTER}`, brain, marked)).toBeNull(); // The capabilities note names marked files among the untrusted sources. From 8ad5efe360721169a3e09850b7191e2ce3f02dea Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:55:34 +0000 Subject: [PATCH 04/23] fix: retain search sources across malformed and limited pages --- .../ui-server/src/activity/ingestion-taint.ts | 50 +++++++++++++------ .../tests/ingestion-taint-schema.test.ts | 40 +++++++++++++-- .../ui-server/tests/safety-ledger.test.ts | 2 +- .../tests/safety-result-exits.test.ts | 17 +++++++ 4 files changed, 90 insertions(+), 19 deletions(-) diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index e6fc274f14..3bde8f1228 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -174,7 +174,7 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri } /** Admitted format only. Invalid or incomplete output always retains unknown coverage. */ -interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number } +interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number } // Installed SDK: GlobInput/GrepInput and GlobOutput/GrepOutput in // @anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:905-983,3506-3545. Pi's shipped grep and text // envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:52-91) @@ -189,7 +189,7 @@ const grepOutput = z.object({ mode: z.enum(['content','files_with_matches','coun export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: SearchOutputContext): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; if(Buffer.byteLength(output)>1048576)throw new Error('Safety search output capacity exceeded'); - const result:IngestionSignal[]=[],seen=new Set();let unknown=false; + const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=false; const add=(path:string)=>{ if(!path||/[\r\n\0]/.test(path)){unknown=true;return;} if(/truncat|omitted|\.\.\.|…/i.test(path))unknown=true; @@ -206,7 +206,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str // No line numbers: every colon could separate the filename and content. // With numbers: lookahead preserves overlapping `:2:7:` candidates. for(const split of line.matchAll(numbers?/(?=:[1-9][0-9]*:)/g:/(?=:)/g)){ - if(count++>=256)throw new Error('Safety search candidate capacity exceeded');add(line.slice(0,split.index)); + if(count++>=256)throw new Error('Safety search candidate capacity exceeded');const path=line.slice(0,split.index);contentPaths.add(path);add(path); } if(count!==1)unknown=true; } @@ -215,31 +215,51 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ // `safetyResultInput` (packages/ui-backend-pi/src/worker-protocol.ts:92-99) // joins the shipped tool's text. No JSON envelope is part of this format. - if(/^[\s]*[\[{\"]/.test(output))unknown=true; - else if(output!=='No matches.')content(output,true); + if(output!=='No matches.') { + // Suspicious/unsupported envelopes remain unknown, but never hide any + // independently parseable filename on this or a later line. + for(const line of output.split('\n')){if(/^[\s]*[\[{\"]/.test(line))unknown=true;content(line,true);} + } }else if((context?.backendId??'claude')==='claude'&&tool==='Glob'){ const checked=globOutput.safeParse(parsed); if(!checked.success)unknown=true; else {const value=checked.data;for(const path of value.filenames)add(path); - if(value.numFiles!==value.filenames.length||value.truncated||value.countIsComplete===false|| - value.totalMatches!==undefined&&value.totalMatches!==value.numFiles)unknown=true;} + if(value.numFiles!==value.filenames.length||new Set(value.filenames).size!==value.filenames.length||value.truncated||value.countIsComplete===false|| + value.totalMatches!==undefined&&value.totalMatches!==value.numFiles||value.countIsComplete===true&&value.totalMatches===undefined)unknown=true;} }else if((context?.backendId??'claude')==='claude'&&tool==='Grep'){ const checked=grepOutput.safeParse(parsed),mode=context?.outputMode; if(!checked.success||!['files_with_matches','content','count'].includes(mode??''))unknown=true; else {const value=checked.data;for(const path of value.filenames)add(path); + const lines=mode==='files_with_matches'?value.filenames.length:value.content?value.content.split('\n').length:0; + const total=mode==='content'?value.totalLines:value.totalFiles; + const limits=[value.appliedLimit??0,context?.limit??250]; + // An optional total cannot be invented from a full page. Offset pages + // omit earlier sources even if their returned page is otherwise valid. if(value.mode!==undefined&&value.mode!==mode||value.numFiles!==value.filenames.length|| + new Set(value.filenames).size!==value.filenames.length|| value.totalFiles!==undefined&&value.totalFiles!==value.numFiles|| - (value.appliedOffset??0)>0||(context?.offset??0)>0)unknown=true; + (value.appliedOffset??0)>0||(context?.offset??0)>0|| + limits.some(limit=>limit>0&&lines>=limit)&&total===undefined|| + value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines)unknown=true; + let matches=mode==='files_with_matches'?value.numFiles:lines; if(mode==='files_with_matches'){if(value.content!==undefined&&value.content!=='')unknown=true;} else if(value.content===undefined)unknown=true; else { - if(value.content) { - if(mode==='content')content(value.content,context?.lineNumbers!==false); - else for(const line of value.content.split('\n')){const split=/:([0-9]+)$/.exec(line);if(split)add(line.slice(0,split.index));else unknown=true;} + if(!value.content&&value.numFiles>0)unknown=true; + if(mode==='content'){if(value.content)content(value.content,context?.lineNumbers!==false);} + else { + matches=0; + for(const line of value.content?value.content.split('\n'):[]){ + const split=/:([1-9][0-9]*)$/.exec(line); + if(split){const path=line.slice(0,split.index);contentPaths.add(path);add(path);matches+=Number(split[1]);if(!Number.isSafeInteger(matches))unknown=true;} + else unknown=true; + } } - const lines=value.content?value.content.split('\n').length:0; - if(value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines)unknown=true; } + if(mode!=='files_with_matches'&&(value.numFiles!==contentPaths.size||value.filenames.some(path=>!contentPaths.has(path))))unknown=true; + // Only counts accounted for by the identified output can establish + // completeness; unsupported count semantics remain restrictive. + if(value.numMatches!==undefined&&value.numMatches!==matches)unknown=true; } }else unknown=true; if(unknown){if(result.length>=256)throw new Error('Safety search signal capacity exceeded');result.push({source:'legacy_unknown',detector:'tool_search_output',key:'unknown_remainder'});} @@ -250,6 +270,6 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str export function searchOutputContext(tool:string,input:unknown,backendId=tool==='grep'?'pi':'claude'):SearchOutputContext { if(tool!=='Grep')return {backendId}; const value=input&&typeof input==='object'?input as Record:{}; - const mode=value.output_mode??'files_with_matches',numbers=value['-n']??true,offset=value.offset??0; - return {backendId,outputMode:typeof mode==='string'&&['content','files_with_matches','count'].includes(mode)&&typeof numbers==='boolean'&&Number.isSafeInteger(offset)&&Number(offset)>=0?mode:'unknown',lineNumbers:numbers===true,offset:typeof offset==='number'?offset:0}; + const mode=value.output_mode===undefined?'files_with_matches':value.output_mode,numbers=value['-n']===undefined?true:value['-n'],offset=value.offset===undefined?0:value.offset,limit=value.head_limit===undefined?250:value.head_limit; + return {backendId,outputMode:typeof mode==='string'&&['content','files_with_matches','count'].includes(mode)&&typeof numbers==='boolean'&&Number.isSafeInteger(offset)&&Number(offset)>=0&&Number.isSafeInteger(limit)&&Number(limit)>=0?mode:'unknown',lineNumbers:numbers===true,offset:typeof offset==='number'?offset:0,limit:typeof limit==='number'?limit:250}; } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 32dafbc96c..e031a7e2cc 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -3,6 +3,40 @@ import {outputTaintSignals,searchOutputContext} from '../src/activity/ingestion- const glob=(filenames:string[],extra={})=>JSON.stringify({durationMs:1,numFiles:filenames.length,filenames,truncated:false,...extra}); const grep=(filenames:string[],extra={})=>JSON.stringify({numFiles:filenames.length,filenames,...extra}); for(const [name,tool,input,output,expected] of [ + ['Pi bracket filename and independent later mark','grep',{},'[voyage]/log.md:1:sirens\nnotes/voyage.md:2:echo',['user_marked','user_marked','legacy_unknown']], + ['Pi malformed line retains later mark','grep',{},'{malformed\nnotes/voyage.md:2:echo',['user_marked','legacy_unknown']], + ['Grep at page limit without total','Grep',{},grep(['notes/loom.md'],{appliedLimit:1}),['legacy_unknown']], + ['Grep known complete limit','Grep',{},grep(['notes/loom.md'],{appliedLimit:1,totalFiles:1}),[]], + ['Grep input limit without metadata','Grep',{head_limit:1},grep(['notes/loom.md']),['legacy_unknown']], + ['Grep empty count claims matches','Grep',{output_mode:'count'},grep([],{content:'',numMatches:3}),['legacy_unknown']], + ['Grep wrong sum','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:2',numMatches:3}),['legacy_unknown']], + ['Grep correct sum','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:2',numMatches:2}),[]], + ['Grep empty content claims matches','Grep',{output_mode:'content'},grep([],{content:'',numMatches:3}),['legacy_unknown']], + ['Grep empty files claims matches','Grep',{},grep([],{numMatches:3}),['legacy_unknown']], + ['Grep files have missing content','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:''}),['legacy_unknown']], + ['Grep files have missing counts','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:''}),['legacy_unknown']], + ['Grep duplicate filenames','Grep',{},grep(['notes/loom.md','notes/loom.md']),['legacy_unknown']], + ['Glob duplicate filenames','Glob',{},glob(['notes/loom.md','notes/loom.md']),['legacy_unknown']], + ['Glob missing completed count','Glob',{},glob([],{countIsComplete:true}),['legacy_unknown']], + ['Glob bad duration','Glob',{},glob([],{durationMs:-1}),['legacy_unknown']], + ['Grep invalid optional number','Grep',{},grep([],{numMatches:-1}),['legacy_unknown']], + ['Grep unexpected key','Grep',{},grep([],{unexpected:true}),['legacy_unknown']], + ['Grep hidden line count in files','Grep',{},grep([],{numLines:3}),['legacy_unknown']], + ['Grep hidden total lines in files','Grep',{},grep([],{totalLines:3}),['legacy_unknown']], + ['Grep content at limit without total','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',appliedLimit:1}),['legacy_unknown']], + ['Grep count at limit without total','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:2',appliedLimit:1}),['legacy_unknown']], + ['Grep zero count entry','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:0',numMatches:0}),['legacy_unknown']], + ['Grep wrong reported offset','Grep',{offset:1},grep([],{appliedOffset:0}),['legacy_unknown']], + ['Grep unbounded limit','Grep',{head_limit:0},grep(['notes/loom.md'],{appliedLimit:0}),[]], + ['Grep zero reported files with identified content','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens'}),['legacy_unknown']], + ['Grep count mismatched filenames','Grep',{output_mode:'count'},grep(['notes/other.md'],{content:'notes/loom.md:1',numMatches:1}),['legacy_unknown']], + ['Grep reported unlimited cannot hide input limit','Grep',{head_limit:1},grep(['notes/loom.md'],{appliedLimit:0}),['legacy_unknown']], + ['Grep content count contradicts lines','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens',numMatches:2}),['legacy_unknown']], + ['Grep filename count contradicts matches','Grep',{},grep(['notes/loom.md'],{numMatches:0}),['legacy_unknown']], + ['Grep null output selector','Grep',{output_mode:null},grep([]),['legacy_unknown']], + ['Grep null line selector','Grep',{'-n':null},grep([]),['legacy_unknown']], + ['Grep null limit selector','Grep',{head_limit:null},grep([]),['legacy_unknown']], + ['Grep null offset selector','Grep',{offset:null},grep([]),['legacy_unknown']], ['overlapping numeric delimiters','grep',{},'notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], ['Glob text block rejected','Glob',{},JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['legacy_unknown']], ['plain clipped Glob rejected','Glob',{},'notes/voy...',['legacy_unknown']], @@ -24,8 +58,8 @@ for(const [name,tool,input,output,expected] of [ ['Grep wrong mode','Grep',{},grep([],{mode:'content'}),['legacy_unknown']], ['Grep omitted lines','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',numLines:1,totalLines:2}),['legacy_unknown']], ['Grep offset','Grep',{offset:1},grep([]),['legacy_unknown']], - ['Grep count colon filename','Grep',{output_mode:'count'},grep([],{content:'notes/voyage:2:7'}),['user_marked']], - ['Grep numbered content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked']], + ['Grep count colon filename','Grep',{output_mode:'count'},grep(['notes/voyage:2'],{content:'notes/voyage:2:7'}),['user_marked']], + ['Grep numbered content','Grep',{output_mode:'content'},grep(['notes/voyage.md'],{content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked']], ['Grep ambiguous content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage:2:7:sirens',numLines:1}),['user_marked','legacy_unknown']], ['Pi exact sentinel','grep',{},'No matches.',[]], ['Pi transport sentinel','grep',{},JSON.stringify([{type:'text',text:'No matches.'}]),['legacy_unknown']], @@ -34,7 +68,7 @@ for(const [name,tool,input,output,expected] of [ ['Pi malformed JSON','grep',{},'{"matches":',['legacy_unknown']], ['Pi quoted sentinel','grep',{},JSON.stringify('No matches.'),['legacy_unknown']], ] as const)test(`recognized search shape: ${name}`,()=>{ - const marked=(path:string)=>['notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); + const marked=(path:string)=>['[voyage]/log.md','notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); const signals=outputTaintSignals(tool,output,'/srv/odysseus/brain',marked,searchOutputContext(tool,input)); expect(signals.map(s=>s.source),'ONLY_RECOGNIZED_COMPLETE_SHAPES_CAN_REMAIN_HEALTHY').toEqual([...expected]); }); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index b93cef8c06..2c3394bc24 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -582,7 +582,7 @@ for(const [name,tool,output,expected] of [ for(const [name,backend,tool,mode,output,expected] of [ ['Claude filename mode','claude','Grep','files_with_matches',JSON.stringify({numFiles:1,filenames:['notes/voyage:2:home.md']}),['user_marked']], - ['Claude count mode','claude','Grep','count',JSON.stringify({numFiles:0,filenames:[],content:'notes/voyage:2:7'}),['user_marked']], + ['Claude count mode','claude','Grep','count',JSON.stringify({numFiles:1,filenames:['notes/voyage:2'],content:'notes/voyage:2:7'}),['user_marked']], ['invalid Claude mode','claude','Grep','unsupported','notes/voyage:2:7:sirens',['legacy_unknown']], ['Pi sentinel cannot cross backend','claude','grep','content','No matches.',['legacy_unknown']], ] as const)test(`search parser identity: ${name}`,async()=>{ diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 2929cc38d5..4db93a9e8a 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -494,3 +494,20 @@ test('real Pi grep empty output stays empty when the collector records its resul expect(f.chat().restriction).toBe('normal'); }finally{await f.close();} }); + +test('real Pi grep bracket paths retain every independently marked source',async()=>{ + const f=await voyage();try{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + mkdirSync(join(f.brain,'[voyage]')); + for(const name of ['log.md','raft.md']){ + const path=`[voyage]/${name}`;writeFileSync(join(f.brain,path),'sirens\n'); + untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + } + const input={pattern:'sirens',path:'[voyage]'}; + await f.collector.begin('bracket_search','grep',input); + const output=await searchRuns(f,'bracket_search',input); + expect(output.split('\n'),'REAL_GREP_RETURNS_BOTH_BRACKET_FILENAMES').toHaveLength(2); + await f.collector.result('bracket_search','grep',output,true); + expect(f.db.query("SELECT COUNT(*) n FROM safety_records WHERE kind='occurrence' AND source='user_marked'").get(),'REAL_BRACKET_PATHS_RETAIN_BOTH_MARKS').toEqual({n:2}); + }finally{await f.close();} +}); From 8a22ec1bd03995999c927cd276fb82e11a625283 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:02:38 +0000 Subject: [PATCH 05/23] fix: preserve independent signals from partially malformed results --- .../ui-server/src/activity/ingestion-taint.ts | 25 ++++++++++++------- .../tests/ingestion-taint-schema.test.ts | 14 +++++++++-- .../tests/safety-result-exits.test.ts | 25 +++++++++++++------ 3 files changed, 46 insertions(+), 18 deletions(-) diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 3bde8f1228..0c307a51c9 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -211,24 +211,31 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(count!==1)unknown=true; } }; + // Validation decides completeness, never whether an independently typed + // filename survives a malformed sibling or unrelated metadata field. + const salvage=(value:unknown,mode?:string)=>{ + if(!value||typeof value!=='object'||Array.isArray(value))return; + const fields=value as Record; + if(Array.isArray(fields.filenames))for(const path of fields.filenames)if(typeof path==='string')add(path); + if(typeof fields.content!=='string'||!fields.content)return; + if(mode==='content')content(fields.content,context?.lineNumbers!==false); + if(mode==='count')for(const line of fields.content.split('\n')){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} + }; let parsed:unknown;try{parsed=JSON.parse(output);}catch{/* Pi returns raw text; Claude requires its structured schema. */} if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ // `safetyResultInput` (packages/ui-backend-pi/src/worker-protocol.ts:92-99) // joins the shipped tool's text. No JSON envelope is part of this format. - if(output!=='No matches.') { - // Suspicious/unsupported envelopes remain unknown, but never hide any - // independently parseable filename on this or a later line. - for(const line of output.split('\n')){if(/^[\s]*[\[{\"]/.test(line))unknown=true;content(line,true);} - } + if(parsed!==undefined)unknown=true; // An actual JSON value is not Pi's text-row envelope. + if(output!=='No matches.')for(const line of output.split('\n'))content(line,true); }else if((context?.backendId??'claude')==='claude'&&tool==='Glob'){ const checked=globOutput.safeParse(parsed); - if(!checked.success)unknown=true; + if(!checked.success){unknown=true;salvage(parsed);} else {const value=checked.data;for(const path of value.filenames)add(path); - if(value.numFiles!==value.filenames.length||new Set(value.filenames).size!==value.filenames.length||value.truncated||value.countIsComplete===false|| + if(value.numFiles>100||value.numFiles!==value.filenames.length||new Set(value.filenames).size!==value.filenames.length||value.truncated||value.countIsComplete===false|| value.totalMatches!==undefined&&value.totalMatches!==value.numFiles||value.countIsComplete===true&&value.totalMatches===undefined)unknown=true;} }else if((context?.backendId??'claude')==='claude'&&tool==='Grep'){ const checked=grepOutput.safeParse(parsed),mode=context?.outputMode; - if(!checked.success||!['files_with_matches','content','count'].includes(mode??''))unknown=true; + if(!checked.success||!['files_with_matches','content','count'].includes(mode??'')){unknown=true;salvage(parsed,mode);} else {const value=checked.data;for(const path of value.filenames)add(path); const lines=mode==='files_with_matches'?value.filenames.length:value.content?value.content.split('\n').length:0; const total=mode==='content'?value.totalLines:value.totalFiles; @@ -239,7 +246,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str new Set(value.filenames).size!==value.filenames.length|| value.totalFiles!==undefined&&value.totalFiles!==value.numFiles|| (value.appliedOffset??0)>0||(context?.offset??0)>0|| - limits.some(limit=>limit>0&&lines>=limit)&&total===undefined|| + limits.some(limit=>limit>0&&(lines>limit||lines===limit&&total===undefined))|| value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines)unknown=true; let matches=mode==='files_with_matches'?value.numFiles:lines; if(mode==='files_with_matches'){if(value.content!==undefined&&value.content!=='')unknown=true;} diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index e031a7e2cc..180c169f1f 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -3,7 +3,7 @@ import {outputTaintSignals,searchOutputContext} from '../src/activity/ingestion- const glob=(filenames:string[],extra={})=>JSON.stringify({durationMs:1,numFiles:filenames.length,filenames,truncated:false,...extra}); const grep=(filenames:string[],extra={})=>JSON.stringify({numFiles:filenames.length,filenames,...extra}); for(const [name,tool,input,output,expected] of [ - ['Pi bracket filename and independent later mark','grep',{},'[voyage]/log.md:1:sirens\nnotes/voyage.md:2:echo',['user_marked','user_marked','legacy_unknown']], + ['Pi bracket filename and independent later mark','grep',{},'[voyage]/log.md:1:sirens\nnotes/voyage.md:2:echo',['user_marked','user_marked']], ['Pi malformed line retains later mark','grep',{},'{malformed\nnotes/voyage.md:2:echo',['user_marked','legacy_unknown']], ['Grep at page limit without total','Grep',{},grep(['notes/loom.md'],{appliedLimit:1}),['legacy_unknown']], ['Grep known complete limit','Grep',{},grep(['notes/loom.md'],{appliedLimit:1,totalFiles:1}),[]], @@ -37,6 +37,16 @@ for(const [name,tool,input,output,expected] of [ ['Grep null line selector','Grep',{'-n':null},grep([]),['legacy_unknown']], ['Grep null limit selector','Grep',{head_limit:null},grep([]),['legacy_unknown']], ['Grep null offset selector','Grep',{offset:null},grep([]),['legacy_unknown']], + ['Glob mixed filename types','Glob',{},JSON.stringify({durationMs:1,numFiles:2,filenames:['notes/voyage.md',false],truncated:false}),['user_marked','legacy_unknown']], + ['Grep mixed filename types','Grep',{},JSON.stringify({numFiles:2,filenames:['notes/voyage.md',false]}),['user_marked','legacy_unknown']], + ['Glob bad metadata retains filename','Glob',{},glob(['notes/voyage.md'],{durationMs:-1}),['user_marked','legacy_unknown']], + ['Grep bad metadata retains content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage.md:1:sirens',numLines:-1}),['user_marked','legacy_unknown']], + ['Grep bad metadata retains count','Grep',{output_mode:'count'},grep([],{content:'notes/voyage.md:2',numMatches:-1}),['user_marked','legacy_unknown']], + ['Grep exceeds page limit','Grep',{head_limit:1},grep(['notes/loom.md','notes/raft.md'],{appliedLimit:1,totalFiles:2}),['legacy_unknown']], + ['Grep content exceeds page limit','Grep',{head_limit:1,output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens\nnotes/loom.md:2:echo',appliedLimit:1,totalFiles:1,totalLines:2}),['legacy_unknown']], + ['Grep count exceeds page limit','Grep',{head_limit:1,output_mode:'count'},grep(['notes/loom.md','notes/raft.md'],{content:'notes/loom.md:1\nnotes/raft.md:2',appliedLimit:1,totalFiles:2,totalLines:2}),['legacy_unknown']], + ['Pi healthy bracket path','grep',{},'[raft]/log.md:1:sirens',[]], + ['Glob exceeds installed file cap','Glob',{},glob(Array.from({length:101},(_,i)=>`notes/loom-${i}.md`)),['legacy_unknown']], ['overlapping numeric delimiters','grep',{},'notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], ['Glob text block rejected','Glob',{},JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['legacy_unknown']], ['plain clipped Glob rejected','Glob',{},'notes/voy...',['legacy_unknown']], @@ -54,7 +64,7 @@ for(const [name,tool,input,output,expected] of [ ['Glob clipped filename','Glob',{},glob(['notes/voy...']),['legacy_unknown']], ['Glob unknown key','Glob',{},glob([],{unexpected:true}),['legacy_unknown']], ['Glob invalid count','Glob',{},glob(['notes/loom.md'],{numFiles:0}),['legacy_unknown']], - ['Glob missing fields','Glob',{},JSON.stringify({filenames:['notes/voyage.md']}),['legacy_unknown']], + ['Glob missing fields','Glob',{},JSON.stringify({filenames:['notes/voyage.md']}),['user_marked','legacy_unknown']], ['Grep wrong mode','Grep',{},grep([],{mode:'content'}),['legacy_unknown']], ['Grep omitted lines','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',numLines:1,totalLines:2}),['legacy_unknown']], ['Grep offset','Grep',{offset:1},grep([]),['legacy_unknown']], diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 4db93a9e8a..3bf635fa9e 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -495,19 +495,30 @@ test('real Pi grep empty output stays empty when the collector records its resul }finally{await f.close();} }); -test('real Pi grep bracket paths retain every independently marked source',async()=>{ +for(const marked of [false,true])test(`real Pi grep bracket paths retain exactly ${marked?'both marked sources':'healthy coverage'}`,async()=>{ const f=await voyage();try{ - const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + const {untrustedMarkOperations,isMarkedUntrusted}=await import('../src/files/untrusted-marks'); + const {outputTaintSignals,searchOutputContext}=await import('../src/activity/ingestion-taint'); mkdirSync(join(f.brain,'[voyage]')); - for(const name of ['log.md','raft.md']){ - const path=`[voyage]/${name}`;writeFileSync(join(f.brain,path),'sirens\n'); - untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + const paths=['[voyage]/log.md','[voyage]/raft.md']; + for(const path of paths){ + writeFileSync(join(f.brain,path),'sirens\n'); + if(marked)untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); } const input={pattern:'sirens',path:'[voyage]'}; await f.collector.begin('bracket_search','grep',input); const output=await searchRuns(f,'bracket_search',input); - expect(output.split('\n'),'REAL_GREP_RETURNS_BOTH_BRACKET_FILENAMES').toHaveLength(2); + expect(output.split('\n').sort(),'REAL_GREP_RETURNS_BOTH_BRACKET_FILENAMES').toEqual(paths.map(path=>`${path}:1:sirens`)); + const signals=outputTaintSignals('grep',output,f.brain,path=>isMarkedUntrusted(f.db,path),searchOutputContext('grep',input)); + expect(signals.sort((a,b)=>a.key.localeCompare(b.key)),'REAL_BRACKET_OUTPUT_HAS_EXACT_PATH_SIGNALS').toEqual(marked?paths.map(key=>({source:'user_marked',detector:'explicit_untrusted_input',key})):[]); await f.collector.result('bracket_search','grep',output,true); - expect(f.db.query("SELECT COUNT(*) n FROM safety_records WHERE kind='occurrence' AND source='user_marked'").get(),'REAL_BRACKET_PATHS_RETAIN_BOTH_MARKS').toEqual({n:2}); + // The ledger intentionally retains no raw filename. Assert its exact + // occurrence/exposure inventory as well as the detector's actual paths. + expect(f.db.query("SELECT kind,source,detector FROM safety_records ORDER BY kind,length(sequence),sequence").all(),'REAL_BRACKET_LEDGER_HAS_NO_EXTRA_UNKNOWN').toEqual(marked?[ + {kind:'exposure',source:null,detector:null},{kind:'exposure',source:null,detector:null}, + {kind:'occurrence',source:'user_marked',detector:'explicit_untrusted_input'}, + {kind:'occurrence',source:'user_marked',detector:'explicit_untrusted_input'} + ]:[]); + expect(f.chat().restriction).toBe(marked?'restricted':'normal'); }finally{await f.close();} }); From accf202cf39c871f9ad4697d1df3eb2df761f546 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:14:53 +0000 Subject: [PATCH 06/23] fix: qualify original search results and prove backend forwarding --- .changeset/session-safety-input-evidence.md | 1 + packages/ui-backend-pi/src/worker-protocol.ts | 6 ++ .../ui-server/src/activity/ingestion-taint.ts | 4 +- .../tests/ingestion-taint-schema.test.ts | 11 +++- .../tests/safety-result-exits.test.ts | 60 +++++++++++++++---- .../tests/safety-result-retention.test.ts | 32 +++++++--- 6 files changed, 93 insertions(+), 21 deletions(-) diff --git a/.changeset/session-safety-input-evidence.md b/.changeset/session-safety-input-evidence.md index f93d01d685..3945256e08 100644 --- a/.changeset/session-safety-input-evidence.md +++ b/.changeset/session-safety-input-evidence.md @@ -1,5 +1,6 @@ --- "@schlessera/brain-ui-server": patch +"@schlessera/brain-backend-pi": patch --- Retain unknown delivery when concurrent tool calls reuse one ID. Preserve exact structured search filenames containing colons, and recognize the shipped Pi grep empty-result format without creating a spurious safety trigger. diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 21825ff1e1..5eef524735 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -91,6 +91,12 @@ 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[] } { const segments = content.filter(part => part.type === "text").map(part => part.text as string); + // The shipped grep returns exactly one text block. Preserve every text + // row, but add an unparseable empty row when the original result is not + // that complete shape. This host-only observation never changes provider + // content, and mixed/non-text output cannot impersonate the empty sentinel. + if(tool==="grep"&&(!complete||content.length!==1||content[0]?.type!=="text"||typeof content[0]?.text!=="string")) + return {output:segments.join("\n")+"\n",segments}; // 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"))) diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 0c307a51c9..4b52bc44e6 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -191,7 +191,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(Buffer.byteLength(output)>1048576)throw new Error('Safety search output capacity exceeded'); const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=false; const add=(path:string)=>{ - if(!path||/[\r\n\0]/.test(path)){unknown=true;return;} + if(!path||path.includes('\0')){unknown=true;return;} if(/truncat|omitted|\.\.\.|…/i.test(path))unknown=true; for(const signal of fileSignals(path,brainPath,marked,'tool_search_output')){ const key=JSON.stringify([signal.detector,signal.key]);if(seen.has(key))continue; @@ -258,7 +258,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str matches=0; for(const line of value.content?value.content.split('\n'):[]){ const split=/:([1-9][0-9]*)$/.exec(line); - if(split){const path=line.slice(0,split.index);contentPaths.add(path);add(path);matches+=Number(split[1]);if(!Number.isSafeInteger(matches))unknown=true;} + if(split){const path=line.slice(0,split.index);if(contentPaths.has(path))unknown=true;contentPaths.add(path);add(path);matches+=Number(split[1]);if(!Number.isSafeInteger(matches))unknown=true;} else unknown=true; } } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 180c169f1f..49af6179af 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -1,4 +1,5 @@ import {expect,test} from 'bun:test'; +import {safetyResultInput} from '../../ui-backend-pi/src/worker-protocol'; import {outputTaintSignals,searchOutputContext} from '../src/activity/ingestion-taint'; const glob=(filenames:string[],extra={})=>JSON.stringify({durationMs:1,numFiles:filenames.length,filenames,truncated:false,...extra}); const grep=(filenames:string[],extra={})=>JSON.stringify({numFiles:filenames.length,filenames,...extra}); @@ -47,6 +48,14 @@ for(const [name,tool,input,output,expected] of [ ['Grep count exceeds page limit','Grep',{head_limit:1,output_mode:'count'},grep(['notes/loom.md','notes/raft.md'],{content:'notes/loom.md:1\nnotes/raft.md:2',appliedLimit:1,totalFiles:2,totalLines:2}),['legacy_unknown']], ['Pi healthy bracket path','grep',{},'[raft]/log.md:1:sirens',[]], ['Glob exceeds installed file cap','Glob',{},glob(Array.from({length:101},(_,i)=>`notes/loom-${i}.md`)),['legacy_unknown']], + ['Glob legal CR LF filename','Glob',{},glob(['workspaces/voyage/log\r\n.md']),['workspace_read','user_marked']], + ['Grep legal CR LF filename','Grep',{},grep(['workspaces/voyage/log\r\n.md']),['workspace_read','user_marked']], + ['Pi sentinel plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'image'}]).output,['legacy_unknown']], + ['Pi sentinel incomplete original','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],false).output,['legacy_unknown']], + ['Pi marked row plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/voyage.md:1:sirens'},{type:'image'}]).output,['user_marked','legacy_unknown']], + ['Pi sentinel plus empty block','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'text',text:''}]).output,['legacy_unknown']], + ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}]).output,[]], + ['Grep duplicate per-file count rows','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:1\nnotes/loom.md:1',numMatches:2}),['legacy_unknown']], ['overlapping numeric delimiters','grep',{},'notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], ['Glob text block rejected','Glob',{},JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['legacy_unknown']], ['plain clipped Glob rejected','Glob',{},'notes/voy...',['legacy_unknown']], @@ -78,7 +87,7 @@ for(const [name,tool,input,output,expected] of [ ['Pi malformed JSON','grep',{},'{"matches":',['legacy_unknown']], ['Pi quoted sentinel','grep',{},JSON.stringify('No matches.'),['legacy_unknown']], ] as const)test(`recognized search shape: ${name}`,()=>{ - const marked=(path:string)=>['[voyage]/log.md','notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); + const marked=(path:string)=>['workspaces/voyage/log\r\n.md','[voyage]/log.md','notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); const signals=outputTaintSignals(tool,output,'/srv/odysseus/brain',marked,searchOutputContext(tool,input)); expect(signals.map(s=>s.source),'ONLY_RECOGNIZED_COMPLETE_SHAPES_CAN_REMAIN_HEALTHY').toEqual([...expected]); }); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 3bf635fa9e..99a035c80c 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -9,9 +9,10 @@ import { safetyResultInput } from "../../ui-backend-pi/src/worker-protocol"; * `safety-result-retention.test.ts`; these drive the remaining exits against * the real host ledger. Keyless and offline. */ import { afterEach, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import {createRequire} from "node:module"; import type { Agent } from "@earendil-works/pi-agent-core"; import { createEffectiveSafety } from "../src/governance/effective-safety"; import { createUiDb } from "../src/db/client"; @@ -38,19 +39,19 @@ const refusal = (work: Promise) => work.then(() => null, (error: unknow const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -async function voyage() { +async function voyage(backendId:"pi"|"claude"="pi") { const root = mkdtempSync(join(tmpdir(), "odysseus-safety-exits-")); roots.push(root); const brain = join(root, "brain"); mkdirSync(join(brain, "workspaces/voyage"), { recursive: true }); writeFileSync(join(brain, "workspaces/voyage/raft.md"), "Sail past the sirens.\n"); const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db), writes = createGovernanceWrites(db, writer); holdSafetyRecovery(db); const bindingId = crypto.randomUUID(), controller = new AbortController(); - await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: "odysseus", backendId: "pi", at: 0 }); + await writes.safetyBegin({ turnId: "voyage", bindingId, sessionId: null, principalId: "odysseus", backendId, at: 0 }); db.exec("INSERT INTO sessions(id,created_at,last_active_at) VALUES('ithaca',0,0); INSERT INTO chat_session_owners(session_id,principal_id,created_at) VALUES('ithaca','odysseus',0)"); safetyCatalogCreated(db, "ithaca", "odysseus", "voyage"); await writes.bind("voyage", "ithaca"); - const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, backendId: "pi", sessionId: () => "ithaca", brainPath: brain, + const collector = createSafetyCollector(db, writes, { turnId: "voyage", bindingId, backendId, sessionId: () => "ithaca", brainPath: brain, shellProxied: () => false, signal: controller.signal, stop: error => controller.abort(error) }); - await collector.ready("pi", 1); + await collector.ready(backendId, 1); return { db, writes, collector, controller, brain, path: join(root, "ui.db"), /** Resolves once the writer has applied every write sent before it. */ idle: () => writer.idle(), @@ -457,25 +458,51 @@ test("a Pi grant is unusable until the collector's last check passes, and a call } finally { release(); await f.close(); } }); +/** Claude's installed native search executable, with a GrepOutput result for + * the real PostToolUse binding. This exercises the shipped search engine and + * host hooks; the full installed-session proof remains in retention tests. */ +async function claudeSearchRuns(f:Voyage){ + const sdk=createRequire(createRequire(import.meta.url).resolve('@anthropic-ai/claude-agent-sdk')); + const bin=join(f.brain,'native-search');mkdirSync(bin,{recursive:true}); + const rg=join(bin,'rg');if(!existsSync(rg))symlinkSync(sdk.resolve('@anthropic-ai/claude-agent-sdk-linux-x64/claude'),rg); + const path='workspaces/voyage/raft.md'; + const child=Bun.spawn([rg,'--with-filename','-n','--no-heading','--color','never','sirens',path],{cwd:f.brain,env:{PATH:'/usr/bin:/bin'},stdout:'pipe',stderr:'pipe'}); + const [content,errors,code]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]); + expect(code,errors).toBe(0); + return {mode:'content',numFiles:1,filenames:[path],content:content.trimEnd(),numLines:1}; +} + for(const binding of ['pi','claude'] as const)test(`${binding}: two allowed searches reusing an ID cannot share one result discharge`,async()=>{ - const f=await voyage();try{ + const f=await voyage(binding);try{ const input=binding==='claude'?{pattern:'sirens',output_mode:'content'}:{pattern:'sirens'},id='reused_search'; - let admit:()=>Promise; + let admit:()=>Promise,run:()=>Promise,deliver:(output:unknown)=>Promise; if(binding==='pi'){ const turn=createTurnContext();turn.bridge={inputSafety:f.collector,emit(){},requestPermission:async()=>({behavior:'allow'})} as never;turn.signal=f.controller.signal; let handler:((event:unknown)=>Promise)|undefined; const gate=createPermissionGate({turn,allowedTools:new Set(['grep']),confirmPatterns:[]}); (typeof gate==='function'?gate:gate.factory)({on:(name:string,callback:unknown)=>{if(name==='tool_call')handler=callback as typeof handler;}} as never); admit=async()=>{const result=await handler!({toolName:'grep',toolCallId:id,input});expect(result,'PI_REUSED_ID_CALL_REACHES_EXECUTION').toBeUndefined();}; + run=()=>searchRuns(f,id,input); + const dispatch=dispatcher(f); + deliver=output=>dispatch(report(1,id,safetyResultInput('grep',[{type:'text',text:String(output)}]))); }else{ const wiring=createPermissionWiring({req:{prompt:'Listen for the sirens.',signal:f.controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:'allow'}),inputSafety:f.collector}} as never, allowedTools:['Grep'],confirmPatterns:[],brainPath:f.brain,childEnv:{PATH:'/usr/bin:/bin'},log(){},turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never}); const hook=wiring.hooks!.PreToolUse!.find(group=>!group.matcher)!.hooks[0]!; admit=async()=>{const result=await hook({hook_event_name:'PreToolUse',tool_name:'Grep',tool_input:input,tool_use_id:id} as never,id,{signal:f.controller.signal});expect((result as {hookSpecificOutput?:{permissionDecision?:string}}).hookSpecificOutput?.permissionDecision,'CLAUDE_REUSED_ID_CALL_REACHES_EXECUTION').not.toBe('deny');}; + run=()=>claudeSearchRuns(f); + const post=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!.hooks[0]!; + deliver=output=>post({hook_event_name:'PostToolUse',tool_name:'Grep',tool_input:input,tool_use_id:id,tool_response:output} as never,id,{signal:f.controller.signal}); } - await admit();const first=await searchRuns(f,id,input); - await admit();expect(await searchRuns(f,id,input),'SECOND_SAME_ID_SEARCH_ACTUALLY_EXECUTES').toContain('Sail past the sirens'); - await f.collector.result(id,binding==='pi'?'grep':'Grep',first,true); + await admit();const first=await run(); + await admit();expect(JSON.stringify(await run()),'SECOND_SAME_ID_SEARCH_ACTUALLY_EXECUTES').toContain('Sail past the sirens'); + await deliver(first); + // The durable gap alone cannot prove forwarding: without a forwarded + // result it would still be owed. Require its actual occurrence/exposure. + expect(f.db.query("SELECT kind,source,detector,state FROM safety_records ORDER BY kind").all(),'BACKEND_RESULT_MUST_REACH_LEDGER_BEFORE_THE_GAP').toEqual([ + {kind:'exposure',source:null,detector:null,state:'interrupted_unknown'}, + {kind:'occurrence',source:'workspace_read',detector:'tool_search_output',state:'open'} + ]); expect(f.owed(),'ONE_RESULT_CANNOT_DISCHARGE_TWO_LOGICAL_CALLS').toBe(1); await f.writes.safetyEnd('voyage'); expect(f.failure(),'RUNTIME_REUSED_ID_RESULT_LOSS_IS_DURABLE').toBe('recording_failed'); @@ -522,3 +549,16 @@ for(const marked of [false,true])test(`real Pi grep bracket paths retain exactly expect(f.chat().restriction).toBe(marked?'restricted':'normal'); }finally{await f.close();} }); + +for(const shape of ['exact','image','second-text','incomplete'] as const)test(`Pi worker result ${shape}: only the original exact sentinel is empty`,async()=>{ + const f=await voyage();try{ + const input={pattern:'no_cyclops_matches_here'},id='original_empty'; + await f.collector.begin(id,'grep',input); + const text=await searchRuns(f,id,input);expect(text).toBe('No matches.'); + const content=[{type:'text',text},...(shape==='image'?[{type:'image'}]:shape==='second-text'?[{type:'text',text:''}]:[])]; + const converted=safetyResultInput('grep',content,shape!=='incomplete'); + await dispatcher(f)(report(1,id,converted)); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all(),'ORIGINAL_MIXED_PI_RESULT_RETAINS_UNKNOWN').toEqual(shape==='exact'?[]:[{source:'legacy_unknown',detector:'tool_search_output'}]); + expect(f.chat().restriction).toBe(shape==='exact'?'normal':'restricted'); + }finally{await f.close();} +}); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 22dd8a410f..d4141a4110 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -46,7 +46,7 @@ function installedRipgrep(root:string):string { * same id. The Read's native-read hook, which never saw that id, waits until * the search has printed its matches, stops the turn and denies the Read; * the hook shared by both tools is held until that denial has landed. */ -type Interruption="refused"|"cancelled"|"running"|"duplicate"|"denied"|"retooled"; +type Interruption="refused"|"cancelled"|"running"|"duplicate"|"denied"|"retooled"|"same-tool"; /** One model reply carrying each call as its own tool_use block. */ function modelCalls(calls:{name:string;id:string;input:Record}[]):Response { const events:unknown[]=[{type:"message_start",message:{id:"msg_ithaca",type:"message",role:"assistant",model:"claude-probe",content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:1,output_tokens:0}}}]; @@ -62,8 +62,9 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnTyper.turn===0).length===1; const search={name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}; - if(first&&interruption==="duplicate")return modelCalls([search,search]); + if(first&&(interruption==="duplicate"||interruption==="same-tool"))return modelCalls([search,search]); if(first&&interruption==="retooled")return modelCalls([search,{name:"Read",id:search.id,input:{file_path:path}}]); return nativeModelReply(first?search:undefined); }}); @@ -141,7 +142,9 @@ esac results++; if(interruption==="refused")db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END"); else if(interruption==="cancelled")controller.abort(new Error("Odysseus stopped the turn as the result arrived")); - return record(...args); + const result=await record(...args); + if(interruption==="same-tool")controller.abort(new Error("Odysseus stopped the second search after the first result was recorded")); + return result; }]; const failureGroup=wiring.hooks!.PostToolUseFailure!.find(group=>!group.matcher)!,failed=failureGroup.hooks[0]!; failureGroup.hooks=[async(...args)=>{failures++;return failed(...args);}]; @@ -151,7 +154,7 @@ esac const timer=setTimeout(()=>controller.abort(),20000); try{for await(const message of query({prompt:"Listen for the sirens.",options:{cwd:brain,settingSources:[],model:"claude-sonnet-4-6",maxTurns:2,permissionMode:"default",allowedTools:tools,...wiring,abortController:controller, ...(resume?{resume}:{}), - env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"||interruption==="retooled"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ + env:{HOME:home,CLAUDE_CONFIG_DIR:join(home,".claude"),...(interruption==="running"||interruption==="duplicate"||interruption==="denied"||interruption==="retooled"||interruption==="same-tool"?{PATH:`${bin}:${process.env.PATH??"/usr/bin:/bin"}`,USE_BUILTIN_RIPGREP:"0"}:{PATH:process.env.PATH??"/usr/bin:/bin"}),ANTHROPIC_BASE_URL:origin.url.origin,ANTHROPIC_API_KEY:"odysseus-offline-only-key",ANTHROPIC_AUTH_TOKEN:undefined,CLAUDE_CODE_OAUTH_TOKEN:undefined,CLAUDE_CODE_USE_BEDROCK:"",CLAUDE_CODE_USE_VERTEX:"",CLAUDE_CODE_USE_FOUNDRY:"",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1"}}})){ if(message.type==="system"&&message.subtype==="init")version=message.claude_code_version; if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; }}catch{/* The interrupted turn is stopped. */} @@ -287,8 +290,9 @@ test("a denial of another tool under the search's id cannot settle the search th * hook order or with the hook both tools share starting late. */ for(const late of [false,true])test(`a denied shell call reusing a search's id cannot settle the search that ran${late?", even when the shared hook starts late":""}`,async()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retool-")),brain=join(root,"brain"),home=join(root,"home"); - mkdirSync(join(brain,"notes"),{recursive:true});mkdirSync(home); - const path=join(brain,"notes","sirens.md");writeFileSync(path,`${SONG}\n`); + const area=interruption==="same-tool"?"workspaces/voyage":"notes"; + mkdirSync(join(brain,area),{recursive:true});mkdirSync(home); + const path=join(brain,area,"sirens.md");writeFileSync(path,`${SONG}\n`); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); holdSafetyRecovery(db); const controller=new AbortController(),bindingId=crypto.randomUUID(); @@ -331,3 +335,15 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c expect(admitted,"SAFETY_HOST_REPORTS_THE_SHELL_CALL_AS_A_SECOND_ADMISSION").toBeGreaterThanOrEqual(2); }finally{clearTimeout(timer);origin.stop(true);await writer.close();db.close();rmSync(root,{recursive:true,force:true});} },60000); + + +test("two same-ID native Grep calls retain their recorded result and the interrupted call's gap",()=>voyageHome("same-tool",({db,writes,first})=>{ + expect(first.admitted,"NATIVE_SAME_TOOL_ID_HAS_TWO_LOGICAL_ADMISSIONS").toBeGreaterThanOrEqual(2); + expect(first.results,"NATIVE_SAME_TOOL_RESULT_HOOK_ACTUALLY_FORWARDS").toBeGreaterThanOrEqual(1); + expect(db.query("SELECT r.kind,r.source,r.state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' ORDER BY r.kind").all(),"NATIVE_SAME_TOOL_RESULT_REACHES_THE_LEDGER").toEqual(expect.arrayContaining([ + {kind:'exposure',source:null,state:'interrupted_unknown'}, + {kind:'occurrence',source:'workspace_read',state:'open'} + ])); + expect(writes.safety(null,"ithaca").coverage.state,"NATIVE_SAME_TOOL_RESULT_DOES_NOT_ERASE_THE_GAP").toBe('incomplete'); + expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:'recording_failed'}); +}),60000); From 87d0bf5bbd1d5862874fb4379f110bccd6c3c96f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:44:48 +0000 Subject: [PATCH 07/23] fix: preserve NUL-delimited search paths and deterministic native proof --- .changeset/session-safety-input-evidence.md | 2 +- docs/plans/reviewable-session-safety.md | 7 +++- packages/ui-backend-pi/src/file-tools.ts | 7 +++- .../ui-backend-pi/tests/exec-wrapper.test.ts | 4 +- .../tests/tool-factories.test.ts | 2 +- .../tests/worker-host-exec.test.ts | 4 +- .../ui-server/src/activity/ingestion-taint.ts | 24 ++++++++++-- .../tests/helpers/native-safety-proof.ts | 11 ++++++ .../tests/ingestion-taint-schema.test.ts | 11 ++++-- .../tests/native-safety-proof.test.ts | 18 +++++++++ .../ui-server/tests/safety-ledger.test.ts | 2 +- .../tests/safety-result-exits.test.ts | 20 +++++++++- .../tests/safety-result-retention.test.ts | 39 +++++++++++++------ 13 files changed, 121 insertions(+), 30 deletions(-) create mode 100644 packages/ui-server/tests/helpers/native-safety-proof.ts create mode 100644 packages/ui-server/tests/native-safety-proof.test.ts diff --git a/.changeset/session-safety-input-evidence.md b/.changeset/session-safety-input-evidence.md index 3945256e08..f120fb54f5 100644 --- a/.changeset/session-safety-input-evidence.md +++ b/.changeset/session-safety-input-evidence.md @@ -3,4 +3,4 @@ "@schlessera/brain-backend-pi": patch --- -Retain unknown delivery when concurrent tool calls reuse one ID. Preserve exact structured search filenames containing colons, and recognize the shipped Pi grep empty-result format without creating a spurious safety trigger. +Retain unknown delivery when concurrent tool calls reuse one ID. Preserve exact search filenames, including colons and newlines, and recognize only complete original Pi grep empty results without creating a spurious safety trigger. diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index cabf3d7ad0..60525a516a 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -33,7 +33,12 @@ public design or its fixtures. Fictional examples use the Odysseus world. `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:189`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery; display frames alone - never prove finalized delivery or complete coverage. + never prove finalized delivery or complete coverage. Pi's shipped search + preserves filename boundaries with GNU grep's NUL filename separator and a + retained visible colon. New result data can therefore name POSIX filenames + containing newlines without inventing separate paths. Older unframed text + remains restrictive. This changes tool result data, not the provider-facing + tool definition or any previously delivered provider history. - The turn proxy records each admitted non-provider connection and terminal exposure observation (`prepareTurnEgress`, `packages/ui-server/src/brain/turn-egress.ts:86-295`). Relay admissions join diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 5ba1f5a75d..25b807d798 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -60,7 +60,7 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const rel = params.path ?? "."; resolveOrThrow(rel); const exec = deps.exec ?? ambientExecConfig(); - const proc = spawn(wrapCommand(["grep", "-rInE", "--", params.pattern, rel], exec.wrapper), { + const proc = spawn(wrapCommand(["grep", "-rInZE", "--", params.pattern, rel], exec.wrapper), { cwd: brain.root, env: subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), stdout: "pipe", @@ -71,7 +71,10 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { signal?.addEventListener("abort", onAbort, { once: true }); const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); signal?.removeEventListener("abort", onAbort); - const text = out.trim(); + // Keep the visible colon layout and an unambiguous machine boundary. + // POSIX filenames may contain newlines, colons and edge whitespace. + // This changes result data only; provider tool definitions stay identical. + const text = out.replaceAll("\0", ":\0"); return textResult(text ? clip(text) : "No matches.", { pattern: params.pattern }); }, } satisfies ToolDefinition; diff --git a/packages/ui-backend-pi/tests/exec-wrapper.test.ts b/packages/ui-backend-pi/tests/exec-wrapper.test.ts index d6e05dabd0..7f055c5e21 100644 --- a/packages/ui-backend-pi/tests/exec-wrapper.test.ts +++ b/packages/ui-backend-pi/tests/exec-wrapper.test.ts @@ -157,7 +157,7 @@ describe("the grep tool", () => { expect(resultText(res)).toContain("needle"); expect(readFileSync(argvLog, "utf-8").split("\n").filter(Boolean)).toEqual([ Bun.which("grep")!, - "-rInE", + "-rInZE", "--", "needle", ".", @@ -188,7 +188,7 @@ test("host A/C and explicit empty override ambient B for both Pi spawn tools (#1 expect(existsSync(b.argvLog), "EXPLICIT_EMPTY_NOT_AMBIENT").toBe(false); } expect(readFileSync(a.argvLog, "utf8").split("\n").filter(Boolean)).toEqual([ - Bun.which("bash")!, "--noprofile", "--norc", "-c", "echo needle", Bun.which("grep")!, "-rInE", "--", "needle", ".", + Bun.which("bash")!, "--noprofile", "--norc", "-c", "echo needle", Bun.which("grep")!, "-rInZE", "--", "needle", ".", ]); expect(readFileSync(c.argvLog, "utf8")).toBe(readFileSync(a.argvLog, "utf8")); } finally { brain.cleanup(); } diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts index 5bd9b03ec1..b556688c7b 100644 --- a/packages/ui-backend-pi/tests/tool-factories.test.ts +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -73,7 +73,7 @@ test("readFileTool reads one contained file and returns its base on a routed tur test("grepTool searches the repository and names each match", async () => { const result = await run(grepTool(kit({ exec: {} })), { pattern: "Odysseus" }); - expect(resultText(result)).toBe("./notes/ithaca.md:3:Odysseus sails home."); + expect(resultText(result)).toBe("./notes/ithaca.md:\0"+"3:Odysseus sails home.\n"); expect(resultText(await run(grepTool(kit({ exec: {} })), { pattern: "Cyclops" }))).toBe("No matches."); }); diff --git a/packages/ui-backend-pi/tests/worker-host-exec.test.ts b/packages/ui-backend-pi/tests/worker-host-exec.test.ts index 340b4f403c..5db69e4b7e 100644 --- a/packages/ui-backend-pi/tests/worker-host-exec.test.ts +++ b/packages/ui-backend-pi/tests/worker-host-exec.test.ts @@ -60,10 +60,10 @@ for (const profile of ["governed", "strict", "restricted"] as const) { })).session; const report = JSON.parse(session.model!.id); expect(report.error, "HOST_HELPER_VISIBLE_IN_WORKER").toBeUndefined(); - expect(report.grep).toContain("voyage.md:1:The wine-dark sea"); + expect(report.grep).toContain("voyage.md:\0"+"1:The wine-dark sea"); expect(report.bash).toBe("Ithaca"); const wrapped = report.wrapperLog.split("\n"); - expect(wrapped, "WORKER_TOOLS_USED_HOST_WRAPPER").toEqual(expect.arrayContaining(["-rInE", "wine-dark", "--noprofile", "--norc", "-c", "echo Ithaca", "sleep 30"])); + expect(wrapped, "WORKER_TOOLS_USED_HOST_WRAPPER").toEqual(expect.arrayContaining(["-rInZE", "wine-dark", "--noprofile", "--norc", "-c", "echo Ithaca", "sleep 30"])); expect(report.cancel).toBe("AbortError"); expect(report.killerLog, "WORKER_KILLER_CANCELLED_GROUP").toMatch(/^\d+ TERM\n$/); expect(report.cancelMs).toBeLessThan(10_000); diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 4b52bc44e6..bae2bfd193 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -177,7 +177,7 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number } // Installed SDK: GlobInput/GrepInput and GlobOutput/GrepOutput in // @anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:905-983,3506-3545. Pi's shipped grep and text -// envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:52-91) +// envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:44-82) // and `textResult` (packages/ui-backend-pi/src/tool-kit.ts:25-27). const natural = z.number().int().nonnegative().safe(); const globOutput = z.object({ durationMs: z.number().finite().nonnegative(), numFiles: natural, @@ -225,8 +225,26 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ // `safetyResultInput` (packages/ui-backend-pi/src/worker-protocol.ts:92-99) // joins the shipped tool's text. No JSON envelope is part of this format. - if(parsed!==undefined)unknown=true; // An actual JSON value is not Pi's text-row envelope. - if(output!=='No matches.')for(const line of output.split('\n'))content(line,true); + if(output!=='No matches.'){ + if(!output.includes('\0')){ + // Retained text from older runtimes cannot prove filename boundaries: + // even several valid-looking rows can be one newline-bearing path. + unknown=true;for(const line of output.split('\n'))content(line,true); + }else{ + let offset=0; + while(offsetJSON.stringify({durationMs:1,numFiles:filenames.length,filenames,truncated:false,...extra}); const grep=(filenames:string[],extra={})=>JSON.stringify({numFiles:filenames.length,filenames,...extra}); for(const [name,tool,input,output,expected] of [ - ['Pi bracket filename and independent later mark','grep',{},'[voyage]/log.md:1:sirens\nnotes/voyage.md:2:echo',['user_marked','user_marked']], + ['Pi bracket filename and independent later mark','grep',{},'[voyage]/log.md:\0'+'1:sirens\nnotes/voyage.md:\0'+'2:echo\n',['user_marked','user_marked']], ['Pi malformed line retains later mark','grep',{},'{malformed\nnotes/voyage.md:2:echo',['user_marked','legacy_unknown']], ['Grep at page limit without total','Grep',{},grep(['notes/loom.md'],{appliedLimit:1}),['legacy_unknown']], ['Grep known complete limit','Grep',{},grep(['notes/loom.md'],{appliedLimit:1,totalFiles:1}),[]], @@ -46,7 +46,7 @@ for(const [name,tool,input,output,expected] of [ ['Grep exceeds page limit','Grep',{head_limit:1},grep(['notes/loom.md','notes/raft.md'],{appliedLimit:1,totalFiles:2}),['legacy_unknown']], ['Grep content exceeds page limit','Grep',{head_limit:1,output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens\nnotes/loom.md:2:echo',appliedLimit:1,totalFiles:1,totalLines:2}),['legacy_unknown']], ['Grep count exceeds page limit','Grep',{head_limit:1,output_mode:'count'},grep(['notes/loom.md','notes/raft.md'],{content:'notes/loom.md:1\nnotes/raft.md:2',appliedLimit:1,totalFiles:2,totalLines:2}),['legacy_unknown']], - ['Pi healthy bracket path','grep',{},'[raft]/log.md:1:sirens',[]], + ['Pi healthy bracket path','grep',{},'[raft]/log.md:\0'+'1:sirens\n',[]], ['Glob exceeds installed file cap','Glob',{},glob(Array.from({length:101},(_,i)=>`notes/loom-${i}.md`)),['legacy_unknown']], ['Glob legal CR LF filename','Glob',{},glob(['workspaces/voyage/log\r\n.md']),['workspace_read','user_marked']], ['Grep legal CR LF filename','Grep',{},grep(['workspaces/voyage/log\r\n.md']),['workspace_read','user_marked']], @@ -56,6 +56,11 @@ for(const [name,tool,input,output,expected] of [ ['Pi sentinel plus empty block','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'text',text:''}]).output,['legacy_unknown']], ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}]).output,[]], ['Grep duplicate per-file count rows','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:1\nnotes/loom.md:1',numMatches:2}),['legacy_unknown']], + ['Pi newline filename ambiguity is never healthy legacy evidence','grep',{},'./raft:1:sail\nloom.md:1:sirens',['legacy_unknown']], + ['Pi NUL newline filename','grep',{},'./raft:1:sail\nloom.md:\0'+'1:sirens\n',['user_marked']], + ['Pi NUL whitespace filename','grep',{},' notes/loom.md :\0'+'1:sirens\n',[]], + ['Pi NUL malformed line number retains path','grep',{},'notes/voyage.md:\0'+'zero:sirens\n',['user_marked','legacy_unknown']], + ['Pi NUL clipped next path retains first mark','grep',{},'notes/voyage.md:\0'+'1:sirens\nnotes/loo...',['user_marked','legacy_unknown']], ['overlapping numeric delimiters','grep',{},'notes/voyage:2:7:sirens',['user_marked','legacy_unknown']], ['Glob text block rejected','Glob',{},JSON.stringify([{type:'text',text:'notes/voyage:2:home.md'}]),['legacy_unknown']], ['plain clipped Glob rejected','Glob',{},'notes/voy...',['legacy_unknown']], @@ -87,7 +92,7 @@ for(const [name,tool,input,output,expected] of [ ['Pi malformed JSON','grep',{},'{"matches":',['legacy_unknown']], ['Pi quoted sentinel','grep',{},JSON.stringify('No matches.'),['legacy_unknown']], ] as const)test(`recognized search shape: ${name}`,()=>{ - const marked=(path:string)=>['workspaces/voyage/log\r\n.md','[voyage]/log.md','notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); + const marked=(path:string)=>['raft:1:sail\nloom.md','workspaces/voyage/log\r\n.md','[voyage]/log.md','notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); const signals=outputTaintSignals(tool,output,'/srv/odysseus/brain',marked,searchOutputContext(tool,input)); expect(signals.map(s=>s.source),'ONLY_RECOGNIZED_COMPLETE_SHAPES_CAN_REMAIN_HEALTHY').toEqual([...expected]); }); diff --git a/packages/ui-server/tests/native-safety-proof.test.ts b/packages/ui-server/tests/native-safety-proof.test.ts new file mode 100644 index 0000000000..cf9e9816b4 --- /dev/null +++ b/packages/ui-server/tests/native-safety-proof.test.ts @@ -0,0 +1,18 @@ +/** No installed runtime is launched: validate the native proof's oracle. */ +import {expect,test} from 'bun:test'; +import {assertNativeSameToolProof} from './helpers/native-safety-proof'; +const first={admitted:2,results:1,nativeSecondHeld:true}; +const exposure={kind:'exposure',detector:null,state:'interrupted_unknown'}; +const output={kind:'occurrence',detector:'tool_search_output',state:'open'}; +test('native oracle accepts one delivered output and a held second search',()=>{ + expect(()=>assertNativeSameToolProof(first,[exposure,output])).not.toThrow(); +}); +test('native oracle rejects an input-only occurrence despite its interrupted exposure',()=>{ + expect(()=>assertNativeSameToolProof(first,[exposure,{kind:'occurrence',detector:'tool_file_input',state:'open'}])).toThrow('NATIVE_SAME_TOOL_OUTPUT_DETECTOR'); +}); +test('native oracle rejects two delivered results',()=>{ + expect(()=>assertNativeSameToolProof({...first,results:2},[exposure,output])).toThrow('NATIVE_EXACTLY_ONE_RESULT'); +}); +test('native oracle rejects an unheld second search',()=>{ + expect(()=>assertNativeSameToolProof({...first,nativeSecondHeld:false},[exposure,output])).toThrow('NATIVE_SECOND_SEARCH_OUTPUT_IS_HELD'); +}); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 2c3394bc24..779516149f 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -566,7 +566,7 @@ for(const [name,tool,output,expected] of [ ['wrapped mixed Pi match and empty sentinel','grep',JSON.stringify([{type:'text',text:'notes/voyage.md:1: sirens\nNo matches.'}]),['legacy_unknown']], ['structured numeric colon','Glob',JSON.stringify({durationMs:1,numFiles:1,filenames:['notes/voyage:2:home.md'],truncated:false}),['user_marked']], ['structured spaced colon','Glob',JSON.stringify({durationMs:1,numFiles:1,filenames:['notes/voyage home:map.md'],truncated:false}),['user_marked']], - ['plain colon grep','grep','notes/voyage:home.md:7: Odysseus',['user_marked']], + ['plain colon grep','grep','notes/voyage:home.md:7: Odysseus',['user_marked','legacy_unknown']], ['ambiguous numeric colon','grep','notes/voyage:2:home.md:7: Odysseus',['user_marked','legacy_unknown']], ['malformed structured path','Glob',JSON.stringify({filenames:[123]}),['legacy_unknown']], ['unsupported empty wording','Grep','No matches.',['legacy_unknown']], diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 99a035c80c..117e0abdec 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -30,7 +30,7 @@ import { createPermissionWiring } from "../../ui-backend-claude/src/permission-h import { holdSafetyRecovery } from "./helpers/hold-safety-recovery"; /** A search that names a workspace note: only its result's record carries the taint. */ -const SEARCH = "workspaces/voyage/raft.md:1: Sail past the sirens."; +const SEARCH = "workspaces/voyage/raft.md:\0"+"1: Sail past the sirens.\n"; /** Settles `work` on the normal event loop: a pending `expect().rejects` waits * synchronously and never sees the write worker's reply. */ @@ -535,7 +535,7 @@ for(const marked of [false,true])test(`real Pi grep bracket paths retain exactly const input={pattern:'sirens',path:'[voyage]'}; await f.collector.begin('bracket_search','grep',input); const output=await searchRuns(f,'bracket_search',input); - expect(output.split('\n').sort(),'REAL_GREP_RETURNS_BOTH_BRACKET_FILENAMES').toEqual(paths.map(path=>`${path}:1:sirens`)); + expect(output.split('\n').filter(Boolean).sort(),'REAL_GREP_RETURNS_BOTH_BRACKET_FILENAMES').toEqual(paths.map(path=>`${path}:\0`+"1:sirens")); const signals=outputTaintSignals('grep',output,f.brain,path=>isMarkedUntrusted(f.db,path),searchOutputContext('grep',input)); expect(signals.sort((a,b)=>a.key.localeCompare(b.key)),'REAL_BRACKET_OUTPUT_HAS_EXACT_PATH_SIGNALS').toEqual(marked?paths.map(key=>({source:'user_marked',detector:'explicit_untrusted_input',key})):[]); await f.collector.result('bracket_search','grep',output,true); @@ -562,3 +562,19 @@ for(const shape of ['exact','image','second-text','incomplete'] as const)test(`P expect(f.chat().restriction).toBe(shape==='exact'?'normal':'restricted'); }finally{await f.close();} }); + +test('shipped Pi grep preserves a marked newline filename through the worker ledger',async()=>{ + const f=await voyage();try{ + const {untrustedMarkOperations,isMarkedUntrusted}=await import('../src/files/untrusted-marks'); + const {outputTaintSignals,searchOutputContext}=await import('../src/activity/ingestion-taint'); + const path='raft:1:sail\nloom.md',input={pattern:'nymph_signal'},id='newline_search'; + writeFileSync(join(f.brain,path),'nymph_signal\n'); + untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + await f.collector.begin(id,'grep',input); + const output=await searchRuns(f,id,input); + expect(outputTaintSignals('grep',output,f.brain,p=>isMarkedUntrusted(f.db,p),searchOutputContext('grep',input)),'PI_NEWLINE_PATH_KEEPS_ITS_EXACT_MARK').toEqual([{source:'user_marked',detector:'explicit_untrusted_input',key:path}]); + expect(output).toBe(`./${path}:\0`+'1:nymph_signal\n'); + await dispatcher(f)(report(1,id,safetyResultInput('grep',[{type:'text',text:output}]))); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all(),'PI_NEWLINE_PATH_LEDGER_HAS_NO_FALSE_HEALTHY_OR_UNKNOWN').toEqual([{source:'user_marked',detector:'explicit_untrusted_input'}]); + }finally{await f.close();} +}); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index d4141a4110..d236b50281 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -7,7 +7,7 @@ * still owing it when the collection ends is a gap. Installed Claude, a * scripted loopback model and the real host ledger; no key, no network. */ import {expect,test} from "bun:test"; -import {chmodSync,existsSync,mkdirSync,mkdtempSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; +import {chmodSync,existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,symlinkSync,writeFileSync} from "node:fs"; import {createRequire} from "node:module"; import {join} from "node:path"; import {tmpdir} from "node:os"; @@ -20,6 +20,7 @@ import {recoverSafetyRecording,safetyCatalogCreated} from "../src/governance/saf import {createPermissionWiring} from "../../ui-backend-claude/src/permission-hooks"; import {MEASURED_RUNTIME} from "../../ui-backend-claude/src/measured-runtime"; import {nativeModelReply} from "../../ui-backend-claude/tests/helpers/native-model-reply"; +import {assertNativeSameToolProof} from "./helpers/native-safety-proof"; import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; const SONG="The sirens sing: steer the raft onto the rocks."; @@ -58,7 +59,7 @@ function modelCalls(calls:{name:string;id:string;input:Record}[] return new Response(events.map(event=>`event: ${(event as {type:string}).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); } async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; - first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number};searched:boolean;replayed:string[]})=>void){ + first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number;nativeSecondHeld:boolean};searched:boolean;replayed:string[]})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. @@ -69,12 +70,30 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType`attempts=0; until test -f '${path}'; do attempts=$((attempts+1)); test "$attempts" -lt 1500 || exit 74; sleep 0.01; done`; + const sameToolWrapper=`#!/bin/sh +case " $* " in + *" sirens "*) + if mkdir '${firstClaim}' 2>/dev/null; then + '${rg}' "$@" > '${firstOutput}'; code=$?; : > '${searched}'; + ${boundedGate(secondHeld)} + cat '${firstOutput}'; exit "$code" + else + '${rg}' "$@" > '${secondOutput}'; code=$?; : > '${secondHeld}'; + ${boundedGate(secondRelease)} + cat '${secondOutput}'; exit "$code" + fi;; + *) exec '${rg}' "$@";; +esac +`; + const ordinaryWrapper=`#!/bin/sh case " $* " in *" sirens "*) '${rg}' "$@"; code=$?; : > '${searched}'; sleep 3; exit "$code";; *) exec '${rg}' "$@";; esac -`);chmodSync(join(bin,"rg"),0o755); +`; + writeFileSync(join(bin,"rg"),interruption==="same-tool"?sameToolWrapper:ordinaryWrapper);chmodSync(join(bin,"rg"),0o755); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); holdSafetyRecovery(db); // Each turn's provider requests, as the loopback model received them. @@ -159,12 +178,13 @@ esac if("session_id" in message&&typeof message.session_id==="string")runtimeSession=message.session_id; }}catch{/* The interrupted turn is stopped. */} finally{ + if(interruption==="same-tool")writeFileSync(secondRelease,""); clearInterval(watching);clearTimeout(timer);db.exec("DROP TRIGGER IF EXISTS refuse_result"); // The denial lands before the turn's end, as it would once the hook returns. if(interrupt&&(interruption==="duplicate"||interruption==="retooled"))await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); await writes.safetyEnd(turnId); } - return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals}; + return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals,nativeSecondHeld:existsSync(secondHeld)&&existsSync(secondOutput)&&readFileSync(secondOutput,"utf8").includes(SONG)}; } try{ const first=await voyage("voyage",null,true); @@ -290,7 +310,7 @@ test("a denial of another tool under the search's id cannot settle the search th * hook order or with the hook both tools share starting late. */ for(const late of [false,true])test(`a denied shell call reusing a search's id cannot settle the search that ran${late?", even when the shared hook starts late":""}`,async()=>{ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retool-")),brain=join(root,"brain"),home=join(root,"home"); - const area=interruption==="same-tool"?"workspaces/voyage":"notes"; + const area="notes"; mkdirSync(join(brain,area),{recursive:true});mkdirSync(home); const path=join(brain,area,"sirens.md");writeFileSync(path,`${SONG}\n`); const db=createUiDb(join(root,"ui.db")),writer=openSqliteWriter(db),writes=createGovernanceWrites(db,writer); @@ -338,12 +358,7 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c test("two same-ID native Grep calls retain their recorded result and the interrupted call's gap",()=>voyageHome("same-tool",({db,writes,first})=>{ - expect(first.admitted,"NATIVE_SAME_TOOL_ID_HAS_TWO_LOGICAL_ADMISSIONS").toBeGreaterThanOrEqual(2); - expect(first.results,"NATIVE_SAME_TOOL_RESULT_HOOK_ACTUALLY_FORWARDS").toBeGreaterThanOrEqual(1); - expect(db.query("SELECT r.kind,r.source,r.state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' ORDER BY r.kind").all(),"NATIVE_SAME_TOOL_RESULT_REACHES_THE_LEDGER").toEqual(expect.arrayContaining([ - {kind:'exposure',source:null,state:'interrupted_unknown'}, - {kind:'occurrence',source:'workspace_read',state:'open'} - ])); + assertNativeSameToolProof(first,db.query("SELECT r.kind,r.detector,r.state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' ORDER BY r.kind").all()); expect(writes.safety(null,"ithaca").coverage.state,"NATIVE_SAME_TOOL_RESULT_DOES_NOT_ERASE_THE_GAP").toBe('incomplete'); expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:'recording_failed'}); }),60000); From 459e206f7b0dfab625d5f6573a875b948cf47185 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:51:11 +0000 Subject: [PATCH 08/23] test: gate the second native search by logical request --- .../tests/safety-result-retention.test.ts | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index d236b50281..41261db924 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -70,20 +70,21 @@ async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType`attempts=0; until test -f '${path}'; do attempts=$((attempts+1)); test "$attempts" -lt 1500 || exit 74; sleep 0.01; done`; + // Distinct patterns identify logical calls even if Grep starts auxiliary + // rg processes. Every second-call engine is held before it can finish. const sameToolWrapper=`#!/bin/sh case " $* " in + *" sirens|sirens "*) + '${rg}' "$@" > '${secondOutput}'.$$; code=$?; + cp '${secondOutput}'.$$ '${secondOutput}'; : > '${secondHeld}'; + ${boundedGate(secondRelease)} + cat '${secondOutput}'.$$; exit "$code";; *" sirens "*) - if mkdir '${firstClaim}' 2>/dev/null; then - '${rg}' "$@" > '${firstOutput}'; code=$?; : > '${searched}'; - ${boundedGate(secondHeld)} - cat '${firstOutput}'; exit "$code" - else - '${rg}' "$@" > '${secondOutput}'; code=$?; : > '${secondHeld}'; - ${boundedGate(secondRelease)} - cat '${secondOutput}'; exit "$code" - fi;; + '${rg}' "$@" > '${firstOutput}'.$$; code=$?; : > '${searched}'; + ${boundedGate(secondHeld)} + cat '${firstOutput}'.$$; exit "$code";; *) exec '${rg}' "$@";; esac `; @@ -105,7 +106,8 @@ esac requests.push({turn,raw}); const first=turn===0&&requests.filter(r=>r.turn===0).length===1; const search={name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}; - if(first&&(interruption==="duplicate"||interruption==="same-tool"))return modelCalls([search,search]); + if(first&&interruption==="duplicate")return modelCalls([search,search]); + if(first&&interruption==="same-tool")return modelCalls([search,{...search,input:{...search.input,pattern:"sirens|sirens"}}]); if(first&&interruption==="retooled")return modelCalls([search,{name:"Read",id:search.id,input:{file_path:path}}]); return nativeModelReply(first?search:undefined); }}); @@ -184,7 +186,7 @@ esac if(interrupt&&(interruption==="duplicate"||interruption==="retooled"))await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); await writes.safetyEnd(turnId); } - return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals,nativeSecondHeld:existsSync(secondHeld)&&existsSync(secondOutput)&&readFileSync(secondOutput,"utf8").includes(SONG)}; + return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals,nativeSecondHeld:existsSync(secondHeld)&&existsSync(secondOutput)&&readFileSync(secondOutput,"utf8").length>0}; } try{ const first=await voyage("voyage",null,true); From 69273708b42fec98858b4f6f3e99c7acb48ec6ba Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:16:22 +0000 Subject: [PATCH 09/23] CONTRACT: retain explicit search completion status across Pi result delivery --- .changeset/session-safety-input-evidence.md | 3 + api-report/ui-sdk.txt | 8 +++ docs/integration-contract.md | 8 +++ docs/integration-contract/package-api.md | 21 ++++++ packages/ui-backend-pi/src/file-tools.ts | 11 +-- packages/ui-backend-pi/src/tool-safety.ts | 4 +- packages/ui-backend-pi/src/worker-entry.ts | 4 +- packages/ui-backend-pi/src/worker-protocol.ts | 29 ++++---- packages/ui-backend-pi/src/worker-rpc.ts | 9 ++- .../ui-backend-pi/tests/exec-wrapper.test.ts | 4 +- .../tests/tool-factories.test.ts | 10 +++ .../tests/worker-host-exec.test.ts | 2 +- packages/ui-sdk/src/server/backend.ts | 13 +++- packages/ui-sdk/src/server/index.ts | 1 + .../ui-server/src/activity/ingestion-taint.ts | 4 +- .../src/governance/safety-collector.ts | 8 ++- .../tests/ingestion-taint-schema.test.ts | 21 ++++-- .../tests/safety-result-exits.test.ts | 70 ++++++++++++++----- 18 files changed, 173 insertions(+), 57 deletions(-) diff --git a/.changeset/session-safety-input-evidence.md b/.changeset/session-safety-input-evidence.md index f120fb54f5..45d32f0b8a 100644 --- a/.changeset/session-safety-input-evidence.md +++ b/.changeset/session-safety-input-evidence.md @@ -1,6 +1,9 @@ --- +"@schlessera/brain-ui-sdk": minor "@schlessera/brain-ui-server": patch "@schlessera/brain-backend-pi": patch --- Retain unknown delivery when concurrent tool calls reuse one ID. Preserve exact search filenames, including colons and newlines, and recognize only complete original Pi grep empty results without creating a spurious safety trigger. + +Add optional host-only search output status to the input collector callback so failed, mixed or truncated results retain unknown evidence independently of their text. diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index a993b8e283..ed10295fc2 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -2869,6 +2869,7 @@ export "./server" (./src/server/index.ts) type InboxToolName type InboxView type InboxWorkPayload + type InputSafetyOutputStatus type JournalObservationReference type JournalOutwardAction type JournalRecoveryStatus @@ -10698,6 +10699,13 @@ signatures (every public export and the types it is made of) instruction: string; operation?: InboxOperation; } + InputSafetyOutputStatus (packages/ui-sdk/src/server/backend.ts) + export interface InputSafetyOutputStatus { + readonly complete: boolean; + readonly exitCode?: number; + readonly stderr?: boolean; + readonly truncated?: boolean; + } JournalObservationReference (packages/ui-sdk/src/turn-journal.ts) export interface JournalObservationReference { turnId: string; diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 93ec8afb11..fe62f2a3b4 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -1893,3 +1893,11 @@ archived discussion. Optional negotiated history paging/provenance fields are additive; the retention/privacy meaning change is a pre-1.0 breaking minor. See [durable dialogue](integration-contract/wire.md#durable-live-dialogue-breaking-retention-supersession-3177). Historical provider input remains separate #3178 work. + + +## Collected search output status (additive, 0.45.0, #4275) + +The host input collector accepts optional, explicit completeness and process +status for search output. Incomplete evidence remains restrictive without +rewriting the result text. See the +[package API](integration-contract/package-api.md#collected-search-output-status-additive-0450-4275). diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 3e829dc991..bdfb103b6a 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5952,3 +5952,24 @@ for every interactive session, so a new session's retained append contains the bullet. A session retained earlier keeps its append byte for byte. The same-commit API report records the additive types. See [the MCP component](mcp.md#raw-connections-to-githubs-api-0450-3799). + + +## Collected search output status (additive, 0.45.0, #4275) + +`BackendBridge.inputSafety.result` in `@schlessera/brain-ui-sdk/server` +accepts an optional sixth argument, `outputStatus`, after the existing +`segments` argument. The exported `InputSafetyOutputStatus` type has readonly required `complete: boolean` +and optional `exitCode: number`, `stderr: boolean`, `truncated: boolean`. +`stderr` records presence, never the error bytes. This is host-only evidence, +not a provider-facing tool definition or a permission grant. + +Omission preserves the existing collection behavior. `complete: false`, a +failed search exit, stderr or truncation retains an unknown search remainder +alongside every identifiable source. It is independent of the existing +`finalized` exposure argument; incomplete evidence cannot prove a managed +reference read. Pi carries the original tool status through its result hook +and worker RPC. Exit 1 with empty stdout and no stderr is its only empty +sentinel; exit 0 requires matches. Missing search status is restrictive. +Neither metadata nor completeness is encoded by changing result text, and +neither changes prior provider history. The same-commit API report records +the additive argument. diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 25b807d798..d02748a413 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -15,7 +15,7 @@ import { bashLockKey, killWrapped, rtkRewriteCommand, wrapCommand } from "@schle import { RTK_WORKER_ENV, execWrapperSpawnOptions, WORKER_DATA_ROOT, WORKER_EGRESS_TRANSPORT_ENV } from "@schlessera/brain-ui-sdk/internal"; import { resolveEnabledWebSearchEnvNames, ambientExecConfig, subprocessEnv } from "./config/env.js"; -import { clip, MAX_READ_BYTES, textResult, type BrainToolKit } from "./tool-kit.js"; +import { clip, MAX_READ_BYTES, MAX_OUTPUT_BYTES, textResult, type BrainToolKit } from "./tool-kit.js"; import { revalidatePiAdmission } from "./tool-admission.js"; /** `read_file`: one repo-contained UTF-8 file, remembered as a same-turn base. */ @@ -60,7 +60,7 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const rel = params.path ?? "."; resolveOrThrow(rel); const exec = deps.exec ?? ambientExecConfig(); - const proc = spawn(wrapCommand(["grep", "-rInZE", "--", params.pattern, rel], exec.wrapper), { + const proc = spawn(wrapCommand(["grep", "-rHInZE", "--", params.pattern, rel], exec.wrapper), { cwd: brain.root, env: subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), stdout: "pipe", @@ -69,13 +69,14 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { }); const onAbort = () => killWrapped(proc, exec); signal?.addEventListener("abort", onAbort, { once: true }); - const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); + const [out, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); signal?.removeEventListener("abort", onAbort); // Keep the visible colon layout and an unambiguous machine boundary. // POSIX filenames may contain newlines, colons and edge whitespace. // This changes result data only; provider tool definitions stay identical. - const text = out.replaceAll("\0", ":\0"); - return textResult(text ? clip(text) : "No matches.", { pattern: params.pattern }); + const empty=exitCode===1&&out.length===0&&stderr.length===0; + const text=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; + return textResult(clip(text), {pattern:params.pattern,search:{exitCode,stderr:stderr.length>0,truncated:text.length>MAX_OUTPUT_BYTES}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/src/tool-safety.ts b/packages/ui-backend-pi/src/tool-safety.ts index 327f57ade4..ea49c86b04 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,details?:unknown):Promise; unavailable?():Promise; stop():void; } @@ -70,7 +70,7 @@ export function installPiToolSafety(agent:Agent,safety:PiToolSafety,hasUnqualifi // 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);} + try{await safety.result(context.toolCall.name,context.toolCall.id,final?.content??context.result.content,complete,final&&Object.hasOwn(final,"details")?final.details:final?.content?undefined:context.result.details);} catch(error){stop();throw error;} if(failure){stop();throw failure.error;} return final; diff --git a/packages/ui-backend-pi/src/worker-entry.ts b/packages/ui-backend-pi/src/worker-entry.ts index 74db2f8c39..d2b9790364 100644 --- a/packages/ui-backend-pi/src/worker-entry.ts +++ b/packages/ui-backend-pi/src/worker-entry.ts @@ -201,8 +201,8 @@ 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: (name,id,content,complete,details) => { + return rpc("safetyResult",name,id,safetyResultInput(name,content,complete,details)); }, stop: () => controller.abort(), }, diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 5eef524735..5e52a0c038 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -88,20 +88,21 @@ 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[] } { - const segments = content.filter(part => part.type === "text").map(part => part.text as string); - // The shipped grep returns exactly one text block. Preserve every text - // row, but add an unparseable empty row when the original result is not - // that complete shape. This host-only observation never changes provider - // content, and mixed/non-text output cannot impersonate the empty sentinel. - if(tool==="grep"&&(!complete||content.length!==1||content[0]?.type!=="text"||typeof content[0]?.text!=="string")) - return {output:segments.join("\n")+"\n",segments}; - // 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 }; +export const piOutputStatus=z.object({complete:z.boolean(),exitCode:z.number().int().optional(),stderr:z.boolean().optional(),truncated:z.boolean().optional()}).strict(); +const searchStatus=z.object({exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean()}).strict(); +/** Host-only observation. Never alter provider result content to encode status. */ +export function safetyResultInput(tool:string,content:readonly {type:string;text?:unknown}[],complete=true,details?:unknown): {output:string;segments?:string[];outputStatus:z.infer} { + const segments=content.filter(part=>part.type==='text'&&typeof part.text==='string').map(part=>part.text as string),output=segments.join('\n'); + if(tool==='grep'){ + const status=searchStatus.safeParse(details&&typeof details==='object'?(details as Record).search:undefined); + const original=complete&&content.length===1&&content[0]?.type==='text'&&typeof content[0]?.text==='string'; + const successful=status.success&&!status.data.stderr&&!status.data.truncated&& + (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&output==='No matches.'); + return {output,segments,outputStatus:{...(status.success?status.data:{}),complete:original&&successful}}; + } + // Reference reads require every original segment; omission never proves a read. + if(tool==='reference_read'&&(!complete||content.some(part=>part.type!=='text'||typeof part.text!=='string')))return {output,outputStatus:{complete:false}}; + return {output,segments,outputStatus:{complete}}; } 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..ea7bec5f97 100644 --- a/packages/ui-backend-pi/src/worker-rpc.ts +++ b/packages/ui-backend-pi/src/worker-rpc.ts @@ -18,7 +18,7 @@ import { revalidatePiAdmission } from "./tool-admission.js"; import { 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"; +import { piOutputStatus, type PiWorkerMessage } from "./worker-protocol.js"; import type { PiWorkerReceipts } from "./worker-receipts.js"; import type { CallExecution } from "./worker-session.js"; @@ -283,10 +283,13 @@ 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","outputStatus"].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")); 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); + const parsed=piOutputStatus.safeParse(msg.input.outputStatus); + let status=parsed.success?parsed.data:msg.input.outputStatus===undefined?undefined:{complete:false}; + if(msg.toolName==="grep"&&(!status||status.exitCode===undefined||status.stderr===undefined||status.truncated===undefined))status={complete:false}; + await bridge.inputSafety?.result(msg.toolCallId,msg.toolName,msg.input.output,bounded,msg.input.segments as string[]|undefined,status); context.live();return {ok:true}; }, }; diff --git a/packages/ui-backend-pi/tests/exec-wrapper.test.ts b/packages/ui-backend-pi/tests/exec-wrapper.test.ts index 7f055c5e21..14efe75d7f 100644 --- a/packages/ui-backend-pi/tests/exec-wrapper.test.ts +++ b/packages/ui-backend-pi/tests/exec-wrapper.test.ts @@ -157,7 +157,7 @@ describe("the grep tool", () => { expect(resultText(res)).toContain("needle"); expect(readFileSync(argvLog, "utf-8").split("\n").filter(Boolean)).toEqual([ Bun.which("grep")!, - "-rInZE", + "-rHInZE", "--", "needle", ".", @@ -188,7 +188,7 @@ test("host A/C and explicit empty override ambient B for both Pi spawn tools (#1 expect(existsSync(b.argvLog), "EXPLICIT_EMPTY_NOT_AMBIENT").toBe(false); } expect(readFileSync(a.argvLog, "utf8").split("\n").filter(Boolean)).toEqual([ - Bun.which("bash")!, "--noprofile", "--norc", "-c", "echo needle", Bun.which("grep")!, "-rInZE", "--", "needle", ".", + Bun.which("bash")!, "--noprofile", "--norc", "-c", "echo needle", Bun.which("grep")!, "-rHInZE", "--", "needle", ".", ]); expect(readFileSync(c.argvLog, "utf8")).toBe(readFileSync(a.argvLog, "utf8")); } finally { brain.cleanup(); } diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts index b556688c7b..d4649fc984 100644 --- a/packages/ui-backend-pi/tests/tool-factories.test.ts +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -188,3 +188,13 @@ test("brainReadBaseTool reads the server base and remembers its whole-document h expect(JSON.parse(resultText(result))).toMatchObject({ expectedBaseHash: "d".repeat(64) }); expect(tools.bases.get(tools.turn.bridge!)?.get("notes/ithaca.md")).toBe("d".repeat(64)); }); + +test('grepTool never reports a failed regular expression as an empty search',async()=>{ + const result=await run(grepTool(kit({exec:{}})),{pattern:'['}); + expect(resultText(result),'FAILED_GREP_IS_NOT_THE_EMPTY_SENTINEL').not.toBe('No matches.'); +}); + +test('grepTool prefixes a single file operand with its exact filename',async()=>{ + const result=await run(grepTool(kit({exec:{}})),{pattern:'Odysseus',path:'notes/ithaca.md'}); + expect(resultText(result),'SINGLE_FILE_GREP_HAS_A_FILENAME_BOUNDARY').toBe('notes/ithaca.md:\0'+'3:Odysseus sails home.\n'); +}); diff --git a/packages/ui-backend-pi/tests/worker-host-exec.test.ts b/packages/ui-backend-pi/tests/worker-host-exec.test.ts index 5db69e4b7e..2a61c4e6e4 100644 --- a/packages/ui-backend-pi/tests/worker-host-exec.test.ts +++ b/packages/ui-backend-pi/tests/worker-host-exec.test.ts @@ -63,7 +63,7 @@ for (const profile of ["governed", "strict", "restricted"] as const) { expect(report.grep).toContain("voyage.md:\0"+"1:The wine-dark sea"); expect(report.bash).toBe("Ithaca"); const wrapped = report.wrapperLog.split("\n"); - expect(wrapped, "WORKER_TOOLS_USED_HOST_WRAPPER").toEqual(expect.arrayContaining(["-rInZE", "wine-dark", "--noprofile", "--norc", "-c", "echo Ithaca", "sleep 30"])); + expect(wrapped, "WORKER_TOOLS_USED_HOST_WRAPPER").toEqual(expect.arrayContaining(["-rHInZE", "wine-dark", "--noprofile", "--norc", "-c", "echo Ithaca", "sleep 30"])); expect(report.cancel).toBe("AbortError"); expect(report.killerLog, "WORKER_KILLER_CANCELLED_GROUP").toMatch(/^\d+ TERM\n$/); expect(report.cancelMs).toBeLessThan(10_000); diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index 81c66106a4..ae633b903f 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -167,6 +167,14 @@ export interface LocationFix { timestamp: number; } +/** Host-only collection status. This is evidence, never dispatch authority. */ +export interface InputSafetyOutputStatus { + readonly complete: boolean; + readonly exitCode?: number; + readonly stderr?: boolean; + readonly truncated?: boolean; +} + /** * Host plumbing handed to the backend for one turn. `emit` delivers protocol * frames to the client; the request/response methods resolve when the user @@ -190,7 +198,10 @@ export interface BackendBridge { /** @internal Persist collector loss before refusing unqualified input. */ unavailable?(): Promise; begin(toolUseId: string, toolName: string, input: Readonly>): Promise; - result(toolUseId: string, toolName: string, output: string, finalized: boolean, segments?: readonly string[]): Promise; + /** `outputStatus.complete:false` retains an unknown search remainder even when + * known rows were delivered. Omission preserves the existing behavior; + * it is independent of the result's finalized exposure lifecycle. */ + result(toolUseId: string, toolName: string, output: string, finalized: boolean, segments?: readonly string[], outputStatus?: InputSafetyOutputStatus): Promise; /** @internal A tool ran, but its result report was refused before `result` * could record it: the turn's chat keeps a permanent gap. Resolves once * that gap is durable. */ diff --git a/packages/ui-sdk/src/server/index.ts b/packages/ui-sdk/src/server/index.ts index d935d77f67..3d60c2d0a9 100644 --- a/packages/ui-sdk/src/server/index.ts +++ b/packages/ui-sdk/src/server/index.ts @@ -1,6 +1,7 @@ export type { AgentBackend, BackendBridge, + InputSafetyOutputStatus, BackendActivityEvent, ActivityQuery, ActivityQueryResult, diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index bae2bfd193..e75a09a60a 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -174,7 +174,7 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri } /** Admitted format only. Invalid or incomplete output always retains unknown coverage. */ -interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number } +interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number; outputComplete?: boolean } // Installed SDK: GlobInput/GrepInput and GlobOutput/GrepOutput in // @anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:905-983,3506-3545. Pi's shipped grep and text // envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:44-82) @@ -189,7 +189,7 @@ const grepOutput = z.object({ mode: z.enum(['content','files_with_matches','coun export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: SearchOutputContext): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; if(Buffer.byteLength(output)>1048576)throw new Error('Safety search output capacity exceeded'); - const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=false; + const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=context?.outputComplete===false; const add=(path:string)=>{ if(!path||path.includes('\0')){unknown=true;return;} if(/truncat|omitted|\.\.\.|…/i.test(path))unknown=true; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 8782866166..ecb48a0c5f 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -137,7 +137,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option // may skip both: a stopped turn still records it (stopping refuses new // tools, never a record; the turn's end waits for a record under way), // and any failure leaves its chat a permanent gap. - result(toolUseId,tool,output,finalized,segments){ + result(toolUseId,tool,output,finalized,segments,outputStatus){ const reject=(error:unknown)=>rejectReadResult(toolUseId,tool,error); return recording(serial(toolUseId,async()=>{ try{ @@ -152,11 +152,13 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option } // Record output independently, before the backend releases it to the // model. Its bytes already exist, so a refusal here is never "before delivery". - for(const signal of outputTaintSignals(tool,output,options.brainPath,marked,op.searchContext)){ + const outputComplete=outputStatus===undefined?undefined:outputStatus.complete&&outputStatus.stderr!==true&&outputStatus.truncated!==true&& + (outputStatus.exitCode===undefined||outputStatus.exitCode===0&&output.length>0&&output!=="No matches."||outputStatus.exitCode===1&&output==="No matches."); + for(const signal of outputTaintSignals(tool,output,options.brainPath,marked,{...op.searchContext,outputComplete})){ const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); } - await options.referenceReads?.observeResult(options.turnId,toolUseId,tool,output,finalized&&!op.uncertain,segments); + await options.referenceReads?.observeResult(options.turnId,toolUseId,tool,output,finalized&&!op.uncertain&&outputComplete!==false,segments); const state=finalized&&!op.uncertain&&!['Bash','bash'].includes(tool)?"finalized":"interrupted_unknown"; // The last exposure commits with the call's discharge, in one // transaction: no end and no restart can find the record durable and diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index cd42ac33e3..7a7cd68dd5 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -50,11 +50,11 @@ for(const [name,tool,input,output,expected] of [ ['Glob exceeds installed file cap','Glob',{},glob(Array.from({length:101},(_,i)=>`notes/loom-${i}.md`)),['legacy_unknown']], ['Glob legal CR LF filename','Glob',{},glob(['workspaces/voyage/log\r\n.md']),['workspace_read','user_marked']], ['Grep legal CR LF filename','Grep',{},grep(['workspaces/voyage/log\r\n.md']),['workspace_read','user_marked']], - ['Pi sentinel plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'image'}]).output,['legacy_unknown']], - ['Pi sentinel incomplete original','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],false).output,['legacy_unknown']], - ['Pi marked row plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/voyage.md:1:sirens'},{type:'image'}]).output,['user_marked','legacy_unknown']], - ['Pi sentinel plus empty block','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'text',text:''}]).output,['legacy_unknown']], - ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}]).output,[]], + ['Pi sentinel plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'image'}]),['legacy_unknown']], + ['Pi sentinel incomplete original','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],false),['legacy_unknown']], + ['Pi marked row plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/voyage.md:1:sirens'},{type:'image'}]),['user_marked','legacy_unknown']], + ['Pi sentinel plus empty block','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'text',text:''}]),['legacy_unknown']], + ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],true,{search:{exitCode:1,stderr:false,truncated:false}}),[]], ['Grep duplicate per-file count rows','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:1\nnotes/loom.md:1',numMatches:2}),['legacy_unknown']], ['Pi newline filename ambiguity is never healthy legacy evidence','grep',{},'./raft:1:sail\nloom.md:1:sirens',['legacy_unknown']], ['Pi NUL newline filename','grep',{},'./raft:1:sail\nloom.md:\0'+'1:sirens\n',['user_marked']], @@ -93,6 +93,15 @@ for(const [name,tool,input,output,expected] of [ ['Pi quoted sentinel','grep',{},JSON.stringify('No matches.'),['legacy_unknown']], ] as const)test(`recognized search shape: ${name}`,()=>{ const marked=(path:string)=>['raft:1:sail\nloom.md','workspaces/voyage/log\r\n.md','[voyage]/log.md','notes/voyage.md','notes/voyage:2','notes/voyage:2:home.md'].includes(path); - const signals=outputTaintSignals(tool,output,'/srv/odysseus/brain',marked,searchOutputContext(tool,input)); + const observation=typeof output==='string'?{output,outputStatus:undefined}:output; + const signals=outputTaintSignals(tool,observation.output,'/srv/odysseus/brain',marked,{...searchOutputContext(tool,input),outputComplete:observation.outputStatus?.complete}); expect(signals.map(s=>s.source),'ONLY_RECOGNIZED_COMPLETE_SHAPES_CAN_REMAIN_HEALTHY').toEqual([...expected]); }); + +for(const terminated of [false,true])for(const shape of ['incomplete','image'] as const)test(`explicit Pi completeness is independent of row text: ${shape}-${terminated?'terminated':'unterminated'}`,()=>{ + const text='notes/loom.md:\0'+'1:sirens'+(terminated?'\n':''); + const converted=safetyResultInput('grep',[{type:'text',text},...(shape==='image'?[{type:'image'}]:[])],shape!=='incomplete',{search:{exitCode:0,stderr:false,truncated:false}}); + expect(converted.output,'STATUS_NEVER_REWRITES_RESULT_TEXT').toBe(text); + const signals=outputTaintSignals('grep',converted.output,'/srv/odysseus/brain',()=>false,{...searchOutputContext('grep',{}),outputComplete:converted.outputStatus.complete}); + expect(signals.map(signal=>signal.source),'EXPLICIT_INCOMPLETE_RESULT_STAYS_UNKNOWN').toEqual(['legacy_unknown']); +}); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 117e0abdec..c136fc1d6e 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -9,7 +9,7 @@ import { safetyResultInput } from "../../ui-backend-pi/src/worker-protocol"; * `safety-result-retention.test.ts`; these drive the remaining exits against * the real host ledger. Keyless and offline. */ import { afterEach, expect, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import {createRequire} from "node:module"; @@ -73,7 +73,7 @@ function dispatcher(f: Voyage) { canFinalizeSafety: () => false } as unknown as PiWorkerRpcContext); } const report = (id: number, toolCallId: string, input: Record): PiWorkerRpc => - ({ type: "rpc", id, method: "safetyResult", toolName: "grep", toolCallId, input }) as PiWorkerRpc; + ({ type: "rpc", id, method: "safetyResult", toolName: "grep", toolCallId, input: {outputStatus:{complete:true,exitCode:0,stderr:false,truncated:false},...input} }) as PiWorkerRpc; test("a result reaching a turn that stopped and ended leaves its chat a permanent gap", async () => { const f = await voyage(); try { @@ -279,11 +279,15 @@ test("a call still owed when the host dies leaves its chat a permanent gap at bo }); /** The real curated search, run the way the worker runs it once the host allowed it. */ -async function searchRuns(f: Voyage, toolCallId: string, input: Record): Promise { - const grep = createBrainTools({ brain: createBrainAccess(f.brain), turn: createTurnContext(), exec: {}, - lock: { withKey: async (_key: string, run: () => Promise) => run() } } as never).find(tool => tool.name === "grep")!; - return safetyResultInput("grep",(await grep.execute(toolCallId, input as never, f.controller.signal, undefined, undefined as never)).content).output; +async function runSearchTool(f:Voyage,toolCallId:string,input:Record,wrapper?:string){ + const grep=createBrainTools({brain:createBrainAccess(f.brain),turn:createTurnContext(),exec:wrapper?{wrapper}:{},lock:{withKey:async(_key:string,run:()=>Promise)=>run()}} as never).find(tool=>tool.name==='grep')!; + return grep.execute(toolCallId,input as never,f.controller.signal,undefined,undefined as never); } +async function searchResult(f:Voyage,toolCallId:string,input:Record){ + const result=await runSearchTool(f,toolCallId,input); + return safetyResultInput('grep',result.content,true,result.details); +} +async function searchRuns(f:Voyage,toolCallId:string,input:Record):Promise{return (await searchResult(f,toolCallId,input)).output;} /** What stands for a call that ran and was never reported: its obligation, then its chat's gap. */ async function stillOwed(f: Voyage, call: string) { @@ -482,9 +486,9 @@ for(const binding of ['pi','claude'] as const)test(`${binding}: two allowed sear const gate=createPermissionGate({turn,allowedTools:new Set(['grep']),confirmPatterns:[]}); (typeof gate==='function'?gate:gate.factory)({on:(name:string,callback:unknown)=>{if(name==='tool_call')handler=callback as typeof handler;}} as never); admit=async()=>{const result=await handler!({toolName:'grep',toolCallId:id,input});expect(result,'PI_REUSED_ID_CALL_REACHES_EXECUTION').toBeUndefined();}; - run=()=>searchRuns(f,id,input); + run=()=>searchResult(f,id,input); const dispatch=dispatcher(f); - deliver=output=>dispatch(report(1,id,safetyResultInput('grep',[{type:'text',text:String(output)}]))); + deliver=output=>dispatch(report(1,id,output as Record)); }else{ const wiring=createPermissionWiring({req:{prompt:'Listen for the sirens.',signal:f.controller.signal,bridge:{emit(){},requestPermission:async()=>({behavior:'allow'}),inputSafety:f.collector}} as never, allowedTools:['Grep'],confirmPatterns:[],brainPath:f.brain,childEnv:{PATH:'/usr/bin:/bin'},log(){},turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never}); @@ -514,9 +518,9 @@ test('real Pi grep empty output stays empty when the collector records its resul const f=await voyage();try{ const input={pattern:'no_cyclops_matches_here'}; await f.collector.begin('empty_search','grep',input); - const output=await searchRuns(f,'empty_search',input); + const observed=await searchResult(f,'empty_search',input),output=observed.output; expect(output,'SHIPPED_PI_EMPTY_SEARCH_FORMAT').toBe('No matches.'); - await f.collector.result('empty_search','grep',output,true); + await dispatcher(f)(report(1,'empty_search',observed)); expect(f.recorded(),'REAL_EMPTY_SEARCH_CREATES_NO_OCCURRENCE').toEqual([]); expect(f.chat().restriction).toBe('normal'); }finally{await f.close();} @@ -534,11 +538,11 @@ for(const marked of [false,true])test(`real Pi grep bracket paths retain exactly } const input={pattern:'sirens',path:'[voyage]'}; await f.collector.begin('bracket_search','grep',input); - const output=await searchRuns(f,'bracket_search',input); + const observed=await searchResult(f,'bracket_search',input),output=observed.output; expect(output.split('\n').filter(Boolean).sort(),'REAL_GREP_RETURNS_BOTH_BRACKET_FILENAMES').toEqual(paths.map(path=>`${path}:\0`+"1:sirens")); const signals=outputTaintSignals('grep',output,f.brain,path=>isMarkedUntrusted(f.db,path),searchOutputContext('grep',input)); expect(signals.sort((a,b)=>a.key.localeCompare(b.key)),'REAL_BRACKET_OUTPUT_HAS_EXACT_PATH_SIGNALS').toEqual(marked?paths.map(key=>({source:'user_marked',detector:'explicit_untrusted_input',key})):[]); - await f.collector.result('bracket_search','grep',output,true); + await dispatcher(f)(report(1,'bracket_search',observed)); // The ledger intentionally retains no raw filename. Assert its exact // occurrence/exposure inventory as well as the detector's actual paths. expect(f.db.query("SELECT kind,source,detector FROM safety_records ORDER BY kind,length(sequence),sequence").all(),'REAL_BRACKET_LEDGER_HAS_NO_EXTRA_UNKNOWN').toEqual(marked?[ @@ -554,9 +558,9 @@ for(const shape of ['exact','image','second-text','incomplete'] as const)test(`P const f=await voyage();try{ const input={pattern:'no_cyclops_matches_here'},id='original_empty'; await f.collector.begin(id,'grep',input); - const text=await searchRuns(f,id,input);expect(text).toBe('No matches.'); + const actual=await runSearchTool(f,id,input),text=actual.content.filter(part=>part.type==='text').map(part=>part.text).join('');expect(text).toBe('No matches.'); const content=[{type:'text',text},...(shape==='image'?[{type:'image'}]:shape==='second-text'?[{type:'text',text:''}]:[])]; - const converted=safetyResultInput('grep',content,shape!=='incomplete'); + const converted=safetyResultInput('grep',content,shape!=='incomplete',actual.details); await dispatcher(f)(report(1,id,converted)); expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all(),'ORIGINAL_MIXED_PI_RESULT_RETAINS_UNKNOWN').toEqual(shape==='exact'?[]:[{source:'legacy_unknown',detector:'tool_search_output'}]); expect(f.chat().restriction).toBe(shape==='exact'?'normal':'restricted'); @@ -571,10 +575,44 @@ test('shipped Pi grep preserves a marked newline filename through the worker led writeFileSync(join(f.brain,path),'nymph_signal\n'); untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); await f.collector.begin(id,'grep',input); - const output=await searchRuns(f,id,input); + const observed=await searchResult(f,id,input),output=observed.output; expect(outputTaintSignals('grep',output,f.brain,p=>isMarkedUntrusted(f.db,p),searchOutputContext('grep',input)),'PI_NEWLINE_PATH_KEEPS_ITS_EXACT_MARK').toEqual([{source:'user_marked',detector:'explicit_untrusted_input',key:path}]); expect(output).toBe(`./${path}:\0`+'1:nymph_signal\n'); - await dispatcher(f)(report(1,id,safetyResultInput('grep',[{type:'text',text:output}]))); + await dispatcher(f)(report(1,id,observed)); expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all(),'PI_NEWLINE_PATH_LEDGER_HAS_NO_FALSE_HEALTHY_OR_UNKNOWN').toEqual([{source:'user_marked',detector:'explicit_untrusted_input'}]); }finally{await f.close();} }); + +for(const mode of ['file','empty','regex','partial','warning'] as const)test(`Pi after-tool RPC preserves grep status: ${mode}`,async()=>{ + const f=await voyage();let unreadable:string|undefined;try{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + mkdirSync(join(f.brain,'notes')); + writeFileSync(join(f.brain,'notes/loom.md'),'nymph_signal\n'); + if(mode==='partial'){ + unreadable=join(f.brain,'notes/raft.md');writeFileSync(unreadable,'nymph_signal\n');chmodSync(unreadable,0); + untrustedMarkOperations(f.db).mark('notes/loom.md',null,Date.UTC(2026,6,12)); + } + const wrapper=mode==='warning'?join(f.brain,'warning-wrapper'):undefined; + if(wrapper)writeFileSync(wrapper,'#!/bin/sh\nprintf "search warning\\n" >&2\nexec "$@"\n',{mode:0o755}); + const input={pattern:mode==='regex'?'[':mode==='empty'?'no_cyclops_here':'nymph_signal',...(mode==='file'?{path:'notes/loom.md'}:{})},id='status_search'; + await f.collector.begin(id,'grep',input); + const actual=await runSearchTool(f,id,input,wrapper); + const expectedCode=mode==='empty'?1:mode==='regex'||mode==='partial'?2:0; + expect((actual.details as {search:unknown}).search,'GREP_EXIT_STATUS_AND_STDERR_ARE_OBSERVED').toEqual({exitCode:expectedCode,stderr:['regex','partial','warning'].includes(mode),truncated:false}); + let stopped=false,forwarded:unknown; + const agent={abort(){stopped=true;},streamFunction:async()=>{}} as unknown as Agent; + const dispatch=dispatcher(f); + installPiToolSafety(agent,{permission:async()=>({behavior:'allow'}),stop(){stopped=true;},async result(name,toolId,content,complete,details){ + const converted=safetyResultInput(name,content,complete,details);forwarded=converted.outputStatus; + await dispatch(JSON.parse(JSON.stringify(report(1,toolId,converted)))); + }},()=>false); + await agent.afterToolCall!({toolCall:{name:'grep',id},args:input,result:actual,isError:false} as never,f.controller.signal); + const incomplete=['regex','partial','warning'].includes(mode); + expect(forwarded,'GREP_STATUS_REACHES_WORKER_RPC').toEqual({complete:!incomplete,exitCode:expectedCode,stderr:incomplete,truncated:false}); + expect(stopped).toBe(false); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all(),'PARTIAL_GREP_KEEPS_KNOWN_MARKS_AND_AN_UNKNOWN_REMAINDER').toEqual(mode==='partial'?[ + {source:'user_marked',detector:'explicit_untrusted_input'},{source:'legacy_unknown',detector:'tool_search_output'} + ]:incomplete?[{source:'legacy_unknown',detector:'tool_search_output'}]:[]); + expect(f.chat().restriction).toBe(incomplete?'restricted':'normal'); + }finally{if(unreadable)chmodSync(unreadable,0o600);await f.close();} +}); From 81b9a887cefd6014b187ed240514ae52c8dc35bf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:31:46 +0000 Subject: [PATCH 10/23] CONTRACT: keep search framing host-only and retain conflicting evidence --- docs/integration-contract/package-api.md | 4 ++- packages/ui-backend-pi/src/file-tools.ts | 9 ++++--- packages/ui-backend-pi/src/worker-protocol.ts | 9 ++++--- .../tests/tool-factories.test.ts | 13 ++++++++-- .../tests/worker-host-exec.test.ts | 2 +- .../ui-server/src/activity/ingestion-taint.ts | 5 ++-- .../src/governance/safety-collector.ts | 10 ++++++-- .../tests/ingestion-taint-schema.test.ts | 1 + .../tests/safety-result-exits.test.ts | 25 +++++++++++++------ 9 files changed, 57 insertions(+), 21 deletions(-) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index bdfb103b6a..9558cdd774 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5970,6 +5970,8 @@ alongside every identifiable source. It is independent of the existing reference read. Pi carries the original tool status through its result hook and worker RPC. Exit 1 with empty stdout and no stderr is its only empty sentinel; exit 0 requires matches. Missing search status is restrictive. -Neither metadata nor completeness is encoded by changing result text, and +Pi keeps NUL filename framing in host-only result details; provider text retains +the advertised `path:line:content` format. Neither metadata nor completeness is +encoded by changing result text, and neither changes prior provider history. The same-commit API report records the additive argument. diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index d02748a413..e4f6bffccd 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -71,12 +71,15 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { signal?.addEventListener("abort", onAbort, { once: true }); const [out, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); signal?.removeEventListener("abort", onAbort); - // Keep the visible colon layout and an unambiguous machine boundary. + // Keep an unambiguous machine boundary in host-only result details. // POSIX filenames may contain newlines, colons and edge whitespace. // This changes result data only; provider tool definitions stay identical. const empty=exitCode===1&&out.length===0&&stderr.length===0; - const text=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; - return textResult(clip(text), {pattern:params.pattern,search:{exitCode,stderr:stderr.length>0,truncated:text.length>MAX_OUTPUT_BYTES}}); + const framedOutput=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; + // Only the host observation carries framing; provider text keeps the + // advertised path:line:content format, byte for byte for ordinary paths. + const text=empty?"No matches.":out.replaceAll("\0", ":")||"Search output unavailable."; + return textResult(clip(text), {pattern:params.pattern,search:{exitCode,stderr:stderr.length>0,truncated:framedOutput.length>MAX_OUTPUT_BYTES,framedOutput:clip(framedOutput)}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 5e52a0c038..084fa7b813 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -89,16 +89,19 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ export type PiWorkerMessage = z.infer; export const piOutputStatus=z.object({complete:z.boolean(),exitCode:z.number().int().optional(),stderr:z.boolean().optional(),truncated:z.boolean().optional()}).strict(); -const searchStatus=z.object({exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean()}).strict(); +const searchStatus=z.object({exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional()}).strict(); /** Host-only observation. Never alter provider result content to encode status. */ export function safetyResultInput(tool:string,content:readonly {type:string;text?:unknown}[],complete=true,details?:unknown): {output:string;segments?:string[];outputStatus:z.infer} { const segments=content.filter(part=>part.type==='text'&&typeof part.text==='string').map(part=>part.text as string),output=segments.join('\n'); if(tool==='grep'){ const status=searchStatus.safeParse(details&&typeof details==='object'?(details as Record).search:undefined); const original=complete&&content.length===1&&content[0]?.type==='text'&&typeof content[0]?.text==='string'; - const successful=status.success&&!status.data.stderr&&!status.data.truncated&& + const framed=status.success?status.data.framedOutput:undefined; + const bound=framed===undefined?output==='No matches.':framed.replaceAll('\0','')===output; + const successful=bound&&status.success&&!status.data.stderr&&!status.data.truncated&& (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&output==='No matches.'); - return {output,segments,outputStatus:{...(status.success?status.data:{}),complete:original&&successful}}; + const processStatus=status.success?{exitCode:status.data.exitCode,stderr:status.data.stderr,truncated:status.data.truncated}:{}; + return {output:framed??output,segments,outputStatus:{...processStatus,complete:original&&successful}}; } // Reference reads require every original segment; omission never proves a read. if(tool==='reference_read'&&(!complete||content.some(part=>part.type!=='text'||typeof part.text!=='string')))return {output,outputStatus:{complete:false}}; diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts index d4649fc984..423ea10287 100644 --- a/packages/ui-backend-pi/tests/tool-factories.test.ts +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -73,7 +73,7 @@ test("readFileTool reads one contained file and returns its base on a routed tur test("grepTool searches the repository and names each match", async () => { const result = await run(grepTool(kit({ exec: {} })), { pattern: "Odysseus" }); - expect(resultText(result)).toBe("./notes/ithaca.md:\0"+"3:Odysseus sails home.\n"); + expect(resultText(result)).toBe("./notes/ithaca.md:3:Odysseus sails home.\n"); expect(resultText(await run(grepTool(kit({ exec: {} })), { pattern: "Cyclops" }))).toBe("No matches."); }); @@ -196,5 +196,14 @@ test('grepTool never reports a failed regular expression as an empty search',asy test('grepTool prefixes a single file operand with its exact filename',async()=>{ const result=await run(grepTool(kit({exec:{}})),{pattern:'Odysseus',path:'notes/ithaca.md'}); - expect(resultText(result),'SINGLE_FILE_GREP_HAS_A_FILENAME_BOUNDARY').toBe('notes/ithaca.md:\0'+'3:Odysseus sails home.\n'); + expect(resultText(result),'SINGLE_FILE_GREP_HAS_A_FILENAME_BOUNDARY').toBe('notes/ithaca.md:3:Odysseus sails home.\n'); }); + + test('grep model text is byte-identical to ordinary grep directory output',async()=>{ + const result=await run(grepTool(kit({exec:{}})),{pattern:'Odysseus',path:'notes'}); + const proc=Bun.spawn(['grep','-rInE','--','Odysseus','notes'],{cwd:root,stdout:'pipe',stderr:'pipe'}); + const old=await new Response(proc.stdout).text();expect(await proc.exited).toBe(0); + expect(resultText(result),'MODEL_VISIBLE_GREP_BYTES_MATCH_OLD_FORMAT').toBe(old); + expect((result.details as {search:{framedOutput:string}}).search.framedOutput,'EXACT_FILENAME_FRAME_IS_HOST_ONLY').toBe(old.replace(':3:',':\0'+'3:')); + expect(resultText(result)).not.toContain('\0'); + }); diff --git a/packages/ui-backend-pi/tests/worker-host-exec.test.ts b/packages/ui-backend-pi/tests/worker-host-exec.test.ts index 2a61c4e6e4..5a134e5d36 100644 --- a/packages/ui-backend-pi/tests/worker-host-exec.test.ts +++ b/packages/ui-backend-pi/tests/worker-host-exec.test.ts @@ -60,7 +60,7 @@ for (const profile of ["governed", "strict", "restricted"] as const) { })).session; const report = JSON.parse(session.model!.id); expect(report.error, "HOST_HELPER_VISIBLE_IN_WORKER").toBeUndefined(); - expect(report.grep).toContain("voyage.md:\0"+"1:The wine-dark sea"); + expect(report.grep).toContain("voyage.md:1:The wine-dark sea"); expect(report.bash).toBe("Ithaca"); const wrapped = report.wrapperLog.split("\n"); expect(wrapped, "WORKER_TOOLS_USED_HOST_WRAPPER").toEqual(expect.arrayContaining(["-rHInZE", "wine-dark", "--noprofile", "--norc", "-c", "echo Ithaca", "sleep 30"])); diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index e75a09a60a..a3151f321d 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -253,8 +253,9 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str value.totalMatches!==undefined&&value.totalMatches!==value.numFiles||value.countIsComplete===true&&value.totalMatches===undefined)unknown=true;} }else if((context?.backendId??'claude')==='claude'&&tool==='Grep'){ const checked=grepOutput.safeParse(parsed),mode=context?.outputMode; - if(!checked.success||!['files_with_matches','content','count'].includes(mode??'')){unknown=true;salvage(parsed,mode);} + if(!checked.success||!['files_with_matches','content','count'].includes(mode??'')){unknown=true;salvage(parsed,mode);if(parsed&&typeof parsed==='object'&&'mode' in parsed)salvage(parsed,String(parsed.mode));} else {const value=checked.data;for(const path of value.filenames)add(path); + if(value.mode!==undefined&&value.mode!==mode)salvage(value,value.mode); const lines=mode==='files_with_matches'?value.filenames.length:value.content?value.content.split('\n').length:0; const total=mode==='content'?value.totalLines:value.totalFiles; const limits=[value.appliedLimit??0,context?.limit??250]; @@ -267,7 +268,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str limits.some(limit=>limit>0&&(lines>limit||lines===limit&&total===undefined))|| value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines)unknown=true; let matches=mode==='files_with_matches'?value.numFiles:lines; - if(mode==='files_with_matches'){if(value.content!==undefined&&value.content!=='')unknown=true;} + if(mode==='files_with_matches'){if(value.content!==undefined&&value.content!==''){unknown=true;salvage(value,value.mode==='count'?'count':'content');}} else if(value.content===undefined)unknown=true; else { if(!value.content&&value.numFiles>0)unknown=true; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index ecb48a0c5f..83a76f070d 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -143,8 +143,13 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option try{ if(segments&&segments.length>256)throw new Error("Safety result segment capacity exceeded"); const op=operations.get(toolUseId);if(!op||op.tool!==tool||!op.admitted)throw new Error("Safety result has no admitted operation"); - const outputHash=hash(JSON.stringify([output,finalized,segments??null])); - if(op.done){if(op.outputHash!==outputHash)throw new Error("Conflicting safety result delivery");return;} + const outputHash=hash(JSON.stringify([output,finalized,segments??null,outputStatus??null])); + const conflicting=op.done&&op.outputHash!==outputHash; + if(op.done&&!conflicting)return; + if(conflicting){ + op.uncertain=true; + if(!op.owed){await writes.safetyOblige(options.turnId,op.id,toolUseId,tool);op.owed=true;} + } // Each separately delivered external result segment has its own exposure. for(const _segment of (segments??[]).slice(1))for(const signal of op.signals.filter(signal=>["compute_input","external_mcp_input","attachment_input","tool_web_input"].includes(signal.detector))){ const item=observed(toolUseId,signal.detector,op.id); @@ -169,6 +174,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option if(last&&stored.discharged)op.owed=false; } op.done=true;op.outputHash=outputHash; + if(conflicting)throw new Error("Conflicting safety result delivery"); // A result with nothing to record is recorded by its discharge alone. A // discharge that cannot commit stays owed, which only gaps the chat; it // is no loss of this record. diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 7a7cd68dd5..24c6467005 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -83,6 +83,7 @@ for(const [name,tool,input,output,expected] of [ ['Grep omitted lines','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',numLines:1,totalLines:2}),['legacy_unknown']], ['Grep offset','Grep',{offset:1},grep([]),['legacy_unknown']], ['Grep count colon filename','Grep',{output_mode:'count'},grep(['notes/voyage:2'],{content:'notes/voyage:2:7'}),['user_marked']], + ['Grep mode mismatch salvages content','Grep',{output_mode:'files_with_matches'},grep([],{mode:'content',content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked','legacy_unknown']], ['Grep numbered content','Grep',{output_mode:'content'},grep(['notes/voyage.md'],{content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked']], ['Grep ambiguous content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage:2:7:sirens',numLines:1}),['user_marked','legacy_unknown']], ['Pi exact sentinel','grep',{},'No matches.',[]], diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index c136fc1d6e..1892f458f8 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -9,7 +9,7 @@ import { safetyResultInput } from "../../ui-backend-pi/src/worker-protocol"; * `safety-result-retention.test.ts`; these drive the remaining exits against * the real host ledger. Keyless and offline. */ import { afterEach, expect, test } from "bun:test"; -import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import {createRequire} from "node:module"; @@ -584,21 +584,20 @@ test('shipped Pi grep preserves a marked newline filename through the worker led }); for(const mode of ['file','empty','regex','partial','warning'] as const)test(`Pi after-tool RPC preserves grep status: ${mode}`,async()=>{ - const f=await voyage();let unreadable:string|undefined;try{ + const f=await voyage();try{ const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); mkdirSync(join(f.brain,'notes')); writeFileSync(join(f.brain,'notes/loom.md'),'nymph_signal\n'); if(mode==='partial'){ - unreadable=join(f.brain,'notes/raft.md');writeFileSync(unreadable,'nymph_signal\n');chmodSync(unreadable,0); untrustedMarkOperations(f.db).mark('notes/loom.md',null,Date.UTC(2026,6,12)); } - const wrapper=mode==='warning'?join(f.brain,'warning-wrapper'):undefined; - if(wrapper)writeFileSync(wrapper,'#!/bin/sh\nprintf "search warning\\n" >&2\nexec "$@"\n',{mode:0o755}); + const wrapper=['warning','partial'].includes(mode)?join(f.brain,'grep-wrapper'):undefined; + if(wrapper)writeFileSync(wrapper,mode==='partial'?"#!/bin/sh\nprintf \"notes/loom.md\\0001:nymph_signal\\n\"\nprintf \"search error\\n\" >&2\nexit 2\n":"#!/bin/sh\nprintf \"search warning\\n\" >&2\nexec \"$@\"\n",{mode:0o755}); const input={pattern:mode==='regex'?'[':mode==='empty'?'no_cyclops_here':'nymph_signal',...(mode==='file'?{path:'notes/loom.md'}:{})},id='status_search'; await f.collector.begin(id,'grep',input); const actual=await runSearchTool(f,id,input,wrapper); const expectedCode=mode==='empty'?1:mode==='regex'||mode==='partial'?2:0; - expect((actual.details as {search:unknown}).search,'GREP_EXIT_STATUS_AND_STDERR_ARE_OBSERVED').toEqual({exitCode:expectedCode,stderr:['regex','partial','warning'].includes(mode),truncated:false}); + expect((actual.details as {search:unknown}).search,'GREP_EXIT_STATUS_AND_STDERR_ARE_OBSERVED').toMatchObject({exitCode:expectedCode,stderr:['regex','partial','warning'].includes(mode),truncated:false}); let stopped=false,forwarded:unknown; const agent={abort(){stopped=true;},streamFunction:async()=>{}} as unknown as Agent; const dispatch=dispatcher(f); @@ -614,5 +613,17 @@ for(const mode of ['file','empty','regex','partial','warning'] as const)test(`Pi {source:'user_marked',detector:'explicit_untrusted_input'},{source:'legacy_unknown',detector:'tool_search_output'} ]:incomplete?[{source:'legacy_unknown',detector:'tool_search_output'}]:[]); expect(f.chat().restriction).toBe(incomplete?'restricted':'normal'); - }finally{if(unreadable)chmodSync(unreadable,0o600);await f.close();} + }finally{await f.close();} +}); + +for(const status of [{complete:false},{complete:true,truncated:true}])test(`a stricter repeated result reopens its obligation: ${JSON.stringify(status)}`,async()=>{ + const f=await voyage();try{ + await f.collector.begin('status_conflict','grep',{}); + await f.collector.result('status_conflict','grep','No matches.',true,undefined,{complete:true,exitCode:1,stderr:false,truncated:false}); + expect(f.owed()).toBe(0); + await refusal(f.collector.result('status_conflict','grep','No matches.',true,undefined,{exitCode:1,stderr:false,truncated:false,...status})); + expect(f.owed(),'CONFLICTING_STATUS_REOPENS_DISCHARGED_RESULT').toBe(1); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all(),'STRICTER_STATUS_RETAINS_UNKNOWN_EVIDENCE').toEqual([{source:'legacy_unknown',detector:'tool_search_output'}]); + expect(f.chat().coverage.state,'CONFLICTING_STATUS_CANNOT_LEAVE_COMPLETE_COVERAGE').toBe('incomplete'); + }finally{await f.close();} }); From 83f9de9fadddea85822ca8fa9acf3ad93e9db828 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:44:54 +0000 Subject: [PATCH 11/23] fix: bind search framing to delivered trimmed text --- docs/integration-contract/package-api.md | 6 ++- packages/ui-backend-pi/src/file-tools.ts | 20 ++++++--- packages/ui-backend-pi/src/worker-protocol.ts | 8 ++-- .../tests/fixtures/grep-before-safety.ts | 45 +++++++++++++++++++ .../tests/tool-factories.test.ts | 10 ++--- packages/ui-server/src/activity/recorder.ts | 4 +- .../tests/ingestion-taint-schema.test.ts | 2 + .../ui-server/tests/ingestion-taint.test.ts | 13 ++++++ .../tests/safety-result-exits.test.ts | 17 +++++++ 9 files changed, 110 insertions(+), 15 deletions(-) create mode 100644 packages/ui-backend-pi/tests/fixtures/grep-before-safety.ts diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 9558cdd774..48c0fed062 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5971,7 +5971,11 @@ reference read. Pi carries the original tool status through its result hook and worker RPC. Exit 1 with empty stdout and no stderr is its only empty sentinel; exit 0 requires matches. Missing search status is restrictive. Pi keeps NUL filename framing in host-only result details; provider text retains -the advertised `path:line:content` format. Neither metadata nor completeness is +the advertised `path:line:content` format, with the existing trim-then-clip +pipeline. Hidden frame separators do not consume the delivered text budget; +an inconsistent frame cannot replace the paths in delivered text. Display-only +result frames cannot establish the verified empty-search exemption. +Neither metadata nor completeness is encoded by changing result text, and neither changes prior provider history. The same-commit API report records the additive argument. diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index e4f6bffccd..eb1fde18c8 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -75,11 +75,21 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { // POSIX filenames may contain newlines, colons and edge whitespace. // This changes result data only; provider tool definitions stay identical. const empty=exitCode===1&&out.length===0&&stderr.length===0; - const framedOutput=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; - // Only the host observation carries framing; provider text keeps the - // advertised path:line:content format, byte for byte for ordinary paths. - const text=empty?"No matches.":out.replaceAll("\0", ":")||"Search output unavailable."; - return textResult(clip(text), {pattern:params.pattern,search:{exitCode,stderr:stderr.length>0,truncated:framedOutput.length>MAX_OUTPUT_BYTES,framedOutput:clip(framedOutput)}}); + const frame=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; + const rawText=frame.replaceAll("\0", ""),text=rawText.trim(); + const visibleText=clip(text),truncated=text.length>MAX_OUTPUT_BYTES; + // Frame every character actually delivered before clip's annotation. + // Hidden separators do not consume the visible budget. Preserve raw + // filename whitespace and the final row terminator for host lookup. + let end=frame.length; + if(truncated){ + const limit=rawText.length-rawText.trimStart().length+MAX_OUTPUT_BYTES; + let visible=0;end=0; + while(end0,truncated,framedOutput:frame.slice(0,end),visibleText}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 084fa7b813..7d79d48067 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -3,6 +3,7 @@ import { WORKER_SCRATCH } from "@schlessera/brain-ui-sdk/internal"; import { FIRST_PARTY_FAILURE_CLASSES, type StateRoomObservation } from "@schlessera/brain-ui-sdk/protocol"; import { z } from "zod"; import type { Readable, Writable } from "node:stream"; +import { MAX_OUTPUT_BYTES } from "./tool-kit.js"; // Internal protocol. A worker can propose inputs, never a decision or authority. export const PI_PIPE_MAX_BYTES = 16 * 1024 * 1024; @@ -89,7 +90,7 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ export type PiWorkerMessage = z.infer; export const piOutputStatus=z.object({complete:z.boolean(),exitCode:z.number().int().optional(),stderr:z.boolean().optional(),truncated:z.boolean().optional()}).strict(); -const searchStatus=z.object({exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional()}).strict(); +const searchStatus=z.object({exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional(),visibleText:z.string().optional()}).strict(); /** Host-only observation. Never alter provider result content to encode status. */ export function safetyResultInput(tool:string,content:readonly {type:string;text?:unknown}[],complete=true,details?:unknown): {output:string;segments?:string[];outputStatus:z.infer} { const segments=content.filter(part=>part.type==='text'&&typeof part.text==='string').map(part=>part.text as string),output=segments.join('\n'); @@ -97,11 +98,12 @@ export function safetyResultInput(tool:string,content:readonly {type:string;text const status=searchStatus.safeParse(details&&typeof details==='object'?(details as Record).search:undefined); const original=complete&&content.length===1&&content[0]?.type==='text'&&typeof content[0]?.text==='string'; const framed=status.success?status.data.framedOutput:undefined; - const bound=framed===undefined?output==='No matches.':framed.replaceAll('\0','')===output; + const rendered=framed?.replaceAll('\0','').trim(); + const bound=framed===undefined?output==='No matches.':status.success&&status.data.truncated?status.data.visibleText===output&&framed.replaceAll('\0','').trimStart()===output.slice(0,MAX_OUTPUT_BYTES):rendered===output; const successful=bound&&status.success&&!status.data.stderr&&!status.data.truncated&& (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&output==='No matches.'); const processStatus=status.success?{exitCode:status.data.exitCode,stderr:status.data.stderr,truncated:status.data.truncated}:{}; - return {output:framed??output,segments,outputStatus:{...processStatus,complete:original&&successful}}; + return {output:bound?(framed??output):output,segments,outputStatus:{...processStatus,complete:original&&successful}}; } // Reference reads require every original segment; omission never proves a read. if(tool==='reference_read'&&(!complete||content.some(part=>part.type!=='text'||typeof part.text!=='string')))return {output,outputStatus:{complete:false}}; diff --git a/packages/ui-backend-pi/tests/fixtures/grep-before-safety.ts b/packages/ui-backend-pi/tests/fixtures/grep-before-safety.ts new file mode 100644 index 0000000000..d5097d624f --- /dev/null +++ b/packages/ui-backend-pi/tests/fixtures/grep-before-safety.ts @@ -0,0 +1,45 @@ +/** Pre-safety grepTool implementation, copied verbatim from main + * 134c0eee935f1c88ddbef5f1f59aee8b2363fe3a for byte-compatibility proof. */ +import { spawn } from "bun"; +import { Type } from "typebox"; +import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; +import {killWrapped,wrapCommand} from "@schlessera/brain-ui-sdk/server"; +import {execWrapperSpawnOptions,WORKER_EGRESS_TRANSPORT_ENV} from "@schlessera/brain-ui-sdk/internal"; +import {resolveEnabledWebSearchEnvNames,ambientExecConfig,subprocessEnv} from "../../src/config/env.js"; +import {clip,textResult,type BrainToolKit} from "../../src/tool-kit.js"; +export function baselineGrepTool(kit: BrainToolKit): ToolDefinition { + const { deps, brain, resolveOrThrow } = kit; + return { + name: "grep", + label: "Grep", + description: + "Search file contents in the brain repository with a regular expression. " + + "Returns matching lines as `path:line: text`.", + parameters: Type.Object({ + pattern: Type.String({ description: "Regular expression to search for." }), + path: Type.Optional( + Type.String({ description: "Repo-relative subtree to search (default: whole repo)." }) + ), + }), + async execute(_id: string, params: { pattern: string; path?: string }, signal?: AbortSignal) { + // Containment: scope the search path to the repo; grep runs with cwd=repo. + const rel = params.path ?? "."; + resolveOrThrow(rel); + const exec = deps.exec ?? ambientExecConfig(); + const proc = spawn(wrapCommand(["grep", "-rInE", "--", params.pattern, rel], exec.wrapper), { + cwd: brain.root, + env: subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]), + stdout: "pipe", + stderr: "pipe", + ...execWrapperSpawnOptions(exec.wrapper), + }); + const onAbort = () => killWrapped(proc, exec); + signal?.addEventListener("abort", onAbort, { once: true }); + const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); + signal?.removeEventListener("abort", onAbort); + const text = out.trim(); + return textResult(text ? clip(text) : "No matches.", { pattern: params.pattern }); + }, + } satisfies ToolDefinition; +} + diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts index 423ea10287..83546e31d6 100644 --- a/packages/ui-backend-pi/tests/tool-factories.test.ts +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -18,6 +18,7 @@ import { createBrainToolKit, type BrainToolKit } from "../src/tool-kit"; import { toolLockFromKeyed, type BrainToolDeps } from "../src/tools"; import { createTurnContext } from "../src/turn-context"; import { resultText } from "./helpers"; +import {baselineGrepTool} from "./fixtures/grep-before-safety"; import { makeMockBridge } from "./mock-bridge"; const CTX = {} as never; @@ -73,7 +74,7 @@ test("readFileTool reads one contained file and returns its base on a routed tur test("grepTool searches the repository and names each match", async () => { const result = await run(grepTool(kit({ exec: {} })), { pattern: "Odysseus" }); - expect(resultText(result)).toBe("./notes/ithaca.md:3:Odysseus sails home.\n"); + expect(resultText(result)).toBe("./notes/ithaca.md:3:Odysseus sails home."); expect(resultText(await run(grepTool(kit({ exec: {} })), { pattern: "Cyclops" }))).toBe("No matches."); }); @@ -196,14 +197,13 @@ test('grepTool never reports a failed regular expression as an empty search',asy test('grepTool prefixes a single file operand with its exact filename',async()=>{ const result=await run(grepTool(kit({exec:{}})),{pattern:'Odysseus',path:'notes/ithaca.md'}); - expect(resultText(result),'SINGLE_FILE_GREP_HAS_A_FILENAME_BOUNDARY').toBe('notes/ithaca.md:3:Odysseus sails home.\n'); + expect(resultText(result),'SINGLE_FILE_GREP_HAS_A_FILENAME_BOUNDARY').toBe('notes/ithaca.md:3:Odysseus sails home.'); }); test('grep model text is byte-identical to ordinary grep directory output',async()=>{ const result=await run(grepTool(kit({exec:{}})),{pattern:'Odysseus',path:'notes'}); - const proc=Bun.spawn(['grep','-rInE','--','Odysseus','notes'],{cwd:root,stdout:'pipe',stderr:'pipe'}); - const old=await new Response(proc.stdout).text();expect(await proc.exited).toBe(0); + const old=resultText(await run(baselineGrepTool(kit({exec:{}})),{pattern:'Odysseus',path:'notes'})); expect(resultText(result),'MODEL_VISIBLE_GREP_BYTES_MATCH_OLD_FORMAT').toBe(old); - expect((result.details as {search:{framedOutput:string}}).search.framedOutput,'EXACT_FILENAME_FRAME_IS_HOST_ONLY').toBe(old.replace(':3:',':\0'+'3:')); + expect((result.details as {search:{framedOutput:string}}).search.framedOutput,'EXACT_FILENAME_FRAME_IS_HOST_ONLY').toBe(old.replace(':3:',':\0'+'3:')+'\n'); expect(resultText(result)).not.toContain('\0'); }); diff --git a/packages/ui-server/src/activity/recorder.ts b/packages/ui-server/src/activity/recorder.ts index 34a8e531fd..e29459a5c5 100644 --- a/packages/ui-server/src/activity/recorder.ts +++ b/packages/ui-server/src/activity/recorder.ts @@ -382,7 +382,9 @@ export function createTurnRecorder( ingestions.delete(msg.toolUseId); let signals:IngestionSignal[]=[]; if(!safetyHooked&&ingestion){ - try { signals=[...ingestion.signals,...outputTaintSignals(ingestion.tool,msg.output,deps.brainPath,marked,ingestion.searchContext)]; } + // Display bytes cannot verify a backend's original result parts. + // Only structured collection can establish an empty Pi search. + try { signals=[...ingestion.signals,...outputTaintSignals(ingestion.tool,msg.output,deps.brainPath,marked,{...ingestion.searchContext,outputComplete:msg.output==="No matches."?false:undefined})]; } catch { deps.abort?.(new Error("Safety result detection failed; the turn was stopped."));if(governanceWrites)writes.after(()=>governanceWrites.safetyFail(runId)); } } if (!safetyHooked && ingestion && signals.length && !traced?.denied && firstTaint && deps.governance) { diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 24c6467005..030e148486 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -54,6 +54,8 @@ for(const [name,tool,input,output,expected] of [ ['Pi sentinel incomplete original','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],false),['legacy_unknown']], ['Pi marked row plus image','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/voyage.md:1:sirens'},{type:'image'}]),['user_marked','legacy_unknown']], ['Pi sentinel plus empty block','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'text',text:''}]),['legacy_unknown']], + ['Pi inconsistent frame salvages visible path','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/voyage.md:1:sirens'}],true,{search:{exitCode:0,stderr:false,truncated:false,framedOutput:'notes/loom.md:\0'+'1:echo\n'}}),['user_marked','legacy_unknown']], + ['Pi truncated frame cannot omit visible paths','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/loom.md:1:echo\nnotes/voyage.md:1:sirens'}],true,{search:{exitCode:0,stderr:false,truncated:true,framedOutput:'notes/loom.md:\0'+'1:echo\n',visibleText:'notes/loom.md:1:echo\nnotes/voyage.md:1:sirens'}}),['user_marked','legacy_unknown']], ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],true,{search:{exitCode:1,stderr:false,truncated:false}}),[]], ['Grep duplicate per-file count rows','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:1\nnotes/loom.md:1',numMatches:2}),['legacy_unknown']], ['Pi newline filename ambiguity is never healthy legacy evidence','grep',{},'./raft:1:sail\nloom.md:1:sirens',['legacy_unknown']], diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index ebd5027d82..9bedda23b9 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -136,3 +136,16 @@ test('the display recorder uses admitted Claude filename mode for colon paths',a expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source),'RECORDER_PRESERVES_ADMITTED_SEARCH_FORMAT').toEqual(['user_marked']); }finally{recorder.finish('success');db.close();} }); + +test('display-only grep sentinel never proves complete empty evidence',()=>{ + const output='No matches.'; + const db=createUiDb(':memory:');const sessionId='ithaca-display';db.query("INSERT INTO sessions(id,created_at,last_active_at) VALUES(?,0,0)").run(sessionId); + const recorder=createTurnRecorder({store:createActivityStore(db,{writer:'test'}),governanceDb:db,brainPath:brain,governance:event=>{recordGovernanceEvent(db,event);}},{turnId:'voyage-display',sessionId,profile:'governed'}); + try{ + recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'display_grep',toolName:'grep'}); + recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'display_grep',toolName:'grep',input:{pattern:'sirens'}}); + recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'display_grep',output,isError:false}); + expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(event=>event.payload.source),'DISPLAY_TEXT_CANNOT_VERIFY_ORIGINAL_EMPTY_RESULT').toEqual(['legacy_unknown']); + recorder.finish('success'); + }finally{db.close();} +}); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 1892f458f8..eba629813f 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -627,3 +627,20 @@ for(const status of [{complete:false},{complete:true,truncated:true}])test(`a st expect(f.chat().coverage.state,'CONFLICTING_STATUS_CANNOT_LEAVE_COMPLETE_COVERAGE').toBe('incomplete'); }finally{await f.close();} }); + +test('clipped Pi observation checks every marked filename still delivered to the model',async()=>{ + const f=await voyage();try{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + untrustedMarkOperations(f.db).mark('notes/raft\nloom.md',null,Date.UTC(2026,6,12)); + let raw='';while(raw.replaceAll('\0',':').trim().length<29800)raw+='notes/loom.md\0'+'1:a\n'; + raw+='notes/raft\nloom.md\0'+'1:sirens\n'+('notes/loom.md\0'+'1:a\n').repeat(100); + const wrapper=join(f.brain,'fake-grep');writeFileSync(join(f.brain,'grep-data'),raw); + writeFileSync(wrapper,'#!/bin/sh\ncat "$(dirname "$0")/grep-data"\n',{mode:0o755}); + const input={pattern:'sirens'},id='clipped';await f.collector.begin(id,'grep',input); + const result=await runSearchTool(f,id,input,wrapper); + expect(result.content[0]?.type==='text'&&result.content[0].text,'MARKED_FILENAME_REALLY_REACHED_MODEL').toContain('notes/raft\nloom.md:1:sirens'); + const observed=safetyResultInput('grep',result.content,true,result.details); + await f.collector.result(id,'grep',observed.output,true,observed.segments,observed.outputStatus); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all(),'ALL_DELIVERED_PATHS_ARE_CHECKED_DESPITE_FRAME_OVERHEAD').toEqual([{source:'user_marked',detector:'explicit_untrusted_input'},{source:'legacy_unknown',detector:'tool_search_output'}]); + }finally{await f.close();} +}); From 8cb9b46e063bd3c5eb3dfaf5d7e97e7997dcd28d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 19:58:49 +0000 Subject: [PATCH 12/23] CONTRACT: preserve process evidence through every result wrapper --- docs/integration-contract/package-api.md | 8 ++- packages/ui-backend-pi/src/file-tools.ts | 9 ++- packages/ui-backend-pi/src/worker-protocol.ts | 2 +- packages/ui-sdk/src/server/backend.ts | 3 +- .../ui-server/src/activity/ingestion-taint.ts | 9 +++ .../ui-server/src/brain/turn-extraction.ts | 17 +++--- .../src/governance/safety-collector.ts | 7 +-- .../tests/input-safety-forwarders.test.ts | 35 ++++++++++++ .../ui-server/tests/safety-ledger.test.ts | 4 +- .../tests/safety-result-exits.test.ts | 57 +++++++++++++++++-- 10 files changed, 128 insertions(+), 23 deletions(-) create mode 100644 packages/ui-server/tests/input-safety-forwarders.test.ts diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 48c0fed062..165b5d1f2f 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5963,13 +5963,19 @@ and optional `exitCode: number`, `stderr: boolean`, `truncated: boolean`. `stderr` records presence, never the error bytes. This is host-only evidence, not a provider-facing tool definition or a permission grant. -Omission preserves the existing collection behavior. `complete: false`, a +Omission grants no success or empty-search exemption: Pi grep without explicit +process status retains unknown evidence. Other observations preserve their +existing behavior or become stricter. `complete: false`, a failed search exit, stderr or truncation retains an unknown search remainder alongside every identifiable source. It is independent of the existing `finalized` exposure argument; incomplete evidence cannot prove a managed reference read. Pi carries the original tool status through its result hook and worker RPC. Exit 1 with empty stdout and no stderr is its only empty sentinel; exit 0 requires matches. Missing search status is restrictive. +Every wrapper forwards the complete typed callback tuple. Extraction also +withholds its relaxation when result evidence is incomplete. Status identity +uses canonical key order, and host frames have an independent byte bound; +clipping that frame retains unknown instead of overflowing collection. Pi keeps NUL filename framing in host-only result details; provider text retains the advertised `path:line:content` format, with the existing trim-then-clip pipeline. Hidden frame separators do not consume the delivered text budget; diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index eb1fde18c8..6422c8029d 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -77,19 +77,22 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const empty=exitCode===1&&out.length===0&&stderr.length===0; const frame=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; const rawText=frame.replaceAll("\0", ""),text=rawText.trim(); - const visibleText=clip(text),truncated=text.length>MAX_OUTPUT_BYTES; + const visibleText=clip(text),displayTruncated=text.length>MAX_OUTPUT_BYTES; // Frame every character actually delivered before clip's annotation. // Hidden separators do not consume the visible budget. Preserve raw // filename whitespace and the final row terminator for host lookup. let end=frame.length; - if(truncated){ + if(displayTruncated){ const limit=rawText.length-rawText.trimStart().length+MAX_OUTPUT_BYTES; let visible=0;end=0; while(end0,truncated,framedOutput:frame.slice(0,end),visibleText}}); + const bytes=Buffer.from(frame.slice(0,end)),frameClipped=bytes.length>1048576; + // Leave room for a decoder replacement if the byte cut splits UTF-8. + const framedOutput=frameClipped?bytes.subarray(0,1048573).toString('utf8'):frame.slice(0,end); + return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr:stderr.length>0,truncated:displayTruncated||frameClipped,framedOutput,visibleText}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 7d79d48067..ebc2652c28 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -99,7 +99,7 @@ export function safetyResultInput(tool:string,content:readonly {type:string;text const original=complete&&content.length===1&&content[0]?.type==='text'&&typeof content[0]?.text==='string'; const framed=status.success?status.data.framedOutput:undefined; const rendered=framed?.replaceAll('\0','').trim(); - const bound=framed===undefined?output==='No matches.':status.success&&status.data.truncated?status.data.visibleText===output&&framed.replaceAll('\0','').trimStart()===output.slice(0,MAX_OUTPUT_BYTES):rendered===output; + const bound=framed===undefined?output==='No matches.':status.success&&status.data.truncated?status.data.visibleText===output&&(output.length>MAX_OUTPUT_BYTES?framed.replaceAll('\0','').trimStart()===output.slice(0,MAX_OUTPUT_BYTES):rendered===output):rendered===output; const successful=bound&&status.success&&!status.data.stderr&&!status.data.truncated&& (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&output==='No matches.'); const processStatus=status.success?{exitCode:status.data.exitCode,stderr:status.data.stderr,truncated:status.data.truncated}:{}; diff --git a/packages/ui-sdk/src/server/backend.ts b/packages/ui-sdk/src/server/backend.ts index ae633b903f..e39611a35f 100644 --- a/packages/ui-sdk/src/server/backend.ts +++ b/packages/ui-sdk/src/server/backend.ts @@ -199,7 +199,8 @@ export interface BackendBridge { unavailable?(): Promise; begin(toolUseId: string, toolName: string, input: Readonly>): Promise; /** `outputStatus.complete:false` retains an unknown search remainder even when - * known rows were delivered. Omission preserves the existing behavior; + * known rows were delivered. Omission grants no success exemption; + * process-qualified search without status remains unknown, and * it is independent of the result's finalized exposure lifecycle. */ result(toolUseId: string, toolName: string, output: string, finalized: boolean, segments?: readonly string[], outputStatus?: InputSafetyOutputStatus): Promise; /** @internal A tool ran, but its result report was refused before `result` diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index a3151f321d..a74ca7f3c6 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -1,6 +1,7 @@ /** Which completed tool calls ingested untrusted content (G6); this grants no tool authority. */ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { z } from "zod"; +import type {InputSafetyOutputStatus} from "@schlessera/brain-ui-sdk/server"; import { posix } from "node:path"; import { WORKER_AREA_ROOT, WORKER_REFERENCE_ROOT, WORKER_WORKTREE_ROOT } from "@schlessera/brain-ui-sdk/internal"; import { commandTaintSource } from "./command-taint.js"; @@ -186,6 +187,14 @@ const grepOutput = z.object({ mode: z.enum(['content','files_with_matches','coun filenames: z.array(z.string()), content: z.string().optional(), numLines: natural.optional(), numMatches: natural.optional(), totalFiles: natural.optional(), totalLines: natural.optional(), appliedLimit: natural.optional(), appliedOffset: natural.optional() }).strict(); +/** Process evidence is mandatory for Pi search; omission never proves success. */ +export function searchOutputComplete(output:string,status:InputSafetyOutputStatus|undefined,requireProcess=false):boolean|undefined { + if(status===undefined)return requireProcess?false:undefined; + if(requireProcess&&(status.exitCode===undefined||status.stderr===undefined||status.truncated===undefined))return false; + return status.complete&&status.stderr!==true&&status.truncated!==true&& + (status.exitCode===undefined||status.exitCode===0&&output.length>0&&output!=="No matches."||status.exitCode===1&&output==="No matches."); +} + export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: SearchOutputContext): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; if(Buffer.byteLength(output)>1048576)throw new Error('Safety search output capacity exceeded'); diff --git a/packages/ui-server/src/brain/turn-extraction.ts b/packages/ui-server/src/brain/turn-extraction.ts index 4e171d776f..c1a9d51456 100644 --- a/packages/ui-server/src/brain/turn-extraction.ts +++ b/packages/ui-server/src/brain/turn-extraction.ts @@ -28,8 +28,8 @@ * never written to the record or the provider-facing conversation. */ import { prepareOutwardPlan } from "@schlessera/brain-ui-sdk/internal"; -import { requestToolPermission, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; -import { inputTaintSignals, outputTaintSignals, searchOutputContext } from "../activity/ingestion-taint.js"; +import { requestToolPermission, type BackendBridge, type InputSafetyOutputStatus } from "@schlessera/brain-ui-sdk/server"; +import { inputTaintSignals, outputTaintSignals, searchOutputContext, searchOutputComplete } from "../activity/ingestion-taint.js"; import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { existsSync } from "node:fs"; import { posix } from "node:path"; @@ -165,11 +165,12 @@ export function createTurnExtraction(options: { try { calls.set(toolUseId, await prior.outcome); } catch (error) { end(toolUseId); throw error; } }, - async result(toolUseId, tool, output, finalized, segments) { + async result(...args:Parameters) { + const [toolUseId,tool,output,,,outputStatus]=args; const input = inputs.get(toolUseId); end(toolUseId); inputs.delete(toolUseId); - try { await safety.result(toolUseId, tool, output, finalized, segments); } - finally { observe(tool, input, output); } + try { await safety.result(...args); } + finally { observe(tool, input, output, outputStatus); } }, refused(toolUseId, denied) { end(toolUseId); inputs.delete(toolUseId); return safety.refused?.(toolUseId, denied) ?? Promise.resolve(); }, }); @@ -180,16 +181,18 @@ export function createTurnExtraction(options: { return isWithin(root, absolute, { includeRoot: false }) ? absolute.slice(root.length + 1) : absolute; }; /** What the session read, and what its tainting content named. Never fails the call it observes. */ - const observe = (tool: string, input: unknown, output: string) => { + const observe = (tool: string, input: unknown, output: string, outputStatus?:InputSafetyOutputStatus) => { try { const current = session(); + const outputComplete=searchOutputComplete(output,outputStatus,tool==='grep'); + if(outputComplete===false)current.complete=false; const path = readPath(tool, input); if (path !== null) current.read(display(path), readText(output)); // Content from anywhere the host cannot vouch for: a fetch, a command // (its connections taint the session at the proxy), another MCP server, // an untrusted area or a marked file. const tainting = !localTool(tool) || inputTaintSignals(tool, input, options.brainPath, options.marked, true).length > 0 - || outputTaintSignals(tool, output, options.brainPath, options.marked, searchOutputContext(tool,input)).length > 0; + || outputTaintSignals(tool, output, options.brainPath, options.marked, {...searchOutputContext(tool,input),outputComplete}).length > 0; if (tainting) current.tainting(namedHosts(output)); } catch { state.complete = false; } }; diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index 83a76f070d..c820694f33 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -1,7 +1,7 @@ /** Concrete turn-bound pre-delivery collector. All decisions remain restrictive. */ import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import type { Database } from "bun:sqlite"; -import { inputTaintSignals, outputTaintSignals, searchOutputContext, type IngestionSignal } from "../activity/ingestion-taint.js"; +import { inputTaintSignals, outputTaintSignals, searchOutputComplete, searchOutputContext, type IngestionSignal } from "../activity/ingestion-taint.js"; import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { occurrence } from "./occurrence.js"; import type { GovernanceWrites } from "./event-writes.js"; @@ -143,7 +143,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option try{ if(segments&&segments.length>256)throw new Error("Safety result segment capacity exceeded"); const op=operations.get(toolUseId);if(!op||op.tool!==tool||!op.admitted)throw new Error("Safety result has no admitted operation"); - const outputHash=hash(JSON.stringify([output,finalized,segments??null,outputStatus??null])); + const outputHash=hash(JSON.stringify([output,finalized,segments??null,outputStatus===undefined?null:Object.fromEntries(Object.entries(outputStatus).sort(([a],[b])=>ab?1:0))])); const conflicting=op.done&&op.outputHash!==outputHash; if(op.done&&!conflicting)return; if(conflicting){ @@ -157,8 +157,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option } // Record output independently, before the backend releases it to the // model. Its bytes already exist, so a refusal here is never "before delivery". - const outputComplete=outputStatus===undefined?undefined:outputStatus.complete&&outputStatus.stderr!==true&&outputStatus.truncated!==true&& - (outputStatus.exitCode===undefined||outputStatus.exitCode===0&&output.length>0&&output!=="No matches."||outputStatus.exitCode===1&&output==="No matches."); + const outputComplete=searchOutputComplete(output,outputStatus,tool==='grep'&&options.backendId==='pi'); for(const signal of outputTaintSignals(tool,output,options.brainPath,marked,{...op.searchContext,outputComplete})){ const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}});op.occurrences.push(item.id); diff --git a/packages/ui-server/tests/input-safety-forwarders.test.ts b/packages/ui-server/tests/input-safety-forwarders.test.ts new file mode 100644 index 0000000000..183f086565 --- /dev/null +++ b/packages/ui-server/tests/input-safety-forwarders.test.ts @@ -0,0 +1,35 @@ +/** Inventory forwarding methods so optional collector arguments cannot disappear. */ +import {expect,test} from 'bun:test'; +import ts from 'typescript'; +import {fileURLToPath} from 'node:url'; + + test('every input-safety result wrapper forwards its typed argument tuple intact',async()=>{ + const root=fileURLToPath(new URL('../../../',import.meta.url)),found:string[]=[]; + for await(const path of new Bun.Glob('packages/*/src/**/*.ts').scan({cwd:root})){ + const source=ts.createSourceFile(path,await Bun.file(`${root}/${path}`).text(),ts.ScriptTarget.Latest,true); + const visit=(node:ts.Node)=>{ + const method=ts.isMethodDeclaration(node)&&node.name.getText(source)==='result'?node: + ts.isPropertyAssignment(node)&&node.name.getText(source)==='result'&&(ts.isArrowFunction(node.initializer)||ts.isFunctionExpression(node.initializer))?node.initializer:undefined; + if(method?.body){ + const calls:ts.CallExpression[]=[]; + const nested=(child:ts.Node)=>{if(ts.isCallExpression(child)&&ts.isPropertyAccessExpression(child.expression)&&child.expression.name.text==='result')calls.push(child);ts.forEachChild(child,nested);}; + nested(method.body); + if(calls.length){ + found.push(path); + expect(method.parameters.length,`${path}: wrapper keeps one typed rest tuple`).toBe(1); + const parameter=method.parameters[0]!; + expect(parameter.dotDotDotToken,`${path}: rest parameter is mandatory`).toBeDefined(); + expect(parameter.type?.getText(source),`${path}: signature tracks the SDK callback`).toBe('Parameters'); + for(const call of calls){ + expect(call.arguments.length,`${path}: no positional forwarding list`).toBe(1); + expect(ts.isSpreadElement(call.arguments[0]!),`${path}: spread every argument`).toBe(true); + expect(call.arguments[0]!.getText(source)).toBe(`...${parameter.name.getText(source)}`); + } + } + } + ts.forEachChild(node,visit); + }; + visit(source); + } + expect(found.sort(),'REVIEW_EVERY_NEW_RESULT_WRAPPER').toEqual(['packages/ui-server/src/brain/turn-extraction.ts']); + }); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 779516149f..0b707ba3cb 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -530,7 +530,7 @@ test("structured Glob paths preserve a marked colon filename",async()=>{ test("the Pi grep known empty result does not manufacture unknown input",async()=>{ const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca','pi'); await collector.begin('empty_grep','grep',{path:'.',pattern:'sirens'}); - await collector.result('empty_grep','grep','No matches.',true); + await collector.result('empty_grep','grep','No matches.',true,undefined,{complete:true,exitCode:1,stderr:false,truncated:false}); expect(triggers(f),'PI_EMPTY_GREP_CREATES_NO_SPURIOUS_TRIGGER').toHaveLength(0); expect(f.writes.safety(null,'ithaca').restriction).toBe('normal'); }finally{await f.close();} @@ -597,7 +597,7 @@ for(const [name,backend,tool,mode,output,expected] of [ test('Pi empty output never suppresses an independent untrusted input signal',async()=>{ const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca','pi'); await collector.begin('empty_workspace','grep',{path:'workspaces',pattern:'sirens'}); - await collector.result('empty_workspace','grep','No matches.',true); + await collector.result('empty_workspace','grep','No matches.',true,undefined,{complete:true,exitCode:1,stderr:false,truncated:false}); expect(triggers(f).map(r=>(r.payload as {source:string}).source)).toEqual(['workspace_read']); }finally{await f.close();} }); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index eba629813f..c09e4f03e1 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -138,10 +138,10 @@ test("a Pi result is still reported when the session's own after-hook fails", as let stopped = 0; const agent = { afterToolCall: async () => { throw new Error("the session's after-hook failed"); }, abort() {} } as unknown as Agent; installPiToolSafety(agent, { permission: async () => ({ behavior: "allow" }), stop: () => { stopped++; }, - result: (name, id, content) => f.collector.result(id, name, content.filter(p => p.type === "text").map(p => (p as { text: string }).text).join("\n"), true) }, () => false); + result: (name,id,content,complete,details)=>{const observation=safetyResultInput(name,content,complete,details);return f.collector.result(id,name,observation.output,true,observation.segments,observation.outputStatus);} }, () => false); expect((await refusal(agent.afterToolCall!({ toolCall: { name: "grep", id: "call_raft" }, result: { content: [{ type: "text", text: SEARCH }] } } as never, undefined)))?.message) .toBe("the session's after-hook failed"); - expect(f.recorded(), "SAFETY_PI_RESULT_SURVIVES_A_FAILED_AFTER_HOOK").toEqual([{ detector: "tool_search_output" }]); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all(), "SAFETY_PI_RESULT_SURVIVES_A_FAILED_AFTER_HOOK").toEqual([{source:"workspace_read",detector:"tool_search_output"},{source:"legacy_unknown",detector:"tool_search_output"}]); expect(stopped, "SAFETY_PI_FAILED_AFTER_HOOK_STOPS_THE_WORKER").toBe(1); } finally { await f.close(); } }); @@ -376,7 +376,7 @@ test("a result's last record discharges its call in the same commit, so a host d // Hold the collector the moment the result's exposure has committed. const record = f.writes.record; f.writes.record = async (...args: Parameters) => { const stored = await record(...args); if (args[0].kind === "taint_exposure") { committed(); await hold; } return stored; }; - reported = refusal(f.collector.result("call_raft", "grep", SEARCH, true)); + reported = refusal(f.collector.result("call_raft", "grep", SEARCH, true,undefined,{complete:true,exitCode:0,stderr:false,truncated:false})); await recorded; expect(f.db.query("SELECT kind,state FROM safety_records ORDER BY rowid").all(), "SAFETY_RESULT_RECORD_IS_DURABLE").toContainEqual({ kind: "exposure", state: "finalized" }); expect(f.owed(), "SAFETY_RECORDED_RESULT_IS_DISCHARGED_IN_ITS_OWN_COMMIT").toBe(0); @@ -403,7 +403,7 @@ test("a collection's end waits for a stopped turn's result record already under f.writes.record = async (...args: Parameters) => { if (args[0].kind === "taint_exposure") { reached(); await hold; } return record(...args); }; // Odysseus stops the turn as the result arrives; teardown then ends its collection. f.controller.abort(new Error("Odysseus stopped the turn as the result arrived")); - reported = refusal(f.collector.result("call_raft", "grep", SEARCH, true)); + reported = refusal(f.collector.result("call_raft", "grep", SEARCH, true,undefined,{complete:true,exitCode:0,stderr:false,truncated:false})); await midway; const ending = f.writes.safetyEnd("voyage"); // The writer applies its writes in order: had the end been sent, it is applied now. @@ -644,3 +644,52 @@ test('clipped Pi observation checks every marked filename still delivered to the expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all(),'ALL_DELIVERED_PATHS_ARE_CHECKED_DESPITE_FRAME_OVERHEAD').toEqual([{source:'user_marked',detector:'explicit_untrusted_input'},{source:'legacy_unknown',detector:'tool_search_output'}]); }finally{await f.close();} }); + + test('Pi legacy empty output without process status remains unknown',async()=>{ + const f=await voyage();try{ + await f.collector.begin('legacy_empty','grep',{}); + await f.collector.result('legacy_empty','grep','No matches.',true); + expect(f.db.query("SELECT source FROM safety_records WHERE kind='occurrence'").all(),'EMPTY_EXEMPTION_REQUIRES_EXPLICIT_EXIT_ONE_AND_EMPTY_STDERR').toEqual([{source:'legacy_unknown'}]); + }finally{await f.close();} + }); + test('status key order does not change result identity',async()=>{ + const f=await voyage();try{ + await f.collector.begin('canonical_status','grep',{}); + await f.collector.result('canonical_status','grep','No matches.',true,undefined,{complete:true,exitCode:1,stderr:false,truncated:false}); + await f.collector.result('canonical_status','grep','No matches.',true,undefined,{truncated:false,stderr:false,exitCode:1,complete:true}); + expect(f.owed(),'CANONICAL_STATUS_RETRY_STAYS_DISCHARGED').toBe(0); + expect(f.failure()).toBeNull(); + }finally{await f.close();} + }); + test('extraction result wrapper preserves process status and withholds incomplete evidence',async()=>{ + const f=await voyage();try{ + const {createTurnExtraction}=await import('../src/brain/turn-extraction'); + let forwarded:unknown;const original=f.collector.result; + f.collector.result=(...args)=>{forwarded=args[5];return original(...args);}; + const extraction=createTurnExtraction({bridge:{emit(){},requestPermission:async()=>({behavior:'allow'}),inputSafety:f.collector},origin:'interactive',sessionId:()=>null,tainted:()=>true,contacted:new Set(),cause:()=>null,brainPath:f.brain}); + const wrapped=extraction.inputSafety(f.collector)!; + await wrapped.begin('warning','grep',{pattern:'sirens'}); + await wrapped.result('warning','grep','notes/loom.md:\0'+'1:sirens\n',true,undefined,{complete:false,exitCode:0,stderr:true,truncated:false}); + expect(forwarded,'ALL_PROCESS_STATUS_FIELDS_SURVIVE_THE_WRAPPER').toEqual({complete:false,exitCode:0,stderr:true,truncated:false}); + expect(f.db.query("SELECT source FROM safety_records WHERE kind='occurrence'").all(),'WRAPPER_FORWARDS_UNKNOWN_REMAINDER_TO_LEDGER').toEqual([{source:'legacy_unknown'}]); + await wrapped.begin('fetch','WebFetch',{url:'https://aeaea.invalid/notice'}); + expect(extraction.relaxes('aeaea.invalid'),'EXTRACTION_CANNOT_RELAX_FROM_INCOMPLETE_RESULT').toBe(false); + }finally{await f.close();} + }); + test('trailing grep whitespace cannot exceed host observation limits',async()=>{ + const f=await voyage();try{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + untrustedMarkOperations(f.db).mark('notes/loom.md',null,Date.UTC(2026,6,12)); + const wrapper=join(f.brain,'fake-grep');writeFileSync(join(f.brain,'grep-data'),'notes/loom.md\0'+'1:sirens'+ ' '.repeat(2*1024*1024)+'\n'); + writeFileSync(wrapper,'#!/bin/sh\ncat "$(dirname "$0")/grep-data"\n',{mode:0o755}); + const input={pattern:'sirens'},id='whitespace';await f.collector.begin(id,'grep',input); + const result=await runSearchTool(f,id,input,wrapper); + expect(result.content[0]?.type==='text'&&result.content[0].text).toBe('notes/loom.md:1:sirens'); + const observed=safetyResultInput('grep',result.content,true,result.details); + expect(Buffer.byteLength(observed.output),'HOST_FRAME_IS_BOUNDED_IN_BYTES').toBeLessThanOrEqual(1048576); + expect(Buffer.byteLength(JSON.stringify(observed))).toBeLessThan(16*1024*1024); + await f.collector.result(id,'grep',observed.output,true,observed.segments,observed.outputStatus); + expect(f.db.query("SELECT source FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all()).toEqual([{source:'user_marked'},{source:'legacy_unknown'}]); + expect(f.failure()).toBeNull(); + }finally{await f.close();} + }); From f49bb40649c9600961af89b16f73193a7c18328d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 23:56:47 +0000 Subject: [PATCH 13/23] fix: preserve BOM filenames and trust structured search completeness --- packages/ui-backend-pi/src/file-tools.ts | 5 ++++- packages/ui-server/src/activity/ingestion-taint.ts | 2 -- .../ui-server/tests/ingestion-taint-schema.test.ts | 7 ++++++- .../ui-server/tests/safety-result-exits.test.ts | 13 +++++++++++++ 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 6422c8029d..55c12c250f 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -69,7 +69,10 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { }); const onAbort = () => killWrapped(proc, exec); signal?.addEventListener("abort", onAbort, { once: true }); - const [out, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + const [outBytes,stderrBytes,exitCode]=await Promise.all([new Response(proc.stdout).arrayBuffer(),new Response(proc.stderr).arrayBuffer(),proc.exited]); + // A leading BOM can be part of a POSIX filename, not stream metadata. + const decoder=new TextDecoder("utf-8",{ignoreBOM:true}); + const out=decoder.decode(outBytes),stderr=decoder.decode(stderrBytes); signal?.removeEventListener("abort", onAbort); // Keep an unambiguous machine boundary in host-only result details. // POSIX filenames may contain newlines, colons and edge whitespace. diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index a74ca7f3c6..deb6494b34 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -201,14 +201,12 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=context?.outputComplete===false; const add=(path:string)=>{ if(!path||path.includes('\0')){unknown=true;return;} - if(/truncat|omitted|\.\.\.|…/i.test(path))unknown=true; for(const signal of fileSignals(path,brainPath,marked,'tool_search_output')){ const key=JSON.stringify([signal.detector,signal.key]);if(seen.has(key))continue; if(result.length>=256)throw new Error('Safety search signal capacity exceeded');seen.add(key);result.push(signal); } }; const content=(text:string,numbers:boolean)=>{ - if(/truncat|omitted|\.\.\.|…/i.test(text))unknown=true; for(const line of text.split('\n')){ if(!line){unknown=true;continue;} let count=0; diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 030e148486..38f42cc00a 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -74,10 +74,15 @@ for(const [name,tool,input,output,expected] of [ ['Claude no line numbers','Grep',{output_mode:'content','-n':false},grep([],{content:'notes/voyage.md:signal:2:echo',numLines:1}),['user_marked','legacy_unknown']], ['marked exact Glob','Glob',{},glob(['notes/voyage:2:home.md']),['user_marked']], ['complete Glob','Glob',{},glob(['notes/loom.md']),[]], + ['Glob literal omission filename','Glob',{},glob(['notes/omitted.md'],{countIsComplete:true,totalMatches:1}),[]], + ['Glob literal truncation filename','Glob',{},glob(['notes/truncated.md'],{countIsComplete:true,totalMatches:1}),[]], + ['Grep literal omission content','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:omitted',numLines:1}),[]], + ['Grep literal omission count path','Grep',{output_mode:'count'},grep(['notes/omitted.md'],{content:'notes/omitted.md:2',numMatches:2}),[]], + ['Pi exact literal omission path','grep',{},'notes/omitted.md:\0'+'1:sirens\n',[]], ['Glob total omitted','Glob',{},glob(['notes/loom.md'],{totalMatches:2}),['legacy_unknown']], ['Glob lower bound','Glob',{},glob(['notes/loom.md'],{countIsComplete:false}),['legacy_unknown']], ['Glob truncated flag','Glob',{},glob(['notes/loom.md'],{truncated:true}),['legacy_unknown']], - ['Glob clipped filename','Glob',{},glob(['notes/voy...']),['legacy_unknown']], + ['Glob literal ellipsis filename','Glob',{},glob(['notes/voy...']),[]], ['Glob unknown key','Glob',{},glob([],{unexpected:true}),['legacy_unknown']], ['Glob invalid count','Glob',{},glob(['notes/loom.md'],{numFiles:0}),['legacy_unknown']], ['Glob missing fields','Glob',{},JSON.stringify({filenames:['notes/voyage.md']}),['user_marked','legacy_unknown']], diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index c09e4f03e1..c6323630fc 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -693,3 +693,16 @@ test('clipped Pi observation checks every marked filename still delivered to the expect(f.failure()).toBeNull(); }finally{await f.close();} }); + +test('Pi grep preserves a BOM-prefixed directory in the host filename evidence',async()=>{ + const f=await voyage();try{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + const folder='\ufeffvoyage',path=`${folder}/log.md`;mkdirSync(join(f.brain,folder));writeFileSync(join(f.brain,path),'sirens\n'); + untrustedMarkOperations(f.db).mark(path,null,Date.UTC(2026,6,12)); + const id='bom_search',input={pattern:'sirens',path:folder};await f.collector.begin(id,'grep',input); + const actual=await runSearchTool(f,id,input),observed=safetyResultInput('grep',actual.content,true,actual.details); + expect(observed.output,'GREP_DECODER_PRESERVES_FILENAME_BOM').toStartWith(path+':\0'); + await f.collector.result(id,'grep',observed.output,true,observed.segments,observed.outputStatus); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all()).toEqual([{source:'user_marked',detector:'explicit_untrusted_input'}]); + }finally{await f.close();} +}); From b4c2556edd422bfd9e43ca2f7f1184159a0baf69 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 01:00:57 +0000 Subject: [PATCH 14/23] fix: retain unknown extraction coverage and bound grep diagnostics --- docs/plans/reviewable-session-safety.md | 10 +++++----- packages/ui-backend-pi/src/file-tools.ts | 9 +++++---- packages/ui-backend-pi/tests/tool-factories.test.ts | 10 ++++++++++ packages/ui-server/src/brain/turn-extraction.ts | 6 ++++-- .../ui-server/tests/safety-result-exits.test.ts | 13 +++++++++++++ 5 files changed, 37 insertions(+), 11 deletions(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 60525a516a..8d6e52bfb9 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -25,12 +25,12 @@ public design or its fixtures. Fictional examples use the Odysseus world. - Taint recording retains every independently observed signal and reads a durable revisioned aggregate, including pending/failure and explicit unknown coverage (`safetyProjection`, - `packages/ui-server/src/governance/safety-store.ts:418-423`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:429-434`). Legacy rows prove their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, - `packages/ui-server/src/activity/ingestion-taint.ts:156`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:189`). + `packages/ui-server/src/activity/ingestion-taint.ts:157-174`; + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:198-301`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery; display frames alone never prove finalized delivery or complete coverage. Pi's shipped search @@ -41,7 +41,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. tool definition or any previously delivered provider history. - The turn proxy records each admitted non-provider connection and terminal exposure observation (`prepareTurnEgress`, - `packages/ui-server/src/brain/turn-egress.ts:86-295`). Relay admissions join + `packages/ui-server/src/brain/turn-egress.ts:87-296`). Relay admissions join this proxy's submitted terminal observations and its own announced session binding before reading fresh safety (`settleTurnSessionBinding`, `packages/ui-server/src/ws/bridge-session-binding.ts:14-28`), without excluding @@ -328,7 +328,7 @@ Attach to the exact tool/message entry only with authoritative correlation; otherwise use a separate turn-scoped network event, without blaming the nearest message. Examples of accessible names are **Safety restrictions: 2 unresolved triggers** and **Marked safe by you: show details**. Reuse the kit's icon map -(`ICONS`, `packages/ui-kit/src/primitives/Icon.tsx:145-207`). +(`ICONS`, `packages/ui-kit/src/primitives/Icon.tsx:151-213`). The transcript uses a compact safety notice, not an assistant-generated message or modal interruption. It records every new trigger even when another trigger diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 55c12c250f..88c07ea111 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -69,15 +69,16 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { }); const onAbort = () => killWrapped(proc, exec); signal?.addEventListener("abort", onAbort, { once: true }); - const [outBytes,stderrBytes,exitCode]=await Promise.all([new Response(proc.stdout).arrayBuffer(),new Response(proc.stderr).arrayBuffer(),proc.exited]); + const stderrPresent=(async()=>{let present=false;for await(const chunk of proc.stderr)if(chunk.byteLength)present=true;return present;})(); + const [outBytes,stderr,exitCode]=await Promise.all([new Response(proc.stdout).arrayBuffer(),stderrPresent,proc.exited]); // A leading BOM can be part of a POSIX filename, not stream metadata. const decoder=new TextDecoder("utf-8",{ignoreBOM:true}); - const out=decoder.decode(outBytes),stderr=decoder.decode(stderrBytes); + const out=decoder.decode(outBytes); signal?.removeEventListener("abort", onAbort); // Keep an unambiguous machine boundary in host-only result details. // POSIX filenames may contain newlines, colons and edge whitespace. // This changes result data only; provider tool definitions stay identical. - const empty=exitCode===1&&out.length===0&&stderr.length===0; + const empty=exitCode===1&&out.length===0&&!stderr; const frame=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; const rawText=frame.replaceAll("\0", ""),text=rawText.trim(); const visibleText=clip(text),displayTruncated=text.length>MAX_OUTPUT_BYTES; @@ -95,7 +96,7 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const bytes=Buffer.from(frame.slice(0,end)),frameClipped=bytes.length>1048576; // Leave room for a decoder replacement if the byte cut splits UTF-8. const framedOutput=frameClipped?bytes.subarray(0,1048573).toString('utf8'):frame.slice(0,end); - return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr:stderr.length>0,truncated:displayTruncated||frameClipped,framedOutput,visibleText}}); + return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr,truncated:displayTruncated||frameClipped,framedOutput,visibleText}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/tests/tool-factories.test.ts b/packages/ui-backend-pi/tests/tool-factories.test.ts index 83546e31d6..f3b2793938 100644 --- a/packages/ui-backend-pi/tests/tool-factories.test.ts +++ b/packages/ui-backend-pi/tests/tool-factories.test.ts @@ -207,3 +207,13 @@ test('grepTool prefixes a single file operand with its exact filename',async()=> expect((result.details as {search:{framedOutput:string}}).search.framedOutput,'EXACT_FILENAME_FRAME_IS_HOST_ONLY').toBe(old.replace(':3:',':\0'+'3:')+'\n'); expect(resultText(result)).not.toContain('\0'); }); + +test('grep diagnostics drain without whole-stream buffering',async()=>{ + const original=Response.prototype.arrayBuffer;let allocations=0; + Response.prototype.arrayBuffer=function(){allocations++;return original.call(this);}; + try{ + const result=await run(grepTool(kit({exec:{}})),{pattern:'['}); + expect((result.details as {search:{stderr:boolean}}).search.stderr).toBe(true); + expect(allocations,'ONLY_STDOUT_MAY_ALLOCATE_THE_WHOLE_STREAM').toBe(1); + }finally{Response.prototype.arrayBuffer=original;} +}); diff --git a/packages/ui-server/src/brain/turn-extraction.ts b/packages/ui-server/src/brain/turn-extraction.ts index c1a9d51456..46594c6c6e 100644 --- a/packages/ui-server/src/brain/turn-extraction.ts +++ b/packages/ui-server/src/brain/turn-extraction.ts @@ -191,8 +191,10 @@ export function createTurnExtraction(options: { // Content from anywhere the host cannot vouch for: a fetch, a command // (its connections taint the session at the proxy), another MCP server, // an untrusted area or a marked file. - const tainting = !localTool(tool) || inputTaintSignals(tool, input, options.brainPath, options.marked, true).length > 0 - || outputTaintSignals(tool, output, options.brainPath, options.marked, {...searchOutputContext(tool,input),outputComplete}).length > 0; + const signals=[...inputTaintSignals(tool,input,options.brainPath,options.marked,true), + ...outputTaintSignals(tool,output,options.brainPath,options.marked,{...searchOutputContext(tool,input),outputComplete})]; + if(signals.some(signal=>signal.source==="legacy_unknown"))current.complete=false; + const tainting = !localTool(tool) || signals.length > 0; if (tainting) current.tainting(namedHosts(output)); } catch { state.complete = false; } }; diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index c6323630fc..aba04fdfce 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -706,3 +706,16 @@ test('Pi grep preserves a BOM-prefixed directory in the host filename evidence', expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence'").all()).toEqual([{source:'user_marked',detector:'explicit_untrusted_input'}]); }finally{await f.close();} }); + +for(const shape of ['truncated','malformed'] as const)test(`extraction withholds relaxation after Claude Glob ${shape} without status`,async()=>{ + const f=await voyage();try{ + const {createTurnExtraction}=await import('../src/brain/turn-extraction'); + const extraction=createTurnExtraction({bridge:{emit(){},requestPermission:async()=>({behavior:'allow'}),inputSafety:f.collector},origin:'interactive',sessionId:()=>null,tainted:()=>true,contacted:new Set(),cause:()=>null,brainPath:f.brain}); + const wrapped=extraction.inputSafety(f.collector)!; + await wrapped.begin('glob','Glob',{pattern:'notes/*.md'}); + const output=shape==='truncated'?JSON.stringify({filenames:['notes/loom.md'],numFiles:1,durationMs:1,truncated:true}):'{"filenames":['; + await wrapped.result('glob','Glob',output,true); + await wrapped.begin('fetch','WebFetch',{url:'https://aeaea.invalid/notice'}); + expect(extraction.relaxes('aeaea.invalid'),'UNKNOWN_SIGNALS_WITHHOLD_EXTRACTION_RELAXATION').toBe(false); + }finally{await f.close();} +}); From 2754ed582798fc00ac0999f1dfd6bcddd114cd6a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 01:20:01 +0000 Subject: [PATCH 15/23] fix: preserve display search sources and strengthen native witnesses --- docs/plans/reviewable-session-safety.md | 2 +- .../ui-server/src/activity/ingestion-taint.ts | 18 +++++++++++-- packages/ui-server/src/activity/recorder.ts | 2 +- .../tests/helpers/native-safety-proof.ts | 7 +++--- .../ui-server/tests/ingestion-taint.test.ts | 21 +++++++++++++--- .../tests/native-safety-proof.test.ts | 15 ++++++++--- .../tests/safety-result-retention.test.ts | 25 +++++++++++++------ 7 files changed, 68 insertions(+), 22 deletions(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 8d6e52bfb9..81235a5fe3 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -30,7 +30,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:157-174`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:198-301`). + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:198-317`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery; display frames alone never prove finalized delivery or complete coverage. Pi's shipped search diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index deb6494b34..07efd1dd72 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -175,7 +175,7 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri } /** Admitted format only. Invalid or incomplete output always retains unknown coverage. */ -interface SearchOutputContext { backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number; outputComplete?: boolean } +interface SearchOutputContext { displayOnly?:boolean; backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number; outputComplete?: boolean } // Installed SDK: GlobInput/GrepInput and GlobOutput/GrepOutput in // @anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:905-983,3506-3545. Pi's shipped grep and text // envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:44-82) @@ -229,7 +229,21 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(mode==='count')for(const line of fields.content.split('\n')){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} }; let parsed:unknown;try{parsed=JSON.parse(output);}catch{/* Pi returns raw text; Claude requires its structured schema. */} - if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ + if(context?.displayOnly&&parsed===undefined&&(tool==='Glob'||tool==='Grep')){ + // StreamAdapter flattens SDK tool_result text blocks. These are display + // rows, not the SDK's structured hook response or verified empty evidence. + const mode=tool==='Glob'?'files_with_matches':context.outputMode; + const lines=output.split('\n'); + if(!output||output==='No matches.')unknown=true; + else if(mode==='content')content(output,context.lineNumbers!==false); + else if(mode==='files_with_matches')for(const line of lines){ + if(!line||line.includes('\0'))unknown=true; + else add(line); + } + else if(mode==='count')for(const line of lines){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));else unknown=true;} + else unknown=true; + if((context.offset??0)>0||(context.limit??250)>0&&lines.length>=(context.limit??250))unknown=true; + }else if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ // `safetyResultInput` (packages/ui-backend-pi/src/worker-protocol.ts:92-99) // joins the shipped tool's text. No JSON envelope is part of this format. if(output!=='No matches.'){ diff --git a/packages/ui-server/src/activity/recorder.ts b/packages/ui-server/src/activity/recorder.ts index e29459a5c5..145e1e93f3 100644 --- a/packages/ui-server/src/activity/recorder.ts +++ b/packages/ui-server/src/activity/recorder.ts @@ -384,7 +384,7 @@ export function createTurnRecorder( if(!safetyHooked&&ingestion){ // Display bytes cannot verify a backend's original result parts. // Only structured collection can establish an empty Pi search. - try { signals=[...ingestion.signals,...outputTaintSignals(ingestion.tool,msg.output,deps.brainPath,marked,{...ingestion.searchContext,outputComplete:msg.output==="No matches."?false:undefined})]; } + try { signals=[...ingestion.signals,...outputTaintSignals(ingestion.tool,msg.output,deps.brainPath,marked,{...ingestion.searchContext,displayOnly:true,outputComplete:msg.output==="No matches."?false:undefined})]; } catch { deps.abort?.(new Error("Safety result detection failed; the turn was stopped."));if(governanceWrites)writes.after(()=>governanceWrites.safetyFail(runId)); } } if (!safetyHooked && ingestion && signals.length && !traced?.denied && firstTaint && deps.governance) { diff --git a/packages/ui-server/tests/helpers/native-safety-proof.ts b/packages/ui-server/tests/helpers/native-safety-proof.ts index 62b5cf1704..b9b106a33f 100644 --- a/packages/ui-server/tests/helpers/native-safety-proof.ts +++ b/packages/ui-server/tests/helpers/native-safety-proof.ts @@ -1,11 +1,12 @@ /** The native test's oracle, shared with adversarial non-native checks. */ import {expect} from 'bun:test'; -export function assertNativeSameToolProof(first:{admitted:number;results:number;nativeSecondHeld:boolean},records:readonly unknown[]):void { +export function assertNativeSameToolProof(first:{admitted:number;results:number;nativeSecondHeld:boolean;deliveredPaths:readonly string[]},records:readonly unknown[]):void { expect(first.admitted,'NATIVE_SAME_TOOL_ID_HAS_TWO_LOGICAL_ADMISSIONS').toBe(2); expect(first.nativeSecondHeld,'NATIVE_SECOND_SEARCH_OUTPUT_IS_HELD_BEFORE_POST_TOOL_USE').toBe(true); expect(first.results,'NATIVE_EXACTLY_ONE_RESULT_HOOK_ACTUALLY_FORWARDS').toBe(1); + expect(first.deliveredPaths,'NATIVE_DELIVERED_RESULT_NAMES_THE_WORKSPACE_SOURCE').toEqual(['workspaces/voyage/sirens.md']); expect(records,'NATIVE_SAME_TOOL_OUTPUT_DETECTOR_REACHES_THE_LEDGER').toEqual(expect.arrayContaining([ - {kind:'exposure',detector:null,state:'interrupted_unknown'}, - {kind:'occurrence',detector:'tool_search_output',state:'open'} + {kind:'exposure',detector:null,source:null,state:'interrupted_unknown'}, + {kind:'occurrence',detector:'tool_search_output',source:'workspace_read',state:'open'} ])); } diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index 9bedda23b9..d6178c1bf2 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -1,4 +1,5 @@ import { expect, test } from "bun:test"; +import {adaptStreamEvent} from "../../ui-backend-claude/src/stream-adapter"; import { inputTaintSource, outputTaintSource } from "../src/activity/ingestion-taint"; import { createTurnRecorder } from "../src/activity/recorder"; import { createActivityStore } from "../src/activity/store"; @@ -123,16 +124,16 @@ test("a collected external compute job's output is a taint source on both backen } finally { db.close(); } }); -test('the display recorder uses admitted Claude filename mode for colon paths',async()=>{ +for(const filename of ['notes/voyage:2:home.md','notes/voyage\rhome.md'])test(`the display recorder uses real Claude adapter filename text: ${JSON.stringify(filename)}`,async()=>{ const db=createUiDb(':memory:'); const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); const sessionId='odysseus-colon-search';db.query("INSERT INTO sessions(id,title,created_at,last_active_at) VALUES(?,'Voyage',0,0)").run(sessionId); - untrustedMarkOperations(db).mark('notes/voyage:2:home.md',null,Date.UTC(2026,6,12)); + untrustedMarkOperations(db).mark(filename,null,Date.UTC(2026,6,12)); const recorder=createTurnRecorder({store:createActivityStore(db,{writer:'test'}),governanceDb:db,brainPath:brain,governance:event=>{recordGovernanceEvent(db,event);}},{turnId:'colon-search',sessionId,profile:'governed'}); try{ recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'colon_grep',toolName:'Grep'}); recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'colon_grep',toolName:'Grep',input:{path:'.',pattern:'sirens',output_mode:'files_with_matches'}}); - recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'colon_grep',isError:false,output:JSON.stringify({numFiles:1,filenames:['notes/voyage:2:home.md']})}); + recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'colon_grep',isError:false,output:adaptStreamEvent({type:'user',message:{content:[{type:'tool_result',tool_use_id:'colon_grep',content:[{type:'text',text:filename}]}]}} as never).find(frame=>frame.type==='tool_result')!.output}); expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source),'RECORDER_PRESERVES_ADMITTED_SEARCH_FORMAT').toEqual(['user_marked']); }finally{recorder.finish('success');db.close();} }); @@ -149,3 +150,17 @@ test('display-only grep sentinel never proves complete empty evidence',()=>{ recorder.finish('success'); }finally{db.close();} }); + +test('Claude display filenames preserve both workspace and mark evidence independently',async()=>{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks');const db=createUiDb(':memory:'),sessionId='voyage-display-workspace'; + db.query("INSERT INTO sessions(id,created_at,last_active_at) VALUES(?,0,0)").run(sessionId);untrustedMarkOperations(db).mark('workspaces/voyage/sirens.md',null,Date.UTC(2026,6,12)); + const recorder=createTurnRecorder({store:createActivityStore(db,{writer:'test'}),governanceDb:db,brainPath:brain,governance:event=>{recordGovernanceEvent(db,event);}},{turnId:'display-workspace',sessionId,profile:'governed'}); + try{ + const frames=adaptStreamEvent({type:'user',message:{content:[{type:'tool_result',tool_use_id:'workspace_grep',content:[{type:'text',text:'workspaces/voyage/sirens.md'}]}]}} as never); + expect(frames.find(frame=>frame.type==='tool_result')!.output,'ACTUAL_ADAPTER_OUTPUT_IS_DISPLAY_TEXT').toBe('workspaces/voyage/sirens.md'); + recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'workspace_grep',toolName:'Grep'}); + recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'workspace_grep',toolName:'Grep',input:{pattern:'sirens',output_mode:'files_with_matches'}}); + for(const frame of frames)if(frame.type==='tool_result')recorder.observeFrame({...frame,sessionId}); + expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source).sort(),'DISPLAY_PATH_RETAINS_ALL_INDEPENDENT_SIGNALS').toEqual(['user_marked','workspace_read']); + }finally{recorder.finish('success');db.close();} +}); diff --git a/packages/ui-server/tests/native-safety-proof.test.ts b/packages/ui-server/tests/native-safety-proof.test.ts index cf9e9816b4..3a801db5e2 100644 --- a/packages/ui-server/tests/native-safety-proof.test.ts +++ b/packages/ui-server/tests/native-safety-proof.test.ts @@ -1,14 +1,14 @@ /** No installed runtime is launched: validate the native proof's oracle. */ import {expect,test} from 'bun:test'; import {assertNativeSameToolProof} from './helpers/native-safety-proof'; -const first={admitted:2,results:1,nativeSecondHeld:true}; -const exposure={kind:'exposure',detector:null,state:'interrupted_unknown'}; -const output={kind:'occurrence',detector:'tool_search_output',state:'open'}; +const first={admitted:2,results:1,nativeSecondHeld:true,deliveredPaths:['workspaces/voyage/sirens.md']}; +const exposure={kind:'exposure',detector:null,source:null,state:'interrupted_unknown'}; +const output={kind:'occurrence',detector:'tool_search_output',source:'workspace_read',state:'open'}; test('native oracle accepts one delivered output and a held second search',()=>{ expect(()=>assertNativeSameToolProof(first,[exposure,output])).not.toThrow(); }); test('native oracle rejects an input-only occurrence despite its interrupted exposure',()=>{ - expect(()=>assertNativeSameToolProof(first,[exposure,{kind:'occurrence',detector:'tool_file_input',state:'open'}])).toThrow('NATIVE_SAME_TOOL_OUTPUT_DETECTOR'); + expect(()=>assertNativeSameToolProof(first,[exposure,{kind:'occurrence',detector:'tool_file_input',source:'workspace_read',state:'open'}])).toThrow('NATIVE_SAME_TOOL_OUTPUT_DETECTOR'); }); test('native oracle rejects two delivered results',()=>{ expect(()=>assertNativeSameToolProof({...first,results:2},[exposure,output])).toThrow('NATIVE_EXACTLY_ONE_RESULT'); @@ -16,3 +16,10 @@ test('native oracle rejects two delivered results',()=>{ test('native oracle rejects an unheld second search',()=>{ expect(()=>assertNativeSameToolProof({...first,nativeSecondHeld:false},[exposure,output])).toThrow('NATIVE_SECOND_SEARCH_OUTPUT_IS_HELD'); }); + +test('native oracle rejects an unknown output instead of the returned workspace source',()=>{ + expect(()=>assertNativeSameToolProof(first,[exposure,{...output,source:'legacy_unknown'}])).toThrow('NATIVE_SAME_TOOL_OUTPUT_DETECTOR'); +}); +test('native oracle rejects a result that lost the actual returned filename',()=>{ + expect(()=>assertNativeSameToolProof({...first,deliveredPaths:[]},[exposure,output])).toThrow('NATIVE_DELIVERED_RESULT_NAMES'); +}); diff --git a/packages/ui-server/tests/safety-result-retention.test.ts b/packages/ui-server/tests/safety-result-retention.test.ts index 41261db924..2cbf2dc35c 100644 --- a/packages/ui-server/tests/safety-result-retention.test.ts +++ b/packages/ui-server/tests/safety-result-retention.test.ts @@ -20,6 +20,7 @@ import {recoverSafetyRecording,safetyCatalogCreated} from "../src/governance/saf import {createPermissionWiring} from "../../ui-backend-claude/src/permission-hooks"; import {MEASURED_RUNTIME} from "../../ui-backend-claude/src/measured-runtime"; import {nativeModelReply} from "../../ui-backend-claude/tests/helpers/native-model-reply"; +import {outputTaintSignals,searchOutputContext} from "../src/activity/ingestion-taint"; import {assertNativeSameToolProof} from "./helpers/native-safety-proof"; import {holdSafetyRecovery} from "./helpers/hold-safety-recovery"; @@ -59,7 +60,7 @@ function modelCalls(calls:{name:string;id:string;input:Record}[] return new Response(events.map(event=>`event: ${(event as {type:string}).type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),{headers:{"content-type":"text/event-stream"}}); } async function voyageHome(interruption:Interruption,check:(f:{db:ReturnType;writes:ReturnType; - first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number;nativeSecondHeld:boolean};searched:boolean;replayed:string[]})=>void){ + first:{results:number;failures:number;aborted:boolean;indexWaits:number;admitted:number;cards:number;refusals:number;nativeSecondHeld:boolean;deliveredPaths:string[]};searched:boolean;replayed:string[]})=>void){ const root=mkdtempSync(join(tmpdir(),"odysseus-safety-retention-")),brain=join(root,"brain"),home=join(root,"home"); // A note: reading it records nothing before the tool runs, so only the // search output's own record stands between it and a complete chat. @@ -105,7 +106,7 @@ esac if(!Array.isArray(body.tools)||!body.tools.length)return nativeModelReply(); requests.push({turn,raw}); const first=turn===0&&requests.filter(r=>r.turn===0).length===1; - const search={name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path,output_mode:"content"}}; + const search={name:"Grep",id:"toolu_sirens",input:{pattern:"sirens",path:interruption==="same-tool"?brain:path,output_mode:"content"}}; if(first&&interruption==="duplicate")return modelCalls([search,search]); if(first&&interruption==="same-tool")return modelCalls([search,{...search,input:{...search.input,pattern:"sirens|sirens"}}]); if(first&&interruption==="retooled")return modelCalls([search,{name:"Read",id:search.id,input:{file_path:path}}]); @@ -155,12 +156,17 @@ esac const wiring=createPermissionWiring({req:{prompt:"Listen for the sirens.",signal:controller.signal,enforceAllowedTools:denying,bridge:{emit(){},requestPermission,inputSafety,awaitIndex}},allowedTools:denying?[]:tools,confirmPatterns:[],brainPath:brain,turnLock:{acquireForTool:async()=>({ok:true}),releaseForTool(){}} as never,childEnv:{PATH:"/usr/bin:/bin"},...(retooling?{fileVersions:fileVersions as never}:{}),log(){}}); // The hook both tools share is held for the Read until its denial landed. if(retooling)for(const group of wiring.hooks!.PreToolUse!)if(!group.matcher)group.hooks=group.hooks.map(hook=>async(...args)=>{if((args[0] as {tool_name?:string}).tool_name==="Read")await refused;return hook(...args);}); - let results=0,failures=0; + let results=0,failures=0;const deliveredPaths:string[]=[]; if(interrupt){ // The Grep result exists and the runtime holds it; only its record is at risk. const group=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!,record=group.hooks[0]!; group.hooks=[async(...args)=>{ results++; + if(interruption==="same-tool"&&args[0].hook_event_name==="PostToolUse"){ + const response=args[0].tool_response; + const signals=outputTaintSignals("Grep",typeof response==="string"?response:JSON.stringify(response),brain,undefined,searchOutputContext("Grep",args[0].tool_input,"claude")); + for(const signal of signals)if(signal.source==="workspace_read"&&signal.detector==="tool_search_output")deliveredPaths.push(signal.key.startsWith(brain+"/")?signal.key.slice(brain.length+1):signal.key); + } if(interruption==="refused")db.exec("CREATE TRIGGER refuse_result BEFORE INSERT ON safety_pending BEGIN SELECT RAISE(ABORT,'forced result reservation failure'); END"); else if(interruption==="cancelled")controller.abort(new Error("Odysseus stopped the turn as the result arrived")); const result=await record(...args); @@ -186,7 +192,7 @@ esac if(interrupt&&(interruption==="duplicate"||interruption==="retooled"))await Promise.race([refused,new Promise(resolve=>setTimeout(resolve,2000))]); await writes.safetyEnd(turnId); } - return {results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals,nativeSecondHeld:existsSync(secondHeld)&&existsSync(secondOutput)&&readFileSync(secondOutput,"utf8").length>0}; + return {deliveredPaths,results,failures,aborted:controller.signal.aborted,indexWaits,admitted,cards,refusals,nativeSecondHeld:existsSync(secondHeld)&&existsSync(secondOutput)&&readFileSync(secondOutput,"utf8").length>0}; } try{ const first=await voyage("voyage",null,true); @@ -239,7 +245,8 @@ test("a turn stopped as its result arrives still records the result the runtime expect(chat.coverage.state,"SAFETY_CANCELLED_RECORDED_RESULT_KEEPS_COVERAGE").toBe("complete"); }),60000); -test("a turn stopped while its search runs reaches neither result hook, and its chat keeps a permanent gap",()=>voyageHome("running",({db,writes,first,replayed})=>{ +test("a turn stopped while its search runs reaches neither result hook, and its chat keeps a permanent gap",()=>voyageHome("running",({db,writes,first,replayed,searched})=>{ + expect(searched,"SAFETY_POSITIVE_SEARCH_INVOCATION_RUNNING").toBe(true); // The runtime skips both result hooks for a stopped turn, so the host never // sees this result: only the call's admission stands for it. expect(first.results+first.failures,"SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS").toBe(0); @@ -256,7 +263,8 @@ test("a turn stopped while its search runs reaches neither result hook, and its expect(JSON.parse(voyage.failure_cause??"{}"),"SAFETY_UNRECORDED_RESULT_NAMES_ITS_CALL").toMatchObject({site:"safetyEnd",turnId:"voyage",message:expect.stringContaining("Grep (toolu_sirens)")}); }),60000); -test("a denial under an id the runtime admitted twice cannot settle the search that already ran, so its chat keeps a permanent gap",()=>voyageHome("duplicate",({db,writes,first})=>{ +test("a denial under an id the runtime admitted twice cannot settle the search that already ran, so its chat keeps a permanent gap",()=>voyageHome("duplicate",({db,writes,first,searched})=>{ + expect(searched,"SAFETY_POSITIVE_SEARCH_INVOCATION_DUPLICATE").toBe(true); // The installed runtime admits the same tool_use id twice and runs the // first search; its allow never reaches a callback, since `allowedTools` // lists Grep bare. @@ -290,7 +298,8 @@ test("a search denied at its permission card never runs, and its chat stays norm expect(first.refusals,"SAFETY_CARD_DENY_IS_REPORTED").toBeGreaterThan(0); }),60000); -test("a denial of another tool under the search's id cannot settle the search that already ran, so its chat keeps a permanent gap",()=>voyageHome("retooled",({db,writes,first})=>{ +test("a denial of another tool under the search's id cannot settle the search that already ran, so its chat keeps a permanent gap",()=>voyageHome("retooled",({db,writes,first,searched})=>{ + expect(searched,"SAFETY_POSITIVE_SEARCH_INVOCATION_RETOOLED").toBe(true); // The runtime ran the search and was stopped before either result hook. expect(first.results+first.failures,"SAFETY_RUNTIME_SKIPPED_BOTH_RESULT_HOOKS").toBe(0); // The Read's own hook denied it before the shared hook counted it: that @@ -360,7 +369,7 @@ for(const late of [false,true])test(`a denied shell call reusing a search's id c test("two same-ID native Grep calls retain their recorded result and the interrupted call's gap",()=>voyageHome("same-tool",({db,writes,first})=>{ - assertNativeSameToolProof(first,db.query("SELECT r.kind,r.detector,r.state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' ORDER BY r.kind").all()); + assertNativeSameToolProof(first,db.query("SELECT r.kind,r.detector,r.source,r.state FROM safety_records r JOIN safety_collections c ON c.id=r.collection_id WHERE c.turn_id='voyage' ORDER BY r.kind").all()); expect(writes.safety(null,"ithaca").coverage.state,"NATIVE_SAME_TOOL_RESULT_DOES_NOT_ERASE_THE_GAP").toBe('incomplete'); expect(db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:'recording_failed'}); }),60000); From 9d32900341a4abb6e36b9ec0549256f51a42afa6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 01:53:24 +0000 Subject: [PATCH 16/23] CONTRACT: require framed empty proof and preserve ambiguous display sources --- docs/integration-contract/package-api.md | 4 +- docs/plans/reviewable-session-safety.md | 8 +++- packages/ui-backend-pi/src/file-tools.ts | 4 +- packages/ui-backend-pi/src/worker-protocol.ts | 4 +- .../ui-server/src/activity/ingestion-taint.ts | 33 ++++++++------ .../tests/ingestion-taint-schema.test.ts | 13 +++++- .../ui-server/tests/ingestion-taint.test.ts | 12 ++--- .../tests/input-safety-forwarders.test.ts | 16 +++++++ .../tests/safety-result-exits.test.ts | 44 ++++++++++++++++--- 9 files changed, 104 insertions(+), 34 deletions(-) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 165b5d1f2f..33026d47e1 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5971,7 +5971,9 @@ alongside every identifiable source. It is independent of the existing `finalized` exposure argument; incomplete evidence cannot prove a managed reference read. Pi carries the original tool status through its result hook and worker RPC. Exit 1 with empty stdout and no stderr is its only empty -sentinel; exit 0 requires matches. Missing search status is restrictive. +sentinel; exit 0 requires matches. The shipped tool records zero stdout bytes +in host-only observation metadata; matching sentinel text is never that proof. +Missing search status or zero-byte proof is restrictive. Every wrapper forwards the complete typed callback tuple. Extraction also withholds its relaxation when result evidence is incomplete. Status identity uses canonical key order, and host frames have an independent byte bound; diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 81235a5fe3..a0a4bac3b9 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -30,9 +30,13 @@ public design or its fixtures. Fictional examples use the Odysseus world. mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:157-174`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:198-317`). + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:198-320`). Workspace paths taint regardless of repository ownership. Awaited backend - hooks commit before tool dispatch/result delivery; display frames alone + hooks commit before tool dispatch/result delivery. Normal Claude collection + uses the SDK PostToolUse structured tool_response; collector readiness disables + the display recorder fallback. That fallback treats display filenames literally, + checks adjacent-line joins for marks, and retains unknown coverage for all + nonempty text because filename boundaries are unverified. Display frames alone never prove finalized delivery or complete coverage. Pi's shipped search preserves filename boundaries with GNU grep's NUL filename separator and a retained visible colon. New result data can therefore name POSIX filenames diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 88c07ea111..43dbed5f46 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -78,7 +78,7 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { // Keep an unambiguous machine boundary in host-only result details. // POSIX filenames may contain newlines, colons and edge whitespace. // This changes result data only; provider tool definitions stay identical. - const empty=exitCode===1&&out.length===0&&!stderr; + const empty=exitCode===1&&outBytes.byteLength===0&&!stderr; const frame=empty?"No matches.":out.replaceAll("\0", ":\0")||"Search output unavailable."; const rawText=frame.replaceAll("\0", ""),text=rawText.trim(); const visibleText=clip(text),displayTruncated=text.length>MAX_OUTPUT_BYTES; @@ -96,7 +96,7 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const bytes=Buffer.from(frame.slice(0,end)),frameClipped=bytes.length>1048576; // Leave room for a decoder replacement if the byte cut splits UTF-8. const framedOutput=frameClipped?bytes.subarray(0,1048573).toString('utf8'):frame.slice(0,end); - return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr,truncated:displayTruncated||frameClipped,framedOutput,visibleText}}); + return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr,truncated:displayTruncated||frameClipped,stdoutEmpty:outBytes.byteLength===0,framedOutput,visibleText}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index ebc2652c28..69db334550 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -90,7 +90,7 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ export type PiWorkerMessage = z.infer; export const piOutputStatus=z.object({complete:z.boolean(),exitCode:z.number().int().optional(),stderr:z.boolean().optional(),truncated:z.boolean().optional()}).strict(); -const searchStatus=z.object({exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional(),visibleText:z.string().optional()}).strict(); +const searchStatus=z.object({stdoutEmpty:z.boolean().optional(),exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional(),visibleText:z.string().optional()}).strict(); /** Host-only observation. Never alter provider result content to encode status. */ export function safetyResultInput(tool:string,content:readonly {type:string;text?:unknown}[],complete=true,details?:unknown): {output:string;segments?:string[];outputStatus:z.infer} { const segments=content.filter(part=>part.type==='text'&&typeof part.text==='string').map(part=>part.text as string),output=segments.join('\n'); @@ -101,7 +101,7 @@ export function safetyResultInput(tool:string,content:readonly {type:string;text const rendered=framed?.replaceAll('\0','').trim(); const bound=framed===undefined?output==='No matches.':status.success&&status.data.truncated?status.data.visibleText===output&&(output.length>MAX_OUTPUT_BYTES?framed.replaceAll('\0','').trimStart()===output.slice(0,MAX_OUTPUT_BYTES):rendered===output):rendered===output; const successful=bound&&status.success&&!status.data.stderr&&!status.data.truncated&& - (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&output==='No matches.'); + (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&status.data.stdoutEmpty===true&&output==='No matches.'); const processStatus=status.success?{exitCode:status.data.exitCode,stderr:status.data.stderr,truncated:status.data.truncated}:{}; return {output:bound?(framed??output):output,segments,outputStatus:{...processStatus,complete:original&&successful}}; } diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 07efd1dd72..50e4717cda 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -228,21 +228,26 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(mode==='content')content(fields.content,context?.lineNumbers!==false); if(mode==='count')for(const line of fields.content.split('\n')){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} }; - let parsed:unknown;try{parsed=JSON.parse(output);}catch{/* Pi returns raw text; Claude requires its structured schema. */} - if(context?.displayOnly&&parsed===undefined&&(tool==='Glob'||tool==='Grep')){ - // StreamAdapter flattens SDK tool_result text blocks. These are display - // rows, not the SDK's structured hook response or verified empty evidence. - const mode=tool==='Glob'?'files_with_matches':context.outputMode; - const lines=output.split('\n'); - if(!output||output==='No matches.')unknown=true; - else if(mode==='content')content(output,context.lineNumbers!==false); - else if(mode==='files_with_matches')for(const line of lines){ - if(!line||line.includes('\0'))unknown=true; - else add(line); + const display=context?.displayOnly&&(tool==='Glob'||tool==='Grep'); + let parsed:unknown;if(!display)try{parsed=JSON.parse(output);}catch{/* Hook objects require a validated schema. */} + if(display){ + // SDK display text has no filename framing. Never reinterpret a literal + // filename as JSON; preserve known paths and retain boundary uncertainty. + if(output.length){ + unknown=true; + const lines=output.split('\n'); + if(lines.length>256)throw new Error('Safety display candidate capacity exceeded'); + for(const line of lines)if(line)add(line); + let candidates=0; + joins:for(let span=2;span<=lines.length;span++)for(let start=0;start+span<=lines.length;start++){ + if(++candidates>4096)break joins; + const joined=lines.slice(start,start+span).join('\n');if(Buffer.byteLength(joined)>1024)continue; + const relative=brainRelative(joined,brainPath); + if(relative!==null&&marked?.(relative))add(joined); + } + if(context.outputMode==='content')content(output,context.lineNumbers!==false); + if(context.outputMode==='count')for(const line of lines){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} } - else if(mode==='count')for(const line of lines){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));else unknown=true;} - else unknown=true; - if((context.offset??0)>0||(context.limit??250)>0&&lines.length>=(context.limit??250))unknown=true; }else if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ // `safetyResultInput` (packages/ui-backend-pi/src/worker-protocol.ts:92-99) // joins the shipped tool's text. No JSON envelope is part of this format. diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 38f42cc00a..3cfa0d3a48 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -56,7 +56,9 @@ for(const [name,tool,input,output,expected] of [ ['Pi sentinel plus empty block','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'},{type:'text',text:''}]),['legacy_unknown']], ['Pi inconsistent frame salvages visible path','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/voyage.md:1:sirens'}],true,{search:{exitCode:0,stderr:false,truncated:false,framedOutput:'notes/loom.md:\0'+'1:echo\n'}}),['user_marked','legacy_unknown']], ['Pi truncated frame cannot omit visible paths','grep',{},safetyResultInput('grep',[{type:'text',text:'notes/loom.md:1:echo\nnotes/voyage.md:1:sirens'}],true,{search:{exitCode:0,stderr:false,truncated:true,framedOutput:'notes/loom.md:\0'+'1:echo\n',visibleText:'notes/loom.md:1:echo\nnotes/voyage.md:1:sirens'}}),['user_marked','legacy_unknown']], - ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],true,{search:{exitCode:1,stderr:false,truncated:false}}),[]], + ['Pi exact original sentinel','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],true,{search:{stdoutEmpty:true,exitCode:1,stderr:false,truncated:false}}),[]], + ['Pi sentinel with missing zero-byte proof','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],true,{search:{exitCode:1,stderr:false,truncated:false}}),['legacy_unknown']], + ['Pi sentinel with nonempty stdout','grep',{},safetyResultInput('grep',[{type:'text',text:'No matches.'}],true,{search:{stdoutEmpty:false,exitCode:1,stderr:false,truncated:false}}),['legacy_unknown']], ['Grep duplicate per-file count rows','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:1\nnotes/loom.md:1',numMatches:2}),['legacy_unknown']], ['Pi newline filename ambiguity is never healthy legacy evidence','grep',{},'./raft:1:sail\nloom.md:1:sirens',['legacy_unknown']], ['Pi NUL newline filename','grep',{},'./raft:1:sail\nloom.md:\0'+'1:sirens\n',['user_marked']], @@ -113,3 +115,12 @@ for(const terminated of [false,true])for(const shape of ['incomplete','image'] a const signals=outputTaintSignals('grep',converted.output,'/srv/odysseus/brain',()=>false,{...searchOutputContext('grep',{}),outputComplete:converted.outputStatus.complete}); expect(signals.map(signal=>signal.source),'EXPLICIT_INCOMPLETE_RESULT_STAYS_UNKNOWN').toEqual(['legacy_unknown']); }); + +for(const filename of ['123','{"durationMs":1,"numFiles":0,"filenames":[],"truncated":false}','notes/voyage\nloom.md'])test(`display-only Glob treats filename bytes literally: ${JSON.stringify(filename)}`,()=>{ + const signals=outputTaintSignals('Glob',filename,undefined,path=>path===filename,{displayOnly:true,backendId:'claude'}); + expect(signals.map(signal=>({source:signal.source,key:signal.key})).sort((a,b)=>a.source.localeCompare(b.source)),'DISPLAY_BOUNDARIES_NEVER_HIDE_MARKS_OR_UNKNOWN').toEqual([{source:'legacy_unknown',key:'unknown_remainder'},{source:'user_marked',key:filename}]); +}); + +test('exactly empty display fallback has no ambiguous filename bytes',()=>{ + expect(outputTaintSignals('Glob','',undefined,()=>false,{displayOnly:true,backendId:'claude'})).toEqual([]); +}); diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index d6178c1bf2..99ed880dee 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -84,12 +84,12 @@ test("the real recorder keeps independent sources and excludes a denied fetch", const events = () => queryGovernanceEvents(db, { sessionId, kinds: ["taint"], limit: 10 }); try { call("denied", "WebFetch", { url: "https://ithaca.invalid" }, "Denied", true); - call("clean", "Grep", { pattern: "Ithaca" }, JSON.stringify({numFiles:1,filenames:[`${brain}/notes/a.md`]})); - expect(events(), "G6_DENIED_FETCH_CLEAN").toHaveLength(0); - call("search", "Grep", { pattern: "Ithaca" }, JSON.stringify({numFiles:1,filenames:[`${brain}/workspaces/voyage/a.md`]})); + call("clean", "Grep", { pattern: "Ithaca" }, `${brain}/notes/a.md`); + expect(events().map(event=>event.payload.source), "G6_DISPLAY_ONLY_SEARCH_IS_UNKNOWN").toEqual(["legacy_unknown"]); + call("search", "Grep", { pattern: "Ithaca" }, `${brain}/workspaces/voyage/a.md`); call("fetch", "WebFetch", { url: "https://ithaca.invalid" }, "A fictional harbour notice."); expect(events().map(event => [event.payload.source, event.payload.tool, event.payload.detail]), "G6_RECORDER_EVERY_TOOL_SOURCE") - .toEqual([["workspace_read", "Grep", null], ["web_fetch", "WebFetch", null]]); + .toEqual([["legacy_unknown", "Grep", null], ["workspace_read", "Grep", null], ["legacy_unknown", "Grep", null], ["web_fetch", "WebFetch", null]]); recorder.finish("success"); } finally { db.close(); } }); @@ -134,7 +134,7 @@ for(const filename of ['notes/voyage:2:home.md','notes/voyage\rhome.md'])test(`t recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'colon_grep',toolName:'Grep'}); recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'colon_grep',toolName:'Grep',input:{path:'.',pattern:'sirens',output_mode:'files_with_matches'}}); recorder.observeFrame({type:'tool_result',sessionId,toolUseId:'colon_grep',isError:false,output:adaptStreamEvent({type:'user',message:{content:[{type:'tool_result',tool_use_id:'colon_grep',content:[{type:'text',text:filename}]}]}} as never).find(frame=>frame.type==='tool_result')!.output}); - expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source),'RECORDER_PRESERVES_ADMITTED_SEARCH_FORMAT').toEqual(['user_marked']); + expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source).sort(),'RECORDER_PRESERVES_ADMITTED_SEARCH_FORMAT').toEqual(['legacy_unknown','user_marked']); }finally{recorder.finish('success');db.close();} }); @@ -161,6 +161,6 @@ test('Claude display filenames preserve both workspace and mark evidence indepen recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'workspace_grep',toolName:'Grep'}); recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'workspace_grep',toolName:'Grep',input:{pattern:'sirens',output_mode:'files_with_matches'}}); for(const frame of frames)if(frame.type==='tool_result')recorder.observeFrame({...frame,sessionId}); - expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source).sort(),'DISPLAY_PATH_RETAINS_ALL_INDEPENDENT_SIGNALS').toEqual(['user_marked','workspace_read']); + expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source).sort(),'DISPLAY_PATH_RETAINS_ALL_INDEPENDENT_SIGNALS').toEqual(['legacy_unknown','user_marked','workspace_read']); }finally{recorder.finish('success');db.close();} }); diff --git a/packages/ui-server/tests/input-safety-forwarders.test.ts b/packages/ui-server/tests/input-safety-forwarders.test.ts index 183f086565..f916480fba 100644 --- a/packages/ui-server/tests/input-safety-forwarders.test.ts +++ b/packages/ui-server/tests/input-safety-forwarders.test.ts @@ -33,3 +33,19 @@ import {fileURLToPath} from 'node:url'; } expect(found.sort(),'REVIEW_EVERY_NEW_RESULT_WRAPPER').toEqual(['packages/ui-server/src/brain/turn-extraction.ts']); }); + +test('normal host startup connects collector readiness to the display-recorder bypass',async()=>{ + const root=fileURLToPath(new URL('../../../',import.meta.url)),path='packages/ui-server/src/ws/session-run/backend-entry.ts'; + const source=ts.createSourceFile(path,await Bun.file(`${root}/${path}`).text(),ts.ScriptTarget.Latest,true);const readiness:ts.Node[]=[]; + const visit=(node:ts.Node)=>{ + if(ts.isCallExpression(node)&&node.expression.getText(source)==='createSafetyCollector'){ + const options=node.arguments[2]; + if(options&&ts.isObjectLiteralExpression(options))for(const property of options.properties)if(ts.isPropertyAssignment(property)&&property.name.getText(source)==='onReady')readiness.push(property); + } + ts.forEachChild(node,visit); + }; + visit(source);expect(readiness,'NORMAL_HOST_INSTALLS_ONE_STRUCTURED_COLLECTION_READY_CALLBACK').toHaveLength(1); + const setters:ts.CallExpression[]=[]; + const calls=(node:ts.Node)=>{if(ts.isCallExpression(node)&&ts.isPropertyAccessExpression(node.expression)&&node.expression.name.text==='setSafetyHooked')setters.push(node);ts.forEachChild(node,calls);}; + calls(readiness[0]!);expect(setters,'STRUCTURED_READY_DISABLES_AMBIGUOUS_DISPLAY_COLLECTION').toHaveLength(1); +}); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index aba04fdfce..752cd1e136 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -13,6 +13,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync import { tmpdir } from "node:os"; import { join } from "node:path"; import {createRequire} from "node:module"; +import type {BackendBridge} from "@schlessera/brain-ui-sdk/server"; import type { Agent } from "@earendil-works/pi-agent-core"; import { createEffectiveSafety } from "../src/governance/effective-safety"; import { createUiDb } from "../src/db/client"; @@ -583,7 +584,7 @@ test('shipped Pi grep preserves a marked newline filename through the worker led }finally{await f.close();} }); -for(const mode of ['file','empty','regex','partial','warning'] as const)test(`Pi after-tool RPC preserves grep status: ${mode}`,async()=>{ +for(const mode of ['file','empty','sentinel','regex','partial','warning'] as const)test(`Pi after-tool RPC preserves grep status: ${mode}`,async()=>{ const f=await voyage();try{ const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); mkdirSync(join(f.brain,'notes')); @@ -591,12 +592,12 @@ for(const mode of ['file','empty','regex','partial','warning'] as const)test(`Pi if(mode==='partial'){ untrustedMarkOperations(f.db).mark('notes/loom.md',null,Date.UTC(2026,6,12)); } - const wrapper=['warning','partial'].includes(mode)?join(f.brain,'grep-wrapper'):undefined; - if(wrapper)writeFileSync(wrapper,mode==='partial'?"#!/bin/sh\nprintf \"notes/loom.md\\0001:nymph_signal\\n\"\nprintf \"search error\\n\" >&2\nexit 2\n":"#!/bin/sh\nprintf \"search warning\\n\" >&2\nexec \"$@\"\n",{mode:0o755}); + const wrapper=['warning','partial','sentinel'].includes(mode)?join(f.brain,'grep-wrapper'):undefined; + if(wrapper)writeFileSync(wrapper,mode==='sentinel'?"#!/bin/sh\nprintf 'No matches.'\nexit 1\n":mode==='partial'?"#!/bin/sh\nprintf \"notes/loom.md\\0001:nymph_signal\\n\"\nprintf \"search error\\n\" >&2\nexit 2\n":"#!/bin/sh\nprintf \"search warning\\n\" >&2\nexec \"$@\"\n",{mode:0o755}); const input={pattern:mode==='regex'?'[':mode==='empty'?'no_cyclops_here':'nymph_signal',...(mode==='file'?{path:'notes/loom.md'}:{})},id='status_search'; await f.collector.begin(id,'grep',input); const actual=await runSearchTool(f,id,input,wrapper); - const expectedCode=mode==='empty'?1:mode==='regex'||mode==='partial'?2:0; + const expectedCode=['empty','sentinel'].includes(mode)?1:mode==='regex'||mode==='partial'?2:0; expect((actual.details as {search:unknown}).search,'GREP_EXIT_STATUS_AND_STDERR_ARE_OBSERVED').toMatchObject({exitCode:expectedCode,stderr:['regex','partial','warning'].includes(mode),truncated:false}); let stopped=false,forwarded:unknown; const agent={abort(){stopped=true;},streamFunction:async()=>{}} as unknown as Agent; @@ -606,8 +607,8 @@ for(const mode of ['file','empty','regex','partial','warning'] as const)test(`Pi await dispatch(JSON.parse(JSON.stringify(report(1,toolId,converted)))); }},()=>false); await agent.afterToolCall!({toolCall:{name:'grep',id},args:input,result:actual,isError:false} as never,f.controller.signal); - const incomplete=['regex','partial','warning'].includes(mode); - expect(forwarded,'GREP_STATUS_REACHES_WORKER_RPC').toEqual({complete:!incomplete,exitCode:expectedCode,stderr:incomplete,truncated:false}); + const incomplete=['sentinel','regex','partial','warning'].includes(mode); + expect(forwarded,'GREP_STATUS_REACHES_WORKER_RPC').toEqual({complete:!incomplete,exitCode:expectedCode,stderr:mode!=='sentinel'&&incomplete,truncated:false}); expect(stopped).toBe(false); expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all(),'PARTIAL_GREP_KEEPS_KNOWN_MARKS_AND_AN_UNKNOWN_REMAINDER').toEqual(mode==='partial'?[ {source:'user_marked',detector:'explicit_untrusted_input'},{source:'legacy_unknown',detector:'tool_search_output'} @@ -719,3 +720,34 @@ for(const shape of ['truncated','malformed'] as const)test(`extraction withholds expect(extraction.relaxes('aeaea.invalid'),'UNKNOWN_SIGNALS_WITHHOLD_EXTRACTION_RELAXATION').toBe(false); }finally{await f.close();} }); + +test('ready Claude collection records structured hook searches instead of ambiguous display text',async()=>{ + const f=await voyage('claude');try{ + const {createTurnRecorder}=await import('../src/activity/recorder'); + const {createActivityStore}=await import('../src/activity/store'); + const {recordGovernanceEvent}=await import('../src/governance/events'); + const {adaptStreamEvent}=await import('../../ui-backend-claude/src/stream-adapter'); + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks'); + untrustedMarkOperations(f.db).mark('123',null,Date.UTC(2026,6,12)); + let ready=false; + const recorder=createTurnRecorder({store:createActivityStore(f.db,{writer:'test'}),governanceDb:f.db,brainPath:f.brain,governance:event=>{recordGovernanceEvent(f.db,event);}},{turnId:'voyage',sessionId:'ithaca',profile:'governed'}); + const bindingId=(f.db.query("SELECT id FROM safety_collections WHERE turn_id='voyage'").get() as {id:string}).id; + const collector=createSafetyCollector(f.db,f.writes,{turnId:'voyage',bindingId,backendId:'claude',sessionId:()=> 'ithaca',brainPath:f.brain,shellProxied:()=>true,signal:f.controller.signal,onReady(){ready=true;recorder.setSafetyHooked();}}); + await collector.ready('claude',1);expect(ready).toBe(true); + const bridge:BackendBridge={emit(){},requestPermission:async()=>({behavior:'allow'}),inputSafety:collector}; + const wiring=createPermissionWiring({req:{prompt:'Return to Ithaca',signal:f.controller.signal,bridge},allowedTools:['Glob'],confirmPatterns:[],brainPath:f.brain,turnLock:{async acquireForTool(){return {ok:true};},releaseForTool(){}} as never,childEnv:{},log(){}}); + const id='structured_glob',input={pattern:'**/*'},response={durationMs:1,numFiles:2,filenames:['123','workspaces/voyage/raft.md'],truncated:false,totalMatches:2,countIsComplete:true}; + await collector.begin(id,'Glob',input); + recorder.observeFrame({type:'tool_use_start',sessionId:'ithaca',toolUseId:id,toolName:'Glob'}); + recorder.observeFrame({type:'tool_use_complete',sessionId:'ithaca',toolUseId:id,toolName:'Glob',input}); + // Installed sdk.d.ts:2662 exposes the exact structured tool_response; + // sdk.d.ts:6280-6293 separately exposes tool_use_result on user messages. + const post=wiring.hooks!.PostToolUse!.find(group=>!group.matcher)!.hooks[0]!; + await post({hook_event_name:'PostToolUse',tool_name:'Glob',tool_use_id:id,tool_input:input,tool_response:response} as never,id,{signal:f.controller.signal}); + for(const frame of adaptStreamEvent({type:'user',tool_use_result:response,message:{content:[{type:'tool_result',tool_use_id:id,content:[{type:'text',text:'123\nworkspaces/voyage/raft.md'}]}]}} as never))if(frame.type==='tool_result')recorder.observeFrame({...frame,sessionId:'ithaca'}); + await f.idle(); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY source").all(),'STRUCTURED_HOOK_PRESERVES_EXACT_FILENAMES_WITHOUT_DISPLAY_UNKNOWN').toEqual([{source:'user_marked',detector:'explicit_untrusted_input'},{source:'workspace_read',detector:'tool_search_output'}]); + expect(f.chat().coverage.state).toBe('complete'); + recorder.finish('success'); + }finally{await f.close();} +}); From 899b6ff90e40ec7359d1fe9bfa0c3a40167be3a0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 02:43:12 +0000 Subject: [PATCH 17/23] fix: retain search evidence without throwing on malformed paths --- docs/plans/reviewable-session-safety.md | 4 +- .../ui-server/src/activity/ingestion-taint.ts | 38 +++++++++++-------- .../tests/ingestion-taint-schema.test.ts | 10 +++++ .../ui-server/tests/ingestion-taint.test.ts | 14 +++++++ .../ui-server/tests/safety-ledger.test.ts | 25 +++++++----- 5 files changed, 64 insertions(+), 27 deletions(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index a0a4bac3b9..3214ab2428 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -29,8 +29,8 @@ public design or its fixtures. Fictional examples use the Odysseus world. their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, - `packages/ui-server/src/activity/ingestion-taint.ts:157-174`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:198-320`). + `packages/ui-server/src/activity/ingestion-taint.ts:158-178`; + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:202-328`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery. Normal Claude collection uses the SDK PostToolUse structured tool_response; collector readiness disables diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 50e4717cda..5282650483 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -144,13 +144,14 @@ export const INGESTION_DETECTOR_MANIFEST = { function fileSignals(path: string, brainPath: string | undefined, marked: MarkedLookup | undefined, detector: "tool_file_input" | "tool_search_output"): IngestionSignal[] { - if(Buffer.byteLength(path)>1024)throw new Error("Safety path capacity exceeded"); + if(Buffer.byteLength(path)>1024)return [{source:"legacy_unknown",detector,key:"unknown_path"}]; const normalized = posix.normalize(path), result: IngestionSignal[] = []; const area = pathSource(normalized, brainPath); if (area) result.push({ source: area, detector, key: normalized }); const relative = brainRelative(normalized, brainPath); // A workspace/staged/attachment signal must never hide the explicit mark. - if (relative !== null && marked?.(relative)) result.push({ source: "user_marked", detector: "explicit_untrusted_input", key: relative }); + try{if (relative !== null && marked?.(relative)) result.push({ source: "user_marked", detector: "explicit_untrusted_input", key: relative });} + catch{result.push({source:"legacy_unknown",detector,key:"unknown_mark"});} return result; } @@ -166,8 +167,11 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri const object=input&&typeof input==="object"?input as Record:{}; const keys=source==="web_fetch"?["url","urls"]:["query","queries","claim"]; const values=keys.flatMap(key=>typeof object[key]==="string"?[object[key] as string]:Array.isArray(object[key])?(object[key] as unknown[]).filter((v):v is string=>typeof v==="string"):[]); - if(values.length>256||values.some(value=>Buffer.byteLength(value)>2048))throw new Error("Safety web input capacity exceeded"); - return [...new Set(values.length?values:["unknown_input"])].map(key=>({source,detector:"tool_web_input" as const,key})); + const incomplete=values.length>256||values.some(value=>Buffer.byteLength(value)>2048); + const kept=values.slice(0,incomplete?255:256).filter(value=>Buffer.byteLength(value)<=2048); + const result:IngestionSignal[]=[...new Set(kept.length?kept:["unknown_input"])].map(key=>({source,detector:"tool_web_input" as const,key})); + if(incomplete)result.push({source:"legacy_unknown",detector:"tool_web_input",key:"unknown_remainder"}); + return result; } const detector = source === "compute_output" ? "compute_input" : source === "chat_attachment" ? "attachment_input" : source === "mcp_document" ? "external_mcp_input" : "unproxied_shell_input"; @@ -197,13 +201,15 @@ export function searchOutputComplete(output:string,status:InputSafetyOutputStatu export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: SearchOutputContext): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; - if(Buffer.byteLength(output)>1048576)throw new Error('Safety search output capacity exceeded'); - const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=context?.outputComplete===false; + const oversized=Buffer.byteLength(output)>1048576; + if(oversized)output=Buffer.from(output.slice(0,1048576)).subarray(0,1048576).toString('utf8'); + const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=oversized||context?.outputComplete===false; const add=(path:string)=>{ if(!path||path.includes('\0')){unknown=true;return;} for(const signal of fileSignals(path,brainPath,marked,'tool_search_output')){ + if(signal.source==='legacy_unknown'){unknown=true;continue;} const key=JSON.stringify([signal.detector,signal.key]);if(seen.has(key))continue; - if(result.length>=256)throw new Error('Safety search signal capacity exceeded');seen.add(key);result.push(signal); + if(result.length>=255){unknown=true;continue;}seen.add(key);result.push(signal); } }; const content=(text:string,numbers:boolean)=>{ @@ -213,7 +219,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str // No line numbers: every colon could separate the filename and content. // With numbers: lookahead preserves overlapping `:2:7:` candidates. for(const split of line.matchAll(numbers?/(?=:[1-9][0-9]*:)/g:/(?=:)/g)){ - if(count++>=256)throw new Error('Safety search candidate capacity exceeded');const path=line.slice(0,split.index);contentPaths.add(path);add(path); + if(count++>=256){unknown=true;break;}const path=line.slice(0,split.index);contentPaths.add(path);add(path); } if(count!==1)unknown=true; } @@ -235,17 +241,19 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str // filename as JSON; preserve known paths and retain boundary uncertainty. if(output.length){ unknown=true; - const lines=output.split('\n'); - if(lines.length>256)throw new Error('Safety display candidate capacity exceeded'); - for(const line of lines)if(line)add(line); + const allLines=output.split('\n'),lines=allLines.slice(0,256); + // Literal filenames are candidates only in filename mode. Match text + // is not a filename and must not consume the path budget. + const filenames=tool==='Glob'||context.outputMode==='files_with_matches'; + if(filenames)for(const line of lines)if(line)add(line); let candidates=0; - joins:for(let span=2;span<=lines.length;span++)for(let start=0;start+span<=lines.length;start++){ + joins:for(let span=2;filenames&&span<=lines.length;span++)for(let start=0;start+span<=lines.length;start++){ if(++candidates>4096)break joins; const joined=lines.slice(start,start+span).join('\n');if(Buffer.byteLength(joined)>1024)continue; const relative=brainRelative(joined,brainPath); - if(relative!==null&&marked?.(relative))add(joined); + try{if(relative!==null&&marked?.(relative))add(joined);}catch{unknown=true;} } - if(context.outputMode==='content')content(output,context.lineNumbers!==false); + if(context.outputMode==='content')content(lines.join('\n'),context.lineNumbers!==false); if(context.outputMode==='count')for(const line of lines){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} } }else if(tool==='grep'&&(context===undefined||context.backendId==='pi')){ @@ -314,7 +322,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(value.numMatches!==undefined&&value.numMatches!==matches)unknown=true; } }else unknown=true; - if(unknown){if(result.length>=256)throw new Error('Safety search signal capacity exceeded');result.push({source:'legacy_unknown',detector:'tool_search_output',key:'unknown_remainder'});} + if(unknown){result.push({source:'legacy_unknown',detector:'tool_search_output',key:'unknown_remainder'});} return result; } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 3cfa0d3a48..ecc6f6ea23 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -124,3 +124,13 @@ for(const filename of ['123','{"durationMs":1,"numFiles":0,"filenames":[],"trunc test('exactly empty display fallback has no ambiguous filename bytes',()=>{ expect(outputTaintSignals('Glob','',undefined,()=>false,{displayOnly:true,backendId:'claude'})).toEqual([]); }); + +for(const mode of ['content','count'] as const)test(`display Grep ${mode} guards parsed paths rather than match text`,()=>{ + const output=mode==='content'?`notes/loom.md:7:${'s'.repeat(1100)}`:`notes/loom.md:${'7'.repeat(1100)}`; + const signals=outputTaintSignals('Grep',output,undefined,path=>path==='notes/loom.md',{displayOnly:true,backendId:'claude',outputMode:mode,lineNumbers:true}); + expect(signals.map(signal=>signal.source).sort(),'LONG_CONTENT_RETAINS_MARK_AND_UNKNOWN').toEqual(['legacy_unknown','user_marked']); +}); +test('unparseable oversized candidates retain independent later marks without throwing',()=>{ + const signals=outputTaintSignals('Grep',`${'x'.repeat(1100)}:1:echo\nnotes/loom.md:2:sirens`,undefined,path=>path==='notes/loom.md',{displayOnly:true,backendId:'claude',outputMode:'content',lineNumbers:true}); + expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); +}); diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index 99ed880dee..d408642804 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -164,3 +164,17 @@ test('Claude display filenames preserve both workspace and mark evidence indepen expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(e=>e.payload.source).sort(),'DISPLAY_PATH_RETAINS_ALL_INDEPENDENT_SIGNALS').toEqual(['legacy_unknown','user_marked','workspace_read']); }finally{recorder.finish('success');db.close();} }); + +for(const mode of ['content','count'] as const)test(`Claude fallback recorder retains a mark from a long ${mode} row without abort`,async()=>{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks');const db=createUiDb(':memory:'),sessionId='voyage-long-display',aborted:Error[]=[]; + db.query("INSERT INTO sessions(id,created_at,last_active_at) VALUES(?,0,0)").run(sessionId);untrustedMarkOperations(db).mark('notes/loom.md',null,Date.UTC(2026,6,12)); + const recorder=createTurnRecorder({store:createActivityStore(db,{writer:'test'}),governanceDb:db,brainPath:brain,governance:event=>{recordGovernanceEvent(db,event);},abort:error=>aborted.push(error)},{turnId:'long-display',sessionId,profile:'governed'}); + try{ + const text=mode==='content'?`notes/loom.md:7:${'s'.repeat(1100)}`:`notes/loom.md:${'7'.repeat(1100)}`; + recorder.observeFrame({type:'tool_use_start',sessionId,toolUseId:'long_grep',toolName:'Grep'}); + recorder.observeFrame({type:'tool_use_complete',sessionId,toolUseId:'long_grep',toolName:'Grep',input:{pattern:'sirens',output_mode:mode}}); + for(const frame of adaptStreamEvent({type:'user',message:{content:[{type:'tool_result',tool_use_id:'long_grep',content:[{type:'text',text}]}]}} as never))if(frame.type==='tool_result')recorder.observeFrame({...frame,sessionId}); + expect(aborted,'LONG_MATCH_TEXT_IS_NOT_A_FATAL_FILENAME').toEqual([]); + expect(queryGovernanceEvents(db,{sessionId,kinds:['taint'],limit:10}).map(event=>event.payload.source).sort(),'LONG_ROW_PRESERVES_MARK_AND_UNKNOWN').toEqual(['legacy_unknown','user_marked']); + }finally{recorder.finish('success');db.close();} +}); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 0b707ba3cb..5167033d67 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -256,12 +256,14 @@ test("imported and legacy provisional histories remain unknown after new detecto expect(f.writes.safety(null,"imported").restriction).toBe("restricted"); }finally{await f.close();}}); -test("detector overflow stops collection rather than silently truncating later paths",async()=>{ +test("detector overflow retains bounded known paths plus an unknown remainder",async()=>{ const f=fixture();try{const {collector}=await fresh(f); await collector.begin("many","Grep",{path:"notes"}); const output=JSON.stringify({numFiles:257,filenames:Array.from({length:257},(_,i)=>`workspaces/voyage/map-${i}.md`)}); - await expectRejection(collector.result("many","Grep",output,true),"signal capacity"); - expect(f.writes.safety(null,"ithaca").reasons,"SAFETY_DETECTOR_OVERFLOW_LATCHED").toContain("recording_failed"); + await collector.result("many","Grep",output,true); + const recorded=f.db.query("SELECT source FROM safety_records WHERE kind='occurrence'").all() as {source:string}[];expect(recorded.filter(row=>row.source==="workspace_read")).toHaveLength(255);expect(recorded.filter(row=>row.source==="legacy_unknown")).toHaveLength(1); + expect(f.writes.safety(null,"ithaca").restriction).toBe("restricted"); + expect(f.writes.safety(null,"ithaca").reasons,"DETECTOR_LIMIT_IS_UNKNOWN_NOT_RECORDING_LOSS").not.toContain("recording_failed"); }finally{await f.close();}}); test("Claude delivery hooks await real SQLite commits before tool contact and result delivery, and refuse recorder loss",async()=>{ @@ -335,13 +337,15 @@ test("a clean search input cannot suppress mixed JSON paths, an explicit mark or expect(triggers(f).map(r=>(r.payload as {source:string}).source),"SAFETY_CLEAN_INPUT_CANNOT_HIDE_UNTRUSTED_JSON_OUTPUT").toEqual(["workspace_read","user_marked","legacy_unknown"]); }finally{await f.close();}}); -test("an unsupported recorder stops and persists a gap when input detection exceeds its bound",async()=>{ +test("a display recorder retains unknown without aborting when an input path exceeds its bound",async()=>{ const f=fixture();try{await fresh(f); const {createTurnRecorder}=await import("../src/activity/recorder"),{createActivityStore}=await import("../src/activity/store");let stopped:Error|undefined; - const recorder=createTurnRecorder({store:createActivityStore(f.db,{writer:"test"}),governanceDb:f.db,governanceWrites:f.writes,governance:event=>f.writes.record(event),abort:error=>{stopped=error;}},{turnId:"voyage",sessionId:"ithaca",profile:"governed"}); + const recorder=createTurnRecorder({store:createActivityStore(f.db,{writer:"test"}),governanceDb:f.db,governanceWrites:f.writes,governance:event=>f.writes.record(event),abort:error=>{stopped=error;}},{turnId:"display-limit",sessionId:"ithaca",profile:"governed"}); recorder.observeFrame({type:"tool_use_complete",sessionId:"ithaca",toolUseId:"too-long",toolName:"Read",input:{file_path:`workspaces/${"x".repeat(1024)}.md`}}); - expect(stopped?.message,"SAFETY_FALLBACK_DETECTOR_OVERFLOW_STOPS_TURN").toContain("detection failed"); - await recorder.settled();expect(f.writes.safety(null,"ithaca").reasons).toContain("recording_failed"); + recorder.observeFrame({type:"tool_result",sessionId:"ithaca",toolUseId:"too-long",output:"",isError:false}); + await recorder.settled();expect(stopped,"UNPARSEABLE_INPUT_DOES_NOT_ABORT_THE_TURN").toBeUndefined(); + expect(triggers(f).some(row=>(row.payload as {source:string}).source==="legacy_unknown")).toBe(true);expect(f.writes.safety(null,"ithaca").restriction).toBe("restricted"); + recorder.finish("success"); }finally{await f.close();}}); test("an imported provisional alias binds its actual owner and generation without inventing complete past coverage",async()=>{ @@ -602,11 +606,12 @@ test('Pi empty output never suppresses an independent untrusted input signal',as }finally{await f.close();} }); -test('excessive grep delimiter ambiguity refuses recording and retains a durable gap',async()=>{ +test('excessive grep delimiter ambiguity records an unknown remainder without a recording gap',async()=>{ const f=fixture();try{const {collector}=await fresh(f,'voyage','ithaca','pi'); await collector.begin('bounded_search','grep',{path:'.',pattern:'sirens'}); - await expectRejection(collector.result('bounded_search','grep',`notes/voyage${':1'.repeat(300)}:sirens`,true),'Safety search candidate capacity exceeded','SEARCH_AMBIGUITY_CAPACITY_STOPS_RECORDING'); - expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:'recording_failed'}); + await collector.result('bounded_search','grep',`notes/voyage${':1'.repeat(300)}:sirens`,true); + expect(triggers(f).map(row=>(row.payload as {source:string}).source)).toEqual(['legacy_unknown']); + expect(f.db.query("SELECT failure FROM safety_collections WHERE turn_id='voyage'").get()).toEqual({failure:null}); expect(f.writes.safety(null,'ithaca').restriction).toBe('restricted'); }finally{await f.close();} }); From 77b363d63049e7d9dddd988efb741ff6320d9a05 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 02:55:30 +0000 Subject: [PATCH 18/23] fix: make search evidence parsing total at capacity boundaries --- docs/plans/reviewable-session-safety.md | 2 +- .../ui-server/src/activity/ingestion-taint.ts | 13 +++++++----- .../tests/ingestion-taint-schema.test.ts | 21 +++++++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 3214ab2428..84f2a4f0b9 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -30,7 +30,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:158-178`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:202-328`). + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:202-331`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery. Normal Claude collection uses the SDK PostToolUse structured tool_response; collector readiness disables diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 5282650483..dac5b620d4 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -201,15 +201,17 @@ export function searchOutputComplete(output:string,status:InputSafetyOutputStatu export function outputTaintSignals(tool: string, output: string, brainPath?: string, marked?: MarkedLookup, context?: SearchOutputContext): IngestionSignal[] { if (!SEARCH_TOOLS.has(tool)) return []; + const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=false; + try{ const oversized=Buffer.byteLength(output)>1048576; if(oversized)output=Buffer.from(output.slice(0,1048576)).subarray(0,1048576).toString('utf8'); - const result:IngestionSignal[]=[],seen=new Set(),contentPaths=new Set();let unknown=oversized||context?.outputComplete===false; + unknown=oversized||context?.outputComplete===false; const add=(path:string)=>{ if(!path||path.includes('\0')){unknown=true;return;} for(const signal of fileSignals(path,brainPath,marked,'tool_search_output')){ if(signal.source==='legacy_unknown'){unknown=true;continue;} const key=JSON.stringify([signal.detector,signal.key]);if(seen.has(key))continue; - if(result.length>=255){unknown=true;continue;}seen.add(key);result.push(signal); + if(result.length>=256){unknown=true;continue;}seen.add(key);result.push(signal); } }; const content=(text:string,numbers:boolean)=>{ @@ -241,7 +243,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str // filename as JSON; preserve known paths and retain boundary uncertainty. if(output.length){ unknown=true; - const allLines=output.split('\n'),lines=allLines.slice(0,256); + const lines=output.split('\n'); // Literal filenames are candidates only in filename mode. Match text // is not a filename and must not consume the path budget. const filenames=tool==='Glob'||context.outputMode==='files_with_matches'; @@ -287,7 +289,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str value.totalMatches!==undefined&&value.totalMatches!==value.numFiles||value.countIsComplete===true&&value.totalMatches===undefined)unknown=true;} }else if((context?.backendId??'claude')==='claude'&&tool==='Grep'){ const checked=grepOutput.safeParse(parsed),mode=context?.outputMode; - if(!checked.success||!['files_with_matches','content','count'].includes(mode??'')){unknown=true;salvage(parsed,mode);if(parsed&&typeof parsed==='object'&&'mode' in parsed)salvage(parsed,String(parsed.mode));} + if(!checked.success||!['files_with_matches','content','count'].includes(mode??'')){unknown=true;salvage(parsed,mode);if(parsed&&typeof parsed==='object'&&'mode' in parsed&&typeof parsed.mode==='string')salvage(parsed,parsed.mode);} else {const value=checked.data;for(const path of value.filenames)add(path); if(value.mode!==undefined&&value.mode!==mode)salvage(value,value.mode); const lines=mode==='files_with_matches'?value.filenames.length:value.content?value.content.split('\n').length:0; @@ -322,7 +324,8 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(value.numMatches!==undefined&&value.numMatches!==matches)unknown=true; } }else unknown=true; - if(unknown){result.push({source:'legacy_unknown',detector:'tool_search_output',key:'unknown_remainder'});} + }catch{unknown=true;} + if(unknown){if(result.length===256)result.pop();result.push({source:'legacy_unknown',detector:'tool_search_output',key:'unknown_remainder'});} return result; } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index ecc6f6ea23..f04955b1e2 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -134,3 +134,24 @@ test('unparseable oversized candidates retain independent later marks without th const signals=outputTaintSignals('Grep',`${'x'.repeat(1100)}:1:echo\nnotes/loom.md:2:sirens`,undefined,path=>path==='notes/loom.md',{displayOnly:true,backendId:'claude',outputMode:'content',lineNumbers:true}); expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); }); + +test('malformed mode never coerces and retains marked siblings',()=>{ + const signals=outputTaintSignals('Grep',grep(['notes/loom.md'],{mode:{toString:null}}),undefined,path=>path==='notes/loom.md',searchOutputContext('Grep',{})); + expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); +}); +test('display filename marks after row 256 remain identifiable within the byte budget',()=>{ + const rows=[...Array.from({length:256},(_,i)=>`notes/ordinary-${i}.md`),'notes/loom.md']; + const signals=outputTaintSignals('Grep',rows.join('\n'),undefined,path=>path==='notes/loom.md',{backendId:'claude',displayOnly:true,outputMode:'files_with_matches'}); + expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); +}); +for(const count of [256,257])test(`complete search signal boundary: ${count}`,()=>{ + const paths=Array.from({length:count},(_,i)=>`notes/loom-${i}.md`); + const signals=outputTaintSignals('Grep',grep(paths),undefined,()=>true,searchOutputContext('Grep',{head_limit:0})); + expect(signals.filter(signal=>signal.source==='user_marked')).toHaveLength(count===256?256:255); + expect(signals.filter(signal=>signal.source==='legacy_unknown')).toHaveLength(count===256?0:1); +}); +test('unexpected detector failure retains marks already found plus unknown',()=>{ + const context={backendId:'claude',outputMode:'content',get lineNumbers():boolean{throw new Error('Malformed selector');}}; + const signals=outputTaintSignals('Grep',grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens'}),undefined,()=>true,context); + expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); +}); From dedbb88daad818400cf919e5762630b45a8be292 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 03:09:32 +0000 Subject: [PATCH 19/23] fix: retain discriminated search evidence through byte decoding and bounds --- docs/plans/reviewable-session-safety.md | 4 +-- packages/ui-backend-pi/src/file-tools.ts | 9 ++++-- packages/ui-backend-pi/src/worker-protocol.ts | 4 +-- .../ui-server/src/activity/ingestion-taint.ts | 28 +++++++++++++++++-- .../src/governance/safety-collector.ts | 4 +-- .../tests/ingestion-taint-schema.test.ts | 5 ++++ .../tests/safety-result-exits.test.ts | 18 ++++++++++++ 7 files changed, 61 insertions(+), 11 deletions(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 84f2a4f0b9..8047fbb23c 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -29,8 +29,8 @@ public design or its fixtures. Fictional examples use the Odysseus world. their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, - `packages/ui-server/src/activity/ingestion-taint.ts:158-178`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:202-331`). + `packages/ui-server/src/activity/ingestion-taint.ts:164-184`; + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:226-355`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery. Normal Claude collection uses the SDK PostToolUse structured tool_response; collector readiness disables diff --git a/packages/ui-backend-pi/src/file-tools.ts b/packages/ui-backend-pi/src/file-tools.ts index 43dbed5f46..77868f4db8 100644 --- a/packages/ui-backend-pi/src/file-tools.ts +++ b/packages/ui-backend-pi/src/file-tools.ts @@ -72,8 +72,11 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const stderrPresent=(async()=>{let present=false;for await(const chunk of proc.stderr)if(chunk.byteLength)present=true;return present;})(); const [outBytes,stderr,exitCode]=await Promise.all([new Response(proc.stdout).arrayBuffer(),stderrPresent,proc.exited]); // A leading BOM can be part of a POSIX filename, not stream metadata. - const decoder=new TextDecoder("utf-8",{ignoreBOM:true}); - const out=decoder.decode(outBytes); + let decodingLoss=false,out:string; + try{out=new TextDecoder("utf-8",{ignoreBOM:true,fatal:true}).decode(outBytes);} + catch{decodingLoss=true;out=new TextDecoder("utf-8",{ignoreBOM:true}).decode(outBytes);} + // Marks use Unicode path strings, not raw byte keys. Invalid filename + // bytes cannot prove a complete lookup; retain unknown host evidence. signal?.removeEventListener("abort", onAbort); // Keep an unambiguous machine boundary in host-only result details. // POSIX filenames may contain newlines, colons and edge whitespace. @@ -96,7 +99,7 @@ export function grepTool(kit: BrainToolKit): ToolDefinition { const bytes=Buffer.from(frame.slice(0,end)),frameClipped=bytes.length>1048576; // Leave room for a decoder replacement if the byte cut splits UTF-8. const framedOutput=frameClipped?bytes.subarray(0,1048573).toString('utf8'):frame.slice(0,end); - return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr,truncated:displayTruncated||frameClipped,stdoutEmpty:outBytes.byteLength===0,framedOutput,visibleText}}); + return textResult(visibleText, {pattern:params.pattern,search:{exitCode,stderr,decodingLoss,truncated:displayTruncated||frameClipped,stdoutEmpty:outBytes.byteLength===0,framedOutput,visibleText}}); }, } satisfies ToolDefinition; } diff --git a/packages/ui-backend-pi/src/worker-protocol.ts b/packages/ui-backend-pi/src/worker-protocol.ts index 69db334550..ffdcdd05af 100644 --- a/packages/ui-backend-pi/src/worker-protocol.ts +++ b/packages/ui-backend-pi/src/worker-protocol.ts @@ -90,7 +90,7 @@ export const piWorkerMessage = z.discriminatedUnion("type", [ export type PiWorkerMessage = z.infer; export const piOutputStatus=z.object({complete:z.boolean(),exitCode:z.number().int().optional(),stderr:z.boolean().optional(),truncated:z.boolean().optional()}).strict(); -const searchStatus=z.object({stdoutEmpty:z.boolean().optional(),exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional(),visibleText:z.string().optional()}).strict(); +const searchStatus=z.object({decodingLoss:z.boolean().optional(),stdoutEmpty:z.boolean().optional(),exitCode:z.number().int(),stderr:z.boolean(),truncated:z.boolean(),framedOutput:z.string().optional(),visibleText:z.string().optional()}).strict(); /** Host-only observation. Never alter provider result content to encode status. */ export function safetyResultInput(tool:string,content:readonly {type:string;text?:unknown}[],complete=true,details?:unknown): {output:string;segments?:string[];outputStatus:z.infer} { const segments=content.filter(part=>part.type==='text'&&typeof part.text==='string').map(part=>part.text as string),output=segments.join('\n'); @@ -100,7 +100,7 @@ export function safetyResultInput(tool:string,content:readonly {type:string;text const framed=status.success?status.data.framedOutput:undefined; const rendered=framed?.replaceAll('\0','').trim(); const bound=framed===undefined?output==='No matches.':status.success&&status.data.truncated?status.data.visibleText===output&&(output.length>MAX_OUTPUT_BYTES?framed.replaceAll('\0','').trimStart()===output.slice(0,MAX_OUTPUT_BYTES):rendered===output):rendered===output; - const successful=bound&&status.success&&!status.data.stderr&&!status.data.truncated&& + const successful=bound&&status.success&&!status.data.decodingLoss&&!status.data.stderr&&!status.data.truncated&& (status.data.exitCode===0&&output.length>0&&output!=='No matches.'||status.data.exitCode===1&&status.data.stdoutEmpty===true&&output==='No matches.'); const processStatus=status.success?{exitCode:status.data.exitCode,stderr:status.data.stderr,truncated:status.data.truncated}:{}; return {output:bound?(framed??output):output,segments,outputStatus:{...processStatus,complete:original&&successful}}; diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index dac5b620d4..45bf325e5e 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -133,6 +133,12 @@ export interface IngestionSignal { key: string; } +/** User-controlled keys cannot alias synthetic coverage evidence. */ +export function ingestionSignalIdentity(signal:IngestionSignal):string { + const kind=signal.source==='legacy_unknown'?'synthetic':signal.detector==='explicit_untrusted_input'||signal.detector==='tool_web_input'?'user':'structural'; + return JSON.stringify([kind,signal.source,signal.detector,signal.key]); +} + /** Versioned installed-tool inventory. Completeness still needs delivery hooks and epoch acknowledgement. */ export const INGESTION_DETECTOR_MANIFEST = { version: 1, @@ -199,6 +205,24 @@ export function searchOutputComplete(output:string,status:InputSafetyOutputStatu (status.exitCode===undefined||status.exitCode===0&&output.length>0&&output!=="No matches."||status.exitCode===1&&output==="No matches."); } +/** Parse complete top-level fields within the byte budget. An oversized content + * string must not erase a preceding, independently complete filenames array. */ +function completeSearchFields(prefix:string):unknown { + const fields:Record=Object.create(null); + const first=prefix.search(/\S/);if(prefix[first]!=='{')return fields; + let start=first+1,depth=1,quoted=false,escaped=false; + const keep=(end:number)=>{try{Object.assign(fields,JSON.parse('{'+prefix.slice(start,end)+'}'));}catch{/* Only independently complete fields survive. */}}; + for(let i=start;i(),contentPaths=new Set();let unknown=false; @@ -210,7 +234,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(!path||path.includes('\0')){unknown=true;return;} for(const signal of fileSignals(path,brainPath,marked,'tool_search_output')){ if(signal.source==='legacy_unknown'){unknown=true;continue;} - const key=JSON.stringify([signal.detector,signal.key]);if(seen.has(key))continue; + const key=ingestionSignalIdentity(signal);if(seen.has(key))continue; if(result.length>=256){unknown=true;continue;}seen.add(key);result.push(signal); } }; @@ -237,7 +261,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(mode==='count')for(const line of fields.content.split('\n')){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} }; const display=context?.displayOnly&&(tool==='Glob'||tool==='Grep'); - let parsed:unknown;if(!display)try{parsed=JSON.parse(output);}catch{/* Hook objects require a validated schema. */} + let parsed:unknown;if(!display)try{parsed=oversized?completeSearchFields(output):JSON.parse(output);}catch{/* Hook objects require a validated schema. */} if(display){ // SDK display text has no filename framing. Never reinterpret a literal // filename as JSON; preserve known paths and retain boundary uncertainty. diff --git a/packages/ui-server/src/governance/safety-collector.ts b/packages/ui-server/src/governance/safety-collector.ts index c820694f33..1d0815190e 100644 --- a/packages/ui-server/src/governance/safety-collector.ts +++ b/packages/ui-server/src/governance/safety-collector.ts @@ -1,7 +1,7 @@ /** Concrete turn-bound pre-delivery collector. All decisions remain restrictive. */ import type { BackendBridge } from "@schlessera/brain-ui-sdk/server"; import type { Database } from "bun:sqlite"; -import { inputTaintSignals, outputTaintSignals, searchOutputComplete, searchOutputContext, type IngestionSignal } from "../activity/ingestion-taint.js"; +import { ingestionSignalIdentity, inputTaintSignals, outputTaintSignals, searchOutputComplete, searchOutputContext, type IngestionSignal } from "../activity/ingestion-taint.js"; import { isMarkedUntrusted } from "../files/untrusted-marks.js"; import { occurrence } from "./occurrence.js"; import type { GovernanceWrites } from "./event-writes.js"; @@ -122,7 +122,7 @@ export function createSafetyCollector(db:Database,writes:GovernanceWrites,option op.inputHashes.add(inputHash);op.admitted=false;operations.set(toolUseId,op); op.searchContext=searchOutputContext(tool,input,options.backendId); for(const signal of inputTaintSignals(tool,input,options.brainPath,marked,options.shellProxied())){ - if(op.signals.some(prior=>prior.detector===signal.detector&&prior.key===signal.key))continue; + if(op.signals.some(prior=>ingestionSignalIdentity(prior)===ingestionSignalIdentity(signal)))continue; const item=observed(toolUseId,signal.detector,op.id); await writes.firstTaint({...base(),kind:"taint",payload:{source:signal.source,tool,detail:null,occurrence:item}},{beforeDelivery:true}); op.occurrences.push(item.id);op.signals.push(signal); diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index f04955b1e2..6aaa07181a 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -155,3 +155,8 @@ test('unexpected detector failure retains marks already found plus unknown',()=> const signals=outputTaintSignals('Grep',grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens'}),undefined,()=>true,context); expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); }); +test('oversized structured content retains complete filename fields inside the parse budget',()=>{ + const output=grep(['notes/loom.md'],{content:'s'.repeat(1048577)}); + const signals=outputTaintSignals('Grep',output,undefined,path=>path==='notes/loom.md',searchOutputContext('Grep',{output_mode:'content'})); + expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); +}); diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 752cd1e136..0e8a52ba46 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -751,3 +751,21 @@ test('ready Claude collection records structured hook searches instead of ambigu recorder.finish('success'); }finally{await f.close();} }); +test('user query text cannot collide with the synthetic overflow occurrence',async()=>{ + const f=await voyage('claude');try{ + await f.collector.begin('query_collision','WebSearch',{queries:['unknown_remainder','s'.repeat(2049)]}); + expect(f.db.query("SELECT source,detector FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all()).toEqual([{source:'web_search',detector:'tool_web_input'},{source:'legacy_unknown',detector:'tool_web_input'}]); + }finally{await f.close();} +}); +test('invalid UTF-8 grep filename bytes retain unknown alongside valid marked rows',async()=>{ + const f=await voyage();try{ + const {untrustedMarkOperations}=await import('../src/files/untrusted-marks');untrustedMarkOperations(f.db).mark('notes/loom.md',null,Date.UTC(2026,6,12)); + const raw=Buffer.concat([Buffer.from('notes/'),Buffer.from([0xff]),Buffer.from('.md\0'+'1:sirens\nnotes/'),Buffer.from([0xfe]),Buffer.from('.md\0'+'1:sirens\nnotes/loom.md\0'+'1:sirens\n')]); + const wrapper=join(f.brain,'fake-grep');writeFileSync(join(f.brain,'grep-data'),raw);writeFileSync(wrapper,'#!/bin/sh\ncat "$(dirname "$0")/grep-data"\n',{mode:0o755}); + const input={pattern:'sirens'},id='invalid_filename_bytes';await f.collector.begin(id,'grep',input); + const result=await runSearchTool(f,id,input,wrapper),observed=safetyResultInput('grep',result.content,true,result.details); + expect(observed.outputStatus.complete,'DECODING_LOSS_IS_NEVER_COMPLETE').toBe(false); + await f.collector.result(id,'grep',observed.output,true,observed.segments,observed.outputStatus); + expect(f.db.query("SELECT source FROM safety_records WHERE kind='occurrence' ORDER BY length(sequence),sequence").all()).toEqual([{source:'user_marked'},{source:'legacy_unknown'}]); + }finally{await f.close();} +}); From 1274df21b069d2833cd51a708e59f5d5635a4b0a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 03:41:42 +0000 Subject: [PATCH 20/23] fix: retain complete filename elements at every byte cutoff --- docs/plans/reviewable-session-safety.md | 2 +- .../ui-server/src/activity/ingestion-taint.ts | 18 ++++++++++++++++++ .../tests/ingestion-taint-schema.test.ts | 13 +++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 8047fbb23c..ac151e92af 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -30,7 +30,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:164-184`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:226-355`). + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:244-373`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery. Normal Claude collection uses the SDK PostToolUse structured tool_response; collector readiness disables diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 45bf325e5e..bcb3062ef3 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -220,6 +220,24 @@ function completeSearchFields(prefix:string):unknown { else if(c==='}'||c===']'){if(depth===1){keep(i);break;}depth--;} else if(c===','&&depth===1){keep(i);start=i+1;} } + // The last top-level field may be an unfinished filenames array. Its + // independently closed string elements remain identifiable before the cut. + const tail=prefix.slice(start),key=/^\s*("(?:[^"\\]|\\.)*")\s*:\s*\[/.exec(tail); + let filenameKey=false;try{filenameKey=!!key&&JSON.parse(key[1]!)==='filenames';}catch{/* Invalid keys cannot identify an array. */} + if(key&&filenameKey){ + const paths:string[]=[];let level=1,inString=false,escape=false,token=-1; + for(let i=key[0].length;i0;i++){ + const c=tail[i]; + if(inString){ + if(escape)escape=false;else if(c==='\\')escape=true;else if(c==='"'){ + inString=false;if(token>=0){try{paths.push(JSON.parse(tail.slice(token,i+1)));}catch{/* Malformed strings cannot identify a path. */}token=-1;} + } + }else if(c==='"'){inString=true;token=level===1?i:-1;} + else if(c==='['||c==='{')level++; + else if(c===']'||c==='}')level--; + } + fields.filenames=[...(Array.isArray(fields.filenames)?fields.filenames:[]),...paths]; + } return fields; } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 6aaa07181a..80357bb139 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -160,3 +160,16 @@ test('oversized structured content retains complete filename fields inside the p const signals=outputTaintSignals('Grep',output,undefined,path=>path==='notes/loom.md',searchOutputContext('Grep',{output_mode:'content'})); expect(signals.map(signal=>signal.source).sort()).toEqual(['legacy_unknown','user_marked']); }); + +test('byte cutoff at every array position retains every complete filename element',()=>{ + const paths=['workspaces/voyage/raft.md','notes/lo"om.md','notes/a\nb.md'],array=JSON.stringify(paths); + let end=1;const ends=paths.map(path=>{end+=JSON.stringify(path).length;const result=end;end++;return result;}); + for(let cut=0;cut<=array.length;cut++){ + const before='{"padding":"',after='","filenames":',padding=1048576-before.length-after.length-cut; + const output=before+' '.repeat(padding)+after+array+',"content":"'+ 's'.repeat(100)+'"}'; + const signals=outputTaintSignals('Grep',output,undefined,path=>paths.includes(path),searchOutputContext('Grep',{head_limit:0})); + const expected=paths.filter((_,index)=>ends[index]!<=cut).flatMap(path=>[...(path.startsWith('workspaces/')?['workspace_read:'+path]:[]),'user_marked:'+path]); + expected.push('legacy_unknown:unknown_remainder'); + expect(signals.map(signal=>signal.source+':'+signal.key).sort(),'ARRAY_BYTE_CUT_'+cut).toEqual(expected.sort()); + } +}); From dc74c19426aa1a09f1c99023737724325c416a74 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 04:09:35 +0000 Subject: [PATCH 21/23] fix: parse verified Claude Grep modes and all partial arrays --- docs/plans/reviewable-session-safety.md | 2 +- .../ui-server/src/activity/ingestion-taint.ts | 68 ++++++++++--------- .../tests/ingestion-taint-schema.test.ts | 46 ++++++++++--- .../ui-server/tests/safety-ledger.test.ts | 2 +- .../tests/safety-result-exits.test.ts | 2 +- 5 files changed, 77 insertions(+), 43 deletions(-) diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index ac151e92af..2dc6f1f6db 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -30,7 +30,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:164-184`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:244-373`). + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:244-377`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery. Normal Claude collection uses the SDK PostToolUse structured tool_response; collector readiness disables diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index bcb3062ef3..7d805acef5 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -185,7 +185,7 @@ export function inputTaintSignals(tool: string, input: unknown, brainPath?: stri } /** Admitted format only. Invalid or incomplete output always retains unknown coverage. */ -interface SearchOutputContext { displayOnly?:boolean; backendId?: string; outputMode?: string; lineNumbers?: boolean; offset?: number; limit?: number; outputComplete?: boolean } +interface SearchOutputContext { displayOnly?:boolean; backendId?: string; outputMode?: string; lineNumbers?: boolean; contextRows?:boolean; offset?: number; limit?: number; outputComplete?: boolean } // Installed SDK: GlobInput/GrepInput and GlobOutput/GrepOutput in // @anthropic-ai/claude-agent-sdk/sdk-tools.d.ts:905-983,3506-3545. Pi's shipped grep and text // envelope are `grepTool` (packages/ui-backend-pi/src/file-tools.ts:44-82) @@ -258,12 +258,13 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str }; const content=(text:string,numbers:boolean)=>{ for(const line of text.split('\n')){ + if(line==='--'&&context?.contextRows)continue; if(!line){unknown=true;continue;} let count=0; // No line numbers: every colon could separate the filename and content. // With numbers: lookahead preserves overlapping `:2:7:` candidates. - for(const split of line.matchAll(numbers?/(?=:[1-9][0-9]*:)/g:/(?=:)/g)){ - if(count++>=256){unknown=true;break;}const path=line.slice(0,split.index);contentPaths.add(path);add(path); + for(const split of line.matchAll(numbers?/(?=([:-])[1-9][0-9]*\1)/g:context?.contextRows?/(?=[:\-])/g:/(?=:)/g)){ + if(count++>=256){unknown=true;break;}const path=line.slice(0,split.index);if(numbers&&split[1]==='-'&&!context?.contextRows)unknown=true;contentPaths.add(path);add(path); } if(count!==1)unknown=true; } @@ -279,7 +280,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(mode==='count')for(const line of fields.content.split('\n')){const split=/:([1-9][0-9]*)$/.exec(line);if(split)add(line.slice(0,split.index));} }; const display=context?.displayOnly&&(tool==='Glob'||tool==='Grep'); - let parsed:unknown;if(!display)try{parsed=oversized?completeSearchFields(output):JSON.parse(output);}catch{/* Hook objects require a validated schema. */} + let parsed:unknown;if(!display&&(tool==='Glob'||tool==='Grep'))try{parsed=oversized?completeSearchFields(output):JSON.parse(output);}catch{parsed=completeSearchFields(output);unknown=true;} if(display){ // SDK display text has no filename framing. Never reinterpret a literal // filename as JSON; preserve known paths and retain boundary uncertainty. @@ -334,36 +335,39 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(!checked.success||!['files_with_matches','content','count'].includes(mode??'')){unknown=true;salvage(parsed,mode);if(parsed&&typeof parsed==='object'&&'mode' in parsed&&typeof parsed.mode==='string')salvage(parsed,parsed.mode);} else {const value=checked.data;for(const path of value.filenames)add(path); if(value.mode!==undefined&&value.mode!==mode)salvage(value,value.mode); + // Installed CLI 2.1.293, embedded `lno` Grep construction: + // @anthropic-ai/claude-agent-sdk-linux-x64/claude:1464467-1464477 + // (content return at byte 0xcb4ffdf, count return at 0xcb50202). + // Content always reports numFiles=0/filenames=[]; count reports all + // matching files and match totals but leaves filenames empty. `lno` + // preserves both ':' match and '-' context separators from `pno`. + // `cDe` reports appliedLimit only when it omitted additional rows. const lines=mode==='files_with_matches'?value.filenames.length:value.content?value.content.split('\n').length:0; - const total=mode==='content'?value.totalLines:value.totalFiles; + const total=mode==='content'?value.totalLines:mode==='count'?value.numFiles:value.totalFiles; const limits=[value.appliedLimit??0,context?.limit??250]; - // An optional total cannot be invented from a full page. Offset pages - // omit earlier sources even if their returned page is otherwise valid. - if(value.mode!==undefined&&value.mode!==mode||value.numFiles!==value.filenames.length|| - new Set(value.filenames).size!==value.filenames.length|| - value.totalFiles!==undefined&&value.totalFiles!==value.numFiles|| - (value.appliedOffset??0)>0||(context?.offset??0)>0|| - limits.some(limit=>limit>0&&(lines>limit||lines===limit&&total===undefined))|| - value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines)unknown=true; - let matches=mode==='files_with_matches'?value.numFiles:lines; - if(mode==='files_with_matches'){if(value.content!==undefined&&value.content!==''){unknown=true;salvage(value,value.mode==='count'?'count':'content');}} - else if(value.content===undefined)unknown=true; - else { - if(!value.content&&value.numFiles>0)unknown=true; - if(mode==='content'){if(value.content)content(value.content,context?.lineNumbers!==false);} - else { - matches=0; - for(const line of value.content?value.content.split('\n'):[]){ - const split=/:([1-9][0-9]*)$/.exec(line); - if(split){const path=line.slice(0,split.index);if(contentPaths.has(path))unknown=true;contentPaths.add(path);add(path);matches+=Number(split[1]);if(!Number.isSafeInteger(matches))unknown=true;} - else unknown=true; - } + if(value.mode!==undefined&&value.mode!==mode||new Set(value.filenames).size!==value.filenames.length|| + value.appliedLimit!==undefined||(value.appliedOffset??0)>0||(context?.offset??0)>0|| + limits.some(limit=>limit>0&&(lines>limit||lines===limit&&total===undefined)))unknown=true; + if(mode==='files_with_matches'){ + if(value.numFiles!==value.filenames.length||value.totalFiles!==undefined&&value.totalFiles!==value.numFiles|| + value.numLines!==undefined||value.totalLines!==undefined||value.numMatches!==undefined&&value.numMatches!==value.numFiles)unknown=true; + if(value.content!==undefined&&value.content!==''){unknown=true;salvage(value,value.mode==='count'?'count':'content');} + }else if(mode==='content'){ + if(value.content===undefined||value.numFiles!==0||value.filenames.length!==0|| + value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines|| + value.numMatches!==undefined||value.totalFiles!==undefined)unknown=true; + if(value.content)content(value.content,context?.lineNumbers!==false); + }else{ + let matches=0; + if(value.content===undefined||value.filenames.length!==0||value.numLines!==undefined||value.totalLines!==undefined)unknown=true; + for(const line of value.content?value.content.split('\n'):[]){ + const split=/:([1-9][0-9]*)$/.exec(line); + if(split){const path=line.slice(0,split.index);if(contentPaths.has(path))unknown=true;contentPaths.add(path);add(path);matches+=Number(split[1]);if(!Number.isSafeInteger(matches))unknown=true;} + else unknown=true; } + if(value.numFiles!==contentPaths.size||value.numMatches!==undefined&&value.numMatches!==matches|| + value.totalFiles!==undefined&&value.totalFiles!==value.numFiles)unknown=true; } - if(mode!=='files_with_matches'&&(value.numFiles!==contentPaths.size||value.filenames.some(path=>!contentPaths.has(path))))unknown=true; - // Only counts accounted for by the identified output can establish - // completeness; unsupported count semantics remain restrictive. - if(value.numMatches!==undefined&&value.numMatches!==matches)unknown=true; } }else unknown=true; }catch{unknown=true;} @@ -375,6 +379,8 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str export function searchOutputContext(tool:string,input:unknown,backendId=tool==='grep'?'pi':'claude'):SearchOutputContext { if(tool!=='Grep')return {backendId}; const value=input&&typeof input==='object'?input as Record:{}; + const contextValid=['-A','-B','-C','context'].every(key=>value[key]===undefined||typeof value[key]==='number'&&Number.isSafeInteger(value[key])&&(value[key] as number)>=0); + const contextRows=['-A','-B','-C','context'].some(key=>typeof value[key]==='number'&&(value[key] as number)>0); const mode=value.output_mode===undefined?'files_with_matches':value.output_mode,numbers=value['-n']===undefined?true:value['-n'],offset=value.offset===undefined?0:value.offset,limit=value.head_limit===undefined?250:value.head_limit; - return {backendId,outputMode:typeof mode==='string'&&['content','files_with_matches','count'].includes(mode)&&typeof numbers==='boolean'&&Number.isSafeInteger(offset)&&Number(offset)>=0&&Number.isSafeInteger(limit)&&Number(limit)>=0?mode:'unknown',lineNumbers:numbers===true,offset:typeof offset==='number'?offset:0,limit:typeof limit==='number'?limit:250}; + return {backendId,outputMode:contextValid&&typeof mode==='string'&&['content','files_with_matches','count'].includes(mode)&&typeof numbers==='boolean'&&Number.isSafeInteger(offset)&&Number(offset)>=0&&Number.isSafeInteger(limit)&&Number(limit)>=0?mode:'unknown',lineNumbers:numbers===true,contextRows,offset:typeof offset==='number'?offset:0,limit:typeof limit==='number'?limit:250}; } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 80357bb139..114cb9ce96 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -7,11 +7,11 @@ for(const [name,tool,input,output,expected] of [ ['Pi bracket filename and independent later mark','grep',{},'[voyage]/log.md:\0'+'1:sirens\nnotes/voyage.md:\0'+'2:echo\n',['user_marked','user_marked']], ['Pi malformed line retains later mark','grep',{},'{malformed\nnotes/voyage.md:2:echo',['user_marked','legacy_unknown']], ['Grep at page limit without total','Grep',{},grep(['notes/loom.md'],{appliedLimit:1}),['legacy_unknown']], - ['Grep known complete limit','Grep',{},grep(['notes/loom.md'],{appliedLimit:1,totalFiles:1}),[]], + ['Grep inconsistent reported limit','Grep',{},grep(['notes/loom.md'],{appliedLimit:1,totalFiles:1}),['legacy_unknown']], ['Grep input limit without metadata','Grep',{head_limit:1},grep(['notes/loom.md']),['legacy_unknown']], ['Grep empty count claims matches','Grep',{output_mode:'count'},grep([],{content:'',numMatches:3}),['legacy_unknown']], ['Grep wrong sum','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:2',numMatches:3}),['legacy_unknown']], - ['Grep correct sum','Grep',{output_mode:'count'},grep(['notes/loom.md'],{content:'notes/loom.md:2',numMatches:2}),[]], + ['Grep correct sum','Grep',{output_mode:'count'},grep([],{numFiles:1,content:'notes/loom.md:2',numMatches:2}),[]], ['Grep empty content claims matches','Grep',{output_mode:'content'},grep([],{content:'',numMatches:3}),['legacy_unknown']], ['Grep empty files claims matches','Grep',{},grep([],{numMatches:3}),['legacy_unknown']], ['Grep files have missing content','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:''}),['legacy_unknown']], @@ -28,8 +28,8 @@ for(const [name,tool,input,output,expected] of [ ['Grep count at limit without total','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:2',appliedLimit:1}),['legacy_unknown']], ['Grep zero count entry','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:0',numMatches:0}),['legacy_unknown']], ['Grep wrong reported offset','Grep',{offset:1},grep([],{appliedOffset:0}),['legacy_unknown']], - ['Grep unbounded limit','Grep',{head_limit:0},grep(['notes/loom.md'],{appliedLimit:0}),[]], - ['Grep zero reported files with identified content','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens'}),['legacy_unknown']], + ['Grep unbounded limit','Grep',{head_limit:0},grep(['notes/loom.md']),[]], + ['Grep content has no reported filename count','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens'}),[]], ['Grep count mismatched filenames','Grep',{output_mode:'count'},grep(['notes/other.md'],{content:'notes/loom.md:1',numMatches:1}),['legacy_unknown']], ['Grep reported unlimited cannot hide input limit','Grep',{head_limit:1},grep(['notes/loom.md'],{appliedLimit:0}),['legacy_unknown']], ['Grep content count contradicts lines','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens',numMatches:2}),['legacy_unknown']], @@ -72,14 +72,14 @@ for(const [name,tool,input,output,expected] of [ ['mixed Pi sentinel','grep',{},'notes/voyage.md:1:sirens\nNo matches.',['user_marked','legacy_unknown']], ['Claude pagination','Grep',{},grep(['notes/loom.md'],{totalFiles:2}),['legacy_unknown']], ['arbitrary Pi JSON sentinel','grep',{},JSON.stringify({matches:'No matches.'}),['legacy_unknown']], - ['clipped Glob JSON','Glob',{},'{"filenames":["notes/voyage.md"',['legacy_unknown']], + ['clipped Glob JSON','Glob',{},'{"filenames":["notes/voyage.md"',['user_marked','legacy_unknown']], ['Claude no line numbers','Grep',{output_mode:'content','-n':false},grep([],{content:'notes/voyage.md:signal:2:echo',numLines:1}),['user_marked','legacy_unknown']], ['marked exact Glob','Glob',{},glob(['notes/voyage:2:home.md']),['user_marked']], ['complete Glob','Glob',{},glob(['notes/loom.md']),[]], ['Glob literal omission filename','Glob',{},glob(['notes/omitted.md'],{countIsComplete:true,totalMatches:1}),[]], ['Glob literal truncation filename','Glob',{},glob(['notes/truncated.md'],{countIsComplete:true,totalMatches:1}),[]], - ['Grep literal omission content','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:omitted',numLines:1}),[]], - ['Grep literal omission count path','Grep',{output_mode:'count'},grep(['notes/omitted.md'],{content:'notes/omitted.md:2',numMatches:2}),[]], + ['Grep literal omission content','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:omitted',numLines:1,totalLines:1}),[]], + ['Grep literal omission count path','Grep',{output_mode:'count'},grep([],{numFiles:1,content:'notes/omitted.md:2',numMatches:2}),[]], ['Pi exact literal omission path','grep',{},'notes/omitted.md:\0'+'1:sirens\n',[]], ['Glob total omitted','Glob',{},glob(['notes/loom.md'],{totalMatches:2}),['legacy_unknown']], ['Glob lower bound','Glob',{},glob(['notes/loom.md'],{countIsComplete:false}),['legacy_unknown']], @@ -91,9 +91,9 @@ for(const [name,tool,input,output,expected] of [ ['Grep wrong mode','Grep',{},grep([],{mode:'content'}),['legacy_unknown']], ['Grep omitted lines','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',numLines:1,totalLines:2}),['legacy_unknown']], ['Grep offset','Grep',{offset:1},grep([]),['legacy_unknown']], - ['Grep count colon filename','Grep',{output_mode:'count'},grep(['notes/voyage:2'],{content:'notes/voyage:2:7'}),['user_marked']], + ['Grep count colon filename','Grep',{output_mode:'count'},grep([],{numFiles:1,content:'notes/voyage:2:7',numMatches:7}),['user_marked']], ['Grep mode mismatch salvages content','Grep',{output_mode:'files_with_matches'},grep([],{mode:'content',content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked','legacy_unknown']], - ['Grep numbered content','Grep',{output_mode:'content'},grep(['notes/voyage.md'],{content:'notes/voyage.md:1:sirens',numLines:1}),['user_marked']], + ['Grep numbered content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage.md:1:sirens',numLines:1,totalLines:1}),['user_marked']], ['Grep ambiguous content','Grep',{output_mode:'content'},grep([],{content:'notes/voyage:2:7:sirens',numLines:1}),['user_marked','legacy_unknown']], ['Pi exact sentinel','grep',{},'No matches.',[]], ['Pi transport sentinel','grep',{},JSON.stringify([{type:'text',text:'No matches.'}]),['legacy_unknown']], @@ -173,3 +173,31 @@ test('byte cutoff at every array position retains every complete filename elemen expect(signals.map(signal=>signal.source+':'+signal.key).sort(),'ARRAY_BYTE_CUT_'+cut).toEqual(expected.sort()); } }); + +for(const [name,input,output] of [ + ['empty content',{output_mode:'content'},{mode:'content',numFiles:0,filenames:[],content:'',numLines:0,totalLines:0}], + ['empty count',{output_mode:'count'},{mode:'count',numFiles:0,filenames:[],content:'',numMatches:0}], + ['empty filenames',{}, {mode:'files_with_matches',numFiles:0,filenames:[],totalFiles:0}], + ['unnumbered context',{output_mode:'content','-n':false,context:1},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md-sails\nnotes/loom.md:sirens',numLines:2,totalLines:2}], + ['context group separator',{output_mode:'content',context:1},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:1:sirens\n--\nnotes/raft.md:4:sirens',numLines:3,totalLines:3}], + ['content directory match',{output_mode:'content'},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:1:sirens',numLines:1,totalLines:1}], + ['content context and match',{output_mode:'content',context:1},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md-12-sails\nnotes/loom.md:13:sirens',numLines:2,totalLines:2}], + ['content without numbers',{output_mode:'content','-n':false},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:sirens',numLines:1,totalLines:1}], + ['count directory matches',{output_mode:'count'},{mode:'count',numFiles:2,filenames:[],content:'notes/loom.md:2\nnotes/raft.md:3',numMatches:5}], + ['count reaches known total',{output_mode:'count',head_limit:1},{mode:'count',numFiles:1,filenames:[],content:'notes/loom.md:2',numMatches:2}], + ['files with matches',{}, {mode:'files_with_matches',numFiles:2,filenames:['notes/loom.md','notes/raft.md'],totalFiles:2}], +] as const)test(`installed Grep construction remains healthy: ${name}`,()=>{ + expect(outputTaintSignals('Grep',JSON.stringify(output),undefined,()=>false,searchOutputContext('Grep',input))).toEqual([]); +}); +test('a paginated numbered context row retains its marked filename',()=>{ + const output={mode:'content',numFiles:0,filenames:[],content:'notes/loom.md-12-sails',numLines:1,totalLines:2,appliedOffset:1}; + expect(outputTaintSignals('Grep',JSON.stringify(output),undefined,path=>path==='notes/loom.md',searchOutputContext('Grep',{output_mode:'content',context:1,head_limit:1,offset:1})).map(s=>s.source).sort()).toEqual(['legacy_unknown','user_marked']); +}); +test('partial arrays below the byte budget retain every complete filename',()=>{ + const paths=['workspaces/voyage/raft.md','notes/lo"om.md','notes/a\nb.md'],array=JSON.stringify(paths);let end=1;const ends=paths.map(path=>{end+=JSON.stringify(path).length;const result=end;end++;return result;}); + for(let cut=0;cutends[i]!<=cut).flatMap(path=>[...(path.startsWith('workspaces/')?['workspace_read:'+path]:[]),'user_marked:'+path]);expected.push('legacy_unknown:unknown_remainder'); + expect(outputTaintSignals('Glob',output,undefined,path=>paths.includes(path),{backendId:'claude'}).map(s=>s.source+':'+s.key).sort(),'SMALL_ARRAY_CUT_'+cut).toEqual(expected.sort()); + } +}); diff --git a/packages/ui-server/tests/safety-ledger.test.ts b/packages/ui-server/tests/safety-ledger.test.ts index 5167033d67..1a4da59ae8 100644 --- a/packages/ui-server/tests/safety-ledger.test.ts +++ b/packages/ui-server/tests/safety-ledger.test.ts @@ -586,7 +586,7 @@ for(const [name,tool,output,expected] of [ for(const [name,backend,tool,mode,output,expected] of [ ['Claude filename mode','claude','Grep','files_with_matches',JSON.stringify({numFiles:1,filenames:['notes/voyage:2:home.md']}),['user_marked']], - ['Claude count mode','claude','Grep','count',JSON.stringify({numFiles:1,filenames:['notes/voyage:2'],content:'notes/voyage:2:7'}),['user_marked']], + ['Claude count mode','claude','Grep','count',JSON.stringify({mode:'count',numFiles:1,filenames:[],content:'notes/voyage:2:7',numMatches:7}),['user_marked']], ['invalid Claude mode','claude','Grep','unsupported','notes/voyage:2:7:sirens',['legacy_unknown']], ['Pi sentinel cannot cross backend','claude','grep','content','No matches.',['legacy_unknown']], ] as const)test(`search parser identity: ${name}`,async()=>{ diff --git a/packages/ui-server/tests/safety-result-exits.test.ts b/packages/ui-server/tests/safety-result-exits.test.ts index 0e8a52ba46..c2a56b1608 100644 --- a/packages/ui-server/tests/safety-result-exits.test.ts +++ b/packages/ui-server/tests/safety-result-exits.test.ts @@ -474,7 +474,7 @@ async function claudeSearchRuns(f:Voyage){ const child=Bun.spawn([rg,'--with-filename','-n','--no-heading','--color','never','sirens',path],{cwd:f.brain,env:{PATH:'/usr/bin:/bin'},stdout:'pipe',stderr:'pipe'}); const [content,errors,code]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]); expect(code,errors).toBe(0); - return {mode:'content',numFiles:1,filenames:[path],content:content.trimEnd(),numLines:1}; + return {mode:'content',numFiles:0,filenames:[],content:content.trimEnd(),numLines:1,totalLines:1}; } for(const binding of ['pi','claude'] as const)test(`${binding}: two allowed searches reusing an ID cannot share one result discharge`,async()=>{ From 39aba90ff1c093ceee99e43e6066ea1c665452d2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 04:14:29 +0000 Subject: [PATCH 22/23] fix: require complete Grep mode totals and identifiable content sources --- packages/ui-server/src/activity/ingestion-taint.ts | 6 +++--- packages/ui-server/tests/ingestion-taint-schema.test.ts | 9 ++++++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 7d805acef5..0ebce2271c 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -354,9 +354,9 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(value.content!==undefined&&value.content!==''){unknown=true;salvage(value,value.mode==='count'?'count':'content');} }else if(mode==='content'){ if(value.content===undefined||value.numFiles!==0||value.filenames.length!==0|| - value.numLines!==undefined&&value.numLines!==lines||value.totalLines!==undefined&&value.totalLines!==lines|| + value.numLines!==lines||value.totalLines!==lines|| value.numMatches!==undefined||value.totalFiles!==undefined)unknown=true; - if(value.content)content(value.content,context?.lineNumbers!==false); + if(value.content){content(value.content,context?.lineNumbers!==false);if(contentPaths.size===0)unknown=true;} }else{ let matches=0; if(value.content===undefined||value.filenames.length!==0||value.numLines!==undefined||value.totalLines!==undefined)unknown=true; @@ -365,7 +365,7 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str if(split){const path=line.slice(0,split.index);if(contentPaths.has(path))unknown=true;contentPaths.add(path);add(path);matches+=Number(split[1]);if(!Number.isSafeInteger(matches))unknown=true;} else unknown=true; } - if(value.numFiles!==contentPaths.size||value.numMatches!==undefined&&value.numMatches!==matches|| + if(value.numFiles!==contentPaths.size||value.numMatches!==matches|| value.totalFiles!==undefined&&value.totalFiles!==value.numFiles)unknown=true; } } diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 114cb9ce96..32aa3342dd 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -29,7 +29,7 @@ for(const [name,tool,input,output,expected] of [ ['Grep zero count entry','Grep',{output_mode:'count'},grep([],{content:'notes/loom.md:0',numMatches:0}),['legacy_unknown']], ['Grep wrong reported offset','Grep',{offset:1},grep([],{appliedOffset:0}),['legacy_unknown']], ['Grep unbounded limit','Grep',{head_limit:0},grep(['notes/loom.md']),[]], - ['Grep content has no reported filename count','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens'}),[]], + ['Grep content has no reported filename count','Grep',{output_mode:'content'},grep([],{content:'notes/loom.md:1:sirens',numLines:1,totalLines:1}),[]], ['Grep count mismatched filenames','Grep',{output_mode:'count'},grep(['notes/other.md'],{content:'notes/loom.md:1',numMatches:1}),['legacy_unknown']], ['Grep reported unlimited cannot hide input limit','Grep',{head_limit:1},grep(['notes/loom.md'],{appliedLimit:0}),['legacy_unknown']], ['Grep content count contradicts lines','Grep',{output_mode:'content'},grep(['notes/loom.md'],{content:'notes/loom.md:1:sirens',numMatches:2}),['legacy_unknown']], @@ -201,3 +201,10 @@ test('partial arrays below the byte budget retain every complete filename',()=>{ expect(outputTaintSignals('Glob',output,undefined,path=>paths.includes(path),{backendId:'claude'}).map(s=>s.source+':'+s.key).sort(),'SMALL_ARRAY_CUT_'+cut).toEqual(expected.sort()); } }); +for(const [name,input,value] of [ + ['content missing totals',{output_mode:'content'},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:1:sirens',numLines:1}], + ['count missing total matches',{output_mode:'count'},{mode:'count',numFiles:1,filenames:[],content:'notes/loom.md:2'}], + ['context separator without a source',{output_mode:'content',context:1},{mode:'content',numFiles:0,filenames:[],content:'--',numLines:1,totalLines:1}], +] as const)test(`incomplete Grep construction stays unknown: ${name}`,()=>{ + expect(outputTaintSignals('Grep',JSON.stringify(value),undefined,()=>false,searchOutputContext('Grep',input)).map(s=>s.source)).toEqual(['legacy_unknown']); +}); From efb101f842eb9c2c3899fcf4070390c84488e1a4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 21 Nov 2026 04:50:33 +0000 Subject: [PATCH 23/23] fix: scope search completeness and context delimiters --- packages/ui-server/src/activity/ingestion-taint.ts | 4 ++-- packages/ui-server/src/brain/turn-extraction.ts | 2 +- packages/ui-server/tests/extraction-admission.test.ts | 10 ++++++++++ .../ui-server/tests/ingestion-taint-schema.test.ts | 2 ++ 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index 0ebce2271c..3f087d422e 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -263,8 +263,8 @@ export function outputTaintSignals(tool: string, output: string, brainPath?: str let count=0; // No line numbers: every colon could separate the filename and content. // With numbers: lookahead preserves overlapping `:2:7:` candidates. - for(const split of line.matchAll(numbers?/(?=([:-])[1-9][0-9]*\1)/g:context?.contextRows?/(?=[:\-])/g:/(?=:)/g)){ - if(count++>=256){unknown=true;break;}const path=line.slice(0,split.index);if(numbers&&split[1]==='-'&&!context?.contextRows)unknown=true;contentPaths.add(path);add(path); + for(const split of line.matchAll(numbers?(context?.contextRows?/(?=([:-])[1-9][0-9]*\1)/g:/(?=(:)[1-9][0-9]*\1)/g):context?.contextRows?/(?=[:\-])/g:/(?=:)/g)){ + if(count++>=256){unknown=true;break;}const path=line.slice(0,split.index);contentPaths.add(path);add(path); } if(count!==1)unknown=true; } diff --git a/packages/ui-server/src/brain/turn-extraction.ts b/packages/ui-server/src/brain/turn-extraction.ts index 46594c6c6e..afbd1d3701 100644 --- a/packages/ui-server/src/brain/turn-extraction.ts +++ b/packages/ui-server/src/brain/turn-extraction.ts @@ -185,7 +185,7 @@ export function createTurnExtraction(options: { try { const current = session(); const outputComplete=searchOutputComplete(output,outputStatus,tool==='grep'); - if(outputComplete===false)current.complete=false; + if(["Grep","Glob","grep","find"].includes(tool)&&outputComplete===false)current.complete=false; const path = readPath(tool, input); if (path !== null) current.read(display(path), readText(output)); // Content from anywhere the host cannot vouch for: a fetch, a command diff --git a/packages/ui-server/tests/extraction-admission.test.ts b/packages/ui-server/tests/extraction-admission.test.ts index 2e2ce354b9..2672b72822 100644 --- a/packages/ui-server/tests/extraction-admission.test.ts +++ b/packages/ui-server/tests/extraction-admission.test.ts @@ -266,3 +266,13 @@ test("no classifier state, verdict or evidence reaches the conversation: only a expect(f.activity, "CLASSIFIER_REPORTS_NO_ACTIVITY").toEqual([]); } finally { proxy.stop(); } }); + +for(const tool of ["bash","read_file"])test(`failed ${tool} preserves search completeness and extraction relaxation`,async()=>{ + const island=Bun.serve({hostname:"127.0.0.2",port:0,fetch:()=>new Response("Aeaea")}),store=db(),f=fixture(),proxy=await turn(store,f.bridge); + try{ + await safety(proxy).begin("failed",tool,{}); + await safety(proxy).result("failed",tool,"Tool failed",true,undefined,{complete:false}); + await safety(proxy).begin("fetch-clean","WebFetch",{url:`${island.url.href}tides?date=2026-07-12`,prompt:"When is high tide?"}); + expect((await admitted(f,get(proxy.socketPath,`${island.url.href}tides?date=2026-07-12`),"NON_SEARCH_ERROR_PRESERVES_RELAXATION")).status).toBe(200); + }finally{f.answer({behavior:"deny",message:"Fixture cleanup"});proxy.stop();island.stop(true);store.close();} +}); diff --git a/packages/ui-server/tests/ingestion-taint-schema.test.ts b/packages/ui-server/tests/ingestion-taint-schema.test.ts index 32aa3342dd..7a06382a72 100644 --- a/packages/ui-server/tests/ingestion-taint-schema.test.ts +++ b/packages/ui-server/tests/ingestion-taint-schema.test.ts @@ -180,6 +180,8 @@ for(const [name,input,output] of [ ['empty filenames',{}, {mode:'files_with_matches',numFiles:0,filenames:[],totalFiles:0}], ['unnumbered context',{output_mode:'content','-n':false,context:1},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md-sails\nnotes/loom.md:sirens',numLines:2,totalLines:2}], ['context group separator',{output_mode:'content',context:1},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:1:sirens\n--\nnotes/raft.md:4:sirens',numLines:3,totalLines:3}], + ['ISO date content',{output_mode:'content'},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:3:due 2026-11-20',numLines:1,totalLines:1}], + ['date slug filename',{output_mode:'content'},{mode:'content',numFiles:0,filenames:[],content:'notes/2026-11-20-standup.md:3:sirens',numLines:1,totalLines:1}], ['content directory match',{output_mode:'content'},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:1:sirens',numLines:1,totalLines:1}], ['content context and match',{output_mode:'content',context:1},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md-12-sails\nnotes/loom.md:13:sirens',numLines:2,totalLines:2}], ['content without numbers',{output_mode:'content','-n':false},{mode:'content',numFiles:0,filenames:[],content:'notes/loom.md:sirens',numLines:1,totalLines:1}],