Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(repair): an empty preview's printed apply succeeds for every preview-bound kind (#6351)
time-attack94e1e1a48381
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.mdindex ae97eb973f..9e0c9ab913 100644--- a/docs/architecture/key-files/runtime.md+++ b/docs/architecture/key-files/runtime.md@@ -22,7 +22,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and every request carries `X-Gbrain-Client: gbrain-remote-cli/<version>` so hosts serve it full search/query rows (it never sends `fields`); `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). A /token 429 is `rate_limited` with `RemoteMcpErrorDetail.retry_after_s` parsed from Retry-After (`parseRetryAfterSeconds` in `remote-mcp-probe.ts`); any other non-auth /token failure is `token`, never `discovery`. `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `ignoredRemoteParams(res)` lists params the host reported ignoring (`_meta.warnings` `unknown_param` entries plus the warning text blocks after `content[0]`); the CLI fails when a sent scope param (`source_id`, `all_sources`) is among them and warns for other ignored params the op declares. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`. Agent contract v1: a tool_error body is `content[0]` alone; `extractToolErrorDetail` keeps `code` (legacy `error`) plus `canonical_code`, `reason`, `why`, `fix`, `notices`, `contract_version`; `RemoteMcpError.toJSON` adds `code` (derived via `canonicalCodeFor` for old servers) and those fields when present; `extractNotices(res)` reads `_meta.gbrain_notices` or prefixed blocks. Skew pinned by `test/thin-client-contract-skew.test.ts` with a frozen v0.60.37.0 parser. A status-only host's 503 `serve_status_only` envelope from OAuth discovery or `/token` (`status_only` on the `remote-mcp-probe.ts` failure, with `retry_after_s`) becomes `RemoteMcpError` detail (`code`, `reason`, `why`, `fix`), which the CLI renders through the agent envelope and the thin-client doctor reports on its check (`test/remote-mcp-status-only.test.ts`).- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten. Git sync holds (`sync-hold`), their per-source summary while it counts any, `sync-hold-retry` requests, `sync-import-provenance` rows, the blocked-cursor conversion log, the #6188 fence census (`fence-candidate`, `fence-scan`) and paid fence-repair attempt claims and memos (`fence-repair-attempt`) of a live source incarnation survive GC (they leave on resolution; a retired incarnation's rows age out), and `connector-hold-retry` requests never expire.-- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).+- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms`, `repair extractor-facts` and the other preview-bound repair kinds such as `repair ontology-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`). #6351: `loadApprovedSet` takes an optional lazy `emptyHash` (the hash a preview of the same selection prints when it finds nothing, from current state including source incarnations); with no saved row and a matching hash it returns an empty set, so the apply command an empty preview prints succeeds while a changed incarnation still refuses `preview_changed`. The eight preview-bound repair kinds without a local `emptyPlanHash` (stale-atoms, captured-facts, conversation-labels, extractor-facts, failed-writes, frontmatter, loop-facts, ontology-facts) pass it. Pinned by `test/repair-empty-preview-apply.test.ts`.- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `abortOnCleanupPass(name)` wraps that for child work: it returns `{ signal, release }`, the signal aborts when the cleanup pass runs (sync's `git pull` uses it), and `release` deregisters it. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`. #5062: `registerSignalOwner(name, onSignal)` lets a long-lived command (`jobs supervisor`, `jobs work`) claim SIGTERM/SIGHUP/SIGPIPE and a broken stdout/stderr pipe: while an owner is registered the generic handler only forwards the signal (no cleanup pass, no exit), so the owner can drain while still holding its DB lock and then exit through `triggerCleanupAndExit`; crashes keep the generic path. Pinned by `test/process-cleanup.test.ts` and `test/e2e/supervisor-stop-drain-5062.test.ts`.diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 409b130c48..976851ba20 100644--- a/src/core/persistence/preview-approval.ts+++ b/src/core/persistence/preview-approval.ts@@ -48,6 +48,13 @@ export interface ApprovedSetKey {hash: string;/** The read-only command that prints a fresh preview, filled with the caller's real flags. */previewCommand: string;+ /**+ * #6351: the hash a preview of the same selection prints when it finds+ * nothing, computed from current state (source incarnations included). A+ * preview that found nothing saves no set; its hash still approves applying+ * nothing while that state holds.+ */+ emptyHash?: () => Promise<string>;}export interface ApprovedSet<T> {@@ -92,6 +99,9 @@ export async function loadApprovedSet<T>(engine: BrainEngine, key: ApprovedSetKeFROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,[PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash), String(APPROVAL_MAX_AGE_DAYS)]);const saved = row?.completed_keys?.[0];+ if (!row && key.emptyHash && await key.emptyHash() === key.hash) {+ return { command: key.command, hash: key.hash, items: [], approved_at: new Date().toISOString() };+ }if (!row || row.fresh !== true || saved?.command !== key.command || saved.hash !== key.hash || !Array.isArray(saved.items)) {throw previewChangedError(key.hash, key.previewCommand);}diff --git a/src/core/repair/captured-facts.ts b/src/core/repair/captured-facts.tsindex f0c87ff823..5b639c7f4b 100644--- a/src/core/repair/captured-facts.ts+++ b/src/core/repair/captured-facts.ts@@ -268,7 +268,11 @@ export const capturedFactsRepair: RepairHandler = {`Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#explicit-only-repair-kinds');}- const approved = await loadApprovedSet<CapturedFactsPage>(engine, { command: 'captured-facts', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<CapturedFactsPage>(engine, { command: 'captured-facts', hash: opts.expect, previewCommand: command,+ emptyHash: async () => {+ const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1').catch(() => []);+ return previewHash(['captured-facts-v1', brain?.brain_id ?? 'host', scope.source_ids, includeAmbiguous, []]);+ } });const scopeKey = JSON.stringify(scope.source_ids);if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) {throw previewChangedError(opts.expect, command);diff --git a/src/core/repair/conversation-labels.ts b/src/core/repair/conversation-labels.tsindex 8bac06b986..08b4e22145 100644--- a/src/core/repair/conversation-labels.ts+++ b/src/core/repair/conversation-labels.ts@@ -232,7 +232,9 @@ export const conversationLabelsRepair: RepairHandler = {`Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#conversation-labels');}- const approved = await loadApprovedSet<LabelPage>(engine, { command: 'conversation-labels', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<LabelPage>(engine, { command: 'conversation-labels', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash({ kind: 'conversation-labels-v1', brain_id: scope.brain_id, sources: (await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids])),+ selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous }, facts: [], pages: [] }) });const scopeKey = JSON.stringify(scope.source_ids);if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) {throw previewChangedError(opts.expect, command);diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.tsindex 019f75d20c..8016f7bfb4 100644--- a/src/core/repair/extractor-facts.ts+++ b/src/core/repair/extractor-facts.ts@@ -306,7 +306,8 @@ export const extractorFactsRepair: RepairHandler = {`Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#explicit-only-repair-kinds');}- const approved = await loadApprovedSet<ExtractorFactsPage>(engine, { command: 'extractor-facts', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<ExtractorFactsPage>(engine, { command: 'extractor-facts', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(await hashParts(engine, scope, includeAmbiguous, [])) });const scopeKey = JSON.stringify(scope.source_ids);if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) {throw previewChangedError(opts.expect, command);diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex a97f9e45d1..b1c4877a79 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -205,7 +205,8 @@ export const failedWritesRepair: RepairHandler = {`Preview first: ${command} — show the user the listing, then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#failed-writes');}- const approved = await loadApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<ApprovedWrite>(engine, { command: 'failed-writes', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash({ kind: 'failed-writes-v1', brain_id: scope.brain_id, sources: (await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids])), selection: { source_ids: scope.source_ids }, replay: [] }) });if (approved.items.some(write => JSON.stringify(write.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);const items = approved.items.map((write, index) => item(write, opts.expect!, index === approved.items.length - 1));return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };diff --git a/src/core/repair/frontmatter.ts b/src/core/repair/frontmatter.tsindex 3eecf383e4..3be4b5f072 100644--- a/src/core/repair/frontmatter.ts+++ b/src/core/repair/frontmatter.ts@@ -399,7 +399,8 @@ export const frontmatterRepair: RepairHandler = {throw opError('invalid_params', 'gbrain repair frontmatter --apply writes only the set a preview printed.',`Preview first: ${shellQuote(preview)} — show the user the per-file diffs, then run the apply command it prints (with --yes --expect <preview-hash>).`);}- const approved = await loadApprovedSet<ApprovedSetItem>(engine, { command: 'frontmatter', hash: opts.expect, previewCommand: shellQuote(preview) });+ const approved = await loadApprovedSet<ApprovedSetItem>(engine, { command: 'frontmatter', hash: opts.expect, previewCommand: shellQuote(preview),+ emptyHash: async () => previewHash({ kind: 'frontmatter-v1', brain_id: scope.brain_id, sources: (await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids])), selection, items: [] }) });if (approved.items.some(entry => !sameSelection(entry.selection, selection))) throw previewChangedError(opts.expect, shellQuote(preview));for (const sourceId of new Set(approved.items.map(entry => entry.source_id))) {const named = await unfinishedSyncPath(engine, sourceId, new Set(approved.items.filter(entry => entry.source_id === sourceId).flatMap(entry => [entry.path, entry.source_path])));diff --git a/src/core/repair/loop-facts.ts b/src/core/repair/loop-facts.tsindex 64c97fdc7d..7d0fe20114 100644--- a/src/core/repair/loop-facts.ts+++ b/src/core/repair/loop-facts.ts@@ -52,7 +52,8 @@ export const loopFactsRepair: RepairHandler = {`Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#explicit-only-repair-kinds');}- const approved = await loadApprovedSet<ApprovedLoop>(engine, { command: 'loop-facts', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<ApprovedLoop>(engine, { command: 'loop-facts', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash({ kind: 'loop-facts-v1', brain_id: scope.brain_id, sources: (await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids])), selection: { source_ids: scope.source_ids }, loops: [] }) });if (approved.items.some(loop => JSON.stringify(loop.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);const items = approved.items.map(({ selection: _selection, ...loop }, index) => item(loop, opts.expect!, index === approved.items.length - 1));return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };diff --git a/src/core/repair/ontology-facts.ts b/src/core/repair/ontology-facts.tsindex ebf3084be5..90af3ae459 100644--- a/src/core/repair/ontology-facts.ts+++ b/src/core/repair/ontology-facts.ts@@ -143,7 +143,8 @@ export const ontologyFactsRepair: RepairHandler = {`Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#explicit-only-repair-kinds');}- const approved = await loadApprovedSet<ApprovedFact>(engine, { command: 'ontology-facts', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<ApprovedFact>(engine, { command: 'ontology-facts', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash({ kind: 'ontology-facts-v1', brain_id: scope.brain_id, sources: (await engine.executeRaw<{ id: string; incarnation: string }>('SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids])), selection: { source_ids: scope.source_ids }, facts: [] }) });if (approved.items.some(f => JSON.stringify(f.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);const items = approved.items.map(({ selection: _selection, ...f }, index) => item(f, opts.expect!, index === approved.items.length - 1));return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.tsindex 13f2405de7..ad86f13b2c 100644--- a/src/core/repair/stale-atoms.ts+++ b/src/core/repair/stale-atoms.ts@@ -147,7 +147,8 @@ export const staleAtomsRepair: RepairHandler = {`Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,'docs/guides/repair.md#explicit-only-repair-kinds');}- const approved = await loadApprovedSet<ApprovedStaleAtom>(engine, { command: 'stale-atoms', hash: opts.expect, previewCommand: command });+ const approved = await loadApprovedSet<ApprovedStaleAtom>(engine, { command: 'stale-atoms', hash: opts.expect, previewCommand: command,+ emptyHash: async () => previewHash(await hashParts(engine, scope, [])) });if (approved.items.some(atom => JSON.stringify(atom.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);const items = approved.items.map(({ selection: _selection, ...atom }, index) => item(atom, opts.expect!, index === approved.items.length - 1));return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };diff --git a/test/repair-empty-preview-apply.test.ts b/test/repair-empty-preview-apply.test.tsnew file mode 100644index 0000000000..82de8dbfe8--- /dev/null+++ b/test/repair-empty-preview-apply.test.ts@@ -0,0 +1,66 @@+/**+ * #6351: a preview that finds nothing prints an apply command with an+ * `--expect` hash. That command must succeed (applying nothing) for every+ * preview-bound kind, and an old empty hash must still refuse once the+ * source's incarnation changed (the generalised #6377 convention).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { runRepairCommand } from '../src/commands/repair.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const KINDS = ['stale-atoms', 'captured-facts', 'conversation-labels', 'extractor-facts', 'failed-writes',+ 'frontmatter', 'loop-facts', 'ontology-facts', 'fences', 'slug-conflicts'];++interface RepairJson { results: Array<{ affected: number; apply_command: string; applied: number }> }++let engine: PGLiteEngine;+let home: string;+beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ home = mkdtempSync(join(tmpdir(), 'gbrain-empty-preview-'));+}, 60_000);+afterAll(async () => {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});+beforeEach(async () => { await resetPgliteState(engine); });++async function repair(args: string[]): Promise<RepairJson> {+ const lines: string[] = [];+ const original = console.log;+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };+ try {+ await withEnv({ GBRAIN_HOME: home, CLAUDE_CONFIG_DIR: join(home, 'claude') }, () => runRepairCommand(engine, [...args, '--json']));+ } finally { console.log = original; }+ return JSON.parse(lines.join('\n')) as RepairJson;+}+const applyArgs = (json: RepairJson) => json.results[0].apply_command.split(' ').slice(2);++describe('empty preview → printed apply command', () => {+ for (const kind of KINDS) {+ test(`${kind}: the apply it prints succeeds and applies nothing`, async () => {+ const preview = await repair([kind]);+ expect(preview.results[0].affected).toBe(0);+ expect(preview.results[0].apply_command).toContain('--expect ');+ const applied = await repair(applyArgs(preview));+ expect(applied.results[0].applied).toBe(0);+ });+ }++ test('an empty hash refuses with preview_changed after the source incarnation changes', async () => {+ const preview = await repair(['stale-atoms']);+ await engine.executeRaw("UPDATE sources SET incarnation = gen_random_uuid() WHERE id = 'default'");+ let error: unknown;+ try { await repair(applyArgs(preview)); } catch (e) { error = e; }+ expect(error).toBeInstanceOf(OperationError);+ expect((error as OperationError).code).toBe('preview_changed');+ });+});