Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(search,cli): saved-fact probe reads only facts; response sub-stage timings; warm CLI socket loads 169 modules before the send

garrytan1024cf4f1af6
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index 77494b8c8e..f3b9f8770b 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -37,7 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/frontmatter-where.ts` + `src/core/ops/where-param.ts` — the `where` frontmatter equality filter on `search`, `query`, `list_pages` (#7159; CLI `--where key=value`). Bounded keys and values, else `invalid_params`; each value is a bound `p.frontmatter @> $n::text::jsonb` test (GIN-served), pushed into every SQL leg; a filtered call skips the hybrid cache and `keepFrontmatterMatches` re-checks the other arms. Tests: `test/search-frontmatter-where.test.ts`, its e2e parity file.
- `src/core/search/filter-hint.ts` — one `search_filter_hint` info notice per session when a first-page `search`/`query` names a type or time it did not filter on, or one type fills its top rows. Never changes results.
- `src/core/search/search-cost.ts` — `_meta.retrieval.cost` (#7158): `withSearchCost` meters every `invokeAI` in the request via `withAIInvocationMeter` (AsyncLocalStorage); refused calls are not counted; `gateway.expand` gets an `expansion` line. Test: `test/search-cost.serial.test.ts`.
-- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `branch()` returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until `join(branch, promise)` its stage time goes to `overlapped_ms` under the stage name, and from the join the wait is booked to the branch's current stage (the stage key appears in `stages_ms` even at 0). `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings.test.ts` and `test/search/stage-timings-ops.test.ts`.
+- `src/core/search/stage-timings.ts` — per-request search stage timings. The `search`/`query` handlers create one `SearchTimings` and thread it into every hybrid call of the request (`HybridSearchOpts._timings`, `HybridRequest.timer`; absent = `UNTIMED`, a pass-through). `stage(name, work)` books critical-path blocked wall-clock time: one current stage at a time, a nested stage takes the clock and hands it back, so a fan-out or escalation hybrid call is booked once under its own stages, and retries accumulate. `overlap(label, promise)` times concurrent work (the keyword and title arms) into `overlapped_ms` without adding it to a stage. `part()` books a stage's sequential steps into `parts_ms`. `branch()` returns a timer for stages run alongside the critical path (hybrid's vector side: modality, expansion, embed, vector arms); until `join(branch, promise)` its stage time goes to `overlapped_ms` under the stage name, and from the join the wait is booked to the branch's current stage (the stage key appears in `stages_ms` even at 0). `snapshot()` reads `total_ms` from its own monotonic start, apportions integer `stages_ms` + `other_ms` to sum to it exactly (`other_ms >= 0`); `searchOutput` takes it after the returned rows are assembled and emits it as `_meta.retrieval.timings` (never in content blocks); `formatTimingsSummary` is the `--explain` line. Stages: setup, lexical, relational, expansion, embed, vector, fuse, post_fusion, rerank, alias_fanout, anchoring, facts_arm, response. The gate (every bench query: `0 <= total - sum(stages) <= 10%`) is the `timings` phase of `scripts/bench-refactor-wave-1.ts`. Pinned by `test/search/stage-timings{,-ops}.test.ts`.
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (FROM source for `cc`, the full-text match, the `modality = 'text'` filter). For excludePrivate callers it puts the match in an `OFFSET 0` subquery the planner plans on its own: the private-visibility subplans otherwise inflate every join plan's cost so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (~1.1 s → ~0.2 s for a common term at 250k chunks). Local callers keep the unfenced join, which can plan in parallel (an OFFSET subquery forbids that). PGLite does not use it. Pinned by `test/search/keyword-arm-ranking.test.ts` and `test/e2e/keyword-arm-ranking-postgres.test.ts`.
diff --git a/docs/guides/search-explain.md b/docs/guides/search-explain.md
index 66c5e7e0f2..25596014a0 100644
--- a/docs/guides/search-explain.md
+++ b/docs/guides/search-explain.md
@@ -59,7 +59,8 @@ timings: 74ms total — setup 1, lexical 12, relational 0, embed 0, vector 16, f
| `total_ms` | Wall time of the whole operation, measured on its own clock after the response is assembled. |
| `stages_ms` | Time the request spent blocked in each stage that ran: `setup` (scope, config, mode), `lexical`, `relational`, `expansion`, `embed`, `vector`, `fuse`, `post_fusion` (boosts, dedup, identity tiers, return sizing), `rerank`, `alias_fanout`, `anchoring`, `facts_arm` (query), `response` (evidence delivery, response metadata, redaction). A second search the operation runs (a retry, a CRAG re-run) adds to the same stages; the alias fan-out's keyword searches count under `alias_fanout`. |
| `other_ms` | Time no stage claimed. `sum(stages_ms) + other_ms = total_ms`. |
-| `overlapped_ms` | Work that ran alongside a stage, so it is not added to the total: the keyword and title arms run in parallel inside `lexical` (`keyword_arm`, `title_arm`), `search`'s total-match count runs alongside the whole request (`keyword_count`), and the vector side (query expansion, the query embed and the vector search) starts with the lexical arms, so the part of `expansion`, `embed` and `vector` that finished while they ran is listed here under the stage's name. The rest of those stages, the part the request had to wait for, stays in `stages_ms`. |
+| `overlapped_ms` | Work that ran alongside a stage, so it is not added to the total: the keyword and title arms run in parallel inside `lexical` (`keyword_arm`, `title_arm`), `search`'s total-match count runs alongside the whole request (`keyword_count`), and the vector side (query expansion, the query embed and the vector search) starts with the lexical arms, so the part of `expansion`, `embed` and `vector` that finished while they ran is listed here under the stage's name. The rest of those stages, the part the request had to wait for, stays in `stages_ms`. The response metadata's concurrent reads are listed as `meta_saved_facts`, `meta_entity_facts`, `meta_held`, `meta_readiness`, `meta_freshness`, `meta_embedding_held`, `meta_safe_index` and `meta_filter_hint`; `response.meta` waits for the slowest of them. |
+| `parts_ms` | Present when a stage records its steps: `response` splits into `evidence` (evidence delivery), `trust` (the page-trust stamp), `meta` (the response metadata), `keyword_count` (the wait for `search`'s total-match count) and `feedback` (the answer-feedback record). Parts run one after another and never overlap, so they sum to at most the stage; the rest of `response` is redaction, snippet caps and row projection. `stages_ms.response` keeps its whole time. |
All values are integer milliseconds.
@@ -75,7 +76,7 @@ adds one `timings:` line on stderr.
`connect` (opening the brain), `context` (operation context and source
resolution), `remote` (a thin client's round trip to its server), `op` (the
operation's `total_ms`), `stages` (its `stages_ms` plus `other`),
-`overlapped` and `cli_other` (CLI time in no phase: formatting, notices). A
+`overlapped`, `parts` (the operation's `parts_ms`) and `cli_other` (CLI time in no phase: formatting, notices). A
phase that did not run is absent; `0` means it took under half a
millisecond. On a thin client `op` and `stages` are the server's.
diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.md
index d69da421ef..0e4f0bb0b2 100644
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@ -31,7 +31,7 @@ shape for it.
| Key | Producer | Contents |
|-----|----------|----------|
| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call; each fact carries `trust_tier` and `origin`, and `suppressed` (`{withheld, review}`, present only when non-zero) counts unconfirmed agent-written facts activation control withheld, never their content |
-| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) |
+| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed), `timings` (`{total_ms, stages_ms, other_ms, overlapped_ms?, parts_ms?}`, integer ms, every response; [search-explain.md](../guides/search-explain.md#see-where-the-time-went)) |
| `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` |
| `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |
diff --git a/scripts/bench/retrieval-scale/run.ts b/scripts/bench/retrieval-scale/run.ts
index 440e063944..2e5270c085 100644
--- a/scripts/bench/retrieval-scale/run.ts
+++ b/scripts/bench/retrieval-scale/run.ts
@@ -8,7 +8,7 @@
* [--direct-url postgresql://...:5434/bench_retrieval_300k] [--n 20] [--warmup 3] \
* [--ops search,query,get,recall] [--modes cold,warm] [--search-mode tokenmax] \
* [--embed-ms 0] [--rerank-ms 0] [--toxiproxy http://127.0.0.1:8474 --rtt-ms 40] [--trace] [--serve-cpu-prof <dir>] \
- * [--tree <checkout>] [--keep] [--label <name>] [--out results.jsonl]
+ * [--tree <checkout>] [--keep] [--label <name>] [--out results.jsonl] [--results calls.jsonl]
*
* --toxiproxy adds --rtt-ms of round-trip latency to its `pooler` proxy (vm-setup.sh
* creates it on 127.0.0.1:6544 in front of PgBouncer); point --url at 6544 to use it.
@@ -56,6 +56,8 @@ const searchMode = flag('--search-mode', 'tokenmax')!;
const label = flag('--label', manifest.db + (flag('--rtt-ms') ? '-rtt' + flag('--rtt-ms') : ''))!;
const out = flag('--out');
const trace = has('--trace');
+/** --results <file>: one JSONL line per warm call with its arguments and returned content (compare two trees' output). */
+const resultsOut = flag('--results');
const log = (m: string) => console.error('[retrieval-run] ' + m);
export const pct = (xs: number[], q: number) => { if (!xs.length) return NaN; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.ceil(q * s.length) - 1)]!; };
@@ -131,6 +133,7 @@ async function main() {
if (trace) { row.startup_p50_ms = med('startup'); row.db_p50_ms = med('db'); row.tail_p50_ms = med('tail'); row.round_trips_p50 = med('trips'); }
const stageNames = new Set(ok.flatMap(x => Object.keys(x.stages ?? {})));
if (stageNames.size) row.stages_p50_ms = Object.fromEntries([...stageNames].map(k => [k, r0(pct(ok.map(x => x.stages?.[k] ?? 0), 0.5))]));
+ if (stageNames.size) row.stages_p95_ms = Object.fromEntries([...stageNames].map(k => [k, r0(pct(ok.map(x => x.stages?.[k] ?? 0), 0.95))]));
const worst = s.reduce((w, x, i) => (x.ok && x.ms > s[w]!.ms ? i : w), 0);
if (s[worst]) row.slowest = { i: worst, ms: r0(s[worst]!.ms), target: op === 'get' ? pk(worst).slug : q(worst + opBase(op)), ...(s[worst]!.stages ? { stages: s[worst]!.stages } : {}) };
rows.push(row);
@@ -224,7 +227,12 @@ async function main() {
const timings = r?.result?._meta?.retrieval?.timings;
const trips = trace ? await tripsBetween(performance.timeOrigin + t0, performance.timeOrigin + t0 + ms) : undefined;
if (trace) appendFileSync(join(home, 'warm-calls.jsonl'), JSON.stringify({ op, t0: performance.timeOrigin + t0, t1: performance.timeOrigin + t0 + ms }) + '\n');
- return { ms, ok: !r.error && !r.result?.isError, ...(trips !== undefined ? { trips } : {}), ...(timings ? { stages: { ...timings.stages_ms, other: timings.other_ms, total: timings.total_ms } } : {}) };
+ if (resultsOut) {
+ const { timings: _t, cost: _c, ...retrieval } = r?.result?._meta?.retrieval ?? {};
+ appendFileSync(resultsOut, JSON.stringify({ op, i, arguments: args, content: r?.result?.content, meta: { ...r?.result?._meta, retrieval } }) + '\n');
+ }
+ const parts = Object.entries(timings?.parts_ms ?? {}).flatMap(([stage, byPart]) => Object.entries(byPart as Record<string, number>).map(([part, v]) => [stage + '.' + part, v]));
+ return { ms, ok: !r.error && !r.result?.isError, ...(trips !== undefined ? { trips } : {}), ...(timings ? { stages: { ...timings.stages_ms, ...Object.fromEntries(parts), other: timings.other_ms, total: timings.total_ms } } : {}) };
};
for (let i = 0; i < WARMUP; i++) await call(2000 + i);
const samples: Sample[] = [];
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 8be1506e75..1e7a8604a2 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 2952 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); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports
+src/cli/main.ts 2955 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); GBRA-151 #7147 follow-up (cold one-shot read snapshot handoff and pool cap) re-summed at the v0.60.333.0 merge (3027 measured); +1 GBRA-156 warm CLI socket: one gated dispatch call before CLI_ONLY (logic in cli/cli-socket-client.ts); -11 GBRA-156: MERGED_CONFIG_BY_ENGINE and its comment moved to core/published-config.ts (serve reads it); lowered at the v0.60.340.0 merge (3018 measured); +5 #7191: search --exact routing call (dispatch, cannot move; rule in cli/command-route.ts) and the search_exact formatter case + imports; +3 GBRA-156 warm CLI startup: page-render, volunteer and operation-load imported lazily where used, so a warm socket hit loads 169 modules instead of 709 (2955 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)
diff --git a/src/cli/cli-socket-client.ts b/src/cli/cli-socket-client.ts
index 1768eb6119..2dea8dfbc9 100644
--- a/src/cli/cli-socket-client.ts
+++ b/src/cli/cli-socket-client.ts
@@ -13,6 +13,7 @@ import { loadConfig, configDir, configPath, isThinClient } from '../core/config.
import { getCliOptions } from '../core/cli-options.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { VERSION } from '../version.ts';
+import type { OperationMeta } from '../core/ops/contract.ts';
import { cliSocketDir, cliSocketPath, connectProblem } from '../core/cli-socket/fs-guard.ts';
import { cliSocketIdentity } from '../core/cli-socket/identity.ts';
import { peerCredSupport, peerUid, type PeerCredSupport } from '../core/cli-socket/peer-cred.ts';
@@ -108,13 +109,11 @@ async function replay(frame: { output: OutputChunk[] }): Promise<void> {
}
}
-async function opRequest(command: string, args: string[]): Promise<{ op: import('../core/operations.ts').Operation; params: Record<string, unknown> } | string> {
+async function opRequest(command: string, args: string[]): Promise<{ op: OperationMeta; params: Record<string, unknown> } | string> {
const { cliOps } = await import('./op-manifest.ts');
const { cliAliases, parseOpArgs } = await import('./main.ts');
- const meta = cliOps.get(command) ?? cliAliases.get(command);
- if (!meta || !SOCKET_OPS[meta.name]) return 'not_a_socket_op';
- const { loadOperation } = await import('../core/operation-load.ts');
- const op = (await loadOperation(meta.name))!;
+ const op = cliOps.get(command) ?? cliAliases.get(command);
+ if (!op || !SOCKET_OPS[op.name]) return 'not_a_socket_op';
const params = parseOpArgs(op, args);
if (op.cliHints?.stdin && !params[op.cliHints.stdin]) return 'stdin_input';
if (typeof params.image === 'string' && params.image.length > 0) return 'image_query';
@@ -162,7 +161,7 @@ function renderFailed(error: unknown): false {
}
/** Prints an answered op frame the way the cold path would; false (nothing printed) when the frame cannot be rendered. */
-export async function renderOp(command: string, op: import('../core/operations.ts').Operation, params: Record<string, unknown>, frame: Exclude<ResultFrame, { kind: 'fallback' }>): Promise<boolean> {
+export async function renderOp(command: string, op: OperationMeta, params: Record<string, unknown>, frame: Exclude<ResultFrame, { kind: 'fallback' }>): Promise<boolean> {
const { formatResult, captureRetrievalMeta, maybePrintConceptNudge } = await import('./main.ts');
const { applyCliOpNotices, captureOpNotice } = await import('./op-notices.ts');
const { setCliExitVerdict, writeStdoutFinal } = await import('../core/cli-force-exit.ts');
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 67a96324c7..98b097f6e0 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -34,11 +34,9 @@ import type { AIGatewayConfig } from '../core/ai/types.ts';
import type { BrainEngine } from '../core/engine.ts';
import { OperationError, type OperationMeta } from '../core/ops/contract.ts';
import { OPERATION_MANIFEST, cliOps } from './op-manifest.ts';
-import { loadOperation } from '../core/operation-load.ts';
import { openRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';
import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
import { installCliRoutingFor } from './fix-routing-provider.ts';
-import { formatVolunteeredPage } from '../core/context/volunteer.ts';
import type { Operation, OperationContext } from '../core/operations.ts';
import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { isScopeErrorCode } from '../core/error-catalogue.ts';
@@ -51,7 +49,6 @@ import type { Notice } from '../core/agent-output.ts';
import { opError, opOwnsSource } from '../core/ops/contract.ts';
import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';
import { opFlagValue, opParamValue, opStructuredValue } from './op-param-values.ts';
-import { SEGMENTED_STREAMED, formatGetPage, printPagedPage, remoteErrorCode, streamSegmentedGet, wantsWholePage } from './page-render.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';
import { runCliPreflight } from '../core/cli-preflight.ts';
import { isBooleanLiteral, isKnownOpFlag } from '../core/op-flag-tokens.ts';
@@ -534,6 +531,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// Shared operations (fall through to aliases, e.g. link-add -> add_link)
const meta = cliOps.get(command) ?? cliAliases.get(command);
if (!meta) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
+ const { loadOperation } = await import('../core/operation-load.ts');
const op = (await loadOperation(meta.name))!;
// v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
@@ -689,7 +687,9 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
try {
rawResult = await withTimeout(
configSnapshot!.run(() => withRequestIdentityMemo(() => op.handler(ctx, params))).catch(async (e: unknown) => { // large pages: a segmented page streams to stdout
- if (op.name === 'get_page' && await streamSegmentedGet(engine, params, e, writeStdoutFinal)) return SEGMENTED_STREAMED;
+ if (op.name !== 'get_page') throw e;
+ const { streamSegmentedGet, SEGMENTED_STREAMED } = await import('./page-render.ts');
+ if (await streamSegmentedGet(engine, params, e, writeStdoutFinal)) return SEGMENTED_STREAMED;
throw e;
}),
wallclockMs,
@@ -706,7 +706,7 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
rawResult = await withRequestIdentityMemo(() => op.handler(ctx, params));
if (op.mutating) await captureCapacityNotices(engine); // #6696 (A4)
}
- if (rawResult === SEGMENTED_STREAMED) return;
+ if (op.name === 'get_page' && rawResult === (await import('./page-render.ts')).SEGMENTED_STREAMED) return;
captureRetrievalNotices(op.name, rawResult, lastRetrievalMeta, params, ctx.config);
// ENG-2 (renderer parity by data shape): JSON-round-trip the local-engine
// path's return value so renderers see the same shape they'd see on the
@@ -815,7 +815,9 @@ async function runThinClientRouted(
signal: sigintController.signal,
...(op.mutating ? { writeWaitMs: currentCliWriteWait().waitMs } : {}),
}).catch(async (e: unknown) => { // large pages: a page too big for one response is paged to its end, verified, then printed
- if (op.name !== 'get_page' || remoteErrorCode(e) !== 'page_too_large_for_inline' || !wantsWholePage(params)) throw e;
+ if (op.name !== 'get_page') throw e;
+ const { printPagedPage, remoteErrorCode, wantsWholePage } = await import('./page-render.ts');
+ if (remoteErrorCode(e) !== 'page_too_large_for_inline' || !wantsWholePage(params)) throw e;
await printPagedPage(async p => unpackToolResult(await callRemoteTool(cfg, 'get_page', p, { timeoutMs, signal: sigintController.signal })), params, writeStdoutFinal);
return null;
}));
@@ -1050,7 +1052,7 @@ export function resolveQueryImage(
return { path: imagePath, base64, mime };
}
-export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
+export function parseOpArgs(op: OperationMeta, args: string[]): Record<string, unknown> {
// `gbrain search --explain`: the CLI-local formatter flag also asks the op for score attribution.
const params: Record<string, unknown> = (op.name === 'search' || op.name === 'query') && (getCliOptions().explain || args.includes('--explain')) ? { explain: true } : {};
const positional = op.cliHints?.positional || [];
@@ -1640,9 +1642,10 @@ export function formatResult(
}
const pages = (r?.pages ?? []) as any[];
if (!pages.length) return 'Nothing volunteered (no entity cleared the confidence gate).\n';
+ const { formatVolunteeredPage } = require('../core/context/volunteer.ts');
return pages.map((p) => formatVolunteeredPage(p)).join('\n') + '\n';
}
- case 'get_page': return formatGetPage(result as Record<string, any>);
+ case 'get_page': return require('./page-render.ts').formatGetPage(result as Record<string, any>);
case 'search_exact': return formatSearchExact(result as Parameters<typeof formatSearchExact>[0]);
case 'list_pages': {
const pages = result as any[];
diff --git a/src/cli/op-param-values.ts b/src/cli/op-param-values.ts
index 88f1c9ac4d..87613a3332 100644
--- a/src/cli/op-param-values.ts
+++ b/src/cli/op-param-values.ts
@@ -7,11 +7,11 @@
* `validateParams` (types + enums) for the CLI parser.
*/
import { inertText } from '../core/agent-output.ts';
-import type { Operation, ParamDef } from '../core/ops/contract.ts';
+import type { OperationMeta, ParamDef } from '../core/ops/contract.ts';
import { usageError } from './cli-error.ts';
/** Coerce one raw CLI token for `op.params[key]`; `positional` labels a positional slot instead of a flag. */
-export function opParamValue(op: Operation, key: string, def: ParamDef | undefined, raw: string, positional = false): unknown {
+export function opParamValue(op: OperationMeta, key: string, def: ParamDef | undefined, raw: string, positional = false): unknown {
if (!def) return raw;
const name = positional ? `<${key}>` : `--${key.replace(/_/g, '-')}`;
const usage = `gbrain ${op.cliHints?.name ?? op.name}`;
@@ -34,7 +34,7 @@ export function opParamValue(op: Operation, key: string, def: ParamDef | undefin
* (`--where key=value`) collects every repetition into a list that
* `opStructuredValue` turns into the object; every other flag is one value.
*/
-export function opFlagValue(op: Operation, key: string, def: ParamDef | undefined, raw: string, prev: unknown): unknown {
+export function opFlagValue(op: OperationMeta, key: string, def: ParamDef | undefined, raw: string, prev: unknown): unknown {
if (def?.cliKeyValue) return [...(Array.isArray(prev) ? prev : []), raw];
return opParamValue(op, key, def, raw);
}
diff --git a/src/cli/page-render.ts b/src/cli/page-render.ts
index 04758a8d9a..ea02e5a5bb 100644
--- a/src/cli/page-render.ts
+++ b/src/cli/page-render.ts
@@ -31,8 +31,6 @@ import { opError } from '../core/ops/contract.ts';
import { readFix } from '../core/ops/op-fix.ts';
import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';
import { isSegmentedPage } from '../core/page-body/page-shape.ts';
-import { openSegmentedBody } from '../core/page-body/read-range.ts';
-import { markdownHead, segmentedMarkdownDocument } from '../core/page-window/segmented.ts';
/** Window size the thin client asks for while paging a whole page. */
export const REMOTE_PAGE_WINDOW_BYTES = 512 * 1024;
@@ -231,6 +229,7 @@ export async function streamSegmentedGet(engine: BrainEngine, params: Record<str
const { page, tags } = snapshot;
const json = params.json === true;
if (json && Number(page.body_bytes) > PAGE_MAX_BYTES) throw jsonTooLargeError(page.slug, page.source_id, Number(page.body_bytes));
+ const [{ openSegmentedBody }, { markdownHead, segmentedMarkdownDocument }] = await Promise.all([import('../core/page-body/read-range.ts'), import('../core/page-window/segmented.ts')]);
const body = await openSegmentedBody(engine, { pageId: page.id, ledger: { withdrawals: snapshot.withdrawals, ...(snapshot.globalPurges ? { globalPurges: snapshot.globalPurges } : {}) },
pin: { revision: snapshot.revision, generation: snapshot.bodyGeneration } });
const doc = await segmentedMarkdownDocument(engine, body, markdownHead(page, tags), 'trusted');
diff --git a/src/cli/search-timings.ts b/src/cli/search-timings.ts
index 52f1907df3..fd48656d31 100644
--- a/src/cli/search-timings.ts
+++ b/src/cli/search-timings.ts
@@ -44,6 +44,8 @@ export interface CliSearchTimings {
stages?: Record<string, number>;
/** Work that ran alongside the critical path (parallel lexical arms, the vector side before its join). */
overlapped?: Record<string, number>;
+ /** Sequential parts of a stage (`response`: evidence, trust, meta, keyword_count, feedback); the stage keeps its own total. */
+ parts?: Partial<Record<string, Record<string, number>>>;
/** CLI time in no phase: result normalization, notices, formatting. */
cli_other: number;
}
@@ -58,6 +60,7 @@ export function cliSearchTimings(op: SearchTimingsMeta | undefined): CliSearchTi
out.op = op.total_ms;
out.stages = { ...op.stages_ms, other: op.other_ms };
if (op.overlapped_ms) out.overlapped = op.overlapped_ms;
+ if (op.parts_ms) out.parts = op.parts_ms;
}
const accounted = (out.startup ?? 0) + [...phases.values()].reduce((sum, v) => sum + v, 0) + (out.remote === undefined ? op?.total_ms ?? 0 : 0);
out.cli_other = Math.max(0, ms(total - accounted));
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index 95d1bda0d6..60bab0385a 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -37,7 +37,7 @@ import { clampSearchLimit } from '../core/engine.ts';
import { effectiveConfidence } from '../core/facts/decay.ts';
import { resolveEntitySlug } from '../core/entities/resolve.ts';
import { loadConfig, isThinClient } from '../core/config.ts';
-import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../core/mcp-client.ts';
+import { RemoteMcpError } from '../core/remote-mcp-error.ts';
import { readRecallCursor, writeCursor, writePagedCursor, type RecallCursor } from '../core/recall-cursor-state.ts';
import { resolveSourceId, resolveSourceIdEngineFree, SourceTargetError } from '../core/source-resolver.ts';
import { usageError } from '../cli/cli-error.ts';
@@ -491,9 +491,9 @@ async function recallVerbResult(engine: BrainEngine, flags: ParsedFlags, sourceI
...(flags.pending ? { include_pending: true } : {}),
} : {}),
};
- return (oneShot && isThinClient(ctx.config)
- ? unpackToolResult(await callRemoteTool(ctx.config, 'recall', params, { timeoutMs: 30_000 }))
- : await op.handler(ctx, params)) as RecallVerbResult;
+ if (!oneShot || !isThinClient(ctx.config)) return await op.handler(ctx, params) as RecallVerbResult;
+ const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
+ return unpackToolResult(await callRemoteTool(ctx.config, 'recall', params, { timeoutMs: 30_000 })) as RecallVerbResult;
}
export async function renderRecallVerbResult(flags: ParsedFlags, result: RecallVerbResult): Promise<void> {
@@ -686,6 +686,7 @@ async function runRecallOnce(
if (thinClient) {
const cfg = loadConfig();
+ const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
const params: Record<string, unknown> = {
limit: flags.limit,
include_expired: flags.includeExpired,
@@ -1213,6 +1214,7 @@ export async function runForget(engine: BrainEngine | (() => Promise<BrainEngine
// remote brain.
const cfg = loadConfig();
if (isThinClient(cfg)) {
+ const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
try {
if (sourceValue) throw opError('invalid_params', '--source cannot override the remote memory writer grant.',
'Drop --source: on a remote brain the connection\'s memory writer grant decides the source.',
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index 6535ae905a..2e74a7a0cc 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -64,7 +64,7 @@ import {
pgliteCloseTimeoutMs,
SINK_DRAIN_TIMEOUT_MS,
} from './background-work.ts';
-import { POOL_END_TIMEOUT_SECONDS } from './db.ts';
+import { POOL_END_TIMEOUT_SECONDS } from './pool-end-timeout.ts';
import { parseGlobalFlags } from './cli-options.ts';
const DAEMON_COMMANDS: ReadonlySet<string> = new Set(['serve']);
diff --git a/src/core/connection-manager.ts b/src/core/connection-manager.ts
index c7f1b5ead7..d91ecc633d 100644
--- a/src/core/connection-manager.ts
+++ b/src/core/connection-manager.ts
@@ -42,6 +42,9 @@ import { gbrainApplicationName, readPoolPipelineOptions, transactionPipelineOpti
import { redactPgUrl } from './url-redact.ts';
import { logConnectionEvent } from './connection-audit.ts';
import { directPoolProfile, type DirectPoolProfile } from './direct-pool-profile.ts';
+import { deriveDirectUrl, deriveSessionPoolerUrl, isSupabasePoolerUrl } from './supabase-pooler-url.ts';
+
+export { deriveDirectUrl, deriveSessionPoolerUrl, isSupabasePoolerUrl };
export type Sql = ReturnType<typeof postgres>;
@@ -91,111 +94,6 @@ const DDL_IDLE_TX_TIMEOUT_MS = 5 * 60 * 1000; // 5min
/** Bulk pool default maintenance_work_mem (P1). 256MB safe on Supabase. */
const BULK_MAINTENANCE_WORK_MEM = '256MB';
-/**
- * Hostname patterns that indicate a Supabase pooler. Used for auto-detection
- * of the dual-pool topology. Adding more patterns is safe; mis-detection
- * just means we open a "direct" pool against the same URL — wasteful but
- * not broken (the kill-switch is the operator's escape hatch).
- */
-const SUPABASE_POOLER_HOSTNAME_PATTERNS = [
- /\.pooler\.supabase\.com$/i,
- /^pooler\.supabase\.com$/i,
-];
-
-const SUPABASE_POOLER_PORTS = new Set(['6543']);
-
-/**
- * True if the URL looks like a Supabase pooler endpoint. Used for kill-switch
- * activation and dual-pool routing.
- */
-export function isSupabasePoolerUrl(url: string): boolean {
- try {
- const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));
- if (SUPABASE_POOLER_PORTS.has(parsed.port)) return true;
- if (SUPABASE_POOLER_HOSTNAME_PATTERNS.some(re => re.test(parsed.hostname))) return true;
- return false;
- } catch {
- return false;
- }
-}
-
-/**
- * Derive a direct (non-pooler) URL from a Supabase pooler URL. Two known shapes:
- *
- * Pooler hostname: aws-N-region.pooler.supabase.com on port 6543
- * → swap to db.<project-ref>.supabase.co on port 5432
- * (project-ref encoded in the user component as postgres.<ref>)
- * Direct hostname: db.<ref>.supabase.co already on port 5432 → returned as-is
- *
- * For the modern shape, we try to extract project-ref from the user component.
- * If we cannot, we fall back to swapping port-only and the caller may warn.
- *
- * Returns null when the URL isn't a recognized Supabase pooler.
- */
-export function deriveDirectUrl(url: string): string | null {
- try {
- const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));
- const port = parsed.port;
- const hostname = parsed.hostname;
- const isPoolerHost = SUPABASE_POOLER_HOSTNAME_PATTERNS.some(re => re.test(hostname));
- if (port !== '6543' && !isPoolerHost) return null;
- // User part on Supabase pooler is typically `postgres.<project-ref>`.
- // Extract <project-ref> for the direct hostname.
- const user = parsed.username || '';
- const decodedUser = decodeURIComponent(user);
- const refMatch = decodedUser.match(/^postgres\.([a-z0-9]+)$/i);
- let directHost = hostname;
- let directUser = parsed.username;
- if (refMatch && refMatch[1] && isPoolerHost) {
- directHost = `db.${refMatch[1]}.supabase.co`;
- // Supabase direct connections use bare `postgres`; the `postgres.<ref>`
- // form is pooler-only (Supavisor uses the suffix for tenant routing).
- // Without this strip, direct auth fails with `password authentication
- // failed for user "postgres.<ref>"` even though the password is correct.
- directUser = 'postgres';
- }
- // Compose direct URL by swapping host + port. Preserve auth, db, query.
- parsed.hostname = directHost;
- parsed.port = '5432';
- // Reconstruct with the original scheme.
- const scheme = url.match(/^postgres(?:ql)?:\/\//i)?.[0] ?? 'postgres://';
- const auth = directUser
- ? `${directUser}${parsed.password ? `:${parsed.password}` : ''}@`
- : '';
- const search = parsed.search ?? '';
- const path = parsed.pathname ?? '';
- return `${scheme}${auth}${directHost}:5432${path}${search}`;
- } catch {
- return null;
- }
-}
-
-/**
- * Derive the SESSION-mode pooler URL from a TRANSACTION-mode pooler URL
- * (#1915): same pooler host, port 6543 → 5432, KEEPING the postgres.<ref>
- * user (Supavisor needs the tenant suffix — unlike deriveDirectUrl, which
- * strips it for the db.<ref> host). The session pooler is IPv4-reachable and
- * honors the direct pool's startup-parameter timeouts, so it is the natural
- * second choice when the auto-derived db.<ref>.supabase.co host is
- * IPv6-unreachable (Railway, most home ISPs). Returns null when the URL
- * isn't a Supabase transaction-pooler shape (pooler hostname + port 6543 —
- * a bare :6543 on an unknown host proves nothing about what :5432 serves).
- */
-export function deriveSessionPoolerUrl(url: string): string | null {
- try {
- const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));
- const isPoolerHost = SUPABASE_POOLER_HOSTNAME_PATTERNS.some(re => re.test(parsed.hostname));
- if (!isPoolerHost || parsed.port !== '6543') return null;
- const scheme = url.match(/^postgres(?:ql)?:\/\//i)?.[0] ?? 'postgres://';
- const auth = parsed.username
- ? `${parsed.username}${parsed.password ? `:${parsed.password}` : ''}@`
- : '';
- return `${scheme}${auth}${parsed.hostname}:5432${parsed.pathname ?? ''}${parsed.search ?? ''}`;
- } catch {
- return null;
- }
-}
-
/** True when the URL targets Supavisor transaction mode (port 6543). */
function isTransactionPoolerUrl(url: string): boolean {
try {
diff --git a/src/core/db.ts b/src/core/db.ts
index 492c8aae83..8d45e125df 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -7,21 +7,14 @@ import { SCHEMA_SQL } from './schema-embedded.generated.ts';
import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';
import type { BrainEngine } from './engine.ts';
import { verifySchema } from './schema-verify.ts';
+import { POOL_END_TIMEOUT_SECONDS } from './pool-end-timeout.ts';
import { isConnectTimeoutError, isRetryableConnError } from './retry-matcher.ts';
import { loadSharedParameterTypes, sharedArrayTypes, sharedParameterTypes, type SharedArrayTypes, type SharedParameterTypes } from './pg-type-cache.ts';
let sql: ReturnType<typeof postgres> | null = null;
let connectedUrl: string | null = null;
-/**
- * #1972: hard upper bound (seconds) on a single pool `.end()` drain. postgres.js
- * accepts `{ timeout }` but applies it internally — against PgBouncer
- * transaction-mode the drain can still hang, and a stubbed `.end()` ignores it
- * entirely. So `endPoolBounded` ALSO wraps each end in a gbrain-owned
- * Promise.race and passes this value as the postgres.js hint so a healthy drain
- * still finishes fast.
- */
-export const POOL_END_TIMEOUT_SECONDS = 2;
+export { POOL_END_TIMEOUT_SECONDS };
/**
* #1972: end a postgres.js pool with a gbrain-owned hard bound. Resolves as soon
diff --git a/src/core/op-flag-tokens.ts b/src/core/op-flag-tokens.ts
index 5ea2c25892..17bce75ba9 100644
--- a/src/core/op-flag-tokens.ts
+++ b/src/core/op-flag-tokens.ts
@@ -9,7 +9,7 @@
* defined once and imported cannot.
*/
-import type { Operation } from './operations.ts';
+import type { OperationMeta } from './ops/contract.ts';
/**
* #4602: the ONE definition of "a literal true/false value token" — parseOpArgs
@@ -37,7 +37,7 @@ export const isBooleanLiteral = (tok: string | undefined): boolean =>
* markdown body opening with an em-dash, say) is not a known flag and stays a
* value.
*/
-export const isKnownOpFlag = (op: Operation, tok: string | undefined): boolean => {
+export const isKnownOpFlag = (op: OperationMeta, tok: string | undefined): boolean => {
if (!tok || !tok.startsWith('--') || tok === '--') return false;
const eq = tok.indexOf('=');
if (eq >= 0 && eq <= 2) return false; // `--=x` is junk, not a flag
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index cf800dafbb..5f8d0302f1 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -207,9 +207,10 @@ async function evidenceOutput(ctx: OperationContext, p: Record<string, unknown>,
// Every returned row is a copy of one of `results`, so their page trust is read alongside evidence delivery.
const pageTrust = loadPageTrust(ctx.engine, results.filter(r => typeof r.fact_row?.id !== 'number'));
pageTrust.catch(() => {});
- const ev = await withEvidence(ctx, p, results, plan, scope, meta);
- const rows = await stampPageTrust(ctx.engine, keepEnumerated ? keepEnumeratedRows(results, ev.rows) : ev.rows, scope.minTrust, pageTrust);
- return searchOutput(ctx, p, rows, await buildMeta(rows), snippetCap, timings, ev.evidence);
+ const ev = await timings.part('response', 'evidence', () => withEvidence(ctx, p, results, plan, scope, meta));
+ const rows = await timings.part('response', 'trust', () => stampPageTrust(ctx.engine, keepEnumerated ? keepEnumeratedRows(results, ev.rows) : ev.rows, scope.minTrust, pageTrust));
+ const responseMeta = await timings.part('response', 'meta', () => buildMeta(rows));
+ return searchOutput(ctx, p, rows, responseMeta, snippetCap, timings, ev.evidence);
});
}
@@ -380,21 +381,25 @@ async function matchingSavedFacts(ctx: OperationContext, scope: SourceScope, que
if (terms.length === 0 || !ctx.emitResponseMeta) return [];
const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? ctx.sourceId ?? 'default'];
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
- const visibility = `${ctx.remote !== false ? `AND f.visibility = 'world'` : ''} ${excludePrivate ? `AND ${privateProvenanceFilterFragment('f')}` : ''}
- AND ${projectionEligibleSql('facts', 'f', { floor: scope.minTrust })}`;
const active = `f.source_id = ANY($1::text[])
AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now())
AND f.source != ALL($2::text[])
- ${visibility}`;
+ ${ctx.remote !== false ? `AND f.visibility = 'world'` : ''}`;
+ const eligible = `${excludePrivate ? `AND ${privateProvenanceFilterFragment('f')}` : ''}
+ AND ${projectionEligibleSql('facts', 'f', { floor: scope.minTrust })}`;
try {
// Most searches have no saved fact to find: the uncorrelated EXISTS is an indexed probe
// (idx_facts_since) the planner runs once, before the LIKE ANY scan, and the scan is skipped
- // when no fact qualifies; one statement, so one round trip either way.
+ // when no fact qualifies; one statement, so one round trip either way. The probe reads the
+ // fact's own columns only: every row the scan returns passes it, so it never changes the
+ // result, and the page-eligibility filters stay on the scan, where they cost an index
+ // lookup per candidate. In the probe the planner joined them to the whole pages index.
const rows = await ctx.engine.executeRaw<SavedFactMatch & { haystack: string }>(
`SELECT f.id, f.fact, f.entity_slug, f.kind, f.valid_from::text AS valid_from, f.source,
lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) AS haystack
FROM facts f
WHERE ${active}
+ ${eligible}
AND lower(f.fact || ' ' || COALESCE(f.entity_slug, '')) LIKE ANY($3::text[])
AND EXISTS (SELECT 1 FROM facts f WHERE ${active} LIMIT 1)
ORDER BY f.valid_from DESC, f.id DESC
@@ -443,8 +448,10 @@ async function buildRetrievalResponseMeta(
queryText: string,
results: unknown[],
meta: HybridSearchMeta | null,
- opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search'; entity?: ResolvedEntity; filterHintFor?: { op: 'search' | 'query'; p: Record<string, unknown> } } = {},
+ opts: { conceptHint?: boolean; types?: string[]; typeFilterNotice?: string; declarations?: DeclarationMemo; feedbackOp?: 'query' | 'search'; entity?: ResolvedEntity; filterHintFor?: { op: 'search' | 'query'; p: Record<string, unknown> }; timings?: SearchTimings } = {},
): Promise<Record<string, unknown>> {
+ // Each concurrent read below is reported in `overlapped_ms` under its own `meta_*` label.
+ const timed = <T>(label: string, work: T | Promise<T>): Promise<T> => opts.timings ? opts.timings.overlap(`meta_${label}`, Promise.resolve(work)) : Promise.resolve(work);
const m = meta as (HybridSearchMeta & { degraded?: unknown[]; retrieved_count?: number }) | null;
const hint = opts.conceptHint && looksConceptShaped(queryText)
? "concept-shaped question — the 'query' tool ranks the same and adds saved-fact rows and a confidence grade."
@@ -457,17 +464,17 @@ async function buildRetrievalResponseMeta(
// #6721: these reads depend on nothing but the inputs above, so they run at once: on a pooled Postgres
// the wall time is the slowest read's round trips, not their sum. The answer-feedback write still runs last.
const [safeIndexPending, [readiness, pendingCount], entityFacts, matchedFacts, held, sourceFreshness, embeddingHeld, filterNotice] = await Promise.all([
- ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes }),
- probeProjectionReadiness(ctx.engine, readinessScope).then(async r =>
- [r, r.status === 'projection_pending' ? await countPendingProjections(ctx.engine, readinessScope, relevance) : null] as const),
+ timed('safe_index', ctx.remote !== false && hasUnsealedPagesInScope(ctx, scope, excludePrivate, { types: opts.types, excludeSlugPrefixes })),
+ timed('readiness', probeProjectionReadiness(ctx.engine, readinessScope).then(async r =>
+ [r, r.status === 'projection_pending' ? await countPendingProjections(ctx.engine, readinessScope, relevance) : null] as const)),
// Facts saved about the entity the query names come first (newest first, one hop through entities they name).
- opts.entity && ctx.emitResponseMeta ? entitySavedFacts(ctx.engine, opts.entity, { remote: ctx.remote !== false, excludePrivate }) : [],
- matchingSavedFacts(ctx, scope, queryText, aliases),
- stampHeldHits(ctx.engine, results as SearchResult[], scope, relevance, ctx).catch(() => ({ coverage: [], couldAffect: 0 })),
+ timed('entity_facts', opts.entity && ctx.emitResponseMeta ? entitySavedFacts(ctx.engine, opts.entity, { remote: ctx.remote !== false, excludePrivate }) : []),
+ timed('saved_facts', matchingSavedFacts(ctx, scope, queryText, aliases)),
+ timed('held', stampHeldHits(ctx.engine, results as SearchResult[], scope, relevance, ctx).catch(() => ({ coverage: [], couldAffect: 0 }))),
// GBRA-133 PR 2a.5: per-source freshness from the notifier's cached coverage record (no git call).
- readSourceFreshness(ctx.engine, scope),
- countEmbeddingHeld(ctx.engine, readinessScope, relevance),
- opts.filterHintFor ? searchFilterHint(ctx, scope, excludePrivate, queryText, results as SearchResult[], opts.types, opts.filterHintFor) : null,
+ timed('freshness', readSourceFreshness(ctx.engine, scope)),
+ timed('embedding_held', countEmbeddingHeld(ctx.engine, readinessScope, relevance)),
+ timed('filter_hint', opts.filterHintFor ? searchFilterHint(ctx, scope, excludePrivate, queryText, results as SearchResult[], opts.types, opts.filterHintFor) : null),
]);
const heldFiles = held.coverage;
const topHitExact = pendingCount?.top_counted === false;
@@ -528,7 +535,7 @@ async function buildRetrievalResponseMeta(
...(coverage ? { coverage } : {}),
...(freshness.length ? { freshness } : {}),
...(hint || readinessHint ? { hint: [hint, readinessHint].filter(Boolean).join(' ') } : {}),
- ...(opts.feedbackOp ? await searchAnswerFeedback(ctx, opts.feedbackOp, results as SearchResult[]) : {}),
+ ...(opts.feedbackOp ? await (opts.timings ? opts.timings.part('response', 'feedback', () => searchAnswerFeedback(ctx, opts.feedbackOp!, results as SearchResult[])) : searchAnswerFeedback(ctx, opts.feedbackOp, results as SearchResult[])) : {}),
};
}
@@ -786,8 +793,8 @@ const search: Operation = {
await stampKeywordRows(ctx, results, { ...scope, excludePrivate }, queryText, startedAt, timings);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, null, snippetCap, timings,
- async rows => withCountMeta(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, filterHintFor: { op: 'search', p } }),
- page ?? keywordCountMeta(await keywordCount!, offset + limit)), page !== null);
+ async rows => withCountMeta(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, null, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, filterHintFor: { op: 'search', p }, timings }),
+ page ?? keywordCountMeta(await timings.part('response', 'keyword_count', () => keywordCount!), offset + limit)), page !== null);
}
// Cheap-hybrid (D4/D15): full vector+keyword+RRF+pool+title+alias, but
@@ -832,8 +839,8 @@ const search: Operation = {
maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);
// #3800: cap AFTER capture/meta so eval + cache see the real payload.
return evidenceOutput(ctx, p, results, plan, { ...scope, excludePrivate }, capturedMeta, snippetCap, timings,
- async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity, filterHintFor: { op: 'search', p } })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
- keywordCountMeta(await keywordCount, offset + limit)));
+ async rows => withCountMeta(withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, scope, queryText, rows, capturedMeta, { conceptHint: true, types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'search', entity: fanned.entity, filterHintFor: { op: 'search', p }, timings })), ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'search')),
+ keywordCountMeta(await timings.part('response', 'keyword_count', () => keywordCount), offset + limit)));
},
scope: 'read', mutating: false,
cliHints: { name: 'search', positional: ['query'] },
@@ -1242,7 +1249,7 @@ const query: Operation = {
// #3800: cap AFTER capture/meta/CRAG so every internal consumer graded
// and recorded the real payload; only the returned envelope is snipped.
return evidenceOutput(ctx, p, results, plan, { ...querySourceScope, excludePrivate, detail }, capturedMeta, snippetCap, timings,
- async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity, filterHintFor: { op: 'query', p } })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
+ async rows => withExplainTarget({ ...(await buildRetrievalResponseMeta(ctx, querySourceScope, queryText, rows, capturedMeta, { types, typeFilterNotice: typeFilter.notice, declarations, feedbackOp: 'query', entity: fanned.entity, filterHintFor: { op: 'query', p }, timings })), crag, ...(fanned.fanout ? { fanout: fanned.fanout } : {}) }, finishExplainTarget(ctx, p, explainPrep, results, 'query')));
},
scope: 'read', mutating: false,
cliHints: { name: 'query', positional: ['query'] },
diff --git a/src/core/pg-access-classify.ts b/src/core/pg-access-classify.ts
index 703690241e..03a1628ad2 100644
--- a/src/core/pg-access-classify.ts
+++ b/src/core/pg-access-classify.ts
@@ -43,7 +43,7 @@ import {
deriveDirectUrl,
deriveSessionPoolerUrl,
isSupabasePoolerUrl,
-} from './connection-manager.ts';
+} from './supabase-pooler-url.ts';
import { extractProjectRef } from './supabase-admin.ts';
/**
diff --git a/src/core/pool-end-timeout.ts b/src/core/pool-end-timeout.ts
new file mode 100644
index 0000000000..74b6e24e1f
--- /dev/null
+++ b/src/core/pool-end-timeout.ts
@@ -0,0 +1,10 @@
+/**
+ * #1972: hard upper bound (seconds) on a single pool `.end()` drain. postgres.js
+ * accepts `{ timeout }` but applies it internally — against PgBouncer
+ * transaction-mode the drain can still hang, and a stubbed `.end()` ignores it
+ * entirely. So `endPoolBounded` (db.ts) ALSO wraps each end in a gbrain-owned
+ * Promise.race and passes this value as the postgres.js hint so a healthy drain
+ * still finishes fast. Its own module so the CLI exit seam (cli-force-exit.ts)
+ * budgets it without loading the Postgres driver into every invocation.
+ */
+export const POOL_END_TIMEOUT_SECONDS = 2;
diff --git a/src/core/search/stage-timings.ts b/src/core/search/stage-timings.ts
index 131109f675..cbf0bd8edf 100644
--- a/src/core/search/stage-timings.ts
+++ b/src/core/search/stage-timings.ts
@@ -31,6 +31,8 @@ export interface SearchTimingsMeta {
stages_ms: Partial<Record<SearchStage, number>>;
other_ms: number;
overlapped_ms?: Record<string, number>;
+ /** Sequential parts of a stage (`part`), integer ms; the rest of the stage is in no part. */
+ parts_ms?: Partial<Record<SearchStage, Record<string, number>>>;
}
export interface StageTimer {
@@ -56,6 +58,8 @@ export class SearchTimings implements StageTimer {
private since: number;
private readonly spent = new Map<SearchStage, number>();
private readonly overlapped = new Map<string, number>();
+ private readonly parts = new Map<SearchStage, Map<string, number>>();
+ private currentPart: { stage: SearchStage; part: string; since: number } | null = null;
constructor(private readonly now: () => number = () => performance.now()) {
this.startedAt = this.since = now();
@@ -80,6 +84,39 @@ export class SearchTimings implements StageTimer {
}
}
+ /**
+ * Book one sequential part of the current stage (`parts_ms[stage][part]`), for a stage whose
+ * steps run one after another (`response`). Like stages, a nested part takes the clock and
+ * hands it back, so parts never overlap and sum to at most the stage. The stage's own
+ * booking is unchanged.
+ */
+ async part<T>(stage: SearchStage, part: string, work: () => Promise<T>): Promise<T> {
+ const previous = this.switchPart({ stage, part, since: 0 });
+ try {
+ return await work();
+ } finally {
+ this.switchPart(previous);
+ }
+ }
+
+ private switchPart(next: { stage: SearchStage; part: string; since: number } | null): { stage: SearchStage; part: string; since: number } | null {
+ const at = this.now();
+ const previous = this.currentPart;
+ if (previous) this.bookPart(previous.stage, previous.part, at - previous.since);
+ if (next) {
+ next.since = at;
+ if (!this.parts.get(next.stage)?.has(next.part)) this.bookPart(next.stage, next.part, 0);
+ }
+ this.currentPart = next;
+ return previous;
+ }
+
+ private bookPart(stage: SearchStage, part: string, ms: number): void {
+ let byPart = this.parts.get(stage);
+ if (!byPart) this.parts.set(stage, byPart = new Map());
+ byPart.set(part, (byPart.get(part) ?? 0) + ms);
+ }
+
overlap<T>(label: string, work: Promise<T>): Promise<T> {
const started = this.now();
const settle = () => { this.overlapped.set(label, (this.overlapped.get(label) ?? 0) + this.now() - started); };
@@ -128,11 +165,18 @@ export class SearchTimings implements StageTimer {
const other = Math.max(0, total - parts.reduce((sum, [, ms]) => sum + ms, 0));
const ints = apportion([...parts.map(([, ms]) => ms), other], Math.round(total));
const overlappedMs = Object.fromEntries([...this.overlapped].map(([label, ms]) => [label, Math.round(ms)]));
+ const partSpent = new Map([...this.parts].map(([stage, byPart]) => [stage, new Map(byPart)]));
+ if (this.currentPart) {
+ const { stage, part, since } = this.currentPart;
+ partSpent.get(stage)!.set(part, partSpent.get(stage)!.get(part)! + at - since);
+ }
+ const partsMs = Object.fromEntries([...partSpent].map(([stage, byPart]) => [stage, Object.fromEntries([...byPart].map(([part, ms]) => [part, Math.round(ms)]))]));
return {
total_ms: Math.round(total),
stages_ms: Object.fromEntries(parts.map(([stage], i) => [stage, ints[i]])),
other_ms: ints[ints.length - 1],
...(this.overlapped.size > 0 ? { overlapped_ms: overlappedMs } : {}),
+ ...(partSpent.size > 0 ? { parts_ms: partsMs } : {}),
};
}
}
@@ -208,11 +252,13 @@ function apportion(values: number[], total: number): number[] {
return floors;
}
-/** One `--explain` header line: `timings: 142ms total — lexical 12, embed 30, …, other 5 (overlapped: keyword_arm 10)`. */
+/** One `--explain` header line: `timings: 142ms total — lexical 12, embed 30, …, other 5 (overlapped: keyword_arm 10) (parts: response.meta 3)`. */
export function formatTimingsSummary(timings: SearchTimingsMeta | undefined): string | null {
if (!timings || typeof timings.total_ms !== 'number') return null;
const stages = Object.entries(timings.stages_ms ?? {}).map(([stage, ms]) => `${stage} ${ms}`);
const overlapped = Object.entries(timings.overlapped_ms ?? {}).map(([label, ms]) => `${label} ${ms}`);
+ const parts = Object.entries(timings.parts_ms ?? {}).flatMap(([stage, byPart]) => Object.entries(byPart ?? {}).map(([part, ms]) => `${stage}.${part} ${ms}`));
return `timings: ${timings.total_ms}ms total — ${[...stages, `other ${timings.other_ms}`].join(', ')}`
- + (overlapped.length > 0 ? ` (overlapped: ${overlapped.join(', ')})` : '');
+ + (overlapped.length > 0 ? ` (overlapped: ${overlapped.join(', ')})` : '')
+ + (parts.length > 0 ? ` (parts: ${parts.join(', ')})` : '');
}
diff --git a/src/core/supabase-pooler-url.ts b/src/core/supabase-pooler-url.ts
new file mode 100644
index 0000000000..9d150273e4
--- /dev/null
+++ b/src/core/supabase-pooler-url.ts
@@ -0,0 +1,112 @@
+/**
+ * Supabase pooler URL shapes: detection, the derived direct URL and the derived
+ * session-pooler URL. Pure string work with no driver import, so error
+ * classification (pg-access-classify.ts, loaded by every CLI error renderer)
+ * reads them without loading the Postgres driver; connection-manager.ts
+ * routes its pools with them and re-exports them.
+ */
+
+/**
+ * Hostname patterns that indicate a Supabase pooler. Used for auto-detection
+ * of the dual-pool topology. Adding more patterns is safe; mis-detection
+ * just means we open a "direct" pool against the same URL — wasteful but
+ * not broken (the kill-switch is the operator's escape hatch).
+ */
+const SUPABASE_POOLER_HOSTNAME_PATTERNS = [
+ /\.pooler\.supabase\.com$/i,
+ /^pooler\.supabase\.com$/i,
+];
+
+const SUPABASE_POOLER_PORTS = new Set(['6543']);
+
+/**
+ * True if the URL looks like a Supabase pooler endpoint. Used for kill-switch
+ * activation and dual-pool routing.
+ */
+export function isSupabasePoolerUrl(url: string): boolean {
+ try {
+ const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));
+ if (SUPABASE_POOLER_PORTS.has(parsed.port)) return true;
+ if (SUPABASE_POOLER_HOSTNAME_PATTERNS.some(re => re.test(parsed.hostname))) return true;
+ return false;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Derive a direct (non-pooler) URL from a Supabase pooler URL. Two known shapes:
+ *
+ * Pooler hostname: aws-N-region.pooler.supabase.com on port 6543
+ * → swap to db.<project-ref>.supabase.co on port 5432
+ * (project-ref encoded in the user component as postgres.<ref>)
+ * Direct hostname: db.<ref>.supabase.co already on port 5432 → returned as-is
+ *
+ * For the modern shape, we try to extract project-ref from the user component.
+ * If we cannot, we fall back to swapping port-only and the caller may warn.
+ *
+ * Returns null when the URL isn't a recognized Supabase pooler.
+ */
+export function deriveDirectUrl(url: string): string | null {
+ try {
+ const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));
+ const port = parsed.port;
+ const hostname = parsed.hostname;
+ const isPoolerHost = SUPABASE_POOLER_HOSTNAME_PATTERNS.some(re => re.test(hostname));
+ if (port !== '6543' && !isPoolerHost) return null;
+ // User part on Supabase pooler is typically `postgres.<project-ref>`.
+ // Extract <project-ref> for the direct hostname.
+ const user = parsed.username || '';
+ const decodedUser = decodeURIComponent(user);
+ const refMatch = decodedUser.match(/^postgres\.([a-z0-9]+)$/i);
+ let directHost = hostname;
+ let directUser = parsed.username;
+ if (refMatch && refMatch[1] && isPoolerHost) {
+ directHost = `db.${refMatch[1]}.supabase.co`;
+ // Supabase direct connections use bare `postgres`; the `postgres.<ref>`
+ // form is pooler-only (Supavisor uses the suffix for tenant routing).
+ // Without this strip, direct auth fails with `password authentication
+ // failed for user "postgres.<ref>"` even though the password is correct.
+ directUser = 'postgres';
+ }
+ // Compose direct URL by swapping host + port. Preserve auth, db, query.
+ parsed.hostname = directHost;
+ parsed.port = '5432';
+ // Reconstruct with the original scheme.
+ const scheme = url.match(/^postgres(?:ql)?:\/\//i)?.[0] ?? 'postgres://';
+ const auth = directUser
+ ? `${directUser}${parsed.password ? `:${parsed.password}` : ''}@`
+ : '';
+ const search = parsed.search ?? '';
+ const path = parsed.pathname ?? '';
+ return `${scheme}${auth}${directHost}:5432${path}${search}`;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Derive the SESSION-mode pooler URL from a TRANSACTION-mode pooler URL
+ * (#1915): same pooler host, port 6543 → 5432, KEEPING the postgres.<ref>
+ * user (Supavisor needs the tenant suffix — unlike deriveDirectUrl, which
+ * strips it for the db.<ref> host). The session pooler is IPv4-reachable and
+ * honors the direct pool's startup-parameter timeouts, so it is the natural
+ * second choice when the auto-derived db.<ref>.supabase.co host is
+ * IPv6-unreachable (Railway, most home ISPs). Returns null when the URL
+ * isn't a Supabase transaction-pooler shape (pooler hostname + port 6543 —
+ * a bare :6543 on an unknown host proves nothing about what :5432 serves).
+ */
+export function deriveSessionPoolerUrl(url: string): string | null {
+ try {
+ const parsed = new URL(url.replace(/^postgres(ql)?:\/\//, 'http://'));
+ const isPoolerHost = SUPABASE_POOLER_HOSTNAME_PATTERNS.some(re => re.test(parsed.hostname));
+ if (!isPoolerHost || parsed.port !== '6543') return null;
+ const scheme = url.match(/^postgres(?:ql)?:\/\//i)?.[0] ?? 'postgres://';
+ const auth = parsed.username
+ ? `${parsed.username}${parsed.password ? `:${parsed.password}` : ''}@`
+ : '';
+ return `${scheme}${auth}${parsed.hostname}:5432${parsed.pathname ?? ''}${parsed.search ?? ''}`;
+ } catch {
+ return null;
+ }
+}
diff --git a/test/cli-search-timings.test.ts b/test/cli-search-timings.test.ts
index 87e9cf4c95..3b6e492754 100644
--- a/test/cli-search-timings.test.ts
+++ b/test/cli-search-timings.test.ts
@@ -52,6 +52,14 @@ describe('formatResult with --timings', () => {
expect(t.remote).toBeUndefined();
});
+ test('the op\'s stage parts ride along as parts', () => {
+ setCliOptions({ ...DEFAULT_CLI_OPTIONS, timings: true });
+ captureRetrievalMeta('retrieval', { ...META, timings: { ...META.timings, parts_ms: { response: { evidence: 1, meta: 2 } } } });
+ const t = JSON.parse(formatResult('search', [], { json: true })).timings_ms;
+ expect(t.parts).toEqual({ response: { evidence: 1, meta: 2 } });
+ expect(t.stages).toEqual({ setup: 5, lexical: 20, embed: 10, response: 3, other: 2 });
+ });
+
test('a phase that did not run is absent, and a missing cost reads as zero calls', () => {
setCliOptions({ ...DEFAULT_CLI_OPTIONS, timings: true });
const doc = JSON.parse(formatResult('query', [], { json: true }));
diff --git a/test/cli-socket-warm-graph.test.ts b/test/cli-socket-warm-graph.test.ts
new file mode 100644
index 0000000000..330dbe53a7
--- /dev/null
+++ b/test/cli-socket-warm-graph.test.ts
@@ -0,0 +1,158 @@
+/**
+ * Warm CLI socket startup: what a CLI process loads before it sends its
+ * request to a serve's socket, and before it exits after printing the reply.
+ *
+ * 1. Protects: a socket hit never opens a database, so it must not pay for
+ * the operation's handler graph (src/core/ops/search.ts, ops/pages.ts and
+ * the AI SDK behind them), the Postgres driver (src/core/db.ts) or the MCP
+ * client. Loading those took most of a warm hit's CLI time: the request
+ * went out only after the handler module of an op the serve runs anyway.
+ * 2. Fails when: the socket path loads the op through loadOperation again,
+ * cli-force-exit.ts or pg-access-classify.ts reach db.ts statically, the
+ * dispatcher imports the segmented-page reader or volunteer formatter
+ * statically, or recall.ts imports mcp-client.ts statically.
+ * 3. Existing coverage: test/cli-socket.test.ts covers the exchange and the
+ * renderer in process; test/e2e/cli-socket-postgres.test.ts compares warm
+ * and cold bytes against a real serve. Neither looked at the module graph.
+ * 4. Seam: a --preload module records require.cache when the CLI calls
+ * net.createConnection and again at exit; a fake serve in this process
+ * answers the request. No database is opened.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import net from 'node:net';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { peerCredSupport } from '../src/core/cli-socket/peer-cred.ts';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+
+const PROBE = `
+import net from 'node:net';
+import { writeFileSync } from 'node:fs';
+const loaded = () => Object.keys(require.cache);
+const seen = { send: null, exit: null };
+const createConnection = net.createConnection;
+net.createConnection = (...args) => { seen.send ??= loaded(); return createConnection(...args); };
+process.on('exit', () => { seen.exit = loaded(); writeFileSync(process.env.GRAPH_PROBE_OUT, JSON.stringify(seen)); });
+`;
+
+/** Modules a warm hit has no use for, before the send or after it. */
+const NEVER_LOADED: Array<[string, (m: string) => boolean]> = [
+ ['operation registry', m => m.endsWith('/src/core/operations.ts')],
+ ['search op handlers', m => m.endsWith('/src/core/ops/search.ts')],
+ ['page op handlers', m => m.endsWith('/src/core/ops/pages.ts')],
+ ['facts op handlers', m => m.endsWith('/src/core/ops/facts.ts')],
+ ['Postgres driver', m => m.endsWith('/src/core/db.ts') || m.includes('/vendor/postgres/')],
+ ['MCP client', m => m.endsWith('/src/core/mcp-client.ts') || m.includes('/node_modules/@modelcontextprotocol/')],
+ ['AI SDK', m => /\/node_modules\/(ai|@ai-sdk|zod)\//.test(m)],
+ ['segmented page reader', m => m.endsWith('/src/core/page-window/segmented.ts') || m.endsWith('/src/core/page-body/read-range.ts')],
+ ['volunteer formatter', m => m.endsWith('/src/core/context/volunteer.ts')],
+];
+
+function heavy(modules: string[]): string[] {
+ return NEVER_LOADED.filter(([, hit]) => modules.some(hit)).map(([name]) => name);
+}
+
+const SEARCH_ROW = {
+ slug: 'notes/alpha-example', page_id: 1, title: 'Alpha example', type: 'note', chunk_text: 'zephyrquartz synthetic page.',
+ chunk_source: 'compiled_truth', chunk_id: 1, chunk_index: 0, score: 0.5, stale: false, source_id: 'default',
+};
+
+/** The result a serve answers each request kind with. */
+function answer(request: { kind: string; op?: string }): unknown {
+ if (request.kind === 'recall') {
+ return { facts: [{ fact_id: 1, kind: 'fact', fact: 'zephyrquartz synthetic fact', provenance: 'test', entity_slug: null }], results: [] };
+ }
+ if (request.op === 'get_page') {
+ return { slug: 'notes/alpha-example', title: 'Alpha example', type: 'note', frontmatter: {}, compiled_truth: 'zephyrquartz synthetic body.', timeline: '', tags: [] };
+ }
+ return [SEARCH_ROW];
+}
+
+describe.skipIf(!peerCredSupport().ok)('warm CLI socket module graph', () => {
+ let root: string;
+ let server: net.Server;
+ const requests: Array<{ kind: string; op?: string }> = [];
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-cli-sock-graph-'));
+ mkdirSync(join(root, '.gbrain', 'run'), { recursive: true, mode: 0o700 });
+ writeFileSync(join(root, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: 'postgresql://[email protected]:9/never-opened' }), { mode: 0o600 });
+ writeFileSync(join(root, 'probe.ts'), PROBE);
+ const path = join(root, '.gbrain', 'run', 'cli.sock');
+ server = net.createServer(socket => {
+ let buffered = '';
+ socket.on('data', data => {
+ buffered += String(data);
+ if (!buffered.includes('\n')) return;
+ const request = JSON.parse(buffered.slice(0, buffered.indexOf('\n')));
+ requests.push(request);
+ const frame = { v: 1, kind: 'result', result: answer(request), meta: null, notices: [], output: [], source: 'default' };
+ socket.end(`${JSON.stringify({ v: 1, accepted: true })}\n${JSON.stringify(frame)}\n`);
+ });
+ });
+ await new Promise<void>(done => server.listen(path, done));
+ chmodSync(path, 0o600);
+ });
+
+ afterAll(async () => {
+ await new Promise<void>(done => server.close(() => done()));
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ async function warm(args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number; send: string[]; exit: string[] }> {
+ const out = join(root, `graph-${requests.length}.json`);
+ const env = keylessBrainEnv(process.env, root, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_ENGINE: undefined, GBRAIN_SOURCE: undefined, GBRAIN_BRAIN_ID: undefined,
+ GBRAIN_CLI_SOCKET: '1', GBRAIN_DEBUG: '1', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_NO_RETRY_CONNECT: '1', GRAPH_PROBE_OUT: out,
+ });
+ const proc = Bun.spawn([process.execPath, '--no-env-file', '--preload', join(root, 'probe.ts'), join(REPO, 'src/cli.ts'), ...args], {
+ cwd: root, env, stdout: 'pipe', stderr: 'pipe',
+ });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ const graph = JSON.parse(readFileSync(out, 'utf8')) as { send: string[] | null; exit: string[] };
+ return { stdout, stderr, exitCode, send: graph.send ?? [], exit: graph.exit };
+ }
+
+ test('search answered by the socket loads no handler, driver or AI graph before the send or after the reply', async () => {
+ const run = await warm(['search', 'zephyrquartz', '--json']);
+ expect(run.stderr).toContain('[cli-socket] warm: search answered by the serve socket');
+ expect(run.exitCode).toBe(0);
+ expect(JSON.parse(run.stdout).map((row: { slug: string }) => row.slug)).toEqual(['notes/alpha-example']);
+ expect(requests.at(-1)).toMatchObject({ kind: 'op', op: 'search', params: { query: 'zephyrquartz', json: true } });
+ expect(run.send.length).toBeGreaterThan(0);
+ expect(heavy(run.send)).toEqual([]);
+ expect(heavy(run.exit)).toEqual([]);
+ }, 60_000);
+
+ test('get renders the page without the page handlers or the segmented reader', async () => {
+ const run = await warm(['get', 'notes/alpha-example']);
+ expect(run.stderr).toContain('[cli-socket] warm: get answered by the serve socket');
+ expect(run.exitCode).toBe(0);
+ expect(run.stdout).toContain('zephyrquartz synthetic body.');
+ expect(requests.at(-1)).toMatchObject({ kind: 'op', op: 'get_page', params: { slug: 'notes/alpha-example' } });
+ expect(heavy(run.send)).toEqual([]);
+ expect(heavy(run.exit)).toEqual([]);
+ }, 60_000);
+
+ test('recall --query sends before the MCP client or the Postgres driver loads', async () => {
+ const run = await warm(['recall', '--query', 'zephyrquartz', '--json']);
+ expect(run.stderr).toContain('[cli-socket] warm: recall answered by the serve socket');
+ expect(run.exitCode).toBe(0);
+ expect(JSON.parse(run.stdout).facts[0].fact).toBe('zephyrquartz synthetic fact');
+ expect(requests.at(-1)).toMatchObject({ kind: 'recall', args: ['--query', 'zephyrquartz', '--json'] });
+ expect(heavy(run.send)).toEqual([]);
+ expect(heavy(run.exit)).toEqual([]);
+ }, 60_000);
+});
+
+describe('CLI entry point', () => {
+ test('loads no Postgres driver: every command pays for what src/cli.ts imports', () => {
+ const r = Bun.spawnSync([process.execPath, '--no-env-file', '-e', `await import(${JSON.stringify(join(REPO, 'src/cli.ts'))}); console.log(JSON.stringify(Object.keys(require.cache)));`], { cwd: REPO });
+ expect(r.exitCode).toBe(0);
+ const modules = JSON.parse(r.stdout.toString().trim().split('\n').pop()!) as string[];
+ expect(modules.filter(m => m.endsWith('/src/core/db.ts') || m.includes('/vendor/postgres/'))).toEqual([]);
+ }, 60_000);
+});
diff --git a/test/search/saved-facts-probe.test.ts b/test/search/saved-facts-probe.test.ts
new file mode 100644
index 0000000000..013b791c25
--- /dev/null
+++ b/test/search/saved-facts-probe.test.ts
@@ -0,0 +1,99 @@
+/**
+ * The saved-fact match beside search/query blocks (ops/search.ts
+ * matchingSavedFacts) gates its LIKE scan on an uncorrelated EXISTS probe so
+ * a brain with no qualifying fact skips the scan. The probe must read the
+ * facts table alone: with the page-eligibility filters inside it (private
+ * provenance, quarantine, needs-rederive), Postgres planned it as merge anti
+ * joins against the pages index, which read every page on every search once
+ * a brain held many facts, so the probe's cost grew with the page count.
+ * The filters stay on the scan, so the returned facts are unchanged: a
+ * private-sourced or quarantined fact is still left out. PGLite, keyword-only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { newSource, page, putPage } from '../helpers/pinned-questions-fixture.ts';
+
+let engine: PGLiteEngine;
+let sourceId: string;
+const statements: string[] = [];
+const Q = 'harbor ferry timetable';
+const search = operations.find(o => o.name === 'search')!;
+
+async function savedFacts(remote: boolean): Promise<string[]> {
+ let meta: Record<string, any> | null = null;
+ const ctx = {
+ engine, config: { engine: engine.kind } as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote, sourceId,
+ emitResponseMeta: (key: string, value: unknown) => { if (key === 'retrieval') meta = value as Record<string, any>; },
+ } as OperationContext;
+ await search.handler(ctx, { query: Q, source_id: sourceId });
+ return ((meta as Record<string, any> | null)?.saved_facts ?? []).map((f: { fact: string }) => f.fact).sort();
+}
+
+/** The EXISTS probe of the saved-fact statement the last search ran. */
+function probeOf(sql: string): string {
+ const at = sql.indexOf('AND EXISTS (SELECT 1 FROM facts f WHERE');
+ expect(at).toBeGreaterThan(-1);
+ return sql.slice(at, sql.indexOf('LIMIT 1)', at));
+}
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ sourceId = await newSource(engine);
+ await putPage(engine, sourceId, 'notes/harbor-public', page('note', 'Harbor public', 'Public notes on the harbor ferry timetable.'));
+ await putPage(engine, sourceId, 'notes/harbor-private', page('note', 'Harbor private', 'Private notes on the harbor ferry.', 'visibility: private\n'));
+ await putPage(engine, sourceId, 'notes/harbor-held', page('note', 'Harbor held', 'Held notes on the harbor ferry.'));
+ await engine.executeRaw(`UPDATE pages SET frontmatter = COALESCE(frontmatter, '{}'::jsonb) || '{"quarantine": {"reason": "test"}}'::jsonb WHERE source_id = $1 AND slug = 'notes/harbor-held'`, [sourceId]);
+ const add = (fact: string, day: string) =>
+ engine.insertFact({ fact, kind: 'fact', entity_slug: 'harbor', source: 'notes', visibility: 'world', valid_from: new Date(`2025-07-${day}T00:00:00Z`) }, { source_id: sourceId });
+ await add('The harbor ferry timetable changes in May.', '12');
+ await add('The harbor ferry timetable moves to the private schedule.', '13');
+ await add('The harbor ferry timetable is under review.', '14');
+ await engine.executeRaw(`UPDATE facts SET source_markdown_slug = CASE
+ WHEN fact LIKE '%private%' THEN 'notes/harbor-private' WHEN fact LIKE '%review%' THEN 'notes/harbor-held' ELSE 'notes/harbor-public' END
+ WHERE source_id = $1`, [sourceId]);
+ // Unbound and called with the caller's `this`: a transaction-scoped view of the engine must keep its own executor.
+ const run = engine.executeRaw;
+ engine.executeRaw = function (this: PGLiteEngine, ...args: Parameters<typeof run>) {
+ if (args[0].includes('LIKE ANY($3::text[])') && args[0].includes('FROM facts f')) statements.push(args[0]);
+ return run.apply(this, args);
+ } as typeof engine.executeRaw;
+}, 120_000);
+
+afterAll(async () => { resetGateway(); await engine?.disconnect(); }, 60_000);
+
+describe('saved-fact match probe', () => {
+ test('the probe reads only the facts table; the scan keeps the page-eligibility filters', async () => {
+ statements.length = 0;
+ await savedFacts(true);
+ expect(statements).toHaveLength(1);
+ const probe = probeOf(statements[0]!);
+ expect(probe).not.toMatch(/\bpages\b/);
+ expect(probe).not.toContain('needs_rederive');
+ expect(probe).toContain("f.visibility = 'world'");
+ const scan = statements[0]!.slice(0, statements[0]!.indexOf('AND EXISTS (SELECT 1 FROM facts f WHERE'));
+ expect(scan).toContain('FROM pages pp');
+ expect(scan).toContain('needs_rederive');
+ });
+
+ test('a remote caller still gets only the fact whose provenance page it may read', async () => {
+ expect(await savedFacts(true)).toEqual(['The harbor ferry timetable changes in May.']);
+ });
+
+ test('a local caller sees the private-sourced fact; the quarantined page still hides its fact', async () => {
+ expect(await savedFacts(false)).toEqual(['The harbor ferry timetable changes in May.', 'The harbor ferry timetable moves to the private schedule.']);
+ });
+
+ test('when only ineligible facts exist, the match is empty', async () => {
+ await engine.executeRaw(`UPDATE facts SET expired_at = now() WHERE source_id = $1 AND source_markdown_slug = 'notes/harbor-public'`, [sourceId]);
+ try {
+ expect(await savedFacts(true)).toEqual([]);
+ } finally {
+ await engine.executeRaw(`UPDATE facts SET expired_at = NULL WHERE source_id = $1`, [sourceId]);
+ }
+ });
+});
diff --git a/test/search/stage-timings-ops.test.ts b/test/search/stage-timings-ops.test.ts
index f47504b922..8997fb770b 100644
--- a/test/search/stage-timings-ops.test.ts
+++ b/test/search/stage-timings-ops.test.ts
@@ -104,7 +104,10 @@ describe('timings ride every search and query response', () => {
for (const stage of ['setup', 'lexical', 'relational', 'embed', 'vector', 'fuse', 'post_fusion', 'rerank', 'alias_fanout', 'anchoring', 'response']) {
expect(t.stages_ms).toHaveProperty(stage);
}
- expect(Object.keys(t.overlapped_ms ?? {}).sort()).toEqual(['embed', 'keyword_arm', 'keyword_count', 'title_arm', 'vector']);
+ expect(Object.keys(t.overlapped_ms ?? {}).sort()).toEqual(['embed', 'keyword_arm', 'keyword_count', 'meta_embedding_held', 'meta_entity_facts', 'meta_filter_hint',
+ 'meta_freshness', 'meta_held', 'meta_readiness', 'meta_safe_index', 'meta_saved_facts', 'title_arm', 'vector']);
+ expect(Object.keys(t.parts_ms?.response ?? {}).sort()).toEqual(['evidence', 'feedback', 'keyword_count', 'meta', 'trust']);
+ expect(Object.values(t.parts_ms!.response!).reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(t.stages_ms.response! + 1);
});
test('query adds the facts arm and expansion stages', async () => {
diff --git a/test/search/stage-timings.test.ts b/test/search/stage-timings.test.ts
index 76a3472f3d..91c020af23 100644
--- a/test/search/stage-timings.test.ts
+++ b/test/search/stage-timings.test.ts
@@ -43,6 +43,32 @@ describe('SearchTimings attribution', () => {
expect(sum(s.stages_ms) + s.other_ms).toBe(s.total_ms);
});
+ test('parts split a stage into sequential steps without changing its booking; a nested part takes the clock', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ await t.stage('response', async () => {
+ await t.part('response', 'evidence', async () => { c.tick(3); });
+ await t.part('response', 'trust', async () => { c.tick(1); });
+ await t.part('response', 'meta', async () => {
+ c.tick(2);
+ await t.part('response', 'keyword_count', async () => { c.tick(4); });
+ c.tick(1);
+ });
+ c.tick(2);
+ });
+ expect(t.snapshot()).toEqual({ total_ms: 13, stages_ms: { response: 13 }, other_ms: 0, parts_ms: { response: { evidence: 3, trust: 1, meta: 3, keyword_count: 4 } } });
+ });
+
+ test('a part still running at the snapshot is booked up to it; a part that throws keeps its time', async () => {
+ const c = manualClock();
+ const t = new SearchTimings(c.now);
+ await expect(t.part('response', 'evidence', async () => { c.tick(5); throw new Error('fetch failed'); })).rejects.toThrow('fetch failed');
+ let inside: ReturnType<SearchTimings['snapshot']> | undefined;
+ await t.part('response', 'meta', async () => { c.tick(2); inside = t.snapshot(); });
+ expect(inside!.parts_ms).toEqual({ response: { evidence: 5, meta: 2 } });
+ expect(t.snapshot().parts_ms).toEqual({ response: { evidence: 5, meta: 2 } });
+ });
+
test('repeated stages (retries, a discarded escalation) accumulate', async () => {
const c = manualClock();
const t = new SearchTimings(c.now);
@@ -211,6 +237,11 @@ describe('--explain line', () => {
expect(formatTimingsSummary(undefined)).toBeNull();
});
+ test('formatTimingsSummary lists stage parts after the overlapped work', () => {
+ expect(formatTimingsSummary({ ...timings, parts_ms: { response: { evidence: 1, meta: 2 } } }))
+ .toBe('timings: 142ms total — setup 3, lexical 12, embed 30, response 4, other 2 (overlapped: keyword_arm 11, title_arm 9) (parts: response.evidence 1, response.meta 2)');
+ });
+
test('formatResultsExplain prints the timings line in its header', () => {
const out = formatResultsExplain([{ slug: 'notes/a', score: 1, chunk_text: 'x' } as never], { vector_enabled: false, expansion_applied: false, detail_resolved: null, timings } as never);
expect(out.split('\n')).toContain(formatTimingsSummary(timings)!);