Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
large pages #6722: embed_skip pages keep keyword chunks (no vectors); size_state on put_page, remember and sync receipts
garrytane3ebcc4f7e15
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex 58e0f0c591..6e37340fca 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -34,8 +34,8 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.-- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation). `listBudgetLimitedPages` feeds doctor `partial_embedding` and `gbrain embed --held`. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`.-- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`, body under the effective `bytes_block`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with the marker and `content_flag: oversized` removed, `forceRechunk` and no embedding: CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview/approve commands.+- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation). `listBudgetLimitedPages` feeds doctor `partial_embedding` and `gbrain embed --held`. #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.+- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with `forceRechunk` and no embedding: under the effective `bytes_block` the marker and `content_flag: oversized` are removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (`rechunked_over_block`, #6722). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview/approve commands.- `src/core/extraction-watermark.ts` — large pages A7: no silent head-only page extraction. `planExtraction(body, stored, { cap, pipeline, emptyTail })` decides what one extraction reads: the whole body when it fits `cap` (`full`); the text past a stored watermark when the body still starts with exactly the watermarked prefix (`tail`; UTF-8 byte offset + sha256 of the prefix + `EXTRACTION_PIPELINE_VERSION`), its newest `cap` characters when the tail is longer (receipt `tail_window`, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (`truncateUtf8`) with receipt `head` and reason `no_watermark` / `prefix_changed` / `version_changed` / `no_new_text`. An empty tail is a skip (`facts_backstop`) or a head re-read (`extract_atoms`, after a cap rise). `readPageWatermark` (by source + slug, fail-soft), `commitExtractionPlan` (after a successful extraction: the watermark moves to the end of the planned body; a full read clears `input_truncated`, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) and `setExtractionReceipt` (the conversation-facts size skip, no watermark) write `page_extraction_state` (migration v247; hashes, offsets and counts only, rows cascade with the page). Doctor `extraction_input_truncated` reads the receipts. Tests: `test/extraction-watermark.test.ts`, `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`.- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 95b9b98822..37d1095b40 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -109,10 +109,31 @@ whole body again in history on every write.An operator who set a lower `content_sanity.bytes_block` (the`GBRAIN_PAGE_BLOCK_BYTES` env var, the config file, or the database config)-keeps the old behavior above that value: such a page is stored with an-`embed_skip` marker and no chunks, so search doesn't find it. The default is+stops embedding above that value: such a page is stored with an `embed_skip`+marker and gets no vectors, but it is still chunked, so keyword search finds+it. The same holds for any page with an `embed_skip` marker. The default isthe 24 MiB ceiling, so nothing is skipped for size unless someone lowered it.+**What a write says about size.** `put_page`, `remember` and sync receipts+carry the same field for a large or `embed_skip` page, so the writer learns on+the write itself, without reading the sync log. `size_state` on a page receipt+(and on `remember` when it appended to such a page) is+`{ embedding, reason, bytes }`; a sync receipt has `size_states`:+`{ total, pages }` with the first 50 pages, each with its `slug`, `path` (a+managed sync) and the same fields, and the sync output prints a line per page.+An ordinary page carries no field.++| `embedding` | `reason` | What happened |+| --- | --- | --- |+| `deferred` | `large_page` | Over 1 MiB: committed with chunks and no vectors; the embedding sweep embeds it after the commit, under `embed.max_usd_per_page`. |+| `partial` | `spend_cap` | The per-page cap stopped embedding; the rest stays keyword-only. |+| `held` | e.g. `upgrade_backfill` | Embedding waits for the user's approval of the previewed cost (`gbrain embed --held`). |+| `skipped` | `oversized` | Over the operator's `bytes_block`: chunked and keyword-searchable, never embedded. |+| `skipped` | `operator_marker` | Another `embed_skip` marker: chunked and keyword-searchable, never embedded. |++A body over the 24 MiB ceiling has no receipt: the write is refused as+`request_too_large`.+<a id="large-page-limits"></a>### Limits per entry point@@ -165,7 +186,8 @@ for up to two minutes, on the CPU, on keyless brains too, and prints a receipt;`gbrain reindex --oversized` does the rest. The backfill is idempotent andresumes where it stopped. It removes only gate-written markers whose reason is`oversized`, and the matching `content_flag: oversized`; a page above the-operator's effective `bytes_block` keeps both. The backfill never embeds.+operator's effective `bytes_block` keeps both and is re-chunked for keyword+search with no vectors. The backfill never embeds.Backfilled pages over 1 MiB are held for consent; the post-upgrade notice anddoctor's `partial_embedding` check show how many are held and what embeddingthem would cost. Pages between 500 KB and 1 MiB cost a cent or two each anddiff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 6c93b21f00..2b98089d9a 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -39,7 +39,7 @@ src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 basrc/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/embed-stale.ts embedStaleForSource 303 TODO: large-pages A9/T3: per-page spend cap meters each page in embedOneKey (logic in core/page-embedding-budget.ts meterStaleBatch/spendGrant)src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/import-file.ts importFromContent 670 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep+src/core/import-file.ts importFromContent 671 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker)src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut itsrc/core/minions/handlers/subagent.ts makeSubagentHandler 887 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loopsrc/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 817 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loopdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 023f5c8f0d..310154d747 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -6,7 +6,7 @@src/cli/main.ts 3009 ratchet +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.tssrc/commands/autopilot.ts 1642 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)src/commands/doctor.ts 667 ratchet +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-src/commands/embed.ts 2264 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+src/commands/embed.ts 2265 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)src/commands/extract-conversation-facts.ts 2087 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts)src/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baselinesrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes@@ -17,7 +17,7 @@ src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail runsrc/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2789 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts)-src/core/import-file.ts 2031 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep+src/core/import-file.ts 2032 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)src/core/pglite-engine.ts 3032 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts)@@ -37,7 +37,7 @@ src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap insrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeoutsrc/core/config.ts 1974 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold-src/core/persistence/sync-run.ts 1684 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next+src/core/persistence/sync-run.ts 1687 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState)src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 704 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts)diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 9a5b3d507f..f79dd5ffca 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -33,7 +33,7 @@ import { slog, serr } from '../core/console-prefix.ts';import { embedBudgetStopVerdict, noteEmbedBudgetStop } from '../core/embed-budget-stop.ts';import { embedCostCap, embedCostStopVerdict, noteEmbedCostStop } from '../core/embed-cost-cap.ts';import type { Authorization } from '../core/consent.ts';-import { filterOutEmbedSkipped } from '../core/embed-skip.ts';+import { filterOutEmbedSkipped, isEmbedSkipped } from '../core/embed-skip.ts';import { runSlidingPool } from '../core/worker-pool.ts';import { isAborted, anySignal, AbortError } from '../core/abort-check.ts';import { type DbPacer, createDbPacer, createNoopPacer, observed } from '../core/db-pacer.ts';@@ -1087,6 +1087,7 @@ async function embedPage(}const snapshot = origin.snapshot;const page = snapshot.page;+ if (isEmbedSkipped(page.frontmatter)) { if (!quiet) serr(` ${slug}: skipped (frontmatter.embed_skip set); its chunks stay keyword-searchable`); return; }// Get existing chunks or create new ones.// In dryRun, we still chunk the text locally to count what WOULD bediff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex 4305227391..340170334a 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -105,9 +105,10 @@ TARGETS (exactly one required)--vectors Rebuild every HNSW vector index from the stored vectors(no re-embedding, no cost). Run after a PGLite WAL repair.--oversized Re-chunk pages an older gbrain stored without chunks- because they were over 500 KB (embed_skip: oversized),- when they are under content_sanity.bytes_block (default:- the 24 MiB page ceiling). CPU only and free: it works+ because they were over 500 KB (embed_skip: oversized).+ Under content_sanity.bytes_block (default: the 24 MiB+ page ceiling) the marker is removed; over it the marker+ stays and the page gets no vectors. CPU only and free: it workswith embeddings off and makes them keyword-searchablenow. Pages over 1 MiB wait for approval before any paidembedding (gbrain embed --held). Resumable.diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.tsindex d3848a47df..daf4046d3c 100644--- a/src/commands/sync-diagnostics.ts+++ b/src/commands/sync-diagnostics.ts@@ -1,6 +1,7 @@import type { SyncResult } from './sync.ts';import type { GitHoldItem } from '../core/persistence/sync-holds.ts';import { fenceWhere } from '../core/fence-repair/refusal.ts';+import { sizeStateLines } from '../core/page-embedding-budget.ts';const HOLD_LINES = 20;@@ -38,6 +39,7 @@ export function printHoldNotes(result: SyncResult, write: (line: string) => void// #6188: lossless fence rewrites (committed), and in a dry run the ones a real run would make.if (result.fences_normalized) write(` Normalized fences in ${result.fences_normalized.count} file(s) (${classList(result.fences_normalized.by_class)}). ${result.fences_normalized.fix.why}`);if (result.fence_issues) write(` ${result.fence_issues.why} ${result.fence_issues.sample.slice(0, 5).map(item => item.path).join(', ')}`);+ for (const line of sizeStateLines(result.size_states)) write(line);for (const item of (result.would_normalize ?? []).slice(0, HOLD_LINES)) write(` Would normalize ${item.path}: ${item.classes.join(', ')} (rewritten losslessly and committed; preparation may pick other new row numbers).`);if ((result.would_normalize_count ?? 0) > HOLD_LINES) write(` ... and ${result.would_normalize_count! - HOLD_LINES} more would be normalized (--json lists them).`);}diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex f8c28b0f9c..2ddd180ae8 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -22,7 +22,7 @@ export interface SyncResult {/** #6643: the request a `--retry-failed` rediscovery waits for (its producer and slug), instead of a silent no-op. */retryWait?: import('../core/persistence/sync-run.ts').RetryWait;/** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. */- knockOns?: { refrozen: number };+ knockOns?: { refrozen: number }; /** #6722: pages this run left large or embed_skip (chunked, keyword-searchable) and their embedding state. */ size_states?: import('../core/page-embedding-budget.ts').SyncSizeStates;status: 'up_to_date' | 'synced' | 'first_sync' | 'dry_run' | 'blocked_by_failures' | 'partial';fromCommit: string | null;toCommit: string;diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.tsindex fff6159637..2581726a86 100644--- a/src/commands/sync/finalize.ts+++ b/src/commands/sync/finalize.ts@@ -177,6 +177,10 @@ export async function finalizeIncrementalSync(await backstopAffectedPageFacts(run, plan);const { embedded, embedSlugs } = await embedAffectedPages(run, plan, noEmbed);+ // #6722: the pages this run left large or embed_skip, read once after the imports.+ const { readPageSizeStates, addSizeState } = await import('../../core/page-embedding-budget.ts');+ const sizeStates = (await readPageSizeStates(engine, opts.sourceId ?? 'default', pagesAffected.filter(slug => !run.deletedSlugs.has(slug))))+ .reduce<import('../../core/page-embedding-budget.ts').SyncSizeStates | undefined>((tally, state) => addSizeState(tally, state), undefined);if (malformedSkipped.length > 0) {serr(@@ -205,6 +209,7 @@ export async function finalizeIncrementalSync(chunksCreated: run.chunksCreated,embedded,pagesAffected,+ ...(sizeStates ? { size_states: sizeStates } : {}),...(totalChanges > 100 && embedSlugs.length > 0 ? { embedDeferralReason: 'large_sync' as const } : {}),malformedSkipped: malformedSkipped.length,...(typeWarningsEnabled && typeWarnings.length > 0 ? { type_warnings: typeWarnings } : {}),diff --git a/src/commands/sync/full.ts b/src/commands/sync/full.tsindex 08f3678b75..87492937fd 100644--- a/src/commands/sync/full.ts+++ b/src/commands/sync/full.ts@@ -219,6 +219,10 @@ export async function performFullSync(}}+ // #6722: a full sync walked every page of the source, so its large and embed_skip pages are all reported.+ const { readPageSizeStates, addSizeState } = await import('../../core/page-embedding-budget.ts');+ const sizeStates = (await readPageSizeStates(engine, fullSourceId, null))+ .reduce<import('../../core/page-embedding-budget.ts').SyncSizeStates | undefined>((tally, state) => addSizeState(tally, state), undefined);return {status: 'first_sync',fromCommit: null,@@ -230,6 +234,7 @@ export async function performFullSync(chunksCreated: result.chunksCreated,embedded,pagesAffected: [],+ ...(sizeStates ? { size_states: sizeStates } : {}),// Warning aggregates ride the result for worker/JSON consumers — a full// sync that only prints to a daemon's stderr hides them from cron// topologies (codex re-review; same rationale as the incremental path).diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 320ae2ab80..f3c397c88b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -589,7 +589,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: '`gbrain extract-conversation-facts` now checks a `raw_transcript` sidecar\'s size before reading it: a sidecar over the 25 MiB cap is skipped without being read (before, it was read whole and bypassed the cap), and the cap now applies to the text the parser reads, so a sidecar page whose own body is over the cap but whose sidecar is under it is no longer skipped. The cap is derived from the page ceiling and never sits below it. A size skip now leaves a durable receipt as well as the stderr line.' },{ since: 'TBD', text: 'Doctor has a new `extraction_input_truncated` check listing pages whose last extraction read only part of their input (facts from the head or the newest window of a long append, atoms cut at the input cap, conversation pages skipped for size), with sample slugs and the remedy. It warns when atoms or conversation-facts receipts exist (naming `gbrain config set cycle.extract_atoms.max_input_chars <n>`, a paid change for the user to decide); facts-only receipts are reported as info.' },// Large pages A6/A9/T33/T3/F10 (Lane 3). `since` is set at the merge-slot stamp.- { since: 'TBD', text: 'Pages up to 24 MiB are now stored, chunked and keyword-searchable: `content_sanity.bytes_block` defaults to the 24 MiB page ceiling (was 500 KB), so a page between 500 KB and 24 MiB is no longer stored with `embed_skip` and zero chunks. Import, sync, the managed sync read, CLI stdin (`gbrain put`, was 5 MB) and the MCP stdio message limit (was the SDK\'s 10 MiB) all admit a page at the ceiling; one byte more is refused with the limit named. Code files keep their 5 MB limit. Size refusals no longer tell agents to split pages under the ceiling. An operator who set a lower `bytes_block` keeps the old behavior above it. A `put_page` or `capture` body over the ceiling is refused as `request_too_large` before journal admission, so no write request is recorded for it and a body over the journal\'s intent-byte cap no longer returns retryable `queue_capacity`.' },+ { since: 'TBD', text: 'Pages up to 24 MiB are now stored, chunked and keyword-searchable: `content_sanity.bytes_block` defaults to the 24 MiB page ceiling (was 500 KB), so a page between 500 KB and 24 MiB is no longer stored with `embed_skip` and zero chunks. Import, sync, the managed sync read, CLI stdin (`gbrain put`, was 5 MB) and the MCP stdio message limit (was the SDK\'s 10 MiB) all admit a page at the ceiling; one byte more is refused with the limit named. Code files keep their 5 MB limit. Size refusals no longer tell agents to split pages under the ceiling. A page with an `embed_skip` marker, including one over an operator\'s lower `bytes_block`, keeps its chunks and stays keyword-searchable; it only gets no vectors (it used to drop to zero chunks). `put_page`, `remember` and sync receipts carry `size_state` (sync: `size_states`) naming a large or embed_skip page\'s embedding state: `deferred`, `partial`, `held` or `skipped`. A `put_page` or `capture` body over the ceiling is refused as `request_too_large` before journal admission, so no write request is recorded for it and a body over the journal\'s intent-byte cap no longer returns retryable `queue_capacity`.' },{ since: 'TBD', text: 'A page over 1 MiB now commits with its chunks keyword-searchable and no vectors, and is embedded after the write by the stale sweep, `gbrain embed` or the post-write embedding job, instead of embedding every chunk inline before the write commits. Each such page spends at most `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset; `off` disables it) over its lifetime per embedding model, newest chunks first; the run caps still apply and the lowest cap wins. A page the cap stopped, or one held for approval, leaves the stale queue, and doctor\'s new `partial_embedding` check names it with the approval command (`gbrain embed --held --max-usd N`, or `gbrain embed --slugs <slug> --max-usd N`). Before embedding, a large page whose head, middle and tail samples are all markup, or two of them match junk patterns, is held instead. Large pages use the free title context tier, never paid per-chunk synopses.' },{ since: 'TBD', text: '`gbrain upgrade` now re-indexes pages an older gbrain stored without chunks because they were over 500 KB (`embed_skip: oversized`) when they fit under the effective `bytes_block`: for up to two minutes in its post-upgrade step, then `gbrain reindex --oversized` (new; `--dry-run`, `--source`, `--limit`, `--json`) finishes. It is CPU-only, works with embeddings off, makes those pages keyword-searchable at once and prints a receipt. It removes only the gate-written marker and its `content_flag: oversized`. Pages over 1 MiB are held for embedding approval; the post-upgrade notice shows their count and estimated cost and asks before anything is spent.' },{ since: 'TBD', text: 'A page over 1 MiB keeps only its newest 5 large version snapshots in `page_versions` (each snapshot is a full copy of the body); its snapshots at or under 1 MiB, and every snapshot of a smaller page, are kept as before. The persistence journal now admits 64 MiB of outstanding write intent per principal (was 32 MiB), so a second ceiling-size write can wait behind the first. Write-through never writes a canonical file over the 25 MiB pre-push secret-scan limit: it skips with `over_push_scan_cap`, and a managed write that would produce one is refused with `request_too_large`.' },diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex aff9c90f67..9c32cd3d1f 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -634,18 +634,19 @@ export async function importFromContent(// reach the provider.// A large page commits with NULL vectors; the stale sweep embeds it under the// per-page cap and the sampled junk check, so no provider call holds the write.+ const noEmbed = opts.noEmbed || isEmbedSkipped(parsed.frontmatter);const largePage = isLargePageBytes(Buffer.byteLength(parsed.compiled_truth, 'utf-8') + Buffer.byteLength(parsed.timeline ?? '', 'utf-8'));const postCommitEmbedding = largePage ? undefined : opts.onPostCommitEmbedding;const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !postCommitEmbedding && chunks.length > 0&& !(opts.prepare && modeRequiresSynopsis(effectiveCRMode)) && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`);const reuseCtx = { slug, sourceId: sourceId ?? 'default', title: parsed.title, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' as const : 'none' as const };const reuseStoredVectors = (exec: BrainEngine, into: ChunkInput[], keepUnembedded = false) => reuseStoredChunkVectors(exec, into, { ...reuseCtx, prepared: !!opts.prepare, keepUnembedded });- const reused = reusable && !opts.noEmbed && !opts.prepare ? await reuseStoredVectors(engine, chunks) : new Map<number, number | null>();+ const reused = reusable && !noEmbed && !opts.prepare ? await reuseStoredVectors(engine, chunks) : new Map<number, number | null>();let embeddingPartial: EmbeddingZeroNormError | undefined;const embedChunks = async () => {const pending = chunks.map((_, i) => i).filter(i => !reused.has(i));- if (opts.noEmbed || pending.length === 0) return;+ if (noEmbed || pending.length === 0) return;const prefix =modeRequiresWrapper(effectiveCRMode) && !modeRequiresSynopsis(effectiveCRMode)? buildContextualPrefix(parsed.title, null)@@ -666,7 +667,7 @@ export async function importFromContent(// commit with NULL vectors and no embedding signature, and the stale sweep// (`gbrain embed --stale`, sync's embed pass, the cycle) embeds them once// the provider recovers.- let embeddingDeferred = largePage && !opts.noEmbed && chunks.length > 0;+ let embeddingDeferred = largePage && !noEmbed && chunks.length > 0;if (!opts.onPostCommitEmbedding && !largePage) {try {await embedChunks();@@ -788,7 +789,7 @@ export async function importFromContent(// embedded (not --no-embed), so a later model/dims swap is detectable// as stale via embed --stale. The deferred/backfill + per-slug embed// paths stamp too; this covers the inline import/sync path.- if (!opts.noEmbed && !postCommitEmbedding && !embeddingDeferred) {+ if (!noEmbed && !postCommitEmbedding && !embeddingDeferred) {// D9: signature is null when the gateway is unconfigured — skip the// stamp (a wrong signature is worse than none).const importSig = currentEmbeddingSignature();@@ -842,7 +843,7 @@ export async function importFromContent(if (!opts.coordinated) await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');await opts.beforeCommit?.(tx, slug);await disposition.persistReceipt(tx, { existed: !!existing });- if (postCommitEmbedding && !opts.noEmbed && chunks.length > 0) {+ if (postCommitEmbedding && !noEmbed && chunks.length > 0) {// Capture the complete installed projection before releasing the page// guard. Deferred provider results cannot replace newer text or chunks.persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);@@ -874,7 +875,7 @@ export async function importFromContent(});- if (postCommitEmbedding && !opts.noEmbed && chunks.length > 0) {+ if (postCommitEmbedding && !noEmbed && chunks.length > 0) {postCommitEmbedding(async () => {try {if (!persistedProjection) return { status: 'superseded' };diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.tsindex e86196785f..f0a664fb55 100644--- a/src/core/markdown-chunks.ts+++ b/src/core/markdown-chunks.ts@@ -5,7 +5,6 @@ import { chunkCodeText, detectCodeLanguage } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';import { credentialSafeProjection } from './credential-projection.ts';import { scanFencedBlocks, MAX_FENCES_PER_PAGE } from './fence-scan.ts';-import { isEmbedSkipped } from './embed-skip.ts';import { isQuarantined } from './quarantine.ts';import { resolveMaxChunkTokens } from './embedding-input-limit.ts';import { estimateEmbedTokens } from './chunkers/token-estimate.ts';@@ -167,8 +166,9 @@ export async function prepareMarkdownChunks(page: {timeline?: string;frontmatter?: Record<string, unknown> | null;}, maxChunkTokens?: number, overlay?: FenceChunkOverlay): Promise<ChunkInput[]> {- // Both dispositions intentionally have no live chunks, including code.- if (isEmbedSkipped(page.frontmatter) || isQuarantined(page.frontmatter)) return [];+ // A quarantined page has no live chunks. An embed_skip page keeps its chunks (keyword search) and gets no vectors:+ // every embedding path skips it (#6722), so a page under the ceiling never drops out of search for its size.+ if (isQuarantined(page.frontmatter)) return [];return overlaidChunks(page, maxChunkTokens ?? resolveMaxChunkTokens(), overlay, extractFencedChunks);}diff --git a/src/core/oversized-backfill.ts b/src/core/oversized-backfill.tsindex 7bfd588589..3c92ffdfd9 100644--- a/src/core/oversized-backfill.ts+++ b/src/core/oversized-backfill.ts@@ -15,9 +15,10 @@* once; the embedding sweep fills vectors later.** Limits are preserved: a page still above the effective `bytes_block`- * (env `GBRAIN_PAGE_BLOCK_BYTES`, file or DB `content_sanity.bytes_block`) is- * left as it is, and only the gate-written marker shape (`reason: oversized`)- * is touched. A large page (over `pages.inline_max_bytes`) is held in+ * (env `GBRAIN_PAGE_BLOCK_BYTES`, file or DB `content_sanity.bytes_block`)+ * keeps its marker and gets no vectors, and only the gate-written marker shape+ * (`reason: oversized`) is touched. A chunkless one is still re-chunked with+ * the marker kept (#6722), so every page up to the ceiling is keyword-searchable. A large page (over `pages.inline_max_bytes`) is held in* `page_embedding_budget` before its rewrite, so no paid embedding starts* until the user approves the previewed cost (`gbrain embed --held --max-usd N`).*@@ -46,6 +47,8 @@ export const BACKFILL_HOLD_REASON = 'upgrade_backfill';const OVERSIZED_MARKER_SQL = `p.deleted_at IS NULL AND p.frontmatter->'${EMBED_SKIP_KEY}'->>'reason' = 'oversized'`;const PAGE_BYTES_SQL = `(octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))`;+/** Under the block (marker removed), or over it, under the ceiling and chunkless (re-chunked, marker kept). $1 is the block. */+const CANDIDATE_SQL = `(${PAGE_BYTES_SQL} <= $1 OR (${PAGE_BYTES_SQL} <= ${PAGE_MAX_BYTES} AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)))`;export interface OversizedBackfillReceipt {dry_run: boolean;@@ -59,8 +62,10 @@ export interface OversizedBackfillReceipt {failed: Array<{ slug: string; source_id: string; error: string }>;/** Candidates this run did not reach (limit or time budget); the same command continues. */remaining: number;- /** Size-skipped pages still over the block; they stay as they are. */+ /** Size-skipped pages still over the block: they keep the marker and get no vectors. */over_block: number;+ /** Chunkless pages over the block this run re-chunked for keyword search, marker kept (#6722). */+ rechunked_over_block: number;chunks_pending_embedding: number;/** null when embeddings are off on this brain. */estimated_usd: number | null;@@ -75,28 +80,30 @@ async function listCandidates(engine: BrainEngine, block: number, opts: { sourceconst params: unknown[] = [block, opts.afterId, opts.limit];const source = opts.sourceId ? ` AND p.source_id = $${params.push(opts.sourceId)}` : '';const rows = await engine.executeRaw<Candidate>(`SELECT p.id, p.slug, p.source_id, ${PAGE_BYTES_SQL}::bigint AS bytes FROM pages p- WHERE ${OVERSIZED_MARKER_SQL} AND ${PAGE_BYTES_SQL} <= $1 AND p.id > $2${source} ORDER BY p.id LIMIT $3`, params);+ WHERE ${OVERSIZED_MARKER_SQL} AND ${CANDIDATE_SQL} AND p.id > $2${source} ORDER BY p.id LIMIT $3`, params);return rows.map(row => ({ ...row, id: Number(row.id), bytes: Number(row.bytes) }));}-async function countMarked(engine: BrainEngine, block: number, sourceId: string | undefined): Promise<{ under: number; over: number }> {+async function countMarked(engine: BrainEngine, block: number, sourceId: string | undefined): Promise<{ candidates: number; over: number }> {const params: unknown[] = [block];const source = sourceId ? ` AND p.source_id = $${params.push(sourceId)}` : '';- const [row] = await engine.executeRaw<{ under: number; over: number }>(`SELECT- COUNT(*) FILTER (WHERE ${PAGE_BYTES_SQL} <= $1)::int AS under, COUNT(*) FILTER (WHERE ${PAGE_BYTES_SQL} > $1)::int AS over+ const [row] = await engine.executeRaw<{ candidates: number; over: number }>(`SELECT+ COUNT(*) FILTER (WHERE ${CANDIDATE_SQL})::int AS candidates, COUNT(*) FILTER (WHERE ${PAGE_BYTES_SQL} > $1)::int AS overFROM pages p WHERE ${OVERSIZED_MARKER_SQL}${source}`, params);- return { under: Number(row?.under ?? 0), over: Number(row?.over ?? 0) };+ return { candidates: Number(row?.candidates ?? 0), over: Number(row?.over ?? 0) };}-/** Rewrite one page without its size-gate markers, re-chunked, with no embedding. */-async function reindexPage(engine: BrainEngine, page: Candidate, managed: boolean): Promise<void> {+/** Rewrite one page re-chunked with no embedding: without its size-gate markers under the block, with them kept over it. */+async function reindexPage(engine: BrainEngine, page: Candidate, managed: boolean, overBlock: boolean): Promise<void> {const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });if (!snapshot || snapshot.page.id !== page.id) return;const fm = { ...((snapshot.page.frontmatter ?? {}) as Record<string, unknown>) };if ((fm[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason !== 'oversized') return;- delete fm[EMBED_SKIP_KEY];- if ((fm[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete fm[CONTENT_FLAG_KEY];- if (isLargePageBytes(page.bytes)) await holdPageEmbedding(engine, page.id, BACKFILL_HOLD_REASON);+ if (!overBlock) {+ delete fm[EMBED_SKIP_KEY];+ if ((fm[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete fm[CONTENT_FLAG_KEY];+ if (isLargePageBytes(page.bytes)) await holdPageEmbedding(engine, page.id, BACKFILL_HOLD_REASON);+ }const markdown = serializeMarkdown(fm, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,});@@ -122,8 +129,8 @@ export async function runOversizedBackfill(engine: BrainEngine, opts: {const embeddingEnabled = loadConfig()?.embedding_disabled !== true;const scope = opts.sourceId ? ['--source', opts.sourceId] : [];const receipt: OversizedBackfillReceipt = {- dry_run: opts.dryRun === true, block_bytes: block, candidates: before.under, reindexed: 0, held_for_approval: 0, failed: [],- remaining: before.under, over_block: before.over, chunks_pending_embedding: 0, estimated_usd: null, embedding_enabled: embeddingEnabled,+ dry_run: opts.dryRun === true, block_bytes: block, candidates: before.candidates, reindexed: 0, held_for_approval: 0, failed: [],+ remaining: before.candidates, over_block: before.over, rechunked_over_block: 0, chunks_pending_embedding: 0, estimated_usd: null, embedding_enabled: embeddingEnabled,commands: { finish: ['gbrain', 'reindex', '--oversized', ...scope], approve: ['gbrain', 'embed', '--held', ...scope, '--max-usd', '<N>'],preview: ['gbrain', 'embed', '--held', ...scope, '--dry-run'] },};@@ -140,15 +147,18 @@ export async function runOversizedBackfill(engine: BrainEngine, opts: {afterId = page.id;attempted++;opts.onPage?.(page);+ const overBlock = page.bytes > block;if (receipt.dry_run) {+ if (overBlock) { receipt.rechunked_over_block++; continue; }if (isLargePageBytes(page.bytes)) receipt.held_for_approval++;pendingChars += page.bytes;continue;}try {- await reindexPage(engine, page, managed);- touched.push(page.id);+ await reindexPage(engine, page, managed, overBlock);receipt.reindexed++;+ if (overBlock) { receipt.rechunked_over_block++; continue; }+ touched.push(page.id);if (isLargePageBytes(page.bytes)) receipt.held_for_approval++;} catch (error) {receipt.failed.push({ slug: page.slug, source_id: page.source_id, error: (error instanceof Error ? error.message : String(error)).split('\n')[0].slice(0, 300) });@@ -162,18 +172,19 @@ export async function runOversizedBackfill(engine: BrainEngine, opts: {receipt.chunks_pending_embedding = Number(pending?.chunks ?? 0);pendingChars = Number(pending?.chars ?? 0);}- receipt.remaining = receipt.dry_run ? before.under : (await countMarked(engine, block, opts.sourceId)).under;+ receipt.remaining = receipt.dry_run ? before.candidates : (await countMarked(engine, block, opts.sourceId)).candidates;if (embeddingEnabled) receipt.estimated_usd = estimatePageEmbedUsd(pendingChars, currentEmbeddingSignature());return receipt;}/** Human lines for a receipt (stdout of `gbrain reindex --oversized` and post-upgrade). */export function formatOversizedBackfillReceipt(r: OversizedBackfillReceipt): string[] {- const lines = [`[reindex --oversized] ${r.dry_run ? 'Would re-index' : 'Re-indexed'} ${r.dry_run ? r.candidates : r.reindexed} size-skipped page(s) under the ${r.block_bytes}-byte bytes_block`+ const lines = [`[reindex --oversized] ${r.dry_run ? 'Would re-index' : 'Re-indexed'} ${r.dry_run ? r.candidates : r.reindexed} size-skipped page(s)`+ `${r.dry_run ? '' : `; ${r.chunks_pending_embedding} chunk(s) are keyword-searchable now and wait for embedding`}.`];if (r.failed.length) lines.push(` ${r.failed.length} page(s) failed (first: ${r.failed[0].source_id}/${r.failed[0].slug}: ${r.failed[0].error}); rerun: ${r.commands.finish.join(' ')}`);if (!r.dry_run && r.remaining > r.failed.length) lines.push(` ${r.remaining} page(s) remain; continue with: ${r.commands.finish.join(' ')}`);- if (r.over_block) lines.push(` ${r.over_block} page(s) stay size-skipped: they are over content_sanity.bytes_block (${r.block_bytes} bytes).`);+ if (r.over_block) lines.push(` ${r.over_block} page(s) get no vectors: they are over content_sanity.bytes_block (${r.block_bytes} bytes)`+ + `${r.rechunked_over_block ? `; ${r.rechunked_over_block} of them ${r.dry_run ? 'would be' : 'were'} re-chunked for keyword search` : ''}. Chunks keep them in keyword search.`);if (!r.embedding_enabled) lines.push(' Embeddings are off on this brain, so keyword search is the whole result; nothing is spent.');else if (r.held_for_approval) {lines.push(` ${r.held_for_approval} large page(s) wait for approval before embedding (about $${(r.estimated_usd ?? 0).toFixed(2)} in total). `@@ -192,7 +203,7 @@ export function formatOversizedBackfillReceipt(r: OversizedBackfillReceipt): strexport async function printOversizedBackfillUpgradeNotice(engine: BrainEngine): Promise<void> {try {const block = await effectiveBytesBlock(engine);- if ((await countMarked(engine, block, undefined)).under === 0) return;+ if ((await countMarked(engine, block, undefined)).candidates === 0) return;const receipt = await runOversizedBackfill(engine, { deadlineMs: 120_000 });const lines = ['', ...formatOversizedBackfillReceipt(receipt)];if (receipt.embedding_enabled && receipt.held_for_approval > 0) {diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex 824144b595..5e9b6cb892 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -34,7 +34,8 @@import type { BrainEngine } from './engine.ts';import { assessSampledJunk } from './content-sanity.ts';import { estimateCostFromChars, lookupEmbeddingPrice } from './embedding-pricing.ts';-import { isLargePageBytes } from './page-size-policy.ts';+import { PAGE_INLINE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';+import { isEmbedSkipped } from './embed-skip.ts';import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';export const PAGE_EMBED_CAP_KEY = 'embed.max_usd_per_page';@@ -234,3 +235,75 @@ export async function heldEmbedArgv(engine: BrainEngine, args: readonly string[]const rest = args.filter((a, i) => a !== '--held' && a !== '--source' && args[i - 1] !== '--source');return { argv: [...rest, '--source', sources[0], '--slugs', ...limited.map(row => row.slug)] };}++/**+ * #6722: what a write left a page's embedding in, for write, sync and+ * remember receipts. Null for an ordinary page (embedded with the write, or by+ * the post-write job). `deferred`: over the inline threshold, embedded after+ * the commit under the per-page cap. `partial`: the cap stopped it with chunks+ * left keyword-only. `held`: it waits for the user's approval. `skipped`: an+ * embed_skip marker (`oversized` when the gate set it because the page is over+ * the operator's bytes_block). Every such page is chunked and keyword-searchable.+ */+export interface PageSizeState { embedding: 'deferred' | 'partial' | 'held' | 'skipped'; reason: string; bytes: number }++export function pageSizeState(bytes: number, frontmatter: Record<string, unknown> | null | undefined,+ budget?: { state: PageBudgetState; reason: string | null } | null): PageSizeState | null {+ if (isEmbedSkipped(frontmatter)) {+ return { embedding: 'skipped', reason: (frontmatter!.embed_skip as { reason?: unknown } | null)?.reason === 'oversized' ? 'oversized' : 'operator_marker', bytes };+ }+ if (budget?.state === 'held') return { embedding: 'held', reason: budget.reason ?? 'awaiting_approval', bytes };+ if (budget?.state === 'capped') return { embedding: 'partial', reason: 'spend_cap', bytes };+ return isLargePageBytes(bytes) ? { embedding: 'deferred', reason: 'large_page', bytes } : null;+}++/**+ * pageSizeState for stored pages of one source with a non-null state: the given slugs, or (null) every+ * such page in the source, as a full sync walked them all.+ */+export async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slugs: readonly string[] | null): Promise<Array<{ slug: string } & PageSizeState>> {+ if (slugs?.length === 0) return [];+ const bytes = `(octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))`;+ const rows = await engine.executeRaw<{ slug: string; bytes: number; frontmatter: Record<string, unknown> | null; state: PageBudgetState | null; reason: string | null }>(+ `SELECT p.slug, ${bytes}::bigint AS bytes, p.frontmatter, b.state, b.reason+ FROM pages p LEFT JOIN page_embedding_budget b ON b.page_id = p.id+ WHERE p.source_id = $1 AND p.deleted_at IS NULL${slugs ? ' AND p.slug = ANY($3::text[])' : ''}+ AND (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip' OR ${bytes} > $2 OR b.page_id IS NOT NULL) ORDER BY p.slug`,+ slugs ? [sourceId, PAGE_INLINE_MAX_BYTES, [...slugs]] : [sourceId, PAGE_INLINE_MAX_BYTES]);+ return rows.flatMap(row => {+ const state = pageSizeState(Number(row.bytes), row.frontmatter, row.state ? { state: row.state, reason: row.reason } : null);+ return state ? [{ slug: row.slug, ...state }] : [];+ });+}++/** The receipt field for one written page: `{ size_state }` for a large or embed_skip page, else nothing (no query). */+export async function sizeStateField(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string,+ page: { compiled_truth?: string | null; timeline?: string | null; frontmatter?: Record<string, unknown> | null } | null | undefined): Promise<{ size_state?: PageSizeState }> {+ if (!page) return {};+ const bytes = Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8');+ if (!isLargePageBytes(bytes) && !isEmbedSkipped(page.frontmatter)) return {};+ const [state] = await readPageSizeStates(engine, sourceId, [slug]);+ return state ? { size_state: { embedding: state.embedding, reason: state.reason, bytes: state.bytes } } : {};+}++/** #6722: the sync receipt's tally of pages a run left large or embed_skip: the total and the first SIZE_STATE_SAMPLE. */+export interface SyncSizeStates { total: number; pages: Array<{ slug: string; path?: string } & PageSizeState> }+export const SIZE_STATE_SAMPLE = 50;++export function addSizeState(tally: SyncSizeStates | undefined, entry: { slug: string; path?: string } & PageSizeState): SyncSizeStates {+ const pages = tally?.pages ?? [];+ return { total: (tally?.total ?? 0) + 1, pages: pages.length < SIZE_STATE_SAMPLE ? [...pages, entry] : pages };+}++/** One line per sampled page for the sync output, and the rest as a count. */+export function sizeStateLines(tally: SyncSizeStates | undefined): string[] {+ if (!tally?.total) return [];+ const what = (s: PageSizeState) => s.embedding === 'skipped'+ ? `no vectors (${s.reason === 'oversized' ? 'over the content_sanity.bytes_block limit' : 'embed_skip marker'}); chunks keep it in keyword search`+ : s.embedding === 'held' ? `embedding held (${s.reason}); \`gbrain reindex --held\` previews the cost`+ : s.embedding === 'partial' ? 'partly embedded under embed.max_usd_per_page; the rest stays keyword-only'+ : 'large page; embedding runs after the commit under embed.max_usd_per_page';+ const lines = tally.pages.slice(0, 20).map(p => ` Size ${p.path ?? p.slug} (${p.bytes} bytes): ${what(p)}.`);+ if (tally.total > lines.length) lines.push(` ... and ${tally.total - lines.length} more large or embed_skip page(s) (--json lists the first ${tally.pages.length}).`);+ return lines;+}diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex 7fc558754d..a0ffced3c7 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -1,4 +1,5 @@import { withAIAttribution } from '../ai/invocation-guard.ts';+import { isEmbedSkipped } from '../embed-skip.ts';import { trueUpRequests } from './receipt-true-up.ts';import { randomUUID } from 'node:crypto';import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';@@ -308,6 +309,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Persif (!signature) throw opError('embedding_unconfigured', 'Configure an embedding provider before explicitly retrying.',`Page ${snapshot.page.slug} in source ${effect.source_id} was saved but cannot be embedded: this brain has no embedding provider. Pages and keyword search keep working; check embedding readiness and ask the user before configuring a paid provider.`,{ fix: embeddingsFix() });+ if (isEmbedSkipped(snapshot.page.frontmatter)) { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'embed_skip' }); return; }const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);const { prepared } = projection;let pending = projection.pending;diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex d5f19d5548..b029534bbe 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -169,7 +169,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeif (page.observedRevision !== observedRevision) conflict(row);}return { observedRevision, file: page?.file, ...(page?.exclusiveSources ? { exclusiveSources: page.exclusiveSources } : {}), validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {- if (page) await withPageTierKept(tx, { sourceId: row.source_id, slug: row.slug }, () => page!.apply(tx));+ const pageReceipt = page ? await withPageTierKept(tx, { sourceId: row.source_id, slug: row.slug }, () => page!.apply(tx)) as { size_state?: unknown } | undefined : undefined;let id: number;if (rowNum !== undefined) {const inserted = await tx.insertFacts([{ ...fact, row_num: rowNum, source_markdown_slug: row.slug }], { source_id: row.source_id }); // gbrain-allow-direct-insert: coordinator atomically publishes the prepared canonical fact fence and its new indexed row@@ -192,6 +192,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst superseded = status === 'superseded' ? decision.candidate! : undefined;return { ...outcome(id, status, input.entity_slug, validUntil, degraded, p, superseded?.id,superseded !== undefined && superseded.entity_slug == null && input.entity_slug !== null), ...fencesNormalized,- ...(contestedBy ? { contested: contestedBy } : {}), ...(flagged ? { gate: flagged } : {}) };+ ...(contestedBy ? { contested: contestedBy } : {}), ...(flagged ? { gate: flagged } : {}),+ ...(pageReceipt?.size_state ? { size_state: pageReceipt.size_state } : {}) };} };}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 7b538982e5..1342969c6d 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -1,4 +1,5 @@import { isEmbedSkipped } from '../embed-skip.ts';+import { sizeStateField } from '../page-embedding-budget.ts';import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { boundedReads } from './bounded-reads.ts';import { isQuarantined, quarantineOutcome } from '../quarantine.ts';@@ -649,10 +650,13 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ}const coreUsage = core?.usage();const gate = noop ? undefined : gateField(ready.result.gate, `p:${row.source_id}/${row.slug}`, null);+ // #6722: a large or embed_skip page says what this write left its embedding in.+ const sizeState = noop ? {} : await sizeStateField(tx, row.source_id, row.slug, ready.parsedPage);return { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}), ...(coreUsage ? { core: coreUsage } : {}),...(removedTimeline ? { timeline_rows_removed: timelineRowsRemovedAdvisory(row, removedTimeline) } : {}),status: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop,+ ...sizeState,...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),// #6259: say the gate hid the page, not only why it has no chunks.diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 4205dea3ef..29de0d9c7f 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -1,4 +1,5 @@import { existsSync, lstatSync, realpathSync } from 'node:fs';+import { sizeStateField } from '../page-embedding-budget.ts';import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';import { boundedReads } from './bounded-reads.ts';import { basename, dirname, join } from 'node:path';@@ -699,8 +700,10 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrraw_sha256: sha256(p.content!), ...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}) }); },]);preparedImport.postimage = final;+ // #6722: a large or embed_skip page says what this write left its embedding in.+ const sizeState = applied.noop ? {} : await sizeStateField(tx, row.source_id, row.slug, live?.page);return { status: moved ? 'renamed' : applied.noop ? 'skipped' : snapshot ? 'updated' : 'created', slug: row.slug, source_id: row.source_id,- chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}),+ chunks: applied.result.chunks, noop: applied.noop && !moved, imported_file: true, ...(moved ? { renamed_from: moved.slug } : {}), ...sizeState,...(recovery?.length ? { recovered_frontmatter: true } : {}), ...(commentValue ? { comment_value: true } : {}),...(fenceFixes.length ? { fences_normalized: fenceFixesWire(fenceFixes) } : {}) };} };diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex f1abb9099e..88187493a2 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -1,4 +1,5 @@import { randomUUID } from 'node:crypto';+import { addSizeState, type PageSizeState, type SyncSizeStates } from '../page-embedding-budget.ts';import type { BrainEngine, PageSnapshot } from '../engine.ts';import type { SyncOpts, SyncResult } from '../../commands/sync.ts';import { loadConfig } from '../config.ts';@@ -97,7 +98,7 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority/** #5988: imports held, and files imported only after quoting frontmatter. */held?: number; recovered?: { count: number; sample_paths: string[]; comment_values?: number };/** #6188: files whose fences Tier 1 rewrote (and the Git effect committed). */- fences?: FencesTally };+ fences?: FencesTally; /** #6722: committed pages left large or embed_skip, and their embedding state. */ sizeStates?: SyncSizeStates };/** #5988: failed content-refusal requests this run converted in place. */convertedFromFailed?: string[];/** #6643: the indexes this cursor passed without a commit (waived or held), recorded from `settled.from` on; the checkpoint carries them. */@@ -316,6 +317,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], reamanagedCursor: { index: cursor.index, total: 'total' in cursor ? cursor.total : cursor.entries.length, ...(cursor.progress ? { progress: cursor.progress } : {}) },...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),...(cursor.knockOns ? { knockOns: { refrozen: cursor.knockOns } } : {}),+ ...(cursor.counts.sizeStates?.total ? { size_states: cursor.counts.sizeStates } : {}),...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };}@@ -936,6 +938,8 @@ function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: Wricounts.chunks += Number(outcome?.chunks ?? 0);if ((outcome?.recovered_frontmatter || outcome?.comment_value) && pending.intent.path) counts.recovered = addRecovered(counts.recovered,{ paths: outcome.recovered_frontmatter ? [pending.intent.path] : [], commentValues: outcome.comment_value ? 1 : 0 });+ const sizeState = outcome?.size_state as PageSizeState | undefined;+ if (sizeState && typeof outcome?.slug === 'string') counts.sizeStates = addSizeState(counts.sizeStates, { slug: outcome.slug, ...(pending.intent.path ? { path: pending.intent.path } : {}), ...sizeState });const fences = outcome?.fences_normalized;if (Array.isArray(fences) && fences.length && pending.intent.path) counts.fences = addFencesNormalized(counts.fences, pending.intent.path, fences as Array<{ class: string }>);}diff --git a/test/chunkers/recursive.test.ts b/test/chunkers/recursive.test.tsindex 2ee2f9df74..daa8f0c5c2 100644--- a/test/chunkers/recursive.test.ts+++ b/test/chunkers/recursive.test.ts@@ -219,11 +219,13 @@ describe('large pages: delimiter splitting is linear', () => {test('a 4 MiB single-paragraph page chunks in well under a second per MiB', () => {const sentence = 'Plain prose about acme-example. ';const text = sentence.repeat(Math.floor((4 * 1024 * 1024) / sentence.length));- const started = performance.now();+ // CPU time, not wall-clock: a loaded runner stretches wall time without the chunker doing more work.+ const started = process.cpuUsage();const chunks = chunkText(text);- const elapsed = performance.now() - started;+ const used = process.cpuUsage(started);+ const cpuMs = (used.user + used.system) / 1000;expect(chunks.length).toBeGreaterThan(1000);expect(chunks.every(c => c.text.length <= 6000)).toBe(true);- expect(elapsed).toBeLessThan(3000);+ expect(cpuMs).toBeLessThan(3000);});});diff --git a/test/cli-input-plumbing-2822.test.ts b/test/cli-input-plumbing-2822.test.tsindex 93bace3ba0..de842c3751 100644--- a/test/cli-input-plumbing-2822.test.ts+++ b/test/cli-input-plumbing-2822.test.ts@@ -131,16 +131,18 @@ describe('#2822 — chunk_skip_reason on 0-chunk puts', () => {expect(result.chunk_skip_reason).toBe('empty_body');});- test('oversized content the gate marks embed_skip → embed_skip', async () => {- // An operator's bytes_block under the page ceiling: the gate stores the page with embed_skip and no chunks.+ test('oversized content the gate marks embed_skip keeps its chunks and says skipped: oversized (#6722)', async () => {+ // An operator's bytes_block under the page ceiling: the gate stores the page with embed_skip; it stays chunked+ // for keyword search, gets no vectors, and the receipt names why.await engine.setConfig('content_sanity.bytes_block', '500000');try {const result = (await putPage.handler(makeCtx(), {slug: 'inbox/skipped-embed',content: `---\ntitle: Big\n---\n\n${'Some prose that keeps going past the block threshold. '.repeat(10_000)}`,- })) as { chunks: number; chunk_skip_reason?: string };- expect(result.chunks).toBe(0);- expect(result.chunk_skip_reason).toBe('embed_skip');+ })) as { chunks: number; chunk_skip_reason?: string; size_state?: unknown };+ expect(result.chunks).toBeGreaterThan(0);+ expect(result.chunk_skip_reason).toBeUndefined();+ expect(result.size_state).toEqual({ embedding: 'skipped', reason: 'oversized', bytes: expect.any(Number) });} finally {await engine.unsetConfig('content_sanity.bytes_block');}diff --git a/test/import-file-content-sanity.test.ts b/test/import-file-content-sanity.test.tsindex 70e4dfdec1..048d95a2e3 100644--- a/test/import-file-content-sanity.test.ts+++ b/test/import-file-content-sanity.test.ts@@ -255,29 +255,34 @@ describe('importFromContent — soft-block (D9 transition + embed_skip)', () =>});});- test('soft-block deletes existing chunks (D9 transition invariant)', async () => {+ test('soft-block replaces existing chunks with the new body\'s chunks (D9 transition invariant, #6722)', async () => {await withIsolatedHome(async () => {// First write a normal page to seed some chunks.const small = FRONTMATTER + 'Short content with multiple sentences. Plenty of words here. Enough to chunk.';- await importFromContent(engine, 'test/grow', small, { noEmbed: true });- const beforeChunks = await engine.getChunks('test/grow');+ await importFromContent(engine, 'notes/grow', small, { noEmbed: true });+ const beforeChunks = await engine.getChunks('notes/grow');expect(beforeChunks.length).toBeGreaterThan(0);// Now re-import with content that grew past the block threshold.- const big = FRONTMATTER + 'a'.repeat(600_000);- await importFromContent(engine, 'test/grow', big, { noEmbed: true });- const afterChunks = await engine.getChunks('test/grow');- // D9: transition to embed_skip should delete chunks.- expect(afterChunks.length).toBe(0);+ const big = FRONTMATTER + 'Growing transcript line about acme-example. '.repeat(14_000) + 'The marker word is quillfeatherbeacon.';+ await importFromContent(engine, 'notes/grow', big, { noEmbed: true });+ const afterChunks = await engine.getChunks('notes/grow');+ // D9: the transition to embed_skip drops the old chunks; #6722: the new body is chunked, never embedded.+ expect(afterChunks.length).toBeGreaterThan(10);+ expect(afterChunks.some(c => c.chunk_text.includes('Plenty of words here'))).toBe(false);+ expect(afterChunks.every(c => c.embedding == null && c.embedded_at == null)).toBe(true);+ expect((await engine.searchKeyword('quillfeatherbeacon', { limit: 5 })).map(hit => hit.slug)).toEqual(['notes/grow']);});});- test('soft-block skips chunking entirely (no new chunks created)', async () => {+ test('soft-block keeps the page in keyword search: chunks with no vectors (#6722)', async () => {await withIsolatedHome(async () => {const content = FRONTMATTER + 'a'.repeat(600_000);await importFromContent(engine, 'test/big2', content, { noEmbed: true });const chunks = await engine.getChunks('test/big2');- expect(chunks.length).toBe(0);+ expect(chunks.length).toBeGreaterThan(0);+ expect(chunks.every(c => c.embedding == null && c.embedded_at == null)).toBe(true);+ expect(await engine.countStaleChunks()).toBe(0);});});@@ -335,7 +340,8 @@ describe('importFromContent — stale size-gate recovery', () => {await engine.setConfig('content_sanity.bytes_block', '1000');try {await importFromContent(engine, 'notes/threshold', content, { noEmbed: true });- expect((await engine.getChunks('notes/threshold')).length).toBe(0);+ expect(isEmbedSkipped((await engine.getPage('notes/threshold'))!.frontmatter)).toBe(true);+ expect((await engine.getChunks('notes/threshold')).length).toBeGreaterThan(0);await engine.setConfig('content_sanity.bytes_block', '10000');const recovered = await importFromContent(engine, 'notes/threshold', content, { noEmbed: true });expect(recovered.status).toBe('imported');@@ -344,7 +350,8 @@ describe('importFromContent — stale size-gate recovery', () => {expect((await importFromContent(engine, 'notes/threshold', content, { noEmbed: true })).status).toBe('skipped');await engine.setConfig('content_sanity.bytes_block', '1000');expect((await importFromContent(engine, 'notes/threshold', content, { noEmbed: true })).status).toBe('imported');- expect((await engine.getChunks('notes/threshold')).length).toBe(0);+ expect(isEmbedSkipped((await engine.getPage('notes/threshold'))!.frontmatter)).toBe(true);+ expect((await engine.getChunks('notes/threshold')).length).toBeGreaterThan(0);} finally {await engine.unsetConfig('content_sanity.bytes_block');}@@ -367,7 +374,8 @@ describe('importFromContent — stale size-gate recovery', () => {const content = FRONTMATTER.replace('---\n\n', 'embed_skip:\n reason: oversized\n---\n\n') + 'A small useful note.';await importFromContent(engine, 'notes/bypassed', content, { noEmbed: true, remote: false, preserveGateMarkers: true });expect(isEmbedSkipped((await engine.getPage('notes/bypassed'))!.frontmatter)).toBe(true);- expect((await engine.getChunks('notes/bypassed')).length).toBe(0);+ expect((await engine.getChunks('notes/bypassed')).every(c => c.embedding == null)).toBe(true);+ expect((await engine.getChunks('notes/bypassed')).length).toBeGreaterThan(0);}));});@@ -376,7 +384,8 @@ describe('importFromContent — stale size-gate recovery', () => {const content = FRONTMATTER.replace('---\n\n', 'embed_skip:\n reason: manual\n---\n\n') + 'A small useful note.';await importFromContent(engine, 'notes/manual-skip', content, { noEmbed: true, remote: false, preserveGateMarkers: true });expect(isEmbedSkipped((await engine.getPage('notes/manual-skip'))!.frontmatter)).toBe(true);- expect((await engine.getChunks('notes/manual-skip')).length).toBe(0);+ expect((await engine.getChunks('notes/manual-skip')).every(c => c.embedding == null)).toBe(true);+ expect((await engine.getChunks('notes/manual-skip')).length).toBeGreaterThan(0);});});});diff --git a/test/oversized-backfill.serial.test.ts b/test/oversized-backfill.serial.test.tsindex a7a16c28cd..835b06b830 100644--- a/test/oversized-backfill.serial.test.ts+++ b/test/oversized-backfill.serial.test.ts@@ -54,13 +54,18 @@ async function withHome<T>(config: Record<string, unknown> | null, fn: () => Pro}}-/** Write a page the way gbrain did before the ceiling: under a 500 KB block. */+/**+ * Leave a page the way gbrain did before the ceiling: written under a 500 KB block, with the+ * gate's marker and zero chunks. A write today keeps an embed_skip page's chunks (#6722), so+ * the legacy chunkless state is restored by removing them, as an old brain holds it.+ */async function seedSizeSkipped(slug: string, bytes: number): Promise<void> {await engine.setConfig('content_sanity.bytes_block', '500000');await importFromContent(engine, slug, FRONTMATTER + body(bytes), { noEmbed: true });await engine.unsetConfig('content_sanity.bytes_block');const page = await engine.getPage(slug);expect(isEmbedSkipped(page!.frontmatter as Record<string, unknown>)).toBe(true);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [page!.id]);expect((await engine.getChunks(slug)).length).toBe(0);}@@ -140,14 +145,26 @@ describe('gbrain reindex --oversized (keyless upgrade path)', () => {});}, 120_000);- test('a page still over the operator bytes_block keeps its marker', async () => {+ test('a page still over the operator bytes_block keeps its marker and is re-chunked for keyword search (#6722)', async () => {await withHome({ embedding_disabled: true }, async () => {await seedSizeSkipped('chats/operator-limit', 700_000);await engine.setConfig('content_sanity.bytes_block', '500000');- const receipt = await runOversizedBackfill(engine);- expect(receipt).toMatchObject({ candidates: 0, reindexed: 0, over_block: 1, block_bytes: 500_000 });- expect(isEmbedSkipped((await engine.getPage('chats/operator-limit'))!.frontmatter as Record<string, unknown>)).toBe(true);- await engine.unsetConfig('content_sanity.bytes_block');+ try {+ expect(await keywordHits()).toEqual([]);+ const receipt = await runOversizedBackfill(engine);+ expect(receipt).toMatchObject({ candidates: 1, reindexed: 1, rechunked_over_block: 1, over_block: 1, held_for_approval: 0,+ chunks_pending_embedding: 0, remaining: 0, block_bytes: 500_000 });+ expect(isEmbedSkipped((await engine.getPage('chats/operator-limit'))!.frontmatter as Record<string, unknown>)).toBe(true);+ expect(await keywordHits()).toEqual(['chats/operator-limit']);+ const chunks = await engine.getChunks('chats/operator-limit');+ expect(chunks.length).toBeGreaterThan(100);+ expect(chunks.every(c => c.embedded_at == null)).toBe(true);+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);+ expect(providerCalls).toBe(0);+ expect(await runOversizedBackfill(engine)).toMatchObject({ candidates: 0, reindexed: 0, over_block: 1 });+ } finally {+ await engine.unsetConfig('content_sanity.bytes_block');+ }});}, 120_000);});diff --git a/test/page-projection-origin.test.ts b/test/page-projection-origin.test.tsindex 9bd147a9d3..5992a7f09b 100644--- a/test/page-projection-origin.test.ts+++ b/test/page-projection-origin.test.ts@@ -317,7 +317,7 @@ test('queued Markdown rebuild retains ordered fenced code metadata and canonical}});-test('queued Markdown rebuild honors embed-skip and quarantine without retaining stale chunks', async () => {+test('queued Markdown rebuild honors embed-skip and quarantine without retaining stale chunks (#6722: embed_skip keeps keyword chunks)', async () => {for (const engine of engines) {for (const marker of ['embed_skip', 'quarantine']) {const slug = `disposition-${marker}`;@@ -328,7 +328,13 @@ test('queued Markdown rebuild honors embed-skip and quarantine without retainingawait engine.upsertChunks(slug, [chunk('stale-projection-sentinel')], { sourceId });const before = (await engine.readPageSnapshot(slug, { sourceId }))!;expect((await rebuildPendingPageProjections(engine, 100)).rebuilt).toBeGreaterThan(0);- expect(await engine.getChunks(slug, { sourceId, includeUnsealed: true })).toEqual([]);+ const rebuilt = await engine.getChunks(slug, { sourceId, includeUnsealed: true });+ if (marker === 'quarantine') expect(rebuilt).toEqual([]);+ else {+ expect(rebuilt.map(c => c.chunk_text).join('\n')).toContain('Prose.');+ expect(rebuilt.some(c => c.chunk_text.includes('stale-projection-sentinel'))).toBe(false);+ expect(rebuilt.every(c => c.embedding == null)).toBe(true);+ }const after = (await engine.readPageSnapshot(slug, { sourceId }))!;expect(after.revision).toBe(before.revision);expect(after.page.compiled_truth).toBe(before.page.compiled_truth);diff --git a/test/size-state-receipts-6722.test.ts b/test/size-state-receipts-6722.test.tsnew file mode 100644index 0000000000..d437db9b0f--- /dev/null+++ b/test/size-state-receipts-6722.test.ts@@ -0,0 +1,193 @@+/**+ * #6722: every page up to the ceiling is chunked (keyword search), and the+ * write, remember and sync receipts say what a write left a large or+ * embed_skip page's embedding in, in one shape: `size_state` per page+ * (`{ embedding, reason, bytes }`) and the sync tally `size_states`.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performSync } from '../src/commands/sync.ts';+import { sizeStateLines } from '../src/core/page-embedding-budget.ts';+import { withEnv } from './helpers/with-env.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { runEmbedCore } from '../src/commands/embed.ts';++const DIMS = 1536;+const MODEL = 'openai:text-embedding-3-large';+let engine: PGLiteEngine;+let providerTexts = 0;+const dirs: string[] = [];++const prose = (bytes: number, needle = '') => {+ const line = 'alice-example and bob-example talked about acme-example plans today.\n';+ return line.repeat(Math.ceil(bytes / line.length)) + (needle ? `The marker word is ${needle}.\n` : '');+};+const markdown = (title: string, body: string, type = 'note') => `---\ntitle: ${title}\ntype: ${type}\n---\n\n${body}`;++async function call(name: string, params: Record<string, unknown>) {+ const res = await dispatchToolCall(engine, name, params, { remote: false });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'synthetic-6722-fixture' } });+ __setEmbedTransportForTests((async (input: { values: string[] }) => {+ providerTexts += input.values.length;+ return { embeddings: input.values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: input.values.length * 4 } };+ }) as never);+}, 60_000);++afterAll(async () => {+ __setEmbedTransportForTests(null);+ resetGateway();+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+});++beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ providerTexts = 0;+});++describe('put_page receipts', () => {+ test('an ordinary page carries no size_state; a large page says its embedding is deferred', async () => {+ const small = await call('put_page', { slug: 'notes/small', content: markdown('Small', prose(2_000)) });+ expect(small.isError).toBe(false);+ expect(small.body.size_state).toBeUndefined();++ const large = await call('put_page', { slug: 'notes/large', content: markdown('Large', prose(1_100_000)) });+ expect(large.isError).toBe(false);+ expect(large.body.chunks).toBeGreaterThan(100);+ expect(large.body.size_state).toEqual({ embedding: 'deferred', reason: 'large_page', bytes: expect.any(Number) });+ expect(large.body.size_state.bytes).toBeGreaterThan(1024 ** 2);+ }, 120_000);++ test('a page over the operator bytes_block keeps its chunks, says skipped: oversized, and its embedding effect calls no provider', async () => {+ await engine.setConfig('content_sanity.bytes_block', '500000');+ try {+ const context: OperationContext = { engine, sourceId: 'default', config: { engine: 'pglite' }, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } } as OperationContext;+ const requestId = randomUUID();+ const receipt = await operationsByName.put_page.handler(context, { slug: 'chats/over-block', request_id: requestId,+ content: markdown('Over block', prose(600_000, 'quillfeatherbeacon')) }) as Record<string, any>;+ expect(receipt).toMatchObject({ state: 'committed', size_state: { embedding: 'skipped', reason: 'oversized' } });+ expect(receipt.chunks).toBeGreaterThan(50);+ expect(receipt.chunk_skip_reason).toBeUndefined();+ expect((await engine.searchKeyword('quillfeatherbeacon', { limit: 5 })).map(hit => hit.slug)).toEqual(['chats/over-block']);++ const embedded: string[] = [];+ await runPersistenceEffects(engine, { engine: 'pglite' }, { hostId: localHostId(), limit: 20,+ embedding: { signature: `${MODEL}:${DIMS}`, model: MODEL, embed: async texts => { embedded.push(...texts); return texts.map(() => new Float32Array(DIMS).fill(0.001)); } } });+ expect(embedded).toEqual([]);+ expect(providerTexts).toBe(0);+ const effects = await engine.executeRaw<{ state: string; outcome: Record<string, unknown> | null }>(`SELECT e.state, e.outcome FROM persistence_effects e+ JOIN persistence_requests r ON r.id = e.request_id WHERE r.request_id = $1::uuid AND e.kind = 'embedding'`, [requestId]);+ for (const effect of effects) expect(effect).toEqual({ state: 'committed', outcome: { embedding: 'skipped', reason: 'embed_skip' } });+ const chunks = await engine.getChunks('chats/over-block');+ expect(chunks.every(chunk => chunk.embedding == null && chunk.embedded_at == null)).toBe(true);+ } finally {+ await engine.unsetConfig('content_sanity.bytes_block');+ }+ }, 120_000);+});++describe('embed_skip pages are chunked and never embedded', () => {+ test('an explicit slug embed (as sync runs after an incremental import) leaves an embed_skip page keyword-only', async () => {+ await engine.setConfig('content_sanity.bytes_block', '500000');+ try {+ await importFromContent(engine, 'chats/slug-embed', markdown('Slug embed', prose(600_000)), { noEmbed: true });+ expect((await engine.getChunks('chats/slug-embed')).length).toBeGreaterThan(50);+ await runEmbedCore(engine, { slugs: ['chats/slug-embed'], quiet: true });+ expect(providerTexts).toBe(0);+ expect((await engine.getChunks('chats/slug-embed')).every(chunk => chunk.embedding == null)).toBe(true);+ await runEmbedCore(engine, { stale: true, quiet: true });+ expect(providerTexts).toBe(0);+ } finally {+ await engine.unsetConfig('content_sanity.bytes_block');+ }+ }, 120_000);+});++describe('remember receipts', () => {+ test('a fact appended to a large entity page carries the page size_state; one on an ordinary page carries none', async () => {+ expect((await call('put_page', { slug: 'people/alice-example', content: markdown('Alice Example', prose(1_100_000), 'person') })).isError).toBe(false);+ expect((await call('put_page', { slug: 'people/bob-example', content: markdown('Bob Example', 'A person.\n', 'person') })).isError).toBe(false);++ const large = await call('remember', { fact: 'Alice Example prefers async standups.', provenance: 'test', entity: 'people/alice-example' });+ expect(large.isError).toBe(false);+ expect(large.body.size_state).toEqual({ embedding: 'deferred', reason: 'large_page', bytes: expect.any(Number) });++ const small = await call('remember', { fact: 'Bob Example lives in Porto.', provenance: 'test', entity: 'people/bob-example' });+ expect(small.isError).toBe(false);+ expect(small.body.size_state).toBeUndefined();+ }, 120_000);+});++describe('sync receipts', () => {+ const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', ...args],+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+ function repo(): { dir: string; root: string } {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-6722-sync-')); dirs.push(dir);+ const root = join(dir, 'brain'); mkdirSync(join(root, 'notes'), { recursive: true });+ execFileSync('git', ['init', '-q', '-b', 'main', root]);+ writeFileSync(join(root, 'notes/small.md'), markdown('Small', prose(2_000)));+ writeFileSync(join(root, 'notes/big.md'), markdown('Big', prose(1_100_000)));+ git(root, 'add', '.'); git(root, 'commit', '-qm', 'add notes');+ return { dir, root };+ }+ const expected = (path?: string) => ({ total: 1, pages: [{ slug: 'notes/big', ...(path ? { path } : {}), embedding: 'deferred' as const, reason: 'large_page', bytes: expect.any(Number) }] });++ test('a legacy sync lists the large page in size_states on the first (full) and an incremental run, and the output names it', async () => {+ const { dir, root } = repo();+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['legacy-6722', root]);+ const first = await performSync(engine, { repoPath: root, sourceId: 'legacy-6722', noPull: true, noEmbed: true });+ expect(first.status).toBe('first_sync');+ expect(first.size_states).toEqual(expected());+ expect(sizeStateLines(first.size_states).join('\n')).toContain('notes/big');++ writeFileSync(join(root, 'notes/big.md'), markdown('Big', prose(1_200_000)));+ writeFileSync(join(root, 'notes/small.md'), markdown('Small', prose(3_000)));+ git(root, 'commit', '-qam', 'grow notes');+ const next = await performSync(engine, { repoPath: root, sourceId: 'legacy-6722', noPull: true, noEmbed: true });+ expect(next.status).toBe('synced');+ expect(next.size_states).toEqual(expected());+ expect(next.size_states!.pages[0]!.bytes).toBeGreaterThan(1_200_000);+ });+ }, 120_000);++ test('a managed sync carries each committed page size_state into size_states', async () => {+ const { dir, root } = repo();+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['managed-6722', root]);+ await claimWorktree(engine, 'managed-6722', root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ const result = await performSync(engine, { repoPath: root, sourceId: 'managed-6722', noPull: true, noEmbed: true });+ expect(result.status).not.toBe('blocked_by_failures');+ expect(result.size_states).toEqual(expected('notes/big.md'));+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ });+ }, 120_000);+});