Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): #6729 a dirty-tree rename verdict is bound to the bytes it read (classic re-checks before the identity moves; managed refuses source_changed on differing frozen bytes)

garrytan06ee38abbbbf
diff --git a/.wave18-fragments/lane2-s1.md b/.wave18-fragments/lane2-s1.md
index 857f709e5b..e3d6cc56c0 100644
--- a/.wave18-fragments/lane2-s1.md
+++ b/.wave18-fragments/lane2-s1.md
@@ -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 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-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`. A dirty-tree verdict is bound to the bytes it read: each kept rename carries `identityHead` (sha256 of the first 64 KiB), classic `applyRename` re-checks it before the identity moves and managed `readSyncContent` refuses `source_changed` on frozen bytes that differ.
- `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 371e41b7fa..874bdfed79 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -373,7 +373,13 @@ 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`
+that id.
+
+With `--working-tree`, the decision reads the files on disk and holds only for
+the bytes it read. A renamed file edited before its page moves keeps nothing:
+classic sync fails that file and the next sync decides again, and a managed
+sync refuses `source_changed` and names
+`gbrain sync --no-pull --retry-failed --working-tree --source <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/commands/sync/preflight.ts b/src/commands/sync/preflight.ts
index aa994afc45..ac4864f927 100644
--- a/src/commands/sync/preflight.ts
+++ b/src/commands/sync/preflight.ts
@@ -1075,7 +1075,7 @@ async function computeFilteredDelta(
filtered.added = filtered.added.map(scopeRel);
filtered.modified = filtered.modified.map(scopeRel);
filtered.deleted = filtered.deleted.map(scopeRel);
- filtered.renamed = filtered.renamed.map(r => ({ from: scopeRel(r.from), to: scopeRel(r.to) }));
+ filtered.renamed = filtered.renamed.map(r => ({ ...r, from: scopeRel(r.from), to: scopeRel(r.to) }));
}
// Working-tree mass-delete valve: merged working-tree deletes bypass the
diff --git a/src/commands/sync/renames.ts b/src/commands/sync/renames.ts
index c1b26d5721..71bd912904 100644
--- a/src/commands/sync/renames.ts
+++ b/src/commands/sync/renames.ts
@@ -13,6 +13,7 @@ import { maintenanceTransaction } from '../../core/persistence/attribution.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { movePageIdReferences, moveSlugBindings, recordRenameAlias } from '../../core/page-state/rename-alias.ts';
import { renamePageOntoSlug } from './rename-collision.ts';
+import { workingTreeIdentityHead } from '../../core/sync-rename-identity.ts';
import {
resolveSlugsForRemovedPaths,
refusedRemovedPathMessage,
@@ -189,8 +190,8 @@ export async function runRenamesPhase(
const ctx: RenameContext = { renameOpts, slugLiveness, renameOldSlugs, fromSlugByPath, renameSentinelAlreadyOpen, noEmbed };
- for (const { from, to } of renamesToDo) {
- const aborted = await applyRename(run, plan, ctx, progress, from, to);
+ for (const { from, to, identityHead } of renamesToDo) {
+ const aborted = await applyRename(run, plan, ctx, progress, from, to, identityHead);
if (aborted) return aborted;
}
progress.finish();
@@ -206,6 +207,7 @@ async function applyRename(
progress: SyncProgress,
from: string,
to: string,
+ identityHead?: string,
): Promise<SyncResult | undefined> {
const { engine, failedFiles, succeededPaths, pagesAffected, deletedSlugs } = run;
const { opts, gitContextRoot, syncImportRoot, syncActivePack, holds } = plan;
@@ -236,6 +238,14 @@ async function applyRename(
const newSlug = resolveSlugForPath(to);
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `to` is a git-diff rename path; the joined path is read only after the same isPathSafe(filePath, gitContextRoot) realpath containment check the import below applies
const filePath = join(syncImportRoot, to);
+ // #6729: a dirty-tree rename keeps its page only for the bytes its verdict read; a file edited since then is left
+ // for the next sync to re-check, and nothing moves.
+ if (identityHead !== undefined && workingTreeIdentityHead(syncImportRoot, to) !== identityHead) {
+ failedFiles.push({ path: to, error: `${to} changed after sync confirmed it keeps the page of ${from}; nothing moved. Run gbrain sync again to re-check it.` });
+ serr(` [sync] rename ${sanitizePathForDisplay(from)} -> ${sanitizePathForDisplay(to)}: the file changed after its identity was confirmed; nothing moved, the next sync re-checks it.`);
+ progress.tick(1, newSlug);
+ return undefined;
+ }
// #5988 (E13): a destination the import would refuse is screened before the
// old page's slug or origin moves; it is held and the old page stays whole.
if (isPathSafe(filePath, gitContextRoot) && await holdRenameDestination(engine, holds, { from, to, filePath, oldSlug, activePack: syncActivePack })) {
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 4b194279ad..b2bd66c45a 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -9,7 +9,7 @@ import { managedForbiddenFlag, managedSyncFlagRefusal } from './managed-sync-fla
import type { Action } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';
-import { confirmedSyncDelta, confirmRenameIdentities, explicitIdVeto, frontmatterIdentity } from '../sync-rename-identity.ts';
+import { confirmedSyncDelta, confirmRenameIdentities, explicitIdVeto, frontmatterIdentity, identityHeadDigest } 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';
@@ -34,6 +34,8 @@ import { readSyncSlice, sliceEntries, syncCursorOptions, type SyncSliceCursor, t
export interface SyncRename { sourcePath: string; slug: string; pageId: number; revision: string; }
export interface SyncEntry { path: string; sourcePath: string; action: 'import' | 'delete'; working: boolean; slug?: string; pageId?: number | null; revision?: string | null;
renameFrom?: SyncRename;
+ /** #6729: a dirty-tree rename's verdict digest (see `SyncManifest.renamed`); readSyncContent refuses bytes that differ. */
+ identityHead?: string;
/** #5565: a deleted file no page records as its origin; its slug's page keeps another origin, so the deletion is a fenced no-op. */
unownedDeletion?: boolean;
/** #5988: a held rename destination whose source page changed since the rename was recorded; the freeze screen holds it as `rename_held`. */
@@ -299,7 +301,7 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
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>();
+ const renamedFrom = new Map<string, { from: string; identityHead?: string }>();
let workingTreeKept: string[] | undefined;
let treeAbsent: Array<{ id: number; gitPath: string }> = [];
const discoveredAt = new Date().toISOString();
@@ -333,14 +335,14 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
if (refuse(path, action)) return;
if (eligible(path)) entries.set(path, { path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });
};
- const putRename = (rename: { from: string; to: string }, working = false) => {
+ const putRename = (rename: SyncManifest['renamed'][number], working = false) => {
if (isWindowsColonTarget(rename.from) || isWindowsColonTarget(rename.to)) {
for (const path of [rename.from, rename.to]) {
record(path, `${path} is one side of the rename ${rename.from} -> ${rename.to}, which Windows cannot reconcile; sync skipped both sides so the page keeps its identity.`);
}
return;
}
- put(rename.from, 'delete', working); put(rename.to, 'import', working); renamedFrom.set(rename.to, rename.from);
+ put(rename.from, 'delete', working); put(rename.to, 'import', working); renamedFrom.set(rename.to, { from: rename.from, ...(working && rename.identityHead ? { identityHead: rename.identityHead } : {}) });
};
if (delta?.status === 'ok') {
for (const path of [...delta.manifest.added, ...delta.manifest.modified]) put(path, 'import');
@@ -535,12 +537,12 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
continue;
}
Object.assign(winner, { pageId: null, revision: null });
- const from = renamedFrom.get(gitPath(winner));
+ const { from, identityHead } = renamedFrom.get(gitPath(winner)) ?? {};
const deletion = from === undefined ? undefined : [...deletions.values()].find(entry => gitPath(entry) === from);
const moved = deletion?.pageId == null ? undefined : identities.find(page => page.id === deletion.pageId);
if (deletion && moved && !deleted.has(moved.id) && moved.source_path != null) {
// A Git rename moves the page to its new slug, like the library path's updateSlug: same page id, inbound links and an alias.
- winner.renameFrom = { sourcePath: moved.source_path, slug: moved.slug, pageId: moved.id, revision: moved.knowledge_revision };
+ Object.assign(winner, { renameFrom: { sourcePath: moved.source_path, slug: moved.slug, pageId: moved.id, revision: moved.knowledge_revision }, ...(identityHead ? { identityHead } : {}) });
retired.add(deletion);
continue;
}
@@ -602,6 +604,10 @@ export function readSyncContent(discovery: SyncDiscovery, entry: SyncEntry): str
if (bytes === null) throw opError('source_changed', 'The discovered working-tree file disappeared.',
`${entry.path} left the working tree of ${discovery.sourceId} between discovery and import, so nothing was imported from it. Run gbrain sync --no-pull --source ${discovery.sourceId} to rediscover the tree.`,
{ fix: managedSyncFix(discovery.sourceId, 'A new discovery reads the working tree as it is now.') });
+ if (entry.identityHead && identityHeadDigest(bytes) !== entry.identityHead) throw opError('source_changed', 'A renamed working-tree file changed after its page identity was confirmed.',
+ `${entry.path} changed in the working tree of ${discovery.sourceId} after sync confirmed it keeps the page of its rename, so nothing was imported from it and no identity moved. Run gbrain sync --no-pull --retry-failed --working-tree --source ${discovery.sourceId} to re-check it.`,
+ { fix: { ...managedSyncFix(discovery.sourceId, 'A retry rediscovers the tree and re-checks the rename against the file as it is now.'),
+ argv: ['gbrain', 'sync', '--no-pull', '--retry-failed', '--working-tree', '--source', discovery.sourceId] } });
return bytes.toString('utf8');
}
return syncGit(discovery.gitRoot, ['show', `${discovery.target}:${syncGitPath(discovery, entry.path)}`]);
diff --git a/src/core/sync-rename-identity.ts b/src/core/sync-rename-identity.ts
index df7e8ad5ca..0882d6e0f2 100644
--- a/src/core/sync-rename-identity.ts
+++ b/src/core/sync-rename-identity.ts
@@ -105,6 +105,15 @@ export async function catFileHeads(repo: string, objects: string[]): Promise<Arr
}
/** The first 64 KiB of a regular file inside `root`; null for a missing, escaping or non-regular path. */
+/** The digest a dirty-tree rename verdict is bound to: sha256 of the first 64 KiB the verdict read. */
+export const identityHeadDigest = (bytes: Buffer): string => createHash('sha256').update(bytes.subarray(0, HEAD_BYTES)).digest('hex');
+
+/** `identityHeadDigest` of a working-tree file now; null when it is gone, not a regular file, or outside `root`. */
+export function workingTreeIdentityHead(root: string, path: string): string | null {
+ const head = workingTreeHead(root, path);
+ return head === null ? null : identityHeadDigest(head);
+}
+
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
@@ -255,8 +264,8 @@ export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'execute
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 targetHeads = new Map(targetPaths.map((path, index) => [path, target === null ? workingTreeHead(repo, path) : heads[basePaths.length + index] ?? null]));
+ const targetIdentity = new Map(targetPaths.map(path => [path, frontmatterIdentity(targetHeads.get(path) ?? 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);
@@ -275,11 +284,19 @@ export async function confirmRenameIdentities(engine: Pick<BrainEngine, 'execute
`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, {
+ const decided = decideRenameIdentities(manifest, {
base: path => baseIdentity.get(path) ?? NO_IDENTITY,
target: path => targetIdentity.get(path) ?? NO_IDENTITY,
live, sourcePathOf: opts.sourcePathOf, targetSource: target === null ? 'working_tree' : 'commit',
});
+ if (target !== null) return decided;
+ // A dirty-tree verdict holds only for the bytes it read: each kept rename carries their digest, and the identity move
+ // re-checks it against the bytes it imports (classic applyRename, managed readSyncContent).
+ const stamp = (rename: SyncManifest['renamed'][number]) => {
+ const head = targetHeads.get(rename.to);
+ return head ? { ...rename, identityHead: identityHeadDigest(head) } : rename;
+ };
+ return { ...decided, renamed: decided.renamed.map(stamp) };
}
/** `computeSyncDelta` of a commit range with its renames confirmed (the commit-range half of every incremental sync). */
diff --git a/src/core/sync.ts b/src/core/sync.ts
index 2568b588de..87afbbb247 100644
--- a/src/core/sync.ts
+++ b/src/core/sync.ts
@@ -24,7 +24,9 @@ export interface SyncManifest {
modified: string[];
deleted: 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 }>;
+ renamed: Array<{ from: string; to: string; similarity?: number;
+ /** #6729: sha256 of the first 64 KiB of the working-tree `to` file the identity verdict read (dirty-tree renames only); identity moves only for those bytes. */
+ identityHead?: string }>;
/** #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[];
}
diff --git a/test/sync-inexact-rename-6729.test.ts b/test/sync-inexact-rename-6729.test.ts
index 502c5635fa..cbc26970d1 100644
--- a/test/sync-inexact-rename-6729.test.ts
+++ b/test/sync-inexact-rename-6729.test.ts
@@ -256,6 +256,53 @@ for (const kind of testBackends()) describe(`inexact Git rename identity (#6729,
}
}), 240_000);
+ test('dirty tree: a rename verdict is bound to the bytes it read; a file edited between the verdict and the identity move moves nothing, and the next sync re-checks it (classic and managed)', () => withEnv(env, async () => {
+ for (const mode of ['classic', 'managed'] as const) {
+ const s = await (mode === 'classic' ? classic : managed)({ 'notes/spec.md': doc(`title: Drift spec 6729 ${mode}`) });
+ const spec = (await pageRow(s.id, 'notes/spec'))!;
+ git(s.root, 'mv', 'notes/spec.md', 'notes/spec-2.md'); write(s.root, 'notes/spec-2.md', doc(`title: Drift spec 6729 ${mode}`, 'Edited.\n'));
+ git(s.root, 'add', '-A');
+ expect(git(s.root, 'diff', '--cached', '--name-status', '-M')).toMatch(/^R0\d\d\tnotes\/spec.md\tnotes\/spec-2.md$/);
+ // The edit lands after the verdict read the file (on its stored-title lookup) and before the identity move.
+ let drifted = false;
+ const racing = new Proxy(engine, { get(target, key) {
+ if (key === 'executeRaw') return async (sql: string, params?: unknown[]) => {
+ const rows = await target.executeRaw(sql, params);
+ if (!drifted && sql.startsWith('SELECT slug, source_path, title FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND (source_path')) {
+ drifted = true; write(s.root, 'notes/spec-2.md', doc('id: drifted-6729\ntitle: A different document', 'Edited.\n'));
+ }
+ return rows;
+ };
+ const value = Reflect.get(target, key, target);
+ return typeof value === 'function' ? value.bind(target) : value;
+ } }) as BrainEngine;
+ if (mode === 'classic') {
+ const result = await performSync(racing, { repoPath: s.root, sourceId: s.id, noPull: true, noEmbed: true, noExtract: true, concurrency: 1, workingTree: true });
+ expect(result).toMatchObject({ status: 'blocked_by_failures', failedFiles: 1 });
+ } else {
+ await expect(performManagedSync(racing, { sourceId: s.id, noPull: true, workingTree: true })).rejects.toMatchObject({ code: 'source_changed' });
+ }
+ expect(drifted).toBe(true);
+ expect(await pageRow(s.id, 'notes/spec')).toMatchObject({ id: spec.id, deleted_at: null });
+ expect(await pageRow(s.id, 'notes/spec-2')).toBeUndefined();
+ // Classic re-checks on the next sync; managed rediscovers through the --retry-failed its refusal names.
+ const again = await s.sync({ workingTree: true, ...(mode === 'managed' ? { retryFailed: true } : {}) });
+ expect(again.identityDowngrades?.map(entry => [entry.from, entry.reason])).toEqual([['notes/spec.md', 'id_one_side']]);
+ expect((await pageRow(s.id, 'notes/spec-2'))!.id).not.toBe(spec.id);
+ }
+ }), 240_000);
+
+ test('dirty tree: an untracked move (plain mv) keeps its page through its id and file name; an untracked note reusing a deleted note\'s id under another name does not', () => withEnv(env, async () => {
+ const s = await classic({ 'notes/keep.md': doc('id: untracked-6729-keep\ntitle: Keep me'), 'notes/old.md': doc('id: untracked-6729-tmpl\ntitle: Old note') });
+ const keep = (await pageRow(s.id, 'notes/keep'))!, old = (await pageRow(s.id, 'notes/old'))!;
+ rmSync(join(s.root, 'notes/keep.md')); write(s.root, 'archive/keep.md', `---\nid: untracked-6729-keep\ntitle: Keep me, archived\n---\n\nShort now.\n`);
+ rmSync(join(s.root, 'notes/old.md')); write(s.root, 'notes/new.md', `---\nid: untracked-6729-tmpl\ntitle: New note\n---\n\nUnrelated.\n`);
+ expect(git(s.root, 'status', '--porcelain').split('\n').map(line => line.trim()).sort()).toEqual(['?? archive/', '?? notes/new.md', 'D notes/keep.md', 'D notes/old.md']);
+ expect((await s.sync({ workingTree: true })).status).toBe('synced');
+ expect((await pageRow(s.id, 'archive/keep'))!.id).toBe(keep.id);
+ expect((await pageRow(s.id, 'notes/new'))!.id).not.toBe(old.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'))!;