Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

PR 4 E round 2: bound the page embedding lease wait, fence the install, sweep expired rows

garrytanc9cdc7d5635f
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index e49198acfa..ea99db6f64 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/content-drift-sweep.ts` — the content-drift sweep (#4246) as a resumable pass: `runContentDriftSweep(engine, { sourceId?, signal?, deadline?, stopped?, assertOwned?, timeBudgetMs?, batchRows? })` runs `engine-sql/chunks.ts` `invalidateContentDriftBatch` (5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config row `embed.content_drift_sweep.<column>.<all|source:id>` with the batch under a `FOR UPDATE` lock on that row, so concurrent runs share one pass. A run stops at its 60 s budget, the job deadline or an abort; a completed pass restarts after `embed.content_drift.pass_interval_hours` (default 24) unless it fit in one batch. A failed batch is returned as `state: 'failed'` with the error and recorded as `last_error` (cleared by the next committed batch); a missing v133/v221 column is `unsupported`; an `assertOwned` throw propagates. `embedAllStale` (`EmbedResult.content_drift`), `embedStaleForSource` (`contentDrift`) and the embed, embed-backfill and cycle embed results carry the status; doctor `content_drift_sweep` reads the saved rows.
-- `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/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`. The wait is bounded by the caller's `deadline` (`embedStaleForSource` passes its drain deadline) or one TTL, and then returns a busy lease (`{ busy: true }`): drains skip the page without counting a failure, the effect and the segmented effect throw `pageEmbeddingLeaseUnavailable` (`lock_busy`, retried with backoff), and `embedSegmentedPage` stops with `stopped: 'busy'`. A held lease's `assertHeld(tx)` renews the row inside every install transaction and throws `lock_busy` when it matches no row (the lease expired and another path took or deleted it), so a holder that stalled past the TTL installs nothing; a background refresh that matches no row marks the lease lost the same way. `embedStalePages` looks the page id up first and reads its snapshot under the lease. Callers bind it with `await using`, so leaving the scope releases it, error paths included; each release also deletes expired `embed-page:` rows (a crashed holder's), which keeps doctor `stale_locks` from listing them past the next embed. 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`, `waitBoundMs`) 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`; bounded wait, lost lease, snapshot under the lease, expired-row sweep and release on throw (both engines): `test/page-embedding-lease.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/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 7454770894..f985bb717d 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -36,6 +36,7 @@ src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, ref
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 430 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 #5958 (issue #5874): call_timeout_ms read and its per-page bound (phaseBoundedCallTimeout); +1 #5425 [UC4]: the one attribution-check call after the extractor returns (logic in propose-takes-attribution.ts)
src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings); +4 fix wave 11 #6161: concept redirects in grouping and the skipped_deleted pre-check (logic in cycle/concept-redirects.ts); +13 fix wave 12 #6260: a narrative stopped before the end is a counted failure, and the per-member-hash retry bound (state in cycle/concept-retry-bound.ts); +8 #6643 PR B: drifted concepts skipped before spend (state and the live check in persistence/drift-conflicts.ts ConceptDriftSkips), with the warn status, summary clause and skipped_file_drift details
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data
+src/core/embed-stale.ts embedStaleForSource 302 PR 4 E round 2 (gbrain-evals#180): the page embedding lease gives up at the drain deadline with a busy lease (page skipped) and is renewed inside the install transaction; lease logic lives in core/page-embedding-lease.ts
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/import-file.ts importFromContent 692 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts); +3 Wave B review: reuseSegments option (a rename re-preparation reuses the staged segmented body) and the remote fence merge over fenceBody; +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it
src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut it
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index e90a2325d4..31be40337e 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -6,7 +6,7 @@
src/cli/main.ts 3017 ratchet +1 W1 belief ledger: `gbrain beliefs --help` in SELF_HELP_WITHOUT_ENGINE; +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.ts; +3 Wave B PR 2: local gbrain get of a segmented page streams on the page_body_segmented refusal (logic in cli/page-render.ts streamSegmentedGet); +1 #6712 PR 3 (L7): the sync_retry_failed_deprecated notice call (logic in commands/sync/args.ts noteRetryFailedDeprecated);+1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); +1 GBRA-133 PR 2a: sync trigger through a live PGLite serve (logic in commands/sync-delegate.ts maybeTriggerThroughServe); +1 GBRA-133 PR 2a merge: master and the sync trigger serve hand-off each added a dispatch row; +1 GBRA-154 #7171: captureRetrievalNotices call after a search/query op (logic in cli/op-notices.ts)
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 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/embed.ts 2306 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); +2 PR 4 E round 2 (gbrain-evals#180): a busy lease skips the page and the install renews the lease (logic in core/page-embedding-lease.ts)
src/commands/extract-conversation-facts.ts 1889 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; lowered Wave B PR 4 lane 4b: per-window extraction, outcome rows and the version token peeled to core/facts/conversation-window-extract.ts, segmented pages routed to core/facts/conversation-incremental.ts
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 bdaf834f0a..37904b1bb4 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -2080,7 +2080,8 @@ 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 });
+ await using lease = await acquirePageEmbeddingLease(engine, stale[0].page_id, { signal: effectiveSignal });
+ if (lease.busy) return;
// 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
@@ -2147,6 +2148,7 @@ async function embedAllStale(
// work cannot commit between installation and title-tier demotion.
const install = await observed(pacer, () => engine.transaction(async tx => {
await staleOpts?.assertOwned?.(tx);
+ await lease.assertHeld(tx);
const installed = await installPageEmbeddings(tx, prepared, merged);
if (stamp && failed === 0) await stampIfPageProvenanceComplete(tx, slug, keySourceId, stamp);
if (failed === 0 && stale.length === existing.length && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 1068b4fc4e..9669c0ea0e 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1041,7 +1041,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.332.0', text: 'One search or query chunk row returns at most 8,000 characters of chunk text by default, ending with the marker that names the read for the rest (an old oversized chunk could return tens of thousands). Pass `snippet_chars: 0` for the full chunk. Evidence blocks (conversations, long-page units) keep their own budget and cap.' },
{ since: '0.60.332.0', text: '`gbrain search --explain` and `gbrain query --explain` now pass explain to the search, so `score_details` reports the arms, RRF and blend that ran; before, every row said `single_arm_path` / `no_query_embedding` even when both arms ran. A CLI search or query whose keyword or vector arm failed or timed out now prints the `degraded_recall` notice on stderr (the `--json` array stays bare), as MCP already did.' },
// 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.' },
+ { 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. The wait ends at the caller\'s deadline or after 2 minutes: a stale drain then skips the page (its chunks stay stale for the next run, not counted as a failure) and an embedding effect retries with `lock_busy`. A holder renews the lease inside its install transaction and installs nothing (`lock_busy`) when the lease expired and another path took it; every release deletes the expired `embed-page:` rows a crashed holder left, so doctor `stale_locks` stops listing them after the next embed. 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.' },
// PR 4 recall (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
{ since: 'TBD', text: 'Pages over 1 MiB (stored in segments) now cut a long passage that has to be split at a sentence or line end, so a sentence the old cut split across two chunks is found whole by keyword and vector search. Pages stored before keep serving their chunks: `gbrain reindex --segmented` lists them with the chunk counts that would change and writes nothing; `--apply` re-chunks only the segments that change and keeps the vectors of unchanged chunk texts, and `gbrain embed --stale` embeds the new ones. Nothing re-chunks on upgrade.' },
// PR 4 4e (Wave B incremental derivation, transcripts). `since` is restamped at the merge slot.
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 38176b38d4..770b30ab85 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -325,12 +325,15 @@ export async function embedStalePages(
if (page.embedded) result.pagesProcessed += 1;
continue;
}
+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]);
+ if (!page) continue;
+ await using lease = await acquirePageEmbeddingLease(engine, page.id, { signal: opts.signal });
+ if (lease.busy) continue;
// SUP-3874: split legacy oversized rows before embedding so a single
// pre-cap chunk cannot permanently fail the page.
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 });
+ if (!prepared || prepared.snapshot.page.id !== page.id) continue;
const existing = prepared.chunks;
const staleIdx = new Set(
(await engine.executeRaw<{ chunk_index: number }>(
@@ -362,6 +365,7 @@ export async function embedStalePages(
token_count: c.token_count || Math.ceil(c.chunk_text.length / 4),
}));
const install = await engine.transaction(async tx => {
+ await lease.assertHeld(tx);
const installed = await installPageEmbeddings(tx, prepared, merged,
opts.embeddingSignature && stale.length === existing.length ? opts.embeddingSignature : undefined);
if (stale.length === existing.length && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, sourceId);
@@ -559,7 +563,8 @@ 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 });
+ await using lease = await acquirePageEmbeddingLease(engine, stale[0].page_id, { signal, deadline: opts.deadline });
+ if (lease.busy) return;
// SUP-3874: split legacy oversized chunk_text before embedding.
const healed = await observed(pacer, () => engine.transaction(async tx => {
await opts.assertOwned?.(tx);
@@ -617,6 +622,7 @@ export async function embedStaleForSource(
const install = await observed(pacer, () => engine.transaction(async tx => {
await opts.assertOwned?.(tx);
if (stopped()) throw new AbortError();
+ await lease.assertHeld(tx);
const installed = await installPageEmbeddings(tx, prepared, merged);
if (stamp) await stampIfPageProvenanceComplete(tx, slug, keySourceId, stamp);
if (stale.length === existing.length && installed.complete) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, slug, keySourceId);
diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.ts
index ab872a8498..e2eaf6707d 100644
--- a/src/core/page-body/segmented-embedding.ts
+++ b/src/core/page-body/segmented-embedding.ts
@@ -120,9 +120,10 @@ export async function listSegmentedStaleRows(engine: Pick<BrainEngine, 'executeR
* nothing to embed.
*/
export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmbedPage, listed: readonly SegmentedStaleRow[],
- opts: SegmentedEmbedOpts & { includeEmbedded?: boolean }): Promise<{ pending: number; installed: number } | null> {
+ opts: SegmentedEmbedOpts & { includeEmbedded?: boolean }): Promise<{ pending: number; installed: number; busy?: true } | null> {
if (listed.length === 0) return { pending: 0, installed: 0 };
- await using _lease = await acquirePageEmbeddingLease(engine, page.id, { signal: opts.signal, whileWaiting: opts.whileWaiting });
+ await using lease = await acquirePageEmbeddingLease(engine, page.id, { signal: opts.signal, whileWaiting: opts.whileWaiting });
+ if (lease.busy) return { pending: listed.length, installed: 0, busy: true };
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;
@@ -137,7 +138,8 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb
const tier = plainEmbeddingTier(page.contextual_retrieval_mode);
const provenance = embeddingInputContext(target, page.title, null, []);
return { pending: rows.length, installed: await installSegmentedVectors(engine, page, target, chunks.map((chunk, i) => ({ chunk_index: chunk.chunk_index,
- chunk_text: chunk.chunk_text, vector: vectors[i]!, hash: embeddingInputHash(provenance, tier, chunk) })), opts.beforeInstall) };
+ chunk_text: chunk.chunk_text, vector: vectors[i]!, hash: embeddingInputHash(provenance, tier, chunk) })),
+ async tx => { await lease.assertHeld(tx); await opts.beforeInstall?.(tx); }) };
}
/** One vector to install on a segmented page: the row's chunk_index and exact text, and the recorded embedding input. */
@@ -208,7 +210,7 @@ export async function listSegmentChunkRows(engine: Pick<BrainEngine, 'executeRaw
* batches keep the approval's lifted hold but spend under the cap it set.
*/
export async function embedSegmentedPage(engine: BrainEngine, page: SegmentedEmbedPage,
- opts: SegmentedEmbedOpts & { occurrenceIds?: readonly number[]; batchRows?: number; all?: boolean }): Promise<{ embedded: number; complete: boolean; stopped?: 'budget' | 'page_moved' }> {
+ opts: SegmentedEmbedOpts & { occurrenceIds?: readonly number[]; batchRows?: number; all?: boolean }): Promise<{ embedded: number; complete: boolean; stopped?: 'budget' | 'page_moved' | 'busy' }> {
const column = (await embeddingWriteTarget(engine)).column.name;
const limit = opts.batchRows ?? SEGMENTED_EMBED_BATCH_ROWS;
let embedded = 0;
@@ -219,6 +221,7 @@ export async function embedSegmentedPage(engine: BrainEngine, page: SegmentedEmb
const approvedCapUsd = opts.approvedCapUsd === undefined || before === null ? opts.approvedCapUsd : 0;
const done = await embedSegmentedRows(engine, page, rows, { ...opts, approvedCapUsd, includeEmbedded: opts.all });
if (done === null) return { embedded, complete: false, stopped: 'budget' };
+ if (done.busy) return { embedded, complete: false, stopped: 'busy' };
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' };
diff --git a/src/core/page-embedding-lease.ts b/src/core/page-embedding-lease.ts
index a584c3d003..cee7f201cc 100644
--- a/src/core/page-embedding-lease.ts
+++ b/src/core/page-embedding-lease.ts
@@ -12,11 +12,17 @@
* 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.
+ * refreshes it and renews it once more inside its install transaction, which
+ * installs nothing when that renewal matches no row. A waiter gives up at its
+ * deadline or after one TTL and gets a busy lease instead of the page. A holder
+ * that dies leaves a row that expires after the TTL; every release deletes the
+ * expired `embed-page:` rows.
*/
import { randomUUID } from 'node:crypto';
import { hostname } from 'node:os';
import type { BrainEngine } from './engine.ts';
+import { opError, type OperationError } from './ops/contract.ts';
+import { readFix } from './ops/op-fix.ts';
import { quoteIdentifier } from './search/embedding-column.ts';
import { chunkGenerationFilter } from './search/safe-chunks.ts';
@@ -24,13 +30,31 @@ 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 } = {};
+/**
+ * Test seams: `contended` runs each time a path finds a page's lease held by another path, before it waits;
+ * `waitBoundMs` replaces the default wait bound (one TTL).
+ */
+export const pageEmbeddingLeaseProbe: { contended?: (pageId: number) => void; waitBoundMs?: number } = {};
export function pageEmbeddingLeaseId(pageId: number): string {
return `embed-page:${pageId}`;
}
+/**
+ * A page's embedding lease. `busy`: another path held it through the whole wait, nothing was taken and the
+ * caller leaves the page to that path. Otherwise `assertHeld(tx)` renews it inside the install transaction and
+ * throws `lock_busy` when the renewal matches no row (it expired and was taken or deleted), so nothing installs.
+ */
+export type PageEmbeddingLease = AsyncDisposable & ({ busy: true } | { busy: false; assertHeld(tx: Pick<BrainEngine, 'executeRaw'>): Promise<void> });
+
+/** The retryable error for a page whose embedding lease another path holds (`lost`: this holder's lease was taken over). */
+export function pageEmbeddingLeaseUnavailable(pageId: number, lost: boolean): OperationError {
+ return opError('lock_busy', lost ? 'This page\'s embedding lease was lost before the install.' : 'Another path is embedding this page.',
+ lost ? `The embedding lease of page ${pageId} expired and was taken or reclaimed by another path, so this attempt installed no vectors; that path or the next embed run embeds the page.`
+ : `Another path held the embedding lease of page ${pageId} through the whole wait, so this attempt sent nothing to the provider; that path embeds the page, and a retry embeds only what it leaves.`,
+ { fix: readFix('Shows the gbrain_cycle_locks rows, embed-page leases included, with holder and expiry, read-only.', { argv: ['gbrain', 'status', '--section', 'locks', '--json'] }) });
+}
+
function pause(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise(resolve => {
const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', done); resolve(); };
@@ -40,13 +64,13 @@ function pause(ms: number, signal?: AbortSignal): Promise<void> {
}
/**
- * 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
+ * Takes page `pageId`'s embedding lease, waiting while another path holds it until `deadline` (epoch ms) or one
+ * TTL, whichever is sooner, and returning a busy lease then. `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> {
+ opts: { signal?: AbortSignal; deadline?: number; whileWaiting?: () => Promise<void> } = {}): Promise<PageEmbeddingLease> {
const id = pageEmbeddingLeaseId(pageId);
const token = randomUUID();
const take = async () => (await engine.executeRaw(
@@ -56,21 +80,31 @@ export async function acquirePageEmbeddingLease(engine: BrainEngine, pageId: num
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;
+ const bound = Math.min(opts.deadline ?? Infinity, Date.now() + (pageEmbeddingLeaseProbe.waitBoundMs ?? PAGE_EMBEDDING_LEASE_TTL_MINUTES * 60_000));
for (let waitMs = 50; !await take(); waitMs = Math.min(waitMs * 2, LEASE_WAIT_MAX_MS)) {
pageEmbeddingLeaseProbe.contended?.(pageId);
+ if (Date.now() >= bound) return { busy: true, [Symbol.asyncDispose]: async () => {} };
await opts.whileWaiting?.();
- await pause(waitMs, opts.signal);
+ await pause(Math.min(waitMs, Math.max(0, bound - Date.now())), opts.signal);
opts.signal?.throwIfAborted();
}
+ let lost = false;
+ const renew = async (exec: Pick<BrainEngine, 'executeRaw'>) => {
+ if (!lost) lost = (await exec.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 RETURNING id`, [id, token, PAGE_EMBEDDING_LEASE_TTL_MINUTES])).length === 0;
+ return !lost;
+ };
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 */ });
+ renew(engine).then(held => { if (!held) clearInterval(refresh); }, () => { /* the install's renewal decides */ });
}, LEASE_REFRESH_MS);
refresh.unref?.();
return {
+ busy: false,
+ assertHeld: async tx => { if (!await renew(tx)) throw pageEmbeddingLeaseUnavailable(pageId, true); },
[Symbol.asyncDispose]: async () => {
clearInterval(refresh);
- await engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id = $1 AND acquisition_token = $2::uuid', [id, token])
+ await engine.executeRaw(`DELETE FROM gbrain_cycle_locks
+ WHERE (id = $1 AND acquisition_token = $2::uuid) OR (id LIKE 'embed-page:%' AND ttl_expires_at < now())`, [id, token])
.catch(() => { /* the TTL is the backstop */ });
},
};
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index d69dd6fb65..a1f257bbd4 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -54,7 +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 { acquirePageEmbeddingLease, pageEmbeddingLeaseUnavailable } from '../page-embedding-lease.ts';
import { chunkGenerationFilter, chunkManifestReads } from '../search/safe-chunks.ts';
import { classifyItemFailure, ItemRun } from '../item-failure.ts';
@@ -429,11 +429,12 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
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 () => {
+ await using pageLease = 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) });
} });
+ if (pageLease.busy) throw pageEmbeddingLeaseUnavailable(snapshot.page.id, false);
const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);
const { prepared } = projection;
let pending = projection.pending;
@@ -499,6 +500,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
await tx.executeRaw("SELECT key FROM config WHERE key='embedding_disabled' FOR SHARE");
await assertEmbeddingEffectEnabled(tx, config);
signal.throwIfAborted();
+ await pageLease.assertHeld(tx);
// A partially refused page keeps its signature unstamped so `gbrain embed --stale` finds the refused chunks.
// A partial install (the page changed under the provider call) keeps the vectors whose chunk and input
// still match and settles like a superseded one: the newer revision's own effect embeds the rest.
@@ -568,6 +570,7 @@ async function embedSegmentedEffect(engine: BrainEngine, config: GBrainConfig, e
} });
if (result.stopped === 'budget') { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'budget_capped' }); return; }
if (result.stopped === 'page_moved') { await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return; }
+ if (result.stopped === 'busy') throw pageEmbeddingLeaseUnavailable(page.id, false);
const stamp = await resolveProvenanceStamp(engine, signature);
if (stamp) await stampIfPageProvenanceComplete(engine, page.slug, page.source_id, stamp);
await finishPage(engine, effect, snapshot);
diff --git a/test/embed-once-per-content-version.serial.test.ts b/test/embed-once-per-content-version.serial.test.ts
index e3819955a5..5b1b45603e 100644
--- a/test/embed-once-per-content-version.serial.test.ts
+++ b/test/embed-once-per-content-version.serial.test.ts
@@ -23,18 +23,14 @@ 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';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { pendingEmbedPage } from './helpers/pending-embed-page.ts';
/** Marks the drain's provider calls; every other call comes from an embedding effect. */
const drainScope = new AsyncLocalStorage<true>();
@@ -148,31 +144,9 @@ for (const kind of testBackends()) {
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 { sourceId, effectId } = await pendingEmbedPage(engine, CHUNKS);
const fresh = await vectorless(brain, sourceId, 'page');
expect(fresh).toEqual(CHUNKS);
const drained = drain(brain);
diff --git a/test/helpers/embed-projection-mock.ts b/test/helpers/embed-projection-mock.ts
index 6079636708..69131f7a2e 100644
--- a/test/helpers/embed-projection-mock.ts
+++ b/test/helpers/embed-projection-mock.ts
@@ -30,8 +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] }]
+ // The per-page embedding lease (src/core/page-embedding-lease.ts) is always free, and its install-time renewal always holds, in this single-process mock.
+ : sql.startsWith('INSERT INTO gbrain_cycle_locks') || sql.startsWith('UPDATE 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/helpers/pending-embed-page.ts b/test/helpers/pending-embed-page.ts
new file mode 100644
index 0000000000..e723e38269
--- /dev/null
+++ b/test/helpers/pending-embed-page.ts
@@ -0,0 +1,32 @@
+/**
+ * A published put_page in a fresh source whose chunks have no vector and whose embedding effect is queued but not
+ * due for an hour, so a test decides when (and whether) the effect runs. Call it under a GBRAIN_HOME the test owns.
+ */
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.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';
+
+export async function pendingEmbedPage(engine: BrainEngine, chunks: readonly string[], slug = 'page'): Promise<{ sourceId: string; effectId: string; pageId: number }> {
+ await registerLocalWriter(engine, 'cli');
+ const sourceId = `embed-pending-${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, slug);
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId,
+ sourceIncarnation: source!.incarnation, slug, 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(slug, { type: 'note', title: 'Example', compiled_truth: chunks.join(' '), timeline: '', frontmatter: {} }, { sourceId }); return {};
+ } }, localHostId());
+ const prepared = (await readProjectionSnapshot(engine, slug, 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, pageId: prepared.snapshot.page.id };
+}
diff --git a/test/page-embedding-lease.serial.test.ts b/test/page-embedding-lease.serial.test.ts
new file mode 100644
index 0000000000..5beb8206e4
--- /dev/null
+++ b/test/page-embedding-lease.serial.test.ts
@@ -0,0 +1,199 @@
+/**
+ * PR 4 E round 2 (gbrain-evals#180): the per-page embedding lease (src/core/page-embedding-lease.ts) under contention.
+ *
+ * 1. Protects: a path that finds a page's lease held gives up at its deadline (or after one TTL) with a busy lease
+ * instead of waiting forever; a holder whose lease was taken over during its provider call installs nothing;
+ * `embedStalePages` reads the page under the lease; a release deletes the expired `embed-page:` rows a dead
+ * holder left (doctor `stale_locks` clears); and a holder that throws releases its lease.
+ * 2. Fails when: the wait loop has no bound, the install skips the lease renewal, the drain reads its snapshot before
+ * the lease, expired lease rows stay, or an error path skips the release. Each test holds the lease itself or
+ * steals it inside the provider call, so every contention is forced, never timed.
+ * 3. The provider is an injected embedFn or the gateway's transport seam: no network, no spend. PGLite always;
+ * PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt). Serial: the transport and the lease probe are
+ * process-wide.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { openAppendBrain, type AppendBrain } from './helpers/append-brain.ts';
+import { pendingEmbedPage } from './helpers/pending-embed-page.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.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 { acquirePageEmbeddingLease, pageEmbeddingLeaseId, pageEmbeddingLeaseProbe } from '../src/core/page-embedding-lease.ts';
+import { embedStaleForSource, embedStalePages } from '../src/core/embed-stale.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { installPageProjection, readProjectionSnapshot } from '../src/core/page-state/projections.ts';
+import { listStaleLocks } from '../src/core/db-lock.ts';
+import { checkStaleLocks } from '../src/commands/doctor/checks/routing-federation.ts';
+
+const CHUNKS = ['Alpha example chunk about the acme-example ledger.', 'Beta example chunk about the quarterly report.', 'Gamma example chunk about the roadmap.'];
+
+for (const kind of testBackends()) {
+ describe(`page embedding lease under contention (${kind})`, () => {
+ let brain: AppendBrain;
+ let home: string;
+ let dims: number;
+ const sent: string[] = [];
+ const vector = () => Float32Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0));
+ /** The injected provider: records each input and answers unit vectors. */
+ const embedFn = async (texts: string[]) => { sent.push(...texts); return texts.map(vector); };
+ /** The gateway provider the embedding effect calls; `during` runs inside the call, before it answers. */
+ const transport = (during?: () => Promise<void>) => __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ sent.push(...values);
+ await during?.();
+ return { embeddings: values.map(() => Array.from(vector())), usage: { tokens: values.length } };
+ }) as never);
+ const vectorless = async (sourceId: string, slug = 'page') => (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 leaseRows = async (pageId: number) => brain.engine.executeRaw<{ acquisition_token: string }>(
+ 'SELECT acquisition_token FROM gbrain_cycle_locks WHERE id=$1', [pageEmbeddingLeaseId(pageId)]);
+ const steal = (pageId: number) => brain.engine.executeRaw('UPDATE gbrain_cycle_locks SET acquisition_token=$2::uuid WHERE id=$1', [pageEmbeddingLeaseId(pageId), randomUUID()]);
+ const runEffect = async (effectId: string) => {
+ await brain.engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [effectId]);
+ await runPersistenceEffects(brain.engine, { engine: brain.engine.kind }, { hostId: localHostId(), limit: 1 });
+ return (await brain.engine.executeRaw<{ state: string; error_code: string | null }>('SELECT state,error_code FROM persistence_effects WHERE id=$1', [effectId]))[0]!;
+ };
+ const pending = () => withEnv({ GBRAIN_HOME: home }, () => pendingEmbedPage(brain.engine, CHUNKS));
+
+ beforeAll(async () => {
+ brain = await openAppendBrain(kind);
+ dims = (await resolveActiveEmbeddingColumnFromEngine(brain.engine)).dimensions;
+ home = mkdtempSync(join(tmpdir(), 'gbrain-embed-lease-'));
+ }, 600_000);
+ afterEach(() => {
+ sent.length = 0;
+ pageEmbeddingLeaseProbe.contended = undefined;
+ pageEmbeddingLeaseProbe.waitBoundMs = undefined;
+ transport();
+ });
+ afterAll(async () => {
+ await brain.close();
+ rmSync(home, { recursive: true, force: true });
+ }, 120_000);
+
+ test('a waiter gives up at its deadline with a busy lease, and the holder keeps the page', async () => {
+ const { pageId } = await pending();
+ await using _holder = await acquirePageEmbeddingLease(brain.engine, pageId);
+ const [held] = await leaseRows(pageId);
+ let contended = 0;
+ pageEmbeddingLeaseProbe.contended = () => { contended++; };
+ const waiter = await acquirePageEmbeddingLease(brain.engine, pageId, { deadline: Date.now() + 300 });
+ expect(waiter.busy).toBe(true);
+ expect(contended).toBeGreaterThan(0);
+ expect(await leaseRows(pageId)).toEqual([held!]);
+ }, 30_000);
+
+ test('a stale drain skips a page another path holds past the drain deadline: nothing sent, no failure', async () => {
+ const { sourceId, pageId } = await pending();
+ await using _holder = await acquirePageEmbeddingLease(brain.engine, pageId);
+ let contended = 0;
+ pageEmbeddingLeaseProbe.contended = () => { contended++; };
+ const result = await embedStaleForSource(brain.engine, sourceId, { embedFn, concurrency: 1, deadline: Date.now() + 2_000 });
+ expect(contended).toBeGreaterThan(0);
+ expect(sent).toEqual([]);
+ expect(result.failures ?? 0).toBe(0);
+ expect(await vectorless(sourceId)).toEqual(CHUNKS);
+ }, 30_000);
+
+ test('the embedding effect gives up after its wait bound and retries with lock_busy, sending nothing', async () => {
+ const { sourceId, effectId, pageId } = await pending();
+ await using _holder = await acquirePageEmbeddingLease(brain.engine, pageId);
+ pageEmbeddingLeaseProbe.waitBoundMs = 300;
+ let contended = 0;
+ pageEmbeddingLeaseProbe.contended = () => { contended++; };
+ const effect = await withEnv({ GBRAIN_HOME: home }, () => runEffect(effectId));
+ expect(contended).toBeGreaterThan(0);
+ expect(effect).toMatchObject({ state: 'queued', error_code: 'lock_busy' });
+ expect(sent).toEqual([]);
+ expect(await vectorless(sourceId)).toEqual(CHUNKS);
+ }, 30_000);
+
+ test('a stale drain whose lease is taken over during the provider call installs nothing', async () => {
+ const { sourceId, pageId } = await pending();
+ const result = await embedStalePages(brain.engine, ['page'], sourceId, { embedFn: async texts => { await steal(pageId); return embedFn(texts); } });
+ expect(sent.length).toBe(CHUNKS.length);
+ expect(result.embedded).toBe(0);
+ expect(await vectorless(sourceId)).toEqual(CHUNKS);
+ }, 30_000);
+
+ test('the embedding effect whose lease is taken over during the provider call installs nothing and retries', async () => {
+ const { sourceId, effectId, pageId } = await pending();
+ transport(async () => { await steal(pageId); });
+ const effect = await withEnv({ GBRAIN_HOME: home }, () => runEffect(effectId));
+ expect(sent.length).toBe(CHUNKS.length);
+ expect(effect).toMatchObject({ state: 'queued', error_code: 'lock_busy' });
+ expect(await vectorless(sourceId)).toEqual(CHUNKS);
+ }, 30_000);
+
+ test('embedStalePages reads the page under its lease: a rewrite while it waits is what it sends', async () => {
+ const { sourceId, pageId } = await pending();
+ const REWRITTEN = CHUNKS.map(text => text.replace('example chunk', 'rewritten chunk'));
+ const holder = await acquirePageEmbeddingLease(brain.engine, pageId);
+ const waiting = new Promise<void>(resolve => { pageEmbeddingLeaseProbe.contended = () => resolve(); });
+ const drained = embedStalePages(brain.engine, ['page'], sourceId, { embedFn });
+ await waiting;
+ const prepared = (await readProjectionSnapshot(brain.engine, 'page', sourceId))!;
+ await installPageProjection(brain.engine, prepared, REWRITTEN.map((chunk_text, chunk_index) => ({ chunk_index, chunk_source: 'compiled_truth' as const, chunk_text })), { seal: true });
+ await holder[Symbol.asyncDispose]();
+ const result = await drained;
+ expect(sent.filter(input => CHUNKS.some(text => input.endsWith(text)))).toEqual([]);
+ expect(sent.length).toBe(REWRITTEN.length);
+ expect(REWRITTEN.every(text => sent.some(input => input.endsWith(text)))).toBe(true);
+ expect(result.embedded).toBe(REWRITTEN.length);
+ expect(await vectorless(sourceId)).toEqual([]);
+ }, 30_000);
+
+ test('a release deletes the expired embed-page rows a dead holder left, so doctor stale_locks clears; other locks stay', async () => {
+ const { sourceId } = await pending();
+ const dead = 'embed-page:987654321';
+ const sync = `gbrain-sync:lease-test-${randomUUID()}`;
+ for (const id of [dead, sync]) {
+ await brain.engine.executeRaw(`INSERT INTO gbrain_cycle_locks (id, holder_pid, holder_host, acquired_at, ttl_expires_at, last_refreshed_at, acquisition_token)
+ VALUES ($1, 999999, 'host-a', now() - interval '2 hours', now() - interval '1 hour', now() - interval '1 hour', $2::uuid)`, [id, randomUUID()]);
+ }
+ expect((await listStaleLocks(brain.engine)).map(l => l.id)).toContain(dead);
+ const result = await embedStalePages(brain.engine, ['page'], sourceId, { embedFn });
+ expect(result.embedded).toBe(CHUNKS.length);
+ const stale = (await listStaleLocks(brain.engine)).map(l => l.id);
+ expect(stale.filter(id => id.startsWith('embed-page:'))).toEqual([]);
+ expect(stale).toContain(sync);
+ await brain.engine.executeRaw('DELETE FROM gbrain_cycle_locks WHERE id=$1', [sync]);
+ expect((await checkStaleLocks(brain.engine)).status).toBe('ok');
+ }, 30_000);
+
+ test('a holder that throws releases its lease: the drain, the effect and a bare holder', async () => {
+ const failing = async (): Promise<Float32Array[]> => { throw new Error('provider refused'); };
+ const drainPage = await pending();
+ expect((await embedStalePages(brain.engine, ['page'], drainPage.sourceId, { embedFn: failing })).embedded).toBe(0);
+ expect(await leaseRows(drainPage.pageId)).toEqual([]);
+
+ const effectPage = await pending();
+ __setEmbedTransportForTests((async () => { throw new Error('provider refused'); }) as never);
+ const effect = await withEnv({ GBRAIN_HOME: home }, () => runEffect(effectPage.effectId));
+ expect(effect.state).not.toBe('committed');
+ expect(await leaseRows(effectPage.pageId)).toEqual([]);
+
+ const barePage = await pending();
+ await expect((async () => {
+ await using _lease = await acquirePageEmbeddingLease(brain.engine, barePage.pageId);
+ throw new Error('holder failed');
+ })()).rejects.toThrow('holder failed');
+ expect(await leaseRows(barePage.pageId)).toEqual([]);
+
+ let contended = 0;
+ pageEmbeddingLeaseProbe.contended = () => { contended++; };
+ for (const { pageId } of [drainPage, effectPage, barePage]) {
+ await using _next = await acquirePageEmbeddingLease(brain.engine, pageId, { deadline: Date.now() });
+ expect((await leaseRows(pageId)).length).toBe(1);
+ }
+ expect(contended).toBe(0);
+ }, 30_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 530f912ff4..7957855e9f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -236,6 +236,7 @@ test/pack-relation-direction-engine.test.ts
test/page-embedding-budget.test.ts
test/page-embedding-content-validity.test.ts
test/page-embedding-install-batch.test.ts
+test/page-embedding-lease.serial.test.ts
test/page-prepare-shared-origin-6517.test.ts
test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts