Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(reindex): reindex-code, its serve delegate and reindex-search-vector ask through requireConsent (C2)
garrytan4ac559459828
diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsvindex 01c0299267..5d64257515 100644--- a/scripts/agent-contract-baselines/interactive-io.tsv+++ b/scripts/agent-contract-baselines/interactive-io.tsv@@ -8,7 +8,6 @@ src/commands/hook.ts 3src/commands/init.ts 4src/commands/jobs-watch.ts 2src/commands/notability-eval.ts 1-src/commands/reindex-search-vector.ts 1src/commands/report.ts 1src/commands/upgrade.ts 1src/commands/watch.ts 1diff --git a/scripts/agent-contract-baselines/legacy-advice-key.tsv b/scripts/agent-contract-baselines/legacy-advice-key.tsvindex 36a85b8b50..faebf498ea 100644--- a/scripts/agent-contract-baselines/legacy-advice-key.tsv+++ b/scripts/agent-contract-baselines/legacy-advice-key.tsv@@ -21,8 +21,6 @@ src/commands/hook.ts 2src/commands/loops.ts 1src/commands/mcp-admin.ts 2src/commands/mcp.ts 2-src/commands/reindex-code.ts 1-src/commands/reindex-search-vector.ts 1src/commands/serve-http-clients.ts 1src/commands/serve-http-grants.ts 2src/commands/serve-http-oauth.ts 1diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex 108622e556..7210721e2a 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -10,7 +10,7 @@ src/commands/extract-timeline-db.ts 2src/commands/google-attachments.ts 11src/commands/persistence-admin.ts 11src/commands/recall.ts 3-src/commands/reindex-code-delegate.ts 6+src/commands/reindex-code-delegate.ts 5src/commands/repair.ts 6src/commands/source-reconcile.ts 29src/commands/sources-lifecycle-args.ts 1@@ -116,7 +116,7 @@ src/core/persistence/reconcile-merge.ts 13src/core/persistence/reconcile-prepare.ts 7src/core/persistence/reconcile-state.ts 11src/core/persistence/reconcile.ts 11-src/core/persistence/reindex-administration.ts 5+src/core/persistence/reindex-administration.ts 4src/core/persistence/root-registry.ts 2src/core/persistence/semantic-pages.ts 4src/core/persistence/service.ts 5diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 57b047abd6..b2d0b9ebdc 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -350,7 +350,7 @@ test/v0_37_gap_fill.serial.test.ts Lane C.3 — env OPENAI_API_KEY merges into ltest/v0_37_gap_fill.serial.test.ts Lane D.2 — embed pre-flight catches dim mismatch before worker pool 2 source-surface-helpertest/v0_37_gap_fill.serial.test.ts Lane D.3 — sync surfaces dim-mismatch recipe at incremental AND first-sync catches 2 source-surface-helpertest/v0_37_gap_fill.serial.test.ts Lane E.4 — loadRecommendationContext is provider-aware 1 readFileSync,source-surface-helper-test/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 7 source-surface-helper+test/v0_37_gap_fill.serial.test.ts reinit-pglite — backup + reinit 8 source-surface-helpertest/worker-supervised-db-probe.test.ts issue #1801 fix #2 — supervised DB self-defense 5 readFileSynctest/write-attribution-legacy.test.ts write attribution inventory 1 readFileSync# unknown (detectors present, no attributable suite):diff --git a/scripts/test-weights.json b/scripts/test-weights.jsonindex 52e9cb0c67..fc46fc100b 100644--- a/scripts/test-weights.json+++ b/scripts/test-weights.json@@ -1450,7 +1450,6 @@"test/reindex-code-empty-file.test.ts": 680,"test/reindex-code-recovery.test.ts": 230,"test/reindex-code.test.ts": 1060,- "test/reindex-cost-refusal.test.ts": 6,"test/reindex-frontmatter-connect.test.ts": 233,"test/reindex-markdown-persistence.slow.test.ts": 144006,"test/reindex-preserve-tags.test.ts": 569,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 4824102762..e20cc634fb 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -1987,7 +1987,6 @@"unit:test/reindex-code-empty-file.test.ts": 1733,"unit:test/reindex-code-recovery.test.ts": 1253,"unit:test/reindex-code.test.ts": 2342,- "unit:test/reindex-cost-refusal.test.ts": 284,"unit:test/reindex-frontmatter-connect.test.ts": 1357,"unit:test/reindex-preserve-tags.test.ts": 3154,"unit:test/reindex.test.ts": 7577,diff --git a/src/commands/reindex-code-delegate.ts b/src/commands/reindex-code-delegate.tsindex 65a5d22640..7ea1f00227 100644--- a/src/commands/reindex-code-delegate.ts+++ b/src/commands/reindex-code-delegate.ts@@ -7,6 +7,8 @@ import { inspectLockHolder } from '../core/pglite-lock.ts';import { OperationError } from '../core/ops/contract.ts';import { reportPersistenceCliError } from './persistence-delegate.ts';import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';+import { DEFAULT_PAID_CAP_USD } from '../core/consent.ts';+import { consentGate } from '../core/consent-cli.ts';import type { ReindexCodeOpts, ReindexCodeResult } from './reindex-code.ts';export function parseReindexCodeDelegateArgs(args: string[]): ReindexCodeOpts {@@ -37,7 +39,24 @@ export async function maybeDelegateReindexCode(hostConfig: GBrainConfig | null,if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;try {const options = parseReindexCodeDelegateArgs(args);- if (!options.noEmbed && !options.dryRun && !options.yes) throw new OperationError('confirmation_required', 'Pass --no-embed for keyless text recovery, --dry-run for a preview, or --yes to authorize embedding costs.');+ if (!options.noEmbed && !options.dryRun) {+ // A4: paid. The owner holds the brain, so no estimate is available here: the cap is+ // --max-cost when given, else the printed default cap. The owner re-checks `yes`.+ const auth = await consentGate({+ command: 'reindex-code', effects: ['paid'], actor: 'agent',+ what: 'Re-embed the code pages through the running gbrain serve',+ why: 'Rebuilds code chunks and their embeddings so code search uses current chunking; the running serve owns the brain, so it does the work.',+ risk: `Spends with the embedding provider, capped at ${options.maxCostUsd !== undefined ? `$${options.maxCostUsd.toFixed(2)}` : `the default $${DEFAULT_PAID_CAP_USD.toFixed(2)}`} (no estimate while the serve holds the brain). --no-embed rebuilds text and symbol metadata for free.`,+ user_message: `Re-embed the brain's code pages (paid embeddings, at most ${options.maxCostUsd !== undefined ? `$${options.maxCostUsd.toFixed(2)}` : `$${DEFAULT_PAID_CAP_USD.toFixed(2)}`})? --no-embed does the free text-only rebuild instead.`,+ argv: ['gbrain', 'reindex-code', ...args.filter(a => a !== '--yes' && a !== '-y')],+ preview_argv: ['gbrain', 'reindex-code', ...args.filter(a => a !== '--yes' && a !== '-y' && a !== '--json'), '--dry-run', '--json'],+ est_usd: null,+ args,+ }, { json: options.json === true });+ if (!auth) return true;+ options.yes = true;+ if (options.maxCostUsd === undefined && auth.cap_usd !== null) options.maxCostUsd = auth.cap_usd;+ }const delegated = await maybeDelegateLocalAdministration('writer_reindex_code', { options }, config, { timeoutMs: 86_400_000 });if (!delegated.handled) throw new OperationError('owner_unavailable', 'The registered owner stopped before reindex admission. Retry the same command.');const result = delegated.result as ReindexCodeResult;diff --git a/src/commands/reindex-code.ts b/src/commands/reindex-code.tsindex 648535cb32..7ed9cce1f0 100644--- a/src/commands/reindex-code.ts+++ b/src/commands/reindex-code.ts@@ -26,8 +26,8 @@ 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 { errorFor, serializeError } from '../core/errors.ts';-import { promptYesNo } from '../core/confirm-prompt.ts';+import { consentGate, engineConsentEnv } 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';import { BudgetTracker, BudgetExhausted } from '../core/budget/budget-tracker.ts';@@ -55,6 +55,8 @@ export interface ReindexCodeOpts {* imported, the throw aborts the remaining batch).*/maxCostUsd?: number;+ /** A4: where `maxCostUsd` came from (default `user`); a derived cap warns-and-runs an unpriced model. */+ capSource?: CapSource;/*** v0.41.15.0 (T11, D9): per-batch parallel workers. Default 1.* PGLite clamps to 1. Recommended 4-8 for large code corpora.@@ -328,7 +330,7 @@ export async function runReindexCode(try {if (typeof opts.maxCostUsd === 'number' && opts.maxCostUsd > 0) {- const tracker = new BudgetTracker({ maxCostUsd: opts.maxCostUsd, label: 'reindex-code' });+ const tracker = new BudgetTracker({ maxCostUsd: opts.maxCostUsd, label: 'reindex-code', capSource: opts.capSource });await withBudgetTracker(tracker, reindexBody);} else {await reindexBody();@@ -376,44 +378,6 @@ export async function runReindexCode(};}-/**- * v0.42.11.0 (#1784) — what to print when the cost gate refuses to spend- * non-interactively without `--yes`. The REFUSAL (exit 2, no spend) is the- * guardrail and is correct; the FORMAT is a separate axis. Pre-#1784 this path- * always emitted a JSON envelope even without `--json`, violating the repo's- * "human by default" convention. Now: JSON only when `--json` is explicit;- * otherwise a human refusal on stderr. Pure + exported so it's unit-testable- * without a brain or a real cost preview.- */-export interface CostRefusal {- stdout?: string;- stderr?: string;-}-export function buildCostRefusal(opts: {- json: boolean;- previewMsg: string;- preview: unknown;- costUsd: number;- model: string;-}): CostRefusal {- if (opts.json) {- const envelope = serializeError(errorFor({- class: 'ConfirmationRequired',- code: 'cost_preview_requires_yes',- message: opts.previewMsg,- hint: 'Pass --yes to proceed, or --dry-run to see the preview and exit 0.',- }));- return {- stdout: JSON.stringify({ error: envelope, preview: opts.preview, costUsd: opts.costUsd, model: opts.model }),- };- }- return {- stderr:- `${opts.previewMsg}\n` +- 'Refusing to re-embed non-interactively without confirmation. ' +- 'Pass --yes to proceed, or --dry-run for the preview (exit 0).',- };-}/*** issue #3970 — recovery hint for the "0 reindexed, N skipped" wall. Without@@ -436,9 +400,9 @@ export function reindexForceHint(}/**- * CLI entrypoint. Parses argv, wires cost-preview gate + JSON/TTY branching,- * delegates to runReindexCode. Exit codes: 0 on success/dry-run, 2 on- * ConfirmationRequired (matches sync --all), 1 on runtime error.+ * CLI entrypoint. Parses argv, wires the cost preview + consent gate+ * (requireConsent, effect paid), delegates to runReindexCode. Exit codes: 0+ * on success/dry-run, 3 on confirmation_required, 1 on runtime error.*/export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Promise<void> {const sourceIdx = args.indexOf('--source');@@ -468,6 +432,7 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Pr// "cost isn't the constraint" decision that proceeds past the confirmation gate// (like --yes). Numeric must be positive; `0`/garbage is rejected.let maxCostUsd: number | undefined;+ let capSource: CapSource | undefined;let maxCostOff = false;for (const flag of ['--max-cost', '--max-cost-usd']) {const idx = args.indexOf(flag);@@ -522,42 +487,42 @@ export async function runReindexCodeCli(engine: BrainEngine, args: string[]): Prreturn;}- if (!yes) {- // v0.42.42.0 (#2139): spend.posture=tokenmax makes the gate informational- // — print the estimate and proceed (the operator declared cost isn't the- // constraint). The spend is still ledgered by the runtime BudgetTracker.- const { resolveSpendPosture } = await import('../core/spend-posture.ts');- const posture = await resolveSpendPosture(engine);- // An explicit `--max-cost off` is the same "cost isn't the constraint"- // signal as spend.posture=tokenmax — proceed past the confirmation gate.- if (posture === 'tokenmax' || maxCostOff) {- const gate = maxCostOff ? 'max_cost_off' : 'posture_tokenmax';- if (json) {- console.log(JSON.stringify({ status: 'proceeding', gate, codePages: preview.totalPages, totalTokens: preview.totalTokens, costUsd, model: getEmbeddingModelName() }));- } else {- console.log(`${previewMsg} ${maxCostOff ? '--max-cost off' : 'spend.posture=tokenmax'}: proceeding (informational). docs: docs/operations/spend-controls.md`);- }+ if (maxCostOff) {+ // An explicit `--max-cost off` is the user's "cost isn't the constraint" decision: no cap, no ask.+ if (json) {+ console.log(JSON.stringify({ status: 'proceeding', gate: 'max_cost_off', codePages: preview.totalPages, totalTokens: preview.totalTokens, costUsd, model: getEmbeddingModelName() }));} else {- const isTTY = Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY);- if (!isTTY || json) {- // Guardrail unchanged: refuse + exit 2, no spend. Only the FORMAT splits- // on --json now (human refusal on stderr otherwise) — #1784.- const refusal = buildCostRefusal({ json, previewMsg, preview, costUsd, model: getEmbeddingModelName() });- if (refusal.stdout) console.log(refusal.stdout);- if (refusal.stderr) console.error(refusal.stderr);- process.exit(2);- }- console.log(previewMsg);- const answer = await promptYesNo('Proceed? [y/N] ');- if (!answer) {- console.log('Cancelled.');- return;- }+ console.log(`${previewMsg} --max-cost off: proceeding (informational). docs: docs/operations/spend-controls.md`);+ }+ } 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.+ const auth = await consentGate({+ command: 'reindex-code',+ effects: ['paid'],+ actor: 'agent',+ what: `Re-embed ${preview.totalPages} code page(s)`,+ why: `Rebuilds code chunks and their embeddings (~${preview.totalTokens.toLocaleString()} tokens on ${getEmbeddingModelName()}) so code search uses current chunking.`,+ risk: `Spends about $${costUsd.toFixed(2)} with the embedding provider. Pages are kept; --no-embed rebuilds the text and symbol metadata for free.`,+ user_message: `Re-embed ${preview.totalPages} code page(s) for about $${costUsd.toFixed(2)}? (--no-embed does the free text-only rebuild instead.)`,+ argv: ['gbrain', 'reindex-code', ...args.filter(a => a !== '--yes' && a !== '-y')],+ preview_argv: ['gbrain', 'reindex-code', ...args.filter(a => a !== '--yes' && a !== '-y' && a !== '--json'), '--dry-run', '--json'],+ est_usd: costUsd,+ args,+ }, { json, env: engineConsentEnv(engine) });+ 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) {+ maxCostUsd = auth.cap_usd;+ capSource = auth.cap_source ?? undefined;}}}- const result = await runReindexCode(engine, { sourceId, yes, json, force, noEmbed, maxCostUsd, workers });+ const result = await runReindexCode(engine, { sourceId, yes, json, force, noEmbed, maxCostUsd, capSource, workers });if (json) {console.log(JSON.stringify(result));} else {diff --git a/src/commands/reindex-multimodal.ts b/src/commands/reindex-multimodal.tsindex d07a7e655a..e9c41647b5 100644--- a/src/commands/reindex-multimodal.ts+++ b/src/commands/reindex-multimodal.ts@@ -31,6 +31,7 @@ import type { DbLockHandle } from '../core/db-lock.ts';import { sqlQueryForEngine } from '../core/sql-query.ts';import { embedMultimodalSafe } from '../core/ai/gateway.ts';import { createProgress } from '../core/progress.ts';+import { isInteractive } from '../core/interaction.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { gbrainPath } from '../core/config.ts';import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';@@ -188,9 +189,16 @@ export async function runReindexMultimodal(};}- // Cost grace window (TTY only; non-TTY auto-proceeds for CI / cron).- // Skip if --yes was passed.- if (!opts.yes && process.stdout.isTTY && process.stdin.isTTY) {+ // Cost grace window for a human at a terminal. Unattended runs keep+ // proceeding (A4 "no silent flip": CI / cron sweeps ran non-interactively+ // before the consent wave) and say what they spend on stderr.+ if (!opts.yes && !isInteractive()) {+ process.stderr.write(+ `[reindex-multimodal] unattended run: re-embedding ~${pendingBefore} chunks via voyage:voyage-multimodal-3, est. ~$${costUsdEstimate.toFixed(2)}. `+ + 'Set GBRAIN_NO_REEMBED=1 to skip, or --cost-estimate to preview only.\n',+ );+ }+ if (!opts.yes && isInteractive()) {const minutes = Math.ceil((pendingBefore / BATCH_SIZE) * 0.5 / 60); // ~0.5s per batchprocess.stderr.write(`Will re-embed ~${pendingBefore} chunks via voyage:voyage-multimodal-3, ` +diff --git a/src/commands/reindex-search-vector.ts b/src/commands/reindex-search-vector.tsindex bba4f1e2a6..73023a02a6 100644--- a/src/commands/reindex-search-vector.ts+++ b/src/commands/reindex-search-vector.ts@@ -17,8 +17,10 @@** Flags:* --dry-run Show what would happen, exit 0 without touching DB.- * --yes Skip interactive [y/N]. Required for non-TTY (including --json).- * --json Machine-readable result envelope. Does NOT imply --yes.+ * --yes The user's approval (requireConsent, effect destructive). Without+ * it a non-interactive run (including --json) changes nothing and+ * exits 3 with the consent payload.+ * --json Machine-readable result envelope. Does NOT imply consent.** Backfill runs in id-keyset batches (BACKFILL_BATCH_SIZE rows per UPDATE)* so a large brain never holds one giant row lock, and streams progress@@ -46,7 +48,8 @@import type { BrainEngine } from '../core/engine.ts';import { getFtsLanguage, FTS_REINDEX_MARKER_KEY } from '../core/fts-language.ts';import { checkpointKey } from '../core/backfill-base.ts';-import { createInterface } from 'readline';+import { consentGate } from '../core/consent-cli.ts';+import type { ConsentEnv } from '../core/consent.ts';import { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';@@ -54,10 +57,15 @@ export interface ReindexSearchVectorOpts {dryRun?: boolean;yes?: boolean;json?: boolean;+ /** Raw CLI argv for requireConsent (`--yes`, preapproval flags); default derived from `yes`. */+ args?: readonly string[];+ /** Consent seams (interactive probe, prompt reader). */+ consentEnv?: ConsentEnv;}export interface ReindexSearchVectorResult {- status: 'ok' | 'dry_run' | 'cancelled';+ /** `confirmation_required`: consent refused; the refusal was printed (exit verdict 3) and nothing changed. */+ status: 'ok' | 'dry_run' | 'confirmation_required';language: string;pagesUpdated: number;chunksUpdated: number;@@ -146,58 +154,32 @@ export async function runReindexSearchVector(} else {console.log(`[dry-run] Would recreate 2 trigger functions with language='${lang}'`);console.log(`[dry-run] Would backfill ${pagesCount} pages + ${chunksCount} chunks`);- console.log(`[dry-run] Skipping all DB writes. Pass --yes to apply.`);+ console.log(`[dry-run] Skipping all DB writes. Applying needs the user's approval (gbrain reindex-search-vector asks).`);}return result;}- // Confirm unless --yes. --json does NOT bypass the gate — a machine- // caller must pass --yes explicitly (mirrors reindex-code, #1784).- if (!opts.yes) {- if (!process.stdin.isTTY) {- if (opts.json) {- console.log(JSON.stringify({- error: {- class: 'ConfirmationRequired',- code: 'reindex_requires_yes',- message: `Refusing to recreate FTS triggers + backfill ${pagesCount} pages + ${chunksCount} chunks without --yes in a non-TTY environment.`,- hint: 'Pass --yes to proceed, or --dry-run to preview.',- },- language: lang,- pages: pagesCount,- chunks: chunksCount,- }));- } else {- console.error('Refusing to run without --yes in non-TTY environment.');- }- process.exit(2);- }-- const rl = createInterface({ input: process.stdin, output: process.stdout });- const answer = await new Promise<string>(resolve => {- rl.question(- `Recreate FTS triggers with language='${lang}' and backfill ${pagesCount} pages + ${chunksCount} chunks? [y/N]: `,- resolve- );- });- rl.close();-- if (!/^y(es)?$/i.test(answer.trim())) {- const result: ReindexSearchVectorResult = {- status: 'cancelled',- language: lang,- pagesUpdated: 0,- chunksUpdated: 0,- triggersRecreated: 0,- durationMs: Date.now() - startedAt,- };- if (opts.json) {- console.log(JSON.stringify(result, null, 2));- } else {- console.log('Cancelled.');- }- return result;- }+ // Consent (A4). --json does NOT imply it. Effect destructive: every page's+ // and chunk's stored keyword index is rewritten in the new language. Not+ // bound to a plan hash: the rows are derived data and the target is fully+ // named by GBRAIN_FTS_LANGUAGE, so re-running under the previous language+ // is the undo.+ const auth = await consentGate({+ command: 'reindex-search-vector',+ effects: ['destructive'],+ actor: 'agent',+ what: `Rebuild the keyword search index in language '${lang}'`,+ why: `Recreates the full-text trigger functions with language '${lang}' (from GBRAIN_FTS_LANGUAGE) and re-tokenizes ${pagesCount} page(s) and ${chunksCount} chunk(s), so keyword search matches that language.`,+ risk: `Rewrites the stored keyword index of every page and chunk; keyword search uses '${lang}' rules afterwards and is split until the run finishes `+ + '(an interrupted run resumes with the same command; gbrain doctor reports fts_reindex_incomplete meanwhile). Page text is not touched. '+ + 'Undo: run this command again with GBRAIN_FTS_LANGUAGE set to the previous language.',+ user_message: `Rebuild the keyword search index of ${pagesCount} page(s) in '${lang}'? It can take minutes on a large brain; page text is not changed.`,+ argv: ['gbrain', 'reindex-search-vector', ...(opts.json ? ['--json'] : [])],+ preview_argv: ['gbrain', 'reindex-search-vector', '--dry-run', '--json'],+ args: opts.args ?? (opts.yes ? ['--yes'] : []),+ }, { json: opts.json === true, env: opts.consentEnv });+ if (!auth) {+ return { status: 'confirmation_required', language: lang, pagesUpdated: 0, chunksUpdated: 0, triggersRecreated: 0, durationMs: Date.now() - startedAt };}// Recreate trigger functions. The strings are intentionally identical to@@ -320,7 +302,7 @@ export async function runReindexSearchVector(* CLI entrypoint. Parses argv flags and dispatches to runReindexSearchVector.* Matches the style of `reindex-code`: --dry-run, --yes/-y, --json.*- * Exit codes: 0 success/dry-run/cancelled, 2 if non-TTY without --yes.+ * Exit codes: 0 success/dry-run, 3 when consent is required (refusal printed).*/export async function runReindexSearchVectorCli(engine: BrainEngine,@@ -330,5 +312,5 @@ export async function runReindexSearchVectorCli(const yes = args.includes('--yes') || args.includes('-y');const json = args.includes('--json');- await runReindexSearchVector(engine, { dryRun, yes, json });+ await runReindexSearchVector(engine, { dryRun, yes, json, args: yes && !args.includes('--yes') ? [...args, '--yes'] : args });}diff --git a/src/core/persistence/reindex-administration.ts b/src/core/persistence/reindex-administration.tsindex fbc559ad39..5df74c80fc 100644--- a/src/core/persistence/reindex-administration.ts+++ b/src/core/persistence/reindex-administration.ts@@ -14,7 +14,10 @@ export async function runAuthenticatedCodeReindex(engine: BrainEngine, params: Roptions.sourceId !== undefined && (typeof options.sourceId !== 'string' || !options.sourceId) ||options.workers !== undefined && (!Number.isInteger(options.workers) || Number(options.workers) < 1 || Number(options.workers) > 64) ||options.maxCostUsd !== undefined && (typeof options.maxCostUsd !== 'number' || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) throw new OperationError('invalid_params', 'Invalid code reindex options.');- if (!options.noEmbed && !options.dryRun && !options.yes) throw new OperationError('confirmation_required', 'Explicit embedding consent is required; use --no-embed for keyless recovery.');+ if (!options.noEmbed && !options.dryRun && !options.yes) {+ throw new OperationError('confirmation_required', 'Explicit embedding consent is required; use --no-embed for keyless recovery.',+ 'The CLI asks the user before delegating; run gbrain reindex-code without --yes to get the consent request and relay it to the user.');+ }if (!verified.grant.scopes.includes('write') || verified.grant.operations !== null && !verified.grant.operations.includes('submit_job') ||verified.grant.slugPrefixes !== null || !verified.grant.sourceIds.includes('*') &&(typeof options.sourceId !== 'string' || !verified.grant.sourceIds.includes(options.sourceId))) {diff --git a/test/reindex-cost-refusal.test.ts b/test/reindex-cost-refusal.test.tsdeleted file mode 100644index 3e778abf6d..0000000000--- a/test/reindex-cost-refusal.test.ts+++ /dev/null@@ -1,52 +0,0 @@-/**- * v0.42.11.0 (#1784) — reindex-code cost-refusal format unit tests.- *- * The cost gate still REFUSES to spend non-interactively without --yes (exit 2,- * tested at the CLI layer). This pins the separate FORMAT axis: JSON only when- * --json is explicit; otherwise a human refusal on stderr. Pure function — no- * brain, no real cost preview.- */-import { describe, test, expect } from 'bun:test';-import { buildCostRefusal } from '../src/commands/reindex-code.ts';--const PREVIEW_MSG = 'reindex-code: 42 code page(s), ~12,345 tokens, est. $0.12 on voyage:voyage-code-3.';--describe('buildCostRefusal', () => {- test('--json → machine-readable envelope on stdout, nothing on stderr', () => {- const r = buildCostRefusal({- json: true,- previewMsg: PREVIEW_MSG,- preview: { totalPages: 42, totalTokens: 12345 },- costUsd: 0.12,- model: 'voyage:voyage-code-3',- });- expect(r.stderr).toBeUndefined();- expect(typeof r.stdout).toBe('string');- const parsed = JSON.parse(r.stdout!);- expect(parsed.error).toBeDefined();- // The structured refusal must still carry the confirmation code + context.- expect(JSON.stringify(parsed.error)).toContain('cost_preview_requires_yes');- expect(parsed.costUsd).toBe(0.12);- expect(parsed.model).toBe('voyage:voyage-code-3');- expect(parsed.preview).toEqual({ totalPages: 42, totalTokens: 12345 });- });-- test('no --json → human refusal on stderr, nothing on stdout (not JSON)', () => {- const r = buildCostRefusal({- json: false,- previewMsg: PREVIEW_MSG,- preview: {},- costUsd: 0.12,- model: 'voyage:voyage-code-3',- });- expect(r.stdout).toBeUndefined();- expect(typeof r.stderr).toBe('string');- // Human text: includes the preview, the refusal reason, and both escape hatches.- expect(r.stderr).toContain(PREVIEW_MSG);- expect(r.stderr).toContain('Refusing to re-embed');- expect(r.stderr).toContain('--yes');- expect(r.stderr).toContain('--dry-run');- // Must NOT be a JSON envelope.- expect(r.stderr!.trimStart().startsWith('{')).toBe(false);- });-});diff --git a/test/reindex-search-vector.serial.test.ts b/test/reindex-search-vector.serial.test.tsindex 683a6447cc..773f586210 100644--- a/test/reindex-search-vector.serial.test.ts+++ b/test/reindex-search-vector.serial.test.ts@@ -3,6 +3,7 @@ import type { BrainEngine } from '../src/core/engine.ts';import { runReindexSearchVector } from '../src/commands/reindex-search-vector.ts';import { resetFtsLanguageCache } from '../src/core/fts-language.ts';import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';const ENV_KEY = 'GBRAIN_FTS_LANGUAGE';const originalLang = process.env[ENV_KEY];@@ -82,6 +83,28 @@ describe('runReindexSearchVector', () => {expect(state.calls[0]).not.toContain('UPDATE');});+ test('C2: --json without --yes never consents: no DDL, exit 3 with the consent payload', async () => {+ const state: MockState = { calls: [], rowsToReturn: { pages: 50, chunks: 200 } };+ const engine = makeMockEngine(state);+ let stdout = '';+ const write = process.stdout.write;+ process.stdout.write = ((c: string | Uint8Array) => { stdout += String(c); return true; }) as typeof process.stdout.write;+ let result;+ try {+ result = await runReindexSearchVector(engine, { json: true, consentEnv: { interactive: false, preapprovals: {} } });+ } finally {+ process.stdout.write = write;+ }+ expect(result.status).toBe('confirmation_required');+ expect(currentExitCode()).toBe(3);+ setCliExitVerdict(0);+ expect(state.calls.length).toBe(1);+ expect(state.calls.some(sql => sql.includes('CREATE OR REPLACE'))).toBe(false);+ const payload = JSON.parse(stdout);+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['destructive'] });+ expect(payload.fix.argv).toEqual(['gbrain', 'reindex-search-vector', '--json', '--yes']);+ });+test('--yes recreates triggers + backfills with configured language', async () => {const state: MockState = { calls: [], rowsToReturn: { pages: 50, chunks: 200 } };const engine = makeMockEngine(state);