Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): one provider call per chunk content version (gbrain-evals#180 N14)

garrytan196955e11e58
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 7cca73e141..1d76f6106b 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -26,6 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embedding-state.ts` — #6696 B3 derived embedding state: every chunk, and every live page with no chunk row, in one of `embedded | pending | keyword_only | quarantined | empty | deleted_page_chunks | chunkless_healable` against the ACTIVE embedding column (no stored status). The classifier SQL lives once in `engine-sql/chunks.ts` (`chunkEmbeddingState` reuses `staleChunkWhere`, `chunklessPageState` reuses `chunklessPagesWhere`) behind `BrainEngine.readEmbeddingStateCounts` / `listEmbeddingStateRows`. `readEmbeddingState(engine, { mode, sourceIds })`: `full` is exact; `ops` reads only index-backed counts (the partial index `WHERE <active column> IS NULL`, the frontmatter GIN, the purge index; `embedded` is a planner estimate) and is `status: 'unknown', reason: 'no_covering_index'` without that index, never a scan. `unsearchable` sums pending, quarantined, empty and chunkless_healable (pending drops out on a brain keyless by choice). `embeddingStateFix` builds each state's protocol fix from existing commands. Consumers: doctor `embedding_state`, `gbrain pages unsearchable`, lane B's `get_brain_health`. Tests: `test/embedding-state.test.ts`.
- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`. Wave B: a segmented page is embedded by `page-body/segmented-embedding.ts` (vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here, `gbrain embed` and the post-commit embedding effect (`data.occurrence_ids` limits an append's effect to the new occurrences).
+- `src/core/page-embedding-lease.ts` — one provider call per chunk content version (gbrain-evals#180, N14). Every path that embeds a page's vector-less chunks holds the page's embedding lease from reading which chunks lack a vector through its install: the post-write embedding effect (`persistence/effects.ts`, inline and segmented), the `gbrain embed --stale` drain (`src/commands/embed.ts`), `embedStaleForSource` and `embedStalePages` (`embed-stale.ts`), and every segmented install (`embedSegmentedRows` in `page-body/segmented-embedding.ts`). `acquirePageEmbeddingLease` takes a `gbrain_cycle_locks` row `embed-page:<page id>` with plain statements (TTL 2 minutes, refreshed every 30 s while held, no process-liveness takeover), waiting with backoff while another path holds it; an effect renews its claim in `whileWaiting`. Callers bind it with `await using`, so leaving the scope releases it. The holder then keeps only the chunks still without a vector (inline: `stillPendingChunks` over the fresh `getChunks` read; segmented: `vectorlessChunkIndexes`), so a drain whose listing predates an effect's install sends nothing for them. `pageEmbeddingLeaseProbe.contended` is the test seam. Forced probes (effect first on a segmented page after `append_page`, drain first on an inline page; both engines): `test/embed-once-per-content-version.serial.test.ts`.
- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete: an unsealed page only in the `reimport` class (`page-state/projection-class.ts`; `sealable`, `protected` and `archived` are counted, never candidates), a sealed one with no `embedding_image` chunk or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true` (`incomplete_sealed`); `ocr_required` counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root; a page with no recorded `source_path` is located by its slug, which is the lower-cased repo-relative path, and counted in `missingSourcePath`) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes through `importManagedFile` (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records `source_path`. Reports candidates, rebuilt, unchanged, missing source files (`missing_samples`: up to 5 `source:slug: no file at <path tried>` lines, the first printed) and failures; the explicit `--images` CLI (`runEmbedStaleImagesCli`) counts an all-missing, nothing-rebuilt sweep as failures (`sweepFoundNoFiles`), so it never exits 0 as a quiet success. `runStaleImageSweepFirst` is the sweep a plain `gbrain embed --stale` (no `--slugs`) runs before its text drain when multimodal embedding is on, and `foldImageSweep` folds it into the `EmbedResult` as `images`: import failures count toward the run's failures, fileless pages are reported once on stderr (`missingFile`, first sample) and leave the exit code to the text run; a text-only install skips it and keeps the `--images` hint. Pinned by `test/embed-stale-images.test.ts` and `test/embed-stale-images-managed-6529.test.ts` (both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.
- `src/core/embed-budget-stop.ts` — the loud time-budget stop for `gbrain embed --stale`. `noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})` counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, sets `reason: 'time_budget'`, `remaining_stale` and `resume_command` (`gbrain embed --stale --catch-up [--source X] [--include-null-signature]`) on the result; `skip` covers dry runs, `--catch-up` and caller aborts. `embedBudgetStopVerdict(result)` is the stdout verdict `runEmbed` prints; `src/cli/commands/embed.ts` maps the reason to `BUDGET_STOP_EXIT_CODE` (failures still win with 1). Called from every budget exit in `embedAllStale` (readiness-phase deadline returns and the main drain). Pinned by `test/embed.serial.test.ts` ("time-budget stop is loud").
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1da2fb613d..ad7ec2e00a 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -6,7 +6,7 @@
src/cli/main.ts 3016 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row
src/commands/autopilot.ts 1662 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts); +8 GBRA-130 C-6/A-10: the --retry-global mode row, help line and --phase value flag, and --status reading the brain-wide maintenance verdict into its JSON, text and exit code (logic in core/minions/global-maintenance-stall.ts and autopilot-retry-global.ts); +12 GBRA-133 #7003: --status grades from the daemon's heartbeat sidecar (two report fields and their doc line, the classifier's daemon input and threshold branch, the import and the showStatus read; logic in core/autopilot-heartbeat.ts)
src/commands/doctor.ts 688 ratchet +2 Wave B decision #10: Check.skipped_segmented field (logic in doctor/check-fix.ts withSkippedSegmented); +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
-src/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)
+src/commands/embed.ts 2305 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts); +1 PR 4 E (gbrain-evals#180): per-page embedding lease import (lease and still-pending filter live in core/page-embedding-lease.ts)
src/commands/extract-conversation-facts.ts 2044 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); merge v0.60.240.0: large pages and master growth compose at 2087; -6 wave 18 lane 3 (#6731 #6764): the two extractor call sites share one input object, inference lives in core/facts/conversation-subject-infer.ts; Wave B PR 2 (kept at the master 4e29d0904 merge): +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts); integrated at the master 4e29d0904 merge: 2097 measured; lowered to 2044 by #7013: a page's rows publish once through publishConversationFacts (core/facts/conversation-publication.ts), so the delete-first cleanup, the per-segment inserts and the row-number peek left
src/commands/extract.ts 2677 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); 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 baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured
src/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
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index 7f2f21712c..c4500c05e9 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -16,6 +16,7 @@ import { carryChunkMetadata, probeEmbedder, resolveProvenanceStamp, stampIfPageP
import type { StaleImageSweepResult } from '../core/embed-stale-images.ts';
import { resolveMaxChunkTokens } from '../core/embedding-input-limit.ts';
import { healOversizedPageChunks, healedChunksToStaleRows } from '../core/embed-oversize-heal.ts';
+import { acquirePageEmbeddingLease, stillPendingChunks } from '../core/page-embedding-lease.ts';
import { healAndReportOverLength, isSingleInputOverLengthError, statusFromCause } from '../core/embed-overlength-heal.ts';
import {
createEmbedStallWatchdog,
@@ -2080,6 +2081,7 @@ async function embedAllStale(
try {
const segmented = await observed(pacer, () => readSegmentedEmbedPage(engine, { sourceId: keySourceId, slug }));
if (segmented) { await embedSegmented(engine, segmented, result, { dryRun: false, signal: effectiveSignal, signature }); processedPageKeys.add(key); return; }
+ await using _lease = await acquirePageEmbeddingLease(engine, stale[0].page_id, { signal: effectiveSignal });
// SUP-3874: split legacy oversized chunk_text BEFORE the embed call.
// `--stale` reuses stored rows; without this, one pre-cap chunk
// (e.g. a long pre-cap notes page on a 512-token model) fails
@@ -2118,8 +2120,7 @@ async function embedAllStale(
}
const selected = new Map(stale.map(c => [c.chunk_index, c]));
const existing = prepared.chunks;
- stale = existing.filter(c => selected.get(c.chunk_index)?.chunk_text === c.chunk_text)
- .map(c => ({ ...selected.get(c.chunk_index)!, ...c }));
+ stale = stillPendingChunks(existing, selected);
if (!stale.length) return;
const pageRow = prepared.snapshot.page;
const metered = await meterPageBatch(engine, pageRow, existing.filter(c => !c.embedded_at), { signature, announceHeld: true });
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1cb43d132a..6e69d424ea 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1019,6 +1019,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.
{ since: '0.60.326.0', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },
{ since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },
+ // PR 4 E (one provider call per chunk content version, gbrain-evals#180). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A page\'s new chunks now go to the embedding provider once per content version. The post-write embedding effect, `gbrain embed --stale`, the embed-backfill job and phase-end embeds each hold a per-page lease (a `gbrain_cycle_locks` row named `embed-page:<page id>`, refreshed while held, expiring within 2 minutes after a holder dies) from reading which chunks lack a vector through installing them; a path that reaches a page another path is embedding waits for it, then embeds only the chunks still missing a vector. Before, a stale drain that ran while a write\'s embedding effect was in flight sent the same chunks twice (paid twice on a paid provider). Live `embed-page:` rows can show in the `gbrain status` lock list while an embed runs.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 1e4835f1ba..c51621d1b3 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -35,6 +35,7 @@ import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
import { resolveStaleEmbedConcurrency } from './embed-concurrency.ts';
import { AbortError } from './abort-check.ts';
import { meterPageBatch, spendGrant } from './page-embedding-budget.ts';
+import { acquirePageEmbeddingLease, stillPendingChunks } from './page-embedding-lease.ts';
import { chunkGenerationFilter, chunkVisibleFilter } from './search/safe-chunks.ts';
import { embedSegmentedPage, embedSegmentedRows, readSegmentedEmbedPage, type SegmentedEmbedOpts } from './page-body/segmented-embedding.ts';
@@ -277,8 +278,8 @@ async function embedSegmentedStaleRows(engine: BrainEngine, stale: readonly Stal
opts: Omit<SegmentedEmbedOpts, 'beforeInstall'> & { stamp?: ProvenanceStamp; pacer: DbPacer; assertOwned?: (tx?: BrainEngine) => Promise<void>; stopped: () => boolean }): Promise<boolean> {
const page = await observed(opts.pacer, () => readSegmentedEmbedPage(engine, { id: stale[0]!.page_id }));
if (!page) return false;
- const installed = await embedSegmentedRows(engine, page, stale, { ...opts,
- beforeInstall: async tx => { await opts.assertOwned?.(tx); if (opts.stopped()) throw new AbortError(); } });
+ const installed = (await embedSegmentedRows(engine, page, stale, { ...opts,
+ beforeInstall: async tx => { await opts.assertOwned?.(tx); if (opts.stopped()) throw new AbortError(); } }))?.installed;
if (opts.stamp && installed) await stampIfPageProvenanceComplete(engine, page.slug, page.source_id, opts.stamp);
result.embedded += installed ?? 0;
if (installed) result.pagesProcessed += 1;
@@ -326,6 +327,7 @@ export async function embedStalePages(
await healOversizedPageChunks(engine, slug, { sourceId });
const prepared = await readProjectionSnapshot(engine, slug, sourceId, { requireLiveSource: true });
if (!prepared) continue;
+ await using _lease = await acquirePageEmbeddingLease(engine, prepared.snapshot.page.id, { signal: opts.signal });
const existing = prepared.chunks;
const staleIdx = new Set(
(await engine.executeRaw<{ chunk_index: number }>(
@@ -557,6 +559,7 @@ export async function embedStaleForSource(
try {
await opts.assertOwned?.();
if (stopped() || await embedSegmentedStaleRows(engine, stale, result, { embedFn, signal, signature, stamp, pacer, assertOwned: opts.assertOwned, stopped })) return;
+ await using _lease = await acquirePageEmbeddingLease(engine, stale[0].page_id, { signal });
// SUP-3874: split legacy oversized chunk_text before embedding.
const healed = await observed(pacer, () => engine.transaction(async tx => {
await opts.assertOwned?.(tx);
@@ -582,8 +585,7 @@ export async function embedStaleForSource(
if (!prepared) return;
const selected = new Map(stale.map(c => [c.chunk_index, c]));
const existing = prepared.chunks;
- stale = existing.filter(c => selected.get(c.chunk_index)?.chunk_text === c.chunk_text)
- .map(c => ({ ...selected.get(c.chunk_index)!, ...c }));
+ stale = stillPendingChunks(existing, selected);
if (!stale.length) return;
const pageRow = prepared.snapshot.page;
const metered = await meterPageBatch(engine, pageRow, existing.filter(c => !c.embedded_at), { signature });
diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.ts
index 504545e53b..16011d7d5b 100644
--- a/src/core/page-body/segmented-embedding.ts
+++ b/src/core/page-body/segmented-embedding.ts
@@ -14,6 +14,7 @@ import { jsonRowBatches } from '../batch-rows.ts';
import { wrapChunkTextsForStoredMode } from '../embedding-context.ts';
import { embeddingInputHash, plainEmbeddingTier } from '../embedding-input-hash.ts';
import { meterPageBatch, spendGrant } from '../page-embedding-budget.ts';
+import { acquirePageEmbeddingLease, vectorlessChunkIndexes } from '../page-embedding-lease.ts';
import { embeddingInputContext, embeddingWriteTarget } from '../page-state/projections.ts';
import { quoteIdentifier, vectorCastSuffix } from '../search/embedding-column.ts';
import { chunkGenerationFilter, currentTextProjectionFilter } from '../search/safe-chunks.ts';
@@ -46,6 +47,8 @@ export interface SegmentedEmbedOpts {
approvedCapUsd?: number;
/** Runs inside the install transaction after the page guard (ownership, effect claim); throwing installs nothing. */
beforeInstall?: (tx: BrainEngine) => Promise<void>;
+ /** Runs before each wait for the page's embedding lease (page-embedding-lease.ts); an effect renews its claim there. */
+ whileWaiting?: () => Promise<void>;
}
/** A segmented page that is live, sealed and in a live source, by id or by source and slug; null otherwise (inline pages included). */
@@ -104,20 +107,27 @@ export async function listSegmentedStaleRows(engine: Pick<BrainEngine, 'executeR
}
/**
- * Embed `rows` of one segmented page: meter them under the per-page budget,
- * call the provider once for the granted rows, and install each vector with
- * its recorded input on the row with the same chunk_index and text while that
- * row is in the live generation and the page's title, mode and write target
- * are unchanged. Returns the rows that took a vector; null when the budget
- * holds the page or the cap left nothing to embed.
+ * Embed `listed` rows of one segmented page under the page's embedding lease
+ * (page-embedding-lease.ts): keep the rows still without a vector once the
+ * lease is held (every row with `includeEmbedded`), meter them under the
+ * per-page budget, call the provider once for the granted rows, and install
+ * each vector with its recorded input on the row with the same chunk_index and
+ * text while that row is in the live generation and the page's title, mode and
+ * write target are unchanged. Returns how many rows were still pending and how
+ * many took a vector; null when the budget holds the page or the cap left
+ * nothing to embed.
*/
-export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmbedPage, rows: readonly SegmentedStaleRow[],
- opts: SegmentedEmbedOpts): Promise<number | null> {
- if (rows.length === 0) return 0;
+export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmbedPage, listed: readonly SegmentedStaleRow[],
+ opts: SegmentedEmbedOpts & { includeEmbedded?: boolean }): Promise<{ pending: number; installed: number } | null> {
+ if (listed.length === 0) return { pending: 0, installed: 0 };
+ await using _lease = await acquirePageEmbeddingLease(engine, page.id, { signal: opts.signal, whileWaiting: opts.whileWaiting });
+ const target = await embeddingWriteTarget(engine);
+ const missing = opts.includeEmbedded ? null : await vectorlessChunkIndexes(engine, page.id, target.column.name);
+ const rows = missing ? listed.filter(row => missing.has(row.chunk_index)) : listed;
+ if (rows.length === 0) return { pending: 0, installed: 0 };
const metered = await meterPageBatch(engine, page, rows, { signature: opts.signature ?? null, approvedCapUsd: opts.approvedCapUsd });
if (!metered) return null;
const chunks = metered.chunks;
- const target = await embeddingWriteTarget(engine);
const vectors = await spendGrant(metered.grant, () => opts.embedFn(wrapChunkTextsForStoredMode(page, chunks), { abortSignal: opts.signal }));
if (vectors.length !== chunks.length || vectors.some(v => !v?.length || !v.every(Number.isFinite))) {
throw new Error('Embedding provider returned an incomplete or invalid batch');
@@ -134,7 +144,7 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb
const now = await embeddingWriteTarget(tx);
if (!current || current.slug !== page.slug || current.title !== page.title
|| current.contextual_retrieval_mode !== page.contextual_retrieval_mode
- || now.column.name !== target.column.name || now.provenanceModel !== target.provenanceModel) return 0;
+ || now.column.name !== target.column.name || now.provenanceModel !== target.provenanceModel) return { pending: rows.length, installed: 0 };
let installed = 0;
for (const batch of jsonRowBatches(updates, update => update)) {
installed += (await tx.executeRaw(`UPDATE content_chunks cc SET ${col} = v.embedding${vectorCastSuffix(target.column)},
@@ -145,7 +155,7 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb
AND ${chunkGenerationFilter('p', 'cc')}
RETURNING cc.id`, [page.id, batch, target.model])).length;
}
- return installed;
+ return { pending: rows.length, installed };
});
}
@@ -168,11 +178,11 @@ export async function embedSegmentedPage(engine: BrainEngine, page: SegmentedEmb
const rows = await listSegmentedStaleRows(engine, page.id, column, { beforeChunkIndex: before, limit, occurrenceIds: opts.occurrenceIds, includeEmbedded: opts.all });
if (rows.length === 0) return { embedded, complete: true };
const approvedCapUsd = opts.approvedCapUsd === undefined || before === null ? opts.approvedCapUsd : 0;
- const installed = await embedSegmentedRows(engine, page, rows, { ...opts, approvedCapUsd });
- if (installed === null) return { embedded, complete: false, stopped: 'budget' };
- embedded += installed;
- if (installed === 0) return { embedded, complete: false, stopped: 'page_moved' };
- if (installed < rows.length) return { embedded, complete: false, stopped: 'budget' };
+ const done = await embedSegmentedRows(engine, page, rows, { ...opts, approvedCapUsd, includeEmbedded: opts.all });
+ if (done === null) return { embedded, complete: false, stopped: 'budget' };
+ embedded += done.installed;
+ if (done.pending > 0 && done.installed === 0) return { embedded, complete: false, stopped: 'page_moved' };
+ if (done.installed < done.pending) return { embedded, complete: false, stopped: 'budget' };
before = rows[rows.length - 1]!.chunk_index;
}
}
diff --git a/src/core/page-embedding-lease.ts b/src/core/page-embedding-lease.ts
new file mode 100644
index 0000000000..a584c3d003
--- /dev/null
+++ b/src/core/page-embedding-lease.ts
@@ -0,0 +1,95 @@
+/**
+ * One provider call per chunk content version (gbrain-evals#180, N14).
+ *
+ * Every path that embeds a page's vector-less chunks (the post-write embedding
+ * effect, `gbrain embed --stale`, the embed-backfill job, phase-end embeds)
+ * reads which chunks lack a vector, calls the provider and installs. Two paths
+ * that read the same page before either installs both send its chunks, so
+ * each path holds this page's lease from that read through its install. A
+ * path that finds the lease held waits for it, then reads again and embeds
+ * only the chunks still missing a vector.
+ *
+ * The lease is a `gbrain_cycle_locks` row (`embed-page:<page id>`) written with
+ * plain statements, so it holds across processes and through a transaction
+ * pooler without pinning a connection during the provider call. The holder
+ * refreshes it; a holder that dies leaves a row that expires after the TTL.
+ */
+import { randomUUID } from 'node:crypto';
+import { hostname } from 'node:os';
+import type { BrainEngine } from './engine.ts';
+import { quoteIdentifier } from './search/embedding-column.ts';
+import { chunkGenerationFilter } from './search/safe-chunks.ts';
+
+export const PAGE_EMBEDDING_LEASE_TTL_MINUTES = 2;
+const LEASE_REFRESH_MS = 30_000;
+const LEASE_WAIT_MAX_MS = 1_000;
+
+/** Test seam: called each time a path finds a page's lease held by another path, before it waits. */
+export const pageEmbeddingLeaseProbe: { contended?: (pageId: number) => void } = {};
+
+export function pageEmbeddingLeaseId(pageId: number): string {
+ return `embed-page:${pageId}`;
+}
+
+function pause(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise(resolve => {
+ const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); };
+ const timer = setTimeout(done, ms);
+ signal?.addEventListener('abort', done, { once: true });
+ });
+}
+
+/**
+ * Takes page `pageId`'s embedding lease, waiting while another path holds it.
+ * `whileWaiting` runs before each wait (an effect renews its claim there); an
+ * abort of `signal` ends the wait by throwing its reason. Bind the result with
+ * `await using` in the scope that ends with the install: leaving it releases the lease.
+ */
+export async function acquirePageEmbeddingLease(engine: BrainEngine, pageId: number,
+ opts: { signal?: AbortSignal; whileWaiting?: () => Promise<void> } = {}): Promise<AsyncDisposable> {
+ const id = pageEmbeddingLeaseId(pageId);
+ const token = randomUUID();
+ const take = async () => (await engine.executeRaw(
+ `INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)
+ VALUES ($1, $2, $3, now(), now() + make_interval(mins => $4::int), now(), $5::uuid)
+ ON CONFLICT (id) DO UPDATE SET holder_pid = EXCLUDED.holder_pid, holder_host = EXCLUDED.holder_host, acquired_at = now(),
+ ttl_expires_at = EXCLUDED.ttl_expires_at, last_refreshed_at = now(), acquisition_token = EXCLUDED.acquisition_token
+ WHERE gbrain_cycle_locks.ttl_expires_at < now()
+ RETURNING id`, [id, process.pid, hostname(), PAGE_EMBEDDING_LEASE_TTL_MINUTES, token])).length > 0;
+ for (let waitMs = 50; !await take(); waitMs = Math.min(waitMs * 2, LEASE_WAIT_MAX_MS)) {
+ pageEmbeddingLeaseProbe.contended?.(pageId);
+ await opts.whileWaiting?.();
+ await pause(waitMs, opts.signal);
+ opts.signal?.throwIfAborted();
+ }
+ const refresh = setInterval(() => {
+ engine.executeRaw(`UPDATE gbrain_cycle_locks SET ttl_expires_at = now() + make_interval(mins => $3::int), last_refreshed_at = now()
+ WHERE id = $1 AND acquisition_token = $2::uuid`, [id, token, PAGE_EMBEDDING_LEASE_TTL_MINUTES]).catch(() => { /* the TTL is the backstop */ });
+ }, LEASE_REFRESH_MS);
+ refresh.unref?.();
+ return {
+ [Symbol.asyncDispose]: async () => {
+ clearInterval(refresh);
+ await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id = $1 AND acquisition_token = $2::uuid', [id, token])
+ .catch(() => { /* the TTL is the backstop */ });
+ },
+ };
+}
+
+/**
+ * The chunks of `existing` (the page's chunks, read under its lease) that still lack a vector and match a listed
+ * stale row's text, each merged over that row. A chunk another path embedded since the listing drops out.
+ */
+export function stillPendingChunks<C extends { chunk_index: number; chunk_text: string; embedded_at?: Date | string | null; embedding_is_null?: boolean },
+ S extends { chunk_index: number; chunk_text: string }>(existing: readonly C[], selected: ReadonlyMap<number, S>): Array<S & C> {
+ return existing.filter(c => (!c.embedded_at || c.embedding_is_null === true) && selected.get(c.chunk_index)?.chunk_text === c.chunk_text)
+ .map(c => ({ ...selected.get(c.chunk_index)!, ...c }));
+}
+
+/** Chunk indexes of the page's live rows with no vector in `column`, read while the caller holds the page's lease. */
+export async function vectorlessChunkIndexes(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, column: string): Promise<Set<number>> {
+ const rows = await engine.executeRaw<{ chunk_index: number }>(
+ `SELECT cc.chunk_index FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE cc.page_id = $1 AND cc.${quoteIdentifier(column)} IS NULL AND ${chunkGenerationFilter('p', 'cc')}`, [pageId]);
+ return new Set(rows.map(row => Number(row.chunk_index)));
+}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 99a9a6ee15..d69dd6fb65 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -54,6 +54,7 @@ import { nativeFileTarget } from './native-file-target.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
import { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';
import { planPageEmbedding } from '../page-embedding-budget.ts';
+import { acquirePageEmbeddingLease } from '../page-embedding-lease.ts';
import { chunkGenerationFilter, chunkManifestReads } from '../search/safe-chunks.ts';
import { classifyItemFailure, ItemRun } from '../item-failure.ts';
@@ -427,6 +428,12 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
if (isEmbedSkipped(snapshot.page.frontmatter)) { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'embed_skip' }); return; }
const segmented = await readSegmentedEmbedPage(engine, { id: snapshot.page.id });
if (segmented) { await embedSegmentedEffect(engine, config, effect, snapshot, segmented, signature, opts); return; }
+ // A stale drain or another worker embedding this page finishes first; the projection read below then finds its chunks complete.
+ await using _lease = await acquirePageEmbeddingLease(engine, snapshot.page.id, { signal: opts.signal, whileWaiting: async () => {
+ if (!await renewPersistenceEffectClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, effect)) throw opError('write_claim_lost', 'The embedding claim changed.',
+ `Another worker took over the embedding of ${snapshot.page.slug} in source ${effect.source_id}; this attempt stops without installing vectors and the owning claim finishes it.`,
+ { fix: effectStatusFix(effect) });
+ } });
const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);
const { prepared } = projection;
let pending = projection.pending;
@@ -547,6 +554,7 @@ async function embedSegmentedEffect(engine: BrainEngine, config: GBrainConfig, e
{ fix: effectStatusFix(effect) });
const embed = opts.embedding?.embed ?? embedBatch;
const result = await embedSegmentedPage(engine, page, { signature, signal: opts.signal, occurrenceIds: effect.data.occurrence_ids,
+ whileWaiting: async () => { if (!await renewPersistenceEffectClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, effect)) throw claimLost(); },
embedFn: (texts, o) => withAIInvocationPreflight(async () => {
opts.signal?.throwIfAborted();
if (!await renewPersistenceEffectClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, effect)) throw claimLost();
diff --git a/test/embed-once-per-content-version.serial.test.ts b/test/embed-once-per-content-version.serial.test.ts
new file mode 100644
index 0000000000..e3819955a5
--- /dev/null
+++ b/test/embed-once-per-content-version.serial.test.ts
@@ -0,0 +1,194 @@
+/**
+ * PR 4 E (gbrain-evals#180, N14): a chunk's text goes to the embedder once per content version.
+ *
+ * 1. Protects: the post-write embedding effect and a concurrent `gbrain embed --stale` drain never both send the same
+ * chunk to the provider. Whichever path reaches a page first holds its embedding lease (page-embedding-lease.ts)
+ * through its install; the other waits, reads again and finds nothing left to embed. Embedder inputs equal the
+ * page's new (vector-less) chunks, each sent once.
+ * 2. Fails when: either path reads "no vector" as "mine to embed" with no regard for a provider call in flight. The
+ * forced probes hold the first provider call at the transport until the other path calls the provider too, finds
+ * the lease held, or finishes, so the doubled input N14 saw intermittently on Postgres (5 of 23 runs) happens every
+ * run: effect first on a segmented page after append_page (the N14 path), drain first on an inline page.
+ * 3. The provider is the gateway's transport seam: no network, no spend. PGLite always; PostgreSQL when DATABASE_URL is
+ * set (test/postgres-unit-arms.txt). Serial: the gateway transport and the lease probe are process-wide.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { conversationBody, conversationPage } from './helpers/conversation-page.ts';
+import { openAppendBrain, type AppendBrain } from './helpers/append-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { resolveActiveEmbeddingColumnFromEngine } from '../src/core/search/embedding-column.ts';
+import { chunkGenerationFilter } from '../src/core/search/safe-chunks.ts';
+import { runEmbedCore } from '../src/commands/embed.ts';
+import { pageEmbeddingLeaseProbe } from '../src/core/page-embedding-lease.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+
+/** Marks the drain's provider calls; every other call comes from an embedding effect. */
+const drainScope = new AsyncLocalStorage<true>();
+type Path = 'effect' | 'drain';
+
+/**
+ * Records every provider input with the path that sent it and holds the first call until `release`: the other path
+ * calling the provider, finding the page's lease held, or the test, once the other path has finished.
+ */
+class Gate {
+ inputs: Array<{ by: Path; text: string }> = [];
+ holder: Path | undefined;
+ release!: () => void;
+ readonly released = new Promise<void>(resolve => { this.release = resolve; });
+ private arrive!: (by: Path) => void;
+ readonly arrived = new Promise<Path>(resolve => { this.arrive = resolve; });
+ async observe(values: string[]): Promise<void> {
+ const by: Path = drainScope.getStore() ? 'drain' : 'effect';
+ for (const text of values) this.inputs.push({ by, text });
+ if (this.holder === undefined) { this.holder = by; this.arrive(by); await this.released; }
+ else if (this.holder !== by) this.release();
+ }
+}
+let gate: Gate | null = null;
+
+async function withGate(run: (gate: Gate) => Promise<void>): Promise<void> {
+ const g = gate = new Gate();
+ pageEmbeddingLeaseProbe.contended = () => g.release();
+ try { await run(g); } finally {
+ g.release();
+ gate = null;
+ pageEmbeddingLeaseProbe.contended = undefined;
+ }
+}
+
+/** Every provider input matched to one of `chunks` (an input carries its chunk text last); returns the inputs left over. */
+function beyondOnePerChunk(inputs: string[], chunks: string[]): string[] {
+ const left = [...inputs];
+ for (const text of chunks) {
+ const at = left.findIndex(input => input.endsWith(text));
+ if (at >= 0) left.splice(at, 1);
+ }
+ return left;
+}
+
+async function openBrain(kind: 'pglite' | 'postgres'): Promise<AppendBrain> {
+ const brain = await openAppendBrain(kind);
+ const dims = (await resolveActiveEmbeddingColumnFromEngine(brain.engine)).dimensions;
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ await gate?.observe(values);
+ return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };
+ }) as never);
+ return brain;
+}
+
+/** The page's live chunks without a vector (these brains use the default \`embedding\` column). */
+async function vectorless(brain: AppendBrain, sourceId: string, slug: string): Promise<string[]> {
+ return (await brain.engine.executeRaw<{ chunk_text: string }>(
+ `SELECT cc.chunk_text FROM content_chunks cc JOIN pages p ON p.id=cc.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 AND cc.embedding IS NULL AND ${chunkGenerationFilter('p', 'cc')} ORDER BY cc.chunk_index`, [sourceId, slug])).map(r => r.chunk_text);
+}
+
+const drain = (brain: AppendBrain) => drainScope.run(true, () => runEmbedCore(brain.engine, { stale: true, catchUp: true, quiet: true }));
+
+for (const kind of testBackends()) {
+ describe(`one provider call per chunk content version, effect first on a segmented page (${kind})`, () => {
+ const SLUG = 'notes/embed-once-segmented';
+ let brain: AppendBrain;
+ const effectsSettled = async () => (await brain.engine.executeRaw<{ n: number }>(
+ "SELECT count(*)::int AS n FROM persistence_effects WHERE kind='embedding' AND state IN ('queued','running')"))[0]!.n === 0;
+
+ beforeAll(async () => {
+ brain = await openBrain(kind);
+ await brain.seed(SLUG, conversationPage(1_200_000, { seed: 7 }));
+ expect((await brain.body(SLUG)).storage).toBe('segmented');
+ await runEmbedCore(brain.engine, { stale: true, catchUp: true, quiet: true });
+ }, 600_000);
+ afterAll(() => brain.close(), 120_000);
+
+ test('forced probe: the append effect holds its provider call while a stale drain runs; each new chunk is sent once', () => withGate(async g => {
+ const appended = await brain.call('append_page', { slug: SLUG, text: conversationBody(2_000, { seed: 8 }), request_id: randomUUID() });
+ expect(appended).toMatchObject({ isError: false });
+ expect(await g.arrived).toBe('effect');
+ // The effect's call is held before its install: these are the chunks this content version adds.
+ const fresh = await vectorless(brain, 'default', SLUG);
+ const drained = await drain(brain);
+ g.release();
+ await waitFor(effectsSettled, { timeoutMs: 30_000, label: 'the append embedding effect to settle' });
+ const sent = g.inputs.map(i => i.text);
+ const extra = beyondOnePerChunk(sent, fresh);
+ console.log(`[probe effect-first ${kind}] new chunks=${fresh.length} provider inputs=${sent.length} by=${JSON.stringify(g.inputs.map(i => i.by))}`
+ + ` drain.embedded=${drained.embedded} inputs beyond one per new chunk=${extra.length}`);
+ expect(fresh.length).toBeGreaterThan(0);
+ expect(await vectorless(brain, 'default', SLUG)).toEqual([]);
+ expect(extra.length, 'provider inputs beyond one per new chunk').toBe(0);
+ expect(sent.length).toBe(fresh.length);
+ }), 600_000);
+ });
+
+ describe(`one provider call per chunk content version, drain first on an inline page (${kind})`, () => {
+ let brain: AppendBrain;
+ let home: string;
+ const CHUNKS = ['Alpha example chunk about the acme-example ledger.', 'Beta example chunk about the quarterly report.', 'Gamma example chunk about the roadmap.'];
+
+ beforeAll(async () => {
+ brain = await openBrain(kind);
+ home = mkdtempSync(join(tmpdir(), 'gbrain-embed-once-'));
+ }, 600_000);
+ afterAll(async () => {
+ await brain.close();
+ rmSync(home, { recursive: true, force: true });
+ }, 120_000);
+
+ /** A published put_page whose embedding effect is queued but not yet due, and whose chunks have no vector. */
+ async function pendingPage() {
+ const engine = brain.engine;
+ await registerLocalWriter(engine, 'cli');
+ const sourceId = `embed-once-${randomUUID()}`;
+ const [source] = await engine.executeRaw<{ incarnation: string }>('INSERT INTO sources(id,name) VALUES($1,$1) RETURNING incarnation', [sourceId]);
+ const ctx: OperationContext = { engine, config: { engine: engine.kind }, remote: false, dryRun: false, sourceId,
+ logger: { info() {}, warn() {}, error() {} } };
+ const authority = await submissionAuthority(ctx, 'put_page', sourceId, source!.incarnation, 'page');
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,
+ sourceIncarnation: source!.incarnation, slug: 'page', requestId: randomUUID(), callerIntent: { body: CHUNKS.join(' ') }, intent: { body: CHUNKS.join(' ') } });
+ const row = (await claimNextWrite(engine, localHostId()))!;
+ await publishMutation(engine, row, { observedRevision: null, apply: async tx => {
+ await tx.putPage('page', { type: 'note', title: 'Example', compiled_truth: CHUNKS.join(' '), timeline: '', frontmatter: {} }, { sourceId }); return {};
+ } }, localHostId());
+ const prepared = (await readProjectionSnapshot(engine, 'page', sourceId, { allowUnsealed: true }))!;
+ await installPageProjection(engine, prepared, CHUNKS.map((chunk_text, chunk_index) => ({ chunk_index, chunk_source: 'compiled_truth' as const, chunk_text })), { seal: true });
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id=$1::uuid", [row.id]);
+ const [effect] = await engine.executeRaw<{ id: string }>("SELECT id FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [row.id]);
+ return { sourceId, effectId: effect!.id };
+ }
+
+ test('forced probe: a stale drain holds its provider call while the page\'s embedding effect runs; each chunk is sent once', () => withEnv({ GBRAIN_HOME: home }, () => withGate(async g => {
+ const engine = brain.engine;
+ const { sourceId, effectId } = await pendingPage();
+ const fresh = await vectorless(brain, sourceId, 'page');
+ expect(fresh).toEqual(CHUNKS);
+ const drained = drain(brain);
+ expect(await g.arrived).toBe('drain');
+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [effectId]);
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 1 });
+ const result = await drained;
+ const [effect] = await engine.executeRaw<{ state: string; error_code: string | null }>('SELECT state,error_code FROM persistence_effects WHERE id=$1', [effectId]);
+ const sent = g.inputs.map(i => i.text);
+ const extra = beyondOnePerChunk(sent, fresh);
+ console.log(`[probe drain-first ${kind}] new chunks=${fresh.length} provider inputs=${sent.length} by=${JSON.stringify(g.inputs.map(i => i.by))}`
+ + ` drain.embedded=${result.embedded} effect=${effect!.state}/${effect!.error_code} inputs beyond one per new chunk=${extra.length}`);
+ expect(await vectorless(brain, sourceId, 'page')).toEqual([]);
+ expect(effect).toMatchObject({ state: 'committed' });
+ expect(extra.length, 'provider inputs beyond one per new chunk').toBe(0);
+ expect(sent.length).toBe(fresh.length);
+ })), 600_000);
+ });
+}
diff --git a/test/helpers/embed-projection-mock.ts b/test/helpers/embed-projection-mock.ts
index 03d834b130..6079636708 100644
--- a/test/helpers/embed-projection-mock.ts
+++ b/test/helpers/embed-projection-mock.ts
@@ -30,6 +30,8 @@ export function mockEmbedProjectionEngine(overrides: Partial<Record<string, any>
? [{ page_kind: pageKinds.get(Number(params?.[0])) ?? 'markdown' }]
: sql === 'SELECT archived FROM sources WHERE id=$1' ? [{ archived: false }]
: sql.includes('FROM persistence_brain') ? [{ enabled: false }]
+ // The per-page embedding lease (src/core/page-embedding-lease.ts) is always free in this single-process mock.
+ : sql.startsWith('INSERT INTO gbrain_cycle_locks') ? [{ id: params?.[0] }]
: executeRaw(sql, params);
const calls: { method: string; args: any[] }[] = [];
const track = (method: string) => (...args: any[]) => {
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 15d79af331..cad7d1f0e8 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -52,6 +52,7 @@ test/doctor-image-embedding-coverage.test.ts
test/doctor-keyword-plan-6495.test.ts
test/doctor-routing-skill-pack-source.test.ts
test/doctor-sync-freshness-skill-pack-6076.test.ts
+test/embed-once-per-content-version.serial.test.ts
test/embed-stale-images-managed-6529.test.ts
test/embedding-completion-atomic.serial.test.ts
test/engine-sql-facts-keyset.test.ts