Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P2.6 (#5968): embed --stale progress counts chunks exactly, never past 100%

garrytanec71fbd33ade
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index 952fa8fd3b..7fe0ca6387 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. Its result prints from `runEmbed` only without `--json`; under `--json` the CLI dispatch writes the one document. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages. Fix wave 13 P1.18 (#6400): `runEmbed` takes the CLI's consent outcome; a finite approved `cap_usd` runs the foreground text and `--images` paths under `embedCostCap` (`src/core/embed-cost-cap.ts`) and returns `reason: 'cost_cap'` (exit `BUDGET_STOP_EXIT_CODE` from `src/cli/commands/embed.ts`, which now returns the Authorization from `authorizeEmbed`); `--background` stores it on the row through `maybeBackground(...spendAuthorization)` (PGLite runs inline, metered). `--slugs` takes the arguments up to the next flag. Tests: `test/embed-max-usd-metered.serial.test.ts`, `test/e2e/embed-background-cap.test.ts`.
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `--stale` progress (#5968) is exact chunk accounting through `src/core/embed-stale-progress.ts`: `onProgress(done, total, embedded)` carries cumulative stale chunks against a total that grows by heal splits, behind-cursor rows and re-entries, the CLI ticks `embed.pages` by the delta and forwards the grown total with `setTotal`, and `done <= total` holds at every callback. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. Its result prints from `runEmbed` only without `--json`; under `--json` the CLI dispatch writes the one document. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages. Fix wave 13 P1.18 (#6400): `runEmbed` takes the CLI's consent outcome; a finite approved `cap_usd` runs the foreground text and `--images` paths under `embedCostCap` (`src/core/embed-cost-cap.ts`) and returns `reason: 'cost_cap'` (exit `BUDGET_STOP_EXIT_CODE` from `src/cli/commands/embed.ts`, which now returns the Authorization from `authorizeEmbed`); `--background` stores it on the row through `maybeBackground(...spendAuthorization)` (PGLite runs inline, metered). `--slugs` takes the arguments up to the next flag. Tests: `test/embed-max-usd-metered.serial.test.ts`, `test/e2e/embed-background-cap.test.ts`.
- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.
- `src/commands/doctor/checks/atom-holds.ts` — `extract_atoms_held_failed` (#6325, BRAIN, registered before `fence_integrity`). Lists `listHeldManagedAtoms` (`persistence/atom-maintenance.ts`): managed atom pages and transcripts held after `MAX_DETERMINISTIC_FAILURES` failed extractions of their current content (code `held_failed`) that no later run completed, each with its last request id, failure, `receipt_command` and `retry_command`. Warns with a paid `fix` (the reviewed `gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'` retry of the first item). Local doctor only; `run_doctor` does not include it. Tests: `test/managed-atoms-retry.test.ts`.
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 34f4f19533..0df90dd329 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -30,7 +30,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/forward-progress.ts` — process-wide forward-progress signal, zero imports. `noteForwardProgress()` records that a unit of work completed (called by every `progress.ts` tick); `onForwardProgress(listener)` subscribes and returns the unsubscribe; `lastForwardProgressAt()` reads the last note. Consumers are deadlines that must never stop a run that is still progressing: the sync watchdog (`process-watchdog.ts`, `progressWindowMs`) and the `gbrain serve` boot deadline. Heartbeats are not progress.
- `src/core/spawn.ts` — the one module in `src/` that launches subprocesses with `windowsHide` defaulted (#4992, contributed by @rokas-tarasevicius in PR #6105). A `detached: true` child on Windows has no console, so every console program it launches without `windowsHide` opens a visible console window that takes focus; the Stop-hook push, the backup check, the job supervisor, its worker and every job child run that way. Wraps `spawn`, `spawnSync`, `exec`, `execSync`, `execFile`, `execFileSync` (Node's overloads and `util.promisify.custom` kept) plus `bunSpawn` / `bunSpawnSync`, each defaulting `windowsHide: true` and keeping an explicit `false` (only `openBrowser` in `creds/redirect.ts`). Calls go through `child_process` and `Bun` at call time, so `spyOn` in tests still intercepts them. Trade-off: with every stdio stream piped or ignored, libuv turns the flag into CREATE_NO_WINDOW and the child gets a windowless console of its own, so a program that prompts on the console directly prompts invisibly; gbrain's networked git calls set `GIT_TERMINAL_PROMPT=0` (git-remote.ts also `SSH_ASKPASS_REQUIRE=never`), and inherited-stdio launches still attach to the terminal. `scripts/check-windows-hide.ts` (`bun run check:windows-hide`, in `verify`) is a RATCHET: a new runtime `child_process` import or `Bun.spawn*` in `src/` fails unless the file is in its `NOT_YET_MIGRATED` list (the minions supervisor/worker/child/readiness/isolation/registry/shell handler, `workspace-push.ts`, `cli/main.ts`, `context/hook-heartbeat.ts`, the backup check, `cli-force-exit.ts`, `cli-preflight.ts`, `autopilot-lock.ts`, the autopilot commands and `bounded-child-exec.ts` are migrated; the rest, wave-13-claimed files included, are listed and lose the entry when they move), and a listed file that stops launching directly fails as stale. Pinned by `test/spawn-windows-hide.test.ts` (argument shapes; the detached supervisor, worker and push-git sites), `test/scripts/windows-hide-guard.test.ts` (forms, allowlist, ratchet, stale entries, the repository) and, natively on the test.yml `security-regressions` Windows row, `test/windows-hidden-console.test.ts` (a compiled console probe launched from a console-less detached process: the unhidden CONTROL launch must show a window or the run fails as `windows_console_gate_unsupported`; then the worker, the push's git and every seam launcher show none).
-- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY `\r`-rewriting; non-TTY plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` for single long queries. `child()` composes phase paths. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Every `tick` calls `noteForwardProgress()`, so bulk work feeds the progress-aware deadlines; its only import is that zero-import leaf. `emitHumanLine` is prefix-aware — inside a `withSourcePrefix(id, ...)` scope from `src/core/console-prefix.ts` it prepends `[id] ` (and TTY-rewrite mode `\r\x1b[2K` carries the prefix inside the clear-to-EOL escape); `emitJson` is intentionally NOT prefixed so NDJSON consumers don't choke on a `[id] {...}` shape. JSON `tick` events carry `cpu_ms`, the main thread's CPU time since the phase started (`process.threadCpuUsage()`); the scale tier's PGLite import-rate gate (`scripts/scale/gates.ts`) judges on it.
+- `src/core/embed-stale-progress.ts` — `StaleChunkProgress` (#5968, wave 15 P2.6 [R28]): the exact tally behind `embed --stale` progress. Unit: stale chunks. `total` starts at the census and only grows: `listed(rows)` raises it to the rows actually listed (a writer adding stale rows behind the keyset cursor), `reentered(remaining)` to what a paced re-entry will relist, and `pageDone(census, handled)` by the heal delta when one oversized stored chunk became several, in the same step that adds the page's rows to `done` (failed, filtered and quarantined rows included), so `done <= total` at every callback and a finished run reads 100%. Pinned by `test/embed-stale-progress-5968.serial.test.ts`.
+- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY `\r`-rewriting; non-TTY plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` for single long queries. `child()` composes phase paths. `setTotal(total)` (optional on the interface; #5968) replaces a running phase's total once the exact amount of work is known, so a caller whose work grows mid-phase (a heal split, a re-entry) never reports past 100%. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Every `tick` calls `noteForwardProgress()`, so bulk work feeds the progress-aware deadlines; its only import is that zero-import leaf. `emitHumanLine` is prefix-aware — inside a `withSourcePrefix(id, ...)` scope from `src/core/console-prefix.ts` it prepends `[id] ` (and TTY-rewrite mode `\r\x1b[2K` carries the prefix inside the clear-to-EOL escape); `emitJson` is intentionally NOT prefixed so NDJSON consumers don't choke on a `[id] {...}` shape. JSON `tick` events carry `cpu_ms`, the main thread's CPU time since the phase started (`process.threadCpuUsage()`); the scale tier's PGLite import-rate gate (`scripts/scale/gates.ts`) judges on it.
- `src/core/retry.ts` — canonical retry primitive for transient connection errors. Exports `withRetry<T>(fn, opts)` execution wrapper + `BULK_RETRY_OPTS` constant (`{maxRetries:3, delayMs:1000, delayMaxMs:10000, jitter:'decorrelated'}`, tuned for Supabase Supavisor's 5-10s circuit-breaker recovery) + `BATCH_AUDIT_SITES` typed const (closed enum of every audit-emission site) + `resolveBulkRetryOpts(env)` (reads `GBRAIN_BULK_MAX_RETRIES`/`GBRAIN_BULK_RETRY_BASE_MS`/`GBRAIN_BULK_RETRY_MAX_MS` with `>=0` validation, throws on bad input with a paste-ready hint) + `abortableSleep(ms, signal?)` + `RetryAbortError` (tagged error for clean shutdown) + `computeNextDelay()` (pure-fn for 3 jitter modes: `'none'`, `'full'`, `'decorrelated'`). The execution wrapper is consumed by `postgres-engine.ts` + `pglite-engine.ts` batch primitives (`addLinksBatch` / `addTimelineEntriesBatch` / `upsertChunks`) so every caller inherits retry as part of the data-primitive's contract. CI guard `scripts/check-no-double-retry.sh` fails the build on `withRetry(...engine.batch...)` patterns (prevents 3×3=9 retry amplification); `scripts/check-batch-audit-site.sh` validates every string-literal `auditSite: '...'` against the closed `BATCH_AUDIT_SITES` enum. Decorrelated jitter (AWS-style: `uniform(base, prevDelay*3)` capped at `delayMaxMs`) — `'full'` jitter would allow near-zero retries that re-hit the recovering breaker. `WithRetryOpts` has an optional `reconnect?: () => Promise<void>` callback awaited in the catch branch AFTER `isRetryableConnError` classification but BEFORE the inter-attempt sleep — lets engine-level callers rebuild a dead pool/singleton between attempts. `PostgresEngine.batchRetry` injects `() => this.reconnect()` (the race-safe `_reconnecting` guard kicks in). Fail-loud: a reconnect throw PROPAGATES as the new error, replacing the symptomatic "No database connection". `onRetry` callbacks are awaited (sync arrows work identically; async callbacks correctly delay the sleep). Pinned by `test/core/retry.test.ts` (37 cases), `test/core/retry-stress.slow.test.ts` (5 cases, 100 batches × 30% blip rate, asserts zero row loss), `test/core/retry-reconnect.test.ts` (5 cases), `test/e2e/db-singleton-shared-recovery.test.ts` (3 DB-gated cases).
diff --git a/docs/progress-events.md b/docs/progress-events.md
index df05d87158..79cd7506cf 100644
--- a/docs/progress-events.md
+++ b/docs/progress-events.md
@@ -146,7 +146,7 @@ Stable phase names:
passed — a cold start can take 5–20s, so the heartbeat is the only sign of
life)
- `orphans.scan`
-- `embed.pages`
+- `embed.pages` (for `embed --stale` the unit is stale chunks since #5968: `total` is the census, grown by heal splits and re-entries so `done <= total` always; other embed paths tick per page)
- `extract.links_fs`, `extract.timeline_fs`, `extract.links_db`, `extract.timeline_db`
- `import.files`
- `sync.deletes`, `sync.renames`, `sync.imports`
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index a53d3fe1bf..0b12905775 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -23,6 +23,7 @@ import {
} from '../core/embed-stall.ts';
import { createProgress, type ProgressReporter } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
+import { StaleChunkProgress } from '../core/embed-stale-progress.ts';
import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';
import { writeCliError } from '../cli/cli-error.ts';
import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';
@@ -984,19 +985,16 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
// all work. Minion handlers call runEmbedCore directly with their own
// onProgress (see jobs.ts).
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
- let progressStarted = false;
- opts.onProgress = (done, total, _embedded) => {
- if (!progressStarted) {
- progress.start('embed.pages', total);
- progressStarted = true;
- }
- progress.tick(1);
+ let progressDone: number | null = null;
+ opts.onProgress = (done, total) => {
+ if (progressDone === null) progress.start('embed.pages', total); else progress.setTotal?.(total);
+ progress.tick(done - (progressDone ?? 0)); progressDone = done;
};
if (costCap) opts.signal = costCap.signal;
try {
const result = costCap ? await costCap.metered(() => runEmbedCore(engine, opts)) : await runEmbedCore(engine, opts);
- if (progressStarted) progress.finish();
+ if (progressDone !== null) progress.finish();
const capped = costCap?.hit();
if (capped) {
noteEmbedCostStop(result, capped, args);
@@ -1023,7 +1021,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
if (result.reason === 'time_budget') slog(embedBudgetStopVerdict(result));
return result;
} catch (e) {
- if (progressStarted) progress.finish();
+ if (progressDone !== null) progress.finish();
const capped = costCap?.hit();
if (capped) {
const stopped: EmbedResult = { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0, failures: 0, failure_samples: [], dryRun: false, chunkless_pages_healed: 0 };
@@ -1794,6 +1792,7 @@ async function embedAllStale(
? { ...sourceOpt, signature, ...(includeNullSig && { includeNullSignature: true }) }
: sourceOpt,
);
+ const staleProgress = new StaleChunkProgress(staleCount);
if (staleCount === 0) {
await reportArchived();
if (!staleOpts?.quiet) {
@@ -1923,7 +1922,7 @@ async function embedAllStale(
if (remaining === 0) return false;
if (result.embedded === lastReentryEmbedded) return false; // no forward progress
lastReentryEmbedded = result.embedded;
- reentries++;
+ reentries++; staleProgress.reentered(remaining);
afterPageId = 0;
afterChunkIndex = -1;
afterUpdatedAt = null;
@@ -1962,7 +1961,7 @@ async function embedAllStale(
if (await maybeReenter()) continue;
break;
}
- totalChunksLoaded += batch.length;
+ totalChunksLoaded += batch.length; staleProgress.listed(batch.length);
// Advance cursor to last row in this batch.
const last = batch[batch.length - 1];
@@ -1994,11 +1993,13 @@ async function embedAllStale(
const keys = allKeys.filter(k => (_embedFailureCounts.get(k) ?? 0) < QUARANTINE_AFTER);
if (keys.length < allKeys.length) {
serr(`\n [embed] skipping ${allKeys.length - keys.length} page(s) quarantined after ${QUARANTINE_AFTER} consecutive failed embed attempts (this process); set frontmatter.embed_skip to skip permanently, or restart to retry`);
+ for (const k of allKeys) if (!keys.includes(k)) staleProgress.pageDone(byKey.get(k)!.length, 0);
}
result.total_chunks += batch.length;
async function embedOneKey(key: string) {
let stale = byKey.get(key)!;
+ const census = stale.length;
const keySourceId = stale[0]?.source_id ?? 'default';
const slug = stale[0].slug;
try {
@@ -2088,12 +2089,11 @@ async function embedAllStale(
recordFailure(result, stale.length, slug, e);
serr(`\n Error embedding ${slug}: ${e instanceof Error ? e.message : e}`);
noteEmbedQuarantineFailure(key, slug);
+ } finally {
+ const tally = staleProgress.pageDone(census, stale.length); onProgress?.(tally.done, tally.total, result.embedded);
}
processedPageKeys.add(key);
result.pages_processed++;
- // Use staleCount as the estimated total for progress (not exact after
- // pagination starts, but directionally correct).
- onProgress?.(processedPageKeys.size, Math.ceil(staleCount / PAGE_SIZE) * keys.length, result.embedded);
// Cooperative DB-contention pace between keys (no-op when unpaced).
// E-4 (Codex P1): pace() is subject to the EXTERNAL abort only, NOT the
// wall-clock budget — a contended DB's sleep must not be cut by the
diff --git a/src/core/embed-stale-progress.ts b/src/core/embed-stale-progress.ts
new file mode 100644
index 0000000000..84545a5a21
--- /dev/null
+++ b/src/core/embed-stale-progress.ts
@@ -0,0 +1,47 @@
+/**
+ * Exact progress accounting for `embed --stale` (#5968, wave 15 P2.6 [R28]).
+ *
+ * The unit is stale chunks, the thing the census counts. `total` starts at
+ * the census and only grows: to the rows actually listed when a writer adds
+ * stale rows behind the keyset cursor, to the rows a paced re-entry announces,
+ * and by the heal delta when one oversized stored chunk splits into several.
+ * `done` counts the listed rows of every key that finished (failed, filtered
+ * and quarantined rows included) plus that same heal delta, and the page's
+ * delta lands in `total` in the same step, so `done <= total` holds at every
+ * callback and a finished run reads exactly 100%.
+ */
+export class StaleChunkProgress {
+ private floor: number;
+ private loaded = 0;
+ private healExtra = 0;
+ private done = 0;
+
+ constructor(census: number) {
+ this.floor = census;
+ }
+
+ /** A listing batch arrived: the total can never be below the rows listed. */
+ listed(rows: number): void {
+ this.loaded += rows;
+ }
+
+ /** A paced re-entry found `remaining` stale rows behind the cursor; the rescan will list at least those. */
+ reentered(remaining: number): void {
+ this.floor = Math.max(this.floor, this.loaded + remaining);
+ }
+
+ /**
+ * One page key finished. `census` is the rows the listing carried for it;
+ * `handled` is its chunk inventory after healing and the stored-text
+ * filter (0 when nothing was left to embed, or the key was skipped).
+ */
+ pageDone(census: number, handled: number): { done: number; total: number } {
+ if (handled > census) this.healExtra += handled - census;
+ this.done += Math.max(census, handled);
+ return this.snapshot();
+ }
+
+ snapshot(): { done: number; total: number } {
+ return { done: this.done, total: Math.max(this.floor, this.loaded) + this.healExtra };
+ }
+}
diff --git a/src/core/progress.ts b/src/core/progress.ts
index 95596dbf11..77fe4fc89d 100644
--- a/src/core/progress.ts
+++ b/src/core/progress.ts
@@ -40,6 +40,8 @@ export interface ProgressOptions {
export interface ProgressReporter {
start(phase: string, total?: number): void;
tick(n?: number, note?: string): void;
+ /** Replace the phase total once the exact amount of work is known mid-phase (#5968: a heal split or a re-entry grows it). Optional for hand-built reporters. */
+ setTotal?(total: number): void;
heartbeat(note: string): void;
finish(note?: string): void;
child(phase: string, total?: number): ProgressReporter;
@@ -332,6 +334,10 @@ class Reporter implements ReporterInternal {
}
}
+ setTotal(total: number): void {
+ if (this.state) this.state.total = total;
+ }
+
heartbeat(note: string): void {
const s = this.state;
if (!s) return;
diff --git a/test/embed-stale-progress-5968.serial.test.ts b/test/embed-stale-progress-5968.serial.test.ts
new file mode 100644
index 0000000000..59cf112084
--- /dev/null
+++ b/test/embed-stale-progress-5968.serial.test.ts
@@ -0,0 +1,145 @@
+/**
+ * #5968 (wave 15 P2.6, [R28]): `embed --stale` progress is exact chunk
+ * accounting, never an estimate that overshoots 100%.
+ *
+ * Before: the callback reported distinct pages processed against
+ * `ceil(census / batchSize) × keys-in-this-batch`, so a batch with fewer keys
+ * shrank the denominator while the numerator kept climbing (the reporter's
+ * 529/176), and the CLI froze the first batch's total while ticking per page.
+ *
+ * Now the unit is stale chunks: total starts at the census, grows by the heal
+ * delta when one oversized stored chunk splits into several BEFORE the
+ * callback that reports that page, and `done <= total` at every callback.
+ *
+ * Serial: sets GBRAIN_MAX_CHUNK_TOKENS and installs the process-global gateway
+ * transport seam; the CLI arm swaps the process-global CLI options.
+ */
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { runEmbed, runEmbedCore } from '../src/commands/embed.ts';
+import { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { getCliOptions, setCliOptions } from '../src/core/cli-options.ts';
+import { estimateEmbedTokens } from '../src/core/chunkers/token-estimate.ts';
+import { EMBED_PROBE_TEXT } from '../src/core/embed-stale.ts';
+import { resolveMaxChunkTokens } from '../src/core/embedding-input-limit.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+
+const DIMS = 1536;
+const MODEL = 'openai:text-embedding-3-large';
+const CAP = 128;
+const OVERSIZED = 'A stored pre-cap chunk that the heal must split into several pieces before any embed call is made. '.repeat(40);
+const SINGLE_PAGES = 8;
+
+let engine: PGLiteEngine;
+
+async function seedCensus(): Promise<number> {
+ for (let i = 0; i < SINGLE_PAGES; i++) {
+ const slug = `notes/stale-${String(i).padStart(2, '0')}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `${slug} body`, chunk_source: 'compiled_truth', token_count: 4 }]);
+ }
+ await engine.putPage('notes/oversized', { type: 'note', title: 'oversized', compiled_truth: '# oversized' });
+ await installFixtureChunks(engine, 'notes/oversized', [{ chunk_index: 0, chunk_text: OVERSIZED, chunk_source: 'compiled_truth', token_count: 5000 }]);
+ const census = await engine.countStaleChunks({ sourceId: 'default' });
+ expect(census).toBe(SINGLE_PAGES + 1);
+ return census;
+}
+
+beforeAll(async () => {
+ process.env.GBRAIN_MAX_CHUNK_TOKENS = String(CAP);
+ expect(resolveMaxChunkTokens()).toBe(CAP);
+ expect(estimateEmbedTokens(OVERSIZED)).toBeGreaterThan(4 * CAP);
+ configureGateway({ embedding_model: MODEL, embedding_dimensions: DIMS, env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' } });
+ __setEmbedTransportForTests((async (input: { values: string[] }) => ({
+ embeddings: input.values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: input.values.length * 4 },
+ })) as never);
+ engine = new PGLiteEngine();
+ await engine.connect({ embedding_dimensions: DIMS } as never);
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ delete process.env.GBRAIN_MAX_CHUNK_TOKENS;
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => { await resetPgliteState(engine); });
+
+describe('#5968 embed --stale progress counts chunks exactly', () => {
+ test('two-row batches over single-chunk pages plus one oversized chunk: done <= total at every callback, total grows by the heal delta, and the run ends at 100%', async () => {
+ const census = await seedCensus();
+ const events: Array<{ done: number; total: number }> = [];
+ const result = await runEmbedCore(engine, {
+ stale: true, quiet: true, batchSize: 2,
+ onProgress: (done, total) => events.push({ done, total }),
+ });
+ expect(result.failures).toBe(0);
+ expect(result.healed_splits ?? 0).toBeGreaterThanOrEqual(1);
+ const pieces = (await engine.getChunks('notes/oversized')).length;
+ expect(pieces).toBeGreaterThanOrEqual(4);
+ expect(events.length).toBeGreaterThanOrEqual(SINGLE_PAGES + 1);
+ for (const e of events) {
+ expect(e.done).toBeLessThanOrEqual(e.total);
+ expect(e.total).toBeGreaterThanOrEqual(census);
+ }
+ const last = events.at(-1)!;
+ expect(last.total).toBe(census + pieces - 1);
+ expect(last.done).toBe(last.total);
+ expect(await engine.countStaleChunks({ sourceId: 'default' })).toBe(0);
+ });
+
+ test('the CLI reporter ticks by chunk delta and carries the grown total: every emitted tick has done <= total and the last one is complete', async () => {
+ const census = await seedCensus();
+ const before = getCliOptions();
+ const lines: string[] = [];
+ const errSpy = spyOn(process.stderr, 'write').mockImplementation(((chunk: string) => { lines.push(String(chunk)); return true; }) as never);
+ setCliOptions({ ...before, progressJson: true, progressInterval: 0 });
+ try {
+ await runEmbed(engine, ['--stale', '--batch-size', '2']);
+ } finally {
+ setCliOptions(before);
+ errSpy.mockRestore();
+ }
+ const ticks = lines.join('').split('\n').map(line => { try { return JSON.parse(line); } catch { return null; } })
+ .filter((e): e is { event: string; phase: string; done: number; total?: number } => !!e && e.phase === 'embed.pages' && e.event === 'tick');
+ expect(ticks.length).toBeGreaterThan(0);
+ for (const t of ticks) {
+ expect(typeof t.total).toBe('number');
+ expect(t.done).toBeLessThanOrEqual(t.total!);
+ }
+ const pieces = (await engine.getChunks('notes/oversized')).length;
+ const last = ticks.at(-1)!;
+ expect(last.total).toBe(census + pieces - 1);
+ expect(last.done).toBe(last.total!);
+ });
+});
+
+describe('#5968 StaleChunkProgress tally', () => {
+ test('census, listed rows, heal delta, skipped keys and a re-entry never let done pass total', async () => {
+ const { StaleChunkProgress } = await import('../src/core/embed-stale-progress.ts');
+ const p = new StaleChunkProgress(10);
+ p.listed(10);
+ expect(p.pageDone(1, 1)).toEqual({ done: 1, total: 10 });
+ // One oversized stored chunk healed into four: the total grows with the page that reports it.
+ expect(p.pageDone(1, 4)).toEqual({ done: 5, total: 13 });
+ // A key whose rows were filtered out after the read still counts its listed rows.
+ expect(p.pageDone(2, 0)).toEqual({ done: 7, total: 13 });
+ expect(p.pageDone(3, 3)).toEqual({ done: 10, total: 13 });
+ expect(p.pageDone(3, 3)).toEqual({ done: 13, total: 13 });
+ // Rows a writer added behind the cursor within the pass raise the total as they are listed.
+ p.listed(3);
+ expect(p.snapshot()).toEqual({ done: 13, total: 16 });
+ expect(p.pageDone(3, 3)).toEqual({ done: 16, total: 16 });
+ // A paced re-entry announces what is still stale; listing it again does not double count.
+ p.reentered(2);
+ expect(p.snapshot()).toEqual({ done: 16, total: 18 });
+ p.listed(2);
+ expect(p.pageDone(2, 2)).toEqual({ done: 18, total: 18 });
+ // More rows than the re-entry announced: the total follows the listing.
+ p.listed(1);
+ expect(p.pageDone(1, 1)).toEqual({ done: 19, total: 19 });
+ });
+});