Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(reindex): an inline reindex --markdown stops at its approved cost cap (W12 P1)

time-attackf8dbf8210a8e
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 451eede301..591acb3388 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `take-supersession` (#5886 relinks takes supersession chains from journal, stored-pointer or forced fence-structure evidence; ambiguous pages are reported with the manual edit, never rewritten; `src/core/repair/take-supersession.ts`), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `gbrain repair fences [--only <path>]... [--skip <path>]... [--slug <slug>]... [--diff] [--no-llm] [--max-usd <n>] [--apply [--expect <hash>]]` repairs malformed facts and takes fences (#6188, `src/core/repair/fences.ts`). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs; flags a kind does not take name the kinds that do (`--only`/`--skip`/`--diff`: frontmatter, fences; `--slug`: fences; `--yes`: frontmatter); `--expect` is accepted for explicit-only and preview-bound kinds, `--include-ambiguous` for explicit-only kinds; `--max-usd <n>` and `--no-llm` only for `spends: 'llm'` kinds (a non-negative USD amount that only lowers the kind's cap), and on any other kind `--max-usd` names the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n> --expect <plan_hash>` (hash from `doctor --remediation-plan --json`), as `--max-cost` always does. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. An apply with a report hook prints `repaired N; still waiting: <reason>=<count>` (never a repair count it did not make) and a partial scan; a stop prints its `fix` command and the consent it asks for. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost (plus, for a `spends: 'llm'` kind, the paid-model estimate or spend and what is left under today's cap) and capacity, and the apply command; `--json` has the same fields. The dry run lists the kinds that may queue paid embeddings and, when a result carries `cost.llm_usd`, `Kinds that may call a paid model` with the summed estimate and the cap left. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.
-- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]`. W4.5: re-embedding is paid, so `runReindex(engine, args, { authorized?, interactive? })` calls `requireReindexConsent` (`src/core/reindex-consent.ts`) after the dry-run return and before the managed dispatch for every caller unless `--no-embed` or `authorized` (the upgrade path's TTY yes, the job handler's stored spend record); `src/cli/commands/reindex.ts` renders the exit-3 consent refusal and `cost_cap_exceeded`. `countPending` is exported for `jobs submit reindex` and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).
+- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--yes] [--max-usd USD] [--repo PATH]`. W4.5: re-embedding is paid, so `runReindex(engine, args, { authorized?, interactive? })` calls `requireReindexConsent` (`src/core/reindex-consent.ts`) after the dry-run return and before the managed dispatch for every caller unless `--no-embed` or `authorized` (the upgrade path's TTY yes, the job handler's stored spend record); `src/cli/commands/reindex.ts` renders the exit-3 consent refusal and `cost_cap_exceeded`. The approved finite cap runs the inline pass (and the managed dispatch) under a `BudgetTracker` via `withBudgetTracker`; once it is exhausted (an import swallows the refused embedding) the loop stops at the next page and `reportBudgetStop` exits 1 with `budget_exhausted` in `--json`. `countPending` is exported for `jobs submit reindex` and the mode-switch prompt. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`. #5377: on a managed brain (`managedPersistenceEnabled`) the `--markdown` sweep delegates to the projection repairs through `runRepair` (`safe-chunks`, then `contextual-mode` unless `--no-embed`), so it never takes the legacy writer and changes no page revision, journal request or canonical file; `--type` is refused there with the repair commands, and pages the repairs cannot rebuild are reported as `unsupported_pages`. The doctor, upgrade and post-upgrade hints that name `gbrain reindex --markdown` therefore work on both brain modes (C-NEW-5).
- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.
diff --git a/src/commands/reindex.ts b/src/commands/reindex.ts
index 1235b2cfd2..6c610dfe2e 100644
--- a/src/commands/reindex.ts
+++ b/src/commands/reindex.ts
@@ -36,6 +36,8 @@ import { resolveWorkersWithClamp } from '../core/sync-concurrency.ts';
import { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';
import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
import { loadConfig } from '../core/config.ts';
+import { BudgetExhausted, BudgetTracker } from '../core/budget/budget-tracker.ts';
+import { withBudgetTracker } from '../core/ai/gateway.ts';
interface ReindexOpts {
/** Cap total pages reindexed. Useful for triage runs on huge brains. */
@@ -383,12 +385,28 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
}
// W4.5: re-embedding is paid work; ask before it starts (throws the exit-3 consent refusal or cost_cap_exceeded).
+ // W12 P1: the approved cap is enforced while the run spends (embedding and synopsis calls), not only checked up front.
+ let cap: BudgetTracker | null = null;
+ let capHit: BudgetExhausted | null = null;
if (!opts.noEmbed && !runOpts.authorized) {
const { requireReindexConsent } = await import('../core/reindex-consent.ts');
- await requireReindexConsent(engine, { args, type, target, ...(runOpts.interactive === false ? { interactive: false } : {}) });
+ const gate = await requireReindexConsent(engine, { args, type, target, ...(runOpts.interactive === false ? { interactive: false } : {}) });
+ const capUsd = gate?.auth.cap_usd;
+ if (typeof capUsd === 'number' && Number.isFinite(capUsd) && capUsd > 0) {
+ cap = new BudgetTracker({ maxCostUsd: capUsd, label: 'reindex', capSource: gate!.auth.cap_source ?? undefined });
+ // An import swallows a refused embedding (its chunks wait for `embed --stale`), so the run stops at the next page.
+ const tracker = cap;
+ tracker.onExhausted(() => { capHit = new BudgetExhausted(`reindex reached its $${capUsd.toFixed(2)} cost cap`, { reason: 'cost', spent: tracker.totalSpent, cap: capUsd }); });
+ }
}
+ const metered = <T>(fn: () => Promise<T>): Promise<T> => (cap ? withBudgetTracker(cap, fn) : fn());
- if (await managedPersistenceEnabled(engine)) return reindexManaged(engine, opts, type, pending);
+ if (await managedPersistenceEnabled(engine)) {
+ try { return await metered(() => reindexManaged(engine, opts, type, pending)); } catch (e) {
+ if (!(e instanceof BudgetExhausted)) throw e;
+ return reportBudgetStop(engine, e, { pending, type, json: !!opts.json, reindexed: 0, skipped: 0, failed: 0 });
+ }
+ }
const reporter = createProgress(cliOptsToProgressOptions(getCliOptions()));
reporter.start('reindex.markdown', target);
@@ -403,7 +421,8 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
// exactly the auto threshold (100), so batch length never enabled it.
const { workers } = resolveWorkersWithClamp(engine, opts.workers, 'reindex', target);
- while (reindexed + skipped + failed < target) {
+ let stopped: BudgetExhausted | null = null;
+ try { await metered(async () => { while (reindexed + skipped + failed < target) {
const remaining = target - (reindexed + skipped + failed);
const batchSize = Math.min(BATCH, remaining);
const batch = await readBatch(engine, batchSize, type, !!opts.noEmbed, afterId);
@@ -420,6 +439,7 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
workers,
failureLabel: (row) => row.slug,
onItem: async (row) => {
+ if (capHit) throw capHit;
reporter.tick();
try {
if (row.source_path && repoPath) {
@@ -479,15 +499,20 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
skipped++;
}
} catch (err) {
+ if (err instanceof BudgetExhausted) throw err;
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`[reindex] ${row.slug}: ${msg}\n`);
failed++;
}
},
});
+ } }); } catch (e) {
+ if (!(e instanceof BudgetExhausted)) throw e;
+ stopped = e;
}
reporter.finish();
+ if (stopped) return reportBudgetStop(engine, stopped, { pending, type, json: !!opts.json, reindexed, skipped, failed, workers });
if (reindexed > 0) await refreshProjectionStatistics(engine);
const pendingAfter = await countPending(engine, type, !!opts.noEmbed);
@@ -520,6 +545,25 @@ export async function runReindex(engine: BrainEngine, args: string[], runOpts: R
return result;
}
+/**
+ * W12 P1: the run stopped at its approved cost cap. Pages re-chunked so far are
+ * kept (a rerun continues with the rest); exit 1 with the spend and the rerun.
+ */
+async function reportBudgetStop(engine: BrainEngine, e: BudgetExhausted, r: { pending: number; type: string | null; json: boolean; reindexed: number; skipped: number; failed: number; workers?: number }): Promise<ReindexResult> {
+ if (r.reindexed > 0) await refreshProjectionStatistics(engine);
+ const pendingAfter = await countPending(engine, r.type, false);
+ setCliExitVerdict(1);
+ const message = `stopped at the $${e.cap.toFixed(2)} cost cap after spending $${e.spent.toFixed(4)} (${e.message}). ${pendingAfter} page(s) still pending, and pages re-chunked after the cap wait for gbrain embed --stale; ask the user before running again with a higher --max-usd.`;
+ if (r.json) {
+ process.stdout.write(JSON.stringify({ pending: r.pending, pending_after: pendingAfter, reindexed: r.reindexed, skipped: r.skipped, failed: r.failed,
+ chunker_version: MARKDOWN_CHUNKER_VERSION, type: r.type, budget_exhausted: { cap_usd: e.cap, spent_usd: e.spent, reason: e.reason } }) + '\n');
+ } else {
+ process.stderr.write(`[reindex] ${message}\n`);
+ }
+ return { pending: r.pending, pendingAfter, reindexed: r.reindexed, skipped: r.skipped, failed: r.failed, dryRun: false, chunkerVersion: MARKDOWN_CHUNKER_VERSION, type: r.type,
+ ...(r.workers !== undefined ? { workers: r.workers } : {}) };
+}
+
/**
* #5377: a managed brain cannot re-import through the legacy writer, so the
* sweep delegates to the projection repairs: `safe-chunks` re-seals every page
diff --git a/test/reindex-consent.test.ts b/test/reindex-consent.test.ts
index 4d7ec9461d..7bf1cb8191 100644
--- a/test/reindex-consent.test.ts
+++ b/test/reindex-consent.test.ts
@@ -115,6 +115,22 @@ describe('W4.5: reindex --markdown asks before re-embedding', () => {
});
});
+describe('W12 P1: the inline run enforces the approved cap while it spends', () => {
+ test('--max-usd stops the run once measured spend passes the cap; the rest stays pending', async () => {
+ // Each embedding call reports 10M tokens (about $0.20 on text-embedding-3-small); the up-front estimate is tiny.
+ __setEmbedTransportForTests((async (args: { values: string[] }) => {
+ embedCalls++;
+ return { embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.01)), usage: { tokens: 10_000_000 } };
+ }) as never);
+ const { stdout } = await quiet(() => runReindexCli(engine, ['--markdown', '--max-usd', '0.05', '--json']));
+ expect(currentExitCode()).toBe(1);
+ const doc = JSON.parse(stdout.trim().split('\n').at(-1)!);
+ expect(doc.budget_exhausted).toMatchObject({ cap_usd: 0.05 });
+ expect(embedCalls).toBeLessThan(3);
+ expect(await lagging()).toBeGreaterThan(0);
+ });
+});
+
describe('W4.5: the reindex job handler', () => {
const ctx = (spend?: boolean): MinionJobContext => ({
id: 41, name: 'reindex', data: { markdown: true }, attempts_made: 0, signal: new AbortController().signal,