Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): #6729 downgrade hold lasts until the pair gets a disposition (no 72 h window); checkpoint sweep keeps open records
garrytand5d5a34821fc
diff --git a/.wave18-fragments/lane2-s1.md b/.wave18-fragments/lane2-s1.mdindex 9a99d6e959..532429541c 100644--- a/.wave18-fragments/lane2-s1.md+++ b/.wave18-fragments/lane2-s1.md@@ -9,7 +9,7 @@ S1 items: #6729 and #6741 A/B/C. Non-S1 rows are in `.wave18-fragments/lane2.md`1. `src/commands/doctor/registry.ts`: `import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';` and add `renameIdentityDowngradesEntry,` right after `ghostPagesEntry,` in `DOCTOR_CHECK_REGISTRY`.2. `src/core/doctor-categories.ts` `BRAIN_CHECK_NAMES`: after `'ghost_pages',` add```ts- // #6729: inexact renames whose identity sync did not keep, inside their 72 h window (doctor/checks/rename-identity-downgrades.ts).+ // #6729: inexact renames whose identity sync did not keep, until the pair gets a disposition (doctor/checks/rename-identity-downgrades.ts).'rename_identity_downgrades',```3. Regenerate the doctor goldens: `GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/doctor-registry-golden.test.ts`, then the runtime ones (`test/doctor-content-golden.test.ts test/doctor-hot-checks-golden.test.ts test/doctor-json-golden.test.ts test/doctor-json-golden-latest.test.ts`, and the Postgres ones under `test/e2e/` with `DATABASE_URL` + `GBRAIN_TEST_ALLOW_DATABASE_URL=1`). The diff is additions only.@@ -19,17 +19,17 @@ The remedy repair kind is not in S1: it lands in its own commit after the S1 SHA### BEHAVIOR_CHANGES (`src/core/behavior-change-notice.ts`, since = slot version)-- `{ since: '<slot>', text: 'An inexact Git rename (a move that also changed the file, reported as R<100) now keeps its page identity only when the files confirm it: the same frontmatter \`id\` on both sides that no other file or page carries, or, with no id on either side, a \`slug:\` line or title that no other file in the sync and no other live page shares; a respelled path that keeps its slug keeps its page unless the ids conflict (#6729). Any other pair is imported as a delete plus an add: the new file starts a fresh page and the old page keeps its facts, links and aliases on its soft-deleted slug. The sync report prints each pair with \`gbrain restore <old-slug> --source-id <id> --force\`, \`gbrain sync status --json\` lists it under \`identity_downgrades\`, doctor \`rename_identity_downgrades\` names it, and the purge leaves the old page alone until its 72-hour window ends. A new file whose frontmatter \`id\` uniquely matches a file deleted in the same sync range is now its rename, even across two commits.' }`+- `{ since: '<slot>', text: 'An inexact Git rename (a move that also changed the file, reported as R<100) now keeps its page identity only when the files confirm it: the same frontmatter \`id\` on both sides that no other file or page carries, or, with no id on either side, a \`slug:\` line or title (the frontmatter \`title:\`, else the first \`# Heading\`, compared with the title the brain stores for the old page) that no other file in the sync and no other live page shares; a respelled path that keeps its slug keeps its page unless the ids conflict (#6729). Any other pair is imported as a delete plus an add: the new file starts a fresh page and the old page keeps its facts, links and aliases on its soft-deleted slug. The sync report prints each pair with \`gbrain restore <old-slug> --source-id <id> --force\`, \`gbrain sync status --json\` lists it under \`identity_downgrades\`, doctor \`rename_identity_downgrades\` names it, and the purge leaves the old page alone, with no time limit, until the pair gets a disposition (the old page restored, or, once the remedy ships, remedied or closed without merging). A new file whose frontmatter \`id\` uniquely matches a file deleted in the same sync range is now its rename, even across two commits.' }`- `{ since: '<slot>', text: 'A file moved and broken in the same commit (unreadable frontmatter, so Git reports an inexact rename) is no longer held with the old page identity: the old page is soft-deleted and recorded as above and the broken file is held as a new file (#6729). An exact move (R100) that is held still keeps the old page identity and \`rename_from\`. A managed sync refuses \`page_identity_changed\` (detail \`rename_identity_conflict\`) when a file would take over a page, or a held rename would carry one, whose frontmatter \`id\` differs from its own.' }`### CHANGELOG-- Sync no longer moves one page's facts, links and aliases onto a different page when Git guesses an inexact rename between two similar files. Identity follows a shared frontmatter `id`, a unique `slug:` line or a unique title; anything else is a delete plus an add, reported with its restore command and held from the purge for 72 hours (#6729). Contributed by @javieraldape (PR #6732, rewritten).+- Sync no longer moves one page's facts, links and aliases onto a different page when Git guesses an inexact rename between two similar files. Identity follows a shared frontmatter `id`, a unique `slug:` line or a unique title; anything else is a delete plus an add, reported with its restore command and held from the purge until the pair is settled (#6729). Contributed by @javieraldape (PR #6732, rewritten).### KEY_FILES (`docs/architecture/key-files/files-and-sync-*.md`, `commands-*.md`)-- `src/core/sync-rename-identity.ts`: the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with one frontmatter-only parser; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult. An add whose id uniquely matches a delete in the range becomes a rename. Downgraded pairs record `read.from` / `read.to`.-- `src/core/sync-identity-downgrades.ts`: durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, released when the 72 h window ends or the old page is restored or purged), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv.+- `src/core/sync-rename-identity.ts`: the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult. An add whose id uniquely matches a delete in the range becomes a rename. Downgraded pairs record `read.from` / `read.to`.+- `src/core/sync-identity-downgrades.ts`: durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv.- `src/commands/doctor/checks/rename-identity-downgrades.ts`: doctor `rename_identity_downgrades` (warn while a record is open; fix = restore the first old page, behind ask_user).### Tests that changed for the intended behaviourdiff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 15170804af..7c16f982c6 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -344,13 +344,16 @@ and two template-shaped files moved in one commit can be paired the wrong wayround (#6729). So sync keeps the page identity across an inexact rename onlywhen the files confirm it: both carry the same `frontmatter.id` and no otherfile or page shares it, or neither carries an id and they share a `slug:` line-or title that no other file in the source uses. An exact move (`R100`) needs no-signal. Any other pair is imported as a delete plus an add: the new file+or title that no other file in the source uses. The title is the one the page+row gets: the frontmatter `title:`, else the body's first `# Heading` (never+the filename), and the old side counts as the title the brain stores for that+page now. An exact move (`R100`) needs no signal. Any other pair is imported as a delete plus an add: the new filestarts 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. To keep an old page, restore it before the window ends with+until the pair gets a disposition; there is no time limit, so a pair can still+be repaired later. Restoring the old page settles it: run`gbrain restore <old-slug> --source-id <id> --force` (it then lives beside thenew 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 adiff --git a/src/commands/doctor/checks/rename-identity-downgrades.ts b/src/commands/doctor/checks/rename-identity-downgrades.tsindex 1810cbb02d..bb500b285e 100644--- a/src/commands/doctor/checks/rename-identity-downgrades.ts+++ b/src/commands/doctor/checks/rename-identity-downgrades.ts@@ -1,9 +1,9 @@/*** #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; 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.+ * slug, and the purge leaves it alone until the pair gets a disposition (restored, remedied or closed without merging);+ * there is no time window. The finding names every open pair until then; its fix restores the first old page (with its+ * facts, links and aliases, beside the new page) once the user asks to keep it.*/import type { Check } from '../../doctor.ts';import { agentFix, checkError } from '../check-fix.ts';@@ -19,18 +19,18 @@ async function runRenameIdentityDowngrades(ctx: DoctorContext): Promise<Check[]>const open = await listIdentityDowngrades(connectedEngine(ctx));const bySource = [...new Set(open.map(record => record.source_id))].map(source_id => ({ source_id, count: open.filter(record => record.source_id === source_id).length }));const samples = open.slice(0, SAMPLE).map(record => ({ source_id: record.source_id, from: record.from, to: record.to, old_slug: record.old_slug, new_slug: record.new_slug,- reason: record.reason, facts: record.facts, links: record.links, aliases: record.aliases, expires_at: record.expires_at }));+ reason: record.reason, facts: record.facts, links: record.links, aliases: record.aliases, recorded_at: record.recorded_at }));const details = { count: open.length, by_source: bySource, samples, docs: DOCS };if (!open.length) {- checks.push({ name: 'rename_identity_downgrades', status: 'ok', details, message: 'No rename in the last 72 h lost its page identity.' });+ checks.push({ name: 'rename_identity_downgrades', status: 'ok', details, message: 'No rename that lost its page identity is waiting for a disposition.' });return checks;}const first = open[0]!;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 `+ message: `${open.length} rename(s) did not keep their page identity, so each old page's facts, links and aliases stay on its soft-deleted slug, held from the purge until the pair is settled `+ `(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)}). ${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.',+ + `first: ${identityDowngradeReasonText(first.reason)}). ${identityStatusArgv(first.source_id).join(' ')} lists every pair. To keep an old page, restore it; `+ + 'until a pair is restored or settled, its old page stays and this check names it.',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,diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex a57b789fa3..ee8a20c2f5 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -304,7 +304,7 @@ export async function purgeDeletedPages(WHERE deleted_at IS NOT NULLAND deleted_at < now() - (${hours} || ' hours')::intervalAND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text- AND (dg.completed_keys->0->>'expires_at')::timestamptz > now())+ AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)ORDER BY deleted_at ASC, slug ASC`);const pages = rows.map((r) => ({@@ -317,9 +317,9 @@ export async function purgeDeletedPages(DELETE FROM pagesWHERE deleted_at IS NOT NULLAND deleted_at < now() - (${hours} || ' hours')::interval- -- #6729: the old page of an open rename-identity downgrade waits for its window (identityDowngradePurgeHold).+ -- #6729: the old page of an open rename-identity downgrade waits for its disposition (identityDowngradePurgeHold).AND NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = 'sync-identity-downgrade' AND dg.fingerprint = pages.id::text- AND (dg.completed_keys->0->>'expires_at')::timestamptz > now())+ AND dg.completed_keys->0->>'disposition' IS NULL AND pages.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz)RETURNING slug`);const slugs = rows.map((r) => r.slug);diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.tsindex d71ce846e7..0313a7434b 100644--- a/src/core/op-checkpoint.ts+++ b/src/core/op-checkpoint.ts@@ -496,7 +496,8 @@ export function syncFingerprint(p: { sourceId?: string; lastCommit: string }): s* the incarnation), and connector hold-retry requests and stuck-recovery* resolution audit entries never expire (#5988, #6650); a managed purge's* tombstone failure records and parks (#6741, purge-parks.ts) leave only with- * their tombstone, its purge or a rearm.+ * their tombstone, its purge or a rearm; an open #6729 rename-identity downgrade+ * record stays until its pair is settled or its old page is restored or purged.*/export async function purgeStaleCheckpoints(engine: BrainEngine,@@ -514,6 +515,8 @@ export async function purgeStaleCheckpoints(AND op<>'connector-hold-retry'AND op<>'stuck-recovery-resolution'AND op<>'purge-deleted-park'+ AND NOT (op='sync-identity-downgrade' AND completed_keys->0->>'disposition' IS NULL AND EXISTS (+ SELECT 1 FROM pages p WHERE p.id::text=op_checkpoints.fingerprint AND p.deleted_at=(op_checkpoints.completed_keys->0->>'old_deleted_at')::timestamptz))AND NOT (op IN ('sync-hold','sync-hold-retry','sync-import-provenance','sync-hold-summary','sync-conversions','${FENCE_CANDIDATE_OP}','${FENCE_SCAN_OP}','${FENCE_REPAIR_ATTEMPT_OP}','${FENCE_UNCOMMITTED_OP}')AND NOT (op='sync-hold-summary' AND COALESCE((completed_keys->0->>'count')::int,0)=0)AND EXISTS (SELECT 1 FROM sources s WHERE s.id=op_checkpoints.completed_keys->0->>'source_id'diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex a5240faf44..569c17e9e0 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 restore` keeps one). */+ /** #6729: renames whose page identity was not kept and whose pair has no disposition yet (old page soft-deleted with its facts and links, held from the purge; `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/sync-identity-downgrades.ts b/src/core/sync-identity-downgrades.tsindex 48c8522c02..2240a7999d 100644--- a/src/core/sync-identity-downgrades.ts+++ b/src/core/sync-identity-downgrades.ts@@ -1,18 +1,19 @@/*** #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 the report names the detached restore of the old page.+ * add, so the old page's facts, links and aliases stay on its soft-deleted slug. Each one is recorded here until the+ * pair gets a disposition: `gbrain sync status --json` lists it, doctor `rename_identity_downgrades` names it, the purge+ * leaves its old page alone and the checkpoint sweep keeps the record while it is open, and the report names the+ * restore of the old page. There is no time window: a pair recorded before its remedy exists can still be repaired.** 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, or when its old page is restored or- * purged (the readers join the soft-deleted page).+ * `completed_keys[0]` holds the record. A record is open while it has no `disposition` (set when the pair is remedied+ * or closed without merging) and its old page is still soft-deleted from that sync (`deleted_at` = `old_deleted_at`);+ * a restore, a purge or a later delete of the restored page closes it.*/import type { BrainEngine } from './engine.ts';import { resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason } from './sync.ts';export const IDENTITY_DOWNGRADE_OP = 'sync-identity-downgrade';-export const IDENTITY_DOWNGRADE_WINDOW_HOURS = 72;export interface IdentityDowngrade extends DowngradedRename {source_id: string;@@ -20,13 +21,20 @@ export interface IdentityDowngrade extends DowngradedRename {old_slug: string; old_page_id: number; new_slug: string | null;/** What stays on the old slug: facts keyed to it, links from or to it, and its free-text aliases. */facts: number; links: number; aliases: number;- recorded_at: string; expires_at: string;+ /** When the old page was soft-deleted (ISO), and that `deleted_at` exactly as Postgres printed it (the open test). */+ recorded_at: string; old_deleted_at: string;+ /** Set when the pair is remedied or closed without merging; the record is then closed. */+ disposition?: { kind: 'remedied' | 'closed'; at: string };}+/** SQL: the downgrade record `dg` is open for the page aliased `alias` (no disposition, old page still soft-deleted by that sync). */+export const identityDowngradeOpen = (alias: string): string =>+ `dg.completed_keys->0->>'disposition' IS NULL AND ${alias}.deleted_at = (dg.completed_keys->0->>'old_deleted_at')::timestamptz`;+/** SQL predicate for a purge scan over `pages` aliased `alias`: the page has no open downgrade record. */export function identityDowngradePurgeHold(alias: string): string {return `NOT EXISTS (SELECT 1 FROM op_checkpoints dg WHERE dg.op = '${IDENTITY_DOWNGRADE_OP}' AND dg.fingerprint = ${alias}.id::text- AND (dg.completed_keys->0->>'expires_at')::timestamptz > now())`;+ AND ${identityDowngradeOpen(alias)})`;}const REASON_TEXT: Record<RenameDowngradeReason, string> = {@@ -61,7 +69,7 @@ export async function recordIdentityDowngrades(engine: BrainEngine, sourceId: stconst record: IdentityDowngrade = { source_id: sourceId, from: pair.from, to: pair.to, similarity: pair.similarity, reason: pair.reason, ...(pair.read ? { read: pair.read } : {}),old_slug: old.slug, old_page_id: Number(old.id), new_slug: fresh?.slug ?? null,facts: Number(counts?.facts ?? 0), links: Number(counts?.links ?? 0), aliases: Number(counts?.aliases ?? 0),- recorded_at: recorded.toISOString(), expires_at: new Date(recorded.getTime() + IDENTITY_DOWNGRADE_WINDOW_HOURS * 3600_000).toISOString() };+ recorded_at: recorded.toISOString(), old_deleted_at: old.deleted_at };await engine.executeRaw(`INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at) VALUES ($1, $2, $3::text::jsonb, now())ON CONFLICT (op, fingerprint) DO UPDATE SET completed_keys = EXCLUDED.completed_keys, updated_at = now()`,[IDENTITY_DOWNGRADE_OP, String(record.old_page_id), JSON.stringify([record])]);@@ -71,14 +79,14 @@ export async function recordIdentityDowngrades(engine: BrainEngine, sourceId: st}/**- * Open records (inside the window, old page still soft-deleted), oldest first; every source when `sourceIds` is omitted.+ * Open records (no disposition, old page still soft-deleted by that sync), oldest first; every source when `sourceIds` is omitted.* `new_slug` is read live: the live page at the new path now (a held new file that was fixed later counts once it imports).*/export async function listIdentityDowngrades(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: readonly string[]): Promise<IdentityDowngrade[]> {const rows = await engine.executeRaw<{ record: IdentityDowngrade | string; new_slug: string | null }>(`SELECT dg.completed_keys->0 AS record, np.slug AS new_slug FROM op_checkpoints dg JOIN pages p ON p.id::text = dg.fingerprintLEFT JOIN LATERAL (SELECT slug FROM pages WHERE source_id = p.source_id AND deleted_at IS NULL AND source_path = dg.completed_keys->0->>'to' LIMIT 1) np ON true- WHERE dg.op = $1 AND p.deleted_at IS NOT NULL AND (dg.completed_keys->0->>'expires_at')::timestamptz > now()+ WHERE dg.op = $1 AND p.deleted_at IS NOT NULL AND ${identityDowngradeOpen('p')}AND p.source_id = dg.completed_keys->0->>'source_id' AND ($2::text[] IS NULL OR p.source_id = ANY($2::text[]))ORDER BY dg.completed_keys->0->>'recorded_at', dg.fingerprint`, [IDENTITY_DOWNGRADE_OP, sourceIds ? [...sourceIds] : null]);return rows.map(row => ({ ...(typeof row.record === 'string' ? JSON.parse(row.record) as IdentityDowngrade : row.record), new_slug: row.new_slug }));@@ -120,8 +128,8 @@ export function identityDowngradeLines(records: readonly IdentityDowngrade[]): sif (!records.length) return [];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.'} To keep the old page, restore it before then: ${identityRestoreArgv(record).join(' ')}`),+ + `${record.facts} fact(s), ${record.links} link(s) and ${record.aliases} alias(es) stay on the soft-deleted ${record.old_slug}, which the purge keeps until the pair is settled; `+ + `${record.new_slug ? `${record.new_slug} starts fresh.` : 'the new file did not import.'} To keep the old page, restore it: ${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/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.tsindex 58f612f85d..fe5a60a419 100644--- a/test/sync-inexact-rename-6729.test.ts+++ b/test/sync-inexact-rename-6729.test.ts@@ -1,8 +1,8 @@/*** #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 a restore keeps the old page when a person asks for it.+ * old page keeps its facts, links and aliases on its soft-deleted slug, the run records it, the purge leaves it alone+ * until the pair is settled (no time window), 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.*/@@ -135,8 +135,18 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,const [after] = await doctor();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)]);+ // No time window: a month-old open record survives the checkpoint sweep and still holds its old page, and doctor+ // still names it; only a disposition releases it. A restored page deleted again later is not held by its old record.+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at = now() - interval '30 days' WHERE op = 'sync-identity-downgrade' AND fingerprint = ANY($1::text[])", [[String(a.id), String(b.id)]]);+ const { purgeStaleCheckpoints } = await import('../src/core/op-checkpoint.ts');+ await purgeStaleCheckpoints(engine);+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).not.toContain(other.slug);+ expect(mine((await doctor())[0]!)).toBe(1);+ await engine.softDeletePage(slug!, { sourceId: s.id });+ expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain(slug);+ expect((await engine.executeRaw('SELECT fingerprint FROM op_checkpoints WHERE op = $1 AND fingerprint = ANY($2::text[])', ['sync-identity-downgrade', [String(a.id), String(b.id)]])).map(row => (row as { fingerprint: string }).fingerprint)).toEqual([String(other.id)]);+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,disposition}', jsonb_build_object('kind', 'closed', 'at', now()::text)) WHERE op = 'sync-identity-downgrade' AND fingerprint = $1", [String(other.id)]);+ expect(mine((await doctor())[0]!)).toBe(0);expect((await purgeDeletedPagesCoordinated(engine, 0)).slugs).toContain(other.slug);}), 180_000);