Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): an inexact Git rename keeps page identity only when the files confirm it (#6729)
garrytan990df90b9366
diff --git a/docs/.wave18-fragments/lane2.md b/docs/.wave18-fragments/lane2.mdnew file mode 100644index 0000000000..60c599e257--- /dev/null+++ b/docs/.wave18-fragments/lane2.md@@ -0,0 +1,49 @@+# Wave 18 lane 2 fragments (scratch; the integrator applies these rows and deletes this file)++## #6729 inexact Git rename identity++### Registries (integrator-owned)++The `INTEGRATOR-ROW` commit at the end of `capy/wave18-lane2` applies rows 1-4 and regenerates the goldens, so `check:orphan-modules` passes on the lane branch. Drop it and apply the rows by hand if you'd rather.++1. `src/core/repair/core.ts` `REPAIR_KINDS`: insert `'rename-identity'` right after `'ghost-pages'`.+2. `src/core/repair/registry.ts`: add `import { renameIdentityRepair } from './rename-identity.ts';` after the ghost-pages import, and this entry right after `'ghost-pages'`:+ ```ts+ 'rename-identity': {+ handler: renameIdentityRepair, embeds: 'none', checks: ['rename_identity_downgrades'], explicit_only: true, preview_bound: true,+ summary: 'Carry a page identity across an inexact Git rename that sync split into a delete plus an add because the files did not confirm it '+ + '(#6729: no shared frontmatter id, slug: line or unique title). The preview lists each open pair (72 h window, old page still soft-deleted, '+ + 'new page live) with the facts, links and aliases that stay on the old slug; --apply --expect <hash> moves exactly that set onto the new page '+ + 'with the sync rename carrier (old -> new slug redirect, slug-keyed facts and aliases, page-id-keyed links, timeline and versions) and closes '+ + 'each record. Runs only when named.',+ },+ ```+3. `src/commands/doctor/registry.ts`: `import { renameIdentityDowngradesEntry } from './checks/rename-identity-downgrades.ts';` and add `renameIdentityDowngradesEntry,` right after `ghostPagesEntry,` in the entry list.+4. `src/core/doctor-categories.ts`: 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).+ 'rename_identity_downgrades',+ ```+5. Regenerate the doctor goldens (`test/fixtures/goldens/doctor/*`) and any registry golden after 1-4.++### 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 (#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, \`gbrain sync status --json\` lists it under \`identity_downgrades\`, doctor \`rename_identity_downgrades\` names it, the purge leaves the old page for 72 hours, and \`gbrain repair rename-identity --source <id>\` (preview, then \`--apply --expect <hash>\`) carries the identity when the pair really was one page. 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, the broken file is held as a new file, and after it is fixed \`gbrain repair rename-identity\` carries the old page onto it (#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 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, recorded for 72 hours with `gbrain repair rename-identity` to carry it when the move was real (#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 both sides' frontmatter heads through one `git cat-file --batch` stream (`catFileHeads`, 64 KiB per object; the dirty tree reads the working file) and keeps an R<100 pair only on a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages); conflicting ids veto; an add whose id uniquely matches a delete in the range becomes a rename. `confirmedSyncDelta` wraps `computeSyncDelta`. Classic preflight, managed discovery and the dirty-tree manifest call it before any consumer filter.+- `src/core/sync-identity-downgrades.ts`: durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, 72 h), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the remedy preview argv.+- `src/core/repair/rename-identity.ts`: `gbrain repair rename-identity`, preview-bound, reuses `carryRenameIdentity` from `src/commands/sync/renames.ts`.+- `src/commands/doctor/checks/rename-identity-downgrades.ts`: doctor `rename_identity_downgrades` (warn while a record is open; fix = the read-only remedy preview).++### Tests that changed for the intended behaviour++- `test/sync.test.ts` (3) and `test/sync-git-paths.test.ts` (3 platform cases): `buildSyncManifest` rename entries now carry Git's `similarity`.+- Held-rename hold-lane tests whose fixture was an inexact move onto a broken file now use an exact move (R100) held by a stale `slug:` line; every hold-lane assertion is unchanged: `test/persistence-sync-holds.test.ts` (2), `test/repair-frontmatter.test.ts` (2), `test/hold-action-chain-6712.test.ts` (1), `test/sync-legacy-holds.test.ts` (3), `test/write-attribution-sync.test.ts` (1). The inexact-onto-broken fixture keeps a test per path asserting its new outcome (`#6729: an inexact rename onto a broken file ...` in persistence-sync-holds and sync-legacy-holds).+- `test/large-pages/managed-sync-segmented-rename.test.ts`: the fixture carries a frontmatter `id`, so the edited rename whose title follows the slug is still confirmed.diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.mdindex 2a161191e7..7bbcb4c85a 100644--- a/docs/guides/live-sync.md+++ b/docs/guides/live-sync.md@@ -339,6 +339,27 @@ and refuses `revision_conflict` if that page changed after the sync admittedit; the Git projection is the sync's own commit. Keep `frontmatter.id` as itis; a changed id is a different page.+Git reports a move that also changed the file as a similarity guess (`R087`),+and two template-shaped files moved in one commit can be paired the wrong way+round (#6729). So sync keeps the page identity across an inexact rename only+when the files confirm it: both carry the same `frontmatter.id` and no other+file 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+starts a fresh page, and the old page keeps its facts, links and aliases on+its soft-deleted slug. The sync report prints each such pair, `gbrain sync+status --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+matches a file deleted in the same range is treated as its rename, even when+Git did not pair them. A managed sync refuses `page_identity_changed`+(`rename_identity_conflict`) when a file would take over a page whose+`frontmatter.id` differs from the file's own.+`put_page` at a new slug is not a rename. A content-only write cannot prove theold file is gone, so a create-only `put_page` whose `frontmatter.id` andcontent match an existing page resolves to that page (`duplicate`: the receiptdiff --git a/src/commands/doctor/checks/rename-identity-downgrades.ts b/src/commands/doctor/checks/rename-identity-downgrades.tsnew file mode 100644index 0000000000..e292299881--- /dev/null+++ b/src/commands/doctor/checks/rename-identity-downgrades.ts@@ -0,0 +1,38 @@+/**+ * #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.+ */+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';++const DOCS = 'docs/guides/live-sync.md#renaming-a-page';+const SAMPLE = 5;++async function runRenameIdentityDowngrades(ctx: DoctorContext): Promise<Check[]> {+ try {+ 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 }));+ const details = { count: open.length, by_source: bySource, samples, docs: DOCS };+ if (!open.length) return [{ name: 'rename_identity_downgrades', status: 'ok', details, message: 'No rename in the last 72 h lost its page identity.' }];+ const first = open[0]!;+ return [{ 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(' ')}; `+ + '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 }) }];+ } catch (error) {+ return [checkError('rename_identity_downgrades', 'read the renames whose identity was not kept', error, { details: { count: 'unknown', docs: DOCS } })];+ }+}++export const renameIdentityDowngradesEntry: DoctorEntry = { name: 'rename_identity_downgrades', emits: ['rename_identity_downgrades'], run: runRenameIdentityDowngrades };diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 83b61bd3c3..15409c7719 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -71,7 +71,7 @@ export interface SyncResult {prescreened?: number; writeWait?: import('../core/persistence/sync-write-diagnostic.ts').ManagedSyncWriteWait;/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];- fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;+ fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction; /** #6729: inexact renames split into delete + add; once recorded each is an IdentityDowngrade (old slug, what stayed on it). */ identityDowngrades?: Array<import('../core/sync.ts').DowngradedRename | import('../core/sync-identity-downgrades.ts').IdentityDowngrade>;/** #6712 PR 2 (L5): the owed post-checkpoint tail (statistics, links) this call ran after releasing the lease; a degraded tail carries its notice. */tail?: Omit<import('../core/persistence/sync-tail.ts').SyncTailReport, 'links'>;/** #5459 (P4.5): live pages a `--full` tree walk kept because their file is in the working tree and their import provenance is the working tree or unknown. */diff --git a/src/commands/sync/finalize.ts b/src/commands/sync/finalize.tsindex 2581726a86..e0f652aa27 100644--- a/src/commands/sync/finalize.ts+++ b/src/commands/sync/finalize.ts@@ -215,9 +215,18 @@ export async function finalizeIncrementalSync(...(typeWarningsEnabled && typeWarnings.length > 0 ? { type_warnings: typeWarnings } : {}),...(uncommittedDrift ? { uncommitted: uncommittedDrift } : {}),...(extractError ? { extract_error: extractError } : {}),+ ...identityDowngradesOf(plan),};}+/** #6729: the inexact renames this run split into a delete plus an add, in the source's origin form (recorded by `performSync`). */+function identityDowngradesOf(plan: Pick<SyncPlan, 'manifest' | 'inScope' | 'isSelectedForRun' | 'syncOpts' | 'modePath'>): Pick<SyncResult, 'identityDowngrades'> {+ const selected = (path: string) => plan.inScope(path) && plan.isSelectedForRun(path, plan.syncOpts);+ const pairs = (plan.manifest.downgradedRenames ?? []).filter(pair => selected(pair.from) || selected(pair.to))+ .map(pair => ({ ...pair, from: plan.modePath(pair.from), to: plan.modePath(pair.to) }));+ return pairs.length ? { identityDowngrades: pairs } : {};+}+/** v0.42.x (#1794, T3): pin-reachability gate; records a `<head>` sentinel on a rewrite. */function verifyPinnedHead(run: SyncRun, plan: Pick<SyncPlan, 'company' | 'gitContextRoot' | 'pin'>): boolean {const { failedFiles } = run;diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.tsindex f1699daac1..24a8ae0456 100644--- a/src/commands/sync/perform.ts+++ b/src/commands/sync/perform.ts@@ -19,6 +19,7 @@ import { withRefreshingLock, LockUnavailableError, LockStolenError, syncLockId }import { readSyncAnchor } from '../../core/sync-anchor.ts';import { recordUpstreamObservation } from '../../core/sync-upstream.ts';import { assertSyncApplicable } from '../../core/sync-applicability.ts';+import { noteIdentityDowngrades } from '../../core/sync-identity-downgrades.ts';import { SyncLockBusyError, formatLockBusyMessage, buildPartialResult } from '../../core/sync-lock.ts';import type { SyncOpts, SyncResult } from '../sync.ts';import { runConnectorSync } from './connector.ts';@@ -36,7 +37,7 @@ export async function performSync(engine: BrainEngine, opts: SyncOpts): Promise<await refreshProjectionStatistics(engine, result.pagesAffected.length + result.deleted);}if (refresh && !opts.dryRun) await recordUpstreamObservation(engine, opts.sourceId ?? 'default', opts.repoPath);- return result;+ return refresh && !opts.dryRun ? noteIdentityDowngrades(engine, opts.sourceId ?? 'default', result, serr) : result;};const interruptedBeforeWork = async (): Promise<SyncResult> => {assertSourceFilesystemActive(true);@@ -128,6 +129,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promiconst stages = (result.staged.stages ?? 1) + 1, d = result.drain, n = next.drain;result = { ...next, fromCommit: result.fromCommit, added: result.added + next.added, modified: result.modified + next.modified, deleted: result.deleted + next.deleted,renamed: result.renamed + next.renamed, chunksCreated: result.chunksCreated + next.chunksCreated,+ ...(result.identityDowngrades?.length || next.identityDowngrades?.length ? { identityDowngrades: [...result.identityDowngrades ?? [], ...next.identityDowngrades ?? []] } : {}),...(next.staged ? { staged: { ...next.staged, stages } } : {}),...(n ? { drain: { ...n, passes: d.passes + n.passes, processed: d.processed + n.processed, written: d.written + n.written, waived: d.waived + n.waived } } : {}) };if (!next.staged) serr(`[sync] staged catch-up reached HEAD after ${stages} stages.`);diff --git a/src/commands/sync/preflight.ts b/src/commands/sync/preflight.tsindex 8ce9eadc8c..aa994afc45 100644--- a/src/commands/sync/preflight.ts+++ b/src/commands/sync/preflight.ts@@ -21,7 +21,8 @@ import {readChunkerVersion,} from '../../core/sync-anchor.ts';import type { SlugRootMode } from '../../core/sync-anchor.ts';-import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../../core/sync-delta.ts';+import { buildDetachedWorkingTreeManifest, mergeSyncManifests } from '../../core/sync-delta.ts';+import { confirmedSyncDelta, confirmRenameIdentities } from '../../core/sync-rename-identity.ts';import {git,isWithinRoot,@@ -892,6 +893,10 @@ async function resolveWorkingTreeScope(// scoped source thinks in), same form runImport matches on full sync.const scopeRel = (p: string): string =>scoped && p.startsWith(syncScopeRelPath + '/') ? p.slice(syncScopeRelPath.length + 1) : p;+ // #6729: an imported dirty tree's inexact renames are confirmed (base HEAD, target the working tree) before any+ // filter reads them; a manifest only counted as drift decomposes its renames anyway.+ if (importWorkingTree) workingTreeManifest = await confirmRenameIdentities(engine, gitContextRoot, 'HEAD', null, workingTreeManifest,+ { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel });const includedPaths = company ? new Set(company.plan.manifest.filter(entry => entry.disposition === 'included').map(entry => entry.path)) : null;const storedPaths = company ? new Set((await engine.executeRaw<{ source_path: string }>('SELECT source_path FROM pages WHERE source_id=$1 AND source_path IS NOT NULL', [opts.sourceId!])).map(page => page.source_path)) : null;const isSelectedForRun = (path: string, options?: Parameters<typeof isSyncable>[1]): boolean => company@@ -989,9 +994,9 @@ async function computeFilteredDelta(// buffer, and a gc'd anchor object can't be diffed at all. On either// `unavailable`, fall back to the authoritative full reconcile instead of// throwing — a slow correct reconcile beats a hard error or a silent walk.- const delta = computeSyncDelta(gitContextRoot, lastCommit, pin, {- detachedManifest: importWorkingTree ? workingTreeManifest : null,- });+ // #6729: inexact renames keep their page identity only when confirmed, before the company fold, the unsyncable fold+ // and the hold replay read the manifest; the already-confirmed working-tree manifest merges after.+ const delta = await confirmedSyncDelta(engine, gitContextRoot, lastCommit, pin, { sourceId: opts.sourceId ?? DEFAULT_SOURCE_ID, sourcePathOf: scopeRel });if (delta.status === 'unavailable') {serr(`[sync] delta ${lastCommit.slice(0, 8)}..${pin.slice(0, 8)} unavailable ` +@@ -999,7 +1004,7 @@ async function computeFilteredDelta();return { done: await performFullSync(engine, fullSyncRoots, headCommit, opts, holds) };}- const manifest = delta.manifest;+ const manifest = importWorkingTree ? mergeSyncManifests(delta.manifest, workingTreeManifest) : delta.manifest;if (company) {manifest.added.push(...manifest.renamed.map(rename => rename.to));manifest.deleted.push(...manifest.renamed.map(rename => rename.from));diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.tsindex c1b26d5721..eac856d024 100644--- a/src/commands/sync/renames.ts+++ b/src/commands/sync/renames.ts@@ -9,7 +9,9 @@ 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 { maintenanceTransaction } from '../../core/persistence/attribution.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 type { BrainEngine } from '../../core/engine.ts';import { movePageIdReferences, moveSlugBindings, recordRenameAlias } from '../../core/page-state/rename-alias.ts';import { renamePageOntoSlug } from './rename-collision.ts';@@ -361,11 +363,13 @@ 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 }]);- return recordFallbackRename(tx, { sourceId, staleSlug, newSlug, fromPageId: Number(from.id), toPageId: Number(to.id) }, async () => {+ const carry = () => 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/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 1af641ad08..a57b789fa3 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -303,6 +303,8 @@ export async function purgeDeletedPages(SELECT slug, deleted_at FROM pagesWHERE deleted_at IS NOT NULLAND deleted_at < now() - (${hours} || ' hours')::interval+ 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())ORDER BY deleted_at ASC, slug ASC`);const pages = rows.map((r) => ({@@ -315,6 +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).+ 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())RETURNING slug`);const slugs = rows.map((r) => r.slug);diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.tsindex 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/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex 0a6df19b7a..bb50e313e2 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -8,6 +8,7 @@ import { submitPageMutation } from './page-mutations.ts';import { withBeliefBatch } from '../belief/ledger.ts';import { markBeliefCommits } from '../belief/append.ts';import { linkStreamSlugs } from './page-purge.ts';+import { identityDowngradePurgeHold } from '../sync-identity-downgrades.ts';/** A tombstone that moved under a concurrent writer; the next run retries it. */const DEFERRAL_CODES = new Set(['revision_conflict', 'page_not_found', 'page_identity_changed']);@@ -62,7 +63,7 @@ export async function consentedPurgeDeletedPages(engine: BrainEngine, olderThanHasync function expireRecordedTombstones(engine: BrainEngine, olderThanHours: number): Promise<string[]> {const hours = String(Math.max(0, Math.floor(olderThanHours)));const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string }>(`SELECT p.id, p.source_id, p.slug FROM pages p- WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND ${identityDowngradePurgeHold('p')}AND EXISTS (SELECT 1 FROM belief_events e WHERE e.source_id = p.source_id AND e.subject_kind = 'coverage')ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [hours]);const slugs: string[] = [];@@ -72,7 +73,7 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: numconst slugs = [...new Set([row.slug, ...await linkStreamSlugs(tx, row.source_id, row.id)])].sort();await tx.lockPageKeys(slugs.map(slug => ({ sourceId: row.source_id, slug })));return withBeliefBatch(tx, { sourceId: row.source_id, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report },- async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval RETURNING id`,+ async () => (await tx.executeRaw(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} RETURNING id`,[row.id, hours])).length > 0);});if (report.appended) await markBeliefCommits(engine, [publicationId]).catch(() => undefined);@@ -98,7 +99,7 @@ export async function purgeDeletedPagesCoordinated(engine: BrainEngine, olderThaconst hours = Math.max(0, Math.floor(olderThanHours));const rows = await engine.executeRaw<{ source_id: string; slug: string; cutoff: string }>(`SELECT p.source_id, p.slug, (now() - ($1 || ' hours')::interval)::text AS cutoff FROM pages p JOIN sources s ON s.id = p.source_id- WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived+ WHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - ($1 || ' hours')::interval AND NOT s.archived AND ${identityDowngradePurgeHold('p')}ORDER BY p.deleted_at ASC, p.source_id ASC, p.slug ASC`, [String(hours)]);const config = loadConfig() ?? { engine: engine.kind };const slugs: string[] = [];diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.tsindex 637b0e20ff..64988dd158 100644--- a/src/core/persistence/sync-discovery.ts+++ b/src/core/persistence/sync-discovery.ts@@ -9,7 +9,8 @@ import { managedForbiddenFlag, managedSyncFlagRefusal } from './managed-sync-flaimport type { Action } from '../agent-output.ts';import type { RegistryCode } from '../error-registry.ts';import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';-import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';+import { confirmedSyncDelta, confirmRenameIdentities, frontmatterIdentity } from '../sync-rename-identity.ts';+import { isSyncable, isCodeFilePath, isImageFilePath, matchesAnyGlob, resolveSlugForPath, type DowngradedRename, type SyncManifest } from '../sync.ts';import { resolveSlugRootMode } from '../sync-anchor.ts';import { isWriteTargetContained } from '../path-confine.ts';import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';@@ -59,7 +60,9 @@ export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot/** #5459 (P4.5): live pages the tree walk left alone because their file is in the working tree and their import provenance is the working tree or unknown. */workingTreeKept?: string[];/** #6349 (P4.4): this discovery is one path slice of its target; the checkpoint records it instead of advancing `last_commit` until `done`. */- slice?: SyncSliceState; }+ slice?: SyncSliceState;+ /** #6729: inexact Git renames split into a delete plus an add (origin form); recorded after the run commits. */+ identityDowngrades?: DowngradedRename[]; }export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;source: { last_commit: string | null; config: Record<string, unknown> }; }/** The persisted `sync.exclude` globs (plus a run's `--exclude`), as discovery matches them against a path relative to the source root. */@@ -291,8 +294,10 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cconst detached = !company && syncGit(gitRoot, ['rev-parse', '--abbrev-ref', 'HEAD']).trim() === 'HEAD';// #6349: a staged run stops at a commit, so uncommitted working-tree changes wait for the stage that reaches HEAD.const working = !company && !stage && (detached || (opts.workingTree ?? (await engine.getConfig('sync.include_working_tree') === 'true')));- const dirty = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitRoot);- const delta = !opts.full && !walk && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;+ // #6729: inexact renames keep their page identity only when confirmed (an imported dirty tree reads its target side from the working tree).+ const confirm = { sourceId, sourcePathOf: sourcePath }, built: SyncManifest = company ? { added: [], modified: [], deleted: [], renamed: [] } : buildDetachedWorkingTreeManifest(gitRoot);+ const dirty = working ? await confirmRenameIdentities(engine, gitRoot, 'HEAD', null, built, confirm) : built;+ const delta = !opts.full && !walk && source.last_commit ? await confirmedSyncDelta(engine, gitRoot, source.last_commit, target, confirm) : null;const entries = new Map<string, SyncEntry>();const renamedFrom = new Map<string, string>();let workingTreeKept: string[] | undefined;@@ -309,10 +314,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c// A deletion or rename touching one is refused on both sides, so the page// keeps its identity until the change is synced from macOS or Linux.const refused = new Map<string, SyncFileRefusal>();- const refusalMessages = {- import: (path: string) => `${path} has a ':' in its name, which Windows cannot store; sync skipped it.`,- delete: (path: string) => `${path} has a ':' in its name, which Windows cannot reconcile; sync skipped its deletion and its page stays live.`,- };+ const refusalMessages = { import: (path: string) => `${path} has a ':' in its name, which Windows cannot store; sync skipped it.`,+ delete: (path: string) => `${path} has a ':' in its name, which Windows cannot reconcile; sync skipped its deletion and its page stays live.` };const record = (path: string, message: string) => {if (eligible(path)) refused.set(path, { path, code: 'colon_slug_windows_write_through', message,suggestion: `Rename it without ':' on a macOS or Linux checkout and commit, then run gbrain sync --source ${sourceId} --no-pull.`,@@ -450,11 +453,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}const discovered: SyncDiscovery = { discoveredAt, ...(released.length ? { releasedHolds: released } : {}), ...(retryTaken.length ? { retryTaken } : {}),...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}), ...(stage ? { stagedHead: stage.head } : {}),- ...(workingTreeKept ? { workingTreeKept } : {}) };+ ...(workingTreeKept ? { workingTreeKept } : {}), ...(company ? {} : identityDowngradesOf([delta?.status === 'ok' ? delta.manifest : null, working ? dirty : null], eligible, sourcePath)) };// Freeze all logical identities in one database statement, before yielding// between pages. A later interactive edit must conflict with this scan.- const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string; deleted_at: Date | string | null }>(- 'SELECT id,slug,source_path,knowledge_revision,deleted_at FROM pages WHERE source_id=$1', [sourceId]);+ const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string; deleted_at: Date | string | null; fm_id: string | null }>(+ "SELECT id,slug,source_path,knowledge_revision,deleted_at,frontmatter->>'id' AS fm_id FROM pages WHERE source_id=$1", [sourceId]);const bySlug = new Map(identities.map(p => [p.slug, p]));const byPath = new Map<string, typeof identities>();const storableIdentities = identities.filter(storable);@@ -521,6 +524,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, cif (losers.length) collisions.push({ slug, kept: kept ?? winner!.sourcePath, skipped: losers.map(entry => entry.sourcePath) });if (!winner) continue;if (holder) {+ assertTakeoverIdentity(discovered, winner, holder);// Same slug, vanished origin: the file takes over the page (and its history) instead of racing a deletion.Object.assign(winner, { pageId: holder.id, revision: holder.knowledge_revision });if (holderOrigin !== null) {@@ -561,6 +565,26 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c}return discovered;}+/** #6729: the inexact Git renames this discovery split into a delete plus an add, in origin form, for the sync report and its durable record. */+function identityDowngradesOf(manifests: Array<SyncManifest | null>, eligible: (path: string) => boolean, sourcePath: (path: string) => string): Pick<SyncDiscovery, 'identityDowngrades'> {+ const pairs = manifests.flatMap(manifest => manifest?.downgradedRenames ?? []).filter(pair => eligible(pair.from) || eligible(pair.to))+ .map(pair => ({ ...pair, from: sourcePath(pair.from), to: sourcePath(pair.to) }));+ return pairs.length ? { identityDowngrades: pairs } : {};+}+/**+ * #6729: a file that takes over the page holding its slug (a vanished or deleted origin) inherits that page's identity,+ * so it must not when both carry an explicit frontmatter id and the ids differ: they are two different documents that+ * happen to map to one slug. The sync is refused before any write, naming both.+ */+function assertTakeoverIdentity(discovery: SyncDiscovery, winner: SyncEntry, holder: { slug: string; fm_id: string | null }): void {+ if (!holder.fm_id) return;+ const incoming = frontmatterIdentity(readSyncContent(discovery, winner)).id;+ if (!incoming || incoming === holder.fm_id) return;+ throw opError('page_identity_changed', 'A file would take over a page whose frontmatter id differs from its own.',+ `${winner.sourcePath} in ${discovery.sourceId} maps to page ${holder.slug}, whose file is gone, but its frontmatter id '${incoming}' differs from the page's id '${holder.fm_id}', so it is a different document and must not inherit that page's facts, links and history; nothing was written. `+ + `Give the file the page's id if it is the same document, or rename it so its slug differs, commit, then run gbrain sync --no-pull --source ${discovery.sourceId}.`,+ { detail: 'rename_identity_conflict' });+}/** #6517: several live pages (the soft-delete exit is named) or several tombstones record one imported origin. */function ambiguousOriginRefusal(sourceId: string, sourcePath: string, named: Array<{ slug: string }>, ambiguous: 'several_live' | 'several_tombstones'): OperationError {return opError('page_identity_changed', 'Several pages claim the same imported origin.',diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 680c7b2dad..8d80f9ea07 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -68,6 +68,8 @@ import { withSyncTail } from './sync-tail.ts';import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';+import { serr } from '../console-prefix.ts';+import { noteIdentityDowngrades } from '../sync-identity-downgrades.ts';export interface ManagedSyncWriteDiagnostic {source_id: string;@@ -304,7 +306,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], reareturn { status, ...(cursor.authority.writer.remote ? {} : { runId: cursor.runId }), fromCommit: cursor.authority.writer.remote ? null : cursor.from,toCommit: cursor.authority.writer.remote ? '' : cursor.target, added: cursor.counts.added, modified: cursor.counts.modified,deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],- ...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),+ ...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}), ...(cursor.identityDowngrades?.length ? { identityDowngrades: cursor.identityDowngrades } : {}),...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}), ...(cursor.workingTreeKept?.length ? { working_tree_kept: cursor.workingTreeKept.length } : {}),...(cursor.stagedHead && !cursor.authority.writer.remote ? { staged: { target: cursor.target, head: cursor.stagedHead, ...(cursor.slice && !cursor.slice.done ? { slice: { phase: cursor.slice.phase, after: cursor.slice.after } } : {}) } } : {}),waived: { imports: cursor.counts.waived?.imports ?? 0, deletes: cursor.counts.waived?.deletes ?? 0 }, prescreened: cursor.counts.prescreened ?? 0,@@ -1404,7 +1406,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl}async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {const state: HoldRunState = {};- const synced = await runManagedSync(engine, opts, slice, state);+ // #6729: every managed entry point (CLI, drain, owner slice, worktree refresh) records the renames whose identity it did not keep.+ const synced = await noteIdentityDowngrades(engine, opts.sourceId ?? 'default', await runManagedSync(engine, opts, slice, state), serr);if (!state.sourceId || !state.incarnation || synced.status === 'dry_run') return synced;const cursor = state.cursor?.() ?? null;try {diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex a9b849a107..8a50f2c8c0 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -42,6 +42,7 @@ import { classifyRecordedFault, classifyTerminal, type TerminalCategory } from 'import type { PublicCategory } from './public-category.ts';import { readSyncFile, resolveManagedSyncContext } from './sync-discovery.ts';import { sha256 } from './digest.ts';+import { listIdentityDowngrades } from '../sync-identity-downgrades.ts';export interface SyncStatusHold extends SyncFaultVerdict {code: string;@@ -88,6 +89,8 @@ 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). */+ 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. */needs_human: boolean;@@ -297,7 +300,7 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string, optsconst [state, stateReason] = statusState({ human: !!human, oldest, recovery, liveJob: liveJob !== null, unfinished, lastError: !!lastError, actionable: actionable.length > 0, holds: holds.length > 0 });return { source_id: sourceId, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,- committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),+ committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, identity_downgrades: await listIdentityDowngrades(engine, [sourceId]), last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),resume_argv: resume, ...blockers, cursors: detail ? await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures) : [],terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? (stateReason === 'request_pending' && oldest.status === 'ok' && oldest.request ? { argv: ['gbrain', 'sync', ...resume], consent: [], actor: 'agent', requires_exclusive: false, verify,why: `Write request ${oldest.request.request_id} of this source is still ${oldest.request.state}${oldest.request.step ? ` (step ${oldest.request.step})` : ''}; a running owner finishes it on its own, and the next sync of this source drains it.` } satisfies Actiondiff --git a/src/core/repair/rename-identity.ts b/src/core/repair/rename-identity.tsnew file mode 100644index 0000000000..36bcbfdefb--- /dev/null+++ b/src/core/repair/rename-identity.ts@@ -0,0 +1,67 @@+/**+ * `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-delta.ts b/src/core/sync-delta.tsindex 6377c0ce52..beba40fc0f 100644--- a/src/core/sync-delta.ts+++ b/src/core/sync-delta.ts@@ -65,6 +65,18 @@ function unique<T>(items: T[]): T[] {return [...new Set(items)];}+/** Merges a working-tree manifest into a commit-range manifest (paths deduplicated; renames and #6729 downgrades appended). */+export function mergeSyncManifests(into: SyncManifest, from: SyncManifest): SyncManifest {+ const downgradedRenames = [...(into.downgradedRenames ?? []), ...(from.downgradedRenames ?? [])];+ return {+ added: unique([...into.added, ...from.added]),+ modified: unique([...into.modified, ...from.modified]),+ deleted: unique([...into.deleted, ...from.deleted]),+ renamed: [...into.renamed, ...from.renamed],+ ...(downgradedRenames.length ? { downgradedRenames } : {}),+ };+}+/*** Working-tree manifest: tracked changes (`git diff --name-status -M HEAD`)* PLUS untracked files (`ls-files --others --exclude-standard`). Built for@@ -144,12 +156,5 @@ export function computeSyncDelta(: opts.detached? buildDetachedWorkingTreeManifest(repoPath, run): null;- if (detached) {- manifest.added = unique([...manifest.added, ...detached.added]);- manifest.modified = unique([...manifest.modified, ...detached.modified]);- manifest.deleted = unique([...manifest.deleted, ...detached.deleted]);- manifest.renamed = [...manifest.renamed, ...detached.renamed];- }-- return { status: 'ok', manifest };+ return { status: 'ok', manifest: detached ? mergeSyncManifests(manifest, detached) : manifest };}diff --git a/src/core/sync-identity-downgrades.ts b/src/core/sync-identity-downgrades.tsnew file mode 100644index 0000000000..6da2f80e22--- /dev/null+++ b/src/core/sync-identity-downgrades.ts@@ -0,0 +1,128 @@+/**+ * #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.+ *+ * 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).+ */+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;+ /** The soft-deleted page the old file backed, and the page the new file imported to (null when it did not import). */+ 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;+}++/** 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())`;+}++const REASON_TEXT: Record<RenameDowngradeReason, string> = {+ id_conflict: 'the two files carry different frontmatter ids',+ id_shared: 'their frontmatter id is also carried by another file or page',+ id_one_side: 'only one side carries a frontmatter id',+ title_not_unique: 'their shared title is not unique',+ slug_not_unique: 'their shared slug: line is not unique',+ no_identity_signal: 'no frontmatter id, slug: or title matches',+};+export const identityDowngradeReasonText = (reason: RenameDowngradeReason): string => REASON_TEXT[reason];++/**+ * Records the downgraded pairs of a finished sync (paths in the source's origin form). A pair whose old page is not+ * soft-deleted (the delete did not land, or the old file never imported) has nothing to carry and is not recorded.+ */+export async function recordIdentityDowngrades(engine: BrainEngine, sourceId: string, pairs: DowngradedRename[]): Promise<IdentityDowngrade[]> {+ const records: IdentityDowngrade[] = [];+ for (const pair of pairs) {+ const [old] = await engine.executeRaw<{ id: number | string; slug: string; deleted_at: string }>(+ `SELECT id, slug, deleted_at::text AS deleted_at FROM pages WHERE source_id = $1 AND deleted_at IS NOT NULL+ AND (source_path = $2 OR (source_path IS NULL AND slug = $3)) ORDER BY deleted_at DESC LIMIT 1`,+ [sourceId, pair.from, resolveSlugForPath(pair.from)]);+ if (!old) continue;+ const [fresh] = await engine.executeRaw<{ slug: string }>(+ 'SELECT slug FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND source_path = $2 LIMIT 1', [sourceId, pair.to]);+ const [counts] = await engine.executeRaw<{ facts: number | string; links: number | string; aliases: number | string }>(`SELECT+ (SELECT count(*) FROM facts WHERE source_id = $1 AND entity_slug = $2) AS facts,+ (SELECT count(*) FROM links WHERE from_page_id = $3 OR to_page_id = $3) AS links,+ (SELECT count(*) FROM page_aliases WHERE source_id = $1 AND slug = $2) AS aliases`, [sourceId, old.slug, Number(old.id)]);+ const recorded = new Date(old.deleted_at);+ const record: IdentityDowngrade = { source_id: sourceId, from: pair.from, to: pair.to, similarity: pair.similarity, reason: pair.reason,+ 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() };+ 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])]);+ records.push(record);+ }+ return records;+}++/**+ * Open records (inside the window, old page still soft-deleted), 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.fingerprint+ LEFT 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()+ 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 }));+}++/** 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;++/**+ * After a sync that committed (synced or first sync, not a dry run): records its downgraded pairs, prints the report+ * lines, and returns the result with the recorded entries in place of the raw pairs. A recording failure is one line+ * and never fails the sync.+ */+export async function noteIdentityDowngrades<T extends { status: string; identityDowngrades?: DowngradedRename[] }>(engine: BrainEngine, sourceId: string,+ result: T, write: (line: string) => void): Promise<T> {+ const pairs = (result.identityDowngrades ?? []).filter(pair => !isRecordedDowngrade(pair));+ if (!pairs.length || !['synced', 'first_sync'].includes(result.status)) return result;+ try {+ const records = await recordIdentityDowngrades(engine, sourceId, pairs);+ for (const line of identityDowngradeLines(records)) write(line);+ return { ...result, identityDowngrades: records };+ } catch (error) {+ write(` Could not record ${pairs.length} rename(s) whose identity was not kept: ${error instanceof Error ? error.message : String(error)}`);+ return result;+ }+}++/** The read-only preview of the remedy for one source. */+export const identityRemedyPreviewArgv = (sourceId: string): string[] => ['gbrain', 'repair', 'rename-identity', '--source', sourceId];++/** 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>.`,+ ];+}diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.tsnew file mode 100644index 0000000000..558787f7af--- /dev/null+++ b/src/core/sync-rename-identity.ts@@ -0,0 +1,244 @@+/**+ * #6729: Git pairs renames by content similarity, so `git diff -M` can pair+ * two near-identical files the wrong way round when they are moved and+ * rewritten in one range. Every sync path used to carry the old page's+ * identity (facts, links, aliases, a slug redirect) across each pair, so a+ * wrong guess moved one page's knowledge onto another.+ *+ * confirmRenameIdentities is the one stage between the manifest parser and+ * every consumer (classic, managed and the dirty-tree manifest):+ *+ * - an exact rename (R100, byte-identical) stays a rename;+ * - an inexact pair keeps its identity only when (a) both sides carry the+ * same frontmatter id and no other file in the range or live page+ * carries it, or (b) neither side has an id and the frontmatter slug:+ * or title matches, that value is unique across every deleted and added+ * path of the range, and (for a title) no other live page has it.+ * Conflicting ids veto;+ * - an added file whose id uniquely matches a file deleted in the same+ * range is a rename (a move and an edit in separate commits, or a pair+ * Git crossed);+ * - every other inexact pair becomes a delete plus an add and is listed in+ * downgradedRenames.+ *+ * Both sides are read through one git cat-file --batch stream (frontmatter+ * only: at most the first 64 KiB of each blob is kept).+ */+import { lstatSync, openSync, readSync, closeSync } from 'node:fs';+import { resolve, sep } from 'node:path';+import { JSON_SCHEMA, load as yamlLoad } from 'js-yaml';+import type { BrainEngine } from './engine.ts';+import { spawn } from './spawn.ts';+import { gitChildEnv } from './git-env.ts';+import { isMarkdownFilePath, resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason, type SyncManifest } from './sync.ts';+import { computeSyncDelta, type SyncDeltaResult } from './sync-delta.ts';++const HEAD_BYTES = 64 * 1024;++export interface FrontmatterIdentity { id: string | null; slug: string | null; title: string | null }+const NO_IDENTITY: FrontmatterIdentity = { id: null, slug: null, title: null };++/** The identity fields of a file's leading frontmatter block; unparseable or absent frontmatter carries none. */+export function frontmatterIdentity(head: Buffer | string | null): FrontmatterIdentity {+ if (head === null) return NO_IDENTITY;+ const text = (typeof head === 'string' ? head : head.toString('utf8')).replace(/^\uFEFF/, '');+ const block = /^---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(text);+ if (!block) return NO_IDENTITY;+ let data: unknown;+ try { data = yamlLoad(block[1]!, { schema: JSON_SCHEMA }); } catch { return NO_IDENTITY; }+ if (!data || typeof data !== 'object' || Array.isArray(data)) return NO_IDENTITY;+ const field = (key: string, numeric = false): string | null => {+ const value = (data as Record<string, unknown>)[key];+ const text = typeof value === 'string' ? value.trim() : numeric && typeof value === 'number' && Number.isFinite(value) ? String(value) : '';+ return text === '' ? null : text;+ };+ return { id: field('id', true), slug: field('slug'), title: field('title') };+}++/** The first 64 KiB of each `<rev>:<path>` object through one `git cat-file --batch` stream; null for a missing object or a non-blob. */+export async function catFileHeads(repo: string, objects: string[]): Promise<Array<Buffer | null>> {+ if (objects.length === 0) return [];+ return new Promise((done, fail) => {+ const child = spawn('git', ['-c', 'core.quotepath=false', '-C', repo, 'cat-file', '--batch'], { env: gitChildEnv(), stdio: ['pipe', 'pipe', 'pipe'] });+ const out: Array<Buffer | null> = [];+ let pending: Buffer = Buffer.alloc(0), remaining = -1, blob = false, kept: Buffer[] = [], keptBytes = 0, stderr = '';+ child.stdout!.on('data', (chunk: Buffer) => {+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;+ for (;;) {+ if (remaining < 0) {+ const newline = pending.indexOf(10);+ if (newline < 0) return;+ const header = /^[0-9a-f]{40,64} (\S+) (\d+)$/.exec(pending.subarray(0, newline).toString('utf8'));+ pending = pending.subarray(newline + 1);+ if (!header) { out.push(null); continue; }+ blob = header[1] === 'blob'; remaining = Number(header[2]) + 1; kept = []; keptBytes = 0;+ continue;+ }+ if (pending.length === 0) return;+ const piece = pending.subarray(0, Math.min(remaining, pending.length));+ if (keptBytes < HEAD_BYTES) { const keep = piece.subarray(0, HEAD_BYTES - keptBytes); kept.push(Buffer.from(keep)); keptBytes += keep.length; }+ pending = pending.subarray(piece.length); remaining -= piece.length;+ if (remaining === 0) { remaining = -1; out.push(blob ? Buffer.concat(kept) : null); }+ }+ });+ child.stderr!.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8').slice(0, 2000); });+ child.on('error', fail);+ child.on('close', (code: number | null) => {+ if (code !== 0 || out.length !== objects.length) fail(new Error(`git cat-file --batch failed in ${repo} (exit ${code}): ${stderr.trim().slice(0, 300)}`));+ else done(out);+ });+ child.stdin!.end(objects.map(object => `${object}\n`).join(''));+ });+}++/** The first 64 KiB of a regular file inside `root`; null for a missing, escaping or non-regular path. */+function workingTreeHead(root: string, path: string): Buffer | null {+ const base = resolve(root);+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- a git-reported repo-relative path, accepted only when it stays inside the repo root (checked on the next line) and is a regular file, never a symlink+ const absolute = resolve(base, path);+ if (!absolute.startsWith(base + sep)) return null;+ try {+ if (!lstatSync(absolute).isFile()) return null;+ const fd = openSync(absolute, 'r');+ try {+ const buffer = Buffer.alloc(HEAD_BYTES);+ return buffer.subarray(0, readSync(fd, buffer, 0, HEAD_BYTES, 0));+ } finally { closeSync(fd); }+ } catch { return null; }+}++/** A live page that shares an identity value with a renamed file; `source_path` and `slug` tell whether it belongs to a path of this range. */+export interface LiveIdentityHolder { slug: string; source_path: string | null; fm_id: string | null; title: string | null }++export interface RenameIdentityInputs {+ /** Frontmatter of the base side (deleted and renamed-from paths) and the target side (added and renamed-to paths). */+ base: (path: string) => FrontmatterIdentity;+ target: (path: string) => FrontmatterIdentity;+ /** Live pages carrying any candidate id or title. */+ live: LiveIdentityHolder[];+ /** Maps a Git path to its source-relative form; a page recording either form belongs to the range. */+ sourcePathOf?: (gitPath: string) => string;+}++/** Inexact pairs, or an add/delete pool rule (c) can pair; with neither the manifest passes through untouched. */+export function needsRenameConfirmation(manifest: SyncManifest): boolean {+ return manifest.renamed.some(rename => rename.similarity !== undefined && rename.similarity < 100)+ || (manifest.added.some(isMarkdownFilePath) && manifest.deleted.some(isMarkdownFilePath));+}++/**+ * The pure decision over one manifest (see the module header). Returns a new manifest: confirmed renames stay in+ * `renamed`, every other inexact pair is split into `deleted` + `added` and listed in `downgradedRenames`.+ */+export function decideRenameIdentities(manifest: SyncManifest, inputs: RenameIdentityInputs): SyncManifest {+ if (!needsRenameConfirmation(manifest)) return manifest;+ const sourcePathOf = inputs.sourcePathOf ?? ((path: string) => path);+ const exact = manifest.renamed.filter(rename => rename.similarity === undefined || rename.similarity >= 100);+ const inexact = manifest.renamed.filter(rename => rename.similarity !== undefined && rename.similarity < 100);+ const baseSide = [...manifest.deleted, ...manifest.renamed.map(rename => rename.from)];+ const targetSide = [...manifest.added, ...manifest.renamed.map(rename => rename.to)];+ const counter = (paths: string[], read: (path: string) => FrontmatterIdentity) => {+ const counts = new Map<string, number>();+ const bump = (key: string) => counts.set(key, (counts.get(key) ?? 0) + 1);+ for (const path of paths) {+ const identity = read(path);+ if (identity.id) bump(`id\0${identity.id}`);+ if (identity.slug) bump(`slug\0${identity.slug}`);+ if (identity.title) bump(`title\0${identity.title}`);+ }+ return (key: string) => counts.get(key) ?? 0;+ };+ const baseCount = counter(baseSide, inputs.base), targetCount = counter(targetSide, inputs.target);+ // A live page belonging to a path this range removes or rewrites is the page being decided, not a competitor.+ const rangeOrigins = new Set([...baseSide, ...targetSide].flatMap(path => [path, sourcePathOf(path)]));+ const rangeSlugs = new Set([...rangeOrigins].map(path => resolveSlugForPath(path)).filter(Boolean));+ const competitors = inputs.live.filter(page => page.source_path !== null ? !rangeOrigins.has(page.source_path) : !rangeSlugs.has(page.slug));+ const liveIds = new Set(competitors.flatMap(page => page.fm_id ? [page.fm_id] : []));+ const liveTitles = new Set(competitors.flatMap(page => page.title ? [page.title] : []));+ const uniqueId = (id: string) => baseCount(`id\0${id}`) === 1 && targetCount(`id\0${id}`) === 1 && !liveIds.has(id);++ const confirmed: SyncManifest['renamed'] = [];+ const downgraded: DowngradedRename[] = [];+ for (const rename of inexact) {+ const before = inputs.base(rename.from), after = inputs.target(rename.to);+ const downgrade = (reason: RenameDowngradeReason) => downgraded.push({ from: rename.from, to: rename.to, similarity: rename.similarity!, reason });+ if (before.id && after.id) {+ if (before.id !== after.id) downgrade('id_conflict');+ else if (uniqueId(before.id)) confirmed.push(rename);+ else downgrade('id_shared');+ continue;+ }+ if (before.id || after.id) { downgrade('id_one_side'); continue; }+ const unique = (kind: 'slug' | 'title', value: string) => baseCount(`${kind}\0${value}`) === 1 && targetCount(`${kind}\0${value}`) === 1;+ if (before.slug && before.slug === after.slug && unique('slug', before.slug)) { confirmed.push(rename); continue; }+ if (before.title && before.title === after.title) {+ if (unique('title', before.title) && !liveTitles.has(before.title)) confirmed.push(rename);+ else downgrade('title_not_unique');+ continue;+ }+ downgrade(before.slug && before.slug === after.slug ? 'slug_not_unique' : 'no_identity_signal');+ }++ // Rule (c): an added file whose id uniquely matches a file this range deletes keeps that page's identity.+ const added = [...manifest.added, ...downgraded.map(pair => pair.to)];+ const deleted = [...manifest.deleted, ...downgraded.map(pair => pair.from)];+ const deletedById = new Map<string, string[]>();+ for (const path of deleted) {+ const id = isMarkdownFilePath(path) ? inputs.base(path).id : null;+ if (id) deletedById.set(id, [...(deletedById.get(id) ?? []), path]);+ }+ const promoted: SyncManifest['renamed'] = [];+ for (const path of added) {+ const id = isMarkdownFilePath(path) ? inputs.target(path).id : null;+ const from = id ? deletedById.get(id) : undefined;+ if (!id || from?.length !== 1 || !uniqueId(id)) continue;+ promoted.push({ from: from[0]!, to: path });+ }+ const promotedFrom = new Set(promoted.map(pair => pair.from)), promotedTo = new Set(promoted.map(pair => pair.to));+ const remaining = downgraded.filter(pair => !promotedFrom.has(pair.from) && !promotedTo.has(pair.to));+ return {+ added: added.filter(path => !promotedTo.has(path)),+ modified: manifest.modified,+ deleted: deleted.filter(path => !promotedFrom.has(path)),+ renamed: [...exact, ...confirmed, ...promoted],+ downgradedRenames: [...(manifest.downgradedRenames ?? []), ...remaining],+ };+}++export interface ConfirmRenameOpts { sourceId: string; /** See `RenameIdentityInputs.sourcePathOf`. */ sourcePathOf?: (gitPath: string) => string }++/**+ * Reads both sides' frontmatter and the live pages sharing their ids and titles, then applies+ * `decideRenameIdentities`. `target` null reads the target side from the working tree (the dirty-tree manifest,+ * whose base is HEAD).+ */+export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'executeRaw'>, repo: string, base: string, target: string | null,+ manifest: SyncManifest, opts: ConfirmRenameOpts): Promise<SyncManifest> {+ if (!needsRenameConfirmation(manifest)) return manifest;+ const readable = (path: string) => isMarkdownFilePath(path) && !path.includes('\n');+ const basePaths = [...new Set([...manifest.deleted, ...manifest.renamed.map(rename => rename.from)].filter(readable))];+ const targetPaths = [...new Set([...manifest.added, ...manifest.renamed.map(rename => rename.to)].filter(readable))];+ const objects = [...basePaths.map(path => `${base}:${path}`), ...(target === null ? [] : targetPaths.map(path => `${target}:${path}`))];+ const heads = await catFileHeads(repo, objects);+ const baseIdentity = new Map(basePaths.map((path, index) => [path, frontmatterIdentity(heads[index] ?? null)]));+ const targetIdentity = new Map(targetPaths.map((path, index) => [path,+ frontmatterIdentity(target === null ? workingTreeHead(repo, path) : heads[basePaths.length + index] ?? null)]));+ const identities = [...baseIdentity.values(), ...targetIdentity.values()];+ const ids = [...new Set(identities.flatMap(identity => identity.id ? [identity.id] : []))];+ const titles = [...new Set(identities.flatMap(identity => identity.title ? [identity.title] : []))];+ const live = ids.length || titles.length ? await engine.executeRaw<LiveIdentityHolder>(+ `SELECT slug, source_path, frontmatter->>'id' AS fm_id, title FROM pages+ WHERE source_id = $1 AND deleted_at IS NULL AND (frontmatter->>'id' = ANY($2::text[]) OR title = ANY($3::text[]))`,+ [opts.sourceId, ids, titles]) : [];+ return decideRenameIdentities(manifest, {+ base: path => baseIdentity.get(path) ?? NO_IDENTITY,+ target: path => targetIdentity.get(path) ?? NO_IDENTITY,+ live, sourcePathOf: opts.sourcePathOf,+ });+}++/** `computeSyncDelta` of a commit range with its renames confirmed (the commit-range half of every incremental sync). */+export async function confirmedSyncDelta(engine: Pick<BrainEngine, 'executeRaw'>, repo: string, from: string, to: string, opts: ConfirmRenameOpts): Promise<SyncDeltaResult> {+ const delta = computeSyncDelta(repo, from, to);+ return delta.status === 'ok' ? { status: 'ok', manifest: await confirmRenameIdentities(engine, repo, from, to, delta.manifest, opts) } : delta;+}diff --git a/src/core/sync.ts b/src/core/sync.tsindex 595241d549..70e3995d9a 100644--- a/src/core/sync.ts+++ b/src/core/sync.ts@@ -23,9 +23,16 @@ export interface SyncManifest {added: string[];modified: string[];deleted: string[];- renamed: Array<{ from: string; to: string }>;+ /** `similarity`: Git's rename score (100 = byte-identical); absent for a pairing that did not come from Git's similarity guess. */+ renamed: Array<{ from: string; to: string; similarity?: number }>;+ /** #6729: inexact Git renames whose identity could not be confirmed; each was split into a delete of `from` plus an add of `to`. */+ downgradedRenames?: DowngradedRename[];}+/** #6729: why an inexact Git rename did not keep its page identity (see `confirmRenameIdentities`). */+export type RenameDowngradeReason = 'id_conflict' | 'id_shared' | 'id_one_side' | 'title_not_unique' | 'slug_not_unique' | 'no_identity_signal';+export interface DowngradedRename { from: string; to: string; similarity: number; reason: RenameDowngradeReason }+export interface RawManifestEntry {action: 'A' | 'M' | 'D' | 'R';path: string;@@ -228,7 +235,9 @@ export function buildSyncManifest(gitDiffOutput: string): SyncManifest {// A copy leaves the source in place — only the destination is new.manifest.added.push(newPath);} else {- manifest.renamed.push({ from: oldPath, to: newPath });+ // #6729: the score rides along; confirmRenameIdentities decides whether an inexact pair keeps its identity.+ const similarity = Number(action.slice(1));+ manifest.renamed.push({ from: oldPath, to: newPath, ...(action.length > 1 && Number.isInteger(similarity) ? { similarity } : {}) });}}}diff --git a/test/hold-action-chain-6712.test.ts b/test/hold-action-chain-6712.test.tsindex 8e0a937284..511700e08c 100644--- a/test/hold-action-chain-6712.test.ts+++ b/test/hold-action-chain-6712.test.ts@@ -64,7 +64,6 @@ const LONG = Array.from({ length: 40 }, (_, i) => `Line ${i} of a long syntheticconst long = (title: string) => note(title, LONG);const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');const FOLDED = '---\ntitle: alice-example first line\nalice-example second line\n---\nA synthetic post.\n';-const LONG_BROKEN = `---\ntitle: alice-example first line\nalice-example second line\n---\n${LONG}\n`;const TAKES = (who: string) => `---\ntitle: Holder\n---\nA synthetic page.\n\n<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|---|---|---|---|---|---|\n`+ `| 1 | Synthetic take | take | ${who} | 0.7 | 2026-01 | chat |\n<!--- gbrain:takes:end -->\n`;@@ -232,10 +231,11 @@ test('invalid_frontmatter: the preview, then its hash-bound apply, clears the ho}), 180_000);test('rename_held: re-binding the rename to the current page clears the hold', () => each(async engine => {- const s = await managed(engine, { 'notes/x.md': long('X') });+ // #6729: an exact move (R100) whose slug: line still names the old path holds with the old page's identity.+ const s = await managed(engine, { 'notes/x.md': long('X').replace('title: X', 'title: X\nslug: notes/x') });await s.sync();const x = (await engine.getPage('notes/x', { sourceId: s.id }))!;- git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); s.write('notes/y.md', LONG_BROKEN); commit(s.root, 'x to y broken');+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); commit(s.root, 'x to y, held');await s.sync();await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);diff --git a/test/large-pages/managed-sync-segmented-rename.test.ts b/test/large-pages/managed-sync-segmented-rename.test.tsindex 2759235b7f..a846e914da 100644--- a/test/large-pages/managed-sync-segmented-rename.test.ts+++ b/test/large-pages/managed-sync-segmented-rename.test.ts@@ -34,7 +34,8 @@ const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-rename-'));const engines: BrainEngine[] = [];let closePostgres: (() => Promise<void>) | undefined;const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };-const original = conversationPage(1536 * 1024, { seed: 61 });+/** #6729: the frontmatter id confirms the edited renames below (an inexact pair whose title changes keeps its identity only on a shared id). */+const original = conversationPage(1536 * 1024, { seed: 61 }).replace('title: Conversation log\n', 'id: conversation-log-6729\ntitle: Conversation log\n');/** Every fourth body line edited: git still pairs the files as a rename, and most segments change. */const edited = (text: string) => text.split('\n').map((line, i) => i > 6 && i % 4 === 0 && line ? `${line} edited` : line).join('\n');diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.tsindex 94041e1b4d..4a86d7c05f 100644--- a/test/persistence-sync-holds.test.ts+++ b/test/persistence-sync-holds.test.ts@@ -36,6 +36,8 @@ const FOLDED = '---\ntitle: alice-example first line\nalice-example second line\const LONG = Array.from({ length: 40 }, (_, i) => `Line ${i} of a long synthetic observation that keeps Git rename detection certain.`).join('\n');/** Same long body, so Git still detects a rename when only the frontmatter changes. */const long = (title: string) => `---\ntitle: ${title}\n---\n${LONG}\n`;+/** #6729: an explicit slug: line that an exact move (R100) leaves pointing at the old path, so the moved file is held with the old page's identity. */+const pinned = (title: string, slug: string) => `---\ntitle: ${title}\nslug: ${slug}\n---\n${LONG}\n`;const longBroken = `---\ntitle: alice-example first line\nalice-example second line\n---\n${LONG}\n`;const AUTHOR = '---\ntitle: Payments roundup\nauthor: PYMNTS (citing Reuters / Bloomberg) (original: https://x.com/a/status/1)\n---\nA synthetic roundup.\n';@@ -168,10 +170,11 @@ test('a sliced run that has not reached a held file leaves its hold untouched; a}), 180_000);test('renamed to a broken file keeps the old page, a later fix moves it with its id, and a full walk never deletes it meanwhile', () => each(async engine => {- const s = await source(engine, { 'notes/old.md': long('Old') });+ const s = await source(engine, { 'notes/old.md': pinned('Old', 'notes/old') });await s.sync();const page = (await engine.getPage('notes/old', { sourceId: s.id }))!;- git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); s.write('notes/new.md', longBroken); commit(s.root, 'rename to broken');+ git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); commit(s.root, 'exact move onto a stale slug: line');+ expect(git(s.root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toMatch(/^R100\t/);const held = await s.sync();expect(held.held?.[0]).toMatchObject({ path: 'notes/new.md', stale: false });expect((await s.holds())[0]!.meta.rename_from).toMatchObject({ slug: 'notes/old', pageId: page.id });@@ -187,18 +190,20 @@ test('renamed to a broken file keeps the old page, a later fix moves it with its}), 240_000);test('a chained rename carries the held identity, and a changed old page keeps the rename held as rename_held', () => each(async engine => {- const s = await source(engine, { 'notes/a.md': long('A'), 'notes/x.md': long('X') });+ const s = await source(engine, { 'notes/a.md': pinned('A', 'notes/a'), 'notes/x.md': pinned('X', 'notes/x') });await s.sync();const a = (await engine.getPage('notes/a', { sourceId: s.id }))!;- git(s.root, 'mv', 'notes/a.md', 'notes/b.md'); s.write('notes/b.md', longBroken); commit(s.root, 'a to b broken');+ git(s.root, 'mv', 'notes/a.md', 'notes/b.md'); commit(s.root, 'a to b, held');+ await s.sync();+ git(s.root, 'mv', 'notes/b.md', 'notes/c.md'); commit(s.root, 'b to c, still held');await s.sync();- git(s.root, 'mv', 'notes/b.md', 'notes/c.md'); s.write('notes/c.md', long('C')); commit(s.root, 'b to c fixed');+ s.write('notes/c.md', long('C')); commit(s.root, 'fix c');await s.sync();expect((await engine.getPage('notes/c', { sourceId: s.id }))?.id).toBe(a.id);expect(await s.holds()).toEqual([]);const x = (await engine.getPage('notes/x', { sourceId: s.id }))!;- git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); s.write('notes/y.md', longBroken); commit(s.root, 'x to y broken');+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); commit(s.root, 'x to y, held');await s.sync();await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);@@ -209,6 +214,32 @@ 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 => {+ const s = await source(engine, { 'notes/old.md': long('Old') });+ await s.sync();+ const page = (await engine.getPage('notes/old', { sourceId: s.id }))!;+ git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); s.write('notes/new.md', longBroken); commit(s.root, 'rename to broken');+ expect(git(s.root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toMatch(/^R0\d\d\tnotes\/old.md\tnotes\/new.md$/);+ const held = await s.sync();+ expect(held.held?.[0]).toMatchObject({ path: 'notes/new.md', code: 'invalid_frontmatter' });+ expect((await s.holds())[0]!.meta.rename_from).toBeUndefined();+ expect(held.identityDowngrades).toMatchObject([{ from: 'notes/old.md', to: 'notes/new.md', old_slug: 'notes/old', old_page_id: page.id, new_slug: null }]);+ const oldRow = async () => (await engine.executeRaw<{ id: number; deleted_at: string | null }>('SELECT id, deleted_at FROM pages WHERE source_id=$1 AND slug=$2', [s.id, 'notes/old']))[0];+ expect((await oldRow())!.deleted_at).not.toBeNull();+ s.write('notes/new.md', long('New')); commit(s.root, 'fix');+ await 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' }]);+}), 240_000);+test('the hold write and the cursor step past it commit together: a crash between them persists neither', () => each(async engine => {const s = await source(engine, { 'notes/a.md': note('A'), 'notes/broken.md': FOLDED, 'notes/c.md': note('C') });const cursor = async () => (await engine.executeRaw<{ header: { runId: string; index: number; counts: { held?: number } } }>(diff --git a/test/repair-frontmatter.test.ts b/test/repair-frontmatter.test.tsindex 4630d4560b..c663848bf3 100644--- a/test/repair-frontmatter.test.ts+++ b/test/repair-frontmatter.test.ts@@ -50,7 +50,8 @@ const folded = (n: number) => `---\ntitle: alice-example post ${n}\nsecond lineconst UNFIXABLE = '---\ntitle: Broken\n author: nobody\n tags: [a\n---\nBody.\n';const LONG = Array.from({ length: 40 }, (_, i) => `Line ${i} of a long synthetic observation that keeps Git rename detection certain.`).join('\n');const long = (title: string) => `---\ntitle: ${title}\n---\n${LONG}\n`;-const longBroken = `---\ntitle: alice-example first line\nalice-example second line\n---\n${LONG}\n`;+/** #6729: an explicit slug: line that an exact move (R100) leaves pointing at the old path, so the moved file is held with the old page's identity. */+const pinned = (title: string, slug: string) => `---\ntitle: ${title}\nslug: ${slug}\n---\n${LONG}\n`;beforeAll(async () => {if (backends.includes('pglite')) { const engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); engines.push(engine); }@@ -306,10 +307,11 @@ test('repair paths are confined: climbing, absolute and symlinked paths are refu});test('a held renamed file: the repair moves the old page with its id instead of creating a second page', () => each(async engine => {- const s = await managed(engine, { 'notes/old.md': long('Old') });+ const s = await managed(engine, { 'notes/old.md': pinned('Old', 'notes/old') });await s.sync();const page = (await engine.getPage('notes/old', { sourceId: s.id }))!;- git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); s.write('notes/new.md', longBroken); commit(s.root, 'rename to broken');+ git(s.root, 'mv', 'notes/old.md', 'notes/new.md'); commit(s.root, 'exact move onto a stale slug: line');+ expect(git(s.root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toMatch(/^R100\t/);await s.sync();expect((await s.holds())[0]).toMatchObject({ path: 'notes/new.md', meta: { rename_from: { slug: 'notes/old', pageId: page.id } } });const preview = await s.run({ includeAmbiguous: true });@@ -323,10 +325,10 @@ test('a held renamed file: the repair moves the old page with its id instead of}), 180_000);test('a rename held because the old page changed is re-bound to its current revision only under --include-ambiguous', () => each(async engine => {- const s = await managed(engine, { 'notes/x.md': long('X') });+ const s = await managed(engine, { 'notes/x.md': pinned('X', 'notes/x') });await s.sync();const x = (await engine.getPage('notes/x', { sourceId: s.id }))!;- git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); s.write('notes/y.md', longBroken); commit(s.root, 'x to y broken');+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); commit(s.root, 'x to y, held');await s.sync();await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);diff --git a/test/sync-git-paths.test.ts b/test/sync-git-paths.test.tsindex 64a6ac1439..bacf1fbade 100644--- a/test/sync-git-paths.test.ts+++ b/test/sync-git-paths.test.ts@@ -27,7 +27,7 @@ describe('Git-relative sync scope paths (#5108)', () => {expect(manifest.modified.filter(inScope)).toEqual(['docs/brain/nested/changed.md']);expect(manifest.deleted.filter(inScope)).toEqual(['docs/brain/deleted.md']);expect(manifest.renamed.filter(r => inScope(r.to))).toEqual([- { from: 'docs/brain/old.md', to: 'docs/brain/new.md' },+ { from: 'docs/brain/old.md', to: 'docs/brain/new.md', similarity: 100 },]);expect(manifest.modified[0]!.slice(scope.length + 1)).toBe('nested/changed.md');});diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.tsnew file mode 100644index 0000000000..1bafcc5057--- /dev/null+++ b/test/sync-inexact-rename-6729.test.ts@@ -0,0 +1,271 @@+/**+ * #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.+ * 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.+ */+import { afterAll, beforeAll, 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 type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { OperationContext } from '../src/core/ops/contract.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); return git(root, 'rev-parse', 'HEAD'); };+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 doc = (front: string, tail = '') => `---\n${front}\n---\n\n${BODY}\n${tail}`;+const diffStatus = (root: string) => git(root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD').split('\n').sort();+const repairCtx = (engine: BrainEngine) => ({ engine, config: { engine: engine.kind }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;++for (const kind of testBackends()) describe(`inexact Git rename identity (#6729, ${kind})`, () => {+ let engine: BrainEngine, close: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6729-'));+ const env = { GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home };+ 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 });+ });++ async function classic(files: Record<string, string>) {+ const id = `c${randomUUID().replace(/-/g, '').slice(0, 14)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q', '-b', 'main');+ for (const [path, body] of Object.entries(files)) write(root, path, body);+ commit(root, 'initial');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ const sync = (extra: Record<string, unknown> = {}) => performSync(engine, { repoPath: root, sourceId: id, noPull: true, noEmbed: true, noExtract: true, concurrency: 1, ...extra });+ await sync();+ return { id, root, sync };+ }+ async function managed(files: Record<string, string>) {+ const id = `m${randomUUID().replace(/-/g, '').slice(0, 14)}`, root = join(home, id);+ mkdirSync(root, { recursive: true }); git(root, 'init', '-q');+ for (const [path, body] of Object.entries(files)) write(root, path, body);+ 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');+ const sync = (extra: Record<string, unknown> = {}) => performManagedSync(engine, { sourceId: id, noPull: true, ...extra });+ await sync();+ return { id, root, sync };+ }+ const pageRow = async (sourceId: string, slug: string) => (await engine.executeRaw<{ id: number; deleted_at: string | null }>(+ 'SELECT id, deleted_at FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0];+ const factSlugs = (sourceId: string) => engine.executeRaw<{ entity_slug: string; fact: string }>('SELECT entity_slug, fact FROM facts WHERE source_id=$1 ORDER BY fact', [sourceId]);+ 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 () => {+ 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'),+ 'people/peer.md': '---\ntype: person\ntitle: Peer\n---\n\nA different person.\n',+ });+ const a = (await pageRow(s.id, 'people/a-x-com'))!, b = (await pageRow(s.id, 'people/b-x-com'))!, peer = (await pageRow(s.id, 'people/peer'))!;+ await engine.insertFact({ fact: 'A works on payments', entity_slug: 'people/a-x-com', visibility: 'world', source: 'synthetic' }, { source_id: s.id });+ await engine.insertFact({ fact: 'B works on search', entity_slug: 'people/b-x-com', visibility: 'world', source: 'synthetic' }, { source_id: s.id });+ await engine.executeRaw("INSERT INTO links(from_page_id,to_page_id,link_type,link_source) VALUES($1,$2,'knows','test')", [a.id, peer.id]);+ // Both files move and are rewritten; Git pairs them by body similarity alone, and their shared title cannot confirm either pair.+ git(s.root, 'mv', 'people/a-x-com.md', 'people/bob.md'); git(s.root, 'mv', 'people/b-x-com.md', 'people/alice.md');+ write(s.root, 'people/bob.md', doc('type: person\ntitle: Colleague\naliases: [Bobby]', 'Works on search.\n'));+ write(s.root, 'people/alice.md', doc('type: person\ntitle: Colleague\naliases: [Alicia]', 'Works on payments.\n'));+ commit(s.root, 'move and rewrite both');+ for (const line of diffStatus(s.root)) expect(line).toMatch(/^R0\d\d\t/);+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'synced', renamed: 0 });+ const alice = (await pageRow(s.id, 'people/alice'))!, bob = (await pageRow(s.id, 'people/bob'))!;+ expect([alice.id, bob.id]).not.toContain(a.id);+ expect([alice.id, bob.id]).not.toContain(b.id);+ expect((await pageRow(s.id, 'people/a-x-com'))!.deleted_at).not.toBeNull();+ expect(await factSlugs(s.id)).toEqual([{ entity_slug: 'people/a-x-com', fact: 'A works on payments' }, { entity_slug: 'people/b-x-com', fact: 'B works on search' }]);+ expect(await aliasOwner(s.id, 'ali')).toEqual(['people/a-x-com']);+ expect(await aliasOwner(s.id, 'bea')).toEqual(['people/b-x-com']);+ expect(await redirects(s.id)).toEqual([]);+ expect(result.identityDowngrades?.map(entry => [entry.from, entry.to, entry.reason]).sort()).toEqual([+ ['people/a-x-com.md', 'people/alice.md', 'title_not_unique'], ['people/b-x-com.md', 'people/bob.md', 'title_not_unique']]);+ expect(result.identityDowngrades?.find(entry => entry.from === 'people/a-x-com.md')).toMatchObject({ old_slug: 'people/a-x-com', new_slug: 'people/alice', facts: 1, links: 1, aliases: 1 });++ // The purge leaves both old pages while their records are open.+ 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.+ 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 [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');+ 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.+ 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();+ }), 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 () => {+ const s = await classic({ 'notes/plan.md': doc('title: Roadmap Q3 planning'), 'notes/untitled.md': doc('type: note') });+ const plan = (await pageRow(s.id, 'notes/plan'))!, untitled = (await pageRow(s.id, 'notes/untitled'))!;+ await engine.insertFact({ fact: 'Roadmap ships in Q3', entity_slug: 'notes/plan', visibility: 'world', source: 'synthetic' }, { source_id: s.id });+ git(s.root, 'mv', 'notes/plan.md', 'notes/roadmap.md'); write(s.root, 'notes/roadmap.md', doc('title: Roadmap Q3 planning', 'An added paragraph.\n'));+ git(s.root, 'mv', 'notes/untitled.md', 'notes/moved.md');+ commit(s.root, 'move and edit');+ expect(diffStatus(s.root)).toEqual([expect.stringMatching(/^R0\d\d\tnotes\/plan.md\tnotes\/roadmap.md$/), 'R100\tnotes/untitled.md\tnotes/moved.md']);+ expect(await s.sync()).toMatchObject({ status: 'synced', renamed: 2, added: 0, deleted: 0 });+ expect((await pageRow(s.id, 'notes/roadmap'))!.id).toBe(plan.id);+ expect((await pageRow(s.id, 'notes/moved'))!.id).toBe(untitled.id);+ expect(await factSlugs(s.id)).toEqual([{ entity_slug: 'notes/roadmap', fact: 'Roadmap ships in Q3' }]);+ }), 180_000);++ test('classic: an id-bearing move and edit in two commits before one sync keeps its identity; a no-signal move and edit does not', () => withEnv(env, async () => {+ const s = await classic({ 'notes/x.md': doc('id: note-6729-x\ntitle: First title'), 'notes/plain.md': doc('type: note') });+ const x = (await pageRow(s.id, 'notes/x'))!, plain = (await pageRow(s.id, 'notes/plain'))!;+ await engine.insertFact({ fact: 'X has a fact', entity_slug: 'notes/x', visibility: 'world', source: 'synthetic' }, { source_id: s.id });+ git(s.root, 'mv', 'notes/x.md', 'notes/y.md'); commit(s.root, 'move');+ write(s.root, 'notes/y.md', `---\nid: note-6729-x\ntitle: A new title\n---\n\nRewritten from scratch, nothing like before.\n`); commit(s.root, 'rewrite');+ git(s.root, 'mv', 'notes/plain.md', 'notes/plain-2.md'); write(s.root, 'notes/plain-2.md', doc('type: note', 'An edit.\n')); commit(s.root, 'move and edit plain');+ const result = await s.sync();+ expect(result.status).toBe('synced');+ expect((await pageRow(s.id, 'notes/y'))!.id).toBe(x.id);+ expect(await factSlugs(s.id)).toEqual([{ entity_slug: 'notes/y', fact: 'X has a fact' }]);+ expect((await pageRow(s.id, 'notes/plain-2'))!.id).not.toBe(plain.id);+ expect((await pageRow(s.id, 'notes/plain'))!.deleted_at).not.toBeNull();+ expect(result.identityDowngrades?.map(entry => [entry.from, entry.reason])).toEqual([['notes/plain.md', 'no_identity_signal']]);+ }), 180_000);++ test('classic: a template id reused by a new note while the old note is deleted stays a delete plus an add', () => withEnv(env, async () => {+ const s = await classic({ 'templates/meeting.md': doc('id: tmpl-6729\ntitle: Meeting template'), 'notes/standup-1.md': doc('id: tmpl-6729\ntitle: Standup one') });+ const one = (await pageRow(s.id, 'notes/standup-1'))!;+ await engine.insertFact({ fact: 'Standup one decided X', entity_slug: 'notes/standup-1', visibility: 'world', source: 'synthetic' }, { source_id: s.id });+ git(s.root, 'rm', '-q', 'notes/standup-1.md');+ write(s.root, 'notes/standup-2.md', doc('id: tmpl-6729\ntitle: Standup two', 'Different decisions.\n'));+ commit(s.root, 'replace one note with another from the template');+ await s.sync();+ expect((await pageRow(s.id, 'notes/standup-2'))!.id).not.toBe(one.id);+ expect(await factSlugs(s.id)).toEqual([{ entity_slug: 'notes/standup-1', fact: 'Standup one decided X' }]);+ }), 180_000);++ test('dirty tree: an uncommitted move plus edit with no signal is a delete plus an add; one with a unique title keeps its identity', () => withEnv(env, async () => {+ const s = await classic({ 'notes/draft.md': doc('type: note'), 'notes/spec.md': doc('title: Storage spec 6729') });+ const draft = (await pageRow(s.id, 'notes/draft'))!, spec = (await pageRow(s.id, 'notes/spec'))!;+ git(s.root, 'mv', 'notes/draft.md', 'notes/draft-2.md'); write(s.root, 'notes/draft-2.md', doc('type: note', 'Edited.\n'));+ git(s.root, 'mv', 'notes/spec.md', 'notes/storage-spec.md'); write(s.root, 'notes/storage-spec.md', doc('title: Storage spec 6729', 'Edited.\n'));+ git(s.root, 'add', '-A');+ expect(git(s.root, 'diff', '--cached', '--name-status', '-M').split('\n').every(line => /^R0\d\d\t/.test(line))).toBe(true);+ const result = await s.sync({ workingTree: true });+ expect(result.status).toBe('synced');+ expect((await pageRow(s.id, 'notes/draft-2'))!.id).not.toBe(draft.id);+ expect((await pageRow(s.id, 'notes/storage-spec'))!.id).toBe(spec.id);+ }), 180_000);++ test('three pages sharing one title: an inexact move of one of them is a delete plus an add', () => withEnv(env, async () => {+ const s = await classic({ 'notes/a.md': doc('title: Weekly sync'), 'notes/b.md': doc('title: Weekly sync', 'B.\n'), 'notes/c.md': doc('title: Weekly sync', 'C.\n') });+ const a = (await pageRow(s.id, 'notes/a'))!;+ git(s.root, 'mv', 'notes/a.md', 'notes/a-2.md'); write(s.root, 'notes/a-2.md', doc('title: Weekly sync', 'An edit.\n'));+ commit(s.root, 'move and edit one');+ expect(diffStatus(s.root)).toEqual([expect.stringMatching(/^R0\d\d\tnotes\/a.md\tnotes\/a-2.md$/)]);+ const result = await s.sync();+ expect((await pageRow(s.id, 'notes/a-2'))!.id).not.toBe(a.id);+ expect(result.identityDowngrades?.map(entry => entry.reason)).toEqual(['title_not_unique']);+ }), 180_000);++ test('2,000 moved and edited id-bearing files (Git pairs most inexactly, the rest as delete plus add) all become renames through one cat-file stream within 20 s', async () => {+ const { confirmRenameIdentities } = await import('../src/core/sync-rename-identity.ts');+ const { buildSyncManifest } = await import('../src/core/sync.ts');+ const root = join(home, 'bulk'); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q', '-b', 'main');+ const N = 2000;+ for (let i = 0; i < N; i++) writeFileSync(join(root, `notes/n${i}.md`), doc(`id: bulk-${i}\ntitle: Bulk note ${i}`));+ const base = commit(root, 'bulk');+ for (let i = 0; i < N; i++) { rmSync(join(root, `notes/n${i}.md`)); writeFileSync(join(root, `notes/m${i}.md`), doc(`id: bulk-${i}\ntitle: Bulk note ${i} moved`, 'Edited.\n')); }+ const target = commit(root, 'bulk move and edit');+ const manifest = buildSyncManifest(git(root, '-c', 'diff.renameLimit=5000', 'diff', '--name-status', '-M', base, target));+ expect(manifest.renamed.length).toBeGreaterThan(N / 2);+ expect(manifest.renamed.every(rename => (rename.similarity ?? 100) < 100)).toBe(true);+ const engine0 = { executeRaw: async () => [] } as unknown as BrainEngine;+ const started = performance.now();+ const confirmed = await confirmRenameIdentities(engine0, root, base, target, manifest, { sourceId: 'bulk' });+ const elapsed = performance.now() - started;+ expect(confirmed.renamed.length).toBe(N);+ expect(confirmed.renamed.every(rename => rename.from.replace('notes/n', '') === rename.to.replace('notes/m', ''))).toBe(true);+ expect(confirmed.added).toEqual([]);+ expect(confirmed.deleted).toEqual([]);+ expect(elapsed).toBeLessThan(20_000);+ }, 300_000);++ test('managed: crossed inexact pairs with one shared title never swap identities; a unique title keeps one', () => withEnv(env, async () => {+ const s = await managed({+ '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'),+ 'notes/plan.md': doc('title: Managed roadmap 6729'),+ });+ const a = (await pageRow(s.id, 'people/a-x-com'))!, b = (await pageRow(s.id, 'people/b-x-com'))!, plan = (await pageRow(s.id, 'notes/plan'))!;+ git(s.root, 'mv', 'people/a-x-com.md', 'people/bob.md'); git(s.root, 'mv', 'people/b-x-com.md', 'people/alice.md');+ write(s.root, 'people/bob.md', doc('type: person\ntitle: Colleague\naliases: [Bobby]', 'Works on search.\n'));+ write(s.root, 'people/alice.md', doc('type: person\ntitle: Colleague\naliases: [Alicia]', 'Works on payments.\n'));+ git(s.root, 'mv', 'notes/plan.md', 'notes/roadmap.md'); write(s.root, 'notes/roadmap.md', doc('title: Managed roadmap 6729', 'Edited.\n'));+ commit(s.root, 'move and rewrite');+ for (const line of diffStatus(s.root)) expect(line).toMatch(/^R0\d\d\t/);+ const result = await s.sync();+ expect(result).toMatchObject({ status: 'synced', renamed: 1 });+ const alice = (await pageRow(s.id, 'people/alice'))!, bob = (await pageRow(s.id, 'people/bob'))!;+ expect([alice.id, bob.id]).not.toContain(a.id);+ expect([alice.id, bob.id]).not.toContain(b.id);+ expect((await pageRow(s.id, 'people/a-x-com'))!.deleted_at).not.toBeNull();+ expect((await pageRow(s.id, 'notes/roadmap'))!.id).toBe(plan.id);+ expect(await aliasOwner(s.id, 'ali')).toEqual(['people/a-x-com']);+ expect(await redirects(s.id)).toEqual([{ alias_slug: 'notes/plan', canonical_slug: 'notes/roadmap' }]);+ expect(result.identityDowngrades?.map(entry => entry.from).sort()).toEqual(['people/a-x-com.md', 'people/b-x-com.md']);+ const { readSyncStatus } = await import('../src/core/persistence/sync-status.ts');+ expect((await readSyncStatus(engine, s.id, { detail: false })).identity_downgrades.map(entry => entry.old_slug).sort()).toEqual(['people/a-x-com', 'people/b-x-com']);+ }), 180_000);++ test('managed: a file whose explicit id differs from the page holding its slug does not take that page over', () => withEnv(env, async () => {+ const s = await managed({ 'notes/Foo Bar.md': doc('id: doc-one-6729\ntitle: Document one') });+ const one = (await pageRow(s.id, 'notes/foo-bar'))!;+ git(s.root, 'rm', '-q', 'notes/Foo Bar.md');+ write(s.root, 'notes/foo-bar.md', doc('id: doc-two-6729\ntitle: Document two', 'A different document.\n'));+ commit(s.root, 'replace with a different document at the same slug');+ await expect(s.sync()).rejects.toMatchObject({ code: 'page_identity_changed', detail: 'rename_identity_conflict' });+ expect((await pageRow(s.id, 'notes/foo-bar'))).toMatchObject({ id: one.id, deleted_at: null });+ }), 180_000);+});diff --git a/test/sync-legacy-holds.test.ts b/test/sync-legacy-holds.test.tsindex abe05631a5..d451dacf03 100644--- a/test/sync-legacy-holds.test.ts+++ b/test/sync-legacy-holds.test.ts@@ -160,11 +160,13 @@ test('slug conflicts and over-size files are held, and a slug conflict re-screentest('a rename onto a broken file keeps the old page through a full sync and moves it with its id once fixed', () => eachEngine(async () => {const body = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');- const { id, root } = await source({ 'notes/old.md': `---\ntitle: Old\n---\n${body}\n` });+ // #6729: an exact move (R100) whose slug: line still names the old path holds with the old page's identity.+ const { id, root } = await source({ 'notes/old.md': `---\ntitle: Old\nslug: notes/old\n---\n${body}\n` });await sync(id, root);const original = await page(id, 'notes/old');git(root, 'mv', 'notes/old.md', 'notes/new.md');- write(root, { 'notes/new.md': `---\ntitle: alice-example first line\nalice-example second line\n---\n${body}\n` }, 'rename and break');+ write(root, {}, 'exact move onto a stale slug: line');+ expect(git(root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toMatch(/^R100\t/);const renamed = await sync(id, root);expect(renamed.status).toBe('synced');expect(await page(id, 'notes/old')).toMatchObject({ id: original.id, source_path: 'notes/old.md', deleted_at: null });@@ -184,19 +186,39 @@ test('a rename onto a broken file keeps the old page through a full sync and movexpect(await holds(id)).toEqual([]);}), 120_000);+test('#6729: an inexact rename onto a broken file is a delete plus an add, and the old page is recorded instead of carried', () => eachEngine(async () => {+ const body = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');+ const { id, root } = await source({ 'notes/old.md': `---\ntitle: Old\n---\n${body}\n` });+ await sync(id, root);+ const original = await page(id, 'notes/old');+ git(root, 'mv', 'notes/old.md', 'notes/new.md');+ write(root, { 'notes/new.md': `---\ntitle: alice-example first line\nalice-example second line\n---\n${body}\n` }, 'rename and break');+ expect(git(root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toMatch(/^R0\d\d\t/);+ const renamed = await sync(id, root);+ expect(renamed.status).toBe('synced');+ expect(await page(id, 'notes/old')).toMatchObject({ id: original.id, deleted_at: expect.any(String) });+ expect(renamed.identityDowngrades).toMatchObject([{ from: 'notes/old.md', to: 'notes/new.md', old_page_id: original.id }]);+ expect((await holds(id))[0]).toMatchObject({ path: 'notes/new.md' });+ expect((await holds(id))[0]!.meta.rename_from).toBeUndefined();+ write(root, { 'notes/new.md': `---\ntitle: New\n---\n${body}\n` }, 'fix the renamed file');+ await sync(id, root);+ expect((await page(id, 'notes/new'))!.id).not.toBe(original.id);+}), 120_000);+test('a held rename carries its origin across a chained rename, and an edited old page holds as rename_held', async () => eachEngine(async () => {const body = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');- const broken = `---\ntitle: alice-example first line\nalice-example second line\n---\n${body}\n`;- const { id, root } = await source({ 'notes/a.md': `---\ntitle: A\n---\n${body}\n`, 'notes/x.md': `---\ntitle: X\n---\n${body}\n` });+ const { id, root } = await source({ 'notes/a.md': `---\ntitle: A\nslug: notes/a\n---\n${body}\n`, 'notes/x.md': `---\ntitle: X\nslug: notes/x\n---\n${body}\n` });await sync(id, root);const a = await page(id, 'notes/a'), x = await page(id, 'notes/x');git(root, 'mv', 'notes/a.md', 'notes/b.md'); git(root, 'mv', 'notes/x.md', 'notes/y.md');- write(root, { 'notes/b.md': broken, 'notes/y.md': broken }, 'rename both onto broken files');+ write(root, {}, 'exact moves of both onto stale slug: lines');await sync(id, root);expect((await holds(id)).map(h => h.path).sort()).toEqual(['notes/b.md', 'notes/y.md']);git(root, 'mv', 'notes/b.md', 'notes/c.md');- write(root, { 'notes/c.md': `---\ntitle: C\n---\n${body}\n` }, 'rename the held file again, fixed');+ write(root, {}, 'move the held file again, exactly');+ await sync(id, root);+ write(root, { 'notes/c.md': `---\ntitle: C\n---\n${body}\n` }, 'fix the held file');await sync(id, root);expect(await page(id, 'notes/c')).toMatchObject({ id: a.id, source_path: 'notes/c.md', deleted_at: null });expect((await holds(id)).map(h => h.path)).toEqual(['notes/y.md']);@@ -211,11 +233,11 @@ test('a held rename carries its origin across a chained rename, and an edited oltest('a full sync holds a renamed file whose old page changed instead of importing it as a new page', async () => eachEngine(async () => {const body = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');- const { id, root } = await source({ 'notes/x.md': `---\ntitle: X\n---\n${body}\n` });+ const { id, root } = await source({ 'notes/x.md': `---\ntitle: X\nslug: notes/x\n---\n${body}\n` });await sync(id, root);const x = await page(id, 'notes/x');git(root, 'mv', 'notes/x.md', 'notes/y.md');- write(root, { 'notes/y.md': `---\ntitle: alice-example first line\nalice-example second line\n---\n${body}\n` }, 'rename onto a broken file');+ write(root, {}, 'exact move onto a stale slug: line');await sync(id, root);await engine.executeRaw('UPDATE pages SET knowledge_revision=gen_random_uuid() WHERE id=$1', [x.id]);write(root, { 'notes/y.md': `---\ntitle: Y\n---\n${body}\n` }, 'fix y after the old page changed');diff --git a/test/sync.test.ts b/test/sync.test.tsindex c34b84dc1c..9126dea6dc 100644--- a/test/sync.test.ts+++ b/test/sync.test.ts@@ -22,7 +22,7 @@ describe('buildSyncManifest', () => {test('parses R100 rename entries', () => {const output = `R100\tpeople/old-name.md\tpeople/new-name.md`;const manifest = buildSyncManifest(output);- expect(manifest.renamed).toEqual([{ from: 'people/old-name.md', to: 'people/new-name.md' }]);+ expect(manifest.renamed).toEqual([{ from: 'people/old-name.md', to: 'people/new-name.md', similarity: 100 }]);expect(manifest.added).toEqual([]);expect(manifest.modified).toEqual([]);expect(manifest.deleted).toEqual([]);@@ -31,7 +31,7 @@ describe('buildSyncManifest', () => {test('parses partial rename (R075)', () => {const output = `R075\tpeople/old.md\tpeople/new.md`;const manifest = buildSyncManifest(output);- expect(manifest.renamed).toEqual([{ from: 'people/old.md', to: 'people/new.md' }]);+ expect(manifest.renamed).toEqual([{ from: 'people/old.md', to: 'people/new.md', similarity: 75 }]);});test('T (typechange) counts as modified — was silently dropped', () => {@@ -364,7 +364,7 @@ describe('buildSyncManifest — C-style-quoted paths', () => {const output = 'R100\t"people/old \\"nick\\".md"\t"people/new \\"nick\\".md"';const manifest = buildSyncManifest(output);expect(manifest.renamed).toEqual([- { from: 'people/old "nick".md', to: 'people/new "nick".md' },+ { from: 'people/old "nick".md', to: 'people/new "nick".md', similarity: 100 },]);});diff --git a/test/write-attribution-sync.test.ts b/test/write-attribution-sync.test.tsindex ee503874e9..36b91a105a 100644--- a/test/write-attribution-sync.test.ts+++ b/test/write-attribution-sync.test.ts@@ -35,7 +35,6 @@ let closePostgres: (() => Promise<void>) | undefined;const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim();const BODY = Array.from({ length: 30 }, (_, i) => `Line ${i} of a synthetic note that keeps the rename detectable.`).join('\n');const NOTE = `---\ntitle: Renamed example\n---\n${BODY}\n`;-const BROKEN = `---\ntitle: alice-example first line\nalice-example second line\n---\n${BODY}\n`;beforeAll(async () => {configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });@@ -93,11 +92,13 @@ describe('sync rename attribution on an unmanaged brain', () => {test('a full sync moves a held rename once its file screens clean under the maintenance principal', () => withEnv(env, async () => {for (const engine of engines) {const brain = await gitSource(engine);- commit(brain.root, { 'notes/held-old.md': NOTE }, 'add');+ // #6729: an exact move (R100) whose slug: line still names the old path holds with the old page's identity.+ commit(brain.root, { 'notes/held-old.md': NOTE.replace('title: Renamed example', 'title: Renamed example\nslug: notes/held-old') }, 'add');await sync(brain);const id = await pageId(engine, brain.sourceId, 'notes/held-old');git(brain.root, 'mv', 'notes/held-old.md', 'notes/held-new.md');- commit(brain.root, { 'notes/held-new.md': BROKEN }, 'rename onto a broken file');+ commit(brain.root, {}, 'exact move onto a stale slug: line');+ expect(git(brain.root, 'diff', '--name-status', '-M', 'HEAD~1', 'HEAD')).toBe('R100\tnotes/held-old.md\tnotes/held-new.md');await sync(brain);expect(await pageId(engine, brain.sourceId, 'notes/held-new')).toBeUndefined();