/** * Grounding gate — Scenario-B "verification-as-test" for knowledge-work replies. * ========================================================================= * * WHY THIS EXISTS * --------------- * Cowork's autonomous engineering loop is safe because every AI edit is gated * by a machine-checkable signal (`pnpm verify`); a failing edit is reverted, not * shipped. Brain's highest-value output is not code — it's *judgment* (replies, * briefings, recaps, memory writes) — which has no compiler/test to pass. So the * "confident-but-wrong at scale" failure mode has no guardrail. * * This module manufactures the missing signal: **grounding-as-verify.** A reply * is "verified" when each of its *specific factual claims* traces to something the * agent actually consulted this turn (its read-set) or to the user's own message. * A specific claim with an empty / unrelated read-set is the hallucination signal. * * DESIGN HONESTY (read before trusting the verdicts) * -------------------------------------------------- * This is a DETERMINISTIC, HIGH-PRECISION PRE-FILTER, not a perfect fact-checker. * It is tuned to catch the *dangerous, cheap-to-detect* case with few false * positives: a reply asserting concrete specifics (numbers, dates, proper-noun * entities, identifiers, quoted values) that do NOT appear anywhere in what the * agent read. It deliberately does NOT try to verify semantic correctness, * paraphrase, or arithmetic — that is a future LLM-backed verifier slot * (`verifyClaimWithModel`, intentionally left as an extension point). * * Because it is imperfect, the RESULT is consumed through a TIERED policy that * matches strictness to autonomy (`decideDelivery`): * - interactive (user is in the loop, latency matters) → ANNOTATE and send; * a wrongly-flagged claim costs the user one inline mark, nothing more. * - proactive (autonomous artifact, user is NOT watching) → BLOCK on any * ungrounded claim so the pipeline revises before delivery. * * PURITY * ------ * Every export here is a pure function over its inputs (an injectable clock is the * only nondeterminism, for staleness tests). It imports no live singletons, holds * no state, performs no I/O, and sends nothing. It is therefore safe to land with * zero runtime impact until the delivery path explicitly calls it. All wiring * (collecting the read-set from the SDK message stream, choosing the mode, acting * on the decision) lives in the caller. */ /** Which delivery context the reply is headed for. Drives strictness. */ export type DeliveryMode = 'interactive' | 'proactive'; /** Per-claim classification. */ export type ClaimVerdict = 'grounded' | 'ungrounded' | 'stale' | 'unverifiable'; /** What the delivery path should do with the reply. */ export type DeliveryAction = 'send' | 'annotate' | 'block'; /** * One thing the agent actually consulted this turn. The wiring layer builds these * from Read/Grep/Glob tool_use + tool_result pairs in the SDK message stream. */ export interface ReadSetItem { /** Path or identifier of the source (e.g. a conversation .md path). */ source: string; /** The content the agent saw (tool_result text). May be truncated. */ text: string; /** ISO timestamp of the source if known, for staleness detection. Optional. */ timestamp?: string; } /** Result of analysing a single candidate claim. */ export interface ClaimAnalysis { claim: string; verdict: ClaimVerdict; /** The specific tokens that made this a checkable claim. */ salientTokens: string[]; /** Salient tokens NOT found in the read-set (drives the `ungrounded` verdict). */ missingTokens: string[]; /** Sources whose text contained this claim's salient tokens. */ supportingSources: string[]; } /** Whole-reply analysis. */ export interface GroundingAnalysis { claims: ClaimAnalysis[]; groundedCount: number; ungroundedCount: number; staleCount: number; /** True when the agent read nothing this turn — the strongest hallucination prior. */ readSetEmpty: boolean; } /** The gate's decision, ready for the delivery path to act on. */ export interface DeliveryDecision { action: DeliveryAction; mode: DeliveryMode; /** For `annotate`, the reply with inline marks; otherwise the original reply. */ text: string; analysis: GroundingAnalysis; /** Human-readable one-liner for logs. */ reason: string; } export interface GroundingConfig { /** A source older than this many days makes a grounded claim `stale`. Default 30. */ stalenessThresholdDays: number; /** * Fraction of a claim's salient tokens that must appear in the read-set for it * to count as grounded. Default 1.0 (strict — every specific must be backed). */ minCoverage: number; /** Injectable clock (tests). Defaults to real `Date`. */ now: () => Date; } export declare const DEFAULT_GROUNDING_CONFIG: GroundingConfig; /** Extract the set of specific, checkable tokens from a piece of text. */ export declare function extractSalientTokens(text: string): string[]; /** A sentence is unverifiable (excluded from gating) if hedged/meta/interrogative. */ export declare function isUnverifiable(sentence: string): boolean; /** * Split a reply into candidate factual claims. A candidate is a declarative * sentence that carries at least one salient token and is not a hedge/opinion. */ export declare function segmentClaims(reply: string): string[]; /** * EXTENSION POINT (future): replace/augment token matching with an LLM call that * verifies each claim's *meaning* against the read-set, not just token presence. * Kept as a documented seam so the deterministic pre-filter can be upgraded to a * semantic verifier without changing the tiered-decision contract. */ /** * Analyse a reply against the read-set (plus the user's own message, which counts * as a valid source — echoing a user-stated fact is grounded by definition). */ export declare function checkGrounding(reply: string, readSet: ReadSetItem[], userMessage?: string, config?: Partial): GroundingAnalysis; /** * The tiered policy (Amy's choice): strictness scales with autonomy. * interactive → never block; ANNOTATE if anything is ungrounded/stale. * proactive → BLOCK on any ungrounded claim (autonomous artifact, user not * watching); ANNOTATE if only stale. */ export declare function decideDelivery(analysis: GroundingAnalysis, mode: DeliveryMode): DeliveryAction; /** * Produce an annotated copy of the reply: append an inline marker after each * flagged claim, plus a short footer. Inline injection uses the exact extracted * claim substring, so formatting/code blocks elsewhere are untouched. */ export declare function annotateReply(reply: string, analysis: GroundingAnalysis): string; /** * Notice that REPLACES a blocked proactive reply's body. The ungrounded reply * text is withheld — only this notice is delivered — so the notice must be * truthful about what happened (the unverifiable content did not reach the user). * * IMPORTANT: the notice must NOT reprint the full unverifiable claim verbatim — * that would leak the very fabricated specifics we are withholding (e.g. a made-up * "$16 billion"). It reports only the count and the missing/unfounded tokens, so * the user learns WHAT could not be verified without the bot restating the * hallucinated sentence as if quoting a fact. Kept pure so the wiring layer stays * declarative and testable. */ export declare function buildGroundingBlockNotice(analysis: GroundingAnalysis): string; /** * What the delivery layer should actually SEND, given a gate decision. * * This is the pure, testable heart of the wiring: the caller in `index.ts` (and * any other delivery path) must funnel every gate decision through this function * rather than re-deriving the mapping inline. Extracting it fixes the bug where * `block` delivered `originalReply + notice` (i.e. did NOT withhold the ungrounded * body) and let the notice claim the message "was held" when it was actually sent. * * Contract: * - `send` → deliver the reply unchanged, not an error. * - `annotate` → deliver the inline-annotated reply, not an error. * - `block` → WITHHOLD the reply body entirely; deliver ONLY the notice, and * mark isError so the delivery path logs it and skips DB persistence. * `withheld` carries the original text so a future proactive * pipeline can revise + re-run the gate (the documented follow-up). */ export interface AppliedDecision { /** The text to actually deliver to the user. */ text: string; /** True when the reply was blocked; delivery paths log + skip DB store. */ isError: boolean; /** For `block`, the original reply that was withheld (for revise-and-re-run). Else undefined. */ withheld?: string; } export declare function applyDecision(decision: DeliveryDecision): AppliedDecision; /** * Top-level gate. Pure: returns what SHOULD happen. The caller must pass the * result through `applyDecision()` to get the text to deliver — it must NOT read * `decision.text` directly for `block` (that is the original, withheld reply). * For `block`, `decision.text` is the original text so the proactive pipeline can * revise and re-run the gate. */ export declare function groundingGate(reply: string, readSet: ReadSetItem[], mode: DeliveryMode, opts?: { userMessage?: string; config?: Partial; }): DeliveryDecision;