Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(pglite-repair): ask through requireConsent with the risk, backup and undo on every surface (C2)
garrytan2f04533c8cb9
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex a8622d99e1..d26541e9e6 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -40,7 +40,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/persistence-delegate.ts` — shared CLI receipt/error rendering and lazy engine lifecycle for capture/forget/call. `reportPersistenceCliError` owns the write exit verdict (`writeErrorExitCode` in `persistence/write-wait.ts`: pending exits 10 with `poll_command`, 0 with `--accept-pending`); callers never overwrite it. Shared op dispatch and CLI_ONLY dispatch both attempt persistence IPC before connecting. `runDeferredPersistenceCommand` drains/disconnects only an engine actually acquired by the fallback. Capture submits raw content and explicit event/provenance/precondition fields to the capture operation; the owner materializes default slug/time once. Forget uses the frozen verb with an opaque fact ID and stable request UUID. `scripts/generate-flag-registry.ts` excludes this pure router from recursive flag harvesting and records forget's deeper reason/request-id flags explicitly. Real subprocess coverage: `test/persistence-cli-delegation.test.ts`.-- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Its confirmation prompt (and `src/commands/reinit-pglite.ts`'s) writes to stderr so `--json` stdout stays clean, refuses non-TTY stdin in-prompt (defense-in-depth behind the caller-side "Non-TTY environment requires --yes" guard), resolves `false` on EOF/close instead of parking forever on a closed or piped stdin, and cleans up its listeners; `--yes`/`-y` stays the non-interactive path. The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.+- `src/commands/pglite-repair.ts` — `gbrain pglite-repair`: the manual surface for WAL repair (`--dry-run | --yes | --json | --path <dir>`; CLI_ONLY + SELF_HELP; returns an exit code via `setCliExitVerdict`, never `process.exit`). Never connects an engine — works when the DB won't open and when auto-repair is disabled. `--dry-run` is strictly read-only. Consent (agent operator wave C2) goes through `requireConsent` via `consentGate` (`src/core/consent-cli.ts`): effect `destructive`, bound to a `plan_hash` over the data dir, its WAL segment names and a stale postmaster.pid (`--dry-run --json` reports it; the approved command is `--yes --expect <plan_hash>`, so a bare `--yes` re-asks). The risk text (WAL tail may be lost, indexes not rebuilt, the sibling `.wal-repair-backup-<ts>` folder, the undo command from `restoreCommand`) is printed on stderr, carried by the consent payload and the dry run, and the receipt adds `restore_command` with the real backup path. Non-TTY without approval changes nothing and exits 3 with the consent payload; the TTY prompt is interaction.readLine on stderr (EOF/timeout = decline). `src/commands/reinit-pglite.ts` asks the same way (destructive, plan bound to the brain path and target model/width, the `.bak` restore command in the risk text; the `.bak` collision is refused before asking). The real run validates BEFORE locking (`acquireLock` mkdirs the data dir — a typo'd `--path` must not create directories), refuses a live lock holder (pre-lock diagnosis names the PID; a live `gbrain serve` is called out), refuses a reaped acquisition (`refused_reaped_lock` — no `--force` by design: force-removing `.gbrain-lock` would reopen the concurrent-writer hole), re-validates under the lock, repairs with episode-backup reuse, and records the attempt in the sidecar. Pinned by `test/pglite-repair-command.serial.test.ts`.- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.diff --git a/src/commands/pglite-repair.ts b/src/commands/pglite-repair.tsindex abc5f1fd13..40eae454e1 100644--- a/src/commands/pglite-repair.ts+++ b/src/commands/pglite-repair.ts@@ -8,7 +8,8 @@* skipped. `--dry-run` is strictly read-only. The real run:** validate (BEFORE locking — `acquireLock` mkdirs the data dir, and a- * typo'd --path must not create directories) → TTY confirm unless --yes →+ * typo'd --path must not create directories) → requireConsent (TTY prompt+ * or `--yes --expect <plan_hash>`; non-TTY otherwise exits 3) →* acquireLock (refuses a reaped acquisition: a corrupt-lock reap cannot* prove the holder is dead, and WAL surgery under a possibly-live writer is* never correct; a live `gbrain serve` holder fast-fails via@@ -20,7 +21,11 @@* repair does not help — `gbrain reinit-pglite` is the rebuild path.*/-import { promptYesNo } from '../core/confirm-prompt.ts';+import { join } from 'node:path';+import { shellQuote } from '../core/agent-output.ts';+import { currentExitCode } from '../core/cli-force-exit.ts';+import { computePlanHash, type PlanSelection } from '../core/consent.ts';+import { consentGate } from '../core/consent-cli.ts';import { loadConfig, gbrainPath } from '../core/config.ts';import { acquireLock, releaseLock, LiveServeLockError, msSinceLastReap } from '../core/pglite-lock.ts';import {@@ -49,6 +54,11 @@ function parseArgs(args: string[]): RepairCmdOpts {const a = args[i];if (a === '--dry-run') opts.dryRun = true;else if (a === '--yes' || a === '-y') opts.yes = true;+ else if (a === '--expect') {+ // The plan_hash the user approved; requireConsent reads it from the raw args.+ const val = args[++i];+ if (val === undefined || val.startsWith('-')) throw new UnknownFlagError('--expect requires the plan_hash from --dry-run or the refusal');+ }else if (a === '--json') opts.jsonOutput = true;else if (a === '--path') {const val = args[++i];@@ -78,11 +88,16 @@ pre-repair pg_wal + pg_control are kept in a sibling backup directory.Usage:gbrain pglite-repair --dry-run [--json] [--path <dir>] diagnose only- gbrain pglite-repair [--yes] [--json] [--path <dir>] repair (confirm on TTY)+ gbrain pglite-repair [--yes --expect <plan_hash>] [--json] [--path <dir>]+ repair (asks first)Flags:--dry-run Read-only diagnosis of the data dir. Mutates nothing.- --yes, -y Skip the confirmation prompt (required in non-TTY runs).+ --yes --expect <plan_hash>+ Repair without a prompt, only after the user agreed to the plan+ --dry-run printed. Without it a non-interactive run changes+ nothing and exits 3 with the consent payload (relay its+ user_message to the user).--json Machine-readable output on stdout.--path <dir> Repair a specific data dir (default: the configured brain).@@ -101,6 +116,31 @@ function emitError(jsonOutput: boolean, code: string, message: string): void {}}+const BACKUP_SUFFIX = '.wal-repair-backup-';++const REPAIR_RISK = 'Data files are preserved; transactions not checkpointed before the corruption may be lost, and indexes are '+ + 'not rebuilt (run gbrain reindex --vectors afterwards). Before the reset the current pg_wal and postmaster.pid are moved, '+ + `and pg_control copied, into a sibling <data-dir>${BACKUP_SUFFIX}<timestamp> folder (or this incident's existing backup); nothing is deleted.`;++/** The exact undo of a WAL reset: the reset pg_wal set aside, the backed-up pg_wal and pg_control put back (run with gbrain stopped). */+export function restoreCommand(dataDir: string, backupPath: string): string {+ return [+ ['mv', join(dataDir, 'pg_wal'), join(backupPath, 'pg_wal.reset-aside')],+ ['mv', join(backupPath, 'pg_wal'), join(dataDir, 'pg_wal')],+ ['cp', join(backupPath, 'pg_control'), join(dataDir, 'global', 'pg_control')],+ ].map(argv => shellQuote(argv)).join(' && ');+}++/** The diagnosed state an approval binds: the data dir, its WAL segments and the stale postmaster.pid. */+function repairPlan(dataDir: string, d: { verdict: string; walSegments: string[]; postmasterPid: unknown }): { selection: PlanSelection; plan_hash: string } {+ const selection: PlanSelection = {+ brain: dataDir, source: null, operation: 'pglite-repair',+ records: [...d.walSegments.map(id => ({ id: `pg_wal/${id}` })), ...(d.postmasterPid ? [{ id: 'postmaster.pid' }] : [])],+ parameters: { verdict: d.verdict }, effects: ['destructive'],+ };+ return { selection, plan_hash: computePlanHash(selection) };+}+export async function runPgliteRepair(args: string[]): Promise<number> {let opts: RepairCmdOpts;try {@@ -148,6 +188,7 @@ export async function runPgliteRepair(args: string[]): Promise<number> {data_dir: dataDir,validation,diagnosis,+ ...(validation.ok ? { plan_hash: repairPlan(dataDir, diagnosis).plan_hash, risk: REPAIR_RISK } : {}),}));} else {console.log(`PGLite data dir: ${dataDir}`);@@ -163,12 +204,13 @@ export async function runPgliteRepair(args: string[]): Promise<number> {}if (!validation.ok) {console.log(` Repairable: NO — ${validation.detail}`);- } else if (diagnosis.verdict === 'looks-healthy') {- console.log(' Repairable: yes — but no unclean-shutdown markers found; repair is likely');- console.log(' unnecessary. Run `gbrain pglite-repair --yes` ONLY if PGLite fails to open');- console.log(' with `RuntimeError: Aborted()` (repair discards the un-checkpointed WAL tail).');} else {- console.log(' Repairable: yes — run `gbrain pglite-repair --yes` to reset the WAL in place.');+ const approved = shellQuote(['gbrain', 'pglite-repair', ...(opts.customPath ? ['--path', opts.customPath] : []), '--yes', '--expect', repairPlan(dataDir, diagnosis).plan_hash]);+ console.log(diagnosis.verdict === 'looks-healthy'+ ? ' Repairable: yes — but no unclean-shutdown markers found; repair is likely unnecessary. Repair ONLY if PGLite fails to open with `RuntimeError: Aborted()`.'+ : ' Repairable: yes — a WAL reset in place should let it open.');+ console.log(` Risk: ${REPAIR_RISK}`);+ console.log(` The repair is the user's decision. Once they agree: ${approved}`);}}return 0;@@ -199,26 +241,27 @@ export async function runPgliteRepair(args: string[]): Promise<number> {return 1;}- if (!opts.yes) {- if (!process.stdin.isTTY) {- emitError(opts.jsonOutput, 'no_tty_no_yes', 'Non-TTY environment requires --yes to confirm the WAL reset.');- return 1;- }- console.error(`About to reset the WAL of ${dataDir} in place.`);- console.error('Data files are preserved; un-checkpointed transactions may be lost.');- console.error('The current pg_wal + pg_control are kept in a sibling backup directory.');- // Prompt on stderr (not the confirm-prompt default of stdout): stdout- // stays clean for --json payloads.- const confirmed = await promptYesNo('Repair now? [y/N] ', { output: process.stderr });- if (!confirmed) {- if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'aborted', reason: 'user_declined' }));- } else {- console.log('Aborted. Data dir untouched.');- }- return 0;- }- }+ // Consent (A4): destructive, bound to the diagnosed state (data dir + its+ // WAL segments). The approved command is `--yes --expect <plan_hash>`; a+ // bare `--yes` re-asks. The risk text names the backup and the undo.+ process.stderr.write(`About to reset the WAL of ${dataDir} in place.\n${REPAIR_RISK}\n`);+ const plan = repairPlan(dataDir, diagnosis);+ const auth = await consentGate({+ command: 'pglite-repair',+ effects: ['destructive'],+ actor: 'agent',+ what: `Reset the write-ahead log of the PGLite brain at ${dataDir}`,+ why: `The brain does not open cleanly (${diagnosis.verdict}: ${diagnosis.detail}); a WAL reset (pg_resetwal semantics) lets it open with its data files intact.`,+ risk: `${REPAIR_RISK} Undo, with gbrain stopped: ${restoreCommand(dataDir, `${dataDir}${BACKUP_SUFFIX}<timestamp>`)} (the run prints the exact backup path and restore command).`,+ user_message: `Your brain at ${dataDir} cannot open cleanly. Reset its write-ahead log now? Pages and facts on disk are kept, `+ + 'but changes from just before the crash may be lost; the old log is kept in a backup folder.',+ argv: ['gbrain', 'pglite-repair', ...(opts.customPath ? ['--path', opts.customPath] : []), ...(opts.jsonOutput ? ['--json'] : [])],+ preview_argv: ['gbrain', 'pglite-repair', ...(opts.customPath ? ['--path', opts.customPath] : []), '--dry-run', '--json'],+ plan_hash: plan.plan_hash,+ selection: plan.selection,+ args: opts.yes ? [...args, '--yes'] : args,+ }, { json: opts.jsonOutput });+ if (!auth) return currentExitCode();// Short timeout: the diagnosis said the lock is free; if we still can't get// it quickly, someone raced us — refuse rather than queue behind them.@@ -316,6 +359,7 @@ export async function runPgliteRepair(args: string[]): Promise<number> {wal_seg_size: receipt.walSegSize,repaired_at: receipt.repairedAt,backups_on_disk: listRepairBackups(dataDir),+ restore_command: restoreCommand(receipt.dataDir, receipt.backupPath),next_command: 'gbrain reindex --vectors',}));} else {@@ -324,6 +368,7 @@ export async function runPgliteRepair(args: string[]): Promise<number> {console.log(` Backup: ${receipt.backupPath}${receipt.reusedEpisodeBackup ? ' (reused this episode’s existing backup)' : ''}`);console.log(` Reset segment: ${receipt.resetSegment} (timeline ${receipt.timelineId}, ${receipt.walSegSize / (1024 * 1024)}MB segments)`);console.log(' Un-checkpointed transactions may be lost, and indexes are not rebuilt.');+ console.log(` Undo (with gbrain stopped): ${restoreCommand(receipt.dataDir, receipt.backupPath)}`);console.log(' Next: rebuild the vector indexes with `gbrain reindex --vectors` (it reopens the brain), then run `gbrain doctor`.');}return 0;diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex d79926db8f..5d8e08c74c 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -525,11 +525,10 @@ export function buildPgliteInitErrorMessage(' https://github.com/garrytan/gbrain/issues/223.\n' +repairContextLine(ctx ?? { repair: 'not-attempted' }) + '\n' +' Recovery ladder:\n' +- ' 1. gbrain pglite-repair --dry-run (diagnose, mutates nothing)\n' +- ' gbrain pglite-repair --yes (in-place WAL repair, data preserved)\n' +- ' 2. Rebuild from your brain repo: `gbrain reinit-pglite` (or manually:\n' +- ' back up ~/.gbrain, move brain.pglite aside, `gbrain init --pglite`,\n' +- ' re-add sources + `gbrain sync` + `gbrain embed`).\n' ++ ' 1. gbrain pglite-repair --dry-run (diagnose, mutates nothing; prints the\n' ++ ' in-place WAL repair command to run once the user agrees, data preserved)\n' ++ ' 2. Last resort, only with the user\'s agreement: `gbrain reinit-pglite`\n' ++ ' (rebuilds from the brain repo; DB-only pages and facts are not carried over).\n' +' 3. Switch engines (docs/ENGINES.md): `gbrain init --supabase` or\n' +' native Postgres.\n' +' Run `gbrain doctor` for a full diagnosis.';diff --git a/test/pglite-repair-command.serial.test.ts b/test/pglite-repair-command.serial.test.tsindex 45f4a9e0cf..f03eaec4fd 100644--- a/test/pglite-repair-command.serial.test.ts+++ b/test/pglite-repair-command.serial.test.ts@@ -127,6 +127,17 @@ function deadPid(): number {throw new Error('could not obtain a provably-dead PID after 5 spawns');}+/** The plan_hash `--dry-run --json` reports for a data dir (what `--yes --expect` must name). */+async function approvedPlanHash(dir: string): Promise<string> {+ const cap = captureConsole();+ try {+ await runPgliteRepair(['--path', dir, '--dry-run', '--json']);+ } finally {+ cap.restore();+ }+ return parseJsonLine(cap.logs).plan_hash as string;+}+const backupDirsBeside = (dir: string): string[] =>readdirSync(join(dir, '..')).filter((n) => n.startsWith(`${basename(dir)}.wal-repair-backup-`));@@ -250,7 +261,8 @@ describe('gbrain pglite-repair — refusals (validate before lock, never mkdir aconst cap = captureConsole();let rc: number;try {- rc = await runPgliteRepair(['--path', dir, '--yes', '--json']);+ // Approved for the diagnosed plan, so the refusal under test is the lock gate's.+ rc = await runPgliteRepair(['--path', dir, '--yes', '--expect', await approvedPlanHash(dir), '--json']);} finally {cap.restore();}@@ -294,28 +306,34 @@ describe('gbrain pglite-repair — refusals (validate before lock, never mkdir a});describe('gbrain pglite-repair — TTY + config gates', () => {- test('8. non-TTY without --yes refuses: exit 1, no_tty_no_yes, zero mutation', async () => {+ test('8. non-TTY without the bound approval refuses: exit 3, consent payload with risk + undo, zero mutation', async () => {const dir = join(tmp('gbrain-repair-notty-'), 'brain.pglite');makeFakeLayout(dir);- // Pin stdin to non-TTY: under `bun test` in a terminal stdin can still be- // a TTY, which would route into the interactive confirm instead.- const origTty = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');- Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true });const cap = captureConsole();+ let stdout = '';+ const write = process.stdout.write;+ process.stdout.write = ((c: string | Uint8Array) => { stdout += String(c); return true; }) as typeof process.stdout.write;let rc: number;+ let bare: number;try {- rc = await runPgliteRepair(['--path', dir, '--json']); // no --yes+ rc = await withEnv({ GBRAIN_NON_INTERACTIVE: '1' }, () => runPgliteRepair(['--path', dir, '--json'])); // no --yes+ // A bare --yes retry is not the user's approval of this plan.+ bare = await withEnv({ GBRAIN_NON_INTERACTIVE: '1' }, () => runPgliteRepair(['--path', dir, '--yes', '--json']));} finally {+ process.stdout.write = write;cap.restore();- if (origTty) Object.defineProperty(process.stdin, 'isTTY', origTty);- else delete (process.stdin as unknown as Record<string, unknown>).isTTY;+ process.exitCode = 0;}- expect(rc).toBe(1);- const out = parseJsonLine(cap.logs);- expect(out.status).toBe('error');- expect(out.code).toBe('no_tty_no_yes');+ expect(rc).toBe(3);+ expect(bare).toBe(3);+ const out = JSON.parse(stdout.slice(0, stdout.indexOf('\n}\n') + 2));+ expect(out).toMatchObject({ code: 'confirmation_required', effects: ['destructive'], actor: 'agent' });+ expect(out.risk).toContain('may be lost');+ expect(out.risk).toContain('Undo, with gbrain stopped: mv');+ expect(out.fix.argv).toEqual(['gbrain', 'pglite-repair', '--path', dir, '--json', '--yes', '--expect', out.plan_hash]);+ expect(out.user_message).toContain('Reset its write-ahead log now?');// Refused BEFORE any surgery: no backup dir, no sidecar.expect(backupDirsBeside(dir)).toEqual([]);expect(existsSync(`${dir}.wal-repair-attempt.json`)).toBe(false);@@ -333,10 +351,14 @@ describe('gbrain pglite-repair — TTY + config gates', () => {makeFakeLayout(dir);const cap = captureConsole();+ const origOutTty = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY');+ Object.defineProperty(process.stdout, 'isTTY', { value: true, configurable: true });try {- await withInteractiveAnswer('y', () => runPgliteRepair(['--path', dir, '--json']));+ await withEnv({ GBRAIN_INTERACTIVE: '1' }, () => withInteractiveAnswer('y', () => runPgliteRepair(['--path', dir, '--json'])));} finally {cap.restore();+ if (origOutTty) Object.defineProperty(process.stdout, 'isTTY', origOutTty);+ else delete (process.stdout as unknown as Record<string, unknown>).isTTY;}const out = parseJsonLine(cap.logs);@@ -346,6 +368,7 @@ describe('gbrain pglite-repair — TTY + config gates', () => {// correctly-honored "y" (repair attempted on this fake layout) is// covered by other tests in this file.expect(out).not.toEqual({ status: 'aborted', reason: 'user_declined' });+ expect(out.code).not.toBe('confirmation_required');}, 30_000);test('10. no --path with a non-pglite configured engine: exit 1, not_pglite', async () => {@@ -396,11 +419,19 @@ describe('gbrain pglite-repair — the happy path (real PGLite)', () => {writeFileSync(join(walDir, seg), Buffer.alloc(1024, 0xff));}- // 3) Repair in place.+ // 3) Repair in place, approved for the diagnosed plan (C2: --yes --expect <plan_hash>).+ const dry = captureConsole();+ try {+ expect(await runPgliteRepair(['--path', dir, '--dry-run', '--json'])).toBe(0);+ } finally {+ dry.restore();+ }+ const planHash = parseJsonLine(dry.logs).plan_hash as string;+ expect(planHash).toMatch(/^ph_/);const cap = captureConsole();let rc: number;try {- rc = await runPgliteRepair(['--path', dir, '--yes', '--json']);+ rc = await runPgliteRepair(['--path', dir, '--yes', '--expect', planHash, '--json']);} finally {cap.restore();}@@ -412,6 +443,7 @@ describe('gbrain pglite-repair — the happy path (real PGLite)', () => {expect(receipt.reset_segment).toMatch(/^[0-9A-F]{24}$/);expect(existsSync(receipt.backup_path)).toBe(true);expect(existsSync(join(receipt.backup_path, 'pg_wal'))).toBe(true);+ expect(receipt.restore_command).toContain(`${receipt.backup_path}/pg_wal`);// 4) The repaired dir opens WITHOUT auto-repair firing, data intact.const engine2 = new PGLiteEngine();@@ -473,28 +505,17 @@ describe('gbrain pglite-repair — argument + quarantine hardening (adversarial});describe('gbrain pglite-repair — interactive confirm wiring (#4318 residual)', () => {- test('uses the shared confirm-prompt helper, not a local reimplementation', () => {- // This file's own inline `promptYesNo` had the same close-before-resolve- // race that #4318 fixed in sync-cost-gate.ts/reindex-code.ts: `rl.close()`- // fired inside the answer callback synchronously triggered an unguarded- // `rl.on('close', () => resolve(false))`, so a typed "y" was silently- // read as decline. This pins the fix at the source level — a future- // change that reintroduces a local `promptYesNo`/`createInterface` here- // (rather than importing the shared, race-free helper) fails this test,- // even though `test/confirm-prompt.test.ts` cannot see this file at all.- // test-reads-source-ok[structural]: pins that the local reimplementation stays gone- // and the shared helper is wired with the exact stderr-preserving args —- // there's no exported/injectable seam to assert this behaviorally.+ test('asks through the consent primitive, not a local prompt', () => {+ // #4318 class: a local promptYesNo/readline here once read a typed "y" as+ // decline. The prompt now lives in requireConsent (interaction.readLine on+ // stderr, EOF/timeout = decline); this pins that no local prompt returns.+ // test-reads-source-ok[structural]: no injectable seam names the prompt implementation.const src = readFileSync(join(import.meta.dir, '../src/commands/pglite-repair.ts'), 'utf8');- expect(src).toContain("import { promptYesNo } from '../core/confirm-prompt.ts';");+ expect(src).toContain("import { consentGate } from '../core/consent-cli.ts';");expect(src).not.toMatch(/\bfunction promptYesNo\b/);+ expect(src).not.toContain('promptYesNo(');expect(src).not.toContain("from 'readline'");- // The call site itself must keep the prompt on stderr — confirm-prompt's- // default `output` is stdout, and `--json` callers depend on stdout- // staying machine-readable-only. Checking the import above isn't enough:- // dropping `{ output: process.stderr }` from this call would still pass- // that assertion while leaking the prompt into --json output.- expect(src).toContain("await promptYesNo('Repair now? [y/N] ', { output: process.stderr });");expect(src).not.toContain("from 'node:readline'");});+;});