Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(find,stats): gbrain find / find_pages and stats --by source,type [--since] [--collapse-aliases] (#7191)

garrytan796806d7f01f
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index b9a36e6b12..8e388cabb4 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
@@ -177,6 +177,7 @@ Every non-localOnly operation on the MCP surface: 157 tools across 25 areas. **S
| `delete_page` | Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). | write | | |
| `edit_page` | Change part of a page: prefer this over put_page for small changes. | write | yes | |
| `fetch` | Fetch the full text of one search result by its opaque, source-qualified `id` (OpenAI deep-research contract: the search/fetch pair). | read | | |
+| `find_pages` | Find pages by name or path (what ls/find would answer), sorted by slug. | read | | |
| `get_chunks` | Return a page's indexed content chunks (the units search ranks), in chunk_index order, 50 at a time by default. | read | | |
| `get_page` | Read a page by slug. | read | yes | |
| `get_page_upload` | An upload's state and next_part, to resume after a lost reply. | write | | |
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.md
index 8827bb0f37..690cfc2576 100644
--- a/docs/architecture/key-files/engines-2.md
+++ b/docs/architecture/key-files/engines-2.md
@@ -31,6 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/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.
+- `src/core/engine-sql/page-lookup.ts` + `src/core/page-find.ts` + `src/core/page-counts.ts` + `src/core/ops/find-pages.ts` + `src/core/ops/stats-by.ts` + `src/cli/format-page-lookup.ts` — find-by-name and grouped counts (`gbrain find` / `find_pages`, `gbrain stats --by` / `get_stats` `by`, `since`, `collapse_aliases`). `parseFindPattern` turns a glob (`*`/`?`, whole slug or source path), a slug prefix (contains `/`) or a name (title or last slug segment substring) into one `escapeLikePattern`-escaped ILIKE pattern; names are served by `idx_pages_trgm` + `idx_pages_slug_trgm`, while globs and prefixes also match `source_path` (no trigram index). Rows sort by slug then source in the C collation, carry `count(*) OVER ()` as `total`, and the op reports `complete` (limit default 50, cap 500 local, 100 remote). Find hides the ranked-search hard excludes (`resolveHardExcludes` + `buildHardExcludeClause`) unless the pattern's literal lead is inside one, and names them in `hidden_prefixes`. `countPagesBy` returns per (source, type) counts plus raw and distinct-slug totals (per type group through an `unnest` mapping and GROUPING SETS), so cross-source twins are never silently double counted; `since` is the query effective-date bound (`resolveDateBoundary`). Every caller sees live pages in unarchived sources; a remote caller's `readPolicyOpts` policy adds `pageReadFilter(..., live)`. `collapseTypes` lets the active pack decide (declared stays, alias joins canonical), else normalizes (last segment, lower case, singular) and joins a `-<name>` suffix to an existing group; each group lists `member_types` with its rule (`exact`, `pack_alias`, `normalized`, `suffix`). Without the grouping params `get_stats` returns its unchanged counters. Tests: `test/page-find-pattern-7191.test.ts`, `test/page-lookup-7191.test.ts` (Postgres arm: `test/e2e/page-lookup-7191.test.ts`).
- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin).
- `src/core/engine-sql/chunks.ts` `upsertChunksOnce` — a chunk replacement inside the caller's transaction: the batched `chunkWriteInvalidations` guard, then one prune (`moveDisplacedChunksAndPrune`: a row whose vector still matches its text (`movableChunkSql`) and whose exact text and source reappear at another index is parked at a negative index and moved there; rows outside the new set are deleted), then one multi-row INSERT per `jsonRowBatches` batch (at most `ROW_BATCH_MAX_ROWS` rows and `ROW_BATCH_MAX_BYTES` encoded bytes; the first is pipelined with the seal). A failure in any batch rolls back the prune and every earlier batch. Tests: `engine-sql-chunks-batched-write.test.ts`, the multi-batch case in `helpers/engine-sql-rollback-cases.ts`.
diff --git a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
index 844840fbad..844cdeab46 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/brain-first.md
@@ -45,6 +45,14 @@ synonym- and outcome-phrased matches drop silently otherwise. And `query` is
still top-K: for literal "list every page that…" enumeration, use `list_pages`
with pagination.
+Find pages by name or path, and count them, through gbrain too, instead of
+`ls`/`find` on the checkout or `grep -c`/`wc`/SQL:
+
+```bash
+gbrain find 'people/*acme*' # glob, slug prefix or name (instead of ls/find); MCP find_pages
+gbrain stats --by source,type --since 30d # page counts per source and type (instead of grep -c/SQL)
+```
+
Never skip to external APIs without completing steps 1-2. The brain has
thousands of pages. The answer is almost always there.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
index 844840fbad..844cdeab46 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/brain-first.md
@@ -45,6 +45,14 @@ synonym- and outcome-phrased matches drop silently otherwise. And `query` is
still top-K: for literal "list every page that…" enumeration, use `list_pages`
with pagination.
+Find pages by name or path, and count them, through gbrain too, instead of
+`ls`/`find` on the checkout or `grep -c`/`wc`/SQL:
+
+```bash
+gbrain find 'people/*acme*' # glob, slug prefix or name (instead of ls/find); MCP find_pages
+gbrain stats --by source,type --since 30d # page counts per source and type (instead of grep -c/SQL)
+```
+
Never skip to external APIs without completing steps 1-2. The brain has
thousands of pages. The answer is almost always there.
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/plugin/skills/conventions/brain-first.md b/plugin/skills/conventions/brain-first.md
index 844840fbad..844cdeab46 100644
--- a/plugin/skills/conventions/brain-first.md
+++ b/plugin/skills/conventions/brain-first.md
@@ -45,6 +45,14 @@ synonym- and outcome-phrased matches drop silently otherwise. And `query` is
still top-K: for literal "list every page that…" enumeration, use `list_pages`
with pagination.
+Find pages by name or path, and count them, through gbrain too, instead of
+`ls`/`find` on the checkout or `grep -c`/`wc`/SQL:
+
+```bash
+gbrain find 'people/*acme*' # glob, slug prefix or name (instead of ls/find); MCP find_pages
+gbrain stats --by source,type --since 30d # page counts per source and type (instead of grep -c/SQL)
+```
+
Never skip to external APIs without completing steps 1-2. The brain has
thousands of pages. The answer is almost always there.
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 249aaeb8ed..f1f55bce29 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -53,6 +53,7 @@ const CONSTANT_ALLOWLIST: Record<string, string> = {
const VETTED_BUILDERS: Record<string, string> = {
pageReadFilter: 'src/core/search/read-policy-sql.ts: binds scope values as params, splices only the caller alias',
+ buildHardExcludeClause: 'src/core/search/sql-ranking.ts: LIKE-escaped and SQL-escaped slug prefix literals (buildLikePrefixLiteral), the ranked-search hard-exclude clause',
buildRecencyComponentSql: 'src/core/search/sql-ranking.ts: inlines LIKE literals + numeric coefficients from the decay map, as master (planner behavior)',
privatePagesFilterFragment: 'src/core/search/private-visibility.ts: constant visibility predicate over a caller alias',
quarantineFilterFragment: 'src/core/quarantine.ts: constant quarantine predicate over a caller alias',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index b7eaa4b0c7..bef7af02b4 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 3023 ratchet +3 #7191: find_pages/get_stats grouped formatter dispatch and its import (renderers in cli/format-page-lookup.ts); +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/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)
@@ -16,12 +16,12 @@ src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due
src/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
-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/engine.ts 2837 ratchet +5 #7191: findPages/countPagesBy signatures and type imports (SQL in engine-sql/page-lookup.ts); 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/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/operations.ts 243 ratchet +1 #7191: find_pages domain module import (ops/find-pages.ts); 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/pglite-engine.ts 3094 ratchet +9 #7191: findPages/countPagesBy delegates and imports (SQL in engine-sql/page-lookup.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); 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 3116 ratchet +9 #7191: findPages/countPagesBy scoped-read delegates and imports (SQL in engine-sql/page-lookup.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); 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
src/core/types.ts 2339 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts); +14 GBRA-154 ranking wave (#4612 #7153 #7156 #7162 #7164): SearchResult collapsed/redirect_to/image_page/rank_prior/rank_score/fused_score stamps and HybridSearchMeta.collapse (interface fields; logic in search/collapse.ts, rank-priors.ts, score-contract.ts)
src/core/minions/queue.ts 2533 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)
diff --git a/skills/conventions/brain-first.md b/skills/conventions/brain-first.md
index 844840fbad..844cdeab46 100644
--- a/skills/conventions/brain-first.md
+++ b/skills/conventions/brain-first.md
@@ -45,6 +45,14 @@ synonym- and outcome-phrased matches drop silently otherwise. And `query` is
still top-K: for literal "list every page that…" enumeration, use `list_pages`
with pagination.
+Find pages by name or path, and count them, through gbrain too, instead of
+`ls`/`find` on the checkout or `grep -c`/`wc`/SQL:
+
+```bash
+gbrain find 'people/*acme*' # glob, slug prefix or name (instead of ls/find); MCP find_pages
+gbrain stats --by source,type --since 30d # page counts per source and type (instead of grep -c/SQL)
+```
+
Never skip to external APIs without completing steps 1-2. The brain has
thousands of pages. The answer is almost always there.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 843b6c5d7b..37fb8f9e11 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -45,7 +45,7 @@
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
"conventions/agent-operator-protocol.md": "d7cfc7e4c84f61392658cbe969058b1e8237b7d44c3ebdeec352569ffddbe001",
- "conventions/brain-first.md": "987223ce443b3e8cdcd22975aafabce778016f238deddf544c346238dbde1bd9",
+ "conventions/brain-first.md": "e2b957676105c5751cc5c97d4dfbbbcb19b8a728e27a31102ba41e6678affa09",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
diff --git a/src/cli/format-page-lookup.ts b/src/cli/format-page-lookup.ts
new file mode 100644
index 0000000000..c8e37074c7
--- /dev/null
+++ b/src/cli/format-page-lookup.ts
@@ -0,0 +1,39 @@
+/**
+ * #7191: human renderers for `gbrain find` (find_pages) and grouped
+ * `gbrain stats --by` (get_stats). `--json` prints the op result instead
+ * (formatResult). Find rows are tab-separated like `gbrain list`; the
+ * truncation note goes to stderr so stdout stays parseable.
+ */
+import type { StatsByResult } from '../core/page-counts.ts';
+
+const cell = (value: unknown): string => {
+ const text = value === null || value === undefined ? '' : String(value);
+ return text.replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\r/g, '\\r').replace(/\n/g, '\\n');
+};
+
+export function formatFindPages(result: any): string {
+ if (!result.complete) {
+ process.stderr.write(`[find] showing ${result.pages.length} of ${result.total} matches (--limit ${result.limit}); narrow the pattern, add --type or --source, or raise --limit.\n`);
+ }
+ if (result.pages.length === 0) return 'No pages found.\n';
+ return result.pages.map((p: any) =>
+ [p.slug, p.source_id, p.type, String(p.updated_at ?? '').slice(0, 10), p.title].map(cell).join('\t'),
+ ).join('\n') + '\n';
+}
+
+export function formatStatsBy(result: StatsByResult): string {
+ const lines = [`Pages: ${result.total_pages} (${result.distinct_slugs} distinct slugs)`];
+ if (result.since) lines.push(`Since: ${result.since}`);
+ if (result.groups.length > 0) {
+ const header = [...result.by, 'pages', ...(result.groups[0]!.distinct_slugs !== undefined ? ['distinct_slugs'] : [])];
+ lines.push('', header.join('\t'));
+ for (const g of result.groups) {
+ const keys = result.by.map((dim) => (dim === 'source' ? g.source_id : g.type || '(untyped)'));
+ lines.push([...keys, g.pages, ...(g.distinct_slugs !== undefined ? [g.distinct_slugs] : [])].map(cell).join('\t'));
+ if (g.member_types && (g.member_types.length > 1 || g.member_types[0]?.type !== g.type)) {
+ lines.push(` = ${g.member_types.map((m) => `${cell(m.type)} (${m.pages}, ${m.via})`).join(', ')}`);
+ }
+ }
+ }
+ return lines.join('\n') + '\n';
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 2263431a43..40ea41e47d 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -60,6 +60,7 @@ import { redactRetrievalOutput } from '../core/search/output-redaction.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';
+import { formatFindPages, formatStatsBy } from './format-page-lookup.ts';
import { maybePromptForUpgrade } from '../core/thin-client-upgrade-prompt.ts';
import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
import { cliHelpRequested } from './subcommands.ts';
@@ -1695,8 +1696,10 @@ export function formatResult(
const tags = result as string[];
return tags.length > 0 ? tags.join(', ') + '\n' : 'No tags.\n';
}
+ case 'find_pages': return formatFindPages(result);
case 'get_stats': {
const s = result as any;
+ if (Array.isArray(s?.groups)) return formatStatsBy(s);
const lines = [
`Pages: ${s.page_count}`,
`Chunks: ${s.chunk_count}`,
diff --git a/src/cli/top-help.ts b/src/cli/top-help.ts
index 336cb11dc5..e6e9dda294 100644
--- a/src/cli/top-help.ts
+++ b/src/cli/top-help.ts
@@ -45,6 +45,8 @@ PAGES
delete <slug> Delete a page
list [--type T] [--tag T] [--limit N]
List pages
+ find <glob|prefix|name> [--type T] [--source S] [--limit N]
+ Find pages by slug, path or title
SEARCH
search <query> Keyword search (tsvector)
@@ -190,6 +192,8 @@ JOBS (Minions)
ADMIN
stats Brain statistics
+ stats --by source,type [--since 30d] [--collapse-aliases]
+ Live page counts per source and type
health Brain health dashboard
history <slug> [--json] Page version history
revert <slug> <version-id> Revert to version
diff --git a/src/core/engine-sql/page-lookup.ts b/src/core/engine-sql/page-lookup.ts
new file mode 100644
index 0000000000..aed728b92c
--- /dev/null
+++ b/src/core/engine-sql/page-lookup.ts
@@ -0,0 +1,111 @@
+/**
+ * #7191: page lookups agents otherwise run on the filesystem: find by name
+ * or path (`BrainEngine.findPages`, the `find_pages` op) and grouped page
+ * counts (`BrainEngine.countPagesBy`, `get_stats` with `by`/`since`). One
+ * implementation for both engines; reads take `ScopedRead` (Postgres runs
+ * them in `withScopedReadTransaction`).
+ *
+ * Visibility: live pages (`deleted_at IS NULL`) in unarchived sources for
+ * every caller; an untrusted caller's policy adds `pageReadFilter(..., live)`,
+ * the shared read-policy predicate (private pages, trust floor, quarantine).
+ * Find also hides the ranked-search hard-exclude prefixes
+ * (`buildHardExcludeClause` over `resolveHardExcludes`, resolved by the op).
+ *
+ * Index use: a find pattern is one ILIKE pattern. A name pattern matches
+ * `title` or the slug (rechecked on its last segment), so `idx_pages_trgm`
+ * and `idx_pages_slug_trgm` combine in a BitmapOr. A glob or prefix pattern
+ * also matches `source_path`, which has no trigram index, so it reads every
+ * page in scope (measured in the PR). Rows sort by `slug`, then `source_id`,
+ * in the C collation so both engines and every database locale agree; the
+ * distinct-slug counts use it too (a C sort is several times faster than a
+ * locale sort, and both collations are deterministic, so counts match).
+ * Postgres runs untrusted reads with JIT off (as #6276): the read-policy
+ * subplans push their cost estimate past the JIT thresholds.
+ */
+import type { FindPagesQuery, FoundPage, FoundPages, UntrustedReadPolicy } from '../page-find.ts';
+import type { PageCountQuery, PageCounts, TypeGrouper } from '../page-counts.ts';
+import { pageReadFilter } from '../search/read-policy-sql.ts';
+import { buildHardExcludeClause } from '../search/sql-ranking.ts';
+import type { ScopedRead } from './brands.ts';
+import { sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
+import { compileRowNormalizer } from './normalize.ts';
+
+function visiblePages(scope: { sourceId?: string; sourceIds?: string[]; untrusted?: UntrustedReadPolicy }): SqlFragment {
+ const source = scope.sourceIds && scope.sourceIds.length > 0
+ ? sqlFragment`AND p.source_id = ANY(${scope.sourceIds}::text[])`
+ : scope.sourceId
+ ? sqlFragment`AND p.source_id = ${scope.sourceId}`
+ : sqlFragment``;
+ const policy = scope.untrusted ? trustedSql(`AND ${pageReadFilter('p', scope.untrusted, [], true)}`) : sqlFragment``;
+ return sqlFragment`p.deleted_at IS NULL AND NOT s.archived ${source} ${policy}`;
+}
+
+const normalizeFound = compileRowNormalizer<FoundPage & { total: number }>({ total: 'bigint' });
+
+export async function findPages(exec: ScopedRead, query: FindPagesQuery): Promise<FoundPages> {
+ const like = query.pattern.like;
+ const match = query.pattern.kind === 'name'
+ ? sqlFragment`(p.title ILIKE ${like} OR (p.slug ILIKE ${like} AND regexp_replace(p.slug, '^.*/', '') ILIKE ${like}))`
+ : sqlFragment`(p.slug ILIKE ${like} OR p.source_path ILIKE ${like})`;
+ const types = query.types && query.types.length > 0 ? sqlFragment`AND p.type = ANY(${query.types}::text[])` : sqlFragment``;
+ const hidden = trustedSql(buildHardExcludeClause('p.slug', query.excludeSlugPrefixes));
+ const { rows } = await exec.run(sqlFragment`
+ SELECT p.slug, p.source_id, p.type, p.title, p.source_path,
+ to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at,
+ count(*) OVER () AS total
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${match} AND ${visiblePages(query)} ${types} ${hidden}
+ ORDER BY p.slug COLLATE "C", p.source_id COLLATE "C"
+ LIMIT ${query.limit}
+ `);
+ const found = rows.map(normalizeFound);
+ return {
+ rows: found.map(({ total: _total, ...page }) => page),
+ total: found[0]?.total ?? 0,
+ };
+}
+
+const normalizeTypeCount = compileRowNormalizer<{ source_id: string; type: string; pages: number }>({ pages: 'bigint' });
+const normalizeDistinct = compileRowNormalizer<{ grp: string | null; is_total: boolean; pages: number; distinct_slugs: number }>({
+ pages: 'bigint', distinct_slugs: 'bigint',
+});
+
+export async function countPagesBy(exec: ScopedRead, query: PageCountQuery, groupTypes?: TypeGrouper): Promise<PageCounts> {
+ const since = query.since
+ ? sqlFragment`AND COALESCE(p.effective_date, p.updated_at, p.created_at) >= ${query.since}::text::timestamptz`
+ : sqlFragment``;
+ const where = sqlFragment`${visiblePages(query)} ${since}`;
+ const bySourceType = (await exec.run(sqlFragment`
+ SELECT p.source_id, p.type, count(*) AS pages
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${where}
+ GROUP BY p.source_id, p.type
+ `)).rows.map(normalizeTypeCount);
+ if (!groupTypes) {
+ const [total] = (await exec.run(sqlFragment`
+ SELECT NULL::text AS grp, true AS is_total, count(*) AS pages, count(DISTINCT p.slug COLLATE "C") AS distinct_slugs
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ WHERE ${where}
+ `)).rows.map(normalizeDistinct);
+ return { bySourceType, byTypeGroup: [], total: { pages: total?.pages ?? 0, distinct_slugs: total?.distinct_slugs ?? 0 } };
+ }
+ const types = [...new Set(bySourceType.map((row) => row.type))];
+ const groups = groupTypes(types);
+ const rows = (await exec.run(sqlFragment`
+ SELECT m.grp, GROUPING(m.grp) = 1 AS is_total, count(*) AS pages, count(DISTINCT p.slug COLLATE "C") AS distinct_slugs
+ FROM pages p
+ JOIN sources s ON s.id = p.source_id
+ JOIN unnest(${types}::text[], ${groups}::text[]) AS m(type, grp) ON m.type = p.type
+ WHERE ${where}
+ GROUP BY GROUPING SETS ((m.grp), ())
+ `)).rows.map(normalizeDistinct);
+ const total = rows.find((row) => row.is_total);
+ return {
+ bySourceType,
+ byTypeGroup: rows.filter((row) => !row.is_total).map((row) => ({ group: row.grp ?? '', pages: row.pages, distinct_slugs: row.distinct_slugs })),
+ total: { pages: total?.pages ?? 0, distinct_slugs: total?.distinct_slugs ?? 0 },
+ };
+}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 154bd6c9c5..b44efd00cd 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -6,6 +6,8 @@ import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './sea
import type { KeywordPageWindow } from './search/keyword-statement.ts';
import type { EmbeddingState, EmbeddingStateCounts, EmbeddingStateRow } from './embedding-state.ts';
import type { DerivedLinkBatchItem, DerivedLinkOrigin, DerivedLinkReplacementOptions } from './derived-links.ts';
+import type { FindPagesQuery, FoundPages } from './page-find.ts';
+import type { PageCountQuery, PageCounts, TypeGrouper } from './page-counts.ts';
export type { PageKey, PageSnapshot, PageSnapshotOptions, PageWriteOptions, PageMutationPrecondition, PageWithdrawal } from './page-state/types.ts';
import type {
Page, PageInput, PageFilters, GetPageOpts, PageReadScope, PageReadPolicy,
@@ -1031,6 +1033,10 @@ export interface BrainEngine {
* `filters.includeDeleted: true` to surface them.
*/
listPages(filters?: PageFilters): Promise<Page[]>;
+ /** #7191: live pages whose slug, source path or title matches a find pattern (SQL in engine-sql/page-lookup.ts). */
+ findPages(query: FindPagesQuery): Promise<FoundPages>;
+ /** #7191: live page counts per (source, type), with distinct-slug totals per type group when `groupTypes` is set. */
+ countPagesBy(query: PageCountQuery, groupTypes?: TypeGrouper): Promise<PageCounts>;
/**
* Fuzzy slug resolver.
*
diff --git a/src/core/operation-load.ts b/src/core/operation-load.ts
index ef2ebfd745..11204371cf 100644
--- a/src/core/operation-load.ts
+++ b/src/core/operation-load.ts
@@ -31,7 +31,7 @@ const OP_AREAS: Record<string, string> = {
synthesize: 'memory-verbs', forget: 'memory-verbs',
context_pack: 'memory-verbs', delta: 'memory-verbs',
// pages (CRUD, versions, raw payloads, resolution)
- get_page: 'pages', put_page: 'pages', delete_page: 'pages', list_pages: 'pages',
+ get_page: 'pages', put_page: 'pages', delete_page: 'pages', list_pages: 'pages', find_pages: 'pages',
restore_page: 'pages', purge_deleted_pages: 'pages',
get_versions: 'pages', revert_version: 'pages',
resolve_slugs: 'pages', get_chunks: 'pages',
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 84eadef04d..d7c7f052ce 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -21,6 +21,7 @@ const load_extraction = () => import('./ops/extraction.ts') as Promise<Record<st
const load_facts = () => import('./ops/facts.ts') as Promise<Record<string, unknown>>;
const load_feedback = () => import('./ops/feedback.ts') as Promise<Record<string, unknown>>;
const load_files = () => import('./ops/files.ts') as Promise<Record<string, unknown>>;
+const load_find_pages = () => import('./ops/find-pages.ts') as Promise<Record<string, unknown>>;
const load_image = () => import('./ops/image.ts') as Promise<Record<string, unknown>>;
const load_ingest_log = () => import('./ops/ingest-log.ts') as Promise<Record<string, unknown>>;
const load_insights = () => import('./ops/insights.ts') as Promise<Record<string, unknown>>;
@@ -67,6 +68,7 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"purge_deleted_pages": [load_pages, "pagesOperations"],
"capture": [load_pages, "pagesOperations"],
"fetch": [load_pages, "pagesOperations"],
+ "find_pages": [load_find_pages, "findPagesOperations"],
"edit_page": [load_page_edit, "pageEditOperations"],
"append_page": [load_page_append, "pageAppendOperations"],
"put_pages": [load_page_batch, "pageBatchOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index e60aa7961c..154d7d2f17 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -779,6 +779,47 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"area": "pages"
},
+ {
+ "name": "find_pages",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Find pages by name or path (what ls/find would answer), sorted by slug. pattern: a glob ('people/*acme*') matched against slug or source path, a slug prefix ('companies/acme'), or a plain name ('acme', a case-insensitive substring of the title or the slug's last segment). Returns slug, source_id, type, title, source_path and updated_at per page, total matches in scope, and complete (false when limit cut the list).",
+ "params": {
+ "pattern": {
+ "type": "string",
+ "required": true,
+ "description": "Glob, slug prefix or name."
+ },
+ "type": {
+ "type": "string",
+ "description": "Page type, or several comma-separated."
+ },
+ "types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Page types, e.g. ['person']."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max rows (default 50; max 500, remote 100)."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "find",
+ "positional": [
+ "pattern"
+ ]
+ },
+ "area": "pages"
+ },
{
"name": "edit_page",
"idempotent": true,
@@ -2266,8 +2307,21 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"mutating": false,
"idempotent": true,
"outputRedaction": "no_stored_text",
- "description": "Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant.",
- "params": {},
+ "description": "Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant. Pass by (source, type or source,type), since or collapse_aliases for live page counts per group instead, with distinct-slug totals so cross-source twins are not double counted.",
+ "params": {
+ "by": {
+ "type": "string",
+ "description": "Group page counts: 'source', 'type' or 'source,type'."
+ },
+ "since": {
+ "type": "string",
+ "description": "Effective date on/after: YYYY-MM-DD or 7d/2w/1y."
+ },
+ "collapse_aliases": {
+ "type": "boolean",
+ "description": "Merge near-duplicate type names; lists each group's member types."
+ }
+ },
"scope": "admin",
"cliHints": {
"name": "stats"
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 4d1449b83f..0810f377bb 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -126,6 +126,7 @@ import { pageBatchOperations } from './ops/page-batch.ts';
import { pageUploadOperations } from './ops/page-upload.ts';
import { feedbackOperations } from './ops/feedback.ts';
import { trustOperations } from './ops/trust.ts';
+import { findPagesOperations } from './ops/find-pages.ts';
// parseTtlParam moved to ops/facts.ts with the facts cluster; the `remember`
// verb (verbs.ts) loads it from THIS module at runtime — re-exported so every
@@ -143,7 +144,7 @@ export const operations: Operation[] = [
...verbOperations,
// Page CRUD (get_page, put_page, delete_page, list_pages + the v0.26.5
// destructive-guard ops restore_page, purge_deleted_pages) — ops/pages.ts
- ...pagesOperations, ...pageEditOperations, ...pageAppendOperations, ...pageBatchOperations, ...pageUploadOperations,
+ ...pagesOperations, ...findPagesOperations, ...pageEditOperations, ...pageAppendOperations, ...pageBatchOperations, ...pageUploadOperations,
...persistenceOperations,
// Search (search, query) — ops/search.ts
...searchOperations,
diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.ts
index 5c8b7e5518..6ffe9dd742 100644
--- a/src/core/ops/admin.ts
+++ b/src/core/ops/admin.ts
@@ -24,6 +24,7 @@ import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';
import { openSegmentedBody } from '../page-body/read-range.ts';
import { segmentedReadDocument } from '../page-window/segmented.ts';
import { getVersionsKnownAsOf, KNOWN_AS_OF_PARAM, VERSIONS_DIFF_PARAM } from './known-as-of.ts';
+import { STATS_BY_PARAMS, statsBy, wantsStatsBy } from './stats-by.ts';
// --- Admin ---
@@ -44,9 +45,11 @@ const get_stats: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'no_stored_text',
- description: 'Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant.',
- params: {},
- handler: async (ctx) => {
+ description: 'Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant. ' +
+ 'Pass by (source, type or source,type), since or collapse_aliases for live page counts per group instead, with distinct-slug totals so cross-source twins are not double counted.',
+ params: STATS_BY_PARAMS,
+ handler: async (ctx, p) => {
+ if (wantsStatsBy(p)) return statsBy(ctx, p, diagnosticScope(ctx));
return ctx.engine.getStats(diagnosticScope(ctx));
},
scope: 'admin',
diff --git a/src/core/ops/find-pages.ts b/src/core/ops/find-pages.ts
new file mode 100644
index 0000000000..9d05ed53f7
--- /dev/null
+++ b/src/core/ops/find-pages.ts
@@ -0,0 +1,101 @@
+/**
+ * #7191: `find_pages` (CLI `gbrain find <pattern>`): find pages by name or
+ * path in one indexed read, instead of `ls` / `find` on a checkout. Pattern
+ * forms and matching rules: src/core/page-find.ts; SQL and index use:
+ * src/core/engine-sql/page-lookup.ts.
+ *
+ * Scope follows `list_pages`: `federatedSearchScope` (an explicit `source_id`,
+ * `'__all__'` included, is checked against the grant and must name a live
+ * source). Every caller sees live pages in unarchived sources; a remote
+ * caller's `readPolicyOpts` policy goes through `pageReadFilter` (private
+ * pages, trust floor, quarantine). Like ranked search, find hides the
+ * `resolveHardExcludes` prefixes unless the pattern targets one; the result
+ * names the prefixes it hid.
+ *
+ * The result says whether it is complete: `total` counts every match in
+ * scope, and `complete: false` means the limit cut the list.
+ */
+import { clampSearchLimit } from '../engine.ts';
+import { hiddenPrefixesFor, parseFindPattern, type FindPattern } from '../page-find.ts';
+import { resolveHardExcludes } from '../search/source-boost.ts';
+import type { Operation, OperationContext } from './contract.ts';
+import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam, readPolicyOpts } from './context.ts';
+import { invalidParam, paramUse } from './op-fix.ts';
+
+export const FIND_PAGES_DEFAULT_LIMIT = 50;
+/** Hard caps: a find is a lookup, not an export (`list_pages` pages through everything). */
+export const FIND_PAGES_LOCAL_MAX_LIMIT = 500;
+export const FIND_PAGES_REMOTE_MAX_LIMIT = 100;
+
+function parseTypes(ctx: OperationContext, p: Record<string, unknown>): string[] | undefined {
+ const raw: unknown[] = [];
+ for (const key of ['type', 'types'] as const) {
+ const value = p[key];
+ if (value === undefined || value === null) continue;
+ if (Array.isArray(value)) raw.push(...value);
+ else if (typeof value === 'string') raw.push(...value.split(','));
+ else raw.push(value);
+ }
+ if (raw.some((type) => typeof type !== 'string')) {
+ throw invalidParam(ctx, 'find_pages', 'types', 'find_pages: types must be page-type strings.', { example: ctx.remote === false ? '["person","company"]' : ['person', 'company'] });
+ }
+ const types = [...new Set((raw as string[]).map((type) => type.trim()).filter(Boolean))];
+ return types.length > 0 ? types : undefined;
+}
+
+const find_pages: Operation = {
+ name: 'find_pages',
+ mutating: false,
+ idempotent: true,
+ outputRedaction: 'retrieval',
+ description:
+ "Find pages by name or path (what ls/find would answer), sorted by slug. pattern: a glob ('people/*acme*') matched against slug or source path, " +
+ "a slug prefix ('companies/acme'), or a plain name ('acme', a case-insensitive substring of the title or the slug's last segment). " +
+ 'Returns slug, source_id, type, title, source_path and updated_at per page, total matches in scope, and complete (false when limit cut the list).',
+ params: {
+ pattern: { type: 'string', required: true, description: "Glob, slug prefix or name." },
+ type: { type: 'string', description: 'Page type, or several comma-separated.' },
+ types: { type: 'array', items: { type: 'string' }, description: "Page types, e.g. ['person']." },
+ limit: { type: 'number', description: `Max rows (default ${FIND_PAGES_DEFAULT_LIMIT}; max ${FIND_PAGES_LOCAL_MAX_LIMIT}, remote ${FIND_PAGES_REMOTE_MAX_LIMIT}).` },
+ source_id: { type: 'string', description: "One source, or '__all__'." },
+ },
+ handler: async (ctx, p) => {
+ let pattern: FindPattern;
+ try {
+ pattern = parseFindPattern(typeof p.pattern === 'string' ? p.pattern : '');
+ } catch {
+ throw invalidParam(ctx, 'find_pages', 'pattern', `find_pages: pattern is required (e.g. ${paramUse(ctx, 'pattern', 'people/*acme*')}).`, { example: 'people/*acme*' });
+ }
+ const types = parseTypes(ctx, p);
+ const sourceIdParam = parseSourceIdParam(p.source_id, 'find_pages', { allowAll: true });
+ const scope = federatedSearchScope(ctx, sourceIdParam);
+ await assertExplicitSourceLive(ctx, sourceIdParam);
+ const requested = typeof p.limit === 'number' ? p.limit : undefined;
+ const cap = ctx.remote === false ? FIND_PAGES_LOCAL_MAX_LIMIT : FIND_PAGES_REMOTE_MAX_LIMIT;
+ const limit = clampSearchLimit(requested, FIND_PAGES_DEFAULT_LIMIT, cap);
+ const policy = ctx.remote === false ? undefined : await readPolicyOpts(ctx, scope);
+ const hiddenPrefixes = hiddenPrefixesFor(pattern, resolveHardExcludes());
+ const found = await ctx.engine.findPages({
+ pattern,
+ types,
+ limit,
+ ...scope,
+ untrusted: policy && { excludePrivate: policy.excludePrivate, minTrust: policy.minTrust, suppressFlagged: policy.suppressFlagged },
+ excludeSlugPrefixes: hiddenPrefixes,
+ });
+ return {
+ pattern: p.pattern,
+ match: pattern.kind,
+ pages: found.rows,
+ total: found.total,
+ complete: found.total <= found.rows.length,
+ limit,
+ hidden_prefixes: hiddenPrefixes,
+ ...(requested !== undefined && Number.isFinite(requested) && requested > limit ? { limit_clamped_from: requested } : {}),
+ };
+ },
+ scope: 'read',
+ cliHints: { name: 'find', positional: ['pattern'] },
+};
+
+export const findPagesOperations: Operation[] = [find_pages];
diff --git a/src/core/ops/stats-by.ts b/src/core/ops/stats-by.ts
new file mode 100644
index 0000000000..a293e5b722
--- /dev/null
+++ b/src/core/ops/stats-by.ts
@@ -0,0 +1,65 @@
+/**
+ * #7191: `get_stats` grouped mode (`by` / `since` / `collapse_aliases`; CLI
+ * `gbrain stats --by source,type --since 30d --collapse-aliases`). Grouping
+ * rules and the alias collapse: src/core/page-counts.ts; SQL:
+ * src/core/engine-sql/page-lookup.ts. Without any of the three params
+ * `get_stats` returns its unchanged counters (admin.ts).
+ *
+ * Scope is the diagnostic ladder `get_stats` already uses (trusted local:
+ * every source; remote: the caller's grant). Counts cover live pages in
+ * unarchived sources; a remote caller's `readPolicyOpts` policy goes through
+ * `pageReadFilter` (private pages, trust floor, quarantine), like other
+ * remote reads. Stats do not hide the search hard-exclude prefixes: they
+ * count what is stored.
+ */
+import { collapseTypes, groupPageCounts, parseStatsBy, type StatsByResult, type StatsDimension } from '../page-counts.ts';
+import { loadActivePackBestEffort } from '../schema-pack/best-effort.ts';
+import { resolveDateBoundary } from '../search/date-bounds.ts';
+import type { OperationContext, ParamDef } from './contract.ts';
+import { readPolicyOpts } from './context.ts';
+import { invalidParam } from './op-fix.ts';
+
+export const STATS_BY_PARAMS: Record<string, ParamDef> = {
+ by: { type: 'string', description: "Group page counts: 'source', 'type' or 'source,type'." },
+ since: { type: 'string', description: 'Effective date on/after: YYYY-MM-DD or 7d/2w/1y.' },
+ collapse_aliases: { type: 'boolean', description: 'Merge near-duplicate type names; lists each group\'s member types.' },
+};
+
+const blank = (value: unknown): boolean => value === undefined || value === null || (typeof value === 'string' && value.trim() === '');
+
+/** Grouped mode runs when the caller passed any of the grouping params. */
+export function wantsStatsBy(p: Record<string, unknown>): boolean {
+ return !blank(p.by) || !blank(p.since) || p.collapse_aliases === true;
+}
+
+export async function statsBy(
+ ctx: OperationContext,
+ p: Record<string, unknown>,
+ scope: { sourceId?: string; sourceIds?: string[] },
+): Promise<StatsByResult> {
+ let by: StatsDimension[];
+ try {
+ by = parseStatsBy(blank(p.by) ? undefined : p.by);
+ } catch (e) {
+ throw invalidParam(ctx, 'get_stats', 'by', `get_stats: ${(e as Error).message}.`, { example: 'source,type', def: STATS_BY_PARAMS.by });
+ }
+ let since: string | undefined;
+ try {
+ since = resolveDateBoundary(blank(p.since) ? undefined : String(p.since), 'since');
+ } catch (e) {
+ throw invalidParam(ctx, 'get_stats', 'since', `get_stats: ${(e as Error).message}`, { example: '30d', def: STATS_BY_PARAMS.since });
+ }
+ const pack = p.collapse_aliases === true ? (await loadActivePackBestEffort(ctx))?.manifest ?? null : null;
+ const collapseFor = (types: string[]) => (p.collapse_aliases === true ? collapseTypes(types, pack) : null);
+ const groupTypes = by.includes('type') && !by.includes('source')
+ ? (types: string[]) => { const collapse = collapseFor(types); return types.map((type) => collapse?.get(type)?.group ?? type); }
+ : undefined;
+ const policy = ctx.remote === false ? undefined : await readPolicyOpts(ctx, scope);
+ const counts = await ctx.engine.countPagesBy({
+ ...scope,
+ since,
+ untrusted: policy && { excludePrivate: policy.excludePrivate, minTrust: policy.minTrust, suppressFlagged: policy.suppressFlagged },
+ }, groupTypes);
+ const collapse = collapseFor([...new Set(counts.bySourceType.map((row) => row.type))]);
+ return groupPageCounts(counts, { by, since: since ?? null, collapse });
+}
diff --git a/src/core/page-counts.ts b/src/core/page-counts.ts
new file mode 100644
index 0000000000..76c0a73656
--- /dev/null
+++ b/src/core/page-counts.ts
@@ -0,0 +1,164 @@
+/**
+ * #7191: `gbrain stats --by source,type [--since <date>] [--collapse-aliases]`
+ * (the `get_stats` op's `by` / `since` / `collapse_aliases` params): page
+ * counts grouped by source and type, the counts agents otherwise take with
+ * `grep -c`, `wc` or SQL.
+ *
+ * The engine returns live page counts per (source, type) plus raw and
+ * distinct-slug totals (`BrainEngine.countPagesBy`); this module groups them.
+ * A slug present in two sources (a cross-source twin) is one distinct slug:
+ * with `--by source` each source counts its own pages, and every other
+ * grouping reports `distinct_slugs` next to the raw page count, so twins are
+ * never silently counted twice.
+ *
+ * `--collapse-aliases` groups near-duplicate type names. The active schema
+ * pack decides first (a declared type stays itself, a declared alias joins
+ * its canonical type). A type the pack does not declare is normalized: last
+ * path segment, lower case, plural to singular (`media/Transcripts` ->
+ * `transcript`). If the normalized name ends in `-<name>` or `_<name>` where
+ * `<name>` is a declared type or another group, it joins that group
+ * (`audio-transcript` -> `transcript`). Every group lists its member types
+ * with the rule that put each one there, so the collapse is never silent.
+ */
+import { classifyStoredType, type TypeUsagePack } from './schema-pack/type-usage.ts';
+import type { UntrustedReadPolicy } from './page-find.ts';
+
+export const STATS_DIMENSIONS = ['source', 'type'] as const;
+export type StatsDimension = typeof STATS_DIMENSIONS[number];
+
+export interface PageCountQuery {
+ sourceId?: string;
+ sourceIds?: string[];
+ /** Inclusive lower bound on the effective date (`effective_date`, else `updated_at`, else `created_at`). */
+ since?: string;
+ untrusted?: UntrustedReadPolicy;
+}
+
+/** Maps the distinct types the engine saw to their group keys (same order). */
+export type TypeGrouper = (types: string[]) => string[];
+
+export interface PageCounts {
+ bySourceType: Array<{ source_id: string; type: string; pages: number }>;
+ /** Raw and distinct-slug counts per group key; empty unless a grouper was passed. */
+ byTypeGroup: Array<{ group: string; pages: number; distinct_slugs: number }>;
+ total: { pages: number; distinct_slugs: number };
+}
+
+export type TypeCollapseRule = 'exact' | 'pack_alias' | 'normalized' | 'suffix';
+
+export interface TypeMember {
+ type: string;
+ pages: number;
+ via: TypeCollapseRule;
+}
+
+export interface StatsByGroup {
+ source_id?: string;
+ type?: string;
+ pages: number;
+ distinct_slugs?: number;
+ member_types?: TypeMember[];
+}
+
+export interface StatsByResult {
+ schema_version: 1;
+ by: StatsDimension[];
+ since: string | null;
+ collapse_aliases: boolean;
+ total_pages: number;
+ distinct_slugs: number;
+ groups: StatsByGroup[];
+}
+
+/** `'source,type'` (or an array) to dimensions; throws with a message naming the bad value. */
+export function parseStatsBy(raw: unknown): StatsDimension[] {
+ if (raw === undefined || raw === null) return [];
+ const parts = Array.isArray(raw) ? raw : typeof raw === 'string' ? raw.split(',') : null;
+ if (parts === null || parts.some((part) => typeof part !== 'string')) throw new Error('by must be a comma-separated list of: source, type');
+ const dims = [...new Set((parts as string[]).map((part) => part.trim().toLowerCase()).filter(Boolean))];
+ const bad = dims.filter((dim) => !(STATS_DIMENSIONS as readonly string[]).includes(dim));
+ if (bad.length) throw new Error(`by: unknown dimension ${bad.map((dim) => JSON.stringify(dim)).join(', ')}; use source, type or source,type`);
+ return STATS_DIMENSIONS.filter((dim) => dims.includes(dim));
+}
+
+const singular = (word: string): string => {
+ if (word.length > 4 && word.endsWith('ies')) return `${word.slice(0, -3)}y`;
+ if (word.length > 3 && word.endsWith('s') && !/(ss|is|us)$/.test(word)) return word.slice(0, -1);
+ return word;
+};
+
+/** The documented fallback normalization for a type the pack does not declare. */
+export function normalizeTypeName(type: string): string {
+ return singular(type.trim().toLowerCase().split('/').filter(Boolean).pop() ?? '');
+}
+
+/** Group key and rule for each stored type (see the module comment for the rules). */
+export function collapseTypes(types: readonly string[], pack: TypeUsagePack | null): Map<string, { group: string; via: TypeCollapseRule }> {
+ const classify = (name: string) => (pack ? classifyStoredType(name, pack) : { kind: 'undeclared' as const });
+ const out = new Map<string, { group: string; via: TypeCollapseRule; declared: boolean }>();
+ for (const type of types) {
+ const direct = classify(type);
+ if (direct.kind === 'canonical') { out.set(type, { group: type, via: 'exact', declared: true }); continue; }
+ if (direct.kind === 'alias_of') { out.set(type, { group: direct.canonical, via: 'pack_alias', declared: true }); continue; }
+ const norm = normalizeTypeName(type) || type;
+ const viaNorm = classify(norm);
+ const group = viaNorm.kind === 'alias_of' ? viaNorm.canonical : norm;
+ out.set(type, { group, via: group === type ? 'exact' : 'normalized', declared: viaNorm.kind !== 'undeclared' });
+ }
+ const known = new Set([...out.values()].map((entry) => entry.group));
+ for (const pageType of pack?.page_types ?? []) known.add(pageType.name);
+ for (const entry of out.values()) {
+ if (entry.declared) continue;
+ const tail = entry.group.split(/[-_]/).pop() ?? '';
+ if (tail && tail !== entry.group && known.has(tail)) Object.assign(entry, { group: tail, via: 'suffix' });
+ }
+ return new Map([...out].map(([type, { group, via }]) => [type, { group, via }]));
+}
+
+const byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
+
+/** Group engine counts into the `get_stats` grouped result. */
+export function groupPageCounts(
+ counts: PageCounts,
+ opts: { by: StatsDimension[]; since: string | null; collapse: Map<string, { group: string; via: TypeCollapseRule }> | null },
+): StatsByResult {
+ const bySource = opts.by.includes('source');
+ const byType = opts.by.includes('type');
+ const groupOf = (type: string) => opts.collapse?.get(type)?.group ?? type;
+ const groups = new Map<string, StatsByGroup & { members: Map<string, TypeMember> }>();
+ if (opts.by.length > 0) {
+ for (const row of counts.bySourceType) {
+ const type = byType ? groupOf(row.type) : undefined;
+ const key = JSON.stringify([bySource ? row.source_id : null, type ?? null]);
+ let group = groups.get(key);
+ if (!group) {
+ group = { ...(bySource ? { source_id: row.source_id } : {}), ...(byType ? { type } : {}), pages: 0, members: new Map() };
+ groups.set(key, group);
+ }
+ group.pages += row.pages;
+ if (opts.collapse && byType) {
+ const member = group.members.get(row.type) ?? { type: row.type, pages: 0, via: opts.collapse.get(row.type)?.via ?? 'exact' };
+ member.pages += row.pages;
+ group.members.set(row.type, member);
+ }
+ }
+ }
+ const distinct = new Map(counts.byTypeGroup.map((row) => [row.group, row.distinct_slugs]));
+ const out: StatsByGroup[] = [...groups.values()].map(({ members, ...group }) => ({
+ ...group,
+ ...(byType && !bySource ? { distinct_slugs: distinct.get(group.type!) ?? group.pages } : {}),
+ ...(opts.collapse && byType
+ ? { member_types: [...members.values()].sort((a, b) => b.pages - a.pages || byText(a.type, b.type)) }
+ : {}),
+ }));
+ out.sort((a, b) => byText(a.source_id ?? '', b.source_id ?? '') || b.pages - a.pages || byText(a.type ?? '', b.type ?? ''));
+ return {
+ schema_version: 1,
+ by: opts.by,
+ since: opts.since,
+ collapse_aliases: opts.collapse !== null,
+ total_pages: counts.total.pages,
+ distinct_slugs: counts.total.distinct_slugs,
+ groups: out,
+ };
+}
diff --git a/src/core/page-find.ts b/src/core/page-find.ts
new file mode 100644
index 0000000000..6b79f603f1
--- /dev/null
+++ b/src/core/page-find.ts
@@ -0,0 +1,89 @@
+/**
+ * #7191: `gbrain find` / `find_pages`: find pages by name or path, the
+ * lookups agents otherwise do with `ls` and `find`.
+ *
+ * One pattern, three forms, decided by its shape:
+ *
+ * glob contains `*` or `?` matched whole against the slug or the
+ * source path (`people/*acme*`, `*.md`)
+ * prefix contains `/` a slug or source-path prefix
+ * (`companies/acme`)
+ * name anything else a substring of the title or of the slug's
+ * last segment (`acme`)
+ *
+ * Every form is case-insensitive and compiles to one ILIKE pattern, so the
+ * trigram indexes on `pages.slug` and `pages.title` can serve it on both
+ * engines (pg_trgm reads the default `\` escape and needs a literal run of
+ * three characters). LIKE metacharacters in the user text are escaped: `%`
+ * and `_` match themselves.
+ */
+
+import { escapeLikePattern } from './search/sql-ranking.ts';
+import type { PageReadScope } from './types.ts';
+
+/**
+ * The read policy of an untrusted (remote) caller, applied through
+ * `pageReadFilter(..., live = true)`: private pages, the trust floor,
+ * quarantine, soft deletes and archived sources. Absent for the trusted local
+ * CLI, which sees every live page in an unarchived source.
+ */
+export type UntrustedReadPolicy = Pick<PageReadScope, 'excludePrivate' | 'minTrust' | 'suppressFlagged'>;
+
+export type FindPatternKind = 'glob' | 'prefix' | 'name';
+
+export interface FindPattern {
+ kind: FindPatternKind;
+ /** ILIKE pattern with `\` escapes. */
+ like: string;
+ /** The literal text before the first wildcard (empty for a name). */
+ lead: string;
+}
+
+/**
+ * The ranked-search hard-exclude prefixes (`resolveHardExcludes`: `test/`,
+ * `attachments/`, `.raw/` and GBRAIN_SEARCH_EXCLUDE) that a find hides. A
+ * pattern whose literal lead is inside one of them asks for it, so that
+ * prefix stays visible (`gbrain find 'attachments/*'`).
+ */
+export function hiddenPrefixesFor(pattern: FindPattern, excluded: readonly string[]): string[] {
+ const lead = pattern.lead.toLowerCase();
+ return excluded.filter((prefix) => !lead.startsWith(prefix.toLowerCase()));
+}
+
+export interface FindPagesQuery {
+ pattern: FindPattern;
+ types?: string[];
+ limit: number;
+ sourceId?: string;
+ sourceIds?: string[];
+ untrusted?: UntrustedReadPolicy;
+ /** Hidden slug prefixes (`resolveHardExcludes`, as ranked search). */
+ excludeSlugPrefixes: string[];
+}
+
+export interface FoundPage {
+ slug: string;
+ source_id: string;
+ type: string;
+ title: string;
+ source_path: string | null;
+ updated_at: string;
+}
+
+export interface FoundPages {
+ rows: FoundPage[];
+ /** Every page the pattern matched in scope, before the limit. */
+ total: number;
+}
+
+/** Classify and compile a find pattern; throws on an empty one. */
+export function parseFindPattern(raw: string): FindPattern {
+ const text = raw.trim().replace(/^(\.\/)+/, '').replace(/^\/+/, '');
+ if (!text) throw new Error('find pattern is empty');
+ if (/[*?]/.test(text)) {
+ const like = [...text].map((c) => (c === '*' ? '%' : c === '?' ? '_' : escapeLikePattern(c))).join('');
+ return { kind: 'glob', like, lead: text.split(/[*?]/)[0]! };
+ }
+ if (text.includes('/')) return { kind: 'prefix', like: `${escapeLikePattern(text)}%`, lead: text };
+ return { kind: 'name', like: `%${escapeLikePattern(text)}%`, lead: '' };
+}
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 066d197824..ba95c765f9 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -143,6 +143,9 @@ import { scopedRead, unscopedExecutor } from './engine-sql/brands.ts';
import * as codeEdgesImpl from './engine-sql/code-edges.ts';
import { getEdgesByChunk as getEdgesByChunkPglite, type PgliteCodeEdgesDeps } from './pglite-engine/code-edges.ts';
import * as salienceImpl from './engine-sql/salience.ts';
+import * as pageLookupImpl from './engine-sql/page-lookup.ts';
+import type { FindPagesQuery, FoundPages } from './page-find.ts';
+import type { PageCountQuery, PageCounts, TypeGrouper } from './page-counts.ts';
import * as healthImpl from './engine-sql/health.ts';
import { resolveEntityTypes } from './schema-pack/entity-types.ts';
import * as pagesImpl from './engine-sql/pages.ts';
@@ -1352,6 +1355,12 @@ export class PGLiteEngine implements BrainEngine {
async listPages(filters?: PageFilters): Promise<Page[]> {
return plannerRead(this, this._pageTransaction, () => pagesImpl.listPages(scopedRead(this.engineSql), filters));
}
+ async findPages(query: FindPagesQuery): Promise<FoundPages> {
+ return plannerRead(this, this._pageTransaction, () => pageLookupImpl.findPages(scopedRead(this.engineSql), query));
+ }
+ async countPagesBy(query: PageCountQuery, groupTypes?: TypeGrouper): Promise<PageCounts> {
+ return plannerRead(this, this._pageTransaction, () => pageLookupImpl.countPagesBy(scopedRead(this.engineSql), query, groupTypes));
+ }
async getAllSlugs(opts?: { sourceId?: string }): Promise<Set<string>> {
return pagesImpl.getAllSlugs(scopedRead(this.engineSql), opts);
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af1b260aba..e46eb25c7d 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -130,6 +130,9 @@ import * as factsImpl from './engine-sql/facts.ts';
import * as takesImpl from './engine-sql/takes.ts';
import * as codeEdgesImpl from './engine-sql/code-edges.ts';
import * as salienceImpl from './engine-sql/salience.ts';
+import * as pageLookupImpl from './engine-sql/page-lookup.ts';
+import type { FindPagesQuery, FoundPages } from './page-find.ts';
+import type { PageCountQuery, PageCounts, TypeGrouper } from './page-counts.ts';
import * as healthImpl from './engine-sql/health.ts';
import { resolveEntityTypes } from './schema-pack/entity-types.ts';
import * as pagesImpl from './engine-sql/pages.ts';
@@ -933,6 +936,12 @@ export class PostgresEngine implements BrainEngine {
async listPages(filters?: PageFilters): Promise<Page[]> {
return this.withScopedReadTransaction(filters?.sourceIds, filters?.sourceId, tx => pagesImpl.listPages(scopedRead(this.engineSqlOn(tx)), filters));
}
+ async findPages(query: FindPagesQuery): Promise<FoundPages> {
+ return this.withScopedReadTransaction(query.sourceIds, query.sourceId, tx => pageLookupImpl.findPages(scopedRead(this.engineSqlOn(tx)), query), query.untrusted ? { alwaysTransaction: true, jitOff: true } : undefined);
+ }
+ async countPagesBy(query: PageCountQuery, groupTypes?: TypeGrouper): Promise<PageCounts> {
+ return this.withScopedReadTransaction(query.sourceIds, query.sourceId, tx => pageLookupImpl.countPagesBy(scopedRead(this.engineSqlOn(tx)), query, groupTypes), query.untrusted ? { alwaysTransaction: true, jitOff: true } : undefined);
+ }
async getAllSlugs(opts?: { sourceId?: string }): Promise<Set<string>> {
return this.withScopedReadTransaction(undefined, opts?.sourceId, tx => pagesImpl.getAllSlugs(scopedRead(this.engineSqlOn(tx)), opts));
diff --git a/test/e2e/page-lookup-7191.test.ts b/test/e2e/page-lookup-7191.test.ts
new file mode 100644
index 0000000000..e9768a1529
--- /dev/null
+++ b/test/e2e/page-lookup-7191.test.ts
@@ -0,0 +1,2 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+await registerPostgresTests(() => import('../page-lookup-7191.test.ts'));
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 03ee18d1ca..72e85b99c5 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -44,6 +44,8 @@
" delete <slug> Delete a page",
" list [--type T] [--tag T] [--limit N]",
" List pages",
+ " find <glob|prefix|name> [--type T] [--source S] [--limit N]",
+ " Find pages by slug, path or title",
"",
"SEARCH",
" search <query> Keyword search (tsvector)",
@@ -189,6 +191,8 @@
"",
"ADMIN",
" stats Brain statistics",
+ " stats --by source,type [--since 30d] [--collapse-aliases]",
+ " Live page counts per source and type",
" health Brain health dashboard",
" history <slug> [--json] Page version history",
" revert <slug> <version-id> Revert to version",
@@ -269,6 +273,8 @@
" delete <slug> Delete a page",
" list [--type T] [--tag T] [--limit N]",
" List pages",
+ " find <glob|prefix|name> [--type T] [--source S] [--limit N]",
+ " Find pages by slug, path or title",
"",
"SEARCH",
" search <query> Keyword search (tsvector)",
@@ -414,6 +420,8 @@
"",
"ADMIN",
" stats Brain statistics",
+ " stats --by source,type [--since 30d] [--collapse-aliases]",
+ " Live page counts per source and type",
" health Brain health dashboard",
" history <slug> [--json] Page version history",
" revert <slug> <version-id> Revert to version",
@@ -494,6 +502,8 @@
" delete <slug> Delete a page",
" list [--type T] [--tag T] [--limit N]",
" List pages",
+ " find <glob|prefix|name> [--type T] [--source S] [--limit N]",
+ " Find pages by slug, path or title",
"",
"SEARCH",
" search <query> Keyword search (tsvector)",
@@ -639,6 +649,8 @@
"",
"ADMIN",
" stats Brain statistics",
+ " stats --by source,type [--since 30d] [--collapse-aliases]",
+ " Live page counts per source and type",
" health Brain health dashboard",
" history <slug> [--json] Page version history",
" revert <slug> <version-id> Revert to version",
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index aa450155a4..04c86967ed 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": 255041,
+ "stdoutSha256": "4c77e2454ed33590a968e7c91995443d31a5c2d7b94a69822f28f5ea84a876da",
"toolNames": [
"remember",
"entity",
@@ -17,6 +17,7 @@
"purge_deleted_pages",
"capture",
"fetch",
+ "find_pages",
"edit_page",
"append_page",
"put_pages",
@@ -1012,6 +1013,53 @@
},
"scope": "read"
},
+ {
+ "description": "Find pages by name or path (what ls/find would answer), sorted by slug. pattern: a glob ('people/*acme*') matched against slug or source path, a slug prefix ('companies/acme'), or a plain name ('acme', a case-insensitive substring of the title or the slug's last segment). Returns slug, source_id, type, title, source_path and updated_at per page, total matches in scope, and complete (false when limit cut the list).",
+ "idempotent": true,
+ "local_only": false,
+ "mutating": false,
+ "name": "find_pages",
+ "parameters": {
+ "limit": "number?",
+ "pattern": "string",
+ "source_id": "string?",
+ "type": "string?",
+ "types": "array?"
+ },
+ "required_scopes": [],
+ "schema": {
+ "properties": {
+ "limit": {
+ "description": "Max rows (default 50; max 500, remote 100).",
+ "type": "number"
+ },
+ "pattern": {
+ "description": "Glob, slug prefix or name.",
+ "type": "string"
+ },
+ "source_id": {
+ "description": "One source, or '__all__'.",
+ "type": "string"
+ },
+ "type": {
+ "description": "Page type, or several comma-separated.",
+ "type": "string"
+ },
+ "types": {
+ "description": "Page types, e.g. ['person'].",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "pattern"
+ ],
+ "type": "object"
+ },
+ "scope": "read"
+ },
{
"description": "Change part of a page: prefer this over put_page for small changes. expected_revision: from get_page include_content:true. Each old_text must match exactly once (in `within` if set); applied in order, all or none. Stale revision: revision_conflict.",
"idempotent": true,
@@ -2750,15 +2798,32 @@
"scope": "read"
},
{
- "description": "Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant.",
+ "description": "Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant. Pass by (source, type or source,type), since or collapse_aliases for live page counts per group instead, with distinct-slug totals so cross-source twins are not double counted.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "get_stats",
- "parameters": {},
+ "parameters": {
+ "by": "string?",
+ "collapse_aliases": "boolean?",
+ "since": "string?"
+ },
"required_scopes": [],
"schema": {
- "properties": {},
+ "properties": {
+ "by": {
+ "description": "Group page counts: 'source', 'type' or 'source,type'.",
+ "type": "string"
+ },
+ "collapse_aliases": {
+ "description": "Merge near-duplicate type names; lists each group's member types.",
+ "type": "boolean"
+ },
+ "since": {
+ "description": "Effective date on/after: YYYY-MM-DD or 7d/2w/1y.",
+ "type": "string"
+ }
+ },
"required": [],
"type": "object"
},
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 99e549e65f..bb82ebd1ae 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -29,6 +29,7 @@
"consolidateFact",
"countChunklessPagesWithContent",
"countKeywordPages",
+ "countPagesBy",
"countStaleChunks",
"countStaleFrontmatterKeyPages",
"countStalePagesForExtraction",
@@ -56,6 +57,7 @@
"findDuplicatePages",
"findOntologyConflicts",
"findOrphanPages",
+ "findPages",
"findTrajectory",
"flipBodyGeneration",
"getAdjacencyBoosts",
@@ -231,6 +233,7 @@
"consolidateFact",
"countChunklessPagesWithContent",
"countKeywordPages",
+ "countPagesBy",
"countStaleChunks",
"countStaleFrontmatterKeyPages",
"countStalePagesForExtraction",
@@ -260,6 +263,7 @@
"findDuplicatePages",
"findOntologyConflicts",
"findOrphanPages",
+ "findPages",
"findTrajectory",
"flipBodyGeneration",
"getAdjacencyBoosts",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 3cb9b0b931..7878a6a09b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -68,6 +68,7 @@
"consolidateFact: (id: number, takeId: number) => Promise<void>",
"countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",
"countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>",
+ "countPagesBy: (query: PageCountQuery, groupTypes?: TypeGrouper) => Promise<PageCounts>",
"countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"countStaleFrontmatterKeyPages: (opts: { sourceIds: string[]; }) => Promise<Array<{ source_id: string; n: number; }>>",
"countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; held?: \"exclude\" | \"only\"; }) => Promise<number>",
@@ -93,6 +94,7 @@
"findDuplicatePages?: ((sourceId: string, inputs: ReadonlyArray<{ hash: string; frontmatterId?: string | null; excludeSlug?: string; }>) => Promise<Array<{ slug: string; id: number; } | null>>) | undefined",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
+ "findPages: (query: FindPagesQuery) => Promise<FoundPages>",
"findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>",
"flipBodyGeneration: (input: BodyFlipInput) => Promise<BodyFlipResult>",
"getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>",
@@ -1069,6 +1071,7 @@
"consolidateFact: (id: number, takeId: number) => Promise<void>",
"countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",
"countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>",
+ "countPagesBy: (query: PageCountQuery, groupTypes?: TypeGrouper) => Promise<PageCounts>",
"countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"countStaleFrontmatterKeyPages: (opts: { sourceIds: string[]; }) => Promise<{ source_id: string; n: number; }[]>",
"countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; held?: \"exclude\" | \"only\"; }) => Promise<number>",
@@ -1095,6 +1098,7 @@
"findDuplicatePages: (sourceId: string, inputs: Parameters<typeof findDuplicatePages>[2]) => Promise<({ slug: string; id: number; } | null)[]>",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
+ "findPages: (query: FindPagesQuery) => Promise<FoundPages>",
"findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>",
"flipBodyGeneration: (input: BodyFlipInput) => Promise<BodyFlipResult>",
"getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>",
@@ -3373,6 +3377,7 @@
"consolidateFact: (id: number, takeId: number) => Promise<void>",
"countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",
"countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>",
+ "countPagesBy: (query: PageCountQuery, groupTypes?: TypeGrouper) => Promise<PageCounts>",
"countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"countStaleFrontmatterKeyPages: (opts: { sourceIds: string[]; }) => Promise<Array<{ source_id: string; n: number; }>>",
"countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; held?: \"exclude\" | \"only\"; }) => Promise<number>",
@@ -3398,6 +3403,7 @@
"findDuplicatePages?: ((sourceId: string, inputs: ReadonlyArray<{ hash: string; frontmatterId?: string | null; excludeSlug?: string; }>) => Promise<Array<{ slug: string; id: number; } | null>>) | undefined",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: PageReadScope & { sourceId?: string; sourceIds?: string[]; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
+ "findPages: (query: FindPagesQuery) => Promise<FoundPages>",
"findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>",
"flipBodyGeneration: (input: BodyFlipInput) => Promise<BodyFlipResult>",
"getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>",
@@ -6656,6 +6662,7 @@
"consolidateFact: (id: number, takeId: number) => Promise<void>",
"countChunklessPagesWithContent: (opts?: { sourceId?: string; }) => Promise<number>",
"countKeywordPages: (query: string, opts?: SearchOpts & { timeoutMs?: number; }) => Promise<number>",
+ "countPagesBy: (query: PageCountQuery, groupTypes?: TypeGrouper) => Promise<PageCounts>",
"countStaleChunks: (opts?: { sourceId?: string; signature?: string; includeNullSignature?: boolean; }) => Promise<number>",
"countStaleFrontmatterKeyPages: (opts: { sourceIds: string[]; }) => Promise<{ source_id: string; n: number; }[]>",
"countStalePagesForExtraction: (opts?: { sourceId?: string; versionTs?: string; attendance?: \"exclude\" | \"blocked\"; held?: \"exclude\" | \"only\"; }) => Promise<number>",
@@ -6682,6 +6689,7 @@
"findDuplicatePages: (sourceId: string, inputs: Parameters<typeof pagesImpl.findDuplicatePages>[2]) => Promise<({ slug: string; id: number; } | null)[]>",
"findOntologyConflicts: (opts?: PageReadScope & { minConfidence?: number; visibility?: OntologyReadOpts[\"visibility\"]; }) => Promise<OntologyConflict[]>",
"findOrphanPages: (opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; mode?: \"inbound\" | \"islanded\"; }) => Promise<Array<{ slug: string; title: string; domain: string | null; type?: string | null; quarantined?: boolean; source_id?: string; }>>",
+ "findPages: (query: FindPagesQuery) => Promise<FoundPages>",
"findTrajectory: (opts: TrajectoryOpts) => Promise<TrajectoryPoint[]>",
"flipBodyGeneration: (input: BodyFlipInput) => Promise<BodyFlipResult>",
"getAdjacencyBoosts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, AdjacencyRow>>",
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index a0cd35f1de..4991f4ab1c 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -19,7 +19,7 @@
"out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 5,
"out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 9,
"out-of-scope:stats-health (brain-wide aggregates)": 2,
- "pages": 38,
+ "pages": 40,
"salience": 5,
"sources": 2,
"tags": 3,
@@ -48,6 +48,7 @@
"constructor": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
"countChunklessPagesWithContent": "chunks",
"countKeywordPages": "out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)",
+ "countPagesBy": "pages",
"countStaleChunks": "chunks",
"countStaleFrontmatterKeyPages": "pages",
"countStalePagesForExtraction": "pages",
@@ -77,6 +78,7 @@
"findDuplicatePages": "pages",
"findOntologyConflicts": "facts",
"findOrphanPages": "links",
+ "findPages": "pages",
"findTrajectory": "facts",
"flipBodyGeneration": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",
"getAdjacencyBoosts": "out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)",
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 83324fa0a8..ab6820067c 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -2918,6 +2918,56 @@
}
},
"pages": {
+ "countPagesBy": {
+ "grouped+since+remote": [
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "prepare": false,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 4,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "totals": [
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 0,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"countStaleFrontmatterKeyPages": {
"default": [
{
@@ -3117,6 +3167,38 @@
}
]
},
+ "findPages": {
+ "glob+types+sourceIds+remote": [
+ {
+ "paramCount": 1,
+ "unsafeOptions": {
+ "prepare": false,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 5,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ],
+ "name": [
+ {
+ "paramCount": 4,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ }
+ ]
+ },
"getAllSlugs": {
"default": [
{
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index 2bd763e822..16345300b9 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -2,6 +2,60 @@
"golden": {
"domain": "pages",
"methods": {
+ "countPagesBy": {
+ "grouped+since+remote": [
+ {
+ "event": "begin",
+ "lane": "tx"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT set_config('jit', $1, true)",
+ "textSha256": "78f6db2efa50e2a77fa5136eed9ecd3939e1cdf280cd713c488292f4d39ce91c"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "string"
+ ],
+ "sql": "SELECT p.source_id, p.type, count(*) AS pages FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.deleted_at IS NULL AND NOT s.archived AND p.source_id = $1 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND COALESCE(p.effective_date, p.updated_at, p.created_at) >= $2::text::timestamptz GROUP BY p.source_id, p.type",
+ "textSha256": "59392b963e454bef730e54f1438ca00274f00cc67238e37689216e99f76f4e00"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "array<>",
+ "array<>",
+ "string",
+ "string"
+ ],
+ "sql": "SELECT m.grp, GROUPING(m.grp) = 1 AS is_total, count(*) AS pages, count(DISTINCT p.slug COLLATE \"C\") AS distinct_slugs FROM pages p JOIN sources s ON s.id = p.source_id JOIN unnest($1::text[], $2::text[]) AS m(type, grp) ON m.type = p.type WHERE p.deleted_at IS NULL AND NOT s.archived AND p.source_id = $3 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND COALESCE(p.effective_date, p.updated_at, p.created_at) >= $4::text::timestamptz GROUP BY GROUPING SETS ((m.grp), ())",
+ "textSha256": "227b4e785a94b61ccf7d279f5466c91a2f9ee4fc17d62a5408094f72900cafdd"
+ },
+ {
+ "event": "commit",
+ "lane": "tx"
+ }
+ ],
+ "totals": [
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT p.source_id, p.type, count(*) AS pages FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.deleted_at IS NULL AND NOT s.archived GROUP BY p.source_id, p.type",
+ "textSha256": "d789e908314ac7e921f66343115b1e1fce961de185e34cee10febbbf907978ca"
+ },
+ {
+ "lane": "pool",
+ "params": [],
+ "sql": "SELECT NULL::text AS grp, true AS is_total, count(*) AS pages, count(DISTINCT p.slug COLLATE \"C\") AS distinct_slugs FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.deleted_at IS NULL AND NOT s.archived",
+ "textSha256": "f8ee8f7f12fe046b7a894b0850b3ba4018333437ce9c71b6725ff93e9445e5d9"
+ }
+ ]
+ },
"countStaleFrontmatterKeyPages": {
"default": [
{
@@ -233,6 +287,51 @@
}
]
},
+ "findPages": {
+ "glob+types+sourceIds+remote": [
+ {
+ "event": "begin",
+ "lane": "tx"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT set_config('jit', $1, true)",
+ "textSha256": "78f6db2efa50e2a77fa5136eed9ecd3939e1cdf280cd713c488292f4d39ce91c"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "string",
+ "string",
+ "array<string>",
+ "array<string>",
+ "number"
+ ],
+ "sql": "SELECT p.slug, p.source_id, p.type, p.title, p.source_path, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at, count(*) OVER () AS total FROM pages p JOIN sources s ON s.id = p.source_id WHERE (p.slug ILIKE $1 OR p.source_path ILIKE $2) AND p.deleted_at IS NULL AND NOT s.archived AND p.source_id = ANY($3::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) AND p.type = ANY($4::text[]) AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE '.raw/%') ORDER BY p.slug COLLATE \"C\", p.source_id COLLATE \"C\" LIMIT $5",
+ "textSha256": "0dac08a52c2874ca4ef564ae13f2c4bea9c87a3577f69e50581c968de7eeb84a"
+ },
+ {
+ "event": "commit",
+ "lane": "tx"
+ }
+ ],
+ "name": [
+ {
+ "lane": "pool",
+ "params": [
+ "string",
+ "string",
+ "string",
+ "number"
+ ],
+ "sql": "SELECT p.slug, p.source_id, p.type, p.title, p.source_path, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at, count(*) OVER () AS total FROM pages p JOIN sources s ON s.id = p.source_id WHERE (p.title ILIKE $1 OR (p.slug ILIKE $2 AND regexp_replace(p.slug, '^.*/', '') ILIKE $3)) AND p.deleted_at IS NULL AND NOT s.archived ORDER BY p.slug COLLATE \"C\", p.source_id COLLATE \"C\" LIMIT $4",
+ "textSha256": "1785b39ba6a0a7a4bd2e595fe30910fa82369c44286b4a0f6eda3dc3d8abbbd5"
+ }
+ ]
+ },
"getAllSlugs": {
"default": [
{
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index faf4d6ffbc..4128dd080e 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -87,6 +87,7 @@ export const DOMAIN_OF: Record<string, string> = {
'putPage': 'pages', 'deletePage': 'pages', 'deletePages': 'pages', 'resolveSlugsByPaths': 'pages',
'softDeletePage': 'pages', 'softDeletePages': 'pages', 'restorePage': 'pages', 'purgeDeletedPages': 'pages',
'refreshPageBody': 'pages', 'updatePageContextualRetrievalState': 'pages', 'listPages': 'pages',
+ 'findPages': 'pages', 'countPagesBy': 'pages',
'getAllSlugs': 'pages', 'listAllPageRefs': 'pages', 'listPrefixSampledPages': 'pages', 'listCorpusSample': 'pages',
'resolveSlugs': 'pages', 'findByTitleFuzzy': 'pages', 'getPageTimestamps': 'pages',
'createVersion': 'pages', 'getVersions': 'pages', 'revertToVersion': 'pages', 'updateSlug': 'pages',
@@ -334,6 +335,14 @@ export const SQL_CASES: SqlCase[] = [
['effective_before', (e) => e.listPages({ effective_before: '2026-01-01' })],
['sort', (e) => e.listPages({ sort: 'slug' })],
]),
+ ...variants('findPages', [
+ ['name', (e) => e.findPages({ pattern: { kind: 'name', like: '%acme%', lead: '' }, limit: 50, excludeSlugPrefixes: [] })],
+ ['glob+types+sourceIds+remote', (e) => e.findPages({ pattern: { kind: 'glob', like: 'people/%acme%', lead: 'people/' }, types: ['person'], limit: 10, sourceIds: SRCS, untrusted: { excludePrivate: true }, excludeSlugPrefixes: ['test/', '.raw/'] })],
+ ]),
+ ...variants('countPagesBy', [
+ ['totals', (e) => e.countPagesBy({})],
+ ['grouped+since+remote', (e) => e.countPagesBy({ sourceId: SRC, since: '2026-01-01', untrusted: { excludePrivate: true } }, (types: string[]) => types)],
+ ]),
...variants('getAllSlugs', [
['default', (e) => e.getAllSlugs()],
['sourceId', (e) => e.getAllSlugs({ sourceId: SRC })],
diff --git a/test/page-find-pattern-7191.test.ts b/test/page-find-pattern-7191.test.ts
new file mode 100644
index 0000000000..1c94f296db
--- /dev/null
+++ b/test/page-find-pattern-7191.test.ts
@@ -0,0 +1,123 @@
+/** #7191: pure pieces of gbrain find / stats --by (pattern forms, --by parsing, alias collapse). */
+import { describe, expect, test } from 'bun:test';
+import { hiddenPrefixesFor, parseFindPattern } from '../src/core/page-find.ts';
+import { collapseTypes, groupPageCounts, normalizeTypeName, parseStatsBy } from '../src/core/page-counts.ts';
+import { formatFindPages, formatStatsBy } from '../src/cli/format-page-lookup.ts';
+
+describe('parseFindPattern', () => {
+ test('a pattern with * or ? is a whole-string glob', () => {
+ expect(parseFindPattern('people/*acme*')).toEqual({ kind: 'glob', like: 'people/%acme%', lead: 'people/' });
+ expect(parseFindPattern('notes/202?-*')).toEqual({ kind: 'glob', like: 'notes/202_-%', lead: 'notes/202' });
+ });
+ test('a pattern with a slash is a prefix', () => {
+ expect(parseFindPattern('companies/acme')).toEqual({ kind: 'prefix', like: 'companies/acme%', lead: 'companies/acme' });
+ expect(parseFindPattern('./companies/')).toEqual({ kind: 'prefix', like: 'companies/%', lead: 'companies/' });
+ expect(parseFindPattern('/companies/acme')).toEqual({ kind: 'prefix', like: 'companies/acme%', lead: 'companies/acme' });
+ });
+ test('anything else is a name substring', () => {
+ expect(parseFindPattern(' acme ')).toEqual({ kind: 'name', like: '%acme%', lead: '' });
+ });
+ test('LIKE metacharacters are escaped in every form', () => {
+ expect(parseFindPattern('100%_x').like).toBe('%100\\%\\_x%');
+ expect(parseFindPattern('a\\b/*').like).toBe('a\\\\b/%');
+ });
+ test('hard-exclude prefixes stay hidden unless the pattern targets one', () => {
+ const excluded = ['test/', 'attachments/', '.raw/'];
+ expect(hiddenPrefixesFor(parseFindPattern('people/*'), excluded)).toEqual(excluded);
+ expect(hiddenPrefixesFor(parseFindPattern('acme'), excluded)).toEqual(excluded);
+ expect(hiddenPrefixesFor(parseFindPattern('test/fixtures'), excluded)).toEqual(['attachments/', '.raw/']);
+ expect(hiddenPrefixesFor(parseFindPattern('Attachments/*.png'), excluded)).toEqual(['test/', '.raw/']);
+ expect(hiddenPrefixesFor(parseFindPattern('*/test/x'), excluded)).toEqual(excluded);
+ });
+ test('an empty pattern throws', () => {
+ expect(() => parseFindPattern(' ')).toThrow();
+ expect(() => parseFindPattern('./')).toThrow();
+ });
+});
+
+describe('parseStatsBy', () => {
+ test('dimensions in canonical order, deduplicated, case-insensitive', () => {
+ expect(parseStatsBy('type,source')).toEqual(['source', 'type']);
+ expect(parseStatsBy(' Source , source ')).toEqual(['source']);
+ expect(parseStatsBy(['type'])).toEqual(['type']);
+ expect(parseStatsBy(undefined)).toEqual([]);
+ });
+ test('an unknown dimension or a non-string throws, naming the value', () => {
+ expect(() => parseStatsBy('source,author')).toThrow(/"author"/);
+ expect(() => parseStatsBy(42)).toThrow();
+ });
+});
+
+describe('type alias collapse', () => {
+ test('normalization: last path segment, lower case, singular', () => {
+ expect(normalizeTypeName('media/Transcripts')).toBe('transcript');
+ expect(normalizeTypeName('companies')).toBe('company');
+ expect(normalizeTypeName('analysis')).toBe('analysis');
+ expect(normalizeTypeName('address')).toBe('address');
+ });
+
+ test('without a pack: normalized names and -suffix joins, each with its rule', () => {
+ const map = collapseTypes(['transcript', 'media/transcript', 'audio-transcript', 'adversary-profile', 'notes'], null);
+ expect(Object.fromEntries(map)).toEqual({
+ 'transcript': { group: 'transcript', via: 'exact' },
+ 'media/transcript': { group: 'transcript', via: 'normalized' },
+ 'audio-transcript': { group: 'transcript', via: 'suffix' },
+ 'adversary-profile': { group: 'adversary-profile', via: 'exact' },
+ 'notes': { group: 'note', via: 'normalized' },
+ });
+ });
+
+ test('the active pack decides first: declared types stay, aliases join their canonical type', () => {
+ const pack = { page_types: [
+ { name: 'person', path_prefixes: ['people/'], aliases: ['researcher'] },
+ { name: 'meeting-note', path_prefixes: ['meetings/'] },
+ { name: 'note', path_prefixes: ['notes/'] },
+ ] };
+ const map = collapseTypes(['researcher', 'person', 'meeting-note', 'Researchers', 'quick-note'], pack);
+ expect(map.get('researcher')).toEqual({ group: 'person', via: 'pack_alias' });
+ expect(map.get('person')).toEqual({ group: 'person', via: 'exact' });
+ expect(map.get('meeting-note')).toEqual({ group: 'meeting-note', via: 'exact' });
+ expect(map.get('Researchers')).toEqual({ group: 'person', via: 'normalized' });
+ expect(map.get('quick-note')).toEqual({ group: 'note', via: 'suffix' });
+ });
+
+ test('groupPageCounts sorts deterministically and reports members only when collapsing', () => {
+ const counts = {
+ bySourceType: [
+ { source_id: 'b', type: 'note', pages: 1 },
+ { source_id: 'a', type: 'note', pages: 2 },
+ { source_id: 'a', type: 'person', pages: 5 },
+ ],
+ byTypeGroup: [],
+ total: { pages: 8, distinct_slugs: 7 },
+ };
+ const r = groupPageCounts(counts, { by: ['source', 'type'], since: null, collapse: null });
+ expect(r.groups).toEqual([
+ { source_id: 'a', type: 'person', pages: 5 },
+ { source_id: 'a', type: 'note', pages: 2 },
+ { source_id: 'b', type: 'note', pages: 1 },
+ ]);
+ expect(r).toMatchObject({ total_pages: 8, distinct_slugs: 7, collapse_aliases: false });
+ expect(groupPageCounts(counts, { by: [], since: null, collapse: null }).groups).toEqual([]);
+ });
+});
+
+describe('CLI renderers', () => {
+ test('find rows are tab-separated with escaped cells', () => {
+ const out = formatFindPages({ complete: true, total: 1, limit: 50, pages: [
+ { slug: 'people/alice-example', source_id: 'source-a', type: 'person', title: 'Alice\tExample', updated_at: '2026-10-01T00:00:00.000000Z' },
+ ] });
+ expect(out).toBe('people/alice-example\tsource-a\tperson\t2026-10-01\tAlice\\tExample\n');
+ expect(formatFindPages({ complete: true, total: 0, limit: 50, pages: [] })).toBe('No pages found.\n');
+ });
+
+ test('grouped stats print totals, a header and collapsed members', () => {
+ const out = formatStatsBy({
+ schema_version: 1, by: ['type'], since: null, collapse_aliases: true, total_pages: 3, distinct_slugs: 2,
+ groups: [{ type: 'transcript', pages: 3, distinct_slugs: 2, member_types: [
+ { type: 'transcript', pages: 2, via: 'exact' }, { type: 'media/transcript', pages: 1, via: 'normalized' },
+ ] }],
+ });
+ expect(out).toBe('Pages: 3 (2 distinct slugs)\n\ntype\tpages\tdistinct_slugs\ntranscript\t3\t2\n = transcript (2, exact), media/transcript (1, normalized)\n');
+ });
+});
diff --git a/test/page-lookup-7191.test.ts b/test/page-lookup-7191.test.ts
new file mode 100644
index 0000000000..21eac09122
--- /dev/null
+++ b/test/page-lookup-7191.test.ts
@@ -0,0 +1,218 @@
+/**
+ * #7191: `find_pages` (gbrain find) and `get_stats` grouped mode on a real
+ * engine: pattern forms, visibility (deleted, archived source, private and
+ * quarantined pages for remote callers), source scoping, type filters, the
+ * limit/complete contract, --by grouping, --since and alias collapse.
+ * Runs on PGLite, and on Postgres too when DATABASE_URL is set
+ * (test/e2e/page-lookup-7191.test.ts registers the Postgres arm).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const findOp = operations.find((op) => op.name === 'find_pages')!;
+const statsOp = operations.find((op) => op.name === 'get_stats')!;
+const getPageOp = operations.find((op) => op.name === 'get_page')!;
+
+for (const backend of testBackends()) {
+ describe(`find_pages + get_stats --by (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ const ctx = (overrides: Partial<OperationContext> = {}): OperationContext => ({
+ engine, config: {} as any, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: '__all__',
+ ...overrides,
+ } as OperationContext);
+ const remote = (allowedSources = ['source-a', 'source-b']): OperationContext =>
+ ctx({ remote: true, sourceId: undefined, auth: { token: 't', clientId: 'c', scopes: ['read', 'admin'], allowedSources } as any });
+ const find = async (c: OperationContext, params: Record<string, unknown>) => findOp.handler(c, params) as Promise<any>;
+ const stats = async (c: OperationContext, params: Record<string, unknown>) => statsOp.handler(c, params) as Promise<any>;
+ const slugs = (r: any) => r.pages.map((p: any) => `${p.source_id}:${p.slug}`);
+
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ __resetPrivateVisibilityCacheForTests();
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-a', 'source-a'), ('source-b', 'source-b'), ('source-old', 'source-old')");
+ const put = (slug: string, type: string, title: string, sourceId: string, extra: Record<string, unknown> = {}) =>
+ engine.putPage(slug, { title, type, compiled_truth: `about ${title}`, frontmatter: extra.frontmatter ?? {}, ...(extra.source_path ? { source_path: extra.source_path } : {}) } as any, { sourceId });
+ await put('people/alice-example', 'person', 'Alice Example', 'source-a', { source_path: 'People/Alice Example.md' });
+ await put('people/charlie-acme', 'person', 'Charlie of Acme', 'source-a');
+ await put('companies/acme-example', 'company', 'Acme Example Inc', 'source-a');
+ await put('companies/acme-example', 'company', 'Acme Example Inc', 'source-b');
+ await put('companies/widget-co', 'company', 'Widget Co', 'source-b');
+ await put('people/private-acme', 'person', 'Private Acme Contact', 'source-a', { frontmatter: { visibility: 'private' } });
+ await put('people/junk-acme', 'person', 'Junk Acme', 'source-a', { frontmatter: { quarantine: { reason: 'junk_pattern', detail: 'x', assessed_at: '2026-01-01T00:00:00Z' } } });
+ await put('people/deleted-acme', 'person', 'Deleted Acme', 'source-a');
+ await engine.softDeletePage('people/deleted-acme', { sourceId: 'source-a' });
+ await put('people/archived-acme', 'person', 'Archived Acme', 'source-old');
+ await engine.executeRaw("UPDATE sources SET archived = true WHERE id = 'source-old'");
+ await put('media/transcripts/call-1', 'media/transcript', 'Call one', 'source-b');
+ await put('transcripts/call-2', 'transcript', 'Call two', 'source-b');
+ await put('transcripts/call-3', 'audio-transcript', 'Call three', 'source-a');
+ await put('notes/100%_literal', 'note', 'Percent literal', 'source-a');
+ await put('notes/100x-other', 'note', 'Other', 'source-a');
+ await engine.executeRaw("UPDATE pages SET effective_date = '2020-01-01T00:00:00Z' WHERE slug = 'companies/widget-co'");
+ await put('test/fixture-acme', 'note', 'Fixture Acme', 'source-b');
+ await put('.raw/acme-sidecar', 'note', 'Raw Acme', 'source-b');
+ await put('atoms/acme-fact', 'atom', 'Acme atom', 'source-b');
+ await put('notes/acme-summary', 'note', 'Acme summary', 'source-a', { frontmatter: { derived_from: 'people/private-acme' } });
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('glob matches slugs and source paths, sorted by slug then source', async () => {
+ const r = await find(ctx(), { pattern: 'people/*acme*' });
+ expect(r.match).toBe('glob');
+ expect(slugs(r)).toEqual(['source-a:people/charlie-acme', 'source-a:people/junk-acme', 'source-a:people/private-acme']);
+ expect(r).toMatchObject({ total: 3, complete: true });
+ expect(slugs(await find(ctx(), { pattern: 'People/Alice*.md' }))).toEqual(['source-a:people/alice-example']);
+ expect(r.pages[0]).toMatchObject({ slug: 'people/charlie-acme', source_id: 'source-a', type: 'person', title: 'Charlie of Acme' });
+ expect(r.pages[0].updated_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);
+ });
+
+ test('slug prefix lists both cross-source twins', async () => {
+ const r = await find(ctx(), { pattern: 'companies/acme' });
+ expect(r.match).toBe('prefix');
+ expect(slugs(r)).toEqual(['source-a:companies/acme-example', 'source-b:companies/acme-example']);
+ });
+
+ test('plain name matches title or the last slug segment, case-insensitively', async () => {
+ const r = await find(ctx(), { pattern: 'ACME' });
+ expect(r.match).toBe('name');
+ expect(slugs(r)).toEqual([
+ 'source-b:atoms/acme-fact', 'source-a:companies/acme-example', 'source-b:companies/acme-example',
+ 'source-a:notes/acme-summary', 'source-a:people/charlie-acme', 'source-a:people/junk-acme', 'source-a:people/private-acme',
+ ]);
+ // "people" is a directory segment, never the last one: no name match.
+ expect((await find(ctx(), { pattern: 'people' })).total).toBe(0);
+ });
+
+ test('LIKE metacharacters in the pattern match literally', async () => {
+ expect(slugs(await find(ctx(), { pattern: 'notes/100%' }))).toEqual(['source-a:notes/100%_literal']);
+ expect(slugs(await find(ctx(), { pattern: '100%_' }))).toEqual(['source-a:notes/100%_literal']);
+ });
+
+ test('soft-deleted pages and archived sources are never listed', async () => {
+ const r = await find(ctx(), { pattern: 'acme', limit: 500 });
+ expect(slugs(r).some((s: string) => s.includes('deleted-acme') || s.includes('archived-acme'))).toBe(false);
+ });
+
+ test('remote callers lose private and quarantined pages; local callers keep them', async () => {
+ expect(slugs(await find(remote(), { pattern: 'people/*acme*' }))).toEqual(['source-a:people/charlie-acme']);
+ expect((await find(ctx(), { pattern: 'people/*acme*' })).total).toBe(3);
+ });
+
+ test('source scoping: explicit source, __all__, and the remote grant', async () => {
+ expect(slugs(await find(ctx(), { pattern: 'companies/*', source_id: 'source-b' }))).toEqual(['source-b:companies/acme-example', 'source-b:companies/widget-co']);
+ expect((await find(ctx(), { pattern: 'companies/*', source_id: '__all__' })).total).toBe(3);
+ expect(slugs(await find(remote(['source-b']), { pattern: 'companies/*' }))).toEqual(['source-b:companies/acme-example', 'source-b:companies/widget-co']);
+ await expect(find(remote(['source-b']), { pattern: 'companies/*', source_id: 'source-a' })).rejects.toMatchObject({ code: 'permission_denied' });
+ await expect(find(ctx(), { pattern: 'x', source_id: 'source-old' })).rejects.toMatchObject({ code: 'unknown_source' });
+ });
+
+ test('type filters: one type, a comma list, and a types array', async () => {
+ expect((await find(ctx(), { pattern: 'acme', type: 'company' })).total).toBe(2);
+ expect((await find(ctx(), { pattern: 'acme', type: 'company,person' })).total).toBe(5);
+ expect((await find(ctx(), { pattern: 'acme', type: 'note' })).total).toBe(1);
+ expect((await find(ctx(), { pattern: '*', types: ['transcript', 'media/transcript'] })).total).toBe(2);
+ });
+
+ test('limit truncates with complete: false and the full total; remote limit is capped', async () => {
+ const r = await find(ctx(), { pattern: 'acme', limit: 2 });
+ expect(r.pages).toHaveLength(2);
+ expect(r).toMatchObject({ total: 7, complete: false, limit: 2 });
+ const capped = await find(remote(), { pattern: 'acme', limit: 5000 });
+ expect(capped).toMatchObject({ limit: 100, limit_clamped_from: 5000, complete: true });
+ });
+
+ test('the ranked-search hard excludes stay hidden unless the pattern targets them', async () => {
+ const r = await find(ctx(), { pattern: 'acme', limit: 500 });
+ expect(slugs(r).some((s: string) => s.includes('test/') || s.includes('.raw/'))).toBe(false);
+ expect(r.hidden_prefixes).toEqual(expect.arrayContaining(['test/', '.raw/']));
+ const tests = await find(ctx(), { pattern: 'test/*' });
+ expect(slugs(tests)).toEqual(['source-b:test/fixture-acme']);
+ expect(tests.hidden_prefixes).not.toContain('test/');
+ });
+
+ test('remote=true: find never returns a page the untrusted caller cannot read', async () => {
+ const unreadable = ['people/private-acme', 'people/junk-acme', 'atoms/acme-fact', 'notes/acme-summary', 'people/deleted-acme', 'people/archived-acme'];
+ for (const pattern of ['*', 'acme', 'people/', 'atoms/*', 'notes/*']) {
+ const r = await find(remote(['source-a', 'source-b', 'source-old']), { pattern, limit: 100 });
+ expect(r.pages.filter((p: any) => unreadable.includes(p.slug))).toEqual([]);
+ for (const p of r.pages) {
+ const page = await getPageOp.handler(remote(['source-a', 'source-b', 'source-old']), { slug: p.slug, source_id: p.source_id }) as any;
+ expect(page.slug).toBe(p.slug);
+ }
+ }
+ // The trusted local view still lists the private, derived and atom pages (deleted and archived never).
+ const local = slugs(await find(ctx(), { pattern: 'acme', limit: 500 }));
+ expect(local).toEqual(expect.arrayContaining(['source-a:people/private-acme', 'source-b:atoms/acme-fact', 'source-a:notes/acme-summary']));
+ });
+
+ test('an empty pattern is invalid_params', async () => {
+ await expect(find(ctx(), { pattern: ' ' })).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+
+ test('get_stats without grouping params keeps its counters', async () => {
+ const r = await stats(ctx(), {});
+ expect(r).toHaveProperty('page_count');
+ expect(r).toHaveProperty('pages_by_type');
+ expect(r).not.toHaveProperty('groups');
+ });
+
+ test('--by source,type counts each source\'s own live pages', async () => {
+ const r = await stats(ctx(), { by: 'source,type' });
+ expect(r.by).toEqual(['source', 'type']);
+ const row = (s: string, t: string) => r.groups.find((g: any) => g.source_id === s && g.type === t);
+ expect(row('source-a', 'company').pages).toBe(1);
+ expect(row('source-b', 'company').pages).toBe(2);
+ expect(row('source-b', 'atom').pages).toBe(1);
+ expect(row('source-a', 'person').pages).toBe(4);
+ expect(r.groups.some((g: any) => g.source_id === 'source-old')).toBe(false);
+ expect(r.groups[0].distinct_slugs).toBeUndefined();
+ expect(r.total_pages).toBe(16);
+ expect(r.distinct_slugs).toBe(15);
+ });
+
+ test('--by type reports raw and distinct-slug counts so twins are visible', async () => {
+ const r = await stats(ctx(), { by: 'type' });
+ expect(r.groups.find((g: any) => g.type === 'company')).toEqual({ type: 'company', pages: 3, distinct_slugs: 2 });
+ });
+
+ test('--since filters on the effective date', async () => {
+ const r = await stats(ctx(), { by: 'source', since: '2021-01-01' });
+ expect(r.since).toBe('2021-01-01');
+ expect(r.groups.find((g: any) => g.source_id === 'source-b').pages).toBe(6);
+ await expect(stats(ctx(), { since: 'last tuesday' })).rejects.toMatchObject({ code: 'invalid_params' });
+ await expect(stats(ctx(), { by: 'source,author' })).rejects.toMatchObject({ code: 'invalid_params' });
+ });
+
+ test('--collapse-aliases merges near-duplicate types and lists every member', async () => {
+ const r = await stats(ctx(), { by: 'type', collapse_aliases: true });
+ const transcript = r.groups.find((g: any) => g.type === 'transcript');
+ expect(transcript.pages).toBe(3);
+ expect(transcript.member_types).toEqual([
+ { type: 'audio-transcript', pages: 1, via: 'suffix' },
+ { type: 'media/transcript', pages: 1, via: 'normalized' },
+ { type: 'transcript', pages: 1, via: 'exact' },
+ ]);
+ expect(r.groups.some((g: any) => g.type === 'media/transcript')).toBe(false);
+ });
+
+ test('remote grouped stats are confined to the grant and drop private/quarantined pages', async () => {
+ const r = await stats(remote(['source-a']), { by: 'source,type' });
+ expect(r.groups.every((g: any) => g.source_id === 'source-a')).toBe(true);
+ expect(r.groups.find((g: any) => g.type === 'person').pages).toBe(2);
+ });
+ });
+}