Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(trust-reads): unconfirmed label on explicit reads, legacy trust scan with doctor trust_scan and gbrain trust scan, trust explain data API (#5575 CEO-20, DX-6, DX-10, ENG-8)
garrytanc1d72fed8e39
diff --git a/src/cli/commands/trust.ts b/src/cli/commands/trust.tsindex a8f9d40e48..b4d9f45e53 100644--- a/src/cli/commands/trust.ts+++ b/src/cli/commands/trust.ts@@ -9,6 +9,7 @@ import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../../core/cimport type { BrainEngine } from '../../core/engine.ts';import { TRUST_TIERS, trustLabel } from '../../core/trust/tier.ts';import { runTrustBackfill, type TrustBackfillReport } from '../../core/trust/backfill.ts';+import { runTrustScan } from '../../core/eligibility/scan.ts';import type { CliDispatchContext } from '../command-table.ts';export const TRUST_USAGE = [@@ -18,6 +19,11 @@ export const TRUST_USAGE = [' the journaled request that wrote the row. Rows with no signal stay "unverified origin"; nothing becomes',' "confirmed by you". --dry-run is read-only (no migrations, no writes) and works before the trust migration;',' it reports the projected count per table and tier. --resume continues an interrupted run.',+ '',+ 'Usage: gbrain trust scan [--batch-size N] [--json]',+ ' Runs the write gate\'s deterministic detector over agent-written and lower rows written before the gate,',+ ' recording a receipt for each instruction-like row so proactive surfaces stop injecting it until you confirm',+ ' it (gbrain trust review). Changes no row; resumable (rerun to continue); a detector upgrade rescans.',].join('\n');function render(report: TrustBackfillReport): string {@@ -33,9 +39,10 @@ function render(report: TrustBackfillReport): string {export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {const [sub, ...rest] = args;- if (!sub || args.includes('--help') || args.includes('-h') || sub !== 'backfill') {+ const known = sub === 'backfill' || sub === 'scan';+ if (!sub || args.includes('--help') || args.includes('-h') || !known) {console.log(TRUST_USAGE);- if (sub && sub !== 'backfill' && !args.includes('--help') && !args.includes('-h')) setCliExitVerdict(2);+ if (sub && !known && !args.includes('--help') && !args.includes('-h')) setCliExitVerdict(2);return;}const dryRun = rest.includes('--dry-run');@@ -46,6 +53,15 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchCsetCliExitVerdict(2);return;}+ if (sub === 'scan') {+ await ctx.completeStartup?.(engine);+ const scan = await runTrustScan(engine, batchSize ? { batchSize } : {});+ if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(scan, null, 2)}\n`);+ else console.log([`Trust scan (detector v${scan.detector_version}):`,+ ...scan.tables.map(t => ` ${t.table}: ${t.scanned} row(s) scanned, ${t.flagged} flagged${t.done ? '' : ' (more to scan)'}`),+ scan.complete ? ' Complete. Flagged rows are withheld from proactive context until confirmed (gbrain trust review).' : ` Continue with: ${scan.resume_command}`].join('\n'));+ return;+ }if (!dryRun) await ctx.completeStartup?.(engine);const report = await runTrustBackfill(engine, { dryRun, resume: rest.includes('--resume'), ...(batchSize ? { batchSize } : {}) });if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(report, null, 2)}\n`);diff --git a/src/commands/doctor/checks/trust-scan.ts b/src/commands/doctor/checks/trust-scan.tsnew file mode 100644index 0000000000..f0fd593c3b--- /dev/null+++ b/src/commands/doctor/checks/trust-scan.ts@@ -0,0 +1,36 @@+/**+ * trust_scan (#5575, DX-6 / ENG-8): rows at `agent_written` or lower that+ * the write gate's current detector has not scanned. Activation control+ * (CEO-20) only covers scanned rows, so unscanned legacy rows can still be+ * injected by proactive surfaces; the fix runs `gbrain trust scan`, which+ * records flag receipts in bounded, resumable batches and changes no row.+ * A brain before the trust or write-gate migrations is ok. Read-only.+ */+import type { Check } from '../../doctor.ts';+import { agentFix, checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+import { readTrustScanState } from '../../../core/eligibility/scan.ts';+import { isUndefinedColumnError, isUndefinedTableError } from '../../../core/utils.ts';++async function runTrustScan(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ try {+ const state = await readTrustScanState(engine);+ const details = { detector_version: state.detector_version, unscanned: state.unscanned, total_unscanned: state.total_unscanned, completed_at: state.completed_at };+ if (state.total_unscanned === 0) {+ return [{ name: 'trust_scan', status: 'ok', details,+ message: 'Every agent-written or lower row has been scanned by the current write-gate detector; proactive suppression covers them.' }];+ }+ return [{ name: 'trust_scan', status: 'warn', details,+ message: `${state.total_unscanned} agent-written or lower row(s) have not been scanned by the write-gate detector (v${state.detector_version}), `+ + 'so proactive surfaces cannot yet withhold instruction-like ones. Run gbrain trust scan on the brain host; it records receipts in resumable batches and changes no row.',+ fix: agentFix(['gbrain', 'trust', 'scan'], 'Scans legacy agent-written rows with the deterministic detector and records flag receipts; it never hides, moves or rewrites a row.', 'trust_scan') }];+ } catch (err) {+ if (isUndefinedColumnError(err, 'trust_tier') || isUndefinedTableError(err)) {+ return [{ name: 'trust_scan', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates the write gate; the scan arrives with its migration.' }];+ }+ return [checkError('trust_scan', 'read the trust scan state', err)];+ }+}++export const trustScanEntry: DoctorEntry = { name: 'trust_scan', emits: ['trust_scan'], run: runTrustScan };diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex 4fe4504594..bedaedef89 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -96,6 +96,7 @@ import { coreMemoryEntry } from './checks/core-memory.ts';import { plannerStatsEntry } from './checks/planner-stats.ts';import { revisionBackfillEntry } from './checks/revision-backfill.ts';import { trustTiersEntry } from './checks/trust-tiers.ts';+import { trustScanEntry } from './checks/trust-scan.ts';import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';import { agentContractEntry } from './checks/agent-contract.ts';import { chatFallbackChainEntry } from './checks/chat-fallback.ts';@@ -176,6 +177,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [transcriptSecretExposureEntry,revisionBackfillEntry,trustTiersEntry,+ trustScanEntry,coreMemoryEntry,fenceIntegrityEntry,searchModeEntry,diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex 1319a74d2e..e393a72f4f 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -662,7 +662,13 @@ async function assembleDelta(sort: 'updated_asc',});const window = pages.slice(0, DELTA_PAGE_FETCH_LIMIT);- const verdicts = await pageActivationVerdicts(engine, window.map(p => ({ source_id: opts.sourceId, slug: p.slug })), { floor: policy.floor });+ // Labels are best-effort on an unfloored read; with a floor, an unreadable tier fails the arm closed.+ const verdicts = await pageActivationVerdicts(engine, window.map(p => ({ source_id: opts.sourceId, slug: p.slug })), { floor: policy.floor })+ .catch((error: unknown) => {+ if (policy.floor) throw error;+ return new Map(window.map(p => [pageKey({ source_id: opts.sourceId, slug: p.slug }),+ { tier: 'unknown' as const, origin: { channel: 'unrecorded' }, belowFloor: false, suppressed: false }]));+ });acc.pages = {status: 'ok',overflow: pages.length > DELTA_PAGE_FETCH_LIMIT,diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 44708bd196..497cf1db01 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -64,6 +64,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set(['fence_integrity',// #5575: stored trust tier counts and the legacy-row backfill.'trust_tiers',+ 'trust_scan','credential_projection_pending','derived_visibility','extractor_facts_expired',diff --git a/src/core/eligibility/explain.ts b/src/core/eligibility/explain.tsnew file mode 100644index 0000000000..18a3ac4665--- /dev/null+++ b/src/core/eligibility/explain.ts@@ -0,0 +1,146 @@+/**+ * DX-10 `gbrain trust explain` data API: why a memory is (or is not) used.+ * For one typed ref it returns the stored tier and origin, the write-gate+ * verdict and receipts, and the activation decision on every registered+ * proactive surface plus explicit reads. Deterministic, read-only, zero+ * model calls. The CLI (lane L1a) renders it; nothing here prints.+ *+ * Refs (DX-7): `f<id>` fact, `t<id>` take, `e<id>` timeline entry, `h<id>`+ * write-gate hold, `p:<source>/<slug>` page.+ */+import type { BrainEngine } from '../engine.ts';+import { QUARANTINE_KEY } from '../quarantine.ts';+import { getWriteGateHold, parseHoldRef } from '../write-gate-store.ts';+import { admitsTrust, compareTrust, storedTrustTier, trustLabel, type TrustTier } from '../trust/tier.ts';+import { ACTIVATION_REASON_FAMILIES, ACTIVATION_TIER_CEILING, type EligibilityTable } from './sql.ts';+import { FILTER_POLICY_FLOOR, loadTrustReadConfig, type TrustReadConfig } from './policy.ts';+import { PROACTIVE_SURFACES, type ProactiveSurface } from './registry.ts';+import { shortOrigin } from './labels.ts';++type Exec = Pick<BrainEngine, 'executeRaw' | 'getConfig'>;++export type ExplainRef =+ | { kind: 'row'; table: Exclude<EligibilityTable, 'pages'>; id: number }+ | { kind: 'page'; sourceId: string; slug: string }+ | { kind: 'hold'; id: number };++/** Parses a typed ref; null when it names nothing. */+export function parseExplainRef(ref: string): ExplainRef | null {+ const r = ref.trim();+ const page = /^p:([^/]+)\/(.+)$/.exec(r);+ if (page) return { kind: 'page', sourceId: page[1], slug: page[2] };+ const hold = parseHoldRef(r);+ if (hold !== null) return { kind: 'hold', id: hold };+ const row = /^([fte])(\d+)$/.exec(r);+ if (!row) return null;+ const table = ({ f: 'facts', t: 'takes', e: 'timeline_entries' } as const)[row[1] as 'f' | 't' | 'e'];+ return { kind: 'row', table, id: Number(row[2]) };+}++export type SurfaceDecision = 'eligible' | 'suppressed' | 'below_floor' | 'quarantined' | 'needs_rederive' | 'held' | 'not_live';++export interface TrustReceiptView {+ id: number; verdict: string; reason_families: string[]; detector_version: number; tier: string; created_at: string; last_seen_at: string;+}++export interface TrustExplanation {+ ref: string;+ found: boolean;+ table?: EligibilityTable | 'write_gate_holds';+ id?: number;+ trust_tier?: TrustTier;+ label?: string;+ origin?: string;+ write_origin?: Record<string, unknown> | null;+ /** The newest receipt's verdict, or `allow` when the gate never flagged it. */+ verdict?: string;+ receipts: TrustReceiptView[];+ /** Instruction-family flag on an agent-written-or-lower row: withheld from proactive surfaces until confirmed. */+ unconfirmed: boolean;+ quarantined_page: boolean;+ needs_rederive: boolean;+ config: TrustReadConfig;+ /** Per proactive surface, plus `explicit_reads` (search, query, recall, get_page under the brain's read policy). */+ activation: Record<ProactiveSurface | 'explicit_reads', SurfaceDecision>;+ /** What the owner can run next (confirm or review); always the owner's command, never auto-applied. */+ next?: string[];+}++const ISO = (col: string) => `to_char(${col} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`;++async function receiptsFor(engine: Exec, table: string, id: number): Promise<TrustReceiptView[]> {+ const rows = await engine.executeRaw<TrustReceiptView & { id: string | number }>(+ `SELECT id, verdict, reason_families, detector_version, tier, ${ISO('created_at')} AS created_at, ${ISO('last_seen_at')} AS last_seen_at+ FROM write_gate_receipts WHERE target_table = $1 AND target_id = $2 ORDER BY last_seen_at DESC, id DESC LIMIT 20`, [table, String(id)]);+ return rows.map(r => ({ ...r, id: Number(r.id), detector_version: Number(r.detector_version) }));+}++const ROW_SQL: Readonly<Record<Exclude<EligibilityTable, 'pages'>, string>> = {+ facts: `SELECT r.id, r.trust_tier, r.write_origin, (r.expired_at IS NULL) AS live,+ EXISTS (SELECT 1 FROM pages q WHERE q.source_id = r.source_id AND q.slug = r.source_markdown_slug AND q.deleted_at IS NULL+ AND COALESCE(q.frontmatter, '{}'::jsonb) ? '${QUARANTINE_KEY}') AS quarantined+ FROM facts r WHERE r.id = $1`,+ takes: `SELECT r.id, r.trust_tier, r.write_origin, r.active AS live, (COALESCE(q.frontmatter, '{}'::jsonb) ? '${QUARANTINE_KEY}') AS quarantined+ FROM takes r JOIN pages q ON q.id = r.page_id WHERE r.id = $1`,+ timeline_entries: `SELECT r.id, r.trust_tier, r.write_origin, (q.deleted_at IS NULL) AS live, (COALESCE(q.frontmatter, '{}'::jsonb) ? '${QUARANTINE_KEY}') AS quarantined+ FROM timeline_entries r JOIN pages q ON q.id = r.page_id WHERE r.id = $1`,+};++/** The explanation for one ref (found: false when it names nothing). */+export async function explainTrust(engine: Exec, ref: string): Promise<TrustExplanation> {+ const config = await loadTrustReadConfig(engine);+ const parsed = parseExplainRef(ref);+ const empty = (): TrustExplanation => ({ ref, found: false, receipts: [], unconfirmed: false, quarantined_page: false, needs_rederive: false, config,+ activation: decisions('not_live', 'not_live') });+ if (!parsed) return empty();++ if (parsed.kind === 'hold') {+ const hold = await getWriteGateHold(engine, parsed.id);+ if (!hold) return empty();+ const tier = storedTrustTier(hold.tier);+ const held = hold.status === 'held' || hold.status === 'dropped';+ return { ref, found: true, table: 'write_gate_holds', id: hold.id, trust_tier: tier, label: trustLabel(tier), origin: shortOrigin(hold.write_origin),+ write_origin: hold.write_origin as Record<string, unknown> | null, verdict: 'quarantine', receipts: await receiptsFor(engine, 'write_gate_holds', hold.id),+ unconfirmed: false, quarantined_page: false, needs_rederive: false, config, activation: decisions(held ? 'held' : 'not_live', held ? 'held' : 'not_live'),+ ...(hold.status === 'held' ? { next: ['gbrain', 'trust', 'review'] } : {}) };+ }++ let table: EligibilityTable;+ let row: { id: number | string; trust_tier: string; write_origin: unknown; live: boolean; quarantined: boolean } | undefined;+ if (parsed.kind === 'page') {+ table = 'pages';+ [row] = await engine.executeRaw(+ `SELECT id, trust_tier, write_origin, (deleted_at IS NULL) AS live, (COALESCE(frontmatter, '{}'::jsonb) ? '${QUARANTINE_KEY}') AS quarantined+ FROM pages WHERE source_id = $1 AND slug = $2`, [parsed.sourceId, parsed.slug]);+ } else {+ table = parsed.table;+ [row] = await engine.executeRaw(ROW_SQL[parsed.table], [parsed.id]);+ }+ if (!row) return empty();+ const id = Number(row.id);+ const tier = storedTrustTier(row.trust_tier);+ const receipts = await receiptsFor(engine, table, id);+ const [rederive] = await engine.executeRaw<{ n: number }>(+ 'SELECT count(*)::int AS n FROM needs_rederive WHERE derived_table = $1 AND derived_id = $2', [table, String(id)]);+ const needsRederive = Number(rederive?.n ?? 0) > 0;+ const flagged = receipts.some(r => r.verdict === 'flag' && r.reason_families.some(f => (ACTIVATION_REASON_FAMILIES as readonly string[]).includes(f)));+ const unconfirmed = flagged && compareTrust(tier, ACTIVATION_TIER_CEILING) <= 0;+ const policyFloor = config.mode === 'filter' ? FILTER_POLICY_FLOOR : undefined;++ const gone: SurfaceDecision | null = !row.live ? 'not_live' : row.quarantined ? 'quarantined' : needsRederive ? 'needs_rederive'+ : policyFloor && !admitsTrust(tier, policyFloor) ? 'below_floor' : null;+ const proactive: SurfaceDecision = gone ?? (unconfirmed && config.activation === 'suppress' ? 'suppressed' : 'eligible');+ return {+ ref, found: true, table, id, trust_tier: tier, label: trustLabel(tier), origin: shortOrigin(row.write_origin),+ write_origin: typeof row.write_origin === 'string' ? JSON.parse(row.write_origin) : row.write_origin as Record<string, unknown> | null,+ verdict: receipts[0]?.verdict ?? 'allow', receipts, unconfirmed, quarantined_page: row.quarantined === true, needs_rederive: needsRederive, config,+ activation: decisions(proactive, gone ?? 'eligible'),+ ...(unconfirmed ? { next: ['gbrain', 'trust', 'review'] } : {}),+ };+}++function decisions(proactive: SurfaceDecision, explicit: SurfaceDecision): TrustExplanation['activation'] {+ const out = { explicit_reads: explicit } as TrustExplanation['activation'];+ for (const surface of Object.keys(PROACTIVE_SURFACES) as ProactiveSurface[]) out[surface] = proactive;+ return out;+}diff --git a/src/core/eligibility/labels.ts b/src/core/eligibility/labels.tsindex 8558cf21cb..58891a5bad 100644--- a/src/core/eligibility/labels.ts+++ b/src/core/eligibility/labels.ts@@ -18,6 +18,13 @@ import { compareTrust, storedTrustTier, trustLabel, type TrustTier } from '../trexport interface TrustFields {trust_tier: TrustTier;origin: string;+ /**+ * CEO-20: agent-written-or-lower content carrying an instruction-family+ * write-gate flag that the owner has not confirmed. Explicit reads return+ * it with this marker (text label "unconfirmed, agent-written");+ * proactive surfaces never inject it.+ */+ unconfirmed?: true;}const ORIGIN_MAX = 40;@@ -49,7 +56,7 @@ export interface LabelOpts {/** The compact per-item text label, e.g. `[written by an agent · mcp:remember]`. */export function compactTrustLabel(fields: TrustFields, opts: LabelOpts = {}): string {- const words = opts.unconfirmed ? 'unconfirmed, agent-written' : trustLabel(fields.trust_tier);+ const words = opts.unconfirmed || fields.unconfirmed ? 'unconfirmed, agent-written' : trustLabel(fields.trust_tier);return `[${words} · ${fields.origin}]`;}@@ -71,7 +78,7 @@ export function renderTrustedText(text: string, fields: TrustFields, opts: Label/** The attribute string for XML-ish prompt blocks (think `<take>`/`<page>`): `trust="…" origin="…"`. */export function trustAttributes(fields: TrustFields, opts: LabelOpts = {}): string {- return `trust="${opts.unconfirmed ? 'unconfirmed_agent_written' : fields.trust_tier}" origin="${fields.origin}"`;+ return `trust="${opts.unconfirmed || fields.unconfirmed ? 'unconfirmed_agent_written' : fields.trust_tier}" origin="${fields.origin}"`;}/** The one line a prompt carries for external-tier blocks so the model reads them as data. */diff --git a/src/core/eligibility/policy.ts b/src/core/eligibility/policy.tsindex c6a70f5a66..dee06dfcbc 100644--- a/src/core/eligibility/policy.ts+++ b/src/core/eligibility/policy.ts@@ -111,4 +111,5 @@ export const MIN_TRUST_PARAM = {type: 'string' as const,enum: [...TRUST_TIERS],description: 'Lowest trust tier to return (the connection floor still applies).',+ fullSurfaceOnly: true,};diff --git a/src/core/eligibility/scan.ts b/src/core/eligibility/scan.tsnew file mode 100644index 0000000000..8cf236613a--- /dev/null+++ b/src/core/eligibility/scan.ts@@ -0,0 +1,184 @@+/**+ * DX-6 / ENG-8 scan step: run the write gate's deterministic detector over+ * rows that existed before the gate (or were written while it was off), so+ * activation control (CEO-20) covers legacy content too.+ *+ * Scope: rows at `agent_written` or lower (the activation ceiling) in pages,+ * facts, takes and timeline entries. A detector hit records a `flag` receipt+ * (`write_gate_receipts`, deduped on target + content hash + detector+ * version) and never moves, hides or rewrites the row itself: the scan+ * only makes the row ineligible for proactive injection until the owner+ * confirms it. Zero model calls.+ *+ * Bounded and resumable: keyset batches by id per table, with the cursor+ * (the detector version it was taken under and the id ceiling it covers:+ * rows written after the scan began are gated by their writers) in+ * `op_checkpoints`. A+ * detector-version bump restarts the scan from the beginning; stored+ * verdicts from the older version stay until the rescan re-assesses+ * (ENG-21). Doctor `trust_scan` reports the unscanned count.+ */+import type { BrainEngine } from '../engine.ts';+import {+ assessFactForGate, assessPageForGate, assessTakeForGate, assessTimelineForGate, WRITE_GATE_DETECTOR_VERSION,+ type WriteGateAssessment, type WriteGateConfig,+} from '../write-gate.ts';+import { recordWriteGateReceipt } from '../write-gate-store.ts';+import { storedTrustTier, TRUST_TIER_RANK, TRUST_TIERS, type TrustTier } from '../trust/tier.ts';+import { ACTIVATION_TIER_CEILING } from './sql.ts';++export type ScanTable = 'pages' | 'facts' | 'takes' | 'timeline_entries';+export const SCAN_TABLES: readonly ScanTable[] = ['pages', 'facts', 'takes', 'timeline_entries'];++const CHECKPOINT_OP = 'trust_scan';+const CHECKPOINT_KEY = 'v1';+export const DEFAULT_SCAN_BATCH = 500;++/** Every hit is recorded as a flag: the scan never quarantines or rejects retroactively. */+const SCAN_CONFIG: WriteGateConfig = { externalMode: 'flag', agentMode: 'flag' };++/** Tiers the scan covers: at or below the activation ceiling. */+export const SCAN_TIERS: readonly TrustTier[] = TRUST_TIERS.filter(t => TRUST_TIER_RANK[t] <= TRUST_TIER_RANK[ACTIVATION_TIER_CEILING]);+const tierList = SCAN_TIERS.map(t => `'${t}'`).join(',');++/**+ * `until` is each table's max id when the scan (for this detector version)+ * first ran: rows above it were written after the gate went live and are+ * gated at write time, so the scan's work is bounded and it can complete.+ */+interface Cursor { detector_version: number; ids: Partial<Record<ScanTable, number>>; until?: Partial<Record<ScanTable, number>>; completed_at?: string }++async function readCursor(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Cursor | null> {+ const [row] = await engine.executeRaw<{ keys: unknown }>(+ 'SELECT completed_keys AS keys FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [CHECKPOINT_OP, CHECKPOINT_KEY]);+ const keys = typeof row?.keys === 'string' ? JSON.parse(row.keys) as unknown : row?.keys;+ const first = Array.isArray(keys) ? keys[0] as Cursor | undefined : undefined;+ return first && typeof first === 'object' && typeof first.detector_version === 'number' ? first : null;+}++async function saveCursor(engine: Pick<BrainEngine, 'executeRaw'>, cursor: Cursor): Promise<void> {+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ($1, $2, $3::text::jsonb)+ ON CONFLICT (op, fingerprint) DO UPDATE SET completed_keys = EXCLUDED.completed_keys, updated_at = now()`,+ [CHECKPOINT_OP, CHECKPOINT_KEY, JSON.stringify([cursor])]);+}++/** The cursor that applies to the current detector; an older detector's cursor starts over. */+async function currentCursor(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Cursor> {+ const stored = await readCursor(engine).catch(() => null);+ return stored && stored.detector_version === WRITE_GATE_DETECTOR_VERSION ? stored : { detector_version: WRITE_GATE_DETECTOR_VERSION, ids: {} };+}++interface Row { id: number | string; source_id: string | null; trust_tier: string; write_origin: unknown; [k: string]: unknown }++const SELECT: Readonly<Record<ScanTable, string>> = {+ pages: `SELECT p.id, p.source_id, p.trust_tier, p.write_origin, p.title, p.compiled_truth, p.timeline, p.frontmatter FROM pages p+ WHERE p.id > $1 AND p.deleted_at IS NULL AND p.trust_tier IN (${tierList}) ORDER BY p.id LIMIT $2`,+ facts: `SELECT f.id, f.source_id, f.trust_tier, f.write_origin, f.fact, f.context, f.value, f.source FROM facts f+ WHERE f.id > $1 AND f.trust_tier IN (${tierList}) ORDER BY f.id LIMIT $2`,+ takes: `SELECT t.id, p.source_id, t.trust_tier, t.write_origin, t.claim, t.source FROM takes t JOIN pages p ON p.id = t.page_id+ WHERE t.id > $1 AND t.trust_tier IN (${tierList}) ORDER BY t.id LIMIT $2`,+ timeline_entries: `SELECT te.id, p.source_id, te.trust_tier, te.write_origin, te.summary, te.detail, te.source FROM timeline_entries te+ JOIN pages p ON p.id = te.page_id WHERE te.id > $1 AND te.trust_tier IN (${tierList}) ORDER BY te.id LIMIT $2`,+};++const text = (v: unknown) => (typeof v === 'string' ? v : null);+const json = (v: unknown): Record<string, unknown> | null => {+ const parsed = typeof v === 'string' ? (() => { try { return JSON.parse(v) as unknown; } catch { return null; } })() : v;+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : null;+};++function assess(table: ScanTable, row: Row): WriteGateAssessment {+ const input = { tier: storedTrustTier(row.trust_tier), origin: json(row.write_origin) as never };+ switch (table) {+ case 'pages': return assessPageForGate({ title: text(row.title), compiled_truth: text(row.compiled_truth) ?? '', timeline: text(row.timeline), frontmatter: json(row.frontmatter) }, input, SCAN_CONFIG);+ case 'facts': return assessFactForGate({ fact: text(row.fact) ?? '', context: text(row.context), value: text(row.value), source: text(row.source) }, input, SCAN_CONFIG);+ case 'takes': return assessTakeForGate({ claim: text(row.claim) ?? '', source: text(row.source) }, input, SCAN_CONFIG);+ case 'timeline_entries': return assessTimelineForGate({ summary: text(row.summary) ?? '', detail: text(row.detail), source: text(row.source) }, input, SCAN_CONFIG);+ }+}++export interface TrustScanTableReport { table: ScanTable; scanned: number; flagged: number; done: boolean }+export interface TrustScanReport {+ detector_version: number;+ tables: TrustScanTableReport[];+ complete: boolean;+ /** Present while rows remain: the command that continues. */+ resume_command?: string;+}++export interface TrustScanOptions {+ batchSize?: number;+ /** Stop after this many batches per table (bounded runs from a job or doctor remediation). */+ maxBatches?: number;+}++/**+ * Scans forward from the stored cursor (always resumable; the cursor is+ * saved after every batch). Each batch's receipts commit with its cursor+ * advance, so an interrupted run neither loses nor repeats a verdict.+ */+export async function runTrustScan(engine: BrainEngine, opts: TrustScanOptions = {}): Promise<TrustScanReport> {+ const batchSize = Math.max(1, Math.min(opts.batchSize ?? DEFAULT_SCAN_BATCH, 10_000));+ const cursor = await currentCursor(engine);+ if (!cursor.until) {+ cursor.until = {};+ for (const table of SCAN_TABLES) {+ const [row] = await engine.executeRaw<{ n: number | string | null }>(`SELECT max(id) AS n FROM ${table}`);+ cursor.until[table] = Number(row?.n ?? 0);+ }+ await saveCursor(engine, cursor);+ }+ const tables: TrustScanTableReport[] = [];+ for (const table of SCAN_TABLES) {+ const report: TrustScanTableReport = { table, scanned: 0, flagged: 0, done: false };+ const until = cursor.until[table] ?? 0;+ for (let batch = 0; opts.maxBatches === undefined || batch < opts.maxBatches; batch++) {+ const after = cursor.ids[table] ?? 0;+ if (after >= until) { report.done = true; break; }+ // Page bodies are large: their batches stay small whatever the caller asked for.+ const limit = table === 'pages' ? Math.min(batchSize, 100) : batchSize;+ const rows = (await engine.executeRaw<Row>(SELECT[table], [after, limit])).filter(r => Number(r.id) <= until);+ if (rows.length === 0) { cursor.ids[table] = until; await saveCursor(engine, cursor); report.done = true; break; }+ await engine.transaction(async tx => {+ for (const row of rows) {+ const assessment = assess(table, row);+ if (assessment.verdict !== 'flag') continue;+ await recordWriteGateReceipt(tx, { targetTable: table, targetId: row.id, sourceId: row.source_id, assessment });+ report.flagged++;+ }+ cursor.ids[table] = rows.length === limit ? Number(rows[rows.length - 1].id) : until;+ await saveCursor(tx, cursor);+ });+ report.scanned += rows.length;+ if (rows.length < limit) { report.done = true; break; }+ }+ tables.push(report);+ }+ const complete = tables.every(t => t.done);+ if (complete) await saveCursor(engine, { ...cursor, completed_at: new Date().toISOString() });+ return { detector_version: WRITE_GATE_DETECTOR_VERSION, tables, complete, ...(complete ? {} : { resume_command: 'gbrain trust scan' }) };+}++export interface TrustScanState { detector_version: number; unscanned: Record<ScanTable, number>; total_unscanned: number; completed_at: string | null }++/**+ * Rows at or below the activation ceiling the current detector has not+ * scanned (doctor `trust_scan`): everything before the first run, then the+ * rows between the cursor and the run's id ceiling.+ */+export async function readTrustScanState(engine: Pick<BrainEngine, 'executeRaw'>): Promise<TrustScanState> {+ const cursor = await currentCursor(engine);+ const unscanned = {} as Record<ScanTable, number>;+ for (const table of SCAN_TABLES) {+ const alias = { pages: 'pages', facts: 'facts', takes: 'takes', timeline_entries: 'timeline_entries' }[table];+ const live = table === 'pages' ? ' AND deleted_at IS NULL' : '';+ const ceiling = cursor.until ? ` AND id <= ${Number(cursor.until[table] ?? 0)}` : '';+ const [row] = await engine.executeRaw<{ n: number | string }>(+ `SELECT count(*)::int AS n FROM ${alias} WHERE id > $1 AND trust_tier IN (${tierList})${live}${ceiling}`, [cursor.ids[table] ?? 0]);+ unscanned[table] = Number(row?.n ?? 0);+ }+ return {+ detector_version: WRITE_GATE_DETECTOR_VERSION, unscanned,+ total_unscanned: SCAN_TABLES.reduce((n, t) => n + unscanned[t], 0), completed_at: cursor.completed_at ?? null,+ };+}diff --git a/src/core/eligibility/stamp.ts b/src/core/eligibility/stamp.tsindex 1de2b74dd7..908c0a974d 100644--- a/src/core/eligibility/stamp.ts+++ b/src/core/eligibility/stamp.ts@@ -8,6 +8,9 @@import type { BrainEngine } from '../engine.ts';import { admitsTrust, type TrustTier } from '../trust/tier.ts';import { trustFields, type TrustFields } from './labels.ts';+import { activationSuppressedSql } from './sql.ts';++const withFlag = (fields: TrustFields, flagged: unknown): TrustFields => (flagged === true ? { ...fields, unconfirmed: true } : fields);interface PageRef { page_id?: number | null; source_id?: string | null; slug: string; trust_tier?: string; origin?: string }@@ -22,20 +25,20 @@ export async function loadPageTrust(engine: Exec, refs: readonly PageRef[]): Proconst ids = [...new Set(refs.map(r => r.page_id).filter((n): n is number => typeof n === 'number' && Number.isFinite(n)))];const slugRefs = refs.filter(r => typeof r.page_id !== 'number');if (ids.length) {- const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown }>(- 'SELECT id, source_id, slug, trust_tier, write_origin FROM pages WHERE id = ANY($1::int[])', [ids]);+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean }>(+ `SELECT id, source_id, slug, trust_tier, write_origin, ${activationSuppressedSql('pages', 'pages')} AS flagged FROM pages WHERE id = ANY($1::int[])`, [ids]);for (const row of rows) {- const fields = trustFields(row.trust_tier, row.write_origin);+ const fields = withFlag(trustFields(row.trust_tier, row.write_origin), row.flagged);byId.set(Number(row.id), fields);byKey.set(key(row.source_id, row.slug), fields);}}if (slugRefs.length) {- const rows = await engine.executeRaw<{ source_id: string; slug: string; trust_tier: string; write_origin: unknown }>(- `SELECT source_id, slug, trust_tier, write_origin FROM pages+ const rows = await engine.executeRaw<{ source_id: string; slug: string; trust_tier: string; write_origin: unknown; flagged: boolean }>(+ `SELECT source_id, slug, trust_tier, write_origin, ${activationSuppressedSql('pages', 'pages')} AS flagged FROM pagesWHERE deleted_at IS NULL AND (source_id, slug) IN (SELECT * FROM unnest($1::text[], $2::text[]))`,[slugRefs.map(r => r.source_id ?? 'default'), slugRefs.map(r => r.slug)]);- for (const row of rows) byKey.set(key(row.source_id, row.slug), trustFields(row.trust_tier, row.write_origin));+ for (const row of rows) byKey.set(key(row.source_id, row.slug), withFlag(trustFields(row.trust_tier, row.write_origin), row.flagged));}return { byId, byKey };}@@ -56,6 +59,7 @@ export async function stampPageTrust<T extends PageRef>(engine: Exec, rows: T[],?? { trust_tier: 'unknown' as const, origin: 'unrecorded' };row.trust_tier = fields.trust_tier;row.origin = fields.origin;+ if (fields.unconfirmed) (row as PageRef & { unconfirmed?: true }).unconfirmed = true;}return floor ? rows.filter(row => admitsTrust(row.trust_tier as TrustTier, floor)) : rows;}@@ -74,9 +78,9 @@ export async function stampRowTrust<T extends object>(const ids = [...new Set(rows.map(r => Number(idOf(r))).filter(Number.isFinite))];const byId = new Map<number, TrustFields>();try {- const found = await engine.executeRaw<{ id: number | string; trust_tier: string; write_origin: unknown }>(- `SELECT id, trust_tier, write_origin FROM ${ROW_TABLES[table]} WHERE id = ANY($1::bigint[])`, [ids]);- for (const row of found) byId.set(Number(row.id), trustFields(row.trust_tier, row.write_origin));+ const found = await engine.executeRaw<{ id: number | string; trust_tier: string; write_origin: unknown; flagged: boolean }>(+ `SELECT r.id, r.trust_tier, r.write_origin, ${activationSuppressedSql(table, 'r')} AS flagged FROM ${ROW_TABLES[table]} r WHERE r.id = ANY($1::bigint[])`, [ids]);+ for (const row of found) byId.set(Number(row.id), withFlag(trustFields(row.trust_tier, row.write_origin), row.flagged));} catch { /* labeled unknown below */ }return rows.map(row => ({ ...row, ...(byId.get(Number(idOf(row))) ?? { trust_tier: 'unknown' as const, origin: 'unrecorded' }) }));}diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 435ff4eaca..d52d235e88 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -41,7 +41,7 @@ import type { BrainEngine, FactRow } from '../engine.ts';import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';import { proactiveEligibility } from '../eligibility/registry.ts';import { activationSuppressionNotice, suppressionSummary } from '../eligibility/activation.ts';-import { stampPageTrust } from '../eligibility/stamp.ts';+import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';import { trustFields } from '../eligibility/labels.ts';import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';@@ -526,6 +526,8 @@ const recall: Operation = {}: undefined;+ const factTrust = new Map((await stampRowTrust(ctx.engine, 'facts', packedFacts, r => r.id))+ .map(r => [r.id, { trust_tier: r.trust_tier, origin: r.origin, ...(r.unconfirmed ? { unconfirmed: true as const } : {}) }]));return {facts: packedFacts.map(r => ({id: r.id,@@ -557,7 +559,7 @@ const recall: Operation = {// is the protocol name for the stored source attribution.fact_id: String(r.id),provenance: r.source, ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),- ...trustFields(r.trust_tier, r.write_origin),+ ...(factTrust.get(r.id) ?? trustFields(r.trust_tier, r.write_origin)),})),total: packedFacts.length,...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),@@ -576,6 +578,7 @@ const recall: Operation = {...(r.delivered ? { delivered: r.delivered } : {}),...(r.relational ? { relational: r.relational } : {}),...(r.trust_tier ? { trust_tier: r.trust_tier, origin: r.origin } : {}),+ ...(r.unconfirmed ? { unconfirmed: true } : {}),})),...(searchDegraded ? { search_degraded: searchDegraded } : {}),...(searchDegraded ? {} : await searchAnswerFeedback(ctx, 'recall', packedResults)),diff --git a/src/core/ops/get-page-projection.ts b/src/core/ops/get-page-projection.tsindex b30f6cddc8..81368e61f5 100644--- a/src/core/ops/get-page-projection.ts+++ b/src/core/ops/get-page-projection.ts@@ -88,7 +88,6 @@ export function projectGetPage(page: Page, o: GetPageProjectionOpts) {: wrap ? { ...page, compiled_truth: enveloped(page.compiled_truth, o.trust), timeline: enveloped(page.timeline, o.trust) } : page;const content = () => wrap ? enveloped(serializePageToMarkdown(page, tags), o.trust) : serializePageToMarkdown(visibleBody, tags);const extras = {- ...(o.trust ? o.trust : {}),...(quarantined ? { quarantined } : {}),...(o.timeline_entries !== undefined ? { timeline_entries: o.timeline_entries } : {}),...(o.file_held !== undefined ? { file_held: o.file_held } : {}),@@ -113,6 +112,8 @@ export function projectGetPage(page: Page, o: GetPageProjectionOpts) {revision,tags,...(o.includeContent && !omitted ? { content: content() } : {}),+ // #5575 A6: the reading shape carries the page's trust; the content_only round-trip shape stays minimal.+ ...(o.trust ?? {}),...extras,};}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex f8a18ac5c2..054f155981 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -18,6 +18,7 @@ import { PageSnapshotAmbiguousError, type PageSnapshot } from '../page-state/typimport { serializePageToMarkdown } from '../markdown.ts';import { pageTrustForRead, projectFetchText, projectGetPage, readQuarantined } from './get-page-projection.ts';import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';+import { stampRowTrust } from '../eligibility/stamp.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { getContentFlag } from '../quarantine.ts';@@ -206,7 +207,7 @@ const get_page: Operation = {// `content` roughly duplicates compiled_truth + timeline — always emitting// it would double every reader's payload for the round-trip minority.const timelineEntries = includeTimelineEntries- ? await ctx.engine.getTimeline(page.slug, { ...await readPolicyOpts(ctx, { sourceId: page.source_id }), eligibility: readable.eligibility }) : undefined;+ ? await stampRowTrust(ctx.engine, 'timeline_entries', await ctx.engine.getTimeline(page.slug, { ...await readPolicyOpts(ctx, { sourceId: page.source_id }), eligibility: readable.eligibility }), e => e.id) : undefined;const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259return projectGetPage(visibleBody, {revision: snapshot!.revision, tags, includeContent, contentOnly: (p.content_only as boolean) === true, resolved_slug, content_flag, quarantined, trust: readable.trust,diff --git a/src/core/ops/timeline.ts b/src/core/ops/timeline.tsindex fbd4065eab..47bc7a3f93 100644--- a/src/core/ops/timeline.ts+++ b/src/core/ops/timeline.ts@@ -12,7 +12,7 @@ import { opError, type Operation } from './contract.ts';import { opTransport } from './op-fix.ts';import { readPolicyOpts } from './context.ts';import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';-import { withTrustLabel } from '../eligibility/labels.ts';+import { stampRowTrust } from '../eligibility/stamp.ts';import {enforceSubagentSlugFence,enforceClientSlugFence,@@ -99,7 +99,7 @@ const get_timeline: Operation = {...(limit !== undefined ? { limit } : {}),eligibility,});- return entries.map(e => withTrustLabel(e));+ return stampRowTrust(ctx.engine, 'timeline_entries', entries, e => (e as { id: number }).id);},scope: 'read',cliHints: { name: 'timeline', positional: ['slug'] },diff --git a/src/core/search/lean-rows.ts b/src/core/search/lean-rows.tsindex f74590b991..007d37cc16 100644--- a/src/core/search/lean-rows.ts+++ b/src/core/search/lean-rows.ts@@ -30,7 +30,7 @@ const KEPT_FIELDS: ReadonlySet<string> = new Set(['injection_suspected', 'injection_p', 'unverified', 'content_flag', 'status', 'superseded', 'superseded_by','message_id', 'thread_id', 'source_subject', 'relational',// #5575 A6: every row says how much it deserves influence.- 'trust_tier', 'origin',+ 'trust_tier', 'origin', 'unconfirmed',// Present only when the caller asked for `explain: true`.'score_details',]);diff --git a/src/core/types.ts b/src/core/types.tsindex b0df13757f..30e32e4cea 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -835,6 +835,8 @@ export interface SearchResult {/** #5575 A6: the page's trust tier and short write origin (eligibility/stamp.ts), stamped after ranking. */trust_tier?: import('./trust/tier.ts').TrustTier;origin?: string;+ /** #5575 CEO-20: unconfirmed agent-written content with an instruction-family gate flag (explicit reads only). */+ unconfirmed?: true;/*** 2026-09 fix wave (#3617 follow-up): true when this row came from the* keyword/title arm's AND→OR zero-strict-recall fallback rather than adiff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 2db565e1ea..484ee93e68 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -710,6 +710,7 @@" --adaptive-return true when one answer is wanted (fewer rows; never returns empty); omit for breadth."," --autocut Default on (never returns empty); false gives full top-K for breadth, unlike adaptive_return."," --relational Relationship-graph arm (default on).",+ " --min-trust Lowest trust tier to return (the connection floor still applies)."," --explain Per-row score_details."," --explain-target Expected page (slug or source:slug): why it is missing."]diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 945a6cacd4..ac30d1c1f6 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 213467,- "stdoutSha256": "83e5d4ddae14a328b39704f90910d02986cbe8106e72174266310f705ccb4561",+ "stdoutBytes": 218195,+ "stdoutSha256": "47b74412739a61e9149e02ca61ed49d8d15d598ca1327647c6d6fba3a421bdc6","toolNames": ["remember","entity",@@ -376,6 +376,7 @@"include_deleted": "boolean?","include_quarantined": "boolean?","include_timeline_entries": "boolean?",+ "min_trust": "string?","slug": "string","source_id": "string?"},@@ -406,6 +407,18 @@"description": "Also return timeline rows.","type": "boolean"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"slug": {"description": "Page slug.","type": "string"@@ -782,7 +795,8 @@"name": "fetch","parameters": {"id": "string",- "include_quarantined": "boolean?"+ "include_quarantined": "boolean?",+ "min_trust": "string?"},"required_scopes": [],"schema": {@@ -794,6 +808,18 @@"include_quarantined": {"description": "Admin: quarantined body.","type": "boolean"+ },+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"}},"required": [@@ -1026,6 +1052,7 @@"parameters": {"fields": "string?","limit": "number?",+ "min_trust": "string?","mode": "string?","offset": "number?","query": "string",@@ -1053,6 +1080,18 @@"description": "Max results (default 20).","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"mode": {"description": "Local callers only.","type": "string"@@ -1145,6 +1184,7 @@"image_mime": "string?","lang": "string?","limit": "number?",+ "min_trust": "string?","mode": "string?","near_symbol": "string?","offset": "number?",@@ -1228,6 +1268,18 @@"description": "Default 10/25/50 by search mode.","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"mode": {"description": "Local callers only.","type": "string"@@ -1331,6 +1383,7 @@"parameters": {"detail": "string?","hits": "array",+ "min_trust": "string?","return_unit": "string?","return_window": "number?","token_budget": "number?"@@ -1354,6 +1407,18 @@},"type": "array"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"return_unit": {"description": "Evidence unit: 'chunk' | 'window' | 'section' | 'page' | 'auto' (default 'page').","enum": [@@ -2046,6 +2111,7 @@"after": "string?","before": "string?","limit": "number?",+ "min_trust": "string?","since": "string?","slug": "string","until": "string?"@@ -2065,6 +2131,18 @@"description": "Maximum number of timeline entries to return","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"since": {"description": "Alias for after; accepted for agent callers","type": "string"@@ -3828,6 +3906,7 @@"holder": "string?","kind": "string?","limit": "number?",+ "min_trust": "string?","offset": "number?","page_slug": "string?","resolved": "boolean?",@@ -3852,6 +3931,18 @@"description": "Max rows (default 100, cap 500)","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"offset": {"description": "Skip first N rows","type": "number"@@ -3882,6 +3973,7 @@"name": "takes_search","parameters": {"limit": "number?",+ "min_trust": "string?","query": "string"},"required_scopes": [],@@ -3891,6 +3983,18 @@"description": "Max results (default 30, cap 100)","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"query": {"description": "Search text matched against take claim text via trigram similarity, e.g. 'valuation cap'. This is the search text param — there is no `text` param.","type": "string"@@ -5108,6 +5212,7 @@"days": "number?","max_pages": "number?","min_confidence": "number?",+ "min_trust": "string?","prior_context": "string?","session_id": "string?","stats": "boolean?",@@ -5129,6 +5234,18 @@"description": "Confidence gate 0..1 (default 0.7 — slug-suffix matches need an explicit lower gate).","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"prior_context": {"description": "Already-surfaced context (pointer blocks / opened page bodies). Pages whose slug appears here are not re-volunteered.","type": "string"@@ -5433,6 +5550,7 @@"include_expired": "boolean?","include_pending": "boolean?","limit": "number?",+ "min_trust": "string?","query": "string?","return_unit": "string?","return_window": "number?",@@ -5476,6 +5594,18 @@"description": "Per-arm max (default 50, cap 100).","type": "number"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"query": {"description": "Also search pages (results[] arm).","type": "string"@@ -5527,6 +5657,7 @@"budget_tokens": "number?","entities": "string?","include_private": "boolean?",+ "min_trust": "string?","session_id": "string?","since": "string?"},@@ -5545,6 +5676,18 @@"description": "Local trusted callers only.","type": "boolean"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"session_id": {"description": "Opaque session id.","type": "string"@@ -5570,6 +5713,7 @@"cursor": "string?","entities": "string?","include_private": "boolean?",+ "min_trust": "string?","session_id": "string?","since": "string?","since_slug": "string?"@@ -5593,6 +5737,18 @@"description": "Local trusted callers only.","type": "boolean"},+ "min_trust": {+ "description": "Lowest trust tier to return (the connection floor still applies).",+ "enum": [+ "user_confirmed",+ "operator_curated",+ "tool_observed",+ "agent_written",+ "unknown",+ "external_untrusted"+ ],+ "type": "string"+ },"session_id": {"description": "Session id; keeps a cursor.","type": "string"diff --git a/test/get-timeline-op.test.ts b/test/get-timeline-op.test.tsindex 44affadf09..d38da9351e 100644--- a/test/get-timeline-op.test.ts+++ b/test/get-timeline-op.test.ts@@ -62,6 +62,7 @@ describe('get_timeline op', () => {after: '2026-01-01',before: '2026-03-31',limit: 7,+ eligibility: {},},}]);});diff --git a/test/mcp-result-size-ceiling.test.ts b/test/mcp-result-size-ceiling.test.tsindex 2e3b7fb683..37223ed34b 100644--- a/test/mcp-result-size-ceiling.test.ts+++ b/test/mcp-result-size-ceiling.test.ts@@ -25,7 +25,7 @@ import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';import { withEnv } from './helpers/with-env.ts';/** ceil(measured x 1.05) on the fixture below. */-const CEILINGS = { search: 2540, query: 2540 };+const CEILINGS = { search: 2756, query: 2756 };/*** The keyless fixture also gets the operator contract's degraded_recall* notice (F3) on every HTTP call. It is bounded on its own so the ceilings