Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(reindex-frontmatter): --json never implies consent; one source-scoped selection for preview, hash and apply (C3)

garrytanc63b4d0ee817
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 26f38a5820..a8622d99e1 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -57,7 +57,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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-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).
+- `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).
- `src/commands/reindex-multimodal.ts` — `gbrain reindex --multimodal [--limit N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]`. Walks `content_chunks WHERE embedding_multimodal IS NULL`, batches via `embedMultimodalSafe` (partial-failure-aware), persists. Lock via `tryAcquireDbLock` (360min) so a concurrent autopilot embed phase can't race it. Cost prompt + Ctrl-C grace window in TTY. `GBRAIN_NO_REEMBED=1` bypass. Checkpoint at `~/.gbrain/reindex-multimodal-checkpoint.json` for resume. Auto-flip prompt at coverage=100% completion (TTY: interactive; non-TTY: stderr hint with a paste-ready command).
diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsv
index c9cda0130c..758c64527c 100644
--- a/scripts/agent-contract-baselines/interactive-io.tsv
+++ b/scripts/agent-contract-baselines/interactive-io.tsv
@@ -9,7 +9,6 @@ src/commands/init.ts 4
src/commands/jobs-watch.ts 2
src/commands/migrate-embeddings.ts 2
src/commands/notability-eval.ts 1
-src/commands/reindex-frontmatter.ts 1
src/commands/reindex-search-vector.ts 1
src/commands/report.ts 1
src/commands/upgrade.ts 1
diff --git a/src/commands/reindex-frontmatter.ts b/src/commands/reindex-frontmatter.ts
index 7d83a4995c..9efe69890d 100644
--- a/src/commands/reindex-frontmatter.ts
+++ b/src/commands/reindex-frontmatter.ts
@@ -14,10 +14,12 @@
* orchestrator uses; one source of truth for the backfill logic).
*
* Flags mirror `reindex-code`:
- * --source <id> Scope to one sources row. Omit = all pages.
+ * --source <id> Scope to one sources row (preview, hash and apply). Omit = all pages.
* --slug-prefix P Scope to slugs starting with P (e.g. 'meetings/').
- * --dry-run Print what WOULD change, no DB writes.
- * --yes Skip the confirmation prompt (required for non-TTY non-JSON).
+ * --dry-run Print what WOULD change (and its plan_hash), no DB writes.
+ * --yes --expect H Apply the plan the user approved without a prompt. Without
+ * it a non-interactive run (--json included) changes nothing
+ * and exits 3 with the consent payload.
* --json Machine-readable result envelope.
* --force Re-apply even when computed value matches existing
* (bypasses no-op-on-equal guard).
@@ -25,13 +27,16 @@
import type { BrainEngine } from '../core/engine.ts';
import { backfillEffectiveDate } from '../core/backfill-effective-date.ts';
-import { createInterface } from 'readline';
+import { computePlanHash, type PlanSelection } from '../core/consent.ts';
+import { consentGate } from '../core/consent-cli.ts';
export interface ReindexFrontmatterOpts {
sourceId?: string;
slugPrefix?: string;
dryRun?: boolean;
yes?: boolean;
+ /** `--expect <plan_hash>`: the plan the user approved (from the dry run or the refusal). */
+ expect?: string;
json?: boolean;
force?: boolean;
/**
@@ -48,89 +53,95 @@ export interface ReindexFrontmatterOpts {
}
export interface ReindexFrontmatterResult {
- 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';
examined: number;
updated: number;
fallback: number;
durationSec: number;
source_filter?: string;
slug_prefix?: string;
+ /** Dry run: the hash an approved apply names with `--yes --expect <plan_hash>`. */
+ plan_hash?: string;
}
-async function countAffected(
- engine: BrainEngine,
- slugPrefix: string | undefined,
- sourceId: string | undefined,
-): Promise<number> {
- const where: string[] = [];
- const params: unknown[] = [];
- if (slugPrefix) {
- params.push(slugPrefix.replace(/[\\%_]/g, (c) => '\\' + c) + '%');
- where.push(`slug LIKE $${params.length} ESCAPE '\\\\'`);
- }
- if (sourceId) {
- params.push(sourceId);
- where.push(`source_id = $${params.length}`);
- }
- const sql = `SELECT COUNT(*)::text AS n FROM pages${where.length ? ' WHERE ' + where.join(' AND ') : ''}`;
- const rows = await engine.executeRaw<{ n: string }>(sql, params);
- return Number(rows[0]?.n ?? 0);
+/** The rows one invocation would change: the selection its preview, plan hash and apply share. */
+async function previewSelection(engine: BrainEngine, opts: ReindexFrontmatterOpts) {
+ const changes: Array<{ id: string; revision: string }> = [];
+ const r = await backfillEffectiveDate(engine, {
+ slugPrefix: opts.slugPrefix,
+ sourceId: opts.sourceId,
+ dryRun: true,
+ force: opts.force,
+ onChange: row => changes.push({ id: String(row.id), revision: `${row.effective_date ?? ''}|${row.effective_date_source ?? ''}` }),
+ });
+ const selection: PlanSelection = {
+ brain: 'host',
+ source: opts.sourceId ?? null,
+ operation: 'reindex-frontmatter',
+ records: changes,
+ parameters: { slug_prefix: opts.slugPrefix ?? null, force: opts.force === true },
+ effects: ['destructive'],
+ };
+ return { result: r, selection, plan_hash: computePlanHash(selection) };
}
-async function confirm(prompt: string): Promise<boolean> {
- if (!process.stdin.isTTY) return false; // No TTY = require --yes
- const rl = createInterface({ input: process.stdin, output: process.stderr });
- return new Promise(resolve => {
- rl.question(prompt + ' [y/N] ', (ans: string) => {
- rl.close();
- resolve(ans.trim().toLowerCase() === 'y');
- });
- });
+/** The scope flags an approved or preview command repeats. */
+function scopeArgv(opts: ReindexFrontmatterOpts): string[] {
+ return [
+ ...(opts.sourceId ? ['--source', opts.sourceId] : []),
+ ...(opts.slugPrefix ? ['--slug-prefix', opts.slugPrefix] : []),
+ ...(opts.force ? ['--force'] : []),
+ ];
}
+/**
+ * Preview (dry run) or apply. Apply previews the same selection first, asks
+ * through requireConsent (destructive: it overwrites stored effective_date
+ * values, bound to the plan hash of exactly the rows that would change), and
+ * then writes only those rows. `--json` never implies consent. Returns
+ * `confirmation_required` when consent was refused (the refusal is printed,
+ * exit verdict 3).
+ */
export async function runReindexFrontmatter(
engine: BrainEngine,
opts: ReindexFrontmatterOpts,
+ args: readonly string[] = [...(opts.yes ? ['--yes'] : []), ...(opts.expect ? ['--expect', opts.expect] : [])],
): Promise<ReindexFrontmatterResult> {
- const total = await countAffected(engine, opts.slugPrefix, opts.sourceId);
-
+ const preview = await previewSelection(engine, opts);
+ const scope = { slug_prefix: opts.slugPrefix, source_filter: opts.sourceId };
if (opts.dryRun) {
- // Library function with dryRun=true counts would-update without writing.
- const r = await backfillEffectiveDate(engine, {
- slugPrefix: opts.slugPrefix,
- dryRun: true,
- force: opts.force,
- // Note: the library doesn't support sourceId filter today; documented
- // as a v0.30+ enhancement. CLI surfaces the param so the future
- // refinement is non-breaking.
- maxRows: total > 0 ? total : undefined,
- });
- return {
- status: 'dry_run',
- examined: r.examined,
- updated: r.updated,
- fallback: r.fallback,
- durationSec: r.durationSec,
- slug_prefix: opts.slugPrefix,
- source_filter: opts.sourceId,
- };
+ const r = preview.result;
+ return { status: 'dry_run', examined: r.examined, updated: r.updated, fallback: r.fallback, durationSec: r.durationSec, ...scope,
+ plan_hash: preview.plan_hash };
}
-
- // Confirm in TTY non-yes flow.
- if (!opts.yes && !opts.json && total > 100) {
- const ok = await confirm(`Reindex effective_date on ${total} page(s)? Force=${opts.force ? 'yes' : 'no'}.`);
- if (!ok) {
- return {
- status: 'cancelled',
- examined: 0, updated: 0, fallback: 0, durationSec: 0,
- slug_prefix: opts.slugPrefix,
- source_filter: opts.sourceId,
- };
- }
+ const n = preview.selection.records.length;
+ if (n === 0) {
+ return { status: 'ok', examined: preview.result.examined, updated: 0, fallback: 0, durationSec: preview.result.durationSec, ...scope };
}
+ const where = `${opts.sourceId ? ` in source ${opts.sourceId}` : ''}${opts.slugPrefix ? ` under ${opts.slugPrefix}` : ''}`;
+ const auth = await consentGate({
+ command: 'reindex-frontmatter',
+ effects: ['destructive'],
+ actor: 'agent',
+ what: `Rewrite the effective date of ${n} page(s)${where}`,
+ why: 'Re-derives pages.effective_date from each page\'s frontmatter, filename and timestamps with the current precedence rules.',
+ risk: `Overwrites the stored effective_date and effective_date_source of ${n} page(s); the previous values are not kept, `
+ + 'and date-ordered recall and timelines change accordingly. Pages, chunks and frontmatter are not touched.',
+ user_message: `Recompute the effective date of ${n} page(s)${where}? Their current stored dates are replaced.`,
+ argv: ['gbrain', 'reindex-frontmatter', ...scopeArgv(opts), ...(opts.json ? ['--json'] : [])],
+ preview_argv: ['gbrain', 'reindex-frontmatter', ...scopeArgv(opts), '--dry-run', '--json'],
+ plan_hash: preview.plan_hash,
+ selection: preview.selection,
+ args,
+ }, { json: opts.json === true });
+ if (!auth) return { status: 'confirmation_required', examined: preview.result.examined, updated: 0, fallback: 0, durationSec: preview.result.durationSec, ...scope };
+
const r = await backfillEffectiveDate(engine, {
slugPrefix: opts.slugPrefix,
+ sourceId: opts.sourceId,
+ onlyIds: new Set(preview.selection.records.map(rec => Number(rec.id))),
force: opts.force,
fresh: true, // CLI is explicit; ignore checkpoint from prior orchestrator runs
onBatch: ({ batch, lastId, rowsTouched, cumulative }) => {
@@ -140,15 +151,7 @@ export async function runReindexFrontmatter(
},
});
- return {
- status: 'ok',
- examined: r.examined,
- updated: r.updated,
- fallback: r.fallback,
- durationSec: r.durationSec,
- slug_prefix: opts.slugPrefix,
- source_filter: opts.sourceId,
- };
+ return { status: 'ok', examined: r.examined, updated: r.updated, fallback: r.fallback, durationSec: r.durationSec, ...scope };
}
/**
@@ -169,6 +172,7 @@ export async function reindexFrontmatterCli(engine: BrainEngine, args: string[])
else if (a === '--slug-prefix') opts.slugPrefix = args[++i];
else if (a === '--dry-run') opts.dryRun = true;
else if (a === '--yes' || a === '-y') opts.yes = true;
+ else if (a === '--expect') opts.expect = args[++i];
else if (a === '--json') opts.json = true;
else if (a === '--force') opts.force = true;
else if (a === '--workers' || a === '--concurrency') {
@@ -183,6 +187,7 @@ export async function reindexFrontmatterCli(engine: BrainEngine, args: string[])
}
const result = await runReindexFrontmatter(engine, opts);
+ if (result.status === 'confirmation_required') return;
if (opts.json) {
console.log(JSON.stringify(result, null, 2));
} else {
@@ -192,5 +197,4 @@ export async function reindexFrontmatterCli(engine: BrainEngine, args: string[])
`fallback=${result.fallback} dur=${result.durationSec.toFixed(1)}s`,
);
}
- if (result.status === 'cancelled') process.exit(1);
}
diff --git a/src/commands/reinit-pglite.ts b/src/commands/reinit-pglite.ts
index 45f30790c1..6ee28b292a 100644
--- a/src/commands/reinit-pglite.ts
+++ b/src/commands/reinit-pglite.ts
@@ -12,13 +12,15 @@ import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-gua
* everything; a width change with preserved data is
* `gbrain migrate embeddings --to <model> --dim <N>`.
*
- * Destructive. Consent via requireConsent (A4): a TTY prompt or `--yes`;
- * non-TTY without it exits 3 with the consent payload. `--json` for scripts.
+ * Destructive. Consent via requireConsent (A4): a TTY prompt, or
+ * `--yes --expect <plan_hash>` (bound to this brain and target); non-TTY
+ * without it exits 3 with the consent payload. `--json` for scripts.
*/
import { existsSync, statSync, rmSync } from 'fs';
import { dirname } from 'path';
import { loadConfig, loadConfigFileOnly, gbrainPath } from '../core/config.ts';
+import { computePlanHash, type PlanSelection } from '../core/consent.ts';
import { consentGateOrExit } from '../core/consent-cli.ts';
interface ReinitOpts {
@@ -84,8 +86,9 @@ export async function runReinitPglite(args: string[]): Promise<void> {
console.log('');
}
- // Consent (A4): destructive. The whole brain is the selection and the target
- // is fully named by the argv, so there is no record-level plan to bind.
+ // Consent (A4): destructive, bound to the plan (this brain path and the new
+ // model/width): the approved command is `--yes --expect <plan_hash>`, so a
+ // bare `--yes` retry re-asks instead of wiping.
// Non-TTY without --yes refuses with exit 3 and the consent payload; --json
// never implies consent; EOF/timeout at the TTY prompt is a decline.
const bakPath = dbPath + '.bak';
@@ -100,6 +103,9 @@ export async function runReinitPglite(args: string[]): Promise<void> {
const reinitArgv = ['gbrain', 'reinit-pglite', '--embedding-model', opts.embeddingModel,
'--embedding-dimensions', String(opts.embeddingDimensions),
...(opts.customPath ? ['--path', opts.customPath] : []), ...(opts.noSync ? ['--no-sync'] : [])];
+ const selection: PlanSelection = { brain: dbPath, source: null, operation: 'reinit-pglite', records: [{ id: dbPath }],
+ parameters: { embedding_model: opts.embeddingModel, embedding_dimensions: opts.embeddingDimensions, sync: !opts.noSync },
+ effects: ['destructive'] };
await consentGateOrExit({
command: 'reinit-pglite', effects: ['destructive'], actor: 'agent',
what: `Wipe and re-create the PGLite brain at ${dbPath}`,
@@ -110,6 +116,8 @@ export async function runReinitPglite(args: string[]): Promise<void> {
user_message: `Wipe and re-create your brain (${sizeMb > 0 ? `${sizeMb} MB, ` : ''}${dbPath}) for ${opts.embeddingModel}? `
+ `DB-only pages and remembered facts are not carried over; a backup is kept at ${bakPath}.`,
argv: reinitArgv,
+ plan_hash: computePlanHash(selection),
+ selection,
args: opts.yes ? [...args, '--yes'] : args,
}, { json: opts.jsonOutput });
@@ -298,7 +306,8 @@ flag nor the config file provides a value, the command fails.
Optional:
--path <path> Active brain path (default: ~/.gbrain/brain.pglite).
- --yes / -y Authorize the wipe without a prompt (ask the user first).
+ --yes --expect <plan_hash> Authorize the wipe without a prompt, only after the user
+ approved it (the refusal prints the exact command).
--no-sync Skip the post-init \`gbrain sync\`.
--json Emit structured JSON output on stdout.
@@ -310,8 +319,9 @@ Examples:
gbrain reinit-pglite --embedding-model openai:text-embedding-3-large \\
--embedding-dimensions 1536 --no-sync
- # Rebuild with the model/dimensions already in the config file:
- gbrain reinit-pglite --yes
+ # Rebuild with the model/dimensions already in the config file (prints
+ # the plan and asks; non-interactive callers get the approved command):
+ gbrain reinit-pglite
The old brain is preserved as \`<path>.bak\`. To roll back, mv it back.
diff --git a/src/core/backfill-effective-date.ts b/src/core/backfill-effective-date.ts
index 722d691835..6793636188 100644
--- a/src/core/backfill-effective-date.ts
+++ b/src/core/backfill-effective-date.ts
@@ -46,6 +46,19 @@ export interface BackfillOpts {
* scope to a subset. Undefined = no filter.
*/
slugPrefix?: string;
+ /**
+ * Optional source filter (one `sources.id`). The preview, the plan hash and
+ * the apply of `gbrain reindex-frontmatter --source` walk this one selection.
+ */
+ sourceId?: string;
+ /**
+ * Apply only to these page ids (the approved selection). Rows outside it are
+ * examined but never written, so a page that starts matching after the
+ * preview is not touched without a new approval.
+ */
+ onlyIds?: ReadonlySet<number>;
+ /** Called for every row the walk would change (dry run) or changed (apply), with its prior value. */
+ onChange?: (row: { id: number; slug: string; effective_date: string | null; effective_date_source: string | null }) => void;
/**
* When true, recompute even if existing effective_date matches what
* the chain would produce. Default false (no-op-on-equal saves writes).
@@ -136,7 +149,11 @@ export async function backfillEffectiveDate(
const start = Date.now();
const slugPrefix = opts.slugPrefix?.replace(/[\\%_]/g, (c) => '\\' + c) ?? null;
- let lastId = await getCheckpoint(engine, opts.fresh ?? false);
+ // A scoped walk (slug prefix, source, approved ids) never reads or writes the
+ // orchestrator's brain-wide checkpoint: resuming an unscoped walk from a
+ // scoped walk's last id would skip every other source's rows.
+ const scoped = Boolean(opts.slugPrefix || opts.sourceId || opts.onlyIds);
+ let lastId = await getCheckpoint(engine, (opts.fresh ?? false) || scoped);
let examined = 0;
let updated = 0;
let fallback = 0;
@@ -158,18 +175,23 @@ export async function backfillEffectiveDate(
// Keyset pagination: WHERE id > last_id ORDER BY id LIMIT N. Single-direction
// walk; safe under concurrent inserts (new rows show up at the tail).
- const slugFilter = slugPrefix
- ? `AND slug LIKE $2 ESCAPE '\\\\'`
- : '';
const params: unknown[] = [lastId];
- if (slugPrefix) params.push(slugPrefix + '%');
+ let slugFilter = '';
+ if (slugPrefix) {
+ params.push(slugPrefix + '%');
+ slugFilter += ` AND slug LIKE $${params.length} ESCAPE '\\\\'`;
+ }
+ if (opts.sourceId) {
+ params.push(opts.sourceId);
+ slugFilter += ` AND source_id = $${params.length}`;
+ }
params.push(limit);
const limitParam = `$${params.length}`;
const rows = await engine.executeRaw<PageRow>(
`SELECT id, slug, frontmatter, import_filename, effective_date, effective_date_source, created_at, updated_at
FROM pages
- WHERE id > $1 ${slugFilter}
+ WHERE id > $1${slugFilter}
ORDER BY id
LIMIT ${limitParam}`,
params,
@@ -212,12 +234,14 @@ export async function backfillEffectiveDate(
const sourcesMatch = (r.effective_date_source ?? null) === (computed.source ?? null);
if (!opts.force && datesMatch && sourcesMatch) continue;
+ if (opts.onlyIds && !opts.onlyIds.has(Number(r.id))) continue;
await tx.executeRaw(
`UPDATE pages SET effective_date = $1::timestamptz, effective_date_source = $2 WHERE id = $3`,
[computed.date ? computed.date.toISOString() : null, computed.source, r.id],
);
touched++;
+ opts.onChange?.(r);
if (computed.source === 'fallback') fallback++;
}
});
@@ -237,8 +261,9 @@ export async function backfillEffectiveDate(
});
const existingMs = r.effective_date ? new Date(r.effective_date).getTime() : null;
const computedMs = computed.date ? computed.date.getTime() : null;
- if (existingMs !== computedMs || (r.effective_date_source ?? null) !== (computed.source ?? null)) {
+ if (opts.force || existingMs !== computedMs || (r.effective_date_source ?? null) !== (computed.source ?? null)) {
touched++;
+ opts.onChange?.(r);
}
if (computed.source === 'fallback') fallback++;
}
@@ -247,12 +272,12 @@ export async function backfillEffectiveDate(
updated += touched;
lastId = rows[rows.length - 1].id;
batchNum++;
- if (!opts.dryRun) await setCheckpoint(engine, lastId);
+ if (!opts.dryRun && !scoped) await setCheckpoint(engine, lastId);
opts.onBatch?.({ batch: batchNum, lastId, rowsTouched: touched, cumulative: examined });
}
// Walk done; clear the checkpoint so the next manual run starts fresh.
- if (!opts.dryRun) await clearCheckpoint(engine);
+ if (!opts.dryRun && !scoped) await clearCheckpoint(engine);
return {
examined,
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index d39b92219b..943287bf12 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -46,7 +46,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--operations', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],
@@ -98,9 +98,9 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'reindex': ['--accept-pending', '--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--http', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--wait', '--workers', '--yes'],
- 'reindex-frontmatter': ['--brain', '--concurrency', '--dry-run', '--force', '--help', '--json', '--slug-prefix', '--source', '--workers', '--yes'],
+ 'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
- 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
+ 'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--expect', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-cost', '--max-sources', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--trust', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
diff --git a/test/effective-date-historical.test.ts b/test/effective-date-historical.test.ts
index 3c01a9fe1d..b9509a6f1b 100644
--- a/test/effective-date-historical.test.ts
+++ b/test/effective-date-historical.test.ts
@@ -42,7 +42,9 @@ test('an explicit 1851 event_date is stored as the effective date', async () =>
test('reindex-frontmatter recomputes a page stored under the old floor', async () => {
await importFromContent(engine, SLUG, PAGE, { noEmbed: true });
await engine.executeRaw(`UPDATE pages SET effective_date = created_at, effective_date_source = 'fallback' WHERE slug = $1`, [SLUG]);
- const result = await runReindexFrontmatter(engine, { yes: true, json: true });
+ // C3: an apply binds the previewed plan (--yes --expect <plan_hash>).
+ const { plan_hash } = await runReindexFrontmatter(engine, { dryRun: true, json: true });
+ const result = await runReindexFrontmatter(engine, { yes: true, expect: plan_hash, json: true });
expect(result.updated).toBe(1);
expect(await stored()).toEqual({ effective_date: '1851-10-18', effective_date_source: 'event_date' });
});
diff --git a/test/reindex-frontmatter-consent.test.ts b/test/reindex-frontmatter-consent.test.ts
new file mode 100644
index 0000000000..7e6fc6231b
--- /dev/null
+++ b/test/reindex-frontmatter-consent.test.ts
@@ -0,0 +1,106 @@
+/**
+ * C3 (agent operator wave): `gbrain reindex-frontmatter` asks before it
+ * rewrites stored dates, and its preview, plan hash and apply share one
+ * selection.
+ *
+ * Protects: `--json` never implies consent (it used to skip the prompt, so a
+ * non-interactive `--json` run rewrote every page); `--source` scopes the
+ * apply, not just the count (the apply used to walk every source); the
+ * approval binds the exact rows the preview listed (`--yes --expect`), a
+ * changed row re-asks with `preview_changed`, and a page that starts matching
+ * after the preview is not touched. Fails on the base at the --json and
+ * two-source assertions.
+ */
+import { afterAll, beforeAll, beforeEach, expect, spyOn, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { runReindexFrontmatter } from '../src/commands/reindex-frontmatter.ts';
+import { backfillEffectiveDate } from '../src/core/backfill-effective-date.ts';
+import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('other','other') ON CONFLICT DO NOTHING");
+});
+
+const page = (date: string) => `---\ntype: note\ntitle: t\nevent_date: '${date}'\n---\n\nBody.\n`;
+
+/** Two sources, each with a page whose stored date is stale (the fallback). */
+async function seed() {
+ await importFromContent(engine, 'notes/a', page('2001-02-03'), { noEmbed: true });
+ await importFromContent(engine, 'notes/b', page('2004-05-06'), { noEmbed: true, sourceId: 'other' });
+ await engine.executeRaw("UPDATE pages SET effective_date = '2020-01-01', effective_date_source = 'fallback'");
+}
+
+const dates = async () => Object.fromEntries((await engine.executeRaw<{ k: string; d: string }>(
+ "SELECT source_id || ':' || slug AS k, to_char(effective_date AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS d FROM pages ORDER BY 1")).map(r => [r.k, r.d]));
+
+async function quiet<T>(fn: () => Promise<T>): Promise<{ value: T; stdout: string; exit: number }> {
+ let stdout = '';
+ const out = spyOn(process.stdout, 'write').mockImplementation(((c: string | Uint8Array) => { stdout += String(c); return true; }) as never);
+ const err = spyOn(process.stderr, 'write').mockImplementation((() => true) as never);
+ setCliExitVerdict(0);
+ try {
+ const value = await withEnv({ GBRAIN_NON_INTERACTIVE: '1' }, fn);
+ return { value, stdout, exit: currentExitCode() };
+ } finally {
+ out.mockRestore(); err.mockRestore(); setCliExitVerdict(0);
+ }
+}
+
+test('--json never implies consent: a non-interactive apply changes nothing and exits 3 with the consent payload', async () => {
+ await seed();
+ const before = await dates();
+ const r = await quiet(() => runReindexFrontmatter(engine, { json: true }));
+ expect(r.value.status).toBe('confirmation_required');
+ expect(r.exit).toBe(3);
+ const payload = JSON.parse(r.stdout);
+ expect(payload).toMatchObject({ code: 'confirmation_required', effects: ['destructive'], actor: 'agent' });
+ expect(payload.fix.argv).toEqual(['gbrain', 'reindex-frontmatter', '--json', '--yes', '--expect', payload.plan_hash]);
+ expect(payload.preview.argv).toEqual(['gbrain', 'reindex-frontmatter', '--dry-run', '--json']);
+ expect(payload.user_message).toContain('2 page(s)');
+ expect(await dates()).toEqual(before);
+
+ // A bare --yes retry is not the approval: the destructive plan must be named.
+ const bare = await quiet(() => runReindexFrontmatter(engine, { yes: true, json: true }));
+ expect(bare.value.status).toBe('confirmation_required');
+ expect(await dates()).toEqual(before);
+});
+
+test('two sources: --source scopes preview, hash and apply; the unselected source is unchanged', async () => {
+ await seed();
+ const preview = await runReindexFrontmatter(engine, { sourceId: 'other', dryRun: true, json: true });
+ expect(preview).toMatchObject({ status: 'dry_run', examined: 1, updated: 1, source_filter: 'other' });
+ const applied = await quiet(() => runReindexFrontmatter(engine, { sourceId: 'other', yes: true, expect: preview.plan_hash, json: true }));
+ expect(applied.value).toMatchObject({ status: 'ok', updated: 1 });
+ expect(await dates()).toEqual({ 'default:notes/a': '2020-01-01', 'other:notes/b': '2004-05-06' });
+});
+
+test('the approval binds the previewed rows: a changed row re-asks; a newly matching row is not touched', async () => {
+ await seed();
+ const { plan_hash } = await runReindexFrontmatter(engine, { dryRun: true, json: true });
+ await engine.executeRaw("UPDATE pages SET effective_date = '2019-01-01' WHERE slug = 'notes/a'");
+ await expect(quiet(() => runReindexFrontmatter(engine, { yes: true, expect: plan_hash, json: true })))
+ .rejects.toMatchObject({ code: 'preview_changed' });
+ expect(await dates()).toEqual({ 'default:notes/a': '2019-01-01', 'other:notes/b': '2020-01-01' });
+
+ const fresh = await runReindexFrontmatter(engine, { sourceId: 'default', dryRun: true, json: true });
+ const ok = await quiet(() => runReindexFrontmatter(engine, { sourceId: 'default', yes: true, expect: fresh.plan_hash, json: true }));
+ expect(ok.value).toMatchObject({ status: 'ok', updated: 1 });
+ expect((await dates())['default:notes/a']).toBe('2001-02-03');
+
+ // The apply writes only the approved ids: a stale row outside them stays as it is.
+ const r = await backfillEffectiveDate(engine, { onlyIds: new Set<number>(), fresh: true });
+ expect(r.updated).toBe(0);
+ expect((await dates())['other:notes/b']).toBe('2020-01-01');
+});
diff --git a/test/reindex-frontmatter-pglite-spawn.serial.test.ts b/test/reindex-frontmatter-pglite-spawn.serial.test.ts
index 5458c757e7..e3c56dc498 100644
--- a/test/reindex-frontmatter-pglite-spawn.serial.test.ts
+++ b/test/reindex-frontmatter-pglite-spawn.serial.test.ts
@@ -95,7 +95,11 @@ describe('reindex-frontmatter + backfill on PGLite (#1963 double-connect)', () =
// Pre-fix: exits 1 after the 30s PGLite lock timeout, naming ITSELF as
// the holder. Post-fix: reuses cli.ts's connected engine and succeeds.
- const reindex = await runCli(['reindex-frontmatter', '--yes', '--json'], env, 120_000);
+ // C3: the apply binds the plan its dry run printed (--yes --expect <plan_hash>).
+ const preview = await runCli(['reindex-frontmatter', '--dry-run', '--json'], env, 120_000);
+ expect(preview.exitCode).toBe(0);
+ const planHash = JSON.parse(preview.stdout).plan_hash as string;
+ const reindex = await runCli(['reindex-frontmatter', '--yes', '--expect', planHash, '--json'], env, 120_000);
const reindexOut = reindex.stdout + reindex.stderr;
if (reindex.exitCode !== 0) {
console.error('--- reindex-frontmatter stdout ---\n' + reindex.stdout);