Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6729 rename title signal follows parseMarkdown precedence (frontmatter, then H1) and the stored page title

garrytan8918386741fc
diff --git a/src/core/markdown.ts b/src/core/markdown.ts
index f9d2898100..821464ee5d 100644
--- a/src/core/markdown.ts
+++ b/src/core/markdown.ts
@@ -330,6 +330,12 @@ export function parseMarkdown(
};
}
+/** #6729: parseMarkdown's title from the content alone (frontmatter, first H1, embedded fence), with no filename fallback; '' when none. */
+export function explicitMarkdownTitle(content: string): string {
+ const head = parseMarkdownHead(content);
+ return coerceFrontmatterString(head.frontmatter.title).trim() || inferTitleFromBody(head.body) || inferTitleFromEmbeddedFrontmatter(head.body);
+}
+
/**
* What parseMarkdown reads before the body split. `lifted` and `safeContent` are the strings the frontmatter
* readers saw; page-body/body-scan.ts checks that a bounded file head reads the same as the whole file.
diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.ts
index c396aa4317..b387ad5a08 100644
--- a/src/core/sync-rename-identity.ts
+++ b/src/core/sync-rename-identity.ts
@@ -12,8 +12,10 @@
* - 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.
+ * or the title (parseMarkdown's: frontmatter title:, then the first H1;
+ * the old side as its page row stores it) 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
@@ -30,6 +32,7 @@ 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 { explicitMarkdownTitle } from './markdown.ts';
import { isMarkdownFilePath, resolveSlugForPath, type DowngradedRename, type RenameDowngradeReason, type RenameSideSource, type SyncManifest } from './sync.ts';
import { computeSyncDelta, type SyncDeltaResult } from './sync-delta.ts';
@@ -38,21 +41,27 @@ 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. */
+/**
+ * The identity fields of a file: `id` and `slug` from its leading frontmatter block (unparseable or absent frontmatter
+ * carries none), and the title parseMarkdown gives it (frontmatter `title:`, then the body's first H1) without the
+ * filename fallback, so an H1-only page has the title its page row stores.
+ */
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/, '');
+ let title: string | null;
+ try { title = explicitMarkdownTitle(text) || null; } catch { title = null; }
const block = /^---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(text);
- if (!block) return NO_IDENTITY;
+ if (!block) return { ...NO_IDENTITY, title };
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;
+ 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 };
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') };
+ return { id: field('id', true), slug: field('slug'), 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. */
@@ -238,6 +247,17 @@ export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'execute
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)]));
+ // The old side's title is the one its page row stores: a page whose title changed in the brain is compared as it is now.
+ const titled = basePaths.filter(path => baseIdentity.get(path)!.title);
+ const sourcePathOf = opts.sourcePathOf ?? ((path: string) => path);
+ const stored = titled.length ? await engine.executeRaw<{ slug: string; source_path: string | null; title: string | null }>(
+ `SELECT slug, source_path, title FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND (source_path = ANY($2::text[]) OR slug = ANY($3::text[]))`,
+ [opts.sourceId, [...new Set(titled.flatMap(path => [path, sourcePathOf(path)]))], titled.map(path => resolveSlugForPath(sourcePathOf(path)))]) : [];
+ for (const path of titled) {
+ const row = stored.find(page => page.source_path === path || page.source_path === sourcePathOf(path))
+ ?? stored.find(page => page.source_path === null && page.slug === resolveSlugForPath(sourcePathOf(path)));
+ if (row) baseIdentity.set(path, { ...baseIdentity.get(path)!, title: row.title?.trim() || 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] : []))];
diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.ts
index a6b2a28e27..58f612f85d 100644
--- a/test/sync-inexact-rename-6729.test.ts
+++ b/test/sync-inexact-rename-6729.test.ts
@@ -195,6 +195,40 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
expect((await pageRow(s.id, 'notes/storage-spec'))!.id).toBe(spec.id);
}), 180_000);
+ test('H1-only pages: a unique H1 keeps a moved and edited page in classic, managed and dirty-tree sync; a shared H1 or a title changed in the brain does not', () => withEnv(env, async () => {
+ const h1 = (title: string, tail = '') => `# ${title}\n\n${BODY}\n${tail}`;
+ for (const mode of ['classic', 'managed'] as const) {
+ const s = await (mode === 'classic' ? classic : managed)({
+ 'notes/plan.md': h1(`Roadmap ${mode} h1 6729`), 'notes/spec.md': h1(`Spec ${mode} h1 6729`), 'notes/draft.md': h1(`Draft ${mode} h1 6729`),
+ 'people/a.md': h1('Colleague', 'Works on payments.\n'), 'people/b.md': h1('Colleague', 'Works on search.\n'),
+ });
+ const plan = (await pageRow(s.id, 'notes/plan'))!, spec = (await pageRow(s.id, 'notes/spec'))!, draft = (await pageRow(s.id, 'notes/draft'))!;
+ const a = (await pageRow(s.id, 'people/a'))!, b = (await pageRow(s.id, 'people/b'))!;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('UPDATE pages SET title=$3 WHERE source_id=$1 AND slug=$2', [s.id, 'notes/spec', 'Retitled in the brain']);
+ if (mode === 'managed') await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ git(s.root, 'mv', 'notes/plan.md', 'notes/roadmap.md'); write(s.root, 'notes/roadmap.md', h1(`Roadmap ${mode} h1 6729`, 'Edited.\n'));
+ git(s.root, 'mv', 'notes/spec.md', 'notes/spec-2.md'); write(s.root, 'notes/spec-2.md', h1(`Spec ${mode} h1 6729`, 'Edited.\n'));
+ git(s.root, 'mv', 'people/a.md', 'people/bob.md'); git(s.root, 'mv', 'people/b.md', 'people/alice.md');
+ write(s.root, 'people/bob.md', h1('Colleague', 'Works on search.\nNow Bob.\n')); write(s.root, 'people/alice.md', h1('Colleague', 'Works on payments.\nNow Alice.\n'));
+ commit(s.root, 'move and edit');
+ for (const line of diffStatus(s.root)) expect(line).toMatch(/^R0\d\d\t/);
+ const result = await s.sync();
+ expect(result.status).toBe('synced');
+ expect((await pageRow(s.id, 'notes/roadmap'))!.id).toBe(plan.id);
+ expect((await pageRow(s.id, 'notes/spec-2'))!.id).not.toBe(spec.id);
+ expect([(await pageRow(s.id, 'people/alice'))!.id, (await pageRow(s.id, 'people/bob'))!.id]).not.toContain(a.id);
+ expect([(await pageRow(s.id, 'people/alice'))!.id, (await pageRow(s.id, 'people/bob'))!.id]).not.toContain(b.id);
+ expect(result.identityDowngrades?.map(entry => [entry.from, entry.reason]).sort()).toEqual([
+ ['notes/spec.md', 'no_identity_signal'], ['people/a.md', 'title_not_unique'], ['people/b.md', 'title_not_unique']]);
+ git(s.root, 'mv', 'notes/draft.md', 'notes/draft-2.md'); write(s.root, 'notes/draft-2.md', h1(`Draft ${mode} h1 6729`, 'Edited.\n'));
+ git(s.root, 'add', '-A');
+ expect(git(s.root, 'diff', '--cached', '--name-status', '-M')).toMatch(/^R0\d\d\tnotes\/draft.md\tnotes\/draft-2.md$/);
+ expect((await s.sync({ workingTree: true })).status).toBe('synced');
+ expect((await pageRow(s.id, 'notes/draft-2'))!.id).toBe(draft.id);
+ }
+ }), 240_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'))!;