Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): take the rename-identity remedy out of the #6729 S1 core; the report and doctor name the restore (#6729)
garrytan6026185443d0
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 7bbcb4c85a..15170804af 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -350,11 +350,20 @@ starts a fresh page, and the old page keeps its facts, links and aliases onits soft-deleted slug. The sync report prints each such pair, `gbrain syncstatus --source <id> --json` lists it under `identity_downgrades`, doctor`rename_identity_downgrades` names it, and the purge leaves the old page alone-for 72 hours. If the pair really was one page that moved, carry its identity-before the window ends: `gbrain repair rename-identity --source <id>` previews-the pairs, and `--apply --expect <hash>` moves the previewed set onto the new-pages (the same carrier a confirmed rename uses, with an `old -> new` slug-redirect). The reverse also holds: a new file whose `frontmatter.id` uniquely+for 72 hours. To keep an old page, restore it before the window ends with+`gbrain restore <old-slug> --source-id <id> --force` (it then lives beside the+new page; where the old file cannot be re-created the restore names+`--detach`). To move and rewrite a page so it keeps its identity, give it a+stable id or move, commit and sync first, then edit:++```yaml+---+id: roadmap-2026+title: Roadmap+---+```++The reverse also holds: a new file whose `frontmatter.id` uniquelymatches a file deleted in the same range is treated as its rename, even whenGit did not pair them. A managed sync refuses `page_identity_changed`(`rename_identity_conflict`) when a file would take over a page whosediff --git a/src/commands/doctor/checks/rename-identity-downgrades.ts b/src/commands/doctor/checks/rename-identity-downgrades.tsindex 1f4dd38ec1..1810cbb02d 100644--- a/src/commands/doctor/checks/rename-identity-downgrades.ts+++ b/src/commands/doctor/checks/rename-identity-downgrades.ts@@ -2,13 +2,13 @@* #6729 `rename_identity_downgrades`: inexact Git renames a sync split into a delete plus an add because their identity* could not be confirmed (sync-rename-identity.ts). Each old page keeps its facts, links and aliases on its soft-deleted* slug for the 72-hour recovery window, and the purge leaves it alone while the record is open. The finding names every- * open pair and the read-only preview of `gbrain repair rename-identity`, which carries the identity onto the new page- * when a person confirms the pair was one page that moved. Outside the window the check is ok: the pairs are history.+ * open pair; its fix restores the first old page (with its facts, links and aliases, beside the new page)+ * once the user asks to keep it. Outside the window the check is ok: the pairs are history.*/import type { Check } from '../../doctor.ts';import { agentFix, checkError } from '../check-fix.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';-import { identityDowngradeReasonText, identityRemedyPreviewArgv, listIdentityDowngrades } from '../../../core/sync-identity-downgrades.ts';+import { identityDowngradeReasonText, identityRestoreArgv, identityStatusArgv, listIdentityDowngrades } from '../../../core/sync-identity-downgrades.ts';const DOCS = 'docs/guides/live-sync.md#renaming-a-page';const SAMPLE = 5;@@ -29,11 +29,12 @@ async function runRenameIdentityDowngrades(ctx: DoctorContext): Promise<Check[]>checks.push({ name: 'rename_identity_downgrades', status: 'warn', details,message: `${open.length} rename(s) synced in the last 72 h did not keep their page identity, so each old page's facts, links and aliases stay on its soft-deleted slug until its window ends `+ `(e.g. ${samples.map(record => `${record.source_id}:${record.from} -> ${record.to}, ${record.facts} fact(s) and ${record.links} link(s) on ${record.old_slug}`).join('; ')}; `- + `first: ${identityDowngradeReasonText(first.reason)}). If a pair is one page that moved, preview carrying its identity with ${identityRemedyPreviewArgv(first.source_id).join(' ')}; `+ + `first: ${identityDowngradeReasonText(first.reason)}). ${identityStatusArgv(first.source_id).join(' ')} lists every pair. To keep an old page, restore it before its window ends; `+ 'otherwise nothing is needed and the old pages purge after their window.',- fix: agentFix([...identityRemedyPreviewArgv(first.source_id), '--json'],- 'Read-only preview: lists each pair with what would move onto the new page and prints the apply command with its hash. Apply only after the user confirms the pair is one page that moved.',- 'rename_identity_downgrades', { docs: DOCS }) });+ fix: agentFix(identityRestoreArgv(first),+ `Restores ${first.old_slug} with its facts, links and aliases, beside ${first.new_slug ?? 'the new file'}; the record closes and the purge no longer waits for it.`,+ 'rename_identity_downgrades', { docs: DOCS, ask_user: true,+ user_message: `Sync did not keep the identity of ${first.old_slug} when ${first.from} became ${first.to}. Restore ${first.old_slug} as its own page so its ${first.facts} fact(s) and ${first.links} link(s) stay live?` }) });} catch (error) {checks.push(checkError('rename_identity_downgrades', 'read the renames whose identity was not kept', error, { details: { count: 'unknown', docs: DOCS } }));}diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.tsindex eac856d024..c1b26d5721 100644--- a/src/commands/sync/renames.ts+++ b/src/commands/sync/renames.ts@@ -9,9 +9,7 @@ import { softDeleteSyncPages } from '../../core/company-brain/profile.ts';import { serr } from '../../core/console-prefix.ts';import { DELETE_BATCH_SIZE } from '../../core/engine-constants.ts';import { importFile, isImageFilePath as isImageImportPath, importImageFile } from '../../core/import-file.ts';-import { maintenanceAttribution, maintenanceTransaction } from '../../core/persistence/attribution.ts';-import { withCoordinatedWrite } from '../../core/persistence/context.ts';-import { readManagedMode } from '../../core/persistence/managed-mode.ts';+import { maintenanceTransaction } from '../../core/persistence/attribution.ts';import type { BrainEngine } from '../../core/engine.ts';import { movePageIdReferences, moveSlugBindings, recordRenameAlias } from '../../core/page-state/rename-alias.ts';import { renamePageOntoSlug } from './rename-collision.ts';@@ -363,13 +361,11 @@ export async function carryRenameIdentity(engine: BrainEngine, sourceId: string,if (!from || !to || from.id === to.id) return;const publication = await maintenanceTransaction(engine, async tx => {await tx.lockPageKeys([{ sourceId, slug: staleSlug }, { sourceId, slug: newSlug }]);- const carry = () => recordFallbackRename(tx, { sourceId, staleSlug, newSlug, fromPageId: Number(from.id), toPageId: Number(to.id) }, async () => {+ return recordFallbackRename(tx, { sourceId, staleSlug, newSlug, fromPageId: Number(from.id), toPageId: Number(to.id) }, async () => {await recordRenameAlias(tx, sourceId, staleSlug, newSlug);await moveSlugBindings(tx, sourceId, staleSlug, newSlug);await movePageIdReferences(tx, Number(from.id), Number(to.id));});- // #6729: `gbrain repair rename-identity` also carries on a managed brain, whose page tables take writes only inside a coordinated write.- return await readManagedMode(tx) ? withCoordinatedWrite(tx, [sourceId], carry, await maintenanceAttribution(tx)) : carry();});if (publication) await markBeliefCommits(engine, [publication]).catch(() => undefined);}diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex c0934ce930..f4f2b3db63 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' | 'rename-identity';+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 interface ApprovedSetKey {command: PreviewApprovalCommand;diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 8a50f2c8c0..a5240faf44 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -89,7 +89,7 @@ export interface SyncStatus {rate_pages_per_min: number | null;eta_seconds: number | null;holds: SyncStatusHold[];- /** #6729: renames synced in the last 72 h whose page identity was not kept (old page soft-deleted with its facts and links; `gbrain repair rename-identity` carries them). */+ /** #6729: renames synced in the last 72 h whose page identity was not kept (old page soft-deleted with its facts and links; `gbrain restore` keeps one). */identity_downgrades: import('../sync-identity-downgrades.ts').IdentityDowngrade[];last_error: SyncStatusError | null;/** Whether anything (a hold or the last error) waits on a person; the first such reason. */diff --git a/src/core/repair/rename-identity.ts b/src/core/repair/rename-identity.tsdeleted file mode 100644index 36bcbfdefb..0000000000--- a/src/core/repair/rename-identity.ts+++ /dev/null@@ -1,67 +0,0 @@-/**- * `gbrain repair rename-identity [--source <id>]` (#6729): carry a page's identity across an inexact Git rename that- * sync split into a delete plus an add because it could not confirm the pair (sync-rename-identity.ts). Explicit-only- * and preview-bound: the preview lists each open downgrade (inside its 72-hour window, old page still soft-deleted, new- * page live) with what stays on the old slug, and saves the set under a hash; `--apply --expect <hash>` carries exactly- * that set with the sync rename lane's own carrier (`carryRenameIdentity`: an `old -> new` slug redirect, slug-keyed- * facts, aliases and withdrawals, and page-id-keyed links, timeline and versions move onto the new page) and closes- * each record. A pair that is no longer open, or whose new page moved, is kept and counted.- */-import { carryRenameIdentity } from '../../commands/sync/renames.ts';-import { OperationError } from '../ops/contract.ts';-import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';-import { clearIdentityDowngrade, identityDowngradeReasonText, listIdentityDowngrades, type IdentityDowngrade } from '../sync-identity-downgrades.ts';-import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';--type Approved = IdentityDowngrade & { selection: string[] };-type CarryItem = RepairItem & { record: IdentityDowngrade; hash: string; last: boolean };--const previewCommand = (scope: RepairScope) => `gbrain repair rename-identity${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;--function item(record: IdentityDowngrade, index: number, hash: string, last: boolean): CarryItem {- return { cursor: { phase: 0, id: index + 1 }, source_id: record.source_id, slug: record.old_slug, chars: 0, action: 'carry_identity',- change: { from: record.old_slug, to: record.new_slug! }, record, hash, last };-}--const describe = (record: IdentityDowngrade) => `${record.from} -> ${record.to} (git similarity ${record.similarity}%; ${identityDowngradeReasonText(record.reason)}): `- + `${record.facts} fact(s), ${record.links} link(s), ${record.aliases} alias(es) move from ${record.old_slug} to ${record.new_slug}; window ends ${record.expires_at}`;--export const renameIdentityRepair = {- kind: 'rename-identity' as const,- publication: 'projection' as const,- embeds: false,- async plan(engine, scope, after, opts): Promise<RepairPlan> {- const command = previewCommand(scope);- if (!opts?.apply) {- const open = (await listIdentityDowngrades(engine, scope.source_ids)).filter(record => record.new_slug !== null);- const hash = previewHash({ kind: 'rename-identity-v1', brain_id: scope.brain_id, selection: scope.source_ids,- pairs: open.map(record => [record.source_id, record.old_page_id, record.old_slug, record.new_slug, record.recorded_at]) });- if (open.length) await saveApprovedSet<Approved>(engine, { command: 'rename-identity', hash }, open.map(record => ({ ...record, selection: scope.source_ids })));- const unimported = (await listIdentityDowngrades(engine, scope.source_ids)).length - open.length;- return { items: open.map((record, index) => item(record, index, hash, index === open.length - 1)), preview_hash: hash,- residuals: unimported ? { new_file_not_imported: unimported } : {},- listing: open.map(record => ({ item: `${record.source_id}:${record.old_slug}`, class: record.reason, detail: describe(record) })) };- }- if (!opts.expect) {- throw new OperationError('invalid_params', 'gbrain repair rename-identity --apply carries only the set a preview printed.',- `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`, 'docs/guides/live-sync.md#renaming-a-page');- }- const approved = await loadApprovedSet<Approved>(engine, { command: 'rename-identity', hash: opts.expect, previewCommand: command });- if (approved.items.some(entry => JSON.stringify(entry.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);- const items = approved.items.map(({ selection: _selection, ...record }, index) => item(record, index, opts.expect!, index === approved.items.length - 1));- return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };- },- async apply(ctx, entry): Promise<RepairItemOutcome> {- const { record, hash, last } = entry as CarryItem;- try {- const open = (await listIdentityDowngrades(ctx.engine, [record.source_id])).find(candidate => candidate.old_page_id === record.old_page_id);- const [fresh] = await ctx.engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [record.source_id, record.new_slug]);- if (!open || !fresh || open.old_slug !== record.old_slug) return { applied: false, outcome: 'kept', reason: 'no_longer_open' };- await carryRenameIdentity(ctx.engine, record.source_id, record.old_slug, record.new_slug!);- await clearIdentityDowngrade(ctx.engine, record.old_page_id);- return { applied: true, outcome: 'carried', detail: { from: record.old_slug, to: record.new_slug, facts: record.facts, links: record.links, aliases: record.aliases } };- } finally {- if (last) await clearApprovedSet(ctx.engine, { command: 'rename-identity', hash });- }- },-} satisfies Omit<RepairHandler, 'kind'> & { kind: 'rename-identity' };diff --git a/src/core/sync-identity-downgrades.ts b/src/core/sync-identity-downgrades.tsindex 6da2f80e22..f2200eb6dd 100644--- a/src/core/sync-identity-downgrades.ts+++ b/src/core/sync-identity-downgrades.ts@@ -2,12 +2,11 @@* #6729: inexact Git renames a sync could not confirm (see sync-rename-identity.ts) were split into a delete plus an* add, so the old page's facts, links and aliases stay on its soft-deleted slug. Each one is recorded here for the* 72-hour recovery window: `gbrain sync status --json` lists it, doctor `rename_identity_downgrades` names it, the- * purge leaves its old page alone while the record is open, and `gbrain repair rename-identity` carries the identity- * onto the new page when the operator confirms the pair was a real rename.+ * purge leaves its old page alone while the record is open, and the report names the detached restore of the old page.** One `op_checkpoints` row per old page (op `sync-identity-downgrade`, fingerprint = the old page id);- * `completed_keys[0]` holds the record. A record closes when its window ends, when the remedy carries it, or when its- * old page is restored or purged (the readers join the soft-deleted page).+ * `completed_keys[0]` holds the record. A record closes when its window ends, or when its old page is restored or+ * purged (the readers join the soft-deleted page).*/import type { BrainEngine } from './engine.ts';import { resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason } from './sync.ts';@@ -85,11 +84,6 @@ export async function listIdentityDowngrades(engine: Pick<BrainEngine, 'executeRreturn rows.map(row => ({ ...(typeof row.record === 'string' ? JSON.parse(row.record) as IdentityDowngrade : row.record), new_slug: row.new_slug }));}-/** Closes one record (the remedy carried it). */-export async function clearIdentityDowngrade(engine: Pick<BrainEngine, 'executeRaw'>, oldPageId: number): Promise<void> {- await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [IDENTITY_DOWNGRADE_OP, String(oldPageId)]);-}-/** A recorded downgrade (as opposed to a raw pair a sync has not recorded yet). */export const isRecordedDowngrade = (entry: DowngradedRename): entry is IdentityDowngrade => 'old_page_id' in entry;@@ -112,17 +106,22 @@ export async function noteIdentityDowngrades<T extends { status: string; identit}}-/** The read-only preview of the remedy for one source. */-export const identityRemedyPreviewArgv = (sourceId: string): string[] => ['gbrain', 'repair', 'rename-identity', '--source', sourceId];+/**+ * Restores one old page with its facts, links and aliases, beside the new page. Where the restore cannot re-create the+ * old file, it refuses `canonical_file_absent` and names `--detach` (database-only) as the user's choice.+ */+export const identityRestoreArgv = (record: Pick<IdentityDowngrade, 'source_id' | 'old_slug'>): string[] =>+ ['gbrain', 'restore', record.old_slug, '--source-id', record.source_id, '--force'];+/** The read-only listing of a source's open records. */+export const identityStatusArgv = (sourceId: string): string[] => ['gbrain', 'sync', 'status', '--source', sourceId, '--json'];/** The sync report's lines for the downgraded pairs of one run. */export function identityDowngradeLines(records: readonly IdentityDowngrade[]): string[] {if (!records.length) return [];- const sources = [...new Set(records.map(record => record.source_id))];return [...records.map(record => ` Identity not kept: ${record.from} -> ${record.to} (git similarity ${record.similarity}%; ${REASON_TEXT[record.reason]}). `+ `${record.facts} fact(s), ${record.links} link(s) and ${record.aliases} alias(es) stay on the soft-deleted ${record.old_slug} until ${record.expires_at} (72 h); `- + `${record.new_slug ? `${record.new_slug} starts fresh.` : 'the new file did not import.'}`),- ` If a pair above is one page that moved, carry its identity before the window ends: preview ${sources.map(source => identityRemedyPreviewArgv(source).join(' ')).join(' ; ')}, then apply with --apply --expect <hash>.`,+ + `${record.new_slug ? `${record.new_slug} starts fresh.` : 'the new file did not import.'} To keep the old page, restore it before then: ${identityRestoreArgv(record).join(' ')}`),+ ' A move keeps its page when the files share a frontmatter id: (or a unique slug: line or title); to move and rewrite a page, move, commit and sync, then edit.',];}diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.tsindex 4a86d7c05f..9f2cb41756 100644--- a/test/persistence-sync-holds.test.ts+++ b/test/persistence-sync-holds.test.ts@@ -214,7 +214,7 @@ test('a chained rename carries the held identity, and a changed old page keeps texpect((await engine.getPage('notes/x', { sourceId: s.id }))?.id).toBe(x.id);}), 240_000);-test('#6729: an inexact rename onto a broken file is a delete plus an add; the old page stays recorded and the remedy carries it once the file is fixed', () => each(async engine => {+test('#6729: an inexact rename onto a broken file is a delete plus an add; the old page stays recorded, and once the file is fixed the record names the new page', () => each(async engine => {const s = await source(engine, { 'notes/old.md': long('Old') });await s.sync();const page = (await engine.getPage('notes/old', { sourceId: s.id }))!;@@ -230,14 +230,8 @@ test('#6729: an inexact rename onto a broken file is a delete plus an add; the oawait s.sync();const fresh = (await engine.getPage('notes/new', { sourceId: s.id }))!;expect(fresh.id).not.toBe(page.id);- const { renameIdentityRepair } = await import('../src/core/repair/rename-identity.ts');- const scope = { brain_id: 'test', source_ids: [s.id] };- const preview = await renameIdentityRepair.plan(engine, scope, null, { apply: false });- expect(preview.items.map(item => item.change)).toEqual([{ from: 'notes/old', to: 'notes/new' }]);- const [item] = (await renameIdentityRepair.plan(engine, scope, null, { apply: true, expect: preview.preview_hash })).items;- const ctx = { engine, config: { engine: engine.kind }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } };- expect(await renameIdentityRepair.apply(ctx as never, item!)).toMatchObject({ applied: true, outcome: 'carried' });- expect(await engine.executeRaw('SELECT alias_slug, canonical_slug FROM slug_aliases WHERE source_id=$1', [s.id])).toEqual([{ alias_slug: 'notes/old', canonical_slug: 'notes/new' }]);+ const { listIdentityDowngrades } = await import('../src/core/sync-identity-downgrades.ts');+ expect((await listIdentityDowngrades(engine, [s.id])).map(record => [record.old_slug, record.new_slug])).toEqual([['notes/old', 'notes/new']]);}), 240_000);test('the hold write and the cursor step past it commit together: a crash between them persists neither', () => each(async engine => {diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.tsindex 3a8bbd9776..307e3ac441 100644--- a/test/sync-inexact-rename-6729.test.ts+++ b/test/sync-inexact-rename-6729.test.ts@@ -2,7 +2,7 @@* #6729: an inexact Git rename (R<100) is a similarity guess, so it keeps the old page's identity only when the files* confirm it (a shared frontmatter id, or a unique slug: line or title). Every other pair is a delete plus an add, the* old page keeps its facts, links and aliases on its soft-deleted slug for 72 h, the run records it, the purge leaves it- * alone, doctor names it, and gbrain repair rename-identity carries the identity when a person confirms the move.+ * alone, doctor names it, and a restore keeps the old page when a person asks for it.* Classic sync, managed sync and the dirty-tree manifest each keep an R<100 fixture; R100 variants sit beside them.* New modules are imported lazily so this file loads (and fails by behavior) on a master without them.*/@@ -77,7 +77,7 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,const redirects = (sourceId: string) => engine.executeRaw<{ alias_slug: string; canonical_slug: string }>('SELECT alias_slug, canonical_slug FROM slug_aliases WHERE source_id=$1 ORDER BY alias_slug', [sourceId]);const aliasOwner = async (sourceId: string, alias: string) => (await engine.executeRaw<{ slug: string }>('SELECT slug FROM page_aliases WHERE source_id=$1 AND alias_norm=$2 ORDER BY slug', [sourceId, alias])).map(row => row.slug);- test('classic: crossed inexact pairs with one shared title keep their own facts and aliases, are recorded, held from purge, named by doctor, and the remedy carries a confirmed one', () => withEnv(env, async () => {+ test('classic: crossed inexact pairs with one shared title keep their own facts and aliases, are recorded, held from purge, named by doctor, and the restore fix keeps one', () => withEnv(env, async () => {const s = await classic({'people/a-x-com.md': doc('type: person\ntitle: Colleague\naliases: [Ali]', 'Works on payments.\n'),'people/b-x-com.md': doc('type: person\ntitle: Colleague\naliases: [Bea]', 'Works on search.\n'),@@ -111,36 +111,32 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs.filter(slug => slug.endsWith('-x-com'))).toEqual([]);expect(await pageRow(s.id, 'people/a-x-com')).toBeDefined();- // Doctor names them with the read-only remedy preview.+ // Doctor names them; the fix restores the first old page once the user asks (ask_user), and verify clears it.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; details: { count: number; by_source: Array<{ source_id: string; count: number }> }; fix?: Record<string, unknown> & { argv: string[] } }>;+ const doctor = async () => (await renameIdentityDowngradesEntry.run({ engine } as unknown as DoctorContext)) as unknown as Array<{ status: string; details: { count: number; by_source: Array<{ source_id: string; count: number }> }; fix?: Record<string, unknown> & { argv: 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;const [finding] = await doctor();expect(finding!.status).toBe('warn');- expect(finding!.details.by_source.find(entry => entry.source_id === s.id)?.count).toBe(2);- expect(finding!.fix).toMatchObject({ argv: ['gbrain', 'repair', 'rename-identity', '--source', expect.any(String), '--json'], consent: [], actor: 'agent',- verify: { argv: ['gbrain', 'doctor', '--only', 'rename_identity_downgrades', '--json'] } });- expect(finding!.fix).not.toHaveProperty('ask_user');+ expect(mine(finding!)).toBe(2);+ const [, , slug, , sourceId] = finding!.fix!.argv;+ const restored = { 'people/a-x-com': { id: a.id, fact: 'A works on payments', alias: 'ali' }, 'people/b-x-com': { id: b.id, fact: 'B works on search', alias: 'bea' } }[slug!]!;+ const other = slug === 'people/a-x-com' ? { slug: 'people/b-x-com', id: b.id } : { slug: 'people/a-x-com', id: a.id };+ expect(finding!.fix).toMatchObject({ argv: ['gbrain', 'restore', expect.stringMatching(/^people\/[ab]-x-com$/), '--source-id', s.id, '--force'], consent: [], actor: 'agent', ask_user: true,+ user_message: expect.stringContaining(slug!), verify: { argv: ['gbrain', 'doctor', '--only', 'rename_identity_downgrades', '--json'] } });const { deriveNext } = await import('../src/core/agent-output.ts');- expect(deriveNext(finding!.fix as never, { transport: 'cli', isCallable: () => false, preapproved: () => false })).toBe('run');-- // The person confirms a-x-com really became alice: preview, then apply exactly the previewed pair.- const { renameIdentityRepair } = await import('../src/core/repair/rename-identity.ts');- const scope = { brain_id: 'test', source_ids: [s.id] };- const preview = await renameIdentityRepair.plan(engine, scope, null, { apply: false });- expect(preview.items.map(item => [item.slug, item.change?.to]).sort()).toEqual([['people/a-x-com', 'people/alice'], ['people/b-x-com', 'people/bob']]);- await expect(renameIdentityRepair.plan(engine, scope, null, { apply: true })).rejects.toMatchObject({ code: 'invalid_params' });- const approved = await renameIdentityRepair.plan(engine, scope, null, { apply: true, expect: preview.preview_hash });- const pick = approved.items.find(item => item.slug === 'people/a-x-com')!;- expect(await renameIdentityRepair.apply(repairCtx(engine), pick)).toMatchObject({ applied: true, outcome: 'carried' });- expect(await factSlugs(s.id)).toEqual([{ entity_slug: 'people/alice', fact: 'A works on payments' }, { entity_slug: 'people/b-x-com', fact: 'B works on search' }]);- expect(await aliasOwner(s.id, 'ali')).toEqual(['people/alice']);- expect(await engine.executeRaw('SELECT from_page_id FROM links WHERE to_page_id=$1', [peer.id])).toEqual([{ from_page_id: alice.id }]);- expect(await redirects(s.id)).toEqual([{ alias_slug: 'people/a-x-com', canonical_slug: 'people/alice' }]);- // Verify: the carried pair left the finding, and its old page is no longer held from the purge.+ expect(deriveNext(finding!.fix as never, { transport: 'cli', isCallable: () => false, preapproved: () => true })).toBe('ask_user');+ // Run the argv (gbrain restore <slug> --source-id <id> --force) through its operation, then the verify.+ const { operationsByName } = await import('../src/core/operations.ts');+ await operationsByName.restore_page!.handler({ ...repairCtx(engine), sourceId } as never, { slug, source_id: sourceId, force: true });+ expect((await pageRow(s.id, slug!))).toMatchObject({ id: restored.id, deleted_at: null });+ expect(await factSlugs(s.id)).toContainEqual({ entity_slug: slug, fact: restored.fact });+ expect(await aliasOwner(s.id, restored.alias)).toEqual([slug]);const [after] = await doctor();- expect(after!.details.by_source.find(entry => entry.source_id === s.id)?.count).toBe(1);- expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain('people/a-x-com');- expect((await pageRow(s.id, 'people/b-x-com'))!.deleted_at).not.toBeNull();+ expect(mine(after!)).toBe(1);+ expect((await pageRow(s.id, other.slug))!.deleted_at).not.toBeNull();+ // A record whose window ended no longer holds its old page from the purge.+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,expires_at}', to_jsonb((now() - interval '1 hour')::text)) WHERE op = 'sync-identity-downgrade' AND fingerprint = $1", [String(other.id)]);+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain(other.slug);}), 180_000);test('classic: a move plus edit keeps its identity through a unique title, and an exact move needs no signal', () => withEnv(env, async () => {