Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(enrich): ask through requireConsent; tokenmax keeps its uncapped meaning (C2)
garrytan454308747c6d
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.mdindex 606890ee0b..9e63053dd2 100644--- a/docs/architecture/key-files/commands-2-continued.md+++ b/docs/architecture/key-files/commands-2-continued.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-2.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).+- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) through `requireConsent` (effect `paid`; `--yes`, `--max-usd`, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, `--json` never implying it); the budget (`--max-usd`, else the derived consent cap) soft-stops via the pass's `shouldStop` seam (estimate-based) and bounds the `--audit-rejects` half. `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter.diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 3c6b15edf1..a957239ed3 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -55,7 +55,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.- `src/commands/projections.ts` + `src/cli/commands/projections.ts` — `gbrain projections drain [--limit <n>] [--json]` (#5401). Trusted-local CLI, not an operation. Rebuilds queued Markdown and code projections in-process in batches of up to 100 until every row queued at the run start has been tried once (it waits for the database clock to pass the run start, so a page that fails in the run is not retried); `--limit` caps pages tried. Exit 0 (nothing tried failed), 1 (a page failed; each failure prints source, slug, reason and next action), 2 (did not run: bad usage, or `projection_owner_resident` when a process holds the selected PGLite brain, checked with `persistenceConfigForBrain` before any engine opens, so a mounted PGLite brain on a Postgres host is refused too). On Postgres it runs beside a resident owner (per-page locks plus the revision recheck). `residentDrainSteps` gives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests: `projection-drain.test.ts` (both engines via `test/e2e/projection-drain-postgres.test.ts`), `projections-drain-cli.serial.test.ts`.-- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`. Resident-delegated embedding requires explicit --yes; --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.+- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). Consent (agent operator wave C2): the cost preview feeds `requireConsent` via `consentGate` (effect `paid`, the estimate as `est_usd`); `--yes`, `--max-cost <usd>`, a per-run preapproval or `spend.posture=tokenmax` authorize it, and without authorization a non-interactive or `--json` run spends nothing and exits 3 with the consent payload. A run without a user cap is capped at the derived cap (BudgetTracker `capSource`), except under tokenmax, which keeps its documented uncapped meaning (`tokenmaxUncappedEnv`); `--max-cost off` stays the explicit uncapped choice. The owner-delegated path asks the same way with no estimate (default cap). Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source). --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch; it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it). Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands). Consent (agent operator wave C3): every run first previews one selection (the rows whose stored `effective_date`/`effective_date_source` would change, scoped by `--source` and `--slug-prefix` through `backfillEffectiveDate`'s `sourceId` filter) and hashes it; the dry run reports that `plan_hash`. An apply asks through `requireConsent` (effect `destructive`, bound to the plan: `--yes --expect <plan_hash>`; a changed row is `preview_changed`) and writes only the approved ids (`onlyIds`). `--json` never implies consent: non-interactive without approval changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Scoped walks never read or write the orchestrator's brain-wide checkpoint. Pinned by `test/reindex-frontmatter-consent.test.ts` (two-source scope, binding).@@ -63,7 +63,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/reindex-vectors.ts` — `gbrain reindex --vectors [--dry-run] [--json]` (dispatched from cli.ts beside `--aliases`). Lists every HNSW index in the current schema from `pg_indexes` and runs `REINDEX INDEX` on each (`REINDEX INDEX CONCURRENTLY` on Postgres), rebuilding the ANN index from stored vectors with no re-embedding. The PGLite WAL-repair notice (`buildWalRepairNotice`) and `gbrain pglite-repair` name it, because a WAL reset does not rebuild indexes (#4616). Tests: `test/embedding-zero-norm-4616.serial.test.ts` on both engines.-- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Confirmation gate: `--yes`, or an interactive TTY [y/N]; `--json` does NOT bypass the gate (non-TTY without `--yes` refuses with a ConfirmationRequired envelope, exit 2). Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.+- `src/commands/reindex-search-vector.ts` — `gbrain reindex-search-vector [--dry-run] [--yes] [--json]`. Escape hatch for changing `GBRAIN_FTS_LANGUAGE` after the `configurable_fts_language` migration has run (the migration shows applied and is skipped): recreates `update_page_search_vector` + `update_chunk_search_vector` with the configured language — bodies mirror the migration's and KEEP the `SET search_path = pg_catalog, public` hardening (CREATE OR REPLACE resets proconfig) — then backfills `pages` (UPDATE-to-self re-fires the trigger) and `content_chunks` (direct vector recompute) in id-keyset batches of `BACKFILL_BATCH_SIZE` (5000) via `UPDATE … WHERE id IN (SELECT … LIMIT n) RETURNING id`, streaming phases `reindex_search_vector.pages`/`.chunks` through the shared progress reporter (stderr). Consent gate (agent operator wave C2): `requireConsent` (effect `destructive`, not plan-bound: derived index, the undo is a re-run under the previous language) — `--yes` or a TTY prompt; `--json` never implies it, and a refusal changes nothing, returns `status: 'confirmation_required'` and exits 3 with the consent payload. Interrupted-run safety: stamps `fts.reindex_in_progress` (= target language, key exported as `FTS_REINDEX_MARKER_KEY` from `fts-language.ts`) in the config table BEFORE the autocommitted DDL and clears it only after both backfills return; each batch persists its keyset cursor under `backfill.fts_pages.last_id` / `backfill.fts_content_chunks.last_id` (the `checkpointKey` convention from `backfill-base.ts`), so a re-run with the same language resumes from the checkpoint and a different language resets it. Deliberately not one `engine.transaction()` (whole-run row locks on Postgres, zero banked progress on a hang). Idempotent. Pinned by `test/reindex-search-vector.serial.test.ts`.- `src/commands/init-mode-picker.ts` — install-time mode recommendation, downstream-input cost matrix, and mandatory operator choice. Mode summaries describe payload knobs only. Expansion follows the command (`query` on unless opted out; `search` and memory verbs off), not the chosen mode; provider charges and downstream prompt caching are disclosed separately from GBrain result caching.diff --git a/scripts/agent-contract-baselines/yes-rerun-string.tsv b/scripts/agent-contract-baselines/yes-rerun-string.tsvindex c6941b1a08..115f252de0 100644--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv@@ -5,7 +5,6 @@ src/commands/company-brain-connect.ts 1src/commands/config.ts 1src/commands/db-repair.ts 1src/commands/doctor/checks/memory-writeback.ts 2-src/commands/enrich.ts 1src/commands/mcp-expose.ts 3src/commands/migrations/v0_11_0.ts 1src/commands/takes.ts 1diff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex 26e25c741f..709c659402 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -53,6 +53,7 @@ import {type OpCheckpointKey,} from '../core/op-checkpoint.ts';import { createProgress } from '../core/progress.ts';+import { consentGateOrExit, engineConsentEnv, tokenmaxUncappedEnv } from '../core/consent-cli.ts';import { getCliOptions, cliOptsToProgressOptions, maybeBackground } from '../core/cli-options.ts';import { loadConfig } from '../core/config.ts';import { runSlidingPool } from '../core/worker-pool.ts';@@ -1003,37 +1004,37 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<voprocess.exit(1);}- // v0.42.42.0 (#2139, D15A): enrich runs UNCAPPED when the operator says cost- // isn't the constraint — either explicit `--max-usd off` (parsed to Infinity)- // or `spend.posture=tokenmax` with no per-call cap. Uncapped → the missing-cap- // refusals lift AND runEnrichCore passes no ceiling to the BudgetTracker (spend- // still ledgered; posture removes the ceiling, not the accounting). An explicit- // finite --max-usd always wins (precedence: per-call > posture).- const explicitOff = parsed.maxCostUsd === Infinity;- const { resolveSpendPosture } = await import('../core/spend-posture.ts');- const posture = parsed.dryRun ? 'gated' : await resolveSpendPosture(engine);- const uncapped =- !parsed.dryRun && (explicitOff || (parsed.maxCostUsd === undefined && posture === 'tokenmax'));- if (uncapped) {- console.error(`${explicitOff ? '--max-usd off' : 'spend.posture=tokenmax'}: running uncapped, spend ledgered. docs: docs/operations/spend-controls.md`);- }-- // Non-TTY execute without --max-usd or --yes is refused (cost guardrail).- if (!parsed.dryRun && parsed.maxCostUsd === undefined && !parsed.yes && !process.stdout.isTTY && !uncapped) {- console.error('Refusing to spend without a cap in a non-interactive context. Pass --max-usd <FLOAT> (or `off`), --yes, or set spend.posture=tokenmax.');- process.exit(1);- }-const sourceIds: string[] = parsed.sourceId? [parsed.sourceId]: (await listSources(engine)).map((s) => s.id);- // Dry-run cost preview (TTY) before spending.- if (!parsed.dryRun && process.stdout.isTTY && !parsed.yes && parsed.maxCostUsd === undefined && !uncapped) {+ // A4 consent before spending. `--max-usd <usd>`, `--yes` (derived cap: the+ // estimate x1.5), a per-run preapproval or spend.posture=tokenmax authorize+ // it; `--max-usd off` is the explicit uncapped choice. tokenmax keeps its+ // documented meaning here (D15A: the ceiling is removed, spend is still+ // ledgered), so unattended tokenmax runs do not flip to a derived-cap stop.+ // Without authorization: a TTY prompt, else exit 3 with the consent payload.+ const explicitOff = parsed.maxCostUsd === Infinity;+ let maxCostUsd = parsed.maxCostUsd;+ if (!parsed.dryRun && !explicitOff) {const limit = parsed.limit ?? DEFAULT_LIMIT;- const est = (limit * sourceIds.length * COST_ESTIMATE_PER_PAGE_USD).toFixed(2);- console.error(`About to enrich up to ${limit} page(s) per source across ${sourceIds.length} source(s), est. ~$${est}. Re-run with --max-usd or --yes to confirm.`);- process.exit(2);+ const estUsd = Math.ceil(limit * sourceIds.length * COST_ESTIMATE_PER_PAGE_USD * 100) / 100;+ const auth = await consentGateOrExit({+ command: 'enrich', effects: ['paid'], actor: 'agent',+ what: `Enrich up to ${limit} page(s) per source across ${sourceIds.length} source(s)`,+ why: 'Fills thin person and company pages with model-written summaries from the brain\'s own evidence.',+ risk: `Spends about $${estUsd.toFixed(2)} with the chat model provider; pages gain model-written text (each write is attributed and can be reviewed).`,+ user_message: `Enrich up to ${limit} thin page(s) per source across ${sourceIds.length} source(s) for about $${estUsd.toFixed(2)}?`,+ argv: ['gbrain', 'enrich', ...args.filter(a => a !== '--yes')],+ preview_argv: ['gbrain', 'enrich', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run'],+ est_usd: estUsd,+ args,+ }, { json: parsed.json === true, env: engineConsentEnv(engine, await tokenmaxUncappedEnv(engine, parsed.maxCostUsd !== undefined)) });+ if (maxCostUsd === undefined && auth.cap_usd !== null) maxCostUsd = auth.cap_usd;+ }+ const uncapped = !parsed.dryRun && maxCostUsd === Infinity;+ if (uncapped) {+ console.error(`${explicitOff ? '--max-usd off' : 'spend.posture=tokenmax'}: running uncapped, spend ledgered. docs: docs/operations/spend-controls.md`);}const aggregate = emptyAgg();@@ -1053,7 +1054,7 @@ export async function runEnrich(engine: BrainEngine, args: string[]): Promise<vomodel: parsed.model,// uncapped (off / tokenmax) → Infinity sentinel; runEnrichCore maps it// to "no BudgetTracker ceiling".- maxCostUsd: uncapped ? Infinity : parsed.maxCostUsd,+ maxCostUsd,minContextChars: parsed.minContextChars,thinThreshold: parsed.thinThreshold,reenrichAfterMs: parsed.reenrichAfterMs,diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.tsindex 7ed9cce1f0..22f6df3341 100644--- a/src/commands/reindex-code.ts+++ b/src/commands/reindex-code.ts@@ -26,7 +26,7 @@ import { reindexCodeProjection } from '../core/persistence/projection-reindex.tsimport { refreshProjectionStatistics } from '../core/search/projection-statistics.ts';import { estimateTokens } from '../core/chunkers/code.ts';import { getEmbeddingModelName, estimateEmbeddingCostUsd } from '../core/embedding.ts';-import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';+import { consentGate, engineConsentEnv, tokenmaxUncappedEnv } from '../core/consent-cli.ts';import type { CapSource } from '../core/consent.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';@@ -497,7 +497,8 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Pr} else {// A4: paid. --yes, --max-cost <usd>, spend.posture=tokenmax or a per-run// preapproval authorizes it; without a user cap the run is capped at the- // estimate x1.5 (printed). Non-interactive otherwise: exit 3, no spend.+ // estimate x1.5 (printed), except under tokenmax, which keeps its+ // documented uncapped meaning here. Non-interactive otherwise: exit 3.const auth = await consentGate({command: 'reindex-code',effects: ['paid'],@@ -510,12 +511,12 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Prpreview_argv: ['gbrain', 'reindex-code', ...args.filter(a => a !== '--yes' && a !== '-y' && a !== '--json'), '--dry-run', '--json'],est_usd: costUsd,args,- }, { json, env: engineConsentEnv(engine) });+ }, { json, env: engineConsentEnv(engine, await tokenmaxUncappedEnv(engine, maxCostUsd !== undefined)) });if (!auth) return;if (auth.via === 'tokenmax' && json) {console.log(JSON.stringify({ status: 'proceeding', gate: 'posture_tokenmax', codePages: preview.totalPages, totalTokens: preview.totalTokens, costUsd, model: getEmbeddingModelName() }));}- if (maxCostUsd === undefined && auth.cap_usd !== null) {+ if (maxCostUsd === undefined && auth.cap_usd !== null && Number.isFinite(auth.cap_usd)) {maxCostUsd = auth.cap_usd;capSource = auth.cap_source ?? undefined;}diff --git a/src/core/consent-cli.ts b/src/core/consent-cli.tsindex bb102b16bd..87d9ee2239 100644--- a/src/core/consent-cli.ts+++ b/src/core/consent-cli.ts@@ -43,3 +43,19 @@ export function engineConsentEnv(engine: Pick<BrainEngine, 'getConfig'> | null |return engine ? { getConfig: (key: string) => engine.getConfig(key), ...extra } : extra;}++/**+ * `spend.posture=tokenmax` on a command that ran uncapped under it before+ * the consent wave (enrich, reindex-code): the posture keeps its documented+ * meaning there (the user removed the ceiling; spend stays ledgered, see+ * docs/operations/spend-controls.md), so an unattended run does not flip to a+ * derived-cap stop. Returns the ConsentEnv overlay that records the+ * ceiling as Infinity (a user-configured posture, so no derived-cap note);+ * callers treat a non-finite `cap_usd` as "no ceiling". Everywhere else+ * tokenmax authorizes under requireConsent's derived cap.+ */+export async function tokenmaxUncappedEnv(engine: Pick<BrainEngine, 'getConfig'>, explicitCap: boolean): Promise<ConsentEnv> {+ if (explicitCap) return {};+ const { resolveSpendPosture } = await import('./spend-posture.ts');+ return (await resolveSpendPosture(engine as BrainEngine)) === 'tokenmax' ? { configuredCapUsd: Infinity } : {};+}