Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(repair): gbrain repair rename-identity carries an old page's identity onto its new slug, or closes the pair (#6729)

garrytane479ec2dd4b3
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 8468a9aa57..d03e9d644c 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -72,6 +72,8 @@ export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <i
gbrain repair stuck-recovery [--source <id>] [--request-id <uuid>]
[--keep prior|disk --apply --expect <preview-hash> --yes] [--json]
gbrain repair ghost-pages --source <id> [--apply --expect <preview-hash> --yes] [--json]
+ gbrain repair rename-identity --source <id> [--slug <new-slug> [--from <old-slug>] [--close]
+ [--apply --expect <preview-hash> --yes]] [--json]
${REPAIR_CONTENT_HELP}
Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.
@@ -100,6 +102,8 @@ Options:
file-drift: narrow the selected pages by canonical file path (repeatable; an exact path, or, on file-drift
only, a glob with * within a segment and ** across segments, e.g. --only 'concepts/**'); the hash and the apply command cover them.
--slug <slug> fences, file-drift: select a database page by slug (repeatable); the hash covers the selection.
+ rename-identity: the new page of the one open pair to preview (--from <old-slug> when two pairs share it).
+ --close rename-identity: release the pair's purge hold instead of carrying its identity; nothing moves.
--prefer file|database, --request <id>, --all-drifted, --class <name>
file-drift: the side that wins; select conflict receipts by request id (repeatable), or every page
still drifted (refused across mixed drift classes unless --class keeps one). --keep is refused here:
@@ -117,7 +121,7 @@ Options:
stuck-recovery --apply: the version of each blocked file to keep (the user's choice from the preview).
--request-id <uuid>
stuck-recovery: resolve only this request's recovery (default: every blocked record of the source).
- --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages --apply: the user agreed to the previewed changes (destructive
+ --yes frontmatter, conversation-labels, stuck-recovery, ghost-pages, rename-identity --apply: the user agreed to the previewed changes (destructive
consent; without it a terminal asks, and a non-interactive run exits 3 with the consent payload).
--json Machine-readable output with a stable shape (frontmatter: every per-file diff).
@@ -128,20 +132,21 @@ With no kind, previews every kind. Run it on the brain host.
Held files (the content lane, then the two-pass frontmatter repair): docs/guides/repair.md#held-files.
Malformed facts/takes fences (preview, apply, undo): docs/guides/repair.md#fences.
A write recovery blocked on unexpected_file_bytes: docs/guides/repair.md#stuck-recovery.
-Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.`;
+Live pages whose canonical file is missing (ghost pages): docs/guides/repair.md#ghost-pages.
+Renames whose identity sync did not keep (rename-identity): docs/guides/live-sync.md#renaming-a-page.`;
-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force']);
-const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than']);
+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous', '--diff', '--yes', '--no-llm', '--all-drifted', '--include-failures', '--force', '--close']);
+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip', '--slug', '--max-usd', '--prefer', '--request', '--class', '--since', '--keep', '--request-id', '--older-than', '--from']);
/** Flags only some kinds accept, with the kinds that do. */
const KIND_FLAGS: Record<string, readonly string[]> = {
- '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages'],
- '--slug': ['fences', 'file-drift'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
+ '--only': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--skip': ['frontmatter', 'fences', 'slug-conflicts', 'file-drift', CONTENT_LANE], '--diff': ['frontmatter', 'fences', 'slug-conflicts', CONTENT_LANE], '--yes': ['frontmatter', 'conversation-labels', 'stuck-recovery', 'ghost-pages', 'rename-identity'],
+ '--slug': ['fences', 'file-drift', 'rename-identity'], '--from': ['rename-identity'], '--close': ['rename-identity'], '--prefer': ['file-drift'], '--request': ['file-drift'], '--all-drifted': ['file-drift'], '--class': ['file-drift'], '--since': ['file-drift'],
'--keep': ['stuck-recovery'], '--request-id': ['stuck-recovery'],
'--older-than': ['receipt-compaction'], '--include-failures': ['receipt-compaction'], '--force': ['receipt-compaction'],
};
const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md',
'--slug': 'notes/a', '--max-usd': '0.50', '--prefer': 'file', '--request': 'REQUEST_UUID', '--class': 'review_required', '--since': '7d', '--keep': 'prior',
- '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d' };
+ '--request-id': '123e4567-e89b-42d3-a456-426614174000', '--older-than': '30d', '--from': 'notes/old' };
/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */
const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,
{ fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });
@@ -149,7 +154,7 @@ const invalid = (message: string, suggestion: string, preview: string[] = ['gbra
interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;
noLlm: boolean; source?: string; limit?: string; expect?: string; maxUsd?: number; only: string[]; skip: string[]; slugs: string[];
allDrifted: boolean; prefer?: 'file' | 'database'; requests: string[]; driftClass?: string; since?: string;
- keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean }
+ keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures: boolean; force: boolean; from?: string; close: boolean }
/** `--max-usd` on a kind that never calls a paid model: the cap belongs to the doctor remediation run. */
function maxUsdRefusal(flag: string, cap: string | undefined, kind: string | undefined): OperationError {
@@ -182,7 +187,7 @@ function fileDriftKeepRefusal(args: string[], keep: string): OperationError {
/** Strict parse: every flag is known, value flags carry a value, at most one kind. */
export function parseRepairArgs(args: string[]): RepairArgs {
const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false, diff: false, yes: false, noLlm: false, only: [], skip: [], slugs: [],
- allDrifted: false, requests: [], includeFailures: false, force: false };
+ allDrifted: false, requests: [], includeFailures: false, force: false, close: false };
const used = new Set<string>();
const positional: string[] = [];
let maxUsdText: string | undefined;
@@ -211,6 +216,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
else if (flag === '--all-drifted') parsed.allDrifted = true;
else if (flag === '--include-failures') parsed.includeFailures = true;
else if (flag === '--force') parsed.force = true;
+ else if (flag === '--close') parsed.close = true;
else parsed.noEmbed = true;
continue;
}
@@ -229,6 +235,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
parsed.prefer = value;
}
else if (flag === '--request') parsed.requests.push(value);
+ else if (flag === '--from') parsed.from = value;
else if (flag === '--class') parsed.driftClass = value;
else if (flag === '--since') {
try { parsed.since = parseSince(value, '--since'); } catch (error) {
@@ -330,7 +337,7 @@ export function renderRepairResult(result: RepairResult, opts: { diff: boolean }
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, slugs, diff, noLlm, maxUsd, limit: limitText,
- prefer, requests, allDrifted, driftClass, since, keep, requestId, olderThan, includeFailures, force } = parseRepairArgs(args);
+ prefer, requests, allDrifted, driftClass, since, keep, requestId, olderThan, includeFailures, force, from, close } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');
// #6712 PR 2: a repair apply is a soak intervention; a file-drift apply is a content decision (soak-counters.ts).
@@ -354,7 +361,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
if (apply && kind && expect && repairSpec(kind as RepairKind).consent === 'destructive') {
const preview = ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), ...only.flatMap(path => ['--only', path]), ...skip.flatMap(path => ['--skip', path]),
...(includeAmbiguous ? ['--include-ambiguous'] : []), ...(requestId ? ['--request-id', requestId] : []),
- ...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : [])];
+ ...(olderThan ? ['--older-than', olderThan] : []), ...(includeFailures ? ['--include-failures'] : []), ...(force ? ['--force'] : []),
+ ...(kind === 'rename-identity' ? [...slugs.flatMap(slug => ['--slug', slug]), ...(from ? ['--from', from] : []), ...(close ? ['--close'] : [])] : [])];
const custom = repairSpec(kind as RepairKind).consentText;
const text = custom ? { ...custom, why: `Preview ${expect}: ${custom.why}`, user_message: `${custom.user_message} (preview ${expect.slice(0, 12)}${keep ? `, keep ${keep}` : ''})` } : {
what: `Rewrite the previewed ${kind} changes on disk and import them`,
@@ -373,7 +381,8 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
...(k === kind && noLlm ? { noLlm } : {}), ...(k === kind && maxUsd !== undefined ? { maxLlmUsd: maxUsd } : {}),
...(k === kind && k === 'file-drift' ? { prefer, requests, allDrifted, driftClass, since } : {}),
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
- ...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}) });
+ ...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),
+ ...(k === kind && k === 'rename-identity' ? { from, close } : {}) });
results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });
if (result.stopped) break;
}
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
index f4f2b3db63..c0934ce930 100644
--- a/src/core/persistence/preview-approval.ts
+++ b/src/core/persistence/preview-approval.ts
@@ -40,7 +40,7 @@ export const PREVIEW_APPROVAL_OP = 'repair-approval';
/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
export const APPROVAL_MAX_AGE_DAYS = 7;
-export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes';
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts' | 'conversation-labels' | 'captured-facts' | 'loop-facts' | 'ontology-facts' | 'failed-writes' | 'split-facts' | 'frontmatter' | 'fences' | 'slug-conflicts' | 'managed-sync-orphans' | 'frontmatter-keys' | 'file-drift' | 'stuck-recovery' | 'ghost-pages' | 'receipt-compaction' | 'accepted-takes' | 'rename-identity';
export interface ApprovedSetKey {
command: PreviewApprovalCommand;
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 6b63c6a6d5..01dbb6bbab 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -96,7 +96,9 @@ export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmb
/** `stuck-recovery`: the version an apply keeps, and the one request a run selects. */
keep?: 'prior' | 'disk'; requestId?: string;
/** `receipt-compaction` (#6696 A9): the age (`72h`, `30d`), failures too, and compaction inside the retention window. */
- olderThan?: string; includeFailures?: boolean; force?: boolean }
+ olderThan?: string; includeFailures?: boolean; force?: boolean;
+ /** `rename-identity` (#6729): the old slug that disambiguates a pair (`--from`), and the close disposition (`--close`). */
+ from?: string; close?: boolean }
export interface RepairHandler {
kind: RepairKind;
@@ -276,7 +278,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[]; slugs?: string[]; noLlm?: boolean;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string;
- keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean;
+ keep?: 'prior' | 'disk'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean;
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */
publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {
@@ -298,7 +300,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
...(opts.prefer ? { prefer: opts.prefer } : {}), ...(opts.requests?.length ? { requests: opts.requests } : {}),
...(opts.allDrifted ? { allDrifted: true } : {}), ...(opts.driftClass ? { driftClass: opts.driftClass } : {}), ...(opts.since ? { since: opts.since } : {}),
...(opts.keep ? { keep: opts.keep } : {}), ...(opts.requestId ? { requestId: opts.requestId } : {}),
- ...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}) };
+ ...(opts.olderThan ? { olderThan: opts.olderThan } : {}), ...(opts.includeFailures ? { includeFailures: true } : {}), ...(opts.force ? { force: true } : {}),
+ ...(opts.from ? { from: opts.from } : {}), ...(opts.close ? { close: true } : {}) };
const plan = await handler.plan(ctx.engine, scope, resumed, planOpts);
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
@@ -321,7 +324,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`
+ `${opts.requestId ? ` --request-id ${opts.requestId}` : ''}${opts.keep ? ` --keep ${opts.keep}` : ''}`
+ `${[...(opts.only ?? []).flatMap(path => ['--only', path]), ...(opts.skip ?? []).flatMap(path => ['--skip', path]),
- ...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.requests ?? []).flatMap(id => ['--request', id]),
+ ...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.from ? ['--from', opts.from] : []), ...(opts.close ? ['--close'] : []),
+ ...(opts.requests ?? []).flatMap(id => ['--request', id]),
...(opts.allDrifted ? ['--all-drifted'] : []), ...(opts.driftClass ? ['--class', opts.driftClass] : []), ...(opts.since ? ['--since', opts.since] : []),
...(opts.prefer ? ['--prefer', opts.prefer] : [])].map(arg => ` ${shellQuote([arg])}`).join('')}`
+ `${opts.includeAmbiguous ? ' --include-ambiguous' : ''}${llm && opts.noLlm ? ' --no-llm' : ''}${llm && opts.maxLlmUsd !== undefined ? ` --max-usd ${opts.maxLlmUsd}` : ''}`
diff --git a/src/core/repair/rename-identity.ts b/src/core/repair/rename-identity.ts
new file mode 100644
index 0000000000..a115d93d43
--- /dev/null
+++ b/src/core/repair/rename-identity.ts
@@ -0,0 +1,271 @@
+/**
+ * `gbrain repair rename-identity --source <id> --slug <new-slug> [--from <old-slug>] [--close]` (#6729): the remedy for an
+ * inexact Git rename that sync split into a delete plus an add because the files did not confirm it
+ * (sync-rename-identity.ts, recorded by sync-identity-downgrades.ts). The operator picks the mapping: the preview names
+ * exactly one open pair (its new page is <new-slug>; `--from` disambiguates), binds the brain, the pair, both page ids,
+ * both revisions and the disposition into its plan hash, and saves it; with no `--slug` it lists the open pairs with
+ * their per-pair preview commands and nothing can be applied. `--apply --expect <hash> --yes` (destructive consent)
+ * re-reads both pages under their page locks and refuses `changed_since_preview` when anything moved. Both dispositions settle
+ * the record (`completed_keys[0].disposition = { kind: remedied | closed, at }`) in the same transaction as the move.
+ *
+ * Dispositions:
+ * - `carry` (default), a deferred true rename: the old page id moves to the new slug, so its version history,
+ * timeline, links and every page-id-keyed row stay on it, and the new file's current content is imported onto it as
+ * an edit (a new version). The provisional page is retired: re-keyed purge-style (`<slug>~purged-<id>`) and
+ * soft-deleted, its history, timeline and edges moved onto the carried page, nothing hard-deleted. An old -> new
+ * slug redirect is recorded, the old page's slug-keyed facts, aliases and withdrawals move, and the record settles `remedied`.
+ * Facts: every fence row of the old page must be in the new file's fence with the same claim, and the provisional
+ * page's stored row there must carry that claim too. A matching pair is one fact: the old row (id, created_at,
+ * valid_from) survives with the new row's fence fields. Anything else (a different claim at a row number, or an old
+ * row the new file does not hold) refuses `fact_rows_collide` before anything is written, naming the rows.
+ * Classic sources only: on a managed brain page tables take writes only through coordinated publications, so carrying
+ * is unavailable there (`managed_remedy_unavailable`): the preview says so and names `--close`, and an apply refuses.
+ * - `close`: settles the record `closed`, which releases the purge hold, and moves nothing. Classic and managed.
+ *
+ * Explicit-only, preview-bound and destructive: `--all`, the maintenance cycle and the doctor remediation plan never
+ * run it (`explicit_kind_required`).
+ */
+import { randomUUID } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { importFile } from '../import-file.ts';
+import { movePageIdReferences } from '../page-state/rename-alias.ts';
+import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { lockedBeliefBatch } from '../belief/writers.ts';
+import { markBeliefCommits } from '../belief/append.ts';
+import { purgedSlug } from '../../commands/sync/rename-collision.ts';
+import { IDENTITY_DOWNGRADE_OP, IDENTITY_HOLD_RELEASE, MANAGED_REMEDY_UNAVAILABLE, identityDowngradeReasonText, identityRemedyParts, identityRestoreArgv, listIdentityDowngrades,
+ renameIdentityPreviewArgv, settleIdentityDowngrade, withIdentityRemedies, type IdentityDowngrade, type IdentityRemedyDisposition, type IdentityRemedyParts } from '../sync-identity-downgrades.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairPlanOptions } from './core.ts';
+
+const DOCS = 'docs/guides/repair.md#rename-identity';
+/** The restore alternative, named only where the source admits a restore (an unbound Postgres source with a checkout does not). */
+const restoreRoute = (record: IdentityDowngrade): string | null => record.restore_available === false ? null : identityRestoreArgv(record).join(' ');
+
+interface Approved { record: IdentityDowngrade; parts: IdentityRemedyParts; source_id: string }
+interface PairItem extends RepairItem { record: IdentityDowngrade; parts: IdentityRemedyParts; hash: string }
+/** One old fence row and what the new file and the provisional page hold at its row number. */
+export interface FenceRowCheck { row: number; old_id: number; old_claim: string; file_claim: string | null; new_id: number | null; new_claim: string | null }
+
+/** The consent payload of `--apply --expect <hash> --yes` (registry `consentText`). */
+export const RENAME_IDENTITY_CONSENT_TEXT = {
+ what: 'Carry the previewed old page\'s identity onto its new page (or, with --close, release its purge hold)',
+ why: 'Sync split an inexact rename into a delete plus an add because the files did not confirm it; the user picked this pair and the preview bound both pages and their revisions.',
+ risk: 'Carry: the old page id takes the new slug and the new file is imported onto it as an edit; the provisional page is retired (soft-deleted under a purged slug, its history and edges moved). '
+ + 'Facts of both pages stay; colliding fence rows refuse before anything changes. Close: the old page is purged once its soft-delete window ends. Undo neither from gbrain; where the source admits a restore, keep the old page instead with gbrain restore <old-slug> --source-id <id> --force.',
+ user_message: 'Carry the old page\'s history, facts and links onto its new page as previewed (or release the hold with --close)? The provisional page is retired',
+};
+
+const previewCommand = (sourceId: string, opts: Pick<RepairPlanOptions, 'slugs' | 'from' | 'close'> = {}) =>
+ ['gbrain', 'repair', 'rename-identity', '--source', sourceId, ...(opts.slugs ?? []).flatMap(slug => ['--slug', slug]), ...(opts.from ? ['--from', opts.from] : []),
+ ...(opts.close ? ['--close'] : [])].join(' ');
+const listFix = (sourceId: string): Action => readFix('Lists the open pairs of the source with their per-pair preview commands; writes nothing.',
+ { argv: ['gbrain', 'repair', 'rename-identity', '--source', sourceId, '--json'] });
+const refuse = (code: string, message: string, suggestion: string, fix: Action, detail?: string) => {
+ const error = new OperationError(code, message, suggestion, DOCS);
+ error.fix = fix;
+ if (detail) error.detail = detail;
+ return error;
+};
+
+/** Claims the facts fences of a page hold, by row number (body and timeline). */
+function fenceClaims(page: { compiled_truth: string; timeline: string | null }): Map<number, string> {
+ const claims = new Map<number, string>();
+ for (const field of [page.compiled_truth, page.timeline ?? '']) for (const fact of parseFactsFence(field).facts) if (!claims.has(fact.rowNum)) claims.set(fact.rowNum, fact.claim);
+ return claims;
+}
+
+/** Each fence row of the old page against the new file's fence (the provisional page's stored body) and the provisional's stored row. */
+export async function fenceRowChecks(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, oldSlug: string, newPageId: number): Promise<FenceRowCheck[]> {
+ const [fresh] = await engine.executeRaw<{ slug: string; compiled_truth: string; timeline: string | null }>('SELECT slug, compiled_truth, timeline FROM pages WHERE id = $1', [newPageId]);
+ if (!fresh) return [];
+ const file = fenceClaims(fresh);
+ const rows = await engine.executeRaw<{ row_num: number; old_id: number | string; old_fact: string; new_id: number | string | null; new_fact: string | null }>(
+ `SELECT o.row_num, o.id AS old_id, o.fact AS old_fact, n.id AS new_id, n.fact AS new_fact FROM facts o
+ LEFT JOIN facts n ON n.source_id = o.source_id AND n.source_markdown_slug = $3 AND n.row_num = o.row_num
+ WHERE o.source_id = $1 AND o.source_markdown_slug = $2 AND o.row_num IS NOT NULL ORDER BY o.row_num`, [sourceId, oldSlug, fresh.slug]);
+ return rows.map(row => ({ row: Number(row.row_num), old_id: Number(row.old_id), old_claim: row.old_fact, file_claim: file.get(Number(row.row_num)) ?? null,
+ new_id: row.new_id == null ? null : Number(row.new_id), new_claim: row.new_fact }));
+}
+
+const collides = (check: FenceRowCheck) => check.file_claim !== check.old_claim || (check.new_claim !== null && check.new_claim !== check.old_claim);
+
+function factRowsCollide(record: IdentityDowngrade, checks: FenceRowCheck[]): OperationError {
+ const rows = checks.filter(collides).map(check => check.file_claim === null
+ ? `row ${check.row} "${check.old_claim}" is not in ${record.to}'s fence`
+ : `row ${check.row}: "${check.old_claim}" on ${record.old_slug}, "${check.new_claim ?? check.file_claim}" on ${record.new_slug}`);
+ return refuse('fact_rows_collide', `Carrying ${record.old_slug} onto ${record.new_slug} would drop facts: ${rows.join('; ')}.`,
+ `Nothing was written. Give each old claim its own row in the ## Facts fence of ${record.to} (or keep it at its row number with the same claim), commit and sync, then preview again: `
+ + `${renameIdentityPreviewArgv(record).join(' ')}. ${restoreRoute(record) ? `Or keep the old page as its own page: ${restoreRoute(record)}; or r` : 'Or r'}elease the hold without carrying: ${renameIdentityPreviewArgv(record, { close: true }).join(' ')}.`,
+ readFix(`Shows ${record.new_slug}'s page with its facts fence, read-only.`, { argv: ['gbrain', 'get', '--source', record.source_id, '--', record.new_slug!] }));
+}
+
+function managedRemedyUnavailable(record: IdentityDowngrade) {
+ const close = renameIdentityPreviewArgv(record, { close: true });
+ return { close, message: `Carrying ${record.old_slug}'s identity onto ${record.new_slug} is unavailable on a managed source; nothing was written.`,
+ suggestion: `Release the purge hold without carrying identity: preview ${close.join(' ')}, then, after the user agrees, run the apply command it prints. `
+ + (restoreRoute(record) ? `Or keep ${record.old_slug} as its own page: ${restoreRoute(record)}.` : '') };
+}
+
+const managedRemedyRefusal = (record: IdentityDowngrade) => {
+ const unavailable = managedRemedyUnavailable(record);
+ return refuse(MANAGED_REMEDY_UNAVAILABLE, unavailable.message, unavailable.suggestion,
+ readFix('Previews closing this pair, which releases the purge hold without carrying identity; writes nothing.', { argv: unavailable.close }));
+};
+
+const changedSincePreview = (record: IdentityDowngrade, why: string) => refuse('changed_since_preview',
+ `The pair ${record.old_slug} -> ${record.new_slug ?? record.to} changed since its preview: ${why}.`,
+ `Nothing was written. Preview again (${renameIdentityPreviewArgv(record).join(' ')}), review the new plan and approve its new hash.`, listFix(record.source_id));
+
+function describe(record: IdentityDowngrade, disposition: IdentityRemedyDisposition): string {
+ return `${record.from} -> ${record.to} (git similarity ${record.similarity}%; ${identityDowngradeReasonText(record.reason)}): ${disposition === 'carry'
+ ? `page ${record.old_page_id} moves from ${record.old_slug} to ${record.new_slug} with ${record.facts} fact(s), ${record.links} link(s) and ${record.aliases} alias(es); the new file is imported onto it and the provisional page is retired`
+ : `the record closes and ${record.old_slug} purges once its soft-delete window ends; nothing moves`}`;
+}
+
+function pairItem(record: IdentityDowngrade, parts: IdentityRemedyParts, hash: string): PairItem {
+ return { cursor: { phase: 1, id: record.old_page_id }, source_id: record.source_id, slug: record.old_slug, chars: 0,
+ action: `${parts.disposition}:rename_identity`, change: { from: record.old_slug, to: record.new_slug ?? record.old_slug }, record, parts, hash };
+}
+
+/** The open pair the options name, or the refusal that says why none or more than one matches. */
+function selectPair(open: IdentityDowngrade[], sourceId: string, opts: RepairPlanOptions): IdentityDowngrade {
+ const slug = opts.slugs?.[0];
+ const matches = open.filter(record => (!slug || record.new_slug === slug) && (!opts.from || record.old_slug === opts.from));
+ const named = [slug ? `new page ${slug}` : '', opts.from ? `old page ${opts.from}` : ''].filter(Boolean).join(' and ');
+ if (!matches.length) throw refuse('invalid_params', `Source ${sourceId} has no open rename-identity pair with ${named}.`,
+ `A pair already carried or closed, or whose old page was restored or purged, is no longer open, and nothing was written; list the open pairs with gbrain repair rename-identity --source ${sourceId}.`, listFix(sourceId));
+ if (matches.length > 1) throw refuse('invalid_params', `${matches.length} open pairs of source ${sourceId} match ${named}.`,
+ `Name the old page too: ${matches.map(record => renameIdentityPreviewArgv(record, { from: true }).join(' ')).join('; ')}.`, listFix(sourceId));
+ const record = matches[0]!;
+ if (!opts.close && !record.new_slug) throw refuse('invalid_params', `The new file ${record.to} of ${record.old_slug} has no page to carry onto.`,
+ `Fix the file and sync so it imports, then preview again; or release the hold now: ${renameIdentityPreviewArgv(record, { close: true }).join(' ')}.`, listFix(sourceId));
+ return record;
+}
+
+async function listingPlan(engine: BrainEngine, sourceId: string, open: IdentityDowngrade[], apply: boolean): Promise<RepairPlan> {
+ if (apply) throw refuse('invalid_params', 'gbrain repair rename-identity --apply needs one pair: --slug <new-slug> (and --from <old-slug> when two pairs share it).',
+ `Preview the pair first: gbrain repair rename-identity --source ${sourceId} --slug <new-slug>, then run the apply command it prints after the user agrees.`, listFix(sourceId));
+ const entries = await withIdentityRemedies(engine, open);
+ return { items: [], residuals: { open_pairs: entries.length },
+ listing: entries.map(record => ({ item: `${record.source_id}:${record.old_slug} -> ${record.new_slug ?? record.to}`, class: record.reason,
+ detail: `preview: ${record.remedy.preview_argv.join(' ')}; hold releases ${record.remedy.hold_releases}` })),
+ details: { pairs: entries.map(record => ({ old_slug: record.old_slug, new_slug: record.new_slug, from: record.from, to: record.to, remedy: record.remedy })), docs: DOCS } };
+}
+
+export const renameIdentityRepair = {
+ kind: 'rename-identity' as const,
+ publication: 'projection' as const,
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ if (scope.source_ids.length !== 1) throw refuse('invalid_params', 'gbrain repair rename-identity needs --source <id>.',
+ 'Each pair belongs to one source; name it, e.g. gbrain repair rename-identity --source default.', readFix('Lists the registered sources.', { argv: ['gbrain', 'sources', 'list', '--json'] }));
+ const sourceId = scope.source_ids[0]!;
+ const options = opts ?? { apply: false };
+ const open = await listIdentityDowngrades(engine, [sourceId]);
+ if (!options.slugs?.length && !options.from) return listingPlan(engine, sourceId, open, options.apply);
+ const record = selectPair(open, sourceId, options);
+ const disposition: IdentityRemedyDisposition = options.close ? 'close' : 'carry';
+ if (disposition === 'carry' && await managedPersistenceEnabled(engine)) {
+ if (options.apply) throw managedRemedyRefusal(record);
+ const unavailable = managedRemedyUnavailable(record);
+ return { items: [], residuals: { carry_unavailable: 1 },
+ listing: [{ item: `${sourceId}:${record.old_slug} -> ${record.new_slug}`, class: MANAGED_REMEDY_UNAVAILABLE, detail: `${unavailable.message} ${unavailable.suggestion}` }],
+ details: { disposition, code: MANAGED_REMEDY_UNAVAILABLE, message: unavailable.message, suggestion: unavailable.suggestion, close_preview: unavailable.close.join(' '),
+ restore: restoreRoute(record), docs: DOCS } };
+ }
+ const parts = await identityRemedyParts(engine, record, disposition);
+ const hash = previewHash(parts);
+ const command = previewCommand(sourceId, options);
+ if (disposition === 'carry') await assertCarryable(engine, record, parts);
+ if (!options.apply) {
+ await saveApprovedSet<Approved>(engine, { command: 'rename-identity', hash }, [{ record, parts, source_id: sourceId }]);
+ return { items: [pairItem(record, parts, hash)], preview_hash: hash, residuals: {},
+ listing: [{ item: `${sourceId}:${record.old_slug} -> ${record.new_slug ?? record.to}`, class: disposition, detail: describe(record, disposition) }],
+ details: { disposition, old: parts.old, new: parts.new, hold_releases: IDENTITY_HOLD_RELEASE,
+ restore: restoreRoute(record), docs: DOCS } };
+ }
+ if (!options.expect) throw refuse('invalid_params', 'gbrain repair rename-identity --apply applies only the pair a preview printed.',
+ `Preview first: ${command} — then, after the user agrees, run the apply command it prints: ${command} --apply --expect <preview-hash> --yes`, listFix(sourceId));
+ const approved = await loadApprovedSet<Approved>(engine, { command: 'rename-identity', hash: options.expect, previewCommand: command });
+ if (hash !== options.expect || approved.items.length !== 1 || approved.items[0]!.record.old_page_id !== record.old_page_id) throw previewChangedError(options.expect, command);
+ return { items: [pairItem(record, parts, hash)].filter(entry => afterCursor(entry.cursor, after)), preview_hash: hash, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { record, parts, hash } = entry as PairItem;
+ try {
+ if (parts.disposition === 'close') {
+ if (previewHash(await identityRemedyParts(ctx.engine, record, 'close')) !== hash) throw changedSincePreview(record, 'a page of the pair changed');
+ if (!await settleIdentityDowngrade(ctx.engine, record.old_page_id, 'closed')) throw changedSincePreview(record, 'its record was settled since the preview');
+ return { applied: true, outcome: 'closed', detail: { old_slug: record.old_slug, purge_hold: 'released' } };
+ }
+ return await carryIdentity(ctx.engine, record, hash);
+ } finally {
+ await clearApprovedSet(ctx.engine, { command: 'rename-identity', hash });
+ }
+ },
+ render(details) {
+ if (Array.isArray(details.pairs)) return [` each pair: preview it by name to carry or close it; guide: ${details.docs}`];
+ if (details.code) return [` ${details.code}: ${details.message}`, ` ${details.suggestion}`];
+ return [` ${details.disposition}: old page ${JSON.stringify(details.old)}, new page ${JSON.stringify(details.new)}; the purge hold releases ${details.hold_releases}`,
+ ` alternative: keep the old page as its own page: ${details.restore}`];
+ },
+} satisfies Omit<RepairHandler, 'kind'> & { kind: 'rename-identity' };
+
+/** A carry must be possible before a preview hash is printed: both pages as recorded, and no fence row that would drop a fact. */
+async function assertCarryable(engine: BrainEngine, record: IdentityDowngrade, parts: IdentityRemedyParts): Promise<void> {
+ if (!parts.old?.deleted || !parts.new) throw changedSincePreview(record, 'the old page is no longer soft-deleted or the new page is gone');
+ const checks = await fenceRowChecks(engine, record.source_id, parts.old.slug, parts.new.page_id);
+ if (checks.some(collides)) throw factRowsCollide(record, checks);
+}
+
+/**
+ * The carry, in one maintenance transaction under both page locks: re-check the bound state, merge each duplicate fence
+ * row onto the old row, retire the provisional page purge-style, move the old page onto the new slug (redirect and
+ * slug-keyed rows with it), move the provisional's history and edges, import the new file onto it, close the record.
+ */
+async function carryIdentity(engine: BrainEngine, record: IdentityDowngrade, hash: string): Promise<RepairItemOutcome> {
+ if (await managedPersistenceEnabled(engine)) throw managedRemedyRefusal(record);
+ const [source] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id = $1', [record.source_id]);
+ const file = source?.local_path ? join(source.local_path, record.to) : null;
+ if (!file || !existsSync(file)) throw changedSincePreview(record, `the new file ${record.to} is not in the source checkout`);
+ const sourceId = record.source_id, oldSlug = record.old_slug, newSlug = record.new_slug!;
+ const publicationId = randomUUID();
+ const report = { appended: 0 };
+ const outcome = await maintenanceTransaction(engine, async tx => {
+ await tx.lockPageKeys([{ sourceId, slug: oldSlug }, { sourceId, slug: newSlug }]);
+ const live = await identityRemedyParts(tx, record, 'carry');
+ const [open] = await tx.executeRaw(`SELECT 1 FROM op_checkpoints WHERE op = $1 AND fingerprint = $2 AND completed_keys->0->>'disposition' IS NULL`, [IDENTITY_DOWNGRADE_OP, String(record.old_page_id)]);
+ if (previewHash(live) !== hash || !open || !live.old || !live.new) throw changedSincePreview(record, 'a page of the pair changed or its record closed');
+ const checks = await fenceRowChecks(tx, sourceId, oldSlug, live.new.page_id);
+ if (checks.some(collides)) throw factRowsCollide(record, checks);
+ const oldId = live.old.page_id, provisionalId = live.new.page_id, retired = purgedSlug(newSlug, provisionalId);
+ const merged = checks.filter(check => check.new_id !== null);
+ await lockedBeliefBatch(tx, { sourceId, slugs: [oldSlug, newSlug], publicationId, op: 'rename_identity', remote: false, report }, async () => {
+ for (const check of merged) {
+ await tx.executeRaw('UPDATE facts SET superseded_by = $1 WHERE superseded_by = $2', [check.old_id, check.new_id]);
+ await tx.executeRaw(`UPDATE facts o SET kind = n.kind, visibility = n.visibility, notability = n.notability, context = n.context, valid_until = n.valid_until,
+ expired_at = n.expired_at, source = n.source, confidence = n.confidence, claim_metric = n.claim_metric, claim_value = n.claim_value, claim_unit = n.claim_unit,
+ claim_period = n.claim_period, event_type = n.event_type, attributed_to = n.attributed_to FROM facts n WHERE o.id = $1 AND n.id = $2`, [check.old_id, check.new_id]);
+ }
+ await tx.executeRaw('UPDATE pages SET slug = $1, deleted_at = now(), updated_at = now() WHERE id = $2 AND source_id = $3', [retired, provisionalId, sourceId]);
+ if (await tx.updateSlug(oldSlug, newSlug, { sourceId }) !== 1) throw changedSincePreview(record, `page ${oldSlug} could not move to ${newSlug}`);
+ await tx.executeRaw('UPDATE pages SET deleted_at = NULL, source_path = $1, updated_at = now() WHERE id = $2', [record.to, oldId]);
+ await movePageIdReferences(tx, provisionalId, oldId);
+ });
+ const imported = await importFile(tx, file, record.to, { noEmbed: true, sourceId });
+ if (imported.slug !== newSlug || imported.error) throw changedSincePreview(record, `the new file did not import onto ${newSlug} (${imported.error ?? imported.slug})`);
+ if (!await settleIdentityDowngrade(tx, oldId, 'remedied')) throw changedSincePreview(record, 'its record was settled since the preview');
+ return { applied: true, outcome: 'carried', detail: { old_page_id: oldId, from: oldSlug, to: newSlug, retired_page_id: provisionalId, retired_slug: retired,
+ facts_merged: merged.length, import: imported.status } } satisfies RepairItemOutcome;
+ });
+ if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);
+ return outcome;
+}
diff --git a/test/repair-rename-identity-6729.test.ts b/test/repair-rename-identity-6729.test.ts
new file mode 100644
index 0000000000..e197089e90
--- /dev/null
+++ b/test/repair-rename-identity-6729.test.ts
@@ -0,0 +1,396 @@
+/**
+ * #6729 remedy: `gbrain repair rename-identity`, the deferred true rename for an inexact Git rename that sync split into a
+ * delete plus an add. The operator names the pair (--slug, --from); the preview binds both page ids, both revisions and
+ * the disposition into its hash; the apply (destructive consent) carries the old page id onto the new slug with its
+ * version history, timeline, links and facts, imports the new file onto it as an edit and retires the provisional page,
+ * or (--close) releases the purge hold and moves nothing. Facts of both pages survive or the carry refuses
+ * fact_rows_collide before anything is written. Carry is classic-only: on a managed source the preview, apply and every
+ * surface name managed_remedy_unavailable and --close.
+ * Explicit-only: --all, the maintenance cycle and the remediation plan never run it. Modules are imported lazily so this
+ * file loads (and fails by behavior) on a tree without the kind.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { performSync } from '../src/commands/sync.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { renderFactsTable, type ParsedFact } from '../src/core/facts-fence.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+const write = (root: string, path: string, body: string) => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), body); };
+const BODY = Array.from({ length: 30 }, (_, i) => `- Shared meeting ${i}: discussed the project roadmap, hiring and next steps.`).join('\n');
+const fence = (rows: Array<[number, string]>) => rows.length ? `\n## Facts\n\n${renderFactsTable(rows.map(([rowNum, claim]): ParsedFact => ({ rowNum, claim, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium', active: true })))}\n` : '';
+const doc = (rows: Array<[number, string]>, tail = '') => `---\ntype: note\n---\n\n${BODY}\n${tail}${fence(rows)}`;
+const quiet = { info() {}, warn() {}, error() {} };
+
+async function capture(fn: () => Promise<void>): Promise<string> {
+ let printed = '';
+ const original = console.log, write = process.stdout.write;
+ console.log = (...parts: unknown[]) => { printed += `${parts.map(String).join(' ')}\n`; };
+ process.stdout.write = ((chunk: string | Uint8Array) => { printed += String(chunk); return true; }) as typeof process.stdout.write;
+ try { await fn(); } finally { console.log = original; process.stdout.write = write; }
+ return printed;
+}
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+for (const kind of testBackends()) describe(`gbrain repair rename-identity (#6729, ${kind})`, () => {
+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6729-remedy-'));
+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home, GBRAIN_INTERACTIVE: '0', CI: '1' };
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1').catch(() => undefined);
+ if (close) await close(); else await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ });
+ beforeEach(() => _resetCliExitVerdictForTests());
+
+ /** Whether a classic fixture source admits a restore: PGLite does; an unbound Postgres source with a checkout does not. */
+ const restoreOffered = kind === 'pglite';
+ const repair = async (args: string[]) => {
+ const { runRepairCommand } = await import('../src/commands/repair.ts');
+ return capture(() => runRepairCommand(engine, args));
+ };
+ const repairJson = async (args: string[]) => JSON.parse(await repair([...args, '--json'])).results[0];
+
+ /** A classic source whose notes/plan.md moves to notes/roadmap.md with an edit and no identity signal: a recorded downgrade. */
+ async function classicDowngrade(oldFence: Array<[number, string]>, newFence: Array<[number, string]> = oldFence) {
+ const id = `c${randomUUID().replace(/-/g, '').slice(0, 14)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q', '-b', 'main');
+ write(root, 'notes/plan.md', doc(oldFence)); write(root, 'notes/peer.md', '---\ntype: note\ntitle: Peer\n---\n\nA different page.\n');
+ commit(root, 'initial');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ const sync = () => performSync(engine, { repoPath: root, sourceId: id, noPull: true, noEmbed: true, noExtract: true, concurrency: 1 });
+ await sync();
+ const old = (await page(id, 'notes/plan'))!;
+ for (const [row, claim] of oldFence) await fenceFact(id, 'notes/plan', row, claim);
+ git(root, 'mv', 'notes/plan.md', 'notes/roadmap.md'); write(root, 'notes/roadmap.md', doc(newFence, 'An added paragraph.\n'));
+ commit(root, 'move and edit');
+ const result = await sync();
+ expect(result.identityDowngrades?.map(entry => [entry.from, entry.to, entry.reason])).toEqual([['notes/plan.md', 'notes/roadmap.md', 'no_identity_signal']]);
+ const fresh = (await page(id, 'notes/roadmap'))!;
+ for (const [row, claim] of newFence) await fenceFact(id, 'notes/roadmap', row, claim);
+ return { id, root, sync, old, fresh, result };
+ }
+ const page = async (sourceId: string, slug: string) => (await engine.executeRaw<{ id: number; slug: string; deleted_at: string | null; compiled_truth: string; source_path: string | null }>(
+ 'SELECT id, slug, deleted_at, compiled_truth, source_path FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0];
+ const pageById = async (id: number) => (await engine.executeRaw<{ slug: string; deleted_at: string | null }>('SELECT slug, deleted_at FROM pages WHERE id=$1', [id]))[0];
+ const fenceFact = async (sourceId: string, slug: string, row: number, claim: string) => {
+ await engine.insertFacts([{ fact: claim, kind: 'fact', visibility: 'world', notability: 'medium', source: 'fence:reconcile', entity_slug: slug, row_num: row, source_markdown_slug: slug }], { source_id: sourceId });
+ };
+ const facts = (sourceId: string) => engine.executeRaw<{ id: number; fact: string; entity_slug: string; source_markdown_slug: string | null; row_num: number | null; created_at: string; valid_from: string }>(
+ 'SELECT id, fact, entity_slug, source_markdown_slug, row_num, created_at::text, valid_from::text FROM facts WHERE source_id=$1 ORDER BY fact', [sourceId]);
+ const versions = async (pageId: number) => Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_versions WHERE page_id=$1', [pageId]))[0]!.n);
+ const disposition = async (oldPageId: number) => (await engine.executeRaw<{ d: unknown }>("SELECT completed_keys->0->'disposition' AS d FROM op_checkpoints WHERE op='sync-identity-downgrade' AND fingerprint=$1", [String(oldPageId)]))
+ .map(row => typeof row.d === 'string' ? JSON.parse(row.d) : row.d)[0];
+ const openRecords = async (sourceId: string) => (await import('../src/core/sync-identity-downgrades.ts')).listIdentityDowngrades(engine, [sourceId]);
+
+ test('carry: the old page id takes the new slug with its history, timeline, links and facts; the new file is an edit; the provisional page is retired; a rerun refuses cleanly', () => withEnv(env, async () => {
+ const s = await classicDowngrade([[1, 'Alpha ships payments']]);
+ const peer = (await page(s.id, 'notes/peer'))!;
+ // Identity the old page holds: a version, a timeline entry, a link, an unfenced fact known since January.
+ await engine.executeRaw("INSERT INTO page_versions(page_id, compiled_truth, frontmatter) VALUES($1, 'an earlier body', '{}')", [s.old.id]);
+ await engine.executeRaw("INSERT INTO timeline_entries(page_id, date, source, summary) VALUES($1, '2026-01-05', 'test', 'Planning kickoff')", [s.old.id]);
+ await engine.executeRaw("INSERT INTO links(from_page_id,to_page_id,link_type,link_source) VALUES($1,$2,'mentions','test')", [s.old.id, peer.id]);
+ await engine.insertFact({ fact: 'Plan is owned by the platform team', entity_slug: 'notes/plan', visibility: 'world', source: 'synthetic' }, { source_id: s.id });
+ await engine.executeRaw("UPDATE facts SET created_at='2026-01-02T00:00:00Z', valid_from='2026-01-02T00:00:00Z' WHERE source_id=$1 AND source_markdown_slug IS DISTINCT FROM 'notes/roadmap'", [s.id]);
+ const knownBefore = Object.fromEntries((await facts(s.id)).filter(f => f.entity_slug === 'notes/plan').map(f => [f.fact, { id: f.id, created_at: f.created_at, valid_from: f.valid_from }]));
+ // The destination is edited after the split: a second fence row and a new paragraph, then a fact on the provisional page.
+ write(s.root, 'notes/roadmap.md', doc([[1, 'Alpha ships payments'], [2, 'Beta ships search']], 'An added paragraph.\nEdited after the split.\n'));
+ commit(s.root, 'edit the destination');
+ await s.sync();
+ await fenceFact(s.id, 'notes/roadmap', 2, 'Beta ships search');
+ await engine.insertFact({ fact: 'Roadmap is reviewed weekly', entity_slug: 'notes/roadmap', visibility: 'world', source: 'synthetic' }, { source_id: s.id });
+ const oldVersions = await versions(s.old.id), provisionalVersions = await versions(s.fresh.id);
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.fresh.id);
+
+ const preview = await repairJson(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap']);
+ expect(structuredClone(preview)).toMatchObject({ kind: 'rename-identity', mode: 'dry_run', affected: 1, preview_hash: expect.stringMatching(/^[0-9a-f]{64}$/),
+ details: { disposition: 'carry', old: { page_id: s.old.id, slug: 'notes/plan', deleted: true }, new: { page_id: s.fresh.id, slug: 'notes/roadmap', deleted: false } } });
+ expect(preview.apply_command).toBe(`gbrain repair rename-identity --source ${s.id} --slug notes/roadmap --apply --expect ${preview.preview_hash} --yes`);
+ const [record] = await openRecords(s.id);
+ const { identityRemedy } = await import('../src/core/sync-identity-downgrades.ts');
+ expect((await identityRemedy(engine, record!)).plan_hash).toBe(preview.preview_hash);
+
+ const applied = await repairJson(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap', '--apply', '--expect', preview.preview_hash, '--yes']);
+ expect(applied).toMatchObject({ mode: 'apply', applied: 1, failed: [], complete: true, outcomes: { carried: 1 } });
+ const carried = (await page(s.id, 'notes/roadmap'))!;
+ expect(carried).toMatchObject({ id: s.old.id, deleted_at: null, source_path: 'notes/roadmap.md' });
+ expect(carried.compiled_truth).toContain('Edited after the split.');
+ expect(await page(s.id, 'notes/plan')).toBeUndefined();
+ expect(await engine.executeRaw('SELECT alias_slug, canonical_slug FROM slug_aliases WHERE source_id=$1', [s.id])).toEqual([{ alias_slug: 'notes/plan', canonical_slug: 'notes/roadmap' }]);
+ expect(await pageById(s.fresh.id)).toMatchObject({ slug: `notes/roadmap~purged-${s.fresh.id}`, deleted_at: expect.anything() });
+ // History: the old versions, the provisional's versions, and the import's snapshot of the old body (the new file is the page now).
+ expect(await versions(s.old.id)).toBe(oldVersions + provisionalVersions + 1);
+ expect(await versions(s.fresh.id)).toBe(0);
+ expect(await engine.executeRaw('SELECT summary FROM timeline_entries WHERE page_id=$1', [s.old.id])).toEqual([{ summary: 'Planning kickoff' }]);
+ expect((await engine.executeRaw<{ to_page_id: number }>('SELECT to_page_id FROM links WHERE from_page_id=$1', [s.old.id])).map(l => Number(l.to_page_id))).toContain(peer.id);
+ const after = await facts(s.id);
+ expect(after.map(f => [f.fact, f.entity_slug, f.source_markdown_slug, f.row_num])).toEqual([
+ ['Alpha ships payments', 'notes/roadmap', 'notes/roadmap', 1], ['Beta ships search', 'notes/roadmap', 'notes/roadmap', 2],
+ ['Plan is owned by the platform team', 'notes/roadmap', null, null], ['Roadmap is reviewed weekly', 'notes/roadmap', null, null]]);
+ // known_as_of: the carried rows keep their id, created_at and valid_from.
+ for (const fact of ['Alpha ships payments', 'Plan is owned by the platform team']) {
+ expect(after.find(f => f.fact === fact)).toMatchObject(knownBefore[fact]!);
+ }
+ expect(await openRecords(s.id)).toEqual([]);
+ expect(await disposition(s.old.id)).toEqual({ kind: 'remedied', at: expect.stringMatching(/^\d{4}-\d\d-\d\dT/) });
+
+ // Idempotent: the same apply, and a new preview, find no open pair and refuse; nothing is duplicated.
+ for (const rerun of [['--apply', '--expect', preview.preview_hash, '--yes'], []]) {
+ const again = await refusal(() => repair(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap', ...rerun]));
+ expect(again.code).toBe('invalid_params');
+ expect(again.message).toContain('has no open rename-identity pair with new page notes/roadmap');
+ expect(again.suggestion).toContain('already carried or closed');
+ }
+ expect(await facts(s.id)).toEqual(after);
+ expect(await versions(s.old.id)).toBe(oldVersions + provisionalVersions + 1);
+ // The next sync keeps the carried page.
+ await s.sync();
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.old.id);
+ }), 240_000);
+
+ test('different claims at one fence row number refuse fact_rows_collide before anything is written, naming the rows; so does an old row the new file dropped', () => withEnv(env, async () => {
+ for (const newFence of [[[1, 'Gamma ships billing']], []] as Array<Array<[number, string]>>) {
+ const s = await classicDowngrade([[1, 'Alpha ships payments']], newFence);
+ const before = await facts(s.id);
+ const error = await refusal(() => repair(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap']));
+ expect(error.code).toBe('fact_rows_collide');
+ expect(error.message).toContain('row 1');
+ expect(error.message).toContain('Alpha ships payments');
+ expect(error.suggestion).toContain('--close');
+ expect(await facts(s.id)).toEqual(before);
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.fresh.id);
+ expect((await page(s.id, 'notes/plan'))!.deleted_at).not.toBeNull();
+ expect((await openRecords(s.id)).length).toBe(1);
+ }
+ }), 240_000);
+
+ test('--close releases the purge hold and moves nothing; the purge then takes the old page', () => withEnv(env, async () => {
+ const s = await classicDowngrade([]);
+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).not.toContain('notes/plan');
+ const preview = await repairJson(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap', '--close']);
+ expect(preview.apply_command).toBe(`gbrain repair rename-identity --source ${s.id} --slug notes/roadmap --close --apply --expect ${preview.preview_hash} --yes`);
+ const carryHash = (await repairJson(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap'])).preview_hash;
+ expect(carryHash).not.toBe(preview.preview_hash);
+ const applied = await repairJson(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap', '--close', '--apply', '--expect', preview.preview_hash, '--yes']);
+ expect(applied).toMatchObject({ applied: 1, outcomes: { closed: 1 } });
+ expect(await disposition(s.old.id)).toEqual({ kind: 'closed', at: expect.stringMatching(/^\d{4}-\d\d-\d\dT/) });
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.fresh.id);
+ expect(await pageById(s.old.id)).toMatchObject({ slug: 'notes/plan', deleted_at: expect.anything() });
+ expect(await openRecords(s.id)).toEqual([]);
+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain('notes/plan');
+ expect(await pageById(s.old.id)).toBeUndefined();
+ }), 240_000);
+
+ test('without --slug the preview lists each open pair with its preview command and nothing can be applied; --apply without a pair refuses', () => withEnv(env, async () => {
+ const s = await classicDowngrade([]);
+ const listed = await repairJson(['rename-identity', '--source', s.id]);
+ expect(listed).toMatchObject({ affected: 0, residuals: { open_pairs: 1 } });
+ expect(listed.preview_hash).toBeUndefined();
+ expect(listed.listing).toEqual([{ item: `${s.id}:notes/plan -> notes/roadmap`, class: 'no_identity_signal',
+ detail: expect.stringContaining(`preview: gbrain repair rename-identity --source ${s.id} --slug notes/roadmap;`) }]);
+ expect((await refusal(() => repair(['rename-identity', '--source', s.id, '--apply', '--yes']))).code).toBe('invalid_params');
+ expect((await refusal(() => repair(['rename-identity', '--slug', 'notes/roadmap']))).code).toBe('invalid_params');
+ }), 240_000);
+
+ test('without --yes a non-interactive apply exits 3 with the destructive consent payload and changes nothing', () => withEnv(env, async () => {
+ const s = await classicDowngrade([]);
+ const preview = await repairJson(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap']);
+ const priorExitCode = process.exitCode;
+ const out = await repair(['rename-identity', '--source', s.id, '--slug', 'notes/roadmap', '--apply', '--expect', preview.preview_hash, '--json']);
+ expect(currentExitCode()).toBe(3);
+ process.exitCode = priorExitCode ?? 0;
+ const payload = JSON.parse(out);
+ expect(JSON.stringify(payload)).toContain('destructive');
+ expect(JSON.stringify(payload)).toContain('user_message');
+ expect(JSON.stringify(payload)).toContain(`--slug notes/roadmap --apply --expect ${preview.preview_hash}`);
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.fresh.id);
+ expect((await openRecords(s.id)).length).toBe(1);
+ }), 240_000);
+
+ test('doctor names the remedy: render the envelope, run preview_argv, run argv with the hash (consent given), then verify clears the finding', () => withEnv(env, async () => {
+ const s = await classicDowngrade([]);
+ const { renameIdentityDowngradesEntry } = await import('../src/commands/doctor/checks/rename-identity-downgrades.ts');
+ const doctor = async () => (await renameIdentityDowngradesEntry.run({ engine } as unknown as DoctorContext)) as unknown as Array<{ status: string; message: string;
+ details: { by_source: Array<{ source_id: string; count: number }>; samples: Array<{ source_id: string; remedy: Record<string, unknown> }> }; fix?: Record<string, unknown> & { argv: string[]; preview_argv: string[]; plan_hash: string; verify: { argv: string[] } } }>;
+ const mine = (finding: Awaited<ReturnType<typeof doctor>>[number]) => finding.details.by_source.find(entry => entry.source_id === s.id)?.count ?? 0;
+ // Only this source's pair is open, so the first pair is ours.
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-identity-downgrade' AND completed_keys->0->>'source_id' <> $1", [s.id]);
+ const [finding] = await doctor();
+ expect(finding!.status).toBe('warn');
+ const preview = ['gbrain', 'repair', 'rename-identity', '--source', s.id, '--slug', 'notes/roadmap'];
+ expect(structuredClone(finding!.fix)).toMatchObject({ argv: [...preview, '--apply', '--expect', expect.stringMatching(/^[0-9a-f]{64}$/), '--yes'], preview_argv: preview, consent: ['destructive'],
+ actor: 'agent', ask_user: true, user_message: expect.stringContaining('notes/plan'), verify: { argv: ['gbrain', 'doctor', '--only', 'rename_identity_downgrades', '--json'] } });
+ // An unbound classic Postgres source refuses a restore (owner_unavailable), so only PGLite names the alternative.
+ if (restoreOffered) {
+ expect(finding!.fix!.why).toContain(`gbrain restore notes/plan --source-id ${s.id} --force`);
+ expect(finding!.message).toContain(`gbrain restore notes/plan --source-id ${s.id} --force`);
+ } else {
+ for (const said of [finding!.fix!.why, finding!.message, String(finding!.fix!.user_message)]) expect(said).not.toContain('gbrain restore');
+ expect((finding!.details as unknown as { restore_unavailable_sources: string[] }).restore_unavailable_sources).toContain(s.id);
+ }
+ expect(structuredClone(finding!.details.samples[0]!.remedy)).toMatchObject({ plan_hash: finding!.fix!.plan_hash, consent: ['destructive'], hold_releases: 'the remedy carries or closes the pair, or the old page is restored or purged' });
+ const { deriveNext, renderAction } = await import('../src/core/agent-output.ts');
+ const ctx = { transport: 'cli' as const, isCallable: () => false, preapproved: () => true };
+ expect(deriveNext(finding!.fix as never, ctx)).toBe('ask_user');
+ expect(renderAction(finding!.fix as never, ctx)).toMatchObject({ next: 'ask_user', preview_argv: preview, plan_hash: finding!.fix!.plan_hash });
+ const previewed = await repairJson(finding!.fix!.preview_argv.slice(2));
+ expect(previewed.preview_hash).toBe(finding!.fix!.plan_hash);
+ const applied = await repairJson(finding!.fix!.argv.slice(2));
+ expect(applied).toMatchObject({ applied: 1, outcomes: { carried: 1 } });
+ const [verified] = await doctor();
+ expect(finding!.fix!.verify.argv).toEqual(['gbrain', 'doctor', '--only', 'rename_identity_downgrades', '--json']);
+ expect(mine(verified!)).toBe(0);
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.old.id);
+ }), 240_000);
+
+ test('the sync report and sync status name each pair with its preview, apply, consent and hold release', () => withEnv(env, async () => {
+ const s = await classicDowngrade([]);
+ const [entry] = s.result.identityDowngrades as unknown as Array<{ remedy: { preview_argv: string[]; argv: string[]; consent: string[]; hold_releases: string; plan_hash: string } }>;
+ expect(entry!.remedy).toMatchObject({ preview_argv: ['gbrain', 'repair', 'rename-identity', '--source', s.id, '--slug', 'notes/roadmap'], consent: ['destructive'] });
+ expect(entry!.remedy.argv.slice(-4)).toEqual(['--apply', '--expect', entry!.remedy.plan_hash, '--yes']);
+ expect(entry!.remedy.hold_releases).toBe('the remedy carries or closes the pair, or the old page is restored or purged');
+ const { identityDowngradeLines, withIdentityRemedies } = await import('../src/core/sync-identity-downgrades.ts');
+ const text = identityDowngradeLines(await withIdentityRemedies(engine, await openRecords(s.id))).join('\n');
+ expect(text).toContain(`preview gbrain repair rename-identity --source ${s.id} --slug notes/roadmap, then apply gbrain repair rename-identity --source ${s.id} --slug notes/roadmap --apply --expect ${entry!.remedy.plan_hash} --yes`);
+ expect(text).toContain('asks the user first: destructive');
+ if (restoreOffered) expect(text).toContain(`or keep notes/plan as its own page: gbrain restore notes/plan --source-id ${s.id} --force`);
+ else expect(text).not.toContain('gbrain restore');
+ expect(text).toContain('The purge holds notes/plan until the remedy carries or closes the pair, or the old page is restored or purged.');
+ expect(text).not.toMatch(/72 h|72-hour|expires/);
+ }), 240_000);
+
+ test('--all, the maintenance cycle and the doctor remediation plan never run it', () => withEnv(env, async () => {
+ const s = await classicDowngrade([]);
+ // --all --apply runs every auto kind over the whole shared test brain; an unrelated kind that stops short (timeline on a
+ // large Postgres brain) sets exit 1, which is not this test's subject, so the prior exit code is restored after it.
+ const priorExitCode = process.exitCode;
+ const allOut = await repair(['--all', '--apply', '--json']);
+ process.exitCode = priorExitCode;
+ const all = JSON.parse(allOut) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string; docs: string }> };
+ expect(all.results.map(r => r.kind)).not.toContain('rename-identity');
+ expect(all.explicit_kinds).toContainEqual({ kind: 'rename-identity', code: 'explicit_kind_required', preview_command: 'gbrain repair rename-identity', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' });
+ const { computeRemediationPlan } = await import('../src/core/remediation/index.ts');
+ const plan = await computeRemediationPlan(engine, { repairs: {} });
+ expect(plan.repair_steps!.map(step => step.kind)).not.toContain('rename-identity');
+ expect(plan.explicit_repairs!.map(n => [n.kind, n.code])).toContainEqual(['rename-identity', 'explicit_kind_required']);
+ const { runRepairSteps } = await import('../src/core/remediation/repairs.ts');
+ const supplied = await refusal(() => runRepairSteps(engine, [{ step: 1, id: 'repair:rename-identity', kind: 'rename-identity' as never, affected: 1, command: 'gbrain repair rename-identity --apply',
+ requires_user_agreement: true, protected: true, paid: false, embeds: 'none', est_usd_cost: 0, lifetime_ids: 0, checks: [], rationale: 'supplied' }], { remote: false, remainingUsd: () => undefined }));
+ expect(supplied.code).toBe('explicit_kind_required');
+ const { contentRepairPhaseKinds, runContentRepairPhase } = await import('../src/core/cycle/content-repair.ts');
+ expect(contentRepairPhaseKinds()).not.toContain('rename-identity' as never);
+ await runContentRepairPhase(engine, { dryRun: false });
+ const { repairRunner } = await import('../src/core/repair/registry.ts');
+ const { resolveRepairScope } = await import('../src/core/repair/core.ts');
+ const runner = await repairRunner(engine, { apply: true, logger: quiet });
+ expect((await refusal(() => runner.run('rename-identity' as never, { brain_id: 'host', source_ids: [s.id] }))).code).toBe('explicit_kind_required');
+ expect(await resolveRepairScope(engine, s.id)).toMatchObject({ source_ids: [s.id] });
+ expect((await openRecords(s.id)).length).toBe(1);
+ expect((await page(s.id, 'notes/roadmap'))!.id).toBe(s.fresh.id);
+ expect((await page(s.id, 'notes/plan'))!.deleted_at).not.toBeNull();
+ }), 240_000);
+
+ test('managed: carrying is unavailable (managed_remedy_unavailable) on the preview, the apply, the report, status and doctor; --close settles the pair and the purge takes the old page; restore still keeps one', () => withEnv(env, async () => {
+ const id = `m${randomUUID().replace(/-/g, '').slice(0, 14)}`, root = join(home, id);
+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');
+ write(root, 'notes/plan.md', doc([[1, 'Alpha ships payments']])); write(root, 'notes/other.md', doc([[1, 'Gamma ships billing']], 'The other page.\n')); commit(root, 'initial');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ const lines: string[] = [];
+ const sync = () => performManagedSync(engine, { sourceId: id, noPull: true });
+ await sync();
+ const old = (await page(id, 'notes/plan'))!, other = (await page(id, 'notes/other'))!;
+ git(root, 'mv', 'notes/plan.md', 'notes/roadmap.md'); write(root, 'notes/roadmap.md', doc([[1, 'Alpha ships payments']], 'An added paragraph.\n'));
+ git(root, 'mv', 'notes/other.md', 'notes/another.md'); write(root, 'notes/another.md', doc([[1, 'Gamma ships billing']], 'The other page.\nAn added paragraph.\n'));
+ commit(root, 'move and edit');
+ const result = await sync();
+ expect(result.identityDowngrades?.map(entry => entry.from).sort()).toEqual(['notes/other.md', 'notes/plan.md']);
+ const fresh = (await page(id, 'notes/roadmap'))!;
+ const close = ['gbrain', 'repair', 'rename-identity', '--source', id, '--slug', 'notes/roadmap', '--close'];
+ // The restore alternative works on a managed source: the old page is live again beside its new page.
+ const { operationsByName } = await import('../src/core/operations.ts');
+ await operationsByName.restore_page!.handler({ engine, config: { engine: engine.kind }, remote: false, dryRun: false, logger: quiet, sourceId: id } as never, { slug: 'notes/other', source_id: id, force: true });
+ expect(await pageById(other.id)).toMatchObject({ slug: 'notes/other', deleted_at: null });
+ expect((await page(id, 'notes/another'))!.deleted_at).toBeNull();
+ expect((await openRecords(id)).map(r => r.old_slug)).toEqual(['notes/plan']);
+
+ // Every surface names --close as the only managed remedy, with the restore alternative and no other route.
+ const { identityDowngradeLines, withIdentityRemedies } = await import('../src/core/sync-identity-downgrades.ts');
+ const entries = await withIdentityRemedies(engine, (await openRecords(id)).filter(r => r.old_slug === 'notes/plan'));
+ expect(structuredClone(entries[0]!.remedy)).toMatchObject({ disposition: 'close', carry_unavailable: 'managed_remedy_unavailable', preview_argv: close, consent: ['destructive'] });
+ expect(entries[0]!.remedy.argv).toEqual([...close, '--apply', '--expect', entries[0]!.remedy.plan_hash, '--yes']);
+ lines.push(...identityDowngradeLines(entries));
+ const text = lines.join('\n');
+ expect(text).toContain(`Carrying notes/plan's identity onto notes/roadmap is unavailable on a managed source (managed_remedy_unavailable); release the purge hold without carrying it (asks the user first: destructive): preview ${close.join(' ')}, then apply ${entries[0]!.remedy.argv.join(' ')}; or keep notes/plan as its own page: gbrain restore notes/plan --source-id ${id} --force`);
+ const { readSyncStatus } = await import('../src/core/persistence/sync-status.ts');
+ const status = (await readSyncStatus(engine, id, { detail: false })).identity_downgrades.find(entry => entry.old_slug === 'notes/plan')!;
+ expect(status.remedy).toMatchObject({ disposition: 'close', carry_unavailable: 'managed_remedy_unavailable', preview_argv: close, plan_hash: entries[0]!.remedy.plan_hash });
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-identity-downgrade' AND (completed_keys->0->>'source_id' <> $1 OR completed_keys->0->>'old_slug' <> 'notes/plan')", [id]);
+ const { renameIdentityDowngradesEntry } = await import('../src/commands/doctor/checks/rename-identity-downgrades.ts');
+ const [finding] = (await renameIdentityDowngradesEntry.run({ engine } as unknown as DoctorContext)) as unknown as Array<{ message: string; fix: Record<string, unknown> & { why: string } }>;
+ expect(structuredClone(finding!.fix)).toMatchObject({ argv: entries[0]!.remedy.argv, preview_argv: close, consent: ['destructive'], ask_user: true, plan_hash: entries[0]!.remedy.plan_hash });
+ expect(finding!.message).toContain('Carrying identity is unavailable on a managed source (managed_remedy_unavailable); to release the purge hold without carrying it, preview');
+ expect(finding!.message).toContain(`gbrain restore notes/plan --source-id ${id} --force`);
+ // The last report line is the general tip for future moves (S1), not a route for this pair.
+ for (const said of [lines.slice(0, -1).join('\n'), finding!.message, finding!.fix.why, String(finding!.fix.user_message)]) expect(said).not.toMatch(/\bedit\b|git restore|move (it )?back/);
+
+ // The carry preview states the code and writes nothing; its --apply refuses with it and moves no identity.
+ const preview = await repairJson(['rename-identity', '--source', id, '--slug', 'notes/roadmap']);
+ expect(structuredClone(preview)).toMatchObject({ mode: 'dry_run', affected: 0, residuals: { carry_unavailable: 1 },
+ details: { code: 'managed_remedy_unavailable', close_preview: close.join(' '), restore: `gbrain restore notes/plan --source-id ${id} --force` },
+ listing: [{ item: `${id}:notes/plan -> notes/roadmap`, class: 'managed_remedy_unavailable' }] });
+ expect(preview.preview_hash).toBeUndefined();
+ const carry = await refusal(() => repair(['rename-identity', '--source', id, '--slug', 'notes/roadmap', '--apply', '--expect', 'f'.repeat(64), '--yes']));
+ expect(carry.code).toBe('managed_remedy_unavailable');
+ expect(carry.suggestion).toContain(close.join(' '));
+ expect(carry.suggestion).not.toMatch(/\bedit\b|git restore|move (it )?back/);
+ expect((await page(id, 'notes/roadmap'))!.id).toBe(fresh.id);
+ expect(await pageById(old.id)).toMatchObject({ slug: 'notes/plan', deleted_at: expect.anything() });
+ expect(await disposition(old.id)).toBeNull();
+
+ // --close settles the pair; the purge then takes the old page.
+ await purgeDeletedPagesCoordinated(engine, 0);
+ expect(await pageById(old.id)).toMatchObject({ slug: 'notes/plan', deleted_at: expect.anything() });
+ const closing = await repairJson(['rename-identity', '--source', id, '--slug', 'notes/roadmap', '--close']);
+ expect(closing.preview_hash).toBe(entries[0]!.remedy.plan_hash);
+ expect(await repairJson(['rename-identity', '--source', id, '--slug', 'notes/roadmap', '--close', '--apply', '--expect', closing.preview_hash, '--yes'])).toMatchObject({ applied: 1, outcomes: { closed: 1 } });
+ expect(await disposition(old.id)).toMatchObject({ kind: 'closed' });
+ expect((await openRecords(id)).map(r => r.old_slug)).not.toContain('notes/plan');
+ expect((await page(id, 'notes/roadmap'))!.id).toBe(fresh.id);
+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain('notes/plan');
+ expect(await pageById(old.id)).toBeUndefined();
+
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }), 240_000);
+});