Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(migrate-embeddings): ask through requireConsent (paid + destructive), exit 3 not 2 (C2)
garrytan2307531eb346
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex d26541e9e6..3c6b15edf1 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -20,7 +20,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/lint.ts` — Page quality linter (catches LLM artifacts, placeholder dates). `runLintCore(opts)` walks the tree ONCE; `--fix` applies fixes during that same scan and reports per-page results through the `onPageIssues(relPath, issues, fixedCount)` callback (issues = what remains after this run's fix attempt for the page; `fixedCount` = fixes actually applied), so the summary's auto-fixed count is the true count — a second scan run after fixing would see already-fixed files and report zero. `onScanStart` fires once with the collected page count for progress wiring. Pinned by `test/lint-fix-single-pass.test.ts`. On a durability-hardened brain (`isDurabilityHardened` on the target dir, or the page's directory for a single-file target) every non-dry-run `--fix` repair is committed path-limited via `commitWriteThroughFile` right after the `writeFileSync` — the same contract as put_page write-through, so the cycle, the `lint`/`lint-fix` minion handlers and the CLI never leave hardened repairs as uncommitted drift for the sync phase to flag (pinned by `test/cycle-lint-durability.test.ts`). Lint rules `huge-page` (flags pages exceeding `content_sanity.bytes_warn`) and `scraper-junk` (flags pages matching any junk pattern). Both reuse `assessContent()` from `src/core/content-sanity.ts` so lint, doctor, and ingest share one assessor. `lint.ts` lifts DB config when `~/.gbrain/` is reachable; falls back to file/env on CI. Pinned by `test/lint-content-sanity.test.ts`. Rule `type-undeclared` flags an explicit frontmatter `type` the active schema pack neither declares nor aliases (resolved once per run from the shared/probed engine's DB-plane `schema_pack`, else file/env config; no resolvable pack skips it; `LintOpts.typePack` injects it), pinned by `test/lint-page-type-vocabulary.test.ts`. with `src/commands/sources.ts`: `gbrain lint` has a `markup-heavy` rule (flags pages whose prose-vs-markup ratio exceeds `content_sanity.max_markup_ratio`, reusing `assessContentSanity` so lint/gate/scan share one assessor); pinned by `test/lint-content-sanity.test.ts`. `gbrain sources audit <id>` is disposition-aware: its dry-run disk scan reports would-quarantine / would-reject / would-flag counts driven by the effective `content_sanity.junk_disposition` + markup config, so an operator previews the gate's verdict before sync. The `content-sanity-audit` JSONL (`src/core/audit/content-sanity-audit.ts`) records the quarantine/flag dispositions.-- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 2 non-TTY without `--yes`. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.+- `src/commands/migrate-embeddings.ts` — `gbrain migrate embeddings --to <provider:model> [--dim N] [--dry-run] [--yes] [--json] [--no-embed] [--status] [--reranker auto|off|keep|<model>] [--retarget] [--batch-size N] [--pace[=mode]] [--ignore-env-override]` (alias: `gbrain retrieval-upgrade`). ONE shared orchestrator for CLI and the `migrate_embeddings` op: `planMigrationFlow` (plan + `verifyMigrationComplete` + env presence + un-merged file plane + brain/DB identity via `redactPgUrl` + concurrent-writer census + reranker plan + in-flight-other marker) and `executeMigrationFlow` (global `gbrain-embedding-migration` DbLock → retarget gate under it → all-source embed locks sorted with `includeArchived` → worst-case authorization under the locks (a cap below it returns `refused_budget` / op `refused` with `embedding_budget_below_worst_case` before any provider call or invalidation) → live embed probe → apply → reranker probe + switch → drain via `runEmbedCore({heldLocks, …})` so the migration never lock_skips itself, with a 5-min heartbeat whose refresh-false/3-errors ABORTS as `lock_lost` → reconcile → completion smoke check stamped into the marker → transactional complete; locks released in finally). The skip path exits 0 ONLY on `verify.complete` with no pending retarget decision and no pending reranker action (a resolved switch/disable runs as a config-only completion). `--status` is read-only/spend-free and never refuses on env (it REPORTS planes, key PRESENCE booleans only, censuses, markers verbatim incl. corrupt, the exact resume command, and the last completion + smoke-check outcome). `persistEmbeddingFileConfig` writes through `loadConfigFileOnly` (never persists env-sourced keys) and supports env-canonical no-file deployments (env pins target ⇒ proceed with notice). Exit codes: 0 completed/verified-no-work, 1 locked/refused/failed/incomplete (message names which; lock_skipped and lock_lost get their own copy), 3 consent required (agent operator wave C2: `requireConsent` with effects `paid` + `destructive`; `spend.posture=tokenmax` covers only the paid part, `--json` never implies consent, the payload's fix repeats the caller's argv plus `--yes`; the TTY prompt is interaction.readLine, and the `confirm`/`isTTY` test seams map onto ConsentEnv). Spend stays bounded by the durable `--max-cost-usd` authorization, not the consent cap. Pinned by `test/migrate-embeddings-flow.serial.test.ts`, `test/migrate-embeddings-boundary.serial.test.ts`, `test/migrate-embeddings-hardening.serial.test.ts`. Migration guidance uses `renderCanonicalMigrationCommands` (`src/core/ai/defaults.ts`) to keep supported targets and dimensions consistent.- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`). Copies the complete source catalog FIRST (`copyMigrationSources` — every `sources` row incl. archived rows and sync/routing metadata, `ON CONFLICT (id) DO UPDATE`, `default` ordered first) so every page write has a valid `pages.source_id` FK parent and the target preserves per-source behavior; pages copy afterward: `listAllPageRefs` lists every live page's `(source_id, slug)` in one uncapped query, `copyMigrationPages` reads each body with `getPage(slug, { sourceId })` (a page soft-deleted after the listing reads null and is skipped, reported, and kept out of the link copy; it is not a failure), and each page is tracked in the resume manifest by composite `(source_id, slug)` key. Link copy preserves each row's `to_source_id` (falling back to the origin source only for legacy rows without it), and failed-target filtering uses that same target composite key, so cross-source links migrate without being rebound to the origin source. The resume manifest is target-aware: `migrationTargetId(config)` hashes `(engine, locator)` (`database_url` for Postgres, resolved `database_path` for PGLite) and `manifestMatchesTarget` requires `schema_version === 2` plus a matching `target_id` — a legacy engine-only manifest, or one from a DIFFERENT target of the same engine kind, starts fresh instead of skipping "completed" pages the new target never received. After links, `copyMigrationFacts` carries the facts table verbatim (conversation facts have no markdown fence to re-sync from): source∩target column intersection via information_schema (older source schemas still copy), delete-and-recopy so every re-run converges to source truth, two-pass `superseded_by` restore (the self-FK points old→newer id, so id-ordered single-pass inserts would violate it), embeddings round-tripped as text into whichever physical type (`vector`/`halfvec`) the target column has with a NULL-embedding retry on per-row cast failure, and a `setval` bump so post-migration inserts don't collide with copied ids; fact-row failures block the config flip and force a non-zero exit, same contract as page failures. Takes are deliberately NOT copied (fence-canonical, keyed on target-reassigned `page_id`; the next extract cycle rebuilds them). `copyMigrationConfig` then copies EVERY DB-plane config row except the explicit engine-local denylist `MIGRATE_CONFIG_ENGINE_LOCAL_KEYS` (`engine`, `version` = target-owned schema ledger, `embedding_columns` + `search_embedding_column` = physical-column registry the copy doesn't materialize); skipped keys print in the end-of-run per-table copied-count summary, so nothing is dropped silently. Pinned by `test/migrate-engine-resume.test.ts` (manifest identity) + `test/e2e/migrate-engine-sources-postgres.test.ts` (source catalog lands before overlapping-slug pages, PGLite → real Postgres) + `test/e2e/multi-source-bug-class.test.ts` (cross-source links) + `test/migrate-engine-completeness.serial.test.ts` (facts chains/embeddings/sequence, config copy-all + denylist, summary) + `test/migrate-engine-pagination.serial.test.ts` (no listing cap; a page deleted mid-copy). Legacy engine copies explicitly include stored unverified chunks and queue sanitized text rebuilding under the target revision; retrieval stays gated until rebuilt. Both source and target refuse any durable request history, withdrawal ledger, or ownership record before copying/clearing because this copier cannot preserve those identities.diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsvindex 758c64527c..01c0299267 100644--- a/scripts/agent-contract-baselines/interactive-io.tsv+++ b/scripts/agent-contract-baselines/interactive-io.tsv@@ -7,7 +7,6 @@ src/commands/dream-retriage.ts 1src/commands/hook.ts 3src/commands/init.ts 4src/commands/jobs-watch.ts 2-src/commands/migrate-embeddings.ts 2src/commands/notability-eval.ts 1src/commands/reindex-search-vector.ts 1src/commands/report.ts 1diff --git a/scripts/agent-contract-baselines/yes-rerun-string.tsv b/scripts/agent-contract-baselines/yes-rerun-string.tsvindex 7e30afb24f..592575ccac 100644--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv@@ -10,7 +10,6 @@ src/commands/doctor/checks/memory-writeback.ts 2src/commands/dream-retriage.ts 1src/commands/enrich.ts 1src/commands/mcp-expose.ts 3-src/commands/migrate-embeddings.ts 1src/commands/migrations/v0_11_0.ts 1src/commands/takes.ts 1src/core/bootstrap/harness.ts 1diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.tsindex c0864ce4b9..ee1d658cab 100644--- a/src/commands/migrate-embeddings.ts+++ b/src/commands/migrate-embeddings.ts@@ -1,4 +1,6 @@import type { BrainEngine } from '../core/engine.ts';+import { currentExitCode } from '../core/cli-force-exit.ts';+import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';import { serr, slog } from '../core/console-prefix.ts';import {planEmbeddingMigration,@@ -71,7 +73,8 @@ Flags:--dim <N> Target dimensions. Defaults to the provider recipe'sdeclared width; required when the recipe declares none.--dry-run Plan + cost estimate only; change nothing.- --yes Skip the confirm prompt (required non-interactively).+ --yes The user's approval (paid + destructive); without it a+ non-interactive run changes nothing and exits 3.--max-cost-usd <USD> Total durable authorization; must cover the printed worst case (or the runrefuses before any change). Requests settle to reported usage; raise to renew.--json Machine-readable envelope on stdout.@@ -264,21 +267,6 @@ function renderRerankerOutcome(outcome: RerankerOutcome): string[] {}}-/** Single-keypress y/N confirm on stdin. Injectable for tests. */-async function defaultConfirm(question: string): Promise<boolean> {- process.stderr.write(`${question} [y/N] `);- const stdin = process.stdin;- stdin.setRawMode?.(true);- stdin.resume();- const key: string = await new Promise((resolve) => {- stdin.once('data', (d) => resolve(d.toString()));- });- stdin.setRawMode?.(false);- stdin.pause();- process.stderr.write('\n');- return key.trim().toLowerCase().startsWith('y');-}-/*** One tiny embed against the TARGET provider, BEFORE any mutation: validates* the API key, the model id, and dimension support in a single call, so a bad@@ -1048,32 +1036,46 @@ export async function runMigrateEmbeddings(exit(0);}- // ── Consent gate. Unlike the pure cost gates in- // docs/operations/spend-controls.md, `spend.posture=tokenmax` does NOT- // bypass this one: posture waives the SPEND ceiling, and this gate also- // guards a destructive schema rebuild (existing vectors are dropped, and- // retrieval is degraded until the re-embed finishes). We honor the posture- // by marking the dollar figure informational, and still ask.+ // ── Consent gate (A4): effects paid + destructive. `spend.posture=tokenmax`+ // covers only the paid part; the schema rebuild (existing vectors are+ // dropped, retrieval is degraded until the re-embed finishes) still needs+ // `--yes`. Spend stays bounded by the migration's own durable authorization+ // (`--max-cost-usd` must cover the printed worst case), so the consent cap is+ // not threaded into the run. No plan hash: the brain-wide target is fully+ // named by the argv, and a resume re-runs the same command.if (!flags.yes) {const { resolveSpendPosture } = await import('../core/spend-posture.ts');- const posture = await resolveSpendPosture(engine);- if (posture === 'tokenmax') {- serr(' [migrate] spend.posture=tokenmax: the cost estimate above is informational.');- serr(' [migrate] Confirmation is still required — this rebuilds the embedding column (destructive, not just costly).');- }- const isTTY = opts.isTTY ?? Boolean(process.stdin.isTTY);- if (!isTTY) {- serr('Refusing to migrate without confirmation in a non-TTY environment. Re-run with --yes.');- exit(2);- }- const confirm = opts.confirm ?? defaultConfirm;- const priceNote = plan.price_known ? `~$${plan.est_cost_usd.toFixed(2)}` : 'an UNKNOWN amount';- const ok = await confirm(`Re-embed ${plan.chunks_to_embed} chunks, ${plan.facts_to_embed ?? 0} facts and ${plan.takes_to_embed ?? 0} takes (${priceNote}) with total authorization ${flags.maxCostUsd === undefined ? 'retained from the existing run (required for new work)' : `$${flags.maxCostUsd}`}?`);- if (!ok) {- serr('Aborted. Nothing was changed.');- exit(1);+ if (await resolveSpendPosture(engine) === 'tokenmax') {+ serr(' [migrate] spend.posture=tokenmax: the cost estimate above is informational; the destructive rebuild still needs the user\'s approval.');}}+ const priceNote = plan.price_known ? `about $${plan.est_cost_usd.toFixed(2)}` : 'an unpriced amount';+ const worstCase = plan.worst_case_authorization.usd;+ const auth = await consentGate({+ command: 'migrate embeddings',+ effects: ['paid', 'destructive'],+ actor: 'agent',+ what: `Move the brain's embeddings to ${flags.to}${flags.dim !== undefined ? ` (${flags.dim}d)` : ''}`,+ why: `Re-embeds ${plan.chunks_to_embed} chunk(s), ${plan.facts_to_embed ?? 0} fact(s) and ${plan.takes_to_embed ?? 0} take(s) with ${flags.to} (${priceNote}) so search runs in the new model's vector space; pages and facts are kept.`,+ risk: 'Rebuilds the embedding column in place: existing vectors are dropped and vector search is degraded until the re-embed finishes '+ + `(a killed run resumes with the same command; status: ${EMBEDDING_MIGRATION_RECOVERY.status_command}). `+ + `Spends up to the --max-cost-usd authorization${worstCase !== null ? ` (worst case $${worstCase.toFixed(2)})` : ''} with the target provider.`,+ user_message: `Switch your brain's embeddings to ${flags.to}? It re-embeds ${plan.chunks_to_embed} chunk(s) for ${priceNote}`+ + `${worstCase !== null ? ` (at most $${worstCase.toFixed(2)})` : ''}; search is degraded until it finishes. Your pages and facts are kept.`,+ argv: ['gbrain', 'migrate', 'embeddings', ...args.filter(a => a !== '--yes')],+ preview_argv: ['gbrain', 'migrate', 'embeddings', ...args.filter(a => a !== '--yes' && a !== '--json'), '--dry-run', '--json'],+ est_usd: plan.price_known ? plan.est_cost_usd : null,+ args,+ }, {+ json: flags.json,+ env: engineConsentEnv(engine, {+ configuredCapUsd: flags.maxCostUsd ?? 0,+ note: () => {},+ ...(opts.isTTY !== undefined ? { interactive: opts.isTTY } : {}),+ ...(opts.confirm ? { readLine: async ({ prompt }: { prompt: string }) => ({ kind: 'line' as const, text: (await opts.confirm!(prompt)) ? 'y' : 'n' }) } : {}),+ }),+ });+ if (!auth) return (opts.exit ?? ((value: number) => process.exit(value)))(currentExitCode());// ── Execute: locks → probe → apply → drain → reconcile → complete, all in// the shared orchestrator (identical semantics on the op path).diff --git a/test/migrate-embeddings-flow.serial.test.ts b/test/migrate-embeddings-flow.serial.test.tsindex bd31390ba7..16a59210f7 100644--- a/test/migrate-embeddings-flow.serial.test.ts+++ b/test/migrate-embeddings-flow.serial.test.ts@@ -21,7 +21,7 @@* afterAll), which withEnv() cannot wrap. GBRAIN_HOME is pointed at a temp dir so the file-plane config write* (persistEmbeddingFileConfig) never touches the developer's ~/.gbrain.*/-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';@@ -173,9 +173,19 @@ describe('migrate embeddings — full flow on PGLite', () => {expect(cfg.embedding_model).toBe('voyage:voyage-4');});- test('non-TTY without --yes refuses with exit 2 (cost gate)', async () => {+ test('non-TTY without --yes refuses with exit 3 (consent gate)', async () => {const code = await runMigrate(['--to', 'openai:text-embedding-3-small']);- expect(code).toBe(2);+ expect(code).toBe(3);+ // --json never implies consent; the refusal is the consent payload.+ let stdout = '';+ const write = spyOn(process.stdout, 'write').mockImplementation(((c: string | Uint8Array) => { stdout += String(c); return true; }) as never);+ let jsonCode: number;+ try { jsonCode = await runMigrate(['--to', 'openai:text-embedding-3-small', '--max-cost-usd', '1', '--json']); } finally { write.mockRestore(); }+ expect(jsonCode).toBe(3);+ const payload = JSON.parse(stdout.slice(stdout.lastIndexOf('{\n "status": "confirmation_required"')));+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['paid', 'destructive'] });+ expect(payload.fix.argv).toEqual(['gbrain', 'migrate', 'embeddings', '--to', 'openai:text-embedding-3-small', '--max-cost-usd', '1', '--json', '--yes']);+ expect(payload.risk).toContain('existing vectors are dropped');expect(await columnDims()).toBe(FROM_DIMS);});@@ -183,7 +193,7 @@ describe('migrate embeddings — full flow on PGLite', () => {await engine.setConfig('spend.posture', 'tokenmax');try {const code = await runMigrate(['--to', 'openai:text-embedding-3-small']);- expect(code).toBe(2); // posture waives the spend ceiling, not the consent+ expect(code).toBe(3); // posture covers the paid effect, not the destructive rebuildexpect(await columnDims()).toBe(FROM_DIMS);} finally {await engine.unsetConfig('spend.posture');