Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): a time-budget stop in embed --stale is loud, and doctor reports the backlog

garrytanf3e1197385df
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 4329af93bc..4e6d3d1c1f 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -13,7 +13,7 @@ src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 basel
src/commands/doctor/checks/extraction-sync.ts checkSyncFreshness 333 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/doctor/report-remote.ts doctorReportRemote 416 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/dream-retriage.ts runDreamRetriage 524 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/commands/embed.ts embedAllStale 564 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary; +4 wave 8 lane D1 #5527: subtract current-model chunks from the mixed-space warning
+src/commands/embed.ts embedAllStale 566 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary; +4 wave 8 lane D1 #5527: subtract current-model chunks from the mixed-space warning; +2 Foundations 1 F4d: a time-budget stop with stale chunks left records reason, remaining count and resume command (src/core/embed-budget-stop.ts)
src/commands/embed.ts runEmbedCore 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 wave 8 lane D1 #5885: stale-drain takes pass call and its watchdog progress counter
src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/commands/extract-conversation-facts.ts processPage 307 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d83f5a962..bff432f8a3 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -6,7 +6,7 @@
src/cli.ts 3209 ratchet +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
src/commands/autopilot.ts 1639 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)
src/commands/doctor.ts 653 ratchet 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 2208 ratchet 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)
+src/commands/embed.ts 2217 ratchet 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)
src/commands/extract-conversation-facts.ts 2182 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)
src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit)
src/commands/jobs.ts 658 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)
diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.ts
index 46d4e14b36..6d9f2a64fe 100644
--- a/src/cli/commands/embed.ts
+++ b/src/cli/commands/embed.ts
@@ -5,6 +5,7 @@
* src/cli/command-table.ts.
*/
import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
+import { BUDGET_STOP_EXIT_CODE } from '../../core/exit-codes.ts';
import type { BrainEngine } from '../../core/engine.ts';
import type { CliDispatchContext } from '../command-table.ts';
@@ -18,5 +19,7 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC
const embedResult = await runEmbed(engine, args, SELECTED_CONFIG_BY_ENGINE.get(engine) ?? null);
if (embedResult && embedResult.failures > 0) {
setCliExitVerdict(1);
+ } else if (embedResult && 'reason' in embedResult && embedResult.reason === 'time_budget') {
+ setCliExitVerdict(BUDGET_STOP_EXIT_CODE);
}
}
diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.ts
index 557496caad..8c62f44eaf 100644
--- a/src/commands/doctor/checks/schema-health.ts
+++ b/src/commands/doctor/checks/schema-health.ts
@@ -8,6 +8,7 @@
*/
import * as db from '../../../core/db.ts';
+import { loadConfig } from '../../../core/config.ts';
import { LATEST_VERSION } from '../../../core/migrate.ts';
import { schemaVersionHealth } from '../../../core/schema-version-health.ts';
import { pgvectorCheck, pagesUpsertArbiterCheck, linkSourceCheckConstraintCheck } from './core-health.ts';
@@ -326,6 +327,12 @@ async function runEmbeddings(ctx: DoctorContext): Promise<Check[]> {
// 8. Embedding health
progress.heartbeat('embeddings');
try {
+ // A keyless brain has no embedding backlog to drain: recommending a paid
+ // catch-up there would send the agent into a refusal.
+ if (loadConfig()?.embedding_disabled === true || await engine.getConfig('embedding_disabled') === 'true') {
+ checks.push({ name: 'embeddings', status: 'ok', message: 'Not applicable: embeddings are disabled on this brain (keyword search keeps working).' });
+ return checks;
+ }
const health = await engine.getHealth();
const pct = (health.embed_coverage * 100).toFixed(0);
// Coverage + missing now share one source (the stored vector over
@@ -342,12 +349,23 @@ async function runEmbeddings(ctx: DoctorContext): Promise<Check[]> {
} catch {
// Config read is best-effort; the coverage numbers stand alone.
}
+ // The backlog's fix is the catch-up drain: a plain `embed --stale` stops
+ // at its 30-minute budget, which on a large brain leaves most of the
+ // backlog behind (52k documents: 51,910 chunks after one run).
+ const backlog = health.missing_embeddings;
+ const fix = 'gbrain embed --stale --catch-up';
+ const backlogDetails = { code: 'embedding_backlog', backlog, fix, requires_user_approval: 'paid embedding calls',
+ docs: 'docs/operations/backfill-pacing.md#large-brain-deadlines' };
+ const fixText = `Fix: ${fix} (runs until the backlog is empty; a plain gbrain embed --stale stops after its 30-minute budget). ` +
+ 'It makes paid embedding calls: confirm with the user unless embedding spend is already approved.';
if (health.embed_coverage >= 0.9) {
- checks.push({ name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${health.missing_embeddings} missing${carveOut}` });
+ checks.push(backlog > 0
+ ? { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails }
+ : { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}` });
} else if (health.embed_coverage > 0) {
- checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${health.missing_embeddings} missing. Run: gbrain embed --stale${carveOut}` });
+ checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails });
} else {
- checks.push({ name: 'embeddings', status: 'warn', message: `No embeddings yet. Run: gbrain embed --stale${carveOut}` });
+ checks.push({ name: 'embeddings', status: 'warn', message: `No embeddings yet${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails });
}
} catch {
checks.push({ name: 'embeddings', status: 'warn', message: 'Could not check embedding health' });
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index a032cb00d5..39ed93991c 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -24,6 +24,7 @@ import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';
import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } from '../core/embedding-invalidation.ts';
import { loadConfig, type GBrainConfig } from '../core/config.ts';
import { slog, serr } from '../core/console-prefix.ts';
+import { embedBudgetStopVerdict, noteEmbedBudgetStop } from '../core/embed-budget-stop.ts';
import { filterOutEmbedSkipped } from '../core/embed-skip.ts';
import { runSlidingPool } from '../core/worker-pool.ts';
import { isAborted, anySignal, AbortError } from '../core/abort-check.ts';
@@ -349,7 +350,10 @@ export interface EmbedResult {
* `failures`/`failure_samples` also carry a stall entry so existing
* failures>0 consumers surface it unchanged.
*/
- reason?: 'stall_timeout';
+ reason?: 'stall_timeout' | 'time_budget';
+ /** With `reason: 'time_budget'` (src/core/embed-budget-stop.ts): stale chunks left and the command that finishes them. */
+ remaining_stale?: number;
+ resume_command?: string;
/** #5885: the takes pass of a `stale` drain, when it ran. Its failures are also counted in `failures`. */
takes?: EmbedTakesResult;
}
@@ -984,6 +988,9 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
serr('[embed] exiting non-zero: stall watchdog aborted the drain (reason: stall_timeout); partial progress banked — re-run to resume.');
process.exit(1);
}
+ // A budget stop with work left is partial: verdict on stdout, and
+ // src/cli/commands/embed.ts exits with BUDGET_STOP_EXIT_CODE.
+ if (result.reason === 'time_budget') slog(embedBudgetStopVerdict(result));
return result;
} catch (e) {
if (progressStarted) progress.finish();
@@ -1603,6 +1610,7 @@ async function embedAllStale(
const sourceOpt = sourceId ? { sourceId } : undefined;
if (isAborted(externalSignal)) return;
const includeNullSig = !!staleOpts?.includeNullSignature;
+ const noteBudgetStop = () => noteEmbedBudgetStop(engine, result, { sourceId, signature, includeNullSignature: includeNullSig, skip: dryRun || BUDGET_MS === null || isAborted(externalSignal) });
let reportedArchived = 0;
const reportArchived = async () => {
if (dryRun) return;
@@ -1616,17 +1624,17 @@ async function embedAllStale(
const readinessOptions = { sourceId, existingChunksOnly: true, activeSourcesOnly: true, stale: { signature, includeNullSignature: includeNullSig }, signal: externalSignal,
deadline: BUDGET_MS === null ? undefined : overallStartedAt + BUDGET_MS };
let readiness = await prepareEmbeddingProjections(engine, readinessOptions);
- if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return;
+ if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return await noteBudgetStop();
if (readiness.blocked && !dryRun) {
const probeOk = await probeEmbedder((texts, fnOpts) => embedBatchWithBackoff(texts, { abortSignal: fnOpts.abortSignal }), signature ?? undefined, externalSignal);
- if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return;
+ if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return await noteBudgetStop();
if (!probeOk) {
result.failures += readiness.blocked;
result.failure_samples.push('Projection recovery requires a working embedding provider; existing projections were preserved.');
return;
}
readiness = await prepareEmbeddingProjections(engine, { ...readinessOptions, repair: true, assertOwned: staleOpts?.assertOwned });
- if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return;
+ if (isAborted(externalSignal) || Date.now() >= (readinessOptions.deadline ?? Infinity)) return await noteBudgetStop();
}
if (readiness.blocked && !dryRun) {
result.failures += readiness.blocked;
@@ -2112,6 +2120,7 @@ async function embedAllStale(
}
}
+ if (budgetSignal.aborted) await noteBudgetStop();
if (!staleOpts?.quiet) slog(`Embedded ${result.embedded} chunks across ${processedPageKeys.size} pages`);
// #1946 (OV2a): a catch-up pass that completed without being aborted but left
diff --git a/src/core/embed-budget-stop.ts b/src/core/embed-budget-stop.ts
new file mode 100644
index 0000000000..d227744138
--- /dev/null
+++ b/src/core/embed-budget-stop.ts
@@ -0,0 +1,46 @@
+/**
+ * The loud stop for `gbrain embed --stale` at its wall-clock budget
+ * (`GBRAIN_EMBED_TIME_BUDGET_MS`, default 30 min). A budget stop that leaves
+ * stale chunks behind is a partial run: the result records the reason, the
+ * remaining count and the exact command that finishes the backlog, and the
+ * CLI prints that verdict on stdout and exits with BUDGET_STOP_EXIT_CODE
+ * instead of reading as a clean finish.
+ */
+import type { BrainEngine } from './engine.ts';
+
+export interface EmbedBudgetStopFields {
+ embedded: number;
+ reason?: 'stall_timeout' | 'time_budget';
+ remaining_stale?: number;
+ resume_command?: string;
+}
+
+/**
+ * Record a budget stop on `result` when stale chunks remain; a drained run
+ * records nothing. `skip` covers dry runs, catch-up (no budget) and caller
+ * aborts, which are not budget stops.
+ */
+export async function noteEmbedBudgetStop(
+ engine: BrainEngine,
+ result: EmbedBudgetStopFields,
+ opts: { sourceId?: string; signature?: string; includeNullSignature: boolean; skip: boolean },
+): Promise<void> {
+ if (opts.skip) return;
+ const sourceOpt = opts.sourceId ? { sourceId: opts.sourceId } : undefined;
+ const remaining = await engine.countStaleChunks(opts.signature
+ ? { signature: opts.signature, ...sourceOpt, ...(opts.includeNullSignature && { includeNullSignature: true }) }
+ : sourceOpt);
+ if (remaining === 0) return;
+ result.reason = 'time_budget';
+ result.remaining_stale = remaining;
+ result.resume_command = ['gbrain embed --stale --catch-up', opts.sourceId && `--source ${opts.sourceId}`,
+ opts.includeNullSignature && '--include-null-signature'].filter(Boolean).join(' ');
+}
+
+/** The stdout verdict line for a budget stop. */
+export function embedBudgetStopVerdict(result: EmbedBudgetStopFields): string {
+ return `[embed] stopped (reason: time_budget): the --stale run reached its time budget (GBRAIN_EMBED_TIME_BUDGET_MS, default 30 min) ` +
+ `with ${result.remaining_stale} stale chunk(s) left after embedding ${result.embedded} this run. ` +
+ `Finish without a time cap: ${result.resume_command} (paid embedding calls for the remaining chunks), ` +
+ 'or rerun gbrain embed --stale for another budget window; either resumes where this run stopped.';
+}
diff --git a/src/core/embed-stall.ts b/src/core/embed-stall.ts
index 31f8244dc4..171bc8028a 100644
--- a/src/core/embed-stall.ts
+++ b/src/core/embed-stall.ts
@@ -179,7 +179,7 @@ export function createEmbedStallWatchdog(opts: {
* the CLI wrapper exits the process.
*/
export function assertEmbedNotStalled(result: {
- reason?: 'stall_timeout';
+ reason?: string;
embedded: number;
}): void {
if (result.reason !== 'stall_timeout') return;
diff --git a/src/core/exit-codes.ts b/src/core/exit-codes.ts
index a5b9637a6c..5b87838341 100644
--- a/src/core/exit-codes.ts
+++ b/src/core/exit-codes.ts
@@ -13,3 +13,10 @@ export const MIGRATIONS_RUNNING_EXIT_CODE = 75;
* `--accept-pending` (or GBRAIN_ACCEPT_PENDING=1) to map pending to 0.
*/
export const PENDING_WRITE_EXIT_CODE = 10;
+
+/**
+ * A bounded run stopped at its time budget with work left (`gbrain embed
+ * --stale`). Partial and resumable: stdout names the remaining count and the
+ * exact resume command. Distinct from 1, which means something failed.
+ */
+export const BUDGET_STOP_EXIT_CODE = 3;
diff --git a/test/doctor-embedding-backlog.test.ts b/test/doctor-embedding-backlog.test.ts
new file mode 100644
index 0000000000..bf6d352a47
--- /dev/null
+++ b/test/doctor-embedding-backlog.test.ts
@@ -0,0 +1,67 @@
+/**
+ * embeddings doctor check reports the embedding backlog (Foundations 1, F4d).
+ *
+ * Protects: when chunks lack embeddings, the `embeddings` check names the
+ * backlog count and the command that finishes it (`gbrain embed --stale
+ * --catch-up`), says it makes paid calls, and carries the same facts in
+ * `details` for agents. A clean brain keeps the golden-pinned message.
+ * Fails when: the check goes back to recommending a plain `embed --stale`,
+ * which stops after its 30-minute budget and on a 52k-document brain left
+ * 51,910 chunks behind without saying so.
+ * Why new: no test exercised the embeddings check's messages; the doctor
+ * goldens only pin the fully embedded case.
+ * A keyless brain reports "not applicable" instead of a paid fix.
+ * Seam: none (a stub engine answering getHealth and getConfig).
+ */
+import { describe, expect, test } from 'bun:test';
+import { embeddingsEntry } from '../src/commands/doctor/checks/schema-health.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+async function runCheck(ctx: DoctorContext): Promise<Check[]> {
+ return await embeddingsEntry.run(ctx) as Check[];
+}
+
+function ctxFor(coverage: number, missing: number, config: Record<string, string> = {}): DoctorContext {
+ const engine = {
+ getHealth: async () => ({ embed_coverage: coverage, missing_embeddings: missing }),
+ getConfig: async (key: string) => config[key] ?? null,
+ };
+ return { engine, progress: { heartbeat() {} } } as unknown as DoctorContext;
+}
+
+describe('embeddings doctor check: backlog', () => {
+ test('a large backlog warns with the count and the catch-up command', async () => {
+ const [check] = await runCheck(ctxFor(0.002, 51_910));
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('Backlog: 51910 chunk(s) without embeddings');
+ expect(check.message).toContain('Fix: gbrain embed --stale --catch-up');
+ expect(check.message).toContain('paid embedding calls');
+ expect(check.details).toMatchObject({ code: 'embedding_backlog', backlog: 51_910, fix: 'gbrain embed --stale --catch-up' });
+ });
+
+ test('a brain with no embeddings yet names the backlog too', async () => {
+ const [check] = await runCheck(ctxFor(0, 1200));
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('Backlog: 1200 chunk(s)');
+ });
+
+ test('a mostly embedded brain stays ok but still reports its backlog', async () => {
+ const [check] = await runCheck(ctxFor(0.95, 2600));
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('Backlog: 2600 chunk(s)');
+ expect(check.details).toMatchObject({ backlog: 2600 });
+ });
+
+ test('a keyless brain is not applicable, never told to make paid calls', async () => {
+ const [check] = await runCheck(ctxFor(0, 200, { embedding_disabled: 'true' }));
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('Not applicable: embeddings are disabled');
+ expect(check.message).not.toContain('catch-up');
+ });
+
+ test('a fully embedded brain keeps its message and carries no backlog', async () => {
+ const [check] = await runCheck(ctxFor(1, 0));
+ expect(check).toEqual({ name: 'embeddings', status: 'ok', message: '100% coverage, 0 missing' });
+ });
+});
diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.ts
index a620cd9ea4..5dd1205333 100644
--- a/test/embed.serial.test.ts
+++ b/test/embed.serial.test.ts
@@ -1029,6 +1029,73 @@ describe('embedAllStale wall-clock budget end-to-end (D3 + D3a)', () => {
});
});
+// Large-brain ceiling (F4d): a 30-minute budget stop on a 52k-document brain
+// left 51,910 chunks unembedded with exit 0 and no error. A budget stop with
+// work left now reports reason, remaining count and the exact resume command,
+// and the CLI exits with BUDGET_STOP_EXIT_CODE.
+describe('embed --stale time-budget stop is loud (large-brain ceiling)', () => {
+ const rows = Array.from({ length: 10 }, (_, i) => ({
+ slug: `budget-${i}`, chunk_index: 0, chunk_text: `t${i}`, chunk_source: 'compiled_truth' as const,
+ model: null, token_count: 1, source_id: 'default', page_id: i + 1,
+ }));
+ const budgetEngine = () => mockEngine({
+ countStaleChunks: async () => rows.length,
+ listStaleChunks: async (opts: { afterPageId?: number } = {}) => rows.filter(r => r.page_id > (opts.afterPageId ?? 0)).slice(0, 1),
+ getChunks: async (slug: string) => rows.filter(r => r.slug === slug)
+ .map(r => ({ chunk_index: 0, chunk_text: r.chunk_text, chunk_source: 'compiled_truth', embedded_at: null, token_count: 1 })),
+ upsertChunks: async () => {},
+ });
+
+ test('the result names the stop, the remaining stale chunks and the resume command', async () => {
+ process.env.GBRAIN_EMBED_TIME_BUDGET_MS = '100';
+ process.env.GBRAIN_EMBED_CONCURRENCY = '1';
+ embedBatchBehavior = async (texts) => {
+ await new Promise(r => setTimeout(r, 80));
+ return texts.map(() => new Float32Array(1536));
+ };
+ const result = await runEmbedCore(budgetEngine(), { stale: true, sourceId: 'default', batchSize: 1 });
+ expect(result.embedded).toBeGreaterThan(0);
+ expect(result.pages_processed).toBeLessThan(10);
+ expect(result.reason).toBe('time_budget');
+ expect(result.remaining_stale).toBe(10);
+ expect(result.resume_command).toBe('gbrain embed --stale --catch-up --source default');
+ });
+
+ test('the CLI prints the verdict on stdout and exits with the budget-stop status', async () => {
+ const { BUDGET_STOP_EXIT_CODE } = await import('../src/core/exit-codes.ts');
+ const { currentExitCode, _resetCliExitVerdictForTests } = await import('../src/core/cli-force-exit.ts');
+ const { run } = await import('../src/cli/commands/embed.ts');
+ process.env.GBRAIN_EMBED_TIME_BUDGET_MS = '100';
+ process.env.GBRAIN_EMBED_CONCURRENCY = '1';
+ embedBatchBehavior = async (texts) => {
+ await new Promise(r => setTimeout(r, 80));
+ return texts.map(() => new Float32Array(1536));
+ };
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ _resetCliExitVerdictForTests();
+ try {
+ await run(budgetEngine(), ['--stale', '--batch-size', '1'], { SELECTED_CONFIG_BY_ENGINE: new Map() } as never);
+ expect(currentExitCode()).toBe(BUDGET_STOP_EXIT_CODE);
+ } finally {
+ console.log = log;
+ _resetCliExitVerdictForTests();
+ process.exitCode = 0;
+ }
+ const verdict = lines.find(l => l.includes('reason: time_budget'));
+ expect(verdict).toContain('with 10 stale chunk(s) left');
+ expect(verdict).toContain('Finish without a time cap: gbrain embed --stale --catch-up');
+ });
+
+ test('a run that drains everything before the budget reports no stop', async () => {
+ process.env.GBRAIN_EMBED_TIME_BUDGET_MS = '60000';
+ const result = await runEmbedCore(mockEngine({ countStaleChunks: async () => 0 }), { stale: true });
+ expect(result.reason).toBeUndefined();
+ expect(result.remaining_stale).toBeUndefined();
+ });
+});
+
describe('embedAllStale --source threading (D7)', () => {
test('countStaleChunks receives the sourceId opt', async () => {
const { runEmbedCore } = await import('../src/commands/embed.ts');