Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(search): search_exact, the exhaustive literal scan (gbrain search --exact) (#7191)

garrytanb0c6db403e18
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index b9a36e6b12..8e6ad1a2ae 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 157 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 158 tools across 25 areas. **Starter** marks membership in the ~40-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -230,6 +230,7 @@ Every non-localOnly operation on the MCP surface: 157 tools across 25 areas. **S
| `rate_answer` | Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). | write | | |
| `search` | Cheap hybrid search, no LLM expansion, top 20: exact tokens, names, field values. | read | yes | |
| `search_by_image` | Image-as-query retrieval. | read | | |
+| `search_exact` | Find every page containing a literal phrase or identifier, exhaustively: use instead of grep. | read | | |
| `search_modes` | Read-only search-mode dashboard: active mode, EVERY mode-bundle knob resolved with attribution (mode default vs config override), the three frozen bundles, and a reranker_readiness verdict (whether the resolved reranker will actually run; remote callers get the verdict without the host key inventory). | read | | |
| `search_stats` | Search observability over a window: cache hit rate, intent/mode mix, budget drops, rank-1 score drift, graph-signals failure counts. | admin | | |
| `search_tune` | Read-only tuning recommendations derived from the last 7 days of search telemetry: what should change, why, and the paste-ready config command per recommendation — relay them to the user. | admin | | |
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 8827bb0f37..78647e08d4 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -29,6 +29,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/engine-sql/facts.ts` `listFactsKeyset` + `src/core/engine-sql/pages.ts` keyset predicates — delta's two keyset reads. Both bind the cursor timestamp as `${value}::text::timestamptz`: a bare `::timestamptz` param is typed by the postgres.js driver, which serializes a string through a JS Date and truncates it to milliseconds (on Postgres that re-selected the whole last millisecond every wake and never drained a >limit cluster inside one millisecond). `listFactsKeyset` reads ascending `(created_at, id)` strictly after the keyset (`id: null` = strictly after the timestamp) and projects `created_at_iso` at column precision; recall's newest-first `listFactsSince` is unchanged. `test/engine-sql-facts-keyset.test.ts`, `test/delta-cursor-integrity.test.ts` (both engines).
- `src/core/engine-sql/keyword-pages.ts` + `src/core/search/keyword-statement.ts` — the strict keyword count (`BrainEngine.countKeywordPages`) and the keyword-mode page query (`BrainEngine.searchKeywordPages`) for both engines. `buildKeywordMatch` is the ONE WHERE builder both statements read: `searchKeyword`'s strict match (websearch FTS on `content_chunks.search_vector`, or the CJK LIKE/ILIKE terms), never its OR retry, with the same page filters, hard excludes and `buildVisibilityClause` (private pages, safe chunks, so no private fence text). The match returns its WHERE params first and the score-only rank params after them (`whereParamCount`), so the count binds only what its WHERE reads (a CJK count bound the term-frequency params and failed on both engines; `test/sql-bind-placeholders.test.ts`). The count is `count(*)` over `SELECT DISTINCT page_id … LIMIT 10001`; a non-timeout count failure logs its SQLSTATE once per process (`keyword-paging.ts`); the page query takes each page's best chunk before paging (no global chunk cap) and orders by `(score DESC, page_id ASC)` with float8 scores so the keyset cursor round-trips. Postgres runs both inside `withScopedReadTransaction` with a statement timeout (the count's set from the caller's deadline); PGLite has none.
+- `src/core/search/exact-scan.ts` + `src/core/ops/search-exact.ts` + `src/cli/search-exact-format.ts` — #7191: `search_exact` (CLI `gbrain search --exact`, routed in `cli/main.ts` before ranked-search flags parse): an unranked literal scan of `content_chunks.chunk_text` (words in order, any whitespace between, case-insensitive unless `case_sensitive`; the ARE comes from `phrasePattern`, with a LIKE prefilter on the longest word) in keyset batches of pages by id (`buildExactBatchStatement`), under ranked search's visibility (live page, unarchived source, quarantine, pinned questions, `chunkVisibleFilter`, source scope, private pages and the trust floor for untrusted callers, `safeChunksFilter` for remote) and the hard-excluded prefixes. `complete` is true only when the scope was scanned to the end with no `limit` or `deadline` stop and no unreadable page (`unchunked`, `projection_pending`, remote `unsealed`, `scan_timeout`); a Postgres statement timeout halves the batch, down to one page. `resume_after` continues a bounded scan. Registered `filtered` (`min_trust`, `stampPageTrust`), output redaction `retrieval`. Guide: [exact search](../../guides/exact-search.md). Tests: `test/search-exact.test.ts`, `test/e2e/search-exact-postgres.test.ts`.
- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.
diff --git a/docs/guides/exact-search.md b/docs/guides/exact-search.md
new file mode 100644
index 0000000000..a663e26875
--- /dev/null
+++ b/docs/guides/exact-search.md
@@ -0,0 +1,73 @@
+# Exact search
+
+`gbrain search --exact "<phrase>"` (MCP tool `search_exact`) finds every page
+that contains a literal phrase or identifier. Use it where you would otherwise
+run `grep` over the brain's files. Ranked search returns the best few pages and
+can miss a rare phrase; exact search is unranked and exhaustive, and it tells you
+whether the scan covered everything.
+
+```bash
+gbrain search --exact "INV-2024-0042"
+gbrain search --exact "quarterly board pack" --slug-prefix meetings/ --json
+gbrain search --exact "Acme Example" --case-sensitive --types company,person
+```
+
+## What matches
+
+The phrase's words, in order, with any run of whitespace between them: a phrase
+that wraps onto the next line still matches. It is a substring match, so
+`board pack` also matches `board packs`. Matching is case-insensitive unless
+you pass `--case-sensitive` (`case_sensitive: true`). Nothing else is
+normalized: there is no stemming, and punctuation, accents and quote styles are
+literal. Ranked `search` is different: there, quotes mean a stemmed phrase.
+
+The scan reads the text index (`content_chunks`), every chunk of every page in
+your scope, including keyword-only pages and pages held from embedding, as long
+as they are chunked. An image page's indexed text is its OCR text. Neighboring
+chunks overlap by roughly 25 to 50 words (none after a chunk shorter than
+that), so a phrase that crosses a chunk boundary is still found unless it is
+longer than the overlap or begins in a very short paragraph. Credential values
+are masked in the index, so a secret never matches.
+
+## The result
+
+- `matches`: every matching page in page order, each with `matching_chunks`,
+ up to three snippets, and its trust label (`trust_tier`, `origin`).
+- `complete`: `true` only when every page in your scope was scanned and none of
+ them had text the scan could not read. `complete: true` with no matches means
+ the phrase is not in any page you can read.
+- `incomplete_reasons` when `complete` is `false`:
+ - `limit`: more pages matched than `--limit` (default 100, max 1000).
+ - `deadline`: the scan ran out of time (`--max-seconds`, default 30, max 120).
+ - `unreadable_pages`: some pages in scope have text the index can't serve
+ yet. They are counted under `unreadable.by_reason` and the first 20 are
+ listed under `unreadable.sample`:
+ - `unchunked`: the page has body text but no chunks (for example a page
+ held from chunking). `gbrain embed --stale` chunks it.
+ - `projection_pending`: the page's text index is behind its latest edit.
+ - `unsealed` (remote callers only): the page was indexed before the
+ safe-chunk fence, so it is withheld from remote reads until
+ `gbrain repair safe-chunks` reseals it.
+ - `scan_timeout`: one page alone did not finish within the statement
+ deadline.
+- `resume_after`: after `limit` or `deadline`, pass it back as `--after`
+ (`after`) to continue from where the scan stopped. The CLI prints the exact
+ command.
+
+`excluded_slug_prefixes` lists the prefixes ranked search also hides
+(`test/`, `attachments/`, `.raw/`, plus `GBRAIN_SEARCH_EXCLUDE`). Pages under
+them are out of scope and do not make the scan incomplete.
+
+## Scope and privacy
+
+`--source` / `source_id`, `--types` and `--slug-prefix` narrow the scope.
+A remote (MCP) caller gets the same visibility as ranked search: only sources in
+its grant, no private pages, no quarantined pages, pages at or above its trust
+floor, and safe chunks only, so fenced facts and takes never match. Pages a
+caller cannot read are never counted or listed.
+
+## How it runs
+
+The scan walks pages in id order in batches of up to 2,000, one statement per
+batch. On Postgres a batch that hits the statement deadline is retried at half
+the size; a single page that still times out is reported as `scan_timeout`.
diff --git a/docs/guides/search-modes.md b/docs/guides/search-modes.md
index c370e2aaf1..a0cac789cb 100644
--- a/docs/guides/search-modes.md
+++ b/docs/guides/search-modes.md
@@ -12,6 +12,8 @@ Two decisions shape every gbrain lookup, and this guide covers both:
To see how a specific result was ranked, or why an expected page is missing,
see [Explaining search results](search-explain.md).
+To find every page containing a literal phrase or identifier (what you would
+otherwise grep for), use [exact search](exact-search.md): `gbrain search --exact`.
## The three mode bundles
diff --git a/plugin/README.md b/plugin/README.md
index 647dcb5e7f..8fcc37d8f7 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 178
+The plugin's MCP server runs `gbrain serve --surface full` — 179
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index b7eaa4b0c7..ceb02d65ce 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,7 +3,7 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli/main.ts 3020 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured)
+src/cli/main.ts 3025 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts); GBRA-151 operability wave x v0.60.332.0 merge: both sides added a line, re-summed (3020 measured); +5 #7191: search --exact routing (dispatch, cannot move) and the search_exact formatter case + import
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 692 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts; +4 #7142: DoctorReport.last_known_sections field and the buildChecks last-known/refresh scope params (logic in doctor/last-known.ts)
src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
@@ -19,7 +19,7 @@ src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in th
src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9
src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
-src/core/operations.ts 242 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)
+src/core/operations.ts 243 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line); +1 #7191: search-exact import
src/core/pglite-engine.ts 3085 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)
src/core/postgres-engine.ts 3107 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)
src/core/search/hybrid.ts 1562 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index c315df6c79..1e7f95f093 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -599,3 +599,4 @@ src/core/persistence/page-edit.ts applyPageEdits call:serializePageToMarkdown SE
src/core/persistence/page-edit.ts applyPageEdits field SEGW within's stored-offset mapping on the materialized snapshot, as pageSegments; a segmented page takes prepareSegmentedEditMutation first
src/core/persistence/page-edit.ts prepareSegmentedEditMutation call:serializePageToMarkdown NONE serializes the frontmatter head with an empty body; the body streams from the segments
src/core/persistence/page-edit.ts assertSegmentedFencesCompile field NONE the fields hold only the stored fence text laid out at its lines (scanCanonicalFences input); no page body is read
+src/core/search/exact-scan.ts buildExactBatchStatement sql META #7191: octet_length of the body columns (stored size, never the body) decides an unreadable page
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 2263431a43..aebb0e5e33 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -57,6 +57,7 @@ import { runCliPreflight } from '../core/cli-preflight.ts';
import { isBooleanLiteral, isKnownOpFlag } from '../core/op-flag-tokens.ts';
import { conceptNudge } from '../core/search/query-intent.ts';
import { redactRetrievalOutput } from '../core/search/output-redaction.ts';
+import { formatSearchExact } from './search-exact-format.ts';
import type { CliOptions } from '../core/cli-options.ts';
import { RemoteMcpError, extractResponseMeta } from '../core/remote-mcp-error.ts';
import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './source-scope.ts';
@@ -364,6 +365,9 @@ async function main() {
if (command === 'ask') {
command = 'query';
}
+ // #7191: `search --exact "<phrase>"` is the exhaustive literal scan, routed before any ranked-search flag is parsed.
+ const exactAt = command === 'search' ? subArgs.indexOf('--exact') : -1;
+ if (exactAt >= 0 && (subArgs.indexOf('--') < 0 || exactAt < subArgs.indexOf('--'))) { command = 'search-exact'; subArgs.splice(exactAt, 1); }
dispatchedCommand = command;
// Local patch 2026-06-11 — mark one-shot CLI processes so the facts
@@ -1643,6 +1647,7 @@ export function formatResult(
return pages.map((p) => formatVolunteeredPage(p)).join('\n') + '\n';
}
case 'get_page': return formatGetPage(result as Record<string, any>);
+ case 'search_exact': return formatSearchExact(result as Parameters<typeof formatSearchExact>[0]);
case 'list_pages': {
const pages = result as any[];
if (pages.length === 0) return 'No pages found.\n';
diff --git a/src/cli/search-exact-format.ts b/src/cli/search-exact-format.ts
new file mode 100644
index 0000000000..825370a207
--- /dev/null
+++ b/src/cli/search-exact-format.ts
@@ -0,0 +1,33 @@
+/** Human rendering of `search_exact` (`gbrain search --exact`): one block per page, then the completeness line. */
+interface ExactOut {
+ phrase: string;
+ matches: Array<{ slug: string; source_id: string; title: string; matching_chunks: number; snippets: Array<{ text: string }> }>;
+ complete: boolean;
+ incomplete_reasons: string[];
+ resume_after: number | null;
+ pages_scanned: number;
+ unreadable: { total: number; by_reason: Record<string, number>; sample: Array<{ slug: string; source_id: string; reason: string }> };
+}
+
+const oneLine = (text: string) => text.replace(/\s+/g, ' ').trim();
+
+export function formatSearchExact(r: ExactOut): string {
+ const lines: string[] = [];
+ for (const m of r.matches) {
+ lines.push(m.source_id + ':' + m.slug + ' (' + m.matching_chunks + ' chunk' + (m.matching_chunks === 1 ? '' : 's') + ') ' + m.title);
+ for (const s of m.snippets) lines.push(' ' + oneLine(s.text ?? ''));
+ }
+ if (!r.matches.length) lines.push('No page contains "' + r.phrase + '".');
+ if (r.complete) {
+ lines.push('Complete: scanned all ' + r.pages_scanned + ' page(s) in scope.');
+ } else {
+ lines.push('INCOMPLETE (' + r.incomplete_reasons.join(', ') + '): scanned ' + r.pages_scanned + ' page(s).');
+ if (r.resume_after !== null) lines.push(' Continue: gbrain search --exact ' + JSON.stringify(r.phrase) + ' --after ' + r.resume_after);
+ if (r.unreadable.total) {
+ const reasons = Object.entries(r.unreadable.by_reason).map(([k, v]) => k + ' ' + v).join(', ');
+ lines.push(' ' + r.unreadable.total + ' page(s) have text the scan could not read (' + reasons + '):');
+ for (const g of r.unreadable.sample) lines.push(' ' + g.source_id + ':' + g.slug + ' (' + g.reason + ')');
+ }
+ }
+ return lines.join('\n') + '\n';
+}
diff --git a/src/core/eligibility/registry.ts b/src/core/eligibility/registry.ts
index 4c2430d5d7..d40c2b235b 100644
--- a/src/core/eligibility/registry.ts
+++ b/src/core/eligibility/registry.ts
@@ -26,7 +26,7 @@ export type ReadTrustHandling = 'filtered' | 'labeled' | 'text_free';
export const OP_READ_TRUST: Readonly<Record<string, ReadTrustHandling>> = {
// memory verbs and retrieval
recall: 'filtered', context_pack: 'filtered', delta: 'filtered',
- search: 'filtered', query: 'filtered', get_page: 'filtered', fetch: 'filtered',
+ search: 'filtered', search_exact: 'filtered', query: 'filtered', get_page: 'filtered', fetch: 'filtered',
get_chunks: 'filtered', get_timeline: 'filtered', takes_list: 'filtered', takes_search: 'filtered',
assemble_evidence: 'filtered',
entity: 'labeled', synthesize: 'labeled', think: 'labeled',
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index ef2ebfd745..d014418022 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -38,7 +38,7 @@ const OP_AREAS: Record<string, string> = {
put_raw_data: 'pages', get_raw_data: 'pages',
fetch: 'pages', // #4039 deep-research read adapter (search/fetch pair)
// search
- search: 'search', query: 'search', search_by_image: 'search', assemble_evidence: 'search',
+ search: 'search', search_exact: 'search', query: 'search', search_by_image: 'search', assemble_evidence: 'search',
// tags
add_tag: 'tags', remove_tag: 'tags', get_tags: 'tags',
// links + graph
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 84eadef04d..c22dccbf51 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -41,6 +41,7 @@ const load_raw_data = () => import('./ops/raw-data.ts') as Promise<Record<string
const load_request_tools = () => import('./ops/request-tools.ts') as Promise<Record<string, unknown>>;
const load_salience = () => import('./ops/salience.ts') as Promise<Record<string, unknown>>;
const load_schema_packs = () => import('./ops/schema-packs.ts') as Promise<Record<string, unknown>>;
+const load_search_exact = () => import('./ops/search-exact.ts') as Promise<Record<string, unknown>>;
const load_search = () => import('./ops/search.ts') as Promise<Record<string, unknown>>;
const load_skillopt = () => import('./ops/skillopt.ts') as Promise<Record<string, unknown>>;
const load_skills_catalog = () => import('./ops/skills-catalog.ts') as Promise<Record<string, unknown>>;
@@ -86,6 +87,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"search_modes": [load_search, "searchOperations"],
"search_tune": [load_search, "searchOperations"],
"cache_stats": [load_search, "searchOperations"],
+ "search_exact": [load_search_exact, "searchExactOperations"],
"rate_answer": [load_feedback, "feedbackOperations"],
"search_by_image": [load_image, "imageOperations"],
"add_tag": [load_tags, "tagsOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index e60aa7961c..588dd4ea4a 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -1633,6 +1633,72 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"scope": "admin",
"area": "search"
},
+ {
+ "name": "search_exact",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "scope": "read",
+ "description": "Find every page containing a literal phrase or identifier, exhaustively: use instead of grep. Unranked; returns every match in page order with snippets, and complete: true only when every page you can read was scanned. Literal: words in order with any whitespace between them, case-insensitive unless case_sensitive; no stemming, punctuation literal (ranked search treats quotes as a stemmed phrase). When complete is false, incomplete_reasons says why: deadline or limit (call again with after: resume_after), or unreadable_pages (pages whose text is not indexed yet, listed under unreadable).",
+ "params": {
+ "phrase": {
+ "type": "string",
+ "required": true,
+ "description": "The literal text, e.g. 'INV-2024-0042' or 'quarterly board pack'."
+ },
+ "case_sensitive": {
+ "type": "boolean",
+ "description": "Match case exactly (default false)."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Only this source; '__all__' spans every source you can read."
+ },
+ "types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Only these page types, e.g. ['meeting']."
+ },
+ "slug_prefix": {
+ "type": "string",
+ "description": "Only slugs starting with this, e.g. 'meetings/'."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Matching pages to return (default 100, max 1000)."
+ },
+ "after": {
+ "type": "number",
+ "description": "Resume a bounded scan: the resume_after of the previous call."
+ },
+ "max_seconds": {
+ "type": "number",
+ "description": "Scan budget in seconds (default 30, max 120)."
+ },
+ "min_trust": {
+ "type": "string",
+ "enum": [
+ "user_confirmed",
+ "operator_curated",
+ "tool_observed",
+ "agent_written",
+ "unknown",
+ "external_untrusted"
+ ],
+ "description": "Lowest trust tier to return (the connection floor still applies).",
+ "fullSurfaceOnly": true
+ }
+ },
+ "cliHints": {
+ "name": "search-exact",
+ "positional": [
+ "phrase"
+ ]
+ },
+ "area": "search"
+ },
{
"name": "rate_answer",
"area": "search",
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 4d1449b83f..9996fdacce 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -58,6 +58,7 @@ export {
import { pagesOperations } from './ops/pages.ts';
import { persistenceOperations } from './ops/persistence.ts';
import { searchOperations } from './ops/search.ts';
+import { searchExactOperations } from './ops/search-exact.ts';
import { takesOperations } from './ops/takes.ts';
import { tagsOperations } from './ops/tags.ts';
import { linksOperations } from './ops/links.ts';
@@ -145,8 +146,8 @@ export const operations: Operation[] = [
// destructive-guard ops restore_page, purge_deleted_pages) — ops/pages.ts
...pagesOperations, ...pageEditOperations, ...pageAppendOperations, ...pageBatchOperations, ...pageUploadOperations,
...persistenceOperations,
- // Search (search, query) — ops/search.ts
- ...searchOperations,
+ // Search (search, query) — ops/search.ts; search_exact — ops/search-exact.ts
+ ...searchOperations, ...searchExactOperations,
...feedbackOperations,
// v0.36 Phase 2: image-as-query (search_by_image) — ops/image.ts
...imageOperations,
diff --git a/src/core/ops/search-exact.ts b/src/core/ops/search-exact.ts
new file mode 100644
index 0000000000..bbdca18401
--- /dev/null
+++ b/src/core/ops/search-exact.ts
@@ -0,0 +1,109 @@
+/**
+ * #7191 ask 2: the `search_exact` op (CLI `gbrain search --exact "<phrase>"`).
+ * The scan, its visibility predicate and its completeness contract live in
+ * src/core/search/exact-scan.ts; this file validates params and resolves the
+ * caller's scope the way `search` does.
+ */
+import type { Operation, OperationContext } from './contract.ts';
+import { invalidParam } from './op-fix.ts';
+import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam } from './context.ts';
+import { MIN_TRUST_PARAM, resolveReadEligibility } from '../eligibility/policy.ts';
+import {
+ EXACT_DEFAULT_LIMIT, EXACT_DEFAULT_SECONDS, EXACT_MAX_LIMIT, EXACT_MAX_PHRASE_CHARS, EXACT_MAX_SECONDS, runExactScan,
+} from '../search/exact-scan.ts';
+
+const TYPE_NAME = /^[A-Za-z0-9_.:/-]+$/;
+
+function parseParams(ctx: OperationContext, p: Record<string, unknown>) {
+ const bad = (param: string, message: string, example: unknown) =>
+ invalidParam(ctx, 'search_exact', param, 'search_exact: ' + message, { def: search_exact.params[param], example });
+ const phrase = typeof p.phrase === 'string' ? p.phrase.trim() : '';
+ if (!phrase) throw bad('phrase', 'phrase must be the literal text to find', 'invoice INV-2024-0042');
+ if (phrase.length > EXACT_MAX_PHRASE_CHARS) throw bad('phrase', 'phrase must be at most ' + EXACT_MAX_PHRASE_CHARS + ' characters', 'invoice INV-2024-0042');
+ if (p.case_sensitive !== undefined && typeof p.case_sensitive !== 'boolean') throw bad('case_sensitive', 'case_sensitive must be true or false', true);
+ const limit = p.limit ?? EXACT_DEFAULT_LIMIT;
+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > EXACT_MAX_LIMIT) {
+ throw bad('limit', 'limit must be an integer from 1 to ' + EXACT_MAX_LIMIT, EXACT_DEFAULT_LIMIT);
+ }
+ const after = p.after;
+ if (after !== undefined && (typeof after !== 'number' || !Number.isInteger(after) || after < 0)) throw bad('after', 'after must be the resume_after value of an earlier call', 1200);
+ const seconds = p.max_seconds ?? EXACT_DEFAULT_SECONDS;
+ if (typeof seconds !== 'number' || !(seconds > 0) || seconds > EXACT_MAX_SECONDS) {
+ throw bad('max_seconds', 'max_seconds must be a number above 0 and at most ' + EXACT_MAX_SECONDS, EXACT_DEFAULT_SECONDS);
+ }
+ let types: string[] | undefined;
+ if (p.types !== undefined) {
+ const ok = Array.isArray(p.types) && p.types.length >= 1 && p.types.length <= 50 && p.types.every(t => typeof t === 'string' && TYPE_NAME.test(t));
+ if (!ok) throw bad('types', 'types must be a list of page type names', ['meeting']);
+ types = [...new Set(p.types as string[])];
+ }
+ const slugPrefix = p.slug_prefix;
+ if (slugPrefix !== undefined && (typeof slugPrefix !== 'string' || slugPrefix.trim() === '')) throw bad('slug_prefix', 'slug_prefix must be a slug prefix', 'meetings/');
+ return { phrase, caseSensitive: p.case_sensitive === true, limit, after: after as number | undefined, seconds, types, slugPrefix: slugPrefix as string | undefined };
+}
+
+const search_exact: Operation = {
+ name: 'search_exact',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: 'retrieval',
+ scope: 'read',
+ description: 'Find every page containing a literal phrase or identifier, exhaustively: use instead of grep. Unranked; returns every match in page order with snippets, '
+ + 'and complete: true only when every page you can read was scanned. Literal: words in order with any whitespace between them, case-insensitive unless case_sensitive; '
+ + 'no stemming, punctuation literal (ranked search treats quotes as a stemmed phrase). When complete is false, incomplete_reasons says why: deadline or limit '
+ + '(call again with after: resume_after), or unreadable_pages (pages whose text is not indexed yet, listed under unreadable).',
+ params: {
+ phrase: { type: 'string', required: true, description: "The literal text, e.g. 'INV-2024-0042' or 'quarterly board pack'." },
+ case_sensitive: { type: 'boolean', description: 'Match case exactly (default false).' },
+ source_id: { type: 'string', description: "Only this source; '__all__' spans every source you can read." },
+ types: { type: 'array', items: { type: 'string' }, description: "Only these page types, e.g. ['meeting']." },
+ slug_prefix: { type: 'string', description: "Only slugs starting with this, e.g. 'meetings/'." },
+ limit: { type: 'number', description: 'Matching pages to return (default ' + EXACT_DEFAULT_LIMIT + ', max ' + EXACT_MAX_LIMIT + ').' },
+ after: { type: 'number', description: 'Resume a bounded scan: the resume_after of the previous call.' },
+ max_seconds: { type: 'number', description: 'Scan budget in seconds (default ' + EXACT_DEFAULT_SECONDS + ', max ' + EXACT_MAX_SECONDS + ').' },
+ min_trust: MIN_TRUST_PARAM,
+ },
+ handler: async (ctx, p) => {
+ const params = parseParams(ctx, p);
+ const startedAt = Date.now();
+ const sourceIdParam = parseSourceIdParam(p.source_id, 'search_exact', { allowAll: true });
+ const scope = federatedSearchScope(ctx, sourceIdParam);
+ const { floor } = await resolveReadEligibility(ctx, { minTrust: p.min_trust });
+ await assertExplicitSourceLive(ctx, sourceIdParam);
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
+ const { resolveHardExcludes } = await import('../search/source-boost.ts');
+ const excludeSlugPrefixes = resolveHardExcludes();
+ const result = await runExactScan(ctx.engine, {
+ phrase: params.phrase,
+ caseSensitive: params.caseSensitive,
+ ...scope,
+ ...(params.types ? { types: params.types } : {}),
+ ...(params.slugPrefix ? { slugPrefix: params.slugPrefix } : {}),
+ excludeSlugPrefixes,
+ excludePrivate,
+ remote: ctx.remote !== false,
+ ...(floor ? { minTrust: floor } : {}),
+ limit: params.limit,
+ ...(params.after !== undefined ? { afterPageId: params.after } : {}),
+ deadlineMs: startedAt + params.seconds * 1000,
+ });
+ const { stampPageTrust } = await import('../eligibility/stamp.ts');
+ const matches = await stampPageTrust(ctx.engine, result.matches.map(m => ({ ...m, chunk_text: m.snippets.map(s => s.text).join('\n') })), floor);
+ return {
+ phrase: params.phrase,
+ case_sensitive: params.caseSensitive,
+ matches: matches.map(({ chunk_text: _text, ...m }) => m),
+ complete: result.complete,
+ incomplete_reasons: result.incomplete_reasons,
+ resume_after: result.resume_after,
+ pages_scanned: result.pages_scanned,
+ unreadable: result.unreadable,
+ excluded_slug_prefixes: excludeSlugPrefixes,
+ latency_ms: Date.now() - startedAt,
+ };
+ },
+ cliHints: { name: 'search-exact', positional: ['phrase'] },
+};
+
+export const searchExactOperations: Operation[] = [search_exact];
diff --git a/src/core/search/exact-scan.ts b/src/core/search/exact-scan.ts
new file mode 100644
index 0000000000..797c09a42a
--- /dev/null
+++ b/src/core/search/exact-scan.ts
@@ -0,0 +1,231 @@
+/**
+ * #7191 ask 2: `search_exact` (CLI `gbrain search --exact "<phrase>"`), the
+ * exhaustive literal scan agents otherwise run with grep. Unranked: every page
+ * with a visible text chunk containing the phrase, in page-id order, plus a
+ * `complete` flag that is true only when every page in the caller's scope was
+ * scanned and none of them had text the scan could not read.
+ *
+ * Match: the phrase's words in order with any run of whitespace between them
+ * (a line break included), case-insensitive unless `caseSensitive`. Nothing
+ * else is normalized: no stemming, punctuation and accents are literal.
+ *
+ * What it reads: `content_chunks.chunk_text` (an image page's chunk holds its OCR text) under the same
+ * visibility predicate as ranked search (live page, unarchived source, not
+ * quarantined, current text projection, live body generation, the caller's
+ * source scope, private pages and the trust floor for an untrusted caller, safe
+ * chunks for a remote caller), so a remote caller never matches fence text.
+ * Chunks overlap by a sentence-aware margin, so a phrase inside one sentence is
+ * always inside one chunk.
+ *
+ * What makes it incomplete: the deadline or the page limit (both resumable
+ * from `resume_after`), and pages in scope whose text the scan cannot read:
+ * a page with body text and no visible chunk (`unchunked`, e.g. a page
+ * held from chunking), a page whose text projection is behind its revision
+ * (`projection_pending`), and for a remote caller a page indexed before the
+ * safe-chunk fence (`unsealed`). Those are listed, never silently skipped.
+ *
+ * Scan shape: keyset batches of pages by id, each one statement, run with JIT
+ * off (the private-visibility subplans cost past `jit_above_cost`, and JIT
+ * compilation alone took about 1 s per batch on Postgres 16). A statement
+ * that times out is retried with half the batch; a single page that still
+ * times out is recorded as `scan_timeout` and passed.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { TrustTier } from '../trust/tier.ts';
+import { quarantineFilterFragment } from '../quarantine.ts';
+import { privatePagesFilterFragment } from './private-visibility.ts';
+import { pageEligibleSql } from '../eligibility/sql.ts';
+import { buildHardExcludeClause } from './sql-ranking.ts';
+import { escapeLikePattern } from './sql-ranking.ts';
+import { isStatementTimeoutError } from '../retry-matcher.ts';
+import { chunkVisibleFilter, currentTextProjectionFilter, safeChunksFilter, SAFE_FENCE_CHUNKER_VERSION } from './safe-chunks.ts';
+
+export const EXACT_DEFAULT_LIMIT = 100;
+export const EXACT_MAX_LIMIT = 1000;
+export const EXACT_DEFAULT_SECONDS = 30;
+export const EXACT_MAX_SECONDS = 120;
+export const EXACT_MAX_PHRASE_CHARS = 500;
+export const EXACT_SNIPPETS_PER_PAGE = 3;
+const SNIPPET_CONTEXT = 80;
+const BATCH_PAGES = 2000;
+const GAP_SAMPLE = 20;
+
+export type ExactGapReason = 'unchunked' | 'projection_pending' | 'unsealed' | 'scan_timeout';
+
+export interface ExactScanOpts {
+ phrase: string;
+ caseSensitive?: boolean;
+ sourceId?: string;
+ sourceIds?: string[];
+ types?: string[];
+ slugPrefix?: string;
+ excludeSlugPrefixes: string[];
+ excludePrivate: boolean;
+ remote: boolean;
+ minTrust?: TrustTier;
+ limit: number;
+ afterPageId?: number;
+ deadlineMs: number;
+ /** Test seam: pages per statement. */
+ batchPages?: number;
+}
+
+export interface ExactMatch {
+ page_id: number;
+ slug: string;
+ source_id: string;
+ title: string;
+ type: string;
+ matching_chunks: number;
+ snippets: Array<{ chunk_index: number; chunk_source: string; text: string }>;
+}
+
+export interface ExactScanResult {
+ matches: ExactMatch[];
+ complete: boolean;
+ incomplete_reasons: Array<'deadline' | 'limit' | 'unreadable_pages'>;
+ resume_after: number | null;
+ pages_scanned: number;
+ unreadable: { total: number; by_reason: Partial<Record<ExactGapReason, number>>; sample: Array<{ slug: string; source_id: string; reason: ExactGapReason }> };
+}
+
+/** The phrase as a POSIX ARE: each word escaped literally, words joined by one or more whitespace characters. */
+export function phrasePattern(phrase: string): { regex: string; longest: string } | null {
+ const words = phrase.trim().split(/\s+/).filter(Boolean);
+ if (words.length === 0) return null;
+ const regex = words.map(w => w.replace(/[\\^$.|?*+()[\]{}]/g, ch => '\\' + ch)).join('[[:space:]]+');
+ const longest = words.reduce((a, b) => (b.length > a.length ? b : a));
+ return { regex, longest };
+}
+
+interface BatchRow {
+ page_id: number;
+ slug: string | null;
+ source_id: string | null;
+ title: string | null;
+ type: string | null;
+ gap: ExactGapReason | null;
+ matching_chunks: number | null;
+ snippets: unknown;
+}
+
+/** One batch statement: every page of the next `batchPages` in scope after `after`, in id order, with its matches or the reason its text could not be read. */
+export function buildExactBatchStatement(opts: ExactScanOpts, after: number, batchPages: number): { sql: string; params: unknown[] } | null {
+ const pattern = phrasePattern(opts.phrase);
+ if (!pattern) return null;
+ const params: unknown[] = [];
+ const add = (v: unknown) => { params.push(v); return '$' + params.length; };
+ const afterP = add(after);
+ const limitP = add(batchPages);
+ const flags = opts.caseSensitive ? "''" : "'i'";
+ const re = add(pattern.regex);
+ const snippetRe = add('.{0,' + SNIPPET_CONTEXT + '}' + pattern.regex + '.{0,' + SNIPPET_CONTEXT + '}');
+ const like = add('%' + escapeLikePattern(pattern.longest) + '%');
+ const op = opts.caseSensitive ? '~' : '~*';
+ const likeOp = opts.caseSensitive ? 'LIKE' : 'ILIKE';
+ const pageFilters: string[] = [
+ 'p.id > ' + afterP + '::int',
+ 'p.deleted_at IS NULL',
+ 'NOT s.archived',
+ quarantineFilterFragment('p'),
+ "NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question')",
+ ];
+ if (opts.sourceIds?.length) pageFilters.push('p.source_id = ANY(' + add(opts.sourceIds) + '::text[])');
+ else if (opts.sourceId) pageFilters.push('p.source_id = ' + add(opts.sourceId));
+ if (opts.types?.length) pageFilters.push('p.type = ANY(' + add(opts.types) + '::text[])');
+ if (opts.slugPrefix) pageFilters.push('p.slug LIKE ' + add(escapeLikePattern(opts.slugPrefix) + '%') + " ESCAPE '\\'");
+ if (opts.excludePrivate) pageFilters.push(privatePagesFilterFragment('p'));
+ if (opts.minTrust) pageFilters.push(pageEligibleSql('p', { floor: opts.minTrust }));
+ const hardExclude = buildHardExcludeClause('p.slug', opts.excludeSlugPrefixes);
+ const safe = opts.remote ? ` AND ${safeChunksFilter('p')}` : '';
+ const unsealed = opts.remote ? `WHEN p.chunker_version < ${SAFE_FENCE_CHUNKER_VERSION} THEN 'unsealed'` : '';
+ // Sizes only (octet_length reads the stored length, never the body): does the page have text to index?
+ const hasBody = `(octet_length(p.compiled_truth) > 0 OR octet_length(p.timeline) > 0 OR (p.body_storage = 'segmented' AND p.body_bytes > 0))`;
+ const sql = `WITH batch AS MATERIALIZED (
+ SELECT p.id FROM pages p JOIN sources s ON s.id = p.source_id
+ WHERE ${pageFilters.join('\n AND ')} ${hardExclude}
+ ORDER BY p.id LIMIT ${limitP}::int
+), hits AS (
+ SELECT cc.page_id, cc.chunk_index, cc.chunk_source,
+ (regexp_match(cc.chunk_text, ${snippetRe}, ${flags}))[1] AS snippet,
+ row_number() OVER (PARTITION BY cc.page_id ORDER BY cc.chunk_index) AS rn
+ FROM batch b JOIN pages p ON p.id = b.id JOIN content_chunks cc ON cc.page_id = b.id
+ WHERE ${chunkVisibleFilter('p', 'cc')}${safe}
+ AND cc.chunk_text ${likeOp} ${like} ESCAPE '\\' AND cc.chunk_text ${op} ${re}
+), per_page AS (
+ SELECT h.page_id, count(*)::int AS matching_chunks,
+ json_agg(json_build_object('chunk_index', h.chunk_index, 'chunk_source', h.chunk_source, 'text', h.snippet) ORDER BY h.chunk_index)
+ FILTER (WHERE h.rn <= ${EXACT_SNIPPETS_PER_PAGE}) AS snippets
+ FROM hits h GROUP BY h.page_id
+)
+SELECT p.id AS page_id, p.slug, p.source_id, p.title, p.type, pp.matching_chunks, pp.snippets,
+ CASE WHEN pp.page_id IS NOT NULL THEN NULL ${unsealed}
+ WHEN NOT ${currentTextProjectionFilter('p')} THEN 'projection_pending'
+ WHEN NOT EXISTS (SELECT 1 FROM content_chunks vc WHERE vc.page_id = p.id AND ${chunkVisibleFilter('p', 'vc')}) AND ${hasBody} THEN 'unchunked'
+ ELSE NULL END AS gap
+ FROM batch b JOIN pages p ON p.id = b.id LEFT JOIN per_page pp ON pp.page_id = b.id
+ ORDER BY p.id`;
+ return { sql, params };
+}
+
+/** Runs the scan from `afterPageId` until the scope ends, the limit fills or the deadline passes. */
+export async function runExactScan(engine: Pick<BrainEngine, 'executeRaw'>, opts: ExactScanOpts): Promise<ExactScanResult> {
+ const matches: ExactMatch[] = [];
+ const gaps: Array<{ page_id: number; slug: string; source_id: string; reason: ExactGapReason }> = [];
+ let after = opts.afterPageId ?? 0;
+ let pagesScanned = 0;
+ let batch = opts.batchPages ?? BATCH_PAGES;
+ let reason: 'deadline' | 'limit' | null = null;
+ let done = false;
+ while (!done) {
+ const remaining = opts.deadlineMs - Date.now();
+ if (remaining <= 0) { reason = 'deadline'; break; }
+ const stmt = buildExactBatchStatement(opts, after, batch);
+ if (!stmt) { done = true; break; }
+ let rows: BatchRow[];
+ try {
+ rows = await engine.executeRaw<BatchRow>(stmt.sql, stmt.params, { timeoutMs: Math.max(1000, remaining), jitOff: true });
+ } catch (e) {
+ if (!isStatementTimeoutError(e)) throw e;
+ if (Date.now() >= opts.deadlineMs) { reason = 'deadline'; break; }
+ if (batch > 1) { batch = Math.max(1, Math.floor(batch / 2)); continue; }
+ const [next] = await engine.executeRaw<{ id: number; slug: string; source_id: string }>(
+ 'SELECT id, slug, source_id FROM pages WHERE id > $1::int AND deleted_at IS NULL ORDER BY id LIMIT 1', [after]);
+ if (!next) { done = true; break; }
+ gaps.push({ page_id: Number(next.id), slug: next.slug, source_id: next.source_id, reason: 'scan_timeout' });
+ after = Number(next.id);
+ pagesScanned++;
+ continue;
+ }
+ if (rows.length === 0) { done = true; break; }
+ for (const row of rows) {
+ const id = Number(row.page_id);
+ if (row.matching_chunks) {
+ if (matches.length >= opts.limit) { reason = 'limit'; break; }
+ const snippets = (typeof row.snippets === 'string' ? JSON.parse(row.snippets) : row.snippets) as ExactMatch['snippets'] | null;
+ matches.push({ page_id: id, slug: row.slug!, source_id: row.source_id!, title: row.title ?? row.slug!, type: row.type ?? '',
+ matching_chunks: Number(row.matching_chunks), snippets: (snippets ?? []).map(s => ({ chunk_index: Number(s.chunk_index), chunk_source: s.chunk_source, text: s.text })) });
+ } else if (row.gap) {
+ gaps.push({ page_id: id, slug: row.slug!, source_id: row.source_id!, reason: row.gap });
+ }
+ after = id;
+ pagesScanned++;
+ }
+ if (reason === 'limit') break;
+ if (rows.length < batch) done = true;
+ }
+ const counted = gaps;
+ const byReason: Partial<Record<ExactGapReason, number>> = {};
+ for (const g of counted) byReason[g.reason] = (byReason[g.reason] ?? 0) + 1;
+ const reasons: ExactScanResult['incomplete_reasons'] = [];
+ if (reason) reasons.push(reason);
+ if (counted.length) reasons.push('unreadable_pages');
+ return {
+ matches,
+ complete: reasons.length === 0,
+ incomplete_reasons: reasons,
+ resume_after: reason ? after : null,
+ pages_scanned: pagesScanned,
+ unreadable: { total: counted.length, by_reason: byReason, sample: counted.slice(0, GAP_SAMPLE).map(({ slug, source_id, reason: r }) => ({ slug, source_id, reason: r })) },
+ };
+}
diff --git a/test/e2e/search-exact-postgres.test.ts b/test/e2e/search-exact-postgres.test.ts
new file mode 100644
index 0000000000..2af3697c17
--- /dev/null
+++ b/test/e2e/search-exact-postgres.test.ts
@@ -0,0 +1,65 @@
+/**
+ * #7191 ask 2: search_exact on real Postgres. The unit suite
+ * (test/search-exact.test.ts) pins matching, completeness and the remote
+ * visibility contract on PGLite; this proves the same statement on pgvector
+ * Postgres, under its statement timeout, for local and remote callers.
+ *
+ * Gated by DATABASE_URL — skips gracefully without real Postgres.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { runExactScan } from '../../src/core/search/exact-scan.ts';
+
+const SKIP = !hasDatabase();
+const describePg = SKIP ? describe.skip : describe;
+
+function mkCtx(engine: unknown, overrides: Record<string, unknown> = {}) {
+ return { engine, config: {} as never, logger: { info: () => {}, warn: () => {}, error: () => {} } as never,
+ dryRun: false, remote: false, sourceId: 'default', ...overrides } as never;
+}
+
+describePg('search_exact on real Postgres (#7191)', () => {
+ beforeAll(async () => {
+ await setupDB();
+ const engine = getEngine();
+ const page = (slug: string, body: string, fm = '') =>
+ importFromContent(engine as never, slug, '---\ntitle: ' + slug + '\ntype: note\n' + fm + '---\n' + body, { sourceId: 'default', noEmbed: true });
+ for (let i = 0; i < 12; i++) await page('notes/filler-' + i, 'ordinary text number ' + i);
+ await page('notes/world', 'The Quarterly\nBoard Pack is due (v2.1).');
+ await page('notes/private', 'board pack private copy', 'visibility: private\n');
+ await page('notes/old', 'board pack legacy copy');
+ await engine.executeRaw("UPDATE pages SET chunker_version = 1 WHERE slug = 'notes/old'");
+ }, 240_000);
+
+ afterAll(async () => {
+ await teardownDB();
+ });
+
+ const exact = (ctx: unknown, params: Record<string, unknown>) => operationsByName['search_exact']!.handler(ctx as never, params) as Promise<any>;
+
+ test('a local caller matches every page holding the phrase and the scan is complete', async () => {
+ const res = await exact(mkCtx(getEngine()), { phrase: 'board pack' });
+ expect(res.matches.map((m: any) => m.slug).sort()).toEqual(['notes/old', 'notes/private', 'notes/world']);
+ expect(res.complete).toBe(true);
+ expect(res.matches.find((m: any) => m.slug === 'notes/world').snippets[0].text).toContain('Board Pack');
+ expect((await exact(mkCtx(getEngine()), { phrase: '(v2.1)' })).matches.map((m: any) => m.slug)).toEqual(['notes/world']);
+ });
+
+ test('a remote caller sees neither the private nor the unsealed page and is told the unsealed one was not read', async () => {
+ const res = await exact(mkCtx(getEngine(), { remote: true, transport: 'stdio', auth: { allowedSources: ['default'] } }), { phrase: 'board pack' });
+ expect(res.matches.map((m: any) => m.slug)).toEqual(['notes/world']);
+ expect(res).toMatchObject({ complete: false, incomplete_reasons: ['unreadable_pages'], unreadable: { by_reason: { unsealed: 1 } } });
+ expect(JSON.stringify(res)).not.toContain('private copy');
+ });
+
+ test('small batches give the same answer under the Postgres statement timeout', async () => {
+ const base = { phrase: 'board pack', excludeSlugPrefixes: [], excludePrivate: false, remote: false, limit: 100, deadlineMs: Date.now() + 60_000, sourceId: 'default' };
+ const whole = await runExactScan(getEngine(), base);
+ const batched = await runExactScan(getEngine(), { ...base, batchPages: 4 });
+ expect(batched.matches.map(m => m.slug)).toEqual(whole.matches.map(m => m.slug));
+ expect(batched.pages_scanned).toBe(whole.pages_scanned);
+ expect(batched.complete).toBe(true);
+ });
+});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index aa450155a4..4106f8e41a 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": 252801,
- "stdoutSha256": "a7fb1bce9dd603de55d2cb1e7d8132d90c3de154bbe4ac4ed0dc29c45eb1037b",
+ "stdoutBytes": 255529,
+ "stdoutSha256": "81d5ecbaf492286225e2ff8d1ec930b6f58524d4ada8af7ac8d0e9cffe3e5a14",
"toolNames": [
"remember",
"entity",
@@ -36,6 +36,7 @@
"search_modes",
"search_tune",
"cache_stats",
+ "search_exact",
"rate_answer",
"search_by_image",
"add_tag",
@@ -2049,6 +2050,81 @@
},
"scope": "admin"
},
+ {
+ "description": "Find every page containing a literal phrase or identifier, exhaustively: use instead of grep. Unranked; returns every match in page order with snippets, and complete: true only when every page you can read was scanned. Literal: words in order with any whitespace between them, case-insensitive unless case_sensitive; no stemming, punctuation literal (ranked search treats quotes as a stemmed phrase). When complete is false, incomplete_reasons says why: deadline or limit (call again with after: resume_after), or unreadable_pages (pages whose text is not indexed yet, listed under unreadable).",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
+ "name": "search_exact",
+ "parameters": {
+ "after": "number?",
+ "case_sensitive": "boolean?",
+ "limit": "number?",
+ "max_seconds": "number?",
+ "min_trust": "string?",
+ "phrase": "string",
+ "slug_prefix": "string?",
+ "source_id": "string?",
+ "types": "array?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "after": {
+ "description": "Resume a bounded scan: the resume_after of the previous call.",
+ "type": "number"
+ },
+ "case_sensitive": {
+ "description": "Match case exactly (default false).",
+ "type": "boolean"
+ },
+ "limit": {
+ "description": "Matching pages to return (default 100, max 1000).",
+ "type": "number"
+ },
+ "max_seconds": {
+ "description": "Scan budget in seconds (default 20, max 120).",
+ "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"
+ },
+ "phrase": {
+ "description": "The literal text, e.g. 'INV-2024-0042' or 'quarterly board pack'.",
+ "type": "string"
+ },
+ "slug_prefix": {
+ "description": "Only slugs starting with this, e.g. 'meetings/'.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "Only this source; '__all__' spans every source you can read.",
+ "type": "string"
+ },
+ "types": {
+ "description": "Only these page types, e.g. ['meeting'].",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "phrase"
+ ],
+ "type": "object"
+ },
+ "scope": "read"
+ },
{
"description": "Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). Pass the answer_id from a query/search/think/synthesize/recall response and rating 1-5, or rate single pages with pages: [{ ref: \"source_id:slug\", rating }]. Example: { answer_id: \"ans_01J…\", pages: [{ ref: \"default:people/alice-example\", rating: 1 }] }. Returns a receipt with each weight before/after; it never edits stored facts.",
"idempotent": true,
diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.ts
index 4ea1e697f7..6b7c97e5a6 100644
--- a/test/operations-coverage-ledger.test.ts
+++ b/test/operations-coverage-ledger.test.ts
@@ -63,6 +63,7 @@ const LEDGER: Record<string, string> = {
search_tune: 'test/search-introspection-ops.test.ts',
cache_stats: 'test/quarantine-cache-ops.test.ts',
search_by_image: 'test/search-by-image-op.test.ts',
+ search_exact: 'test/search-exact.test.ts',
assemble_evidence: 'test/evidence-delivery.test.ts',
add_tag: 'test/source-id-tx-regression.test.ts',
remove_tag: 'test/e2e/mechanical.test.ts',
diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.ts
index b6127c415e..690a39c13a 100644
--- a/test/remote-privacy-sweep.test.ts
+++ b/test/remote-privacy-sweep.test.ts
@@ -158,6 +158,8 @@ const PARAM_FACTORY: Record<string, Record<string, unknown>> = {
fetch: { id: WORLD_FENCE_SLUG },
list_pages: {},
search: { query: 'WORLDSWEEP' },
+ // 'SWEEP_' is inside every PRIVATE sentinel too: the literal scan must still return only world text.
+ search_exact: { phrase: 'SWEEP_' },
query: { query: 'WORLDSWEEP' },
assemble_evidence: { hits: [{ source_id: 'default', slug: WORLD_FENCE_SLUG, chunk_id: 0 }], return_unit: 'page' },
recall: { entity: WORLD_PAGE_SLUG },
@@ -250,6 +252,7 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {
fetch: 'data',
list_pages: 'data',
search: 'data',
+ search_exact: 'data',
query: 'data',
assemble_evidence: 'data',
recall: 'data',
diff --git a/test/retrieval-op-redaction.test.ts b/test/retrieval-op-redaction.test.ts
index 3090044b42..b2ffc46d08 100644
--- a/test/retrieval-op-redaction.test.ts
+++ b/test/retrieval-op-redaction.test.ts
@@ -136,6 +136,7 @@ const SWEEP: Record<string, Row> = {
list_pages: { args: { limit: 100 } },
search: { args: { query: 'PLANTMARK note body', limit: 20 } },
query: { args: { query: 'PLANTMARK note body', limit: 20 } },
+ search_exact: { args: { phrase: 'PLANTMARK' } },
assemble_evidence: { args: { hits: [{ source_id: SRC, slug: 'notes/n1', chunk_id: 0 }], return_unit: 'page' } },
search_by_image: { skip: 'needs image-embedding infra; cross-modal suites own it. Wrapper coverage is the registration test below.' },
get_links: { args: { slug: 'notes/n1' } },
diff --git a/test/search-exact.test.ts b/test/search-exact.test.ts
new file mode 100644
index 0000000000..baf1dbc762
--- /dev/null
+++ b/test/search-exact.test.ts
@@ -0,0 +1,197 @@
+/**
+ * #7191 ask 2: search_exact, the exhaustive literal scan. Match semantics,
+ * completeness (limit, deadline, unreadable pages, resume) and the remote
+ * visibility contract, on PGLite.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { runExactScan, phrasePattern } from '../src/core/search/exact-scan.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw("INSERT INTO sources(id, name) VALUES ('source-a', 'source-a'), ('source-b', 'source-b') ON CONFLICT DO NOTHING");
+});
+
+const op = operations.find(o => o.name === 'search_exact')!;
+
+function ctxOf(overrides: Partial<OperationContext> = {}): OperationContext {
+ return {
+ engine: engine as any,
+ config: {} as any,
+ logger: { info: () => {}, warn: () => {}, error: () => {} } as any,
+ dryRun: false,
+ remote: false,
+ sourceId: 'source-a',
+ ...overrides,
+ } as OperationContext;
+}
+const local = () => ctxOf();
+const allLocal = () => ctxOf({ sourceId: '__all__' });
+const remote = () => ctxOf({ remote: true, transport: 'stdio', auth: { allowedSources: ['source-a'] } as any });
+
+interface Out { matches: Array<{ slug: string; source_id: string; matching_chunks: number; snippets: Array<{ text: string }> }>; complete: boolean; incomplete_reasons: string[];
+ resume_after: number | null; pages_scanned: number; unreadable: { total: number; by_reason: Record<string, number>; sample: Array<{ slug: string; reason: string }> } }
+const exact = (ctx: OperationContext, params: Record<string, unknown>) => op.handler(ctx, params) as Promise<Out>;
+const slugs = (o: Out) => o.matches.map(m => m.slug);
+
+async function page(slug: string, body: string, opts: { sourceId?: string; frontmatter?: string } = {}) {
+ const fm = '---\ntitle: ' + slug.split('/').pop() + '\ntype: note\n' + (opts.frontmatter ?? '') + '---\n';
+ await importFromContent(engine as any, slug, fm + body, { sourceId: opts.sourceId ?? 'source-a', noEmbed: true });
+}
+
+describe('search_exact matching', () => {
+ test('a substring match of the words in order across any whitespace, case-insensitive by default, literal otherwise', async () => {
+ await page('notes/a', 'The Quarterly\nBoard Pack is due on Friday.');
+ await page('notes/b', 'We discussed the board pack later.');
+ await page('notes/c', 'Board packs and boarding passes are different words.');
+ await page('notes/d', 'quarterly board-pack draft');
+ const res = await exact(local(), { phrase: 'board pack' });
+ expect(slugs(res)).toEqual(['notes/a', 'notes/b', 'notes/c']);
+ expect(res.complete).toBe(true);
+ expect(res.matches[0]!.snippets[0]!.text).toContain('Board Pack');
+ expect(slugs(await exact(local(), { phrase: 'Board Pack', case_sensitive: true }))).toEqual(['notes/a']);
+ expect(slugs(await exact(local(), { phrase: 'board-pack' }))).toEqual(['notes/d']);
+ expect(slugs(await exact(local(), { phrase: 'quarterly board pack' }))).toEqual(['notes/a']);
+ });
+
+ test('regex and LIKE metacharacters in the phrase are literal', async () => {
+ await page('notes/a', 'Ticket (A+B)? 100% done_ok [x] c:\\path.');
+ await page('notes/b', 'Ticket AAB done');
+ expect(slugs(await exact(local(), { phrase: '(A+B)?' }))).toEqual(['notes/a']);
+ expect(slugs(await exact(local(), { phrase: '100% done_ok' }))).toEqual(['notes/a']);
+ expect(slugs(await exact(local(), { phrase: '[x] c:\\path.' }))).toEqual(['notes/a']);
+ expect(phrasePattern(' a.b c ')).toEqual({ regex: 'a\\.b[[:space:]]+c', longest: 'a.b' });
+ });
+
+ test('a phrase near the end of a long page is found', async () => {
+ const filler = Array.from({ length: 400 }, (_, i) => 'Paragraph ' + i + ' talks about ordinary planning topics in some detail.').join('\n\n');
+ await page('notes/long', filler + '\n\nThe rare code word is zephyr-nine-alpha.');
+ const res = await exact(local(), { phrase: 'zephyr-nine-alpha' });
+ expect(slugs(res)).toEqual(['notes/long']);
+ expect(res.complete).toBe(true);
+ });
+
+ test('type and slug_prefix narrow the scan', async () => {
+ await page('meetings/m1', 'agenda item alpha');
+ await page('notes/n1', 'agenda item alpha');
+ expect(slugs(await exact(local(), { phrase: 'agenda item', slug_prefix: 'meetings/' }))).toEqual(['meetings/m1']);
+ expect(slugs(await exact(local(), { phrase: 'agenda item', types: ['note'] }))).toEqual(['meetings/m1', 'notes/n1']);
+ expect(slugs(await exact(local(), { phrase: 'agenda item', types: ['person'] }))).toEqual([]);
+ });
+});
+
+describe('search_exact completeness', () => {
+ test('limit bounds the page count and resume_after continues the scan to completion', async () => {
+ for (const n of [1, 2, 3, 4, 5]) await page('notes/p' + n, 'marker phrase number ' + n);
+ await page('notes/other', 'nothing to see');
+ const first = await exact(local(), { phrase: 'marker phrase', limit: 2 });
+ expect(slugs(first)).toEqual(['notes/p1', 'notes/p2']);
+ expect(first.complete).toBe(false);
+ expect(first.incomplete_reasons).toEqual(['limit']);
+ const second = await exact(local(), { phrase: 'marker phrase', limit: 2, after: first.resume_after });
+ expect(slugs(second)).toEqual(['notes/p3', 'notes/p4']);
+ const third = await exact(local(), { phrase: 'marker phrase', limit: 2, after: second.resume_after });
+ expect(slugs(third)).toEqual(['notes/p5']);
+ expect(third).toMatchObject({ complete: true, incomplete_reasons: [], resume_after: null });
+ expect(first.pages_scanned + second.pages_scanned + third.pages_scanned).toBe(6);
+ });
+
+ test('batch size never changes the answer', async () => {
+ for (const n of [1, 2, 3, 4, 5, 6, 7]) await page('notes/p' + n, n % 2 ? 'odd marker here' : 'even page');
+ const base = { phrase: 'odd marker', excludeSlugPrefixes: [], excludePrivate: false, remote: false, limit: 100, deadlineMs: Date.now() + 30_000, sourceId: 'source-a' };
+ const whole = await runExactScan(engine, base);
+ for (const batchPages of [1, 2, 3]) {
+ const batched = await runExactScan(engine, { ...base, batchPages });
+ expect({ batchPages, slugs: batched.matches.map(m => m.slug), complete: batched.complete, scanned: batched.pages_scanned })
+ .toEqual({ batchPages, slugs: whole.matches.map(m => m.slug), complete: true, scanned: 7 });
+ }
+ });
+
+ test('a spent deadline is incomplete and resumable from where it stopped', async () => {
+ await page('notes/a', 'deadline marker');
+ const stopped = await runExactScan(engine, { phrase: 'deadline marker', excludeSlugPrefixes: [], excludePrivate: false, remote: false, limit: 10, deadlineMs: Date.now() - 1, sourceId: 'source-a' });
+ expect(stopped).toMatchObject({ complete: false, incomplete_reasons: ['deadline'], resume_after: 0, matches: [] });
+ expect(slugs(await exact(local(), { phrase: 'deadline marker', after: stopped.resume_after }))).toEqual(['notes/a']);
+ });
+
+ test('a page with text but no readable chunk makes the scan incomplete and is named', async () => {
+ await page('notes/indexed', 'the needle is here');
+ await page('notes/held', 'the needle is also here');
+ await page('notes/pending', 'the needle again');
+ await page('notes/empty', '');
+ const [held] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/held'");
+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [held!.id]);
+ await engine.executeRaw("UPDATE pages SET text_projection_revision = NULL WHERE slug = 'notes/pending'");
+ const res = await exact(local(), { phrase: 'needle' });
+ expect(slugs(res)).toEqual(['notes/indexed']);
+ expect(res.complete).toBe(false);
+ expect(res.incomplete_reasons).toEqual(['unreadable_pages']);
+ expect(res.unreadable.by_reason).toEqual({ unchunked: 1, projection_pending: 1 });
+ expect(res.unreadable.sample.map(s => [s.slug, s.reason]).sort()).toEqual([['notes/held', 'unchunked'], ['notes/pending', 'projection_pending']]);
+ });
+});
+
+describe('search_exact remote visibility', () => {
+ test('private and foreign-source pages are matched locally and never remotely, quarantined pages by nobody; remote stays complete', async () => {
+ await page('notes/world', 'shared secret-word-77 text');
+ const baseline = await exact(remote(), { phrase: 'secret-word-77' });
+ expect(slugs(baseline)).toEqual(['notes/world']);
+ expect(baseline.complete).toBe(true);
+ await page('notes/private', 'private secret-word-77 text', { frontmatter: 'visibility: private\n' });
+ await page('notes/quarantined', 'quarantined secret-word-77 text');
+ await engine.executeRaw("UPDATE pages SET frontmatter = frontmatter || '{\"quarantine\": \"synthetic\"}'::jsonb WHERE slug = 'notes/quarantined'");
+ await page('notes/foreign', 'foreign secret-word-77 text', { sourceId: 'source-b' });
+ const everywhere = await exact(allLocal(), { phrase: 'secret-word-77', source_id: '__all__' });
+ expect(everywhere.matches.map(m => m.source_id + ':' + m.slug).sort()).toEqual(['source-a:notes/private', 'source-a:notes/world', 'source-b:notes/foreign']);
+ const res = await exact(remote(), { phrase: 'secret-word-77' });
+ expect(slugs(res)).toEqual(['notes/world']);
+ expect(res.complete).toBe(true);
+ expect(JSON.stringify(res)).not.toContain('notes/private');
+ });
+
+ test('a page indexed before the safe-chunk fence is withheld remotely and reported as unsealed', async () => {
+ await page('notes/old', 'legacy marker words');
+ await engine.executeRaw("UPDATE pages SET chunker_version = 1 WHERE slug = 'notes/old'");
+ expect(slugs(await exact(local(), { phrase: 'legacy marker' }))).toEqual(['notes/old']);
+ const res = await exact(remote(), { phrase: 'legacy marker' });
+ expect(res.matches).toEqual([]);
+ expect(res).toMatchObject({ complete: false, incomplete_reasons: ['unreadable_pages'], unreadable: { by_reason: { unsealed: 1 } } });
+ });
+
+ test('a source outside the grant is refused', async () => {
+ await expect(exact(remote(), { phrase: 'x y', source_id: 'source-b' })).rejects.toBeDefined();
+ });
+});
+
+describe('search_exact parameters', () => {
+ for (const [label, params] of [
+ ['empty phrase', { phrase: ' ' }],
+ ['limit 0', { phrase: 'a b', limit: 0 }],
+ ['limit 1001', { phrase: 'a b', limit: 1001 }],
+ ['negative after', { phrase: 'a b', after: -1 }],
+ ['max_seconds 0', { phrase: 'a b', max_seconds: 0 }],
+ ['types string', { phrase: 'a b', types: 'note' }],
+ ['case_sensitive string', { phrase: 'a b', case_sensitive: 'yes' }],
+ ] as Array<[string, Record<string, unknown>]>) {
+ test('rejects ' + label, async () => {
+ await expect(exact(local(), params)).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+ }
+});