Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6729 an unpaired add/delete promoted by id needs continuity (same file name, title or bytes); Git-paired same unique id stays a rename

garrytan01e3cb3b3596
diff --git a/.wave18-fragments/lane2-s1.md b/.wave18-fragments/lane2-s1.md
index 532429541c..857f709e5b 100644
--- a/.wave18-fragments/lane2-s1.md
+++ b/.wave18-fragments/lane2-s1.md
@@ -19,7 +19,7 @@ The remedy repair kind is not in S1: it lands in its own commit after the S1 SHA
### BEHAVIOR_CHANGES (`src/core/behavior-change-notice.ts`, since = slot version)
-- `{ since: '<slot>', text: 'An inexact Git rename (a move that also changed the file, reported as R<100) now keeps its page identity only when the files confirm it: the same frontmatter \`id\` on both sides that no other file or page carries, or, with no id on either side, a \`slug:\` line or title (the frontmatter \`title:\`, else the first \`# Heading\`, compared with the title the brain stores for the old page) that no other file in the sync and no other live page shares; a respelled path that keeps its slug keeps its page unless the ids conflict (#6729). Any other pair is imported as a delete plus an add: the new file starts a fresh page and the old page keeps its facts, links and aliases on its soft-deleted slug. The sync report prints each pair with \`gbrain restore <old-slug> --source-id <id> --force\`, \`gbrain sync status --json\` lists it under \`identity_downgrades\`, doctor \`rename_identity_downgrades\` names it, and the purge leaves the old page alone, with no time limit, until the pair gets a disposition (the old page restored, or, once the remedy ships, remedied or closed without merging). A new file whose frontmatter \`id\` uniquely matches a file deleted in the same sync range is now its rename, even across two commits.' }`
+- `{ since: '<slot>', text: 'An inexact Git rename (a move that also changed the file, reported as R<100) now keeps its page identity only when the files confirm it: the same frontmatter \`id\` on both sides that no other file or page carries, or, with no id on either side, a \`slug:\` line or title (the frontmatter \`title:\`, else the first \`# Heading\`, compared with the title the brain stores for the old page) that no other file in the sync and no other live page shares; a respelled path that keeps its slug keeps its page unless the ids conflict (#6729). Any other pair is imported as a delete plus an add: the new file starts a fresh page and the old page keeps its facts, links and aliases on its soft-deleted slug. The sync report prints each pair with \`gbrain restore <old-slug> --source-id <id> --force\`, \`gbrain sync status --json\` lists it under \`identity_downgrades\`, doctor \`rename_identity_downgrades\` names it, and the purge leaves the old page alone, with no time limit, until the pair gets a disposition (the old page restored, or, once the remedy ships, remedied or closed without merging). A new file whose frontmatter \`id\` uniquely matches a file deleted in the same sync range, with the same file name, title or bytes, is now its rename even when Git did not pair them; a template id reused by an unrelated new note stays a new page.' }`
- `{ since: '<slot>', text: 'A file moved and broken in the same commit (unreadable frontmatter, so Git reports an inexact rename) is no longer held with the old page identity: the old page is soft-deleted and recorded as above and the broken file is held as a new file (#6729). An exact move (R100) that is held still keeps the old page identity and \`rename_from\`. A managed sync refuses \`page_identity_changed\` (detail \`rename_identity_conflict\`) when a file would take over a page, or a held rename would carry one, whose frontmatter \`id\` differs from its own.' }`
### CHANGELOG
@@ -28,7 +28,7 @@ The remedy repair kind is not in S1: it lands in its own commit after the S1 SHA
### KEY_FILES (`docs/architecture/key-files/files-and-sync-*.md`, `commands-*.md`)
-- `src/core/sync-rename-identity.ts`: the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult. An add whose id uniquely matches a delete in the range becomes a rename. Downgraded pairs record `read.from` / `read.to`.
+- `src/core/sync-rename-identity.ts`: the one confirmation stage for inexact Git renames (#6729). `confirmRenameIdentities` reads committed sides through one `git cat-file --batch` stream (64 KiB heads) and the dirty tree's working side from disk, with id and `slug:` from the frontmatter and the title by parseMarkdown precedence (frontmatter, then the first H1, no filename fallback; `markdown.ts` `explicitMarkdownTitle`), the old side taking the title its page row stores; it keeps an R<100 pair on a same-slug respelling, a unique shared `id`, or with no id on either side a unique `slug:` line or title (titles also unique among live pages). `explicitIdVeto` is the one explicit-id veto the managed takeovers consult. An add whose id uniquely matches a delete in the range becomes a rename only with continuity (same file name, title or bytes; `digest` is the sha256 of a file that fits the head read), as decideImportIdentity asks of a move. Downgraded pairs record `read.from` / `read.to`.
- `src/core/sync-identity-downgrades.ts`: durable records of downgraded pairs (`op_checkpoints` op `sync-identity-downgrade`, fingerprint = old page id, open until a disposition is set or the old page is restored or purged; no time window; the checkpoint sweep keeps open records), the purge-hold SQL predicate, the live list (new slug read live), the report lines and the restore argv.
- `src/commands/doctor/checks/rename-identity-downgrades.ts`: doctor `rename_identity_downgrades` (warn while a record is open; fix = restore the first old page, behind ask_user).
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 7c16f982c6..371e41b7fa 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -366,9 +366,14 @@ title: Roadmap
---
```
-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`
+Two rules decide by `frontmatter.id`. A pair Git reports as a rename (`R<n>`)
+whose two files carry the same id, held by no other file in the range and no
+other live page, is a rename. A new file and a deleted file that Git did not
+pair are a rename only when they share such an id and also show continuity:
+the same file name, the same title, or the same bytes. So a note moved to
+another folder and rewritten keeps its page, while a new note that reuses a
+deleted note's template id starts a fresh page, even when no live page holds
+that id. 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.
diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.ts
index b387ad5a08..df7e8ad5ca 100644
--- a/src/core/sync-rename-identity.ts
+++ b/src/core/sync-rename-identity.ts
@@ -19,13 +19,15 @@
* 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);
+ * Git crossed) when the two also show continuity (same file name, same
+ * title or same bytes), as decideImportIdentity asks of a move;
* - 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 { createHash } from 'node:crypto';
import { lstatSync, openSync, readSync, closeSync } from 'node:fs';
import { resolve, sep } from 'node:path';
import { JSON_SCHEMA, load as yamlLoad } from 'js-yaml';
@@ -38,8 +40,9 @@ 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 };
+/** `digest`: sha256 of the whole file when it fit in the head read (null for a longer file), the content-continuity signal. */
+export interface FrontmatterIdentity { id: string | null; slug: string | null; title: string | null; digest: string | null }
+const NO_IDENTITY: FrontmatterIdentity = { id: null, slug: null, title: null, digest: null };
/**
* The identity fields of a file: `id` and `slug` from its leading frontmatter block (unparseable or absent frontmatter
@@ -51,17 +54,18 @@ export function frontmatterIdentity(head: Buffer | string | null): FrontmatterId
const text = (typeof head === 'string' ? head : head.toString('utf8')).replace(/^\uFEFF/, '');
let title: string | null;
try { title = explicitMarkdownTitle(text) || null; } catch { title = null; }
+ const digest = Buffer.byteLength(head) < HEAD_BYTES ? createHash('sha256').update(head).digest('hex') : null;
const block = /^---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(text);
- if (!block) return { ...NO_IDENTITY, title };
+ if (!block) return { ...NO_IDENTITY, title, digest };
let data: unknown;
- try { data = yamlLoad(block[1]!, { schema: JSON_SCHEMA }); } catch { return { ...NO_IDENTITY, title }; }
- if (!data || typeof data !== 'object' || Array.isArray(data)) return { ...NO_IDENTITY, title };
+ try { data = yamlLoad(block[1]!, { schema: JSON_SCHEMA }); } catch { return { ...NO_IDENTITY, title, digest }; }
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return { ...NO_IDENTITY, title, digest };
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 };
+ return { id: field('id', true), slug: field('slug'), title, digest };
}
/** 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. */
@@ -203,7 +207,13 @@ export function decideRenameIdentities(manifest: SyncManifest, inputs: RenameIde
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.
+ // Rule (c): an added file whose id uniquely matches a file this range deletes keeps that page's identity when the two
+ // also show continuity, as decideImportIdentity asks of a move whose origin is gone: the same file name, the same
+ // title, or the same bytes. A template id reused by an unrelated new note is not a rename.
+ const continuous = (from: string, to: string) => {
+ const before = inputs.base(from), after = inputs.target(to);
+ return from.split('/').pop() === to.split('/').pop() || (!!before.title && before.title === after.title) || (!!before.digest && before.digest === after.digest);
+ };
const added = [...manifest.added, ...downgraded.map(pair => pair.to)];
const deleted = [...manifest.deleted, ...downgraded.map(pair => pair.from)];
const deletedById = new Map<string, string[]>();
@@ -215,7 +225,7 @@ export function decideRenameIdentities(manifest: SyncManifest, inputs: RenameIde
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;
+ if (!id || from?.length !== 1 || !uniqueId(id) || !continuous(from[0]!, path)) 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));
diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.ts
index fe5a60a419..502c5635fa 100644
--- a/test/sync-inexact-rename-6729.test.ts
+++ b/test/sync-inexact-rename-6729.test.ts
@@ -164,12 +164,12 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
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 () => {
+ test('classic: an id-bearing move and edit in two commits before one sync keeps its identity (same id and title); 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');
+ write(s.root, 'notes/y.md', `---\nid: note-6729-x\ntitle: First 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');
@@ -192,6 +192,23 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
expect(await factSlugs(s.id)).toEqual([{ entity_slug: 'notes/standup-1', fact: 'Standup one decided X' }]);
}), 180_000);
+ test('classic: an unpaired add and delete sharing an id no live page holds need continuity: a template id reused by a new note stays a delete plus an add, the same file name in a new folder is a rename', () => withEnv(env, async () => {
+ const s = await classic({ 'notes/standup-1.md': doc('id: tmpl-6729-free\ntitle: Standup one'), 'notes/retro.md': doc('id: retro-6729\ntitle: Retro') });
+ const one = (await pageRow(s.id, 'notes/standup-1'))!, retro = (await pageRow(s.id, 'notes/retro'))!;
+ 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', `---\nid: tmpl-6729-free\ntitle: Standup two\n---\n\nA different meeting entirely.\n`);
+ git(s.root, 'rm', '-q', 'notes/retro.md');
+ write(s.root, 'archive/retro.md', `---\nid: retro-6729\ntitle: Retro, archived\n---\n\nRewritten summary.\n`);
+ commit(s.root, 'replace one note from the template, archive another');
+ expect(diffStatus(s.root)).toEqual(['A\tarchive/retro.md', 'A\tnotes/standup-2.md', 'D\tnotes/retro.md', 'D\tnotes/standup-1.md']);
+ const result = await s.sync();
+ expect(result.status).toBe('synced');
+ 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' }]);
+ expect((await pageRow(s.id, 'archive/retro'))!.id).toBe(retro.id);
+ }), 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'))!;
@@ -250,14 +267,14 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
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 () => {
+ test('2,000 id-bearing files moved to a new folder and edited (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')); }
+ for (let i = 0; i < N; i++) { rmSync(join(root, `notes/n${i}.md`)); mkdirSync(join(root, 'moved'), { recursive: true }); writeFileSync(join(root, `moved/n${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);
@@ -267,7 +284,7 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
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.renamed.every(rename => rename.from.replace('notes/', '') === rename.to.replace('moved/', ''))).toBe(true);
expect(confirmed.added).toEqual([]);
expect(confirmed.deleted).toEqual([]);
// Stated budget: 4,000 frontmatter heads (both sides) through one cat-file stream plus the pure decision in under 20 s on a