Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Repair file-drift reads an origin twin only where sync would import its file

garrytan13283e0f7e0c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c6e295caa..24dbecea03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,10 +16,10 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
-- `src/core/persistence/drift-conflicts.ts`: `liveFileDrift` reads an adoptable origin twin with no recorded file against its slug-path file. A twin in a read-only mirror source, or whose slug path no file can import as, keeps `database_only`. A twin under a declared db_only path, which sync holds but no repair can adopt, reads `unknown` (`db_only_slug_path`) instead of passing as `no_drift`.
+- `src/core/persistence/drift-conflicts.ts`: `liveFileDrift` reads an adoptable origin twin with no recorded file against its slug-path file. A twin in a read-only mirror source, whose slug path no file can import as, whose slug-path file sync doesn't admit (outside its scope or under `sync.exclude`), or whose slug-path file another page records as its source path keeps `database_only`. A slug path several files import as keeps the earlier reading instead of reporting `slug_path_ambiguous`. A twin under a declared db_only path, which sync holds but no repair can adopt, reads `unknown` (`db_only_slug_path`) instead of passing as `no_drift`, and so does a slug-path file another page names only by file URI (`shared_origin`), since sync still imports it into the twin.
- `src/core/persistence/reconcile-state.ts`: the slug-path adoption check moves into one exported `adoptableSlugOrigin`, which reconcile and the drift preview now share. Reconcile's behaviour is unchanged.
- Applying either side to such a twin binds the slug-path file as its `source_path` and clears `origin_twin`. Maintenance writes to a twin whose slug-path file differs are now refused as drift, like any drifted page.
-- Tests: `test/repair-file-drift-origin-twin-gbra108.test.ts` (PGLite, managed source, real git): a legacy page with no import record held by sync, previewed and applied for both `--prefer database` and `--prefer file`, after which a re-sync clears the hold; also mirror-read-only, db_only, non-importable slug path, missing file and shared-origin cases.
+- Tests: `test/repair-file-drift-origin-twin-gbra108.test.ts` (PGLite, managed source, real git): a legacy page with no import record held by sync, previewed and applied for both `--prefer database` and `--prefer file`, after which a re-sync clears the hold; also mirror-read-only, db_only, non-importable slug path, missing file, shared-origin, excluded slug path, URI-only claimant and ambiguous slug path cases.
## [0.60.628.0] - 2026-11-09
diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.ts
index 7fd20d518d..115fd47950 100644
--- a/src/core/persistence/drift-conflicts.ts
+++ b/src/core/persistence/drift-conflicts.ts
@@ -33,6 +33,7 @@ import { isValidSourceId } from '../source-id.ts';
import { validateSlug } from '../utils.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import { sha256 } from './digest.ts';
+import { findLiveFileClaimants, recordedReconcilePath } from './file-claims.ts';
import { existingHostIdFor } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
import { sourceMirrorReadOnly, staleMirrorPage } from './mirror-read-only.ts';
@@ -41,6 +42,7 @@ import { prepareFileTarget, publishesDatabaseOnly } from './page-prepare.ts';
import { adoptableSlugOrigin, readReconcileState } from './reconcile-state.ts';
import { reconcileCanonical } from './reconcile-merge.ts';
import { classifyDrift } from './reconcile-additive.ts';
+import { loadSyncEligibility, syncGit } from './sync-discovery.ts';
import { recordsNoFileOrigin, slugPathFile } from './unbound-pages.ts';
/** The refusal message `prepareFileTarget` stores on a drift conflict receipt (the detail is not kept on the row). */
@@ -88,8 +90,11 @@ export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug:
// #7974: it is compared as reconcile reads it; a slug path that reading cannot settle (several spellings) is unknown.
// GBRA-108: so is an origin twin with no recorded file that adopts its slug path (twinReading). Sync imports that file
// into it (and holds it file_drift when they differ), so the drift is read from it as repair file-drift adopts it.
- // A slug-path file another live page records is that page's (sync imports it there), so the twin stays database-only.
- const twin = await twinReading(engine, sourceId, root, page);
+ // A slug-path file another live page records as its source path is that page's (sync imports it there), so the twin
+ // stays database-only; one another page names only by file URI is unknown (sync still routes it to the twin).
+ let twin: Awaited<ReturnType<typeof twinReading>>;
+ try { twin = await twinReading(engine, sourceId, root, page); }
+ catch (error) { return { still_present: null, reason: error instanceof OperationError && typeof error.detail === 'string' ? error.detail : 'error' }; }
if (twin === 'db_only') return { still_present: null, reason: 'db_only_slug_path', db_revision: page.revision };
if (twin === 'adopt' || await staleMirrorPage(engine, sourceId, page.page)) {
try {
@@ -99,7 +104,9 @@ export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug:
path: relative(state.root, state.path).split(sep).join('/'), file_hash: sha256(state.raw) };
} catch (error) {
if (!(error instanceof OperationError)) return { still_present: null, reason: 'error' };
- if (error.detail === 'canonical_file_missing' || twin && error.detail === 'shared_origin') return { still_present: false, reason: 'database_only', db_revision: page.revision };
+ if (error.detail === 'canonical_file_missing' || twin && error.detail === 'shared_origin' && await claimedBySourcePath(engine, sourceId, root, page)) {
+ return { still_present: false, reason: 'database_only', db_revision: page.revision };
+ }
return { still_present: null, reason: typeof error.detail === 'string' ? error.detail : error.code };
}
}
@@ -125,17 +132,49 @@ export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug:
/**
* GBRA-108: how liveFileDrift reads an origin twin with no recorded file, in a source that is not a read-only mirror (no
- * repair writes there): `adopt` when it adopts its slug path as reconcile does (adoptableSlugOrigin); `db_only` when that
- * path is under a declared storage.db_only directory and holds a file, which sync imports into the twin but no repair
- * adopts; null (prepareFileTarget's database-only reading) otherwise.
+ * repair writes there): `db_only` when its slug path is under a declared storage.db_only directory and holds a file (one
+ * or several), which sync imports into the twin but no repair adopts; `adopt` when it adopts its slug path as reconcile
+ * does (adoptableSlugOrigin) and sync admits that path (loadSyncEligibility: scope, sync.exclude, hidden and reserved
+ * paths); null (prepareFileTarget's database-only reading) otherwise, including a slug path several files import as.
+ * Any other refusal or failure throws.
*/
async function twinReading(engine: BrainEngine, sourceId: string, root: string, page: PageSnapshot): Promise<'adopt' | 'db_only' | null> {
- if (page.page.source_path || !existsSync(root) || !await isOriginTwinPage(engine, sourceId, page.page.slug) || await sourceMirrorReadOnly(engine, sourceId)) return null;
+ const slug = page.page.slug;
+ if (page.page.source_path || !existsSync(root) || !await isOriginTwinPage(engine, sourceId, slug) || await sourceMirrorReadOnly(engine, sourceId)) return null;
const real = realpathSync(root), mode = await scannerSlugRootMode(engine, sourceId, real);
try {
- if (await adoptableSlugOrigin(engine, sourceId, real, page, mode)) return 'adopt';
- return publishesDatabaseOnly(real, page.page.slug, page) && existsSync(slugPathFile(real, page.page.slug, mode)) ? 'db_only' : null;
- } catch { return 'adopt'; } // a refusal (several files import as the slug, an invalid gbrain.yml): readReconcileState reports it
+ if (publishesDatabaseOnly(real, slug, page)) return existsSync(slugPathFile(real, slug, mode)) ? 'db_only' : null;
+ const derived = await adoptableSlugOrigin(engine, sourceId, real, page, mode);
+ if (!derived) return null;
+ const [source] = await engine.executeRaw<{ last_commit: string | null; config: Record<string, unknown> | null }>('SELECT last_commit, config FROM sources WHERE id=$1', [sourceId]);
+ const gitRoot = realpathSync(syncGit(real, ['rev-parse', '--show-toplevel']).trim());
+ const { nativeRoot, nativeGitRoot, eligible } = await loadSyncEligibility(engine, { root: real, gitRoot, sourceId,
+ source: { last_commit: source?.last_commit ?? null, config: source?.config ?? {} } });
+ return eligible(relative(nativeGitRoot, join(nativeRoot, relative(real, derived.path))).split(sep).join('/')) ? 'adopt' : null;
+ } catch (error) {
+ if (error instanceof OperationError && error.detail === 'slug_path_ambiguous') return publishesDatabaseOnly(real, slug, page) ? 'db_only' : null;
+ throw error;
+ }
+}
+
+/**
+ * GBRA-108: whether another live page records an origin twin's slug-path file as its source path, so sync imports that
+ * file there and not into the twin. A page naming it only by file URI does not count: sync routes by source path. False
+ * when this cannot be read.
+ */
+async function claimedBySourcePath(engine: BrainEngine, sourceId: string, root: string, page: PageSnapshot): Promise<boolean> {
+ try {
+ const real = realpathSync(root), mode = await scannerSlugRootMode(engine, sourceId, real), slug = page.page.slug;
+ const path = slugPathFile(real, slug, mode), canonicalPath = realpathSync(path);
+ const claimants = await findLiveFileClaimants(engine, { sourceId, slug, pageId: page.page.id, root: real, mode, path, canonicalPath, recordedUri: null });
+ if (!claimants.length) return false;
+ const rows = await engine.executeRaw<{ slug: string; source_path: string | null }>('SELECT slug, source_path FROM pages WHERE source_id=$1 AND id=ANY($2::bigint[])',
+ [sourceId, claimants.map(claimant => claimant.id)]);
+ return rows.some(row => {
+ const recorded = row.source_path ? recordedReconcilePath(real, { slug: row.slug, source_path: row.source_path, source_uri: null }, mode) : null;
+ return !!recorded && existsSync(recorded) && realpathSync(recorded) === canonicalPath;
+ });
+ } catch { return false; }
}
/** The path `prepareFileTarget` compares, resolved the same way (recorded source path, captured file URI, then the slug path). */
diff --git a/test/repair-file-drift-origin-twin-gbra108.test.ts b/test/repair-file-drift-origin-twin-gbra108.test.ts
index 56c7567d52..7f8fe0a578 100644
--- a/test/repair-file-drift-origin-twin-gbra108.test.ts
+++ b/test/repair-file-drift-origin-twin-gbra108.test.ts
@@ -9,8 +9,9 @@
*/
import { expect, test } from 'bun:test';
import { execFileSync } from 'node:child_process';
-import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { appendFileSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { pathToFileURL } from 'node:url';
import type { BrainEngine } from '../src/core/engine.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { liveFileDrift } from '../src/core/persistence/drift-conflicts.ts';
@@ -141,3 +142,45 @@ test('an origin twin whose slug path no file can import as stays database-only',
await legacyTwin(engine, tx => tx.executeRaw("UPDATE pages SET slug='notes/Alpha-Example' WHERE source_id='default' AND slug=$1", [SLUG]));
expect(await liveFileDrift(engine, 'default', 'notes/Alpha-Example')).toMatchObject(DATABASE_ONLY);
}, { setup: setupRepo }), 120000);
+
+test('an origin twin whose slug-path file sync.exclude screens out stays database-only, and sync holds nothing for it', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine);
+ await engine.setConfig('sync.exclude', 'notes/');
+ await externalEdit(engine, root);
+ expect(await holds(engine)).toEqual([]);
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject(DATABASE_ONLY);
+}, { setup: setupRepo }), 120000);
+
+test('an origin twin whose slug-path file another live page names only by file URI is unknown, never no_drift, while sync holds it', () => managedBrain(async ({ engine, root }) => {
+ const uri = pathToFileURL(join(realpathSync(root), PATH)).href;
+ await legacyTwin(engine, tx => tx.executeRaw("UPDATE pages SET source_path=NULL, source_uri=$1 WHERE source_id='default' AND slug='notes/keeper-example'", [uri]));
+ git(root, 'rm', '-q', 'notes/keeper-example.md');
+ await externalEdit(engine, root);
+ expect(await holds(engine)).toEqual([{ code: 'file_drift', path: PATH }]);
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject({ still_present: null, reason: 'shared_origin' });
+ const planned = await preview(engine, 'database');
+ expect(planned.affected).toBe(0);
+ expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'unknown', detail: 'shared_origin' }]);
+}, { setup: ({ root }) => { setupRepo({ root }); writeFileSync(join(root, 'notes', 'keeper-example.md'), FILE); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'keeper'); } }), 120000);
+
+/** Two files that both import as the twin's slug, neither spelled exactly `<slug>.md`. */
+function ambiguousSlugPath(root: string): void {
+ git(root, 'mv', PATH, 'notes/Alpha-Example.md');
+ writeFileSync(join(root, 'notes', 'ALPHA-EXAMPLE.md'), FILE);
+ git(root, 'add', '-A');
+ git(root, 'commit', '-qm', 'two spellings');
+}
+
+test('an origin twin whose slug path several files import as reads as prepareFileTarget does, not slug_path_ambiguous', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine);
+ ambiguousSlugPath(root);
+ await performManagedSync(engine, { ...OPTS, full: true });
+ expect((await holds(engine)).filter(hold => hold.code === 'file_drift')).toEqual([]);
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject(DATABASE_ONLY);
+}, { setup: setupRepo }), 120000);
+
+test('an origin twin under a declared db_only path reads db_only_slug_path even when several files import as its slug', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine);
+ ambiguousSlugPath(root);
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject({ still_present: null, reason: 'db_only_slug_path' });
+}, { setup: ({ root }) => { setupRepo({ root }); writeFileSync(join(root, 'gbrain.yml'), 'storage:\n db_only:\n - notes/\n'); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'db_only'); } }), 120000);