Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
a609e53
fix(ui-server): retain exact and ambiguous input evidence
schlessera Nov 20, 2026
2416782
fix: parse search evidence by admitted backend format
schlessera Nov 20, 2026
a2d5e2c
fix: require recognized complete search output schemas
schlessera Nov 20, 2026
8ad5efe
fix: retain search sources across malformed and limited pages
schlessera Nov 20, 2026
8a22ec1
fix: preserve independent signals from partially malformed results
schlessera Nov 20, 2026
accf202
fix: qualify original search results and prove backend forwarding
schlessera Nov 20, 2026
87d0bf5
fix: preserve NUL-delimited search paths and deterministic native proof
schlessera Nov 20, 2026
459e206
test: gate the second native search by logical request
schlessera Nov 20, 2026
6927370
CONTRACT: retain explicit search completion status across Pi result d…
schlessera Nov 20, 2026
81b9a88
CONTRACT: keep search framing host-only and retain conflicting evidence
schlessera Nov 20, 2026
83f9de9
fix: bind search framing to delivered trimmed text
schlessera Nov 20, 2026
8cb9b46
CONTRACT: preserve process evidence through every result wrapper
schlessera Nov 20, 2026
f49bb40
fix: preserve BOM filenames and trust structured search completeness
schlessera Nov 20, 2026
b4c2556
fix: retain unknown extraction coverage and bound grep diagnostics
schlessera Nov 21, 2026
2754ed5
fix: preserve display search sources and strengthen native witnesses
schlessera Nov 21, 2026
9d32900
CONTRACT: require framed empty proof and preserve ambiguous display s…
schlessera Nov 21, 2026
899b6ff
fix: retain search evidence without throwing on malformed paths
schlessera Nov 21, 2026
77b363d
fix: make search evidence parsing total at capacity boundaries
schlessera Nov 21, 2026
dedbb88
fix: retain discriminated search evidence through byte decoding and b…
schlessera Nov 21, 2026
1274df2
fix: retain complete filename elements at every byte cutoff
schlessera Nov 21, 2026
dc74c19
fix: parse verified Claude Grep modes and all partial arrays
schlessera Nov 21, 2026
39aba90
fix: require complete Grep mode totals and identifiable content sources
schlessera Nov 21, 2026
efb101f
fix: scope search completeness and context delimiters
schlessera Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/session-safety-input-evidence.md
Original file line number Diff line number Diff line change
@@ -0,0 +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.
8 changes: 8 additions & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2869,6 +2869,7 @@ export "./server" (./src/server/index.ts)
type InboxToolName
type InboxView
type InboxWorkPayload
type InputSafetyOutputStatus
type JournalObservationReference
type JournalOutwardAction
type JournalRecoveryStatus
Expand Down Expand Up @@ -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;
Expand Down
8 changes: 8 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
35 changes: 35 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5952,3 +5952,38 @@ 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 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. 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;
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;
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.
23 changes: 16 additions & 7 deletions docs/plans/reviewable-session-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,27 @@ 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:155`;
`outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:178`).
`packages/ui-server/src/activity/ingestion-taint.ts:164-184`;
`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; display frames alone
never prove finalized delivery or complete coverage.
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
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
`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
Expand Down Expand Up @@ -323,7 +332,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
Expand Down
37 changes: 32 additions & 5 deletions packages/ui-backend-pi/src/file-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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", "-rHInZE", "--", params.pattern, rel], exec.wrapper), {
cwd: brain.root,
env: subprocessEnv([...resolveEnabledWebSearchEnvNames(), ...WORKER_EGRESS_TRANSPORT_ENV]),
stdout: "pipe",
Expand All @@ -69,10 +69,37 @@ 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 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.
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);
const text = out.trim();
return textResult(text ? clip(text) : "No matches.", { pattern: params.pattern });
// 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&&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;
// 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(displayTruncated){
const limit=rawText.length-rawText.trimStart().length+MAX_OUTPUT_BYTES;
let visible=0;end=0;
while(end<frame.length&&(visible<limit||frame[end]==="\0")){
if(frame[end]!=="\0")visible++;end++;
}
}
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,decodingLoss,truncated:displayTruncated||frameClipped,stdoutEmpty:outBytes.byteLength===0,framedOutput,visibleText}});
},
} satisfies ToolDefinition;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-backend-pi/src/tool-safety.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string,unknown>):Promise<PermissionDecision>;
result(name:string,id:string,content:Content,complete?:boolean):Promise<void>;
result(name:string,id:string,content:Content,complete?:boolean,details?:unknown):Promise<void>;
unavailable?():Promise<void>;
stop():void;
}
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-backend-pi/src/worker-entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,8 @@ async function initialize(init: Init): Promise<void> {
// 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(),
},
Expand Down
28 changes: 20 additions & 8 deletions packages/ui-backend-pi/src/worker-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -88,14 +89,25 @@ export const piWorkerMessage = z.discriminatedUnion("type", [
]);
export type PiWorkerMessage = z.infer<typeof piWorkerMessage>;

/** 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);
// 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({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<typeof piOutputStatus>} {
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<string,unknown>).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 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.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}};
}
// 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<Writable, "write">, value: unknown): void {
Expand Down
9 changes: 6 additions & 3 deletions packages/ui-backend-pi/src/worker-rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -283,10 +283,13 @@ export const PI_WORKER_RPC_HANDLERS: Readonly<Record<PiWorkerRpcMethod, PiWorker
throw new Error("Unqualified Pi input transformations");
},
safetyResult: async(msg,bridge,context)=>{
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};
},
};
Expand Down
Loading
Loading