Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(reindex): reindex --markdown asks before re-embedding, in the CLI and the job handler (W4.5)

time-attack9ab0ad527ec1
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 6813eb0f53..451eede301 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] [--repo PATH]`. 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`. `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/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 471b2b5e69..d25aeb599a 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -61,5 +61,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/preferences.ts` — preferences.json + the migration ledger (`migrations/completed.jsonl` append/read helpers; `appendCompletedMigration`, `loadCompletedMigrations`). Path resolution delegates to `config.ts:gbrainPath()`, so GBRAIN_HOME follows the ONE canonical convention: it is a PARENT dir and `.gbrain` is appended (`GBRAIN_HOME=/tmp/x` → `/tmp/x/.gbrain/migrations/...`). `copyForwardLegacyFile` migrates a legacy layout that placed these files directly under `$GBRAIN_HOME` once per file on first touch: atomic (temp + linkSync, EEXIST = concurrent winner), JSON-validated for prefs, chmod 0600, copy-not-move for binary rollback, once-per-process warning; a valid-but-uncopyable legacy file (read-only home) is READ IN PLACE so a transient failure can't drop a `minion_mode` opt-out or migration history. One-shot by design — mixed-version writers diverging post-snapshot is an accepted, documented limitation.
+- `src/core/reindex-consent.ts` — W4.5 paid-consent gate for `reindex --markdown`: `estimateReindexSpend` (pages after `--limit`, embedding estimate from the pending pages' text under the `countPending` predicate; null when the model has no price) and `requireReindexConsent` (null when `embedWouldSpend` is false; else `requireConsent` with effect `paid`, page count and estimate in `user_message`/`est_usd`, `--yes` command and `--dry-run` preview; `interactive: false` never prompts; a user cap below the estimate throws `cost_cap_exceeded`). Called by `runReindex` (CLI, `upgrade`, the `reindex` job handler) and `jobs submit reindex`, which stores the authorization on the job (`jobSpendAuthorization`); the search-mode switch prompt stores its TTY yes the same way. The handler (`minions/handlers/reindex.ts`) runs authorized only with `job.spend.record` and turns the consent refusal into a terminal `confirmation_required` error. Tests: `test/reindex-consent.test.ts`.
+
- `src/core/remediation-checkpoint.ts` — `doctor --remediate` checkpoint at `~/.gbrain/remediation/<plan_hash>.json`. `plan_hash = sha256(JSON.stringify(sorted recommendation ids)).slice(0,16)`. Schema-versioned, atomic `.tmp + rename`. `gbrain doctor --remediate --resume <plan_hash>` (no arg picks newest matching) loads it and skips completed steps. Mismatched plan_hash refuses with a paste-ready message. Cleared on clean completion. Optional resume-contract fields written by the doctor CLI: `brain_id` (a resume against another brain refuses), `max_usd` (reused by `--resume` without `--max-usd`), `include_repairs`, cumulative `spent_usd` and the original step `manifest` (`job_ids`, `repair_kinds`); a checkpoint without them keeps the legacy exact-plan-hash resume. Pinned by 13 unit cases plus `test/recovery-layer.test.ts`.
- `src/core/remediation/` — the doctor remediation library (`computeRemediationPlan`, `runRemediation`, shared by doctor, onboard and MCP `run_onboard`). `repairs.ts`: `planRepairSteps` previews every registered repair kind brain-wide and returns PROTECTED steps (`requires_user_agreement`, exact `command`, `paid`, `est_usd_cost`), independent of the score target; a `spends: 'llm'` kind's step is `paid` and adds `llm_usd` (its paid-model estimate) to `est_usd_cost`, which is null when either part is unpriced; `runRepairSteps` applies them in-process for a trusted local caller only, refusing a paid step whose estimate exceeds the remaining cap before it starts and continuing with free steps; `effect` kinds reserve their embedding estimate against the cap up front (the consumer embeds outside the tracker), and an `inline` step is marked `budget_exhausted` when the tracker fired even if a callee swallowed the throw. A `spends: 'llm'` step never reserves its model estimate: it runs under the caller's tracker (never a nested `stepBudget` tracker) with what is left of the cap as `maxLlmUsd`, then `charge`s the part of its actual `cost.llm_usd` that `spentUsd()` did not already rise by during the step, so model spend counts once; a step its allowance stopped is `budget_exhausted`. `planRepairSteps`, `runRepairSteps` and `runRemediation`'s `repairs.registry` take stub specs for tests. The plan hash includes the brain id so brains on one host never share a checkpoint file. `run.ts`: `opts.repairs` (doctor CLI only) plans the repair steps and runs them when `include` is set, even when the target is unreachable (job steps are skipped then); a remote `include` refuses `permission_denied`. The cap is cumulative (`spent_usd` from the checkpoint plus this run's tracker, reservations and settled model spend); a refused paid step ends the run budget-exhausted and saves the checkpoint. Callers that omit `repairs` keep the job-only behavior. Plan and run preview through `planRepairStepsReport` (the strict `planRepairSteps` still propagates the first error), so a kind whose preview throws is reported as `repair_preview_failures` (code `timeout` for SQLSTATE 57014, naming `GBRAIN_STATEMENT_TIMEOUT`, else `preview_failed`; message redacted, then capped at 300 characters; `fix` is the rendered read-only `gbrain repair <kind>` preview) and the other kinds still plan and run. Each executed job step whose job moves a tracked metric (`impactMetricForJob`: embed / embed-catch-up: `countStaleChunks`; extract: `findOrphanPages` under the orphan-reporting policy, equal to get_health's orphan_pages without running `getHealth()`; extract-ner / extract-timeline-from-meetings: the onboard coverage checks' `visibleEntityCoverageSql`; extract-takes-from-pages: takes) records it before submit and once the job is terminal as one `migration_impact_log` row (`src/core/onboard/impact-capture.ts` `openStepImpact` / `closeStepImpact`, best-effort: a failed capture records null, a failed write only logs, and neither changes the step result), which `gbrain onboard --history` reads; dry runs, steps that throw before their job is terminal and unmapped jobs record nothing.
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index 6b7855fc9f..be75ddddf8 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -146,6 +146,7 @@ line naming the cap, its source and how to remove it, e.g.
| Backfill per-job budget | `embed.backfill_max_usd` | `10` | caps the job's tracker | `off` (`0`/garbage → default, fail-closed) | uncapped (still ledgered) |
| Backfill cooldown | `embed.backfill_cooldown_min` | `10` | skips re-submission inside window | — (latency knob, not spend) | **not** bypassed |
| `reindex-code` cost gate | — (preview before re-embed) | — | TTY prompt / non-TTY refuse + exit 3 (`confirmation_required`) | `--max-cost off` | runs uncapped (still ledgered) |
+| `reindex --markdown` consent gate | — (page count + estimate before re-embed) | — | TTY prompt / non-TTY refuse + exit 3 (`confirmation_required`); `--yes` runs under the derived cap, `--max-usd` sets it; a queued `reindex` job runs only with the approval stored by `jobs submit reindex ... --yes` or the search-mode switch prompt | `--dry-run`, `--no-embed` (free) | authorizes under the derived cap |
| `migrate embeddings` consent gate | — (plan + estimate before provider migration) | — | TTY y/N prompt / non-TTY refuse + exit 3 (`confirmation_required`) | `--yes` | estimate marked informational, but **still prompts** (guards a destructive schema rebuild, not just spend) |
| `enrich` / `onboard --auto` | `--max-usd` (per-call) | — | non-TTY without `--yes`/`--max-usd`: refuse + exit 3 (`confirmation_required`); `--yes` runs under the derived cap | `--max-usd off` | runs uncapped (still ledgered) |
| Image-OCR per-run ceiling | `embedding_image_ocr_max_images` / `embedding_image_ocr_max_usd` | `200` images / `$1.00` (estimated) | skips OCR over-cap (import continues; skips counted in `ocr_skipped_budget`, surfaced by doctor `ocr_health`) | `0` disables that cap | **not** bypassed (per-run cap, not a tracker gate) |
diff --git a/skills/migrations/v0.21.0.md b/skills/migrations/v0.21.0.md
index 89a25f33fc..475e274ad8 100644
--- a/skills/migrations/v0.21.0.md
+++ b/skills/migrations/v0.21.0.md
@@ -29,9 +29,10 @@ These run as part of `gbrain upgrade` → `gbrain apply-migrations`. No manual D
**Automatic (recommended):** next `gbrain sync --source <id>` detects the version mismatch and forces a full re-walk regardless of git HEAD equality. No cost preview, no user interaction. The Layer 12 SP-1 fix from codex's second-pass review.
- **Immediate:** preview cost, then reindex every code page now.
+ **Immediate (paid, ask first):** preview the cost, show the user the token count and dollar estimate, and reindex only after they agree.
```bash
gbrain reindex-code --dry-run # preview token count + $USD cost
+ # only after the user agrees:
gbrain reindex-code --yes # reindex all code pages
gbrain reindex-code --source <id> --yes # scope to one source
```
diff --git a/skills/migrations/v0.28.0.md b/skills/migrations/v0.28.0.md
index 794fe89ba1..ac04b5c33c 100644
--- a/skills/migrations/v0.28.0.md
+++ b/skills/migrations/v0.28.0.md
@@ -56,9 +56,11 @@ For brains with existing fenced takes content in pre-v0.28 markdown:
```bash
# Pages chunked before the fence strip keep an older chunker_version;
-# reindex re-chunks exactly those pages. Preview, then run:
+# reindex re-chunks exactly those pages and re-embeds them, which costs
+# money. Preview, tell the user the page count, and run it only after they agree:
gbrain reindex --markdown --dry-run
-gbrain reindex --markdown
+# only after the user agrees:
+gbrain reindex --markdown --yes
# To rebuild one page's takes index from its fence afterwards:
gbrain takes rebuild <slug>
```
diff --git a/skills/migrations/v0.40.3.0.md b/skills/migrations/v0.40.3.0.md
index aaddcc306b..de01a2fad7 100644
--- a/skills/migrations/v0.40.3.0.md
+++ b/skills/migrations/v0.40.3.0.md
@@ -74,14 +74,22 @@ worker) offers to submit `gbrain reindex --markdown` as a Minion job.
Non-TTY callers get a paste-ready hint to stderr. Suppress entirely
with `GBRAIN_NO_MODE_SWITCH_UX=1`.
-If you skipped the prompt, run reindex manually:
+If the user skipped or declined that prompt, do not start the reindex
+yourself. Re-embedding every markdown page calls the embedding provider (and,
+under `tokenmax`, a chat model for each chunk), so it costs money. Preview it,
+tell the user how many pages it covers, and run it only after they agree:
```bash
-gbrain reindex --markdown
-# Or as a background job (needs a running `gbrain jobs work` worker; on PGLite add --follow):
-gbrain jobs submit reindex --params '{"markdown":true}'
+gbrain reindex --markdown --dry-run # page count; changes nothing
+# only after the user agrees:
+gbrain reindex --markdown --yes
+# or as a background job (needs a running `gbrain jobs work` worker; on PGLite add --follow):
+gbrain jobs submit reindex --params '{"markdown":true}' --yes
```
+Without `--yes` (or `--max-usd <usd>`) a non-interactive run exits 3 with an
+`ask_user` payload instead of spending; relay its `user_message`.
+
## Optional: per-source CR mode overrides
If you have multiple sources and want different CR tiers per source:
@@ -119,7 +127,8 @@ gbrain config set search.contextual_retrieval_disabled true
Existing cache rows continue to serve via the backward-compat path
(empty `{}` snapshot vacuously valid). New embeds skip the wrapper.
-Recovery is then `gbrain reindex --markdown` to re-embed un-wrapped.
+Recovery is a paid re-embed: preview with `gbrain reindex --markdown --dry-run`,
+and run `gbrain reindex --markdown --yes` only after the user agrees.
## What changed in the file layout
diff --git a/src/cli/commands/reindex.ts b/src/cli/commands/reindex.ts
index d4b9a2a152..b6a5dff62d 100644
--- a/src/cli/commands/reindex.ts
+++ b/src/cli/commands/reindex.ts
@@ -60,5 +60,14 @@ export async function run(engine: BrainEngine, args: string[]): Promise<void> {
return;
}
const { runReindex } = await import('../../commands/reindex.ts');
- await runReindex(engine, args);
+ try {
+ await runReindex(engine, args);
+ } catch (e) {
+ // W4.5: the paid-reindex consent gate (exit 3) and an over-cap estimate (exit 1) render as agent envelopes.
+ const { isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');
+ if (isConsentRefusal(e)) { setCliExitVerdict(printConsentRefusal(e, { json: args.includes('--json') })); return; }
+ const { OperationError } = await import('../../core/ops/contract.ts');
+ if (e instanceof OperationError) { setCliExitVerdict(writeCliError(e, 'reindex')); return; }
+ throw e;
+ }
}
diff --git a/src/commands/jobs/submit.ts b/src/commands/jobs/submit.ts
index 06af1eb1b0..10e66fecb7 100644
--- a/src/commands/jobs/submit.ts
+++ b/src/commands/jobs/submit.ts
@@ -114,6 +114,25 @@ export async function runJobsSubmit({ args, engine, queue }: JobsCommandContext)
// A4 + T8: queued paid enrich/subagent work needs the user's authorization; it is stored on the row and the worker enforces its cap.
let spendAuthorization: SpendAuthorization | undefined;
+ // W4.5: a re-embedding reindex job carries the user's authorization too; its handler refuses a job without one.
+ if (name === 'reindex' && data.dryRun !== true && data.noEmbed !== true) {
+ const { requireReindexConsent } = await import('../../core/reindex-consent.ts');
+ const { countPending } = await import('../reindex.ts');
+ const { isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');
+ const { setCliExitVerdict } = await import('../../core/cli-force-exit.ts');
+ const { jobSpendAuthorization } = await import('../../core/minions/spend-authorization.ts');
+ const argv = ['gbrain', 'jobs', ...args.filter(a => a !== '--yes')];
+ const pending = await countPending(engine, null, false);
+ const target = typeof data.limit === 'number' && data.limit > 0 ? Math.min(data.limit, pending) : pending;
+ try {
+ const gate = await requireReindexConsent(engine, { args, type: null, target, argv, preview_argv: ['gbrain', 'reindex', '--markdown', '--dry-run'] });
+ if (gate) spendAuthorization = jobSpendAuthorization(gate.auth, { command: 'jobs submit reindex', of: 1, argv, ...(gate.plan.est_usd !== null ? { est_usd: gate.plan.est_usd } : {}) });
+ } catch (e) {
+ if (!isConsentRefusal(e)) throw e;
+ setCliExitVerdict(printConsentRefusal(e, { json: hasFlag(args, '--json') }));
+ return;
+ }
+ }
if (PAID_SUBMIT_NAMES.has(name)) {
const authorized = await authorizePaidSubmit(engine, name, data, args);
if (!authorized) return;
diff --git a/src/commands/reindex.ts b/src/commands/reindex.ts
index 1de7bacc99..1235b2cfd2 100644
--- a/src/commands/reindex.ts
+++ b/src/commands/reindex.ts
@@ -83,7 +83,7 @@ export interface ReindexResult {
const REINDEX_HELP = `gbrain reindex — re-chunk / re-embed existing pages after a pipeline upgrade
USAGE
- gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--no-embed] [--json] [--repo PATH]
+ gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--no-embed] [--yes] [--max-usd USD] [--json] [--repo PATH]
gbrain reindex --multimodal [--limit N] [--workers N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]
gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]
gbrain reindex --vectors [--dry-run] [--json]
@@ -112,7 +112,11 @@ OPTIONS
--dry-run Report what would change; write nothing
--cost-estimate --multimodal only: print the embed cost estimate and stop
--no-embed Skip re-embedding (chunk-only reindex)
- --yes --multimodal only: skip the cost confirm
+ --yes Approve the paid run: --markdown re-embeds pages and asks
+ first (exit 3 without approval when not interactive;
+ --dry-run, --no-embed and a keyless brain never ask);
+ --multimodal skips its cost confirm
+ --max-usd USD --markdown: approve the paid run with this cost cap
--source <id> --aliases only: restrict to one source
--repo PATH --markdown only: brain repo override
--json Machine-readable output
@@ -126,7 +130,7 @@ export function printReindexHelp(): void {
console.log(REINDEX_HELP);
}
-const REINDEX_VALUE_FLAGS = new Set(['--type', '--limit', '--repo', '--workers', '--concurrency']);
+const REINDEX_VALUE_FLAGS = new Set(['--type', '--limit', '--repo', '--workers', '--concurrency', '--max-usd']);
export function normalizeReindexArgs(args: string[]): string[] {
return args.flatMap((arg) => {
@@ -223,7 +227,7 @@ function parseArgs(args: string[]): ReindexOpts {
* hook for post-v81 brains. The simple `chunker_version OR mode IS NULL`
* predicate covers the headline upgrade case the wave is shipping.
*/
-async function countPending(engine: BrainEngine, type: string | null = null, noEmbed = false): Promise<number> {
+export async function countPending(engine: BrainEngine, type: string | null = null, noEmbed = false): Promise<number> {
const driftPredicate = pendingDriftPredicate(noEmbed);
if (type) {
const rows = await engine.executeRaw<{ count: string | number }>(
@@ -290,7 +294,15 @@ async function readBatch(
);
}
-export async function runReindex(engine: BrainEngine, args: string[]): Promise<ReindexResult> {
+/** How a caller already authorized the paid run (W4.5): the job handler's stored spend record, or the upgrade prompt's TTY yes. */
+export interface ReindexRunOpts {
+ /** The paid run is already authorized; skip the consent gate. */
+ authorized?: boolean;
+ /** False for unattended callers (the job handler): the gate never prompts. */
+ interactive?: boolean;
+}
+
+export async function runReindex(engine: BrainEngine, args: string[], runOpts: ReindexRunOpts = {}): Promise<ReindexResult> {
args = normalizeReindexArgs(args);
const invalidType = args.some((arg, index) =>
arg === '--type' && !parsePageType(args[index + 1]));
@@ -370,6 +382,12 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<R
return { pending, pendingAfter: pending, reindexed: 0, skipped: 0, failed: 0, dryRun: true, chunkerVersion: MARKDOWN_CHUNKER_VERSION, type };
}
+ // W4.5: re-embedding is paid work; ask before it starts (throws the exit-3 consent refusal or cost_cap_exceeded).
+ if (!opts.noEmbed && !runOpts.authorized) {
+ const { requireReindexConsent } = await import('../core/reindex-consent.ts');
+ await requireReindexConsent(engine, { args, type, target, ...(runOpts.interactive === false ? { interactive: false } : {}) });
+ }
+
if (await managedPersistenceEnabled(engine)) return reindexManaged(engine, opts, type, pending);
const reporter = createProgress(cliOptsToProgressOptions(getCliOptions()));
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index ff14c55a03..1b13c7c4e4 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -818,7 +818,7 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
const promptResult = await runPostUpgradeReembedPrompt(engine, modelString);
if (promptResult.proceeded) {
const { runReindex } = await import('./reindex.ts');
- await runReindex(engine, ['--markdown']);
+ await runReindex(engine, ['--markdown'], { authorized: true }); // the TTY yes above is the consent
}
}
} catch (re) {
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 273df8fcbd..c2a51684b7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -290,6 +290,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.103.0', text: 'Filtered vector search on Postgres runs pgvector iterative scans in relaxed_order, which keeps closer in-filter matches strict order dropped; `gbrain config set search.hnsw_iterative_scan strict_order` and a restart of serve and autopilot restore the old mode.' },
{ since: '0.60.103.0', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },
{ since: '0.60.103.0', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },
+ { since: 'WAVE12', text: '`gbrain reindex --markdown` asks before re-embedding (paid): without a terminal it exits 3 with an ask_user payload naming the page count, the estimate and the `--yes` command; `--yes` or `--max-usd <usd>` approves it, and `--dry-run`, `--no-embed` and a keyless brain never ask. A queued `reindex` job re-embeds only with the approval stored at submit time (`gbrain jobs submit reindex ... --yes`, or the search-mode switch prompt); one queued without it fails with `confirmation_required`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/minions/handlers/reindex.ts b/src/core/minions/handlers/reindex.ts
index e62fb06afa..ca8fd3f13d 100644
--- a/src/core/minions/handlers/reindex.ts
+++ b/src/core/minions/handlers/reindex.ts
@@ -1,7 +1,13 @@
/**
* `reindex` Minion job handler (built-in; registered by registerBuiltinHandlers in src/commands/jobs.ts).
+ *
+ * W4.5: a paid run (re-embedding) is authorized only by the spend record a
+ * consent-gated producer stored on the job (`jobs submit reindex`, the
+ * search-mode switch prompt); the worker never prompts. A queued job without
+ * one fails terminally with the consent refusal instead of spending.
*/
import type { BrainEngine } from '../../engine.ts';
+import { UnrecoverableError } from '../errors.ts';
import type { MinionHandler } from '../types.ts';
export function makeReindexHandler(engine: BrainEngine): MinionHandler {
@@ -12,7 +18,14 @@ export function makeReindexHandler(engine: BrainEngine): MinionHandler {
if (job.data.dryRun) args.push('--dry-run');
if (job.data.noEmbed) args.push('--no-embed');
if (typeof job.data.repoPath === 'string') args.push('--repo', job.data.repoPath);
- const result = await runReindex(engine, args);
- return { ...result, ran: 'reindex' };
+ try {
+ const result = await runReindex(engine, args, { authorized: job.spend?.record != null, interactive: false });
+ return { ...result, ran: 'reindex' };
+ } catch (e) {
+ const { isConsentRefusal } = await import('../../consent.ts');
+ if (!isConsentRefusal(e)) throw e;
+ throw new UnrecoverableError(`confirmation_required: reindex job ${job.id} has no stored spend authorization, so it re-embedded nothing. `
+ + `Ask the user, then queue it again with approval (gbrain jobs submit reindex --params '{"markdown":true}' --yes) or run it inline: ${e.consent.fix.command ?? 'gbrain reindex --markdown --yes'}.`);
+ }
};
}
diff --git a/src/core/reindex-consent.ts b/src/core/reindex-consent.ts
new file mode 100644
index 0000000000..247a20f1ef
--- /dev/null
+++ b/src/core/reindex-consent.ts
@@ -0,0 +1,97 @@
+/**
+ * Consent for the paid markdown reindex (wave 12 W4.5).
+ *
+ * `gbrain reindex --markdown` re-chunks every page whose chunker version or
+ * contextual-retrieval state lags and re-embeds it, which bills the embedding
+ * provider per token (and, under a contextual-retrieval mode that writes
+ * per-chunk synopses, a chat model per chunk). It used to start without
+ * asking. One gate, `requireReindexConsent`, now runs inside `runReindex`
+ * for every caller: the CLI (`--yes`, `--max-usd`, a TTY prompt, a per-run
+ * preapproval or `spend.posture=tokenmax`; otherwise exit 3), the `reindex`
+ * Minion job handler (authorized only by the spend record stored on the job
+ * at submit time, never by a prompt in the worker) and `jobs submit reindex`.
+ * `--dry-run`, `--no-embed` and a keyless or free-provider brain spend
+ * nothing and never ask.
+ */
+import type { BrainEngine } from './engine.ts';
+import { requireConsent, type Authorization } from './consent.ts';
+import { opError } from './ops/contract.ts';
+import { MARKDOWN_CHUNKER_VERSION } from './chunkers/recursive.ts';
+
+export interface ReindexSpendPlan {
+ /** Pages the run would re-embed (after `--limit`). */
+ pages: number;
+ /** Embedding cost estimate for those pages; null when the model has no known price. */
+ est_usd: number | null;
+}
+
+/** Pre-flight estimate from the text of the pages the run would re-embed (the `countPending` predicate, embedding on). */
+export async function estimateReindexSpend(engine: BrainEngine, opts: { type: string | null; target: number }): Promise<ReindexSpendPlan> {
+ try {
+ const { getEmbeddingModel } = await import('./ai/gateway.ts');
+ const { estimateCostFromChars, lookupEmbeddingPrice } = await import('./embedding-pricing.ts');
+ const price = lookupEmbeddingPrice(getEmbeddingModel());
+ if (price.kind !== 'known') return { pages: opts.target, est_usd: null };
+ const rows = await engine.executeRaw<{ n: string | number; chars: string | number | null }>(
+ `SELECT COUNT(*)::bigint AS n, COALESCE(SUM(LENGTH(compiled_truth) + LENGTH(timeline)), 0)::bigint AS chars
+ FROM pages
+ WHERE page_kind = 'markdown' AND (chunker_version < $1 OR contextual_retrieval_mode IS NULL)
+ AND deleted_at IS NULL AND ($2::text IS NULL OR type = $2)`,
+ [MARKDOWN_CHUNKER_VERSION, opts.type]);
+ const pending = Number(rows[0]?.n ?? 0);
+ const chars = Number(rows[0]?.chars ?? 0) * (pending > 0 ? Math.min(1, opts.target / pending) : 1);
+ return { pages: opts.target, est_usd: estimateCostFromChars(chars, price.pricePerMTok) };
+ } catch {
+ return { pages: opts.target, est_usd: null };
+ }
+}
+
+/**
+ * Null when the run cannot spend (embedding disabled, no credentials, a free
+ * local provider); otherwise the Authorization, or throws the exit-3
+ * `confirmation_required` refusal (`isConsentRefusal`) carrying the page
+ * count and estimate. `interactive: false` (the job handler) never prompts.
+ * A user cap below the estimate refuses up front with `cost_cap_exceeded`.
+ */
+export async function requireReindexConsent(engine: BrainEngine, opts: {
+ args: readonly string[];
+ type: string | null;
+ target: number;
+ interactive?: boolean;
+ /** The approved command without `--yes` (default `gbrain reindex <args>`), and its free preview. */
+ argv?: string[];
+ preview_argv?: string[];
+}): Promise<{ auth: Authorization; plan: ReindexSpendPlan } | null> {
+ const { embedWouldSpend } = await import('./embed-consent.ts');
+ if (opts.target <= 0 || !(await embedWouldSpend(engine))) return null;
+ const plan = await estimateReindexSpend(engine, opts);
+ const cost = plan.est_usd === null ? 'cost unknown in advance' : `about $${plan.est_usd.toFixed(2)}`;
+ const base = ['gbrain', 'reindex', ...opts.args.filter((a) => a !== '--yes' && a !== '--json')];
+ const plain: string[] = [];
+ for (let i = 0; i < opts.args.length; i++) {
+ const a = opts.args[i]!;
+ if (a === '--yes' || a === '--json' || a.startsWith('--max-usd=') || a.startsWith('--max-cost=')) continue;
+ if (a === '--max-usd' || a === '--max-cost') { i++; continue; }
+ plain.push(a);
+ }
+ const auth = await requireConsent({
+ command: 'reindex',
+ effects: ['paid'],
+ actor: 'agent',
+ what: `Re-embed ${plan.pages} markdown page(s)`,
+ why: `Re-chunking a page re-embeds it with the configured embedding provider, which bills per token (${cost} for ${plan.pages} page(s)); a contextual-retrieval mode that writes per-chunk synopses also calls a chat model per chunk.`,
+ risk: 'Spends money with the embedding provider (and the chat provider under per-chunk contextual retrieval). Search keeps working on the old chunks until the reindex runs.',
+ user_message: `Rebuilding the search index re-embeds ${plan.pages} page(s) and costs money (${cost}). OK to run it?`,
+ argv: opts.argv ?? base,
+ preview_argv: opts.preview_argv ?? ['gbrain', 'reindex', ...plain, '--dry-run'],
+ est_usd: plan.est_usd,
+ args: opts.args,
+ }, { getConfig: (key) => engine.getConfig(key), ...(opts.interactive === false ? { interactive: false } : {}) });
+ if (auth.cap_usd !== null && plan.est_usd !== null && plan.est_usd > auth.cap_usd) {
+ throw opError('cost_cap_exceeded',
+ `The reindex of ${plan.pages} page(s) is estimated at $${plan.est_usd.toFixed(2)}, above the $${auth.cap_usd.toFixed(2)} cap; nothing ran.`,
+ 'Ask the user whether to raise the cap, then re-run with a higher --max-usd, or narrow the run with --limit or --type.',
+ { why: 'A run whose estimate exceeds its cap would stop part-way.' });
+ }
+ return { auth, plan };
+}
diff --git a/src/core/search/mode-switch-ux.ts b/src/core/search/mode-switch-ux.ts
index f608d798c7..e2ac40a83c 100644
--- a/src/core/search/mode-switch-ux.ts
+++ b/src/core/search/mode-switch-ux.ts
@@ -34,6 +34,7 @@
import type { BrainEngine } from '../engine.ts';
import { readLineSafe } from '../../commands/init.ts';
import { MinionQueue } from '../minions/queue.ts';
+import type { SpendAuthorization } from '../minions/spend-record.ts';
import { isSearchMode, type SearchMode } from './mode.ts';
export type TransitionKind =
@@ -68,7 +69,9 @@ export interface ModeSwitchOpts {
/** Test seam: injectable worker probe. */
probeFn?: (engine: BrainEngine) => Promise<WorkerProbeResult>;
/** Test seam: injectable Minion submitter (avoids real queue in unit tests). */
- submitFn?: (jobName: string, params: Record<string, unknown>, idempotencyKey: string) => Promise<number>;
+ submitFn?: (jobName: string, params: Record<string, unknown>, idempotencyKey: string, spendAuthorization?: SpendAuthorization) => Promise<number>;
+ /** Test seam: the TTY answer to the reindex prompt. */
+ answerFn?: (prompt: string) => Promise<string>;
}
/**
@@ -271,12 +274,13 @@ export async function runModeSwitchUx(opts: ModeSwitchOpts): Promise<void> {
return;
}
- // TTY + interactive: prompt.
- const answer = await readLineSafe(
- `Run '${summary.reindex_command}' now? [y/N]: `,
- 'n',
- 60_000,
- );
+ // TTY + interactive: prompt, naming what the reindex re-embeds and costs (W4.5: the yes is stored on the job as its spend authorization).
+ const { countPending } = await import('../../commands/reindex.ts');
+ const { estimateReindexSpend } = await import('../reindex-consent.ts');
+ const plan = await estimateReindexSpend(opts.engine, { type: null, target: await countPending(opts.engine, null, false) });
+ const cost = plan.est_usd === null ? 'embedding cost unknown in advance' : `embedding about $${plan.est_usd.toFixed(2)}`;
+ const prompt = `Run '${summary.reindex_command}' now? It re-embeds ${plan.pages} page(s) (${cost}, plus a chat call per chunk under tokenmax). [y/N]: `;
+ const answer = opts.answerFn ? await opts.answerFn(prompt) : await readLineSafe(prompt, 'n', 60_000);
if (answer.toLowerCase() !== 'y' && answer.toLowerCase() !== 'yes') {
console.error(`[mode-switch] Skipped. Run \`${summary.reindex_command}\` when ready.`);
return;
@@ -302,11 +306,17 @@ export async function runModeSwitchUx(opts: ModeSwitchOpts): Promise<void> {
const idempotencyKey = buildReindexIdempotencyKey(sourceId, chunkerVersion, opts.newMode);
const submitFn = opts.submitFn ?? defaultSubmit;
+ const { DEFAULT_PAID_CAP_USD, derivedCapUsd } = await import('../consent.ts');
+ const { jobSpendAuthorization } = await import('../minions/spend-authorization.ts');
+ const capUsd = Math.max(DEFAULT_PAID_CAP_USD, plan.est_usd === null ? 0 : derivedCapUsd(plan.est_usd));
+ const spend = jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: capUsd, cap_source: 'default', via: 'tty_prompt' },
+ { command: `config set search.mode ${opts.newMode}`, of: 1, argv: ['gbrain', 'reindex', '--markdown'], ...(plan.est_usd !== null ? { est_usd: plan.est_usd } : {}) });
try {
const jobId = await submitFn(
'reindex',
{ markdown: true, source_id: sourceId },
idempotencyKey,
+ spend,
);
console.error(`[mode-switch] Submitted as job ${jobId}. Watch with: gbrain jobs follow ${jobId}`);
} catch (err) {
@@ -318,13 +328,14 @@ export async function runModeSwitchUx(opts: ModeSwitchOpts): Promise<void> {
jobName: string,
params: Record<string, unknown>,
idemKey: string,
+ spendAuthorization?: SpendAuthorization,
): Promise<number> {
const queue = new MinionQueue(opts.engine);
const job = await queue.add(
jobName,
params,
{ idempotency_key: idemKey },
- { allowProtectedSubmit: true },
+ { allowProtectedSubmit: true, ...(spendAuthorization ? { spendAuthorization } : {}) },
);
return job.id;
}
diff --git a/test/e2e/contextual-retrieval-pglite.test.ts b/test/e2e/contextual-retrieval-pglite.test.ts
index 036b08ca0d..2b014bfc34 100644
--- a/test/e2e/contextual-retrieval-pglite.test.ts
+++ b/test/e2e/contextual-retrieval-pglite.test.ts
@@ -272,7 +272,8 @@ describe('per-source CR mode on the import path (#3885)', () => {
[sourceId, slug],
);
- const result = await runReindex(engine, ['--markdown', '--json', '--limit', '10']);
+ // W4.5: a re-embedding reindex needs the user's approval; --yes is it.
+ const result = await runReindex(engine, ['--markdown', '--json', '--limit', '10', '--yes']);
expect(result.reindexed).toBeGreaterThanOrEqual(1);
expect(await pageMode(slug, sourceId)).toBe('none');
const wrapped = embedderInputs.flat();
diff --git a/test/reindex-consent.test.ts b/test/reindex-consent.test.ts
new file mode 100644
index 0000000000..e0b6c1e893
--- /dev/null
+++ b/test/reindex-consent.test.ts
@@ -0,0 +1,175 @@
+/**
+ * Wave 12 W4.5: `gbrain reindex --markdown` re-embeds pages, which is paid
+ * work, so it asks first. A non-interactive run without `--yes`/`--max-usd`
+ * exits 3 with an ask_user payload naming the page count and estimate and
+ * makes no provider call; `--dry-run`, `--no-embed` and a keyless brain stay
+ * free. A queued `reindex` job re-embeds only under the spend authorization
+ * stored at submit time; one queued without it fails with the refusal.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runReindex } from '../src/commands/reindex.ts';
+import { run as runReindexCli } from '../src/cli/commands/reindex.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { isConsentRefusal } from '../src/core/consent.ts';
+import { makeReindexHandler } from '../src/core/minions/handlers/reindex.ts';
+import { jobSpendAuthorization } from '../src/core/minions/spend-authorization.ts';
+import { UnrecoverableError } from '../src/core/minions/errors.ts';
+import type { MinionJobContext } from '../src/core/minions/types.ts';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+let engine: PGLiteEngine;
+let embedCalls = 0;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+
+beforeEach(async () => {
+ _resetCliExitVerdictForTests();
+ embedCalls = 0;
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'sk-fake-reindex-consent' } });
+ __setEmbedTransportForTests((async (args: { values: string[] }) => {
+ embedCalls++;
+ return { embeddings: args.values.map(() => Array.from({ length: 1536 }, () => 0.01)), usage: { tokens: 1 } };
+ }) as never);
+ await engine.executeRaw('DELETE FROM content_chunks');
+ await engine.executeRaw('DELETE FROM pages');
+ for (const slug of ['notes/one', 'notes/two', 'notes/three']) {
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, page_kind, chunker_version, contextual_retrieval_mode)
+ VALUES ('default', $1, 'note', $1, $2, 'markdown', 1, NULL)`,
+ [slug, `Body of ${slug} with enough words to chunk and embed.`]);
+ }
+});
+afterEach(() => { __setEmbedTransportForTests(null); resetGateway(); });
+
+async function quiet<T>(fn: () => Promise<T>): Promise<{ result: T; stdout: string }> {
+ const out = process.stdout.write.bind(process.stdout);
+ const err = process.stderr.write.bind(process.stderr);
+ let stdout = '';
+ (process.stdout.write as unknown as (c: unknown) => boolean) = (c: unknown) => { stdout += String(c); return true; };
+ (process.stderr.write as unknown as (c: unknown) => boolean) = () => true;
+ try { return { result: await fn(), stdout }; } finally { process.stdout.write = out; process.stderr.write = err; }
+}
+
+const lagging = async () => Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM pages WHERE chunker_version = 1`))[0]!.n);
+
+describe('W4.5: reindex --markdown asks before re-embedding', () => {
+ test('the CLI without approval exits 3 with an ask_user payload (page count, estimate, --yes command) and spends nothing', async () => {
+ const { stdout } = await quiet(() => runReindexCli(engine, ['--markdown', '--json']));
+ expect(currentExitCode()).toBe(3);
+ const doc = JSON.parse(stdout);
+ expect(doc.code).toBe('confirmation_required');
+ expect(doc.effects).toEqual(['paid']);
+ expect(doc.user_message).toContain('3 page(s)');
+ expect(typeof doc.est_usd).toBe('number');
+ expect(doc.fix.next).toBe('ask_user');
+ expect(doc.fix.argv).toEqual(['gbrain', 'reindex', '--markdown', '--yes']);
+ expect(doc.preview.argv).toEqual(['gbrain', 'reindex', '--markdown', '--dry-run']);
+ expect(embedCalls).toBe(0);
+ expect(await lagging()).toBe(3);
+ });
+
+ test('runReindex itself refuses for an unattended caller, so no path skips the gate', async () => {
+ let thrown: unknown;
+ try { await quiet(() => runReindex(engine, ['--markdown'], { interactive: false })); } catch (e) { thrown = e; }
+ expect(isConsentRefusal(thrown)).toBe(true);
+ expect(embedCalls).toBe(0);
+ });
+
+ test('--dry-run, --no-embed and a keyless brain never ask', async () => {
+ await quiet(() => runReindexCli(engine, ['--markdown', '--dry-run']));
+ expect(currentExitCode()).toBe(0);
+ await quiet(() => runReindexCli(engine, ['--markdown', '--no-embed']));
+ expect(currentExitCode()).toBe(0);
+ expect(await lagging()).toBe(0);
+ expect(embedCalls).toBe(0);
+ await engine.executeRaw(`UPDATE pages SET chunker_version = 1, contextual_retrieval_mode = NULL`);
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536, env: {} });
+ await quiet(() => runReindexCli(engine, ['--markdown']));
+ expect(currentExitCode()).not.toBe(3);
+ });
+
+ test('--yes approves the run', async () => {
+ await quiet(() => runReindexCli(engine, ['--markdown', '--yes']));
+ expect(currentExitCode()).toBe(0);
+ expect(await lagging()).toBe(0);
+ });
+
+ test('a cap below the estimate refuses before anything runs', async () => {
+ await engine.executeRaw(`UPDATE pages SET compiled_truth = repeat('word ', 2000000) WHERE slug = 'notes/one'`);
+ await quiet(() => runReindexCli(engine, ['--markdown', '--max-usd', '0.0001', '--json']));
+ expect(currentExitCode()).toBe(1);
+ expect(embedCalls).toBe(0);
+ expect(await lagging()).toBe(3);
+ });
+});
+
+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,
+ ...(spend ? { spend: { record: jobSpendAuthorization({ consented_effects: ['paid'], cap_usd: 5, cap_source: 'user', via: 'yes' }, { command: 'jobs submit reindex', of: 1 }), budget_key: 'group:x' } } : {}),
+ }) as MinionJobContext;
+
+ test('a queued job without a stored authorization fails with confirmation_required and spends nothing', async () => {
+ let thrown: unknown;
+ try { await quiet(() => makeReindexHandler(engine)(ctx(false))); } catch (e) { thrown = e; }
+ expect(thrown).toBeInstanceOf(UnrecoverableError);
+ expect(String((thrown as Error).message)).toContain('confirmation_required');
+ expect(embedCalls).toBe(0);
+ expect(await lagging()).toBe(3);
+ });
+
+ test('a queued job with its stored authorization runs', async () => {
+ const { result } = await quiet(() => makeReindexHandler(engine)(ctx(true)));
+ expect((result as { ran: string }).ran).toBe('reindex');
+ expect(await lagging()).toBe(0);
+ });
+});
+
+describe('W4.5: jobs submit reindex stores the approval on the job', () => {
+ let home: string;
+ let brainPath: string;
+ const env = { GBRAIN_INTERACTIVE: undefined, OPENAI_API_KEY: 'sk-fake-reindex-submit' };
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-reindex-submit-'));
+ brainPath = join(home, '.gbrain', 'brain.pglite');
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: brainPath,
+ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536 }));
+ const e = new PGLiteEngine();
+ await e.connect({ engine: 'pglite', database_path: brainPath });
+ await e.initSchema();
+ await e.executeRaw(`INSERT INTO pages (source_id, slug, type, title, compiled_truth, page_kind, chunker_version)
+ VALUES ('default', 'notes/queued', 'note', 'Queued', 'Body to re-embed.', 'markdown', 1)`);
+ await e.disconnect();
+ }, 120_000);
+ afterAll(() => rmSync(home, { recursive: true, force: true }));
+ const rows = async () => {
+ const e = new PGLiteEngine();
+ await e.connect({ engine: 'pglite', database_path: brainPath });
+ try { return await e.executeRaw<{ name: string; spend_authorization: Record<string, unknown> | null }>('SELECT name, spend_authorization FROM minion_jobs ORDER BY id'); }
+ finally { await e.disconnect(); }
+ };
+
+ test('without --yes it exits 3 and queues nothing; with --yes the row carries an authorized record', async () => {
+ const refused = await runCli(['jobs', 'submit', 'reindex', '--params', '{"markdown":true}', '--queue-only', '--json'], { home, env, timeoutMs: 90_000 });
+ expect(refused.exitCode).toBe(3);
+ expect(JSON.parse(refused.stdout)).toMatchObject({ code: 'confirmation_required', effects: ['paid'] });
+ expect(await rows()).toEqual([]);
+ const approved = await runCli(['jobs', 'submit', 'reindex', '--params', '{"markdown":true}', '--queue-only', '--yes'], { home, env, timeoutMs: 90_000 });
+ expect(approved.exitCode).toBe(0);
+ const [row] = await rows();
+ expect(row).toMatchObject({ name: 'reindex', spend_authorization: { kind: 'authorized', command: 'jobs submit reindex' } });
+ }, 200_000);
+});