Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): scope and rate-limit retrieval coverage notices (#7165)
garrytan25f2c32ce43e
diff --git a/src/cli/op-notices.ts b/src/cli/op-notices.tsindex 992be0d2de..151a647136 100644--- a/src/cli/op-notices.ts+++ b/src/cli/op-notices.ts@@ -5,12 +5,21 @@* `notices` (array results stay bare, notices go to stderr), human output* gets stderr lines on a TTY and an `[AGENT]` block otherwise (stdout is data).* One op per CLI process, so module state is safe.+ *+ * #7165: an escalating coverage notice, and the `projection_pending` part of+ * search/query's `Retrieval incomplete:` line, show once per+ * COVERAGE_NOTICE_WINDOW_MS across CLI calls under GBRAIN_HOME (per brain),+ * until the count worsens or a new source or kind appears.*/+import { createHash } from 'node:crypto';import { cliRenderContext, renderNotice, type Notice } from '../core/agent-output.ts';import { renderCliNotices } from '../core/agent-markers.ts';import { isInteractive } from '../core/interaction.ts';-import { processNoticeLedger, mutedNoticeCodes } from '../core/notice-ledger.ts';+import { admitAcrossCliCalls, processNoticeLedger, mutedNoticeCodes } from '../core/notice-ledger.ts';import { takeChatFallbackHopNotices } from '../core/ai/fallback-hop-queue.ts';+import { getCliOptions } from '../core/cli-options.ts';+import { loadConfig } from '../core/config.ts';+import type { RetrievalCoverage } from '../core/search/retrieval-coverage.ts';let pending: Notice[] = [];@@ -31,6 +40,7 @@ export function applyCliOpNotices(result: unknown, json: boolean): { result: unkif (captured.length === 0) return { result };let admitted = captured;try { admitted = processNoticeLedger().admit(captured, { transport: 'cli' }, mutedNoticeCodes()); } catch { /* fail-open */ }+ admitted = admitted.filter(n => !n.escalation || admitAcrossCliCalls(`${cliBrainKey()}|${n.code}|${n.escalation.key}`, n.escalation.level));const rendered = admitted.map(n => renderNotice(n, cliRenderContext()));if (rendered.length === 0) return { result };const isObject = typeof result === 'object' && result !== null && !Array.isArray(result);@@ -38,3 +48,30 @@ export function applyCliOpNotices(result: unknown, json: boolean): { result: unkconst out = renderCliNotices(rendered, { json: false, tty: isInteractive(), stdoutIsData: true });return { result, stderr: out.stderr };}++/** The brain this CLI call reads: its id plus a hash of its database location (never the location itself). */+function cliBrainKey(): string {+ let location = '';+ try { const cfg = loadConfig(); location = cfg?.database_url ?? cfg?.database_path ?? ''; } catch { /* unreadable config: one key for the home */ }+ return `${getCliOptions().brain ?? process.env.GBRAIN_BRAIN_ID ?? 'host'}-${createHash('sha256').update(location).digest('hex').slice(0, 12)}`;+}++const INCOMPLETE_STAGES: ReadonlySet<string> = new Set(['vector_candidates_incomplete', 'projection_pending', 'projection_status_unknown']);++/**+ * search/query's `Retrieval incomplete:` line, '' when no stage applies. With the+ * call's `coverage`, `projection_pending` is left out when no pending page could+ * match the query or the same pending count already showed within the window, and+ * otherwise the line says how many could.+ */+export function retrievalIncompleteLine(meta: Record<string, unknown> | null | undefined): string {+ const coverage = meta?.coverage as RetrievalCoverage | undefined;+ const total = coverage?.pending_projection, could = coverage?.could_affect?.pending_projection;+ const counted = typeof total === 'number' && typeof could === 'number';+ const stages = (Array.isArray(meta?.degraded) ? [...new Set((meta.degraded as Array<{ stage?: string }>).map(d => d?.stage))] : [])+ .filter((s): s is string => typeof s === 'string' && INCOMPLETE_STAGES.has(s))+ .filter(s => s !== 'projection_pending' || !counted || (could > 0 && admitAcrossCliCalls(`${cliBrainKey()}|projection_pending`, total)));+ if (!stages.length) return '';+ const scoped = counted && stages.includes('projection_pending') ? ` ${could} of ${total}${coverage?.capped ? '+' : ''} pending page(s) could match this query.` : '';+ return `Retrieval incomplete: ${stages.join(', ')}.${scoped}\n`;+}diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex d0ff90fd0b..c141f8ea18 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -85,6 +85,12 @@ export interface Notice {* alone. renderNotice never copies it, so it never reaches the wire.*/dedupe_key?: string;+ /**+ * Unrendered (#7165): a coverage notice whose repeat of the same state is+ * suppressed per session (NoticeLedger) and per one-shot CLI window, until+ * `level` rises materially or the `key` (code, sources, kinds) is new.+ */+ escalation?: { key: string; level: number };}export interface RenderedNotice extends Omit<Notice, 'fix'> { fix?: RenderedAction; contract_version: 1 }diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 4e49446ea9..2fd810ebb5 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1022,6 +1022,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },+ // #7165 and #7147 (GBRA-151 wave 2). `since` is restamped at the merge slot.+ { since: '0.60.327.0', text: 'search and query responses carry `_meta.retrieval.coverage`: pending text projections, held files and pages held from embedding in scope, each with `could_affect` (how many could match this query; an empty result counts all). The `held_files` notice (which now also names embedding holds), the `projection_pending` part of `degraded_recall` and the CLI `Retrieval incomplete:` line appear only when some could, say how many, and show once per session (CLI: once per 30 minutes per GBRAIN_HOME) unless the count rises 10% or a new source or kind appears. `_meta.retrieval.degraded` still lists `projection_pending`.' },+ { since: '0.60.327.0', text: 'The update check prints one line instead of two: agent harnesses (stderr not a terminal, or GBRAIN_FORCE_UPGRADE_MARKER=1) get only `UPGRADE_AVAILABLE <current> <latest>`, a terminal gets only the `gbrain <a> -> <b> available` sentence, and it shows once per 30 minutes per GBRAIN_HOME for a given version; a newer version shows at once.' },{ since: '0.60.328.0', id: 'google_api_access_probe', text: 'A managed Google source whose enabled services cannot name the account (an API disabled for the OAuth project, a scope not granted) now resolves it through the OAuth userinfo endpoint: the account pins, the services that work keep syncing, the run is `partial`, and the disabled API is reported as `api_not_enabled` instead of failing the whole sync. `connector_account_changed` is raised only when an account resolved and differs from the pin; when nothing can name the account (userinfo also failing), the sync fails with the underlying error, a network failure included, instead of refusing as an account change. `gbrain google setup` now probes every requested service before registering a source and stops (exit 2, `status: api_access_blocked`) naming each disabled API with its Google Cloud project and enable link, or each scope not granted, in one report. `gbrain google status` adds `accounts[].api_access` and exits 1 while a problem remains, and doctor adds `google_api_access`, read from what the last sync recorded. A Google 403 for insufficient authentication scopes is now `scope_missing` (before: `upstream`, and a calendar read named it `calendar_unreadable`).' },];diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex d53a36762c..24ec944159 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -842,7 +842,7 @@ export const NOTICE_CODES = {facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },relational_chain: { kind: 'degraded', summary: 'A typed relationship chain found no complete answer (start page not visible, no typed edges, an empty hop) or hit a cap; the notice names the hop and the next call.' },pinned_answer_stale: { kind: 'degraded', summary: 'A pinned answer has stale sentences (their evidence changed or was removed) or its refresh is blocked; stale sentences are flagged and withheld from context_pack, and the fix is the next step.' },- held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },+ held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import (held new files are missing, pages whose newer file is held are stale), or pages in scope are held from embedding (no vectors); search and query show it when some could match the query, once per session per state. The fix is the repair preview, or gbrain embed --held --dry-run, on the brain host.' },recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },page_quarantined: { kind: 'safety', summary: 'The page was quarantined by the content-quality gate (hidden from search; its facts and takes are not extracted). A read says to treat its text as untrusted scraped content and, for an untrusted reader, that its body was withheld (an admin-scoped caller may pass include_quarantined: true); a write says the page was hidden and that the operator clears a false positive with gbrain quarantine clear <slug> --force.' },fence_normalized: { kind: 'coaching', summary: 'A write\'s facts or takes fence was rewritten losslessly (rows and classes named, never values): the stored page differs from what was sent, so re-read it with get_page before editing; remember and takes_add write rows that never need it.' },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 1123e1021d..81d941447b 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -15,6 +15,7 @@ import type { ExplicitReadBinding } from './ops/contract.ts';import { configReadiness } from './readiness.ts';import { affectsRecall, type DegradedStage } from './types.ts';import type { RerankFailedReason } from './search/rerank.ts';+import type { RetrievalCoverage } from './search/retrieval-coverage.ts';import { localTranscriptsFix } from './transcripts.ts';// ── degraded recall (F3) ───────────────────────────────────────────────────@@ -155,14 +156,19 @@ function embeddingsFix(cfg: GBrainConfig | null | undefined, transport: 'stdio'* A `rerank_failed` stage names its reason, the fallback (fused order) and, when the caller counts them* (`rerankDegradedCalls`), this session's reranker-degraded calls; its fix follows the reason (`retry`* is the call to repeat after a transient failure) when no other stage needs a fix.+ * #7165: with the call's `coverage`, `projection_pending` is left out when no pending page could match the+ * query, names how many could otherwise, and a notice whose only stage it is escalates (the same pending+ * count shows once per session).*/export function degradedRecallNotice(stages: ReadonlyArray<{ stage?: string; reason?: string } | string>,- opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; optedOut?: boolean; rerankDegradedCalls?: number; retry?: { op: string; args: Record<string, unknown> } },+ opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; optedOut?: boolean; rerankDegradedCalls?: number; retry?: { op: string; args: Record<string, unknown> }; coverage?: RetrievalCoverage },): Notice | null {const entries = stages.map(s => (typeof s === 'string' ? { stage: s } : s));+ const pendingTotal = opts.coverage?.pending_projection, pendingCould = opts.coverage?.could_affect?.pending_projection;+ const pendingCounted = typeof pendingTotal === 'number' && typeof pendingCould === 'number';const names = [...new Set(entries- .filter(s => affectsRecall(s) && (s.stage as string) in DEGRADED_STAGE_GUIDANCE)+ .filter(s => affectsRecall(s) && (s.stage as string) in DEGRADED_STAGE_GUIDANCE && !(s.stage === 'projection_pending' && pendingCould === 0)).map(s => s.stage as RecallStage))];if (names.length === 0) return null;const pairs = [...new Set(entries.filter(s => names.includes(s.stage as RecallStage)).map(s => `${s.stage}:${s.reason ?? ''}`))].sort();@@ -172,7 +178,9 @@ export function degradedRecallNotice(const labels = names.map(n => (n === 'rerank_failed' ? `rerank_failed: ${rerank}` : n === 'keyword_arm_failed' && keywordSkipped ? 'keyword_arm_failed: skipped_after_timeout' : n));const whys = names.map(n => (n === 'rerank_failed'? `reranking failed because ${RERANK_REASON_WHY[rerank!]}, so results keep their fused order (fallback: fused_order${opts.rerankDegradedCalls ? `; reranker-degraded calls this session: ${opts.rerankDegradedCalls}` : ''})`- : n === 'keyword_arm_failed' && keywordSkipped ? KEYWORD_SKIPPED_WHY : DEGRADED_STAGE_GUIDANCE[n].why));+ : n === 'keyword_arm_failed' && keywordSkipped ? KEYWORD_SKIPPED_WHY+ : n === 'projection_pending' && pendingCounted ? `${DEGRADED_STAGE_GUIDANCE[n].why} (${pendingCould} of ${pendingTotal}${opts.coverage?.capped ? '+' : ''} pending page(s) could match this query)`+ : DEGRADED_STAGE_GUIDANCE[n].why));const guidance = names.map(n => DEGRADED_STAGE_GUIDANCE[n]);const fixKind: StageFix = guidance.some(g => g.fix === 'embeddings') ? 'embeddings' : guidance.some(g => g.fix === 'doctor') ? 'doctor' : null;const byChoice = opts.optedOut || entries.some(s => s.reason === 'embedding_disabled');@@ -189,6 +197,7 @@ export function degradedRecallNotice(...(fix ? { fix } : {}),...(fix?.user_message ? { user_message: fix.user_message } : {}),...(persistent ? { dedupe_key: pairs.join('|') } : {}),+ ...(pendingCounted && names.every(n => n === 'projection_pending') ? { escalation: { key: 'projection_pending', level: pendingTotal } } : {}),};}@@ -357,7 +366,8 @@ export function recallInteropNotices(const entries = (meta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined)?.degraded ?? [];const stages = recallStagesFor(op, result, meta, opts.config).map(stage => entries.find(d => d.stage === stage) ?? stage);const { _meta: _ignored, ...args } = params;- const degraded = degradedRecallNotice(stages, { ...opts, optedOut: embeddingOptedOutFor(op, result, meta), retry: { op, args } });+ const coverage = (meta.retrieval as { coverage?: RetrievalCoverage } | undefined)?.coverage;+ const degraded = degradedRecallNotice(stages, { ...opts, optedOut: embeddingOptedOutFor(op, result, meta), retry: { op, args }, coverage });if (degraded) out.push(degraded);const narrowed = opts.transport === 'stdio' ? sourceBindingNarrowedNotice(op, params, result, opts.binding) : null;if (narrowed) out.push(narrowed);diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex 031ba5e23f..f332813b4b 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -16,6 +16,12 @@* - Mute applies to `coaching` and `info` only: globally for the local owner* (`gbrain notices mute <code>`), per client on remote transports* (`mute_notice`). Persisted under GBRAIN_HOME.+ * - A notice carrying `escalation` (#7165 coverage notices: held_files and a+ * projection-only degraded_recall) shows once per session per key for+ * COVERAGE_NOTICE_WINDOW_MS, per-call code or not, and again at once when its+ * level rises materially (`coverageWorsened`). HTTP applies it only with a+ * transport-resolved session id. One-shot CLI calls share the window through+ * `admitAcrossCliCalls` (GBRAIN_HOME/notices/coverage.json).*/import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';import { dirname } from 'node:path';@@ -30,6 +36,24 @@ export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decis/** Notices that describe THIS call's result (never deduped unless the notice carries a `dedupe_key`): the diagnosis must ride every affected call. */export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'references_unavailable', 'record_types_undeclared', 'alias_fanout', 'facts_unembedded']);+/** How long a shown coverage state (a notice's `escalation`) stays shown. */+export const COVERAGE_NOTICE_WINDOW_MS = 30 * 60 * 1000;++/** Material worsening over `floor`, the lowest level seen since the notice last showed: up by 10% and at least 1. */+export function coverageWorsened(floor: number, level: number): boolean {+ return level >= floor + Math.max(1, Math.ceil(floor * 0.1));+}++interface EscalationMark { floor: number; at: number }++/** Show or suppress one escalating notice given its last mark; the returned mark replaces it. */+function escalate(prev: EscalationMark | undefined, level: number, now: number): { show: boolean; mark: EscalationMark } {+ if (prev && now - prev.at < COVERAGE_NOTICE_WINDOW_MS && !coverageWorsened(prev.floor, level)) {+ return { show: false, mark: { floor: Math.min(prev.floor, level), at: prev.at } };+ }+ return { show: true, mark: { floor: level, at: now } };+}+/** Notices whose producer already deduped them with `claim` on its own key; admit applies mute only. */export const SELF_DEDUPED_NOTICE_CODES: ReadonlySet<string> = new Set(['grant_blocked_operations']);@@ -47,6 +71,7 @@ export class NoticeLedger {private tallies = new Map<string, { n: number; at: number }>();private claimed = new Map<string, number>();private memo = new Map<string, { value: unknown; at: number }>();+ private escalations = new Map<string, EscalationMark>();constructor(private readonly now: () => number = Date.now) {}@@ -96,6 +121,13 @@ export class NoticeLedger {const session = this.session(audience);for (const n of notices) {if ((n.kind === 'coaching' || n.kind === 'info' || MUTEABLE_ASK_CODES.has(n.code)) && muted.has(n.code)) continue;+ if (n.escalation && (audience.transport !== 'http' || audience.sessionId)) {+ const key = `${session}|${n.code}|${n.escalation.key}`;+ const { show, mark } = escalate(this.escalations.get(key), n.escalation.level, this.now());+ this.escalations.delete(key);+ this.escalations.set(key, mark);+ if (!show) continue;+ }const always = (PER_CALL_NOTICE_CODES.has(n.code) && n.dedupe_key === undefined) || SELF_DEDUPED_NOTICE_CODES.has(n.code)|| (audience.transport === 'http' && (n.kind === 'degraded' || n.kind === 'safety'));const key = n.dedupe_key === undefined ? `${session}|${n.code}` : `${session}|${n.code}|${n.dedupe_key}`;@@ -114,6 +146,7 @@ export class NoticeLedger {}this.prune(this.seen, at => at);this.prune(this.coaching, v => v.at);+ this.prune(this.escalations, v => v.at);return out;}}@@ -126,6 +159,42 @@ export function processNoticeLedger(): NoticeLedger {}export function __resetProcessNoticeLedgerForTests(): void { processLedger = null; }+// ── coverage window for one-shot CLI calls ─────────────────────────────────++const CLI_COVERAGE_MARKS_MAX = 200;++export function coverageNoticePath(): string {+ return gbrainPath('notices', 'coverage.json');+}++/**+ * #7165: whether an escalating notice shows in this CLI call, given what earlier+ * calls under this GBRAIN_HOME showed within COVERAGE_NOTICE_WINDOW_MS. `key`+ * names the brain, the code and the escalation key. A store that cannot be+ * written shows it. Never throws.+ */+export function admitAcrossCliCalls(key: string, level: number, now: number = Date.now()): boolean {+ let marks: Record<string, EscalationMark> = {};+ try {+ const raw = JSON.parse(readFileSync(coverageNoticePath(), 'utf8')) as { marks?: Record<string, EscalationMark> };+ if (raw.marks && typeof raw.marks === 'object') marks = raw.marks;+ } catch { /* no marks yet */ }+ const { show, mark } = escalate(marks[key], level, now);+ const kept = Object.entries({ ...marks, [key]: mark })+ .filter(([, m]) => typeof m?.at === 'number' && typeof m.floor === 'number' && now - m.at < COVERAGE_NOTICE_WINDOW_MS)+ .sort((a, b) => b[1].at - a[1].at).slice(0, CLI_COVERAGE_MARKS_MAX);+ try {+ const path = coverageNoticePath();+ mkdirSync(dirname(path), { recursive: true });+ const tmp = `${path}.tmp-${process.pid}`;+ writeFileSync(tmp, `${JSON.stringify({ marks: Object.fromEntries(kept) })}\n`, { mode: 0o600 });+ renameSync(tmp, path);+ } catch {+ return true;+ }+ return show;+}+// ── mute store ──────────────────────────────────────────────────────────────interface MuteFile { global: string[]; clients: Record<string, string[]> }diff --git a/src/core/ops/search.ts b/src/core/ops/search.tsindex 0b20dfd8a3..3c026995ff 100644--- a/src/core/ops/search.ts+++ b/src/core/ops/search.ts@@ -44,6 +44,7 @@ import { SAFE_FENCE_CHUNKER_VERSION, chunkManifestReads } from '../search/safe-cimport { expandEngineTypeFilters } from '../schema-pack/query-types.ts';import { reconcileTypeFilter } from './search-type-filter.ts';import { probeProjectionReadiness } from '../search/projection-readiness.ts';+import { countEmbeddingHeld, countPendingProjections, coverageRelevance, type RetrievalCoverage } from '../search/retrieval-coverage.ts';import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';import { pageReadFilter } from '../search/read-policy-sql.ts';import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION, SEARCH_MATCH_DESCRIPTION } from '../operations-descriptions.ts';@@ -413,6 +414,12 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que* #5988: hits whose page's newer file is held get `stale` (the rows are the* call's own copies, stamped in place), and a scope with held files gets* `held_files` per source plus the `held_files` degraded notice.+ *+ * #7165: `coverage` carries the pending-projection and held-file counts and how+ * many could affect this query (search/retrieval-coverage.ts). `degraded` still+ * records `projection_pending`; the readiness hint, the `held_files` notice and+ * the human renderers of the stage (degraded_recall, the CLI line) appear only+ * when some could. An unknown count stays loud.*/async function buildRetrievalResponseMeta(ctx: OperationContext,@@ -430,25 +437,41 @@ async function buildRetrievalResponseMeta(const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);const excludeSlugPrefixes = resolveHardExcludes();const aliases = (opts.declarations ?? new DeclarationMemo()).scan(results as DeclarationRow[], queryText);+ const relevance = coverageRelevance(results as SearchResult[], queryText, opts.types, FACT_MATCH_STOPWORDS);+ const readinessScope = { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes };// #6721: these reads depend on nothing but the inputs above, so they run at once: on a pooled Postgres// the wall time is the slowest read's round trips, not their sum. The answer-feedback write still runs last.- const [safeIndexPending, readiness, entityFacts, matchedFacts, heldFiles, sourceFreshness] = await Promise.all([+ const [safeIndexPending, [readiness, pending], entityFacts, matchedFacts, held, sourceFreshness, embeddingHeld] = await Promise.all([ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes }),- probeProjectionReadiness(ctx.engine, { ...scope, excludePrivate, types: opts.types, excludeSlugPrefixes }),+ probeProjectionReadiness(ctx.engine, readinessScope).then(async r =>+ [r, r.status === 'projection_pending' ? await countPendingProjections(ctx.engine, readinessScope, relevance) : null] as const),// Facts saved about the entity the query names come first (newest first, one hop through entities they name).opts.entity && ctx.emitResponseMeta ? entitySavedFacts(ctx.engine, opts.entity, { remote: ctx.remote !== false, excludePrivate }) : [],matchingSavedFacts(ctx, scope, queryText, aliases),- stampHeldHits(ctx.engine, results as SearchResult[], scope, ctx).catch(() => []),+ stampHeldHits(ctx.engine, results as SearchResult[], scope, relevance, ctx).catch(() => ({ coverage: [], couldAffect: 0 })),// GBRA-133 PR 2a.5: per-source freshness from the notifier's cached coverage record (no git call).readSourceFreshness(ctx.engine, scope),+ countEmbeddingHeld(ctx.engine, readinessScope, relevance),]);+ const heldFiles = held.coverage;const heldBySource = new Map(heldFiles.map(h => [h.source_id, h.missing + h.stale]));const freshness = sourceFreshness.map(f => ({ ...f, held_count: heldBySource.get(f.source_id) ?? 0 }));// A fact the facts arm already returned as a row is not repeated beside the blocks.const factRowIds = new Set((results as SearchResult[]).flatMap(r => r.fact_row ? [r.fact_row.id] : []));const savedFacts = [...entityFacts, ...matchedFacts.filter(m => !entityFacts.some(e => e.id === m.id))].filter(f => !factRowIds.has(f.id));- const heldNotice = heldFilesNotice(heldFiles, ctx.remote !== false);+ const heldTotal = [...heldBySource.values()].reduce((sum, n) => sum + n, 0);+ const embedding = embeddingHeld?.total ? embeddingHeld : null;+ const coverage: RetrievalCoverage | undefined = pending || heldTotal || embedding ? {+ ...(pending ? { pending_projection: pending.total } : {}),+ ...(heldTotal ? { held_files: heldTotal } : {}),+ ...(embedding ? { embedding_held: embedding.total } : {}),+ could_affect: { ...(pending ? { pending_projection: pending.could_affect } : {}), ...(heldTotal && held.couldAffect !== null ? { held_files: held.couldAffect } : {}),+ ...(embedding ? { embedding_held: embedding.could_affect } : {}) },+ ...(pending?.capped || embedding?.capped ? { capped: true as const } : {}),+ } : undefined;+ const heldNotice = heldFilesNotice(held.couldAffect === 0 ? [] : heldFiles, ctx.remote !== false, held.couldAffect ?? undefined,+ embedding?.could_affect ? embedding : undefined);if (heldNotice) ctx.emitNotice?.(heldNotice);const degraded = [...(m?.degraded ?? [])];if (safeIndexPending) degraded.push({ stage: 'safe_index_pending' });@@ -456,6 +479,7 @@ async function buildRetrievalResponseMeta(else if (readiness.status !== 'ready') {degraded.push({ stage: readiness.status === 'projection_pending' ? 'projection_pending' : 'projection_status_unknown' });}+ const readinessHint = pending?.could_affect === 0 ? undefined : readiness.hint;const planNotice = relationalPlanNotice(m?.relational_plan);if (planNotice) ctx.emitNotice?.(planNotice);return {@@ -480,8 +504,9 @@ async function buildRetrievalResponseMeta(...(savedFacts.length ? { saved_facts: savedFacts } : {}),...(aliases.length ? { other_names: aliases } : {}),...(heldFiles.length ? { held_files: heldFiles } : {}),+ ...(coverage ? { coverage } : {}),...(freshness.length ? { freshness } : {}),- ...(hint || readiness.hint ? { hint: [hint, readiness.hint].filter(Boolean).join(' ') } : {}),+ ...(hint || readinessHint ? { hint: [hint, readinessHint].filter(Boolean).join(' ') } : {}),...(opts.feedbackOp ? await searchAnswerFeedback(ctx, opts.feedbackOp, results as SearchResult[]) : {}),};}diff --git a/src/core/persistence/held-reads.ts b/src/core/persistence/held-reads.tsindex e6487109c7..701c5091a0 100644--- a/src/core/persistence/held-reads.ts+++ b/src/core/persistence/held-reads.ts@@ -7,11 +7,13 @@* the file path for trusted local callers only).* - search and query hits for such a page carry `stale` (held_since, last_indexed_revision).* - retrieval meta carries `held_files` per source in scope (held new files- * missing, held modified files stale) and a `held_files` degraded notice.+ * missing, held modified files stale) and a `held_files` degraded notice+ * when some held file could match the query (#7165, `stampHeldHits`).*- * Cost: one indexed lookup (`op_checkpoints_sync_hold_page_idx`) for the pages- * a call returns and one read of the per-source summary rows in scope, each- * cached per request (plus, only for a page whose held file is an+ * Cost: one read of the per-source summary rows in scope, cached per request,+ * plus one read per call that returned hits from a scope with holds: the+ * returned pages' holds (indexed, `op_checkpoints_sync_hold_page_idx`) and the+ * query-relevant count. `get_page` reads its page's hold (plus, only for an* `invalid_fence` hold, the two reads that say whether the maintenance run* repairs it). Remote callers get codes, counts and flags, never paths, and a* fix addressed to the brain host operator; the repair commands come from the@@ -23,6 +25,7 @@ import type { Action, Notice } from '../agent-output.ts';import { ALL_SOURCES } from '../source-id.ts';import { outOfAttemptsHold, GIT_HOLD_OP, GIT_HOLD_SUMMARY_OP, contentRepairArgv, fenceAutoRepairFor, gitHoldDocs, gitHoldFix, holdRepairSteps, type GitHoldCode, type GitHoldReason, type GitHoldRecord, type HoldRepairRoute } from './sync-holds.ts';import { fenceHoldLocation, fenceHoldRelay, type FenceAutoRepair, type FenceHoldLocation } from '../fence-repair/hold-fix.ts';+import { COVERAGE_COUNT_CAP, type CoverageRelevance } from '../search/retrieval-coverage.ts';type Exec = Pick<BrainEngine, 'executeRaw'>;@@ -180,33 +183,83 @@ export function fileHeldField(held: HeldPage, remote: boolean): FileHeld {fix, docs: gitHoldDocs(record.code, record.meta.reason) };}+const HOLD_PAGE_JOIN = `FROM op_checkpoints h+ JOIN sources s ON s.id=h.completed_keys->0->>'source_id' AND s.incarnation::text=h.completed_keys->0->>'incarnation'+ LEFT JOIN pages p ON p.id=(h.completed_keys->0->>'page_id')::int`;+/**- * Stamps `stale` on hits whose page's newer file is held (one indexed read)- * and returns the per-source coverage of the read scope. Hits are mutated in- * place; callers pass their own copies.+ * Stamps `stale` on hits whose page's newer file is held and returns the+ * per-source coverage of the read scope with (#7165) how many held files could+ * affect this query (retrieval-coverage.ts; every one for an empty result). One+ * summary read; when the scope holds files and the call returned hits, one more+ * read gets the hits' holds (indexed) and the count (capped at+ * COVERAGE_COUNT_CAP). `couldAffect` is null when that read fails: unknown,+ * never zero. Hits are mutated in place; callers pass their own copies.*/export async function stampHeldHits(engine: Exec, hits: Array<{ page_id?: number; stale?: boolean | StaleHit }>, scope: { sourceId?: string; sourceIds?: string[] },- request?: object): Promise<HeldCoverage[]> {+ relevance: CoverageRelevance, request?: object): Promise<{ coverage: HeldCoverage[]; couldAffect: number | null }> {const coverage = await readHeldCoverage(engine, scope, request);- if (!coverage.some(source => source.stale > 0) || !hits.length) return coverage;- const held = await readHeldPages(engine, hits.flatMap(hit => typeof hit.page_id === 'number' ? [hit.page_id] : []), request);- for (const hit of hits) {- const page = typeof hit.page_id === 'number' ? held.get(hit.page_id) : undefined;- if (page) hit.stale = { held_since: page.record.held_at, last_indexed_revision: page.revision };+ if (!coverage.length || relevance.all || !hits.length) return { coverage, couldAffect: coverage.reduce((sum, source) => sum + source.missing + source.stale, 0) };+ const ids = [...new Set(hits.flatMap(hit => typeof hit.page_id === 'number' ? [String(hit.page_id)] : []))];+ let rows: Array<{ record: GitHoldRecord | null; revision: string | null; could_affect: number | null }>;+ try {+ rows = await engine.executeRaw(`(SELECT h.completed_keys->0 AS record, p.knowledge_revision::text AS revision, NULL::int AS could_affect ${HOLD_PAGE_JOIN}+ WHERE h.op=$1 AND (h.completed_keys->0->>'page_id')=ANY($2::text[]) ORDER BY h.fingerprint)+ UNION ALL+ SELECT NULL, NULL, (SELECT count(*)::int FROM (SELECT 1 ${HOLD_PAGE_JOIN}+ WHERE h.op=$1 AND s.archived IS NOT TRUE AND s.id=ANY($3::text[])+ AND ((h.completed_keys->0->>'page_id')=ANY($2::text[]) OR p.type=ANY($4::text[])+ OR lower(concat_ws(' ', h.completed_keys->0->>'path', h.completed_keys->0->>'slug', p.title)) LIKE ANY($5::text[]))+ LIMIT ${COVERAGE_COUNT_CAP}) x)`,+ [GIT_HOLD_OP, ids, coverage.map(source => source.source_id), relevance.types, relevance.patterns]);+ } catch {+ return { coverage, couldAffect: null };+ }+ let couldAffect: number | null = null;+ const stamped = new Set<number>();+ for (const row of rows) {+ if (!row.record) { couldAffect = Number(row.could_affect); continue; }+ const id = Number(row.record.page_id);+ if (stamped.has(id)) continue;+ stamped.add(id);+ for (const hit of hits) if (hit.page_id === id) hit.stale = { held_since: row.record.held_at, last_indexed_revision: row.revision };}- return coverage;+ return { coverage, couldAffect: Number.isFinite(couldAffect) ? couldAffect : null };}-/** The `held_files` notice for a read whose scope has held files; null when it has none. */-export function heldFilesNotice(coverage: HeldCoverage[], remote: boolean): Notice | null {- if (!coverage.length) return null;+/**+ * The `held_files` notice for a read whose scope has held files or (#7165) pages held+ * from embedding; null when it has neither. `couldAffect` (a search or query) names+ * how many held files could match the query, `embedding` how many embedding-held+ * pages are in scope and how many could; either makes the notice escalating: the+ * same sources, kinds and counts show once per session.+ */+export function heldFilesNotice(coverage: HeldCoverage[], remote: boolean, couldAffect?: number, embedding?: { total: number; could_affect: number }): Notice | null {+ if (!coverage.length && !embedding) return null;+ const embeddingWhy = embedding ? `${embedding.total} page(s) in this scope are held from embedding (their embedding budget is held or capped), so they have no vectors and semantic search cannot find them; `+ + `${embedding.could_affect} of them could match this query. Keyword search still finds them where they have chunks. ` : '';const missing = coverage.reduce((sum, source) => sum + source.missing, 0), stale = coverage.reduce((sum, source) => sum + source.stale, 0);+ const kinds = (source: HeldCoverage) => (['missing', 'stale', 'fences', 'concurrent', 'stalled', 'dirty', 'drift'] as const).filter(kind => (source[kind] ?? 0) > 0).join('+');+ const escalation = couldAffect === undefined && !embedding ? {} : { escalation: {+ key: [...coverage.map(source => `${source.source_id}:${kinds(source)}`), ...(embedding ? ['embedding'] : [])].sort().join(','),+ level: missing + stale + (embedding?.total ?? 0) } };+ const absent = 'Treat a missing or outdated answer as "held", never as "the brain has nothing on this".';+ if (!coverage.length) {+ const why = `Coverage is partial: ${embeddingWhy}${absent}`;+ const preview = ['gbrain', 'embed', '--held', '--dry-run'];+ const fix: Action = remote+ ? { argv: preview, consent: [], actor: 'host_admin', requires_exclusive: false, why: 'Lists the held and capped large pages with the cost to finish embedding them; read-only.',+ user_message: `Some large pages in your brain are waiting for embedding approval, so semantic search cannot find them. Please run '${preview.join(' ')}' on the brain host to see them and the cost to finish.` }+ : { argv: preview, consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the held and capped large pages with the cost to finish embedding them; read-only. Approving the spend is the user\'s call.' };+ return { code: 'held_files', kind: 'degraded', why: remote ? `${why} Only the brain host operator can approve embedding them.` : why, fix, ...escalation };+ }const per = coverage.map(source => `${source.source_id}: ${source.missing} missing, ${source.stale} stale`).join('; ');- const why = `Coverage is partial: sync holds ${missing + stale} file(s) it cannot import (${per}). `+ const scoped = couldAffect === undefined ? '' : `${couldAffect} of them could match this query. `;+ const why = `Coverage is partial: sync holds ${missing + stale} file(s) it cannot import (${per}). ${scoped}`+ `${missing} held new file(s) have no page, so their content is absent from this result; ${stale} page(s) whose newer file is held show their last good revision (hits carry stale). `- + 'Treat a missing or outdated answer as "held", never as "the brain has nothing on this".';+ + `${embeddingWhy}${absent}`;const ids = coverage.map(source => source.source_id);- if (remote) return { code: 'held_files', kind: 'degraded', why: `${why} Only the brain host operator can inspect and repair held files.`,+ if (remote) return { code: 'held_files', kind: 'degraded', why: `${why} Only the brain host operator can inspect and repair held files.`, ...escalation,fix: hostOperatorFix(coverage.map(source => ({ source_id: source.source_id, route: coverageRoute(source) })), 'The repair preview on the brain host proposes each fix and writes nothing until the operator applies it.') };const single = coverage.length === 1 ? holdRepairSteps(ids[0]!, coverageRoute(coverage[0]!)) : null;const fix: Action = single@@ -216,5 +269,5 @@ export function heldFilesNotice(coverage: HeldCoverage[], remote: boolean): Noti: `Previews the fix for each held file in source ${ids[0]} (gbrain sources status ${ids[0]} lists them); nothing is written until a hash-bound apply.` }: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false,why: `Doctor lists the held files of each source with its next step (${coverage.map(source => holdRepairSteps(source.source_id, coverageRoute(source)).commands.join(', ')).join('; ')}).` };- return { code: 'held_files', kind: 'degraded', why, fix };+ return { code: 'held_files', kind: 'degraded', why, fix, ...escalation };}diff --git a/src/core/search/projection-readiness.ts b/src/core/search/projection-readiness.tsindex 2303176618..7fe12d5513 100644--- a/src/core/search/projection-readiness.ts+++ b/src/core/search/projection-readiness.ts@@ -1,7 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { PageReadScope } from '../types.ts';-import { pageReadFilter } from './read-policy-sql.ts';import { projectionClassSql } from '../page-state/projection-class.ts';+import { coverageScopeFilters } from './retrieval-coverage.ts';export interface ProjectionReadinessScope extends PageReadScope {pageKind?: string;@@ -83,20 +83,7 @@ async function probeUncached(scope: ProjectionReadinessScope,): Promise<ProjectionReadiness> {const params: unknown[] = [];- const filters = [pageReadFilter('p', scope, params, true)];- if (scope.sourceIds?.length === 0) filters.push('FALSE');- if (scope.pageKind) {- params.push(scope.pageKind);- filters.push(`p.page_kind = $${params.length}`);- }- if (scope.types) {- params.push(scope.types);- filters.push(`p.type = ANY($${params.length}::text[])`);- }- for (const prefix of scope.excludeSlugPrefixes ?? []) {- params.push(prefix);- filters.push(`LEFT(p.slug, LENGTH($${params.length}::text)) <> $${params.length}`);- }+ const filters = coverageScopeFilters(scope, params);try {// One bound statement: unsealed pages that need work, then those unsealed by design (the class fragment doctor counts).const unsealed = `SELECT 1 FROM pages p JOIN sources s ON s.id = p.source_id@@ -124,3 +111,4 @@ async function probeUncached(};}}+diff --git a/src/core/search/retrieval-coverage.ts b/src/core/search/retrieval-coverage.tsnew file mode 100644index 0000000000..e5e7cf9cf5--- /dev/null+++ b/src/core/search/retrieval-coverage.ts@@ -0,0 +1,112 @@+/**+ * #7165: query-scoped coverage for search and query. A pending text projection+ * or a held file is brain state; whether it can change THIS answer depends on+ * the query. An item could affect a query when it is one of the returned pages,+ * its page type is one of the result types or the query's types, or its title,+ * slug or file path contains a query word. An empty result counts every item:+ * nothing rules it out, and an empty answer must never read as complete.+ *+ * Counted here: pending text projections (the readiness probe's unsealed pages+ * that need work) and pages held from embedding (a held or capped+ * page_embedding_budget row that still applies: no vectors, so the vector arm+ * cannot find them). Held files are counted by persistence/held-reads.ts.+ */+import type { BrainEngine } from '../engine.ts';+import { budgetRowAppliesFilter } from '../page-size-policy.ts';+import { projectionClassSql } from '../page-state/projection-class.ts';+import { pageReadFilter } from './read-policy-sql.ts';+import type { ProjectionReadinessScope } from './projection-readiness.ts';++/** Counts stop here (one bounded scan per call); a capped count reports `capped`. */+export const COVERAGE_COUNT_CAP = 1000;++export interface CoverageRelevance {+ all: boolean;+ types: string[];+ /** Lowercase LIKE patterns, one per query word. */+ patterns: string[];+ pageIds: number[];+}++/** `_meta.retrieval.coverage`: counts in the read scope and how many of them could affect this query. */+export interface RetrievalCoverage {+ pending_projection?: number;+ held_files?: number;+ embedding_held?: number;+ could_affect: { pending_projection?: number; held_files?: number; embedding_held?: number };+ capped?: true;+}++export interface ScopedCount { total: number; could_affect: number; capped: boolean }++/** What could make a pending or held item relevant to this query (see the module comment). */+export function coverageRelevance(+ results: ReadonlyArray<{ type?: unknown; page_id?: unknown }>,+ queryText: string,+ queryTypes: readonly string[] | undefined,+ stopwords: ReadonlySet<string>,+): CoverageRelevance {+ const terms = [...new Set(queryText.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}'-]+/gu) ?? [])]+ .filter(t => t.length >= 3 && !stopwords.has(t)).slice(0, 12);+ return {+ all: results.length === 0,+ types: [...new Set([...(queryTypes ?? []), ...results.flatMap(r => (typeof r.type === 'string' ? [r.type] : []))])],+ patterns: terms.map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`),+ pageIds: [...new Set(results.flatMap(r => (typeof r.page_id === 'number' ? [r.page_id] : [])))],+ };+}++/** The readiness probe's scope predicates over `pages p` (sources, visibility, kind, types, excluded prefixes), binding into `params`. */+export function coverageScopeFilters(scope: ProjectionReadinessScope, params: unknown[]): string[] {+ const filters = [pageReadFilter('p', scope, params, true)];+ if (scope.sourceIds?.length === 0) filters.push('FALSE');+ if (scope.pageKind) {+ params.push(scope.pageKind);+ filters.push(`p.page_kind = $${params.length}`);+ }+ if (scope.types) {+ params.push(scope.types);+ filters.push(`p.type = ANY($${params.length}::text[])`);+ }+ for (const prefix of scope.excludeSlugPrefixes ?? []) {+ params.push(prefix);+ filters.push(`LEFT(p.slug, LENGTH($${params.length}::text)) <> $${params.length}`);+ }+ return filters;+}++/** Pages in scope matching `where` (over `pages p` joined to `sources s` and `join`), up to the cap, and how many could affect the query. Null when the count fails: unknown, never zero. */+async function countInScope(engine: Pick<BrainEngine, 'executeRaw'>, scope: ProjectionReadinessScope, relevance: CoverageRelevance,+ join: string, where: string): Promise<ScopedCount | null> {+ const params: unknown[] = [];+ const filters = coverageScopeFilters(scope, params);+ params.push(relevance.all, relevance.types, relevance.patterns, relevance.pageIds);+ const n = params.length;+ try {+ const [row] = await engine.executeRaw<{ total: number | string; could_affect: number | string }>(+ `SELECT count(*)::int AS total,+ count(*) FILTER (WHERE $${n - 3}::boolean OR x.type = ANY($${n - 2}::text[]) OR x.haystack LIKE ANY($${n - 1}::text[]) OR x.id = ANY($${n}::int[]))::int AS could_affect+ FROM (SELECT p.id, p.type, lower(COALESCE(p.title, '') || ' ' || p.slug) AS haystack+ FROM pages p JOIN sources s ON s.id = p.source_id ${join}+ WHERE p.deleted_at IS NULL AND ${where} AND ${filters.join(' AND ')}+ LIMIT ${COVERAGE_COUNT_CAP}) x`,+ params,+ );+ const total = Number(row?.total), couldAffect = Number(row?.could_affect);+ if (!Number.isFinite(total) || !Number.isFinite(couldAffect)) return null;+ return { total, could_affect: couldAffect, capped: total >= COVERAGE_COUNT_CAP };+ } catch {+ return null;+ }+}++/** The pending pages the readiness probe found (unsealed, needing work) in the same scope. */+export function countPendingProjections(engine: Pick<BrainEngine, 'executeRaw'>, scope: ProjectionReadinessScope, relevance: CoverageRelevance): Promise<ScopedCount | null> {+ return countInScope(engine, scope, relevance, '',+ `p.text_projection_revision IS DISTINCT FROM p.knowledge_revision AND ${projectionClassSql('p', 's')} NOT IN ('protected','archived')`);+}++/** Pages in scope held from embedding: a held or capped budget row that still applies. */+export function countEmbeddingHeld(engine: Pick<BrainEngine, 'executeRaw'>, scope: ProjectionReadinessScope, relevance: CoverageRelevance): Promise<ScopedCount | null> {+ return countInScope(engine, scope, relevance, 'JOIN page_embedding_budget b ON b.page_id = p.id', budgetRowAppliesFilter('b', 'p'));+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 15d79af331..8eee4883a6 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -373,6 +373,7 @@ test/repair-frontmatter-keys-sweep-6454.test.tstest/repair-frontmatter.test.tstest/repair-receipt-compaction.test.tstest/repair-rename-identity-6729.test.ts+test/retrieval-coverage-notices.test.tstest/schema-missing-tables.test.tstest/scripts/test-stress-postgres.test.tstest/search-read-keyword-bound.test.tsdiff --git a/test/retrieval-coverage-notices.test.ts b/test/retrieval-coverage-notices.test.tsnew file mode 100644index 0000000000..af4723a1e3--- /dev/null+++ b/test/retrieval-coverage-notices.test.ts@@ -0,0 +1,312 @@+/**+ * #7165: coverage notices (`projection_pending`, `held_files`) are scoped to the+ * query and rate-limited. A pending projection or a held file that cannot match+ * this query drops the human-facing line but stays in `_meta.retrieval.coverage`+ * (and `projection_pending` in `_meta.retrieval.degraded`);+ * one that can match prints with its count. A repeat of the same state is+ * suppressed per session (stdio/HTTP session ledger) and, for one-shot CLI calls,+ * per GBRAIN_HOME window; a worsening or a new source prints again at once.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, type OperationContext } from '../src/core/operations.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { NoticeLedger, __resetProcessNoticeLedgerForTests } from '../src/core/notice-ledger.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { captureRetrievalMeta, formatResult, resetRetrievalMetaForTests } from '../src/cli/main.ts';+import { applyCliOpNotices, captureOpNotice } from '../src/cli/op-notices.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+let engine: BrainEngine;+const search = operations.find(op => op.name === 'search')!;+const home = mkdtempSync(join(tmpdir(), 'gbrain-coverage-notices-'));+const env = { GBRAIN_HOME: home, GBRAIN_PROJECTION_READINESS_CACHE: '0' };+const QUERY = 'acme-example renewal';+/** The documented window: a shown coverage state stays shown for 30 minutes. */+const WINDOW_MS = 30 * 60 * 1000;++async function page(slug: string, type: string, title: string, text: string, sourceId = 'default') {+ await engine.putPage(slug, { type, title, compiled_truth: text, frontmatter: {} } as never, { sourceId } as never);+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: text, chunk_source: 'compiled_truth' }], { sourceId });+}++const pending = (slug: string, sourceId = 'default') =>+ engine.executeRaw('UPDATE pages SET text_projection_revision = NULL WHERE slug = $1 AND source_id = $2', [slug, sourceId]);++/** A large page (over the inline limit) whose embedding budget is held: no vectors. */+async function embeddingHeldPage(sourceId: string, slug: string, type: string, title: string) {+ await page(slug, type, title, 'a long recording transcript', sourceId);+ await engine.executeRaw(`UPDATE pages SET compiled_truth = repeat('x', 1100000) WHERE slug = $1 AND source_id = $2`, [slug, sourceId]);+ await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE slug = $1 AND source_id = $2', [slug, sourceId]);+ await engine.executeRaw(`INSERT INTO page_embedding_budget(page_id, state, reason) SELECT id, 'held', 'upgrade_backfill' FROM pages WHERE slug = $1 AND source_id = $2`, [slug, sourceId]);+}++async function hold(sourceId: string, path: string) {+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id = $1', [sourceId]);+ await engine.transaction(tx => writeGitHold(tx, {+ source_id: sourceId, incarnation, path, source_path: path, slug: null, page_id: null, code: 'invalid_frontmatter',+ message: 'synthetic hold', upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'legacy',+ meta: { recovery_version: 1 },+ } as never));+}++interface Call { ctx: OperationContext; notices: Notice[]; meta: Record<string, any> }+function call(sourceId: string): Call {+ const notices: Notice[] = [], meta: Record<string, any> = {};+ const ctx = {+ engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId,+ emitNotice: (notice: Notice) => { notices.push(notice); },+ emitResponseMeta: (key: string, value: unknown) => { meta[key] = value; },+ } as unknown as OperationContext;+ return { ctx, notices, meta };+}++/** Runs `fn` once per backend (PGLite, and Postgres when DATABASE_URL is set) with `engine` bound. */+const eachEngine = (fn: () => Promise<void>) => () => withEnv(env, async () => {+ for (const each of engines) { engine = each; await fn(); }+});++beforeAll(async () => {+ const backends = testBackends();+ if (backends.includes('pglite')) {+ const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engines.push(pglite);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const each of engines) {+ engine = each;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES ('held-a','held-a','{}'), ('embed-a','embed-a','{}') ON CONFLICT DO NOTHING");+ for (const sourceId of ['default', 'held-a', 'embed-a']) {+ await page('companies/acme-example', 'company', 'Acme-example', 'acme-example renewal pricing and the contract terms', sourceId);+ await page('notes/acme-example-call', 'note', 'Acme-example call', 'acme-example renewal call notes from the review', sourceId);+ }+ await page('media/scan-0001', 'image', 'Scan 0001', 'a receipt scan from the archive');+ await pending('media/scan-0001');+ }+}, 120_000);++afterAll(async () => {+ for (const each of engines) if (each.kind === 'pglite') await each.disconnect();+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+}, 60_000);++describe('projection_pending is scoped to the query', () => {+ test('a pending page that cannot match keeps the structured stage and counts but no human-facing line', eachEngine(async () => {+ const c = call('default');+ const results = await search.handler(c.ctx, { query: QUERY }) as Array<{ slug: string }>;+ expect(results.length).toBeGreaterThan(0);+ const retrieval = c.meta.retrieval;+ expect(retrieval.projection_readiness.status).toBe('projection_pending');+ expect(retrieval.degraded).toContainEqual({ stage: 'projection_pending' });+ expect(retrieval.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 0 } });+ expect(String(retrieval.hint ?? '')).not.toContain('projections are pending');+ captureRetrievalMeta('retrieval', retrieval);+ try { expect(formatResult('search', results, {})).not.toContain('Retrieval incomplete'); } finally { resetRetrievalMetaForTests(); }+ }));++ test('a pending page whose type or title matches keeps the stage and says how many could match', eachEngine(async () => {+ await page('notes/acme-example-plan', 'note', 'Acme-example renewal plan', 'acme-example renewal plan draft');+ await pending('notes/acme-example-plan');+ try {+ const c = call('default');+ await search.handler(c.ctx, { query: QUERY });+ expect(c.meta.retrieval.coverage).toEqual({ pending_projection: 2, could_affect: { pending_projection: 1 } });+ expect(c.meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });+ } finally {+ await engine.executeRaw("UPDATE pages SET deleted_at = now() WHERE slug = 'notes/acme-example-plan'");+ }+ }));++ test('an empty result counts every pending page: it cannot be ruled out', eachEngine(async () => {+ const c = call('default');+ expect(await search.handler(c.ctx, { query: 'zzqv-absent-term' })).toEqual([]);+ expect(c.meta.retrieval.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 1 } });+ expect(c.meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });+ }));++ test('the query --types scope counts pending pages of those types', eachEngine(async () => {+ const c = call('default');+ await search.handler(c.ctx, { query: QUERY, types: ['image', 'company'] });+ expect(c.meta.retrieval.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 1 } });+ }));+});++describe('held_files is scoped to the query', () => {+ test('a held file that cannot match emits no notice; held_files and coverage still carry it', eachEngine(async () => {+ await hold('held-a', 'notes/unrelated-scan.md');+ const c = call('held-a');+ const results = await search.handler(c.ctx, { query: QUERY }) as unknown[];+ expect(results.length).toBeGreaterThan(0);+ expect(c.meta.retrieval.held_files).toEqual([{ source_id: 'held-a', missing: 1, stale: 0 }]);+ expect(c.meta.retrieval.coverage).toEqual({ held_files: 1, could_affect: { held_files: 0 } });+ expect(c.notices.find(n => n.code === 'held_files')).toBeUndefined();+ }));++ test('a held file whose path matches the query emits the notice with how many could match', eachEngine(async () => {+ await hold('held-a', 'notes/acme-example-renewal-draft.md');+ const c = call('held-a');+ await search.handler(c.ctx, { query: QUERY });+ expect(c.meta.retrieval.coverage).toEqual({ held_files: 2, could_affect: { held_files: 1 } });+ const notice = c.notices.find(n => n.code === 'held_files')!;+ expect(notice.kind).toBe('degraded');+ expect(notice.why).toContain('Coverage is partial: sync holds 2 file(s)');+ expect(notice.why).toContain('1 of them could match this query');+ }));+});++describe('pages held from embedding are named in coverage and the held_files line', () => {+ test('an embedding-held page that cannot match is counted in coverage with no notice', eachEngine(async () => {+ await embeddingHeldPage('embed-a', 'media/recording-0001', 'transcript', 'Recording 0001');+ const c = call('embed-a');+ expect((await search.handler(c.ctx, { query: QUERY }) as unknown[]).length).toBeGreaterThan(0);+ expect(c.meta.retrieval.coverage).toEqual({ embedding_held: 1, could_affect: { embedding_held: 0 } });+ expect(c.notices.find(n => n.code === 'held_files')).toBeUndefined();+ }));++ test('an embedding-held page that could match puts it in the held_files line with the read-only preview', eachEngine(async () => {+ await embeddingHeldPage('embed-a', 'notes/acme-example-renewal-recording', 'note', 'Acme-example renewal recording');+ const c = call('embed-a');+ await search.handler(c.ctx, { query: QUERY });+ expect(c.meta.retrieval.coverage).toEqual({ embedding_held: 2, could_affect: { embedding_held: 1 } });+ const notice = c.notices.find(n => n.code === 'held_files')!;+ expect(notice.why).toContain('2 page(s) in this scope are held from embedding');+ expect(notice.why).toContain('1 of them could match this query');+ expect(notice.fix).toMatchObject({ argv: ['gbrain', 'embed', '--held', '--dry-run'], actor: 'agent' });+ }));+});++describe('repeat suppression and worsening (session ledger)', () => {+ const notice = (level: number, key = 'source-a'): Notice =>+ ({ code: 'held_files', kind: 'degraded', why: 'synthetic', escalation: { key, level } }) as Notice;++ test('a repeat within the window is suppressed; a material rise, a new key or the window end prints again', () => {+ let now = 1_000;+ const ledger = new NoticeLedger(() => now);+ const stdio = { transport: 'stdio' as const };+ expect(ledger.admit([notice(100)], stdio)).toHaveLength(1);+ expect(ledger.admit([notice(100)], stdio)).toHaveLength(0);+ expect(ledger.admit([notice(105)], stdio)).toHaveLength(0);+ expect(ledger.admit([notice(110)], stdio)).toHaveLength(1);+ expect(ledger.admit([notice(3, 'source-b')], stdio)).toHaveLength(1);+ expect(ledger.admit([notice(110)], stdio)).toHaveLength(0);+ now += WINDOW_MS;+ expect(ledger.admit([notice(110)], stdio)).toHaveLength(1);+ });++ test('a drop then a rise from the lower level prints: worsening is measured from the lowest level since it showed', () => {+ const ledger = new NoticeLedger(() => 0);+ const stdio = { transport: 'stdio' as const };+ expect(ledger.admit([notice(100)], stdio)).toHaveLength(1);+ expect(ledger.admit([notice(20)], stdio)).toHaveLength(0);+ expect(ledger.admit([notice(22)], stdio)).toHaveLength(1);+ });++ test('a notice without escalation is unchanged: per-call held_files rides every call', () => {+ const ledger = new NoticeLedger(() => 0);+ const plain: Notice = { code: 'held_files', kind: 'degraded', why: 'synthetic' };+ expect(ledger.admit([plain], { transport: 'stdio' })).toHaveLength(1);+ expect(ledger.admit([plain], { transport: 'stdio' })).toHaveLength(1);+ });++ test('HTTP dedupes per transport-resolved session only; without one every call shows', () => {+ const ledger = new NoticeLedger(() => 0);+ const bare = { transport: 'http' as const, principal: 'client-a' };+ expect(ledger.admit([notice(5)], bare)).toHaveLength(1);+ expect(ledger.admit([notice(5)], bare)).toHaveLength(1);+ const session = { ...bare, sessionId: 'session-1' };+ expect(ledger.admit([notice(5)], session)).toHaveLength(1);+ expect(ledger.admit([notice(5)], session)).toHaveLength(0);+ expect(ledger.admit([notice(5)], { ...bare, sessionId: 'session-2' })).toHaveLength(1);+ });+});++describe('MCP dispatch: one stdio session', () => {+ const blocks = (r: { content: Array<{ text?: string }> }) => r.content.map(c => c.text ?? '').join('\n');++ test('the held_files notice shows once per session while _meta.retrieval.coverage rides every call', eachEngine(async () => {+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'held-a', noticeLedger: new NoticeLedger() };+ const first = await dispatchToolCall(engine, 'search', { query: QUERY }, opts) as any;+ const second = await dispatchToolCall(engine, 'search', { query: QUERY }, opts) as any;+ expect(blocks(first)).toContain('[gbrain notice held_files');+ expect(blocks(first)).toContain('1 of them could match this query');+ expect(blocks(second)).not.toContain('[gbrain notice held_files');+ for (const r of [first, second]) expect(r._meta.retrieval.coverage).toEqual({ held_files: 2, could_affect: { held_files: 1 } });+ await hold('held-a', 'notes/acme-example-renewal-v2.md');+ const worse = await dispatchToolCall(engine, 'search', { query: QUERY }, opts) as any;+ expect(blocks(worse)).toContain('[gbrain notice held_files');+ expect(worse._meta.retrieval.coverage).toEqual({ held_files: 3, could_affect: { held_files: 2 } });+ }));++ test('a pending page that cannot match adds no degraded_recall notice', eachEngine(async () => {+ const r = await dispatchToolCall(engine, 'search', { query: QUERY }, { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger: new NoticeLedger() }) as any;+ expect(r._meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });+ expect(r._meta.retrieval.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 0 } });+ expect(blocks(r)).not.toContain('[gbrain notice degraded_recall');+ }));++ test('a projection_pending degraded_recall names the count and shows once per session', eachEngine(async () => {+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger: new NoticeLedger() };+ const first = await dispatchToolCall(engine, 'search', { query: 'zzqv-absent-term' }, opts) as any;+ const second = await dispatchToolCall(engine, 'search', { query: 'zzqv-absent-term' }, opts) as any;+ expect(blocks(first)).toContain('[gbrain notice degraded_recall');+ expect(blocks(first)).toContain('recently written pages are not in the search index yet (1 of 1 pending page(s) could match this query)');+ expect(blocks(second)).not.toContain('[gbrain notice degraded_recall');+ expect(second._meta.retrieval.degraded).toContainEqual({ stage: 'projection_pending' });+ expect(second._meta.retrieval.coverage).toEqual({ pending_projection: 1, could_affect: { pending_projection: 1 } });+ }));+});++describe('CLI: one-shot calls share a GBRAIN_HOME window', () => {+ const cliHome = () => mkdtempSync(join(tmpdir(), 'gbrain-coverage-cli-'));+ const meta = (total: number, could: number) => ({ degraded: [{ stage: 'projection_pending' }], coverage: { pending_projection: total, could_affect: { pending_projection: could } } });+ const row = [{ slug: 'notes/synthetic', score: 1, chunk_text: 'Synthetic note' }];++ test('the Retrieval incomplete line names the count, is suppressed on repeat and prints again when it worsens', () => withEnv({ GBRAIN_HOME: cliHome() }, async () => {+ try {+ captureRetrievalMeta('retrieval', meta(5, 2));+ expect(formatResult('query', row, {})).toContain('Retrieval incomplete: projection_pending. 2 of 5 pending page(s) could match this query.');+ captureRetrievalMeta('retrieval', meta(5, 2));+ expect(formatResult('query', row, {})).not.toContain('Retrieval incomplete');+ captureRetrievalMeta('retrieval', meta(9, 2));+ expect(formatResult('query', row, {})).toContain('Retrieval incomplete: projection_pending. 2 of 9 pending page(s) could match this query.');+ } finally { resetRetrievalMetaForTests(); }+ }));++ test('--json keeps the bare array and writes the scoped line to stderr once', () => withEnv({ GBRAIN_HOME: cliHome() }, async () => {+ const write = spyOn(process.stderr, 'write').mockReturnValue(true);+ try {+ captureRetrievalMeta('retrieval', meta(4, 4));+ expect(JSON.parse(formatResult('search', [], { json: true }))).toEqual([]);+ captureRetrievalMeta('retrieval', meta(4, 4));+ formatResult('search', [], { json: true });+ const lines = write.mock.calls.map(c => String(c[0])).filter(s => s.startsWith('Retrieval incomplete'));+ expect(lines).toEqual(['Retrieval incomplete: projection_pending. 4 of 4 pending page(s) could match this query.\n']);+ } finally { write.mockRestore(); resetRetrievalMetaForTests(); }+ }));++ test('an escalating op notice is suppressed in the next CLI process and shown again when it worsens', () => withEnv({ GBRAIN_HOME: cliHome() }, async () => {+ const held = (level: number): Notice => ({ code: 'held_files', kind: 'degraded', why: 'Coverage is partial: sync holds ' + level + ' file(s)', escalation: { key: 'source-a', level } } as Notice);+ const run = (level: number) => {+ __resetProcessNoticeLedgerForTests();+ captureOpNotice(held(level));+ return applyCliOpNotices([], false).stderr ?? '';+ };+ expect(run(3)).toContain('held_files');+ expect(run(3)).toBe('');+ expect(run(4)).toContain('held_files');+ }));+});