Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): read an origin twin's drift only where it adopts its slug path

garrytan3f6255282164
diff --git a/src/core/persistence/drift-conflicts.ts b/src/core/persistence/drift-conflicts.ts
index a359f5d7a8..7fd20d518d 100644
--- a/src/core/persistence/drift-conflicts.ts
+++ b/src/core/persistence/drift-conflicts.ts
@@ -19,7 +19,7 @@
* updates and releases it once the file and database agree again;
* - doctor `maintenance_write_drift` and `gbrain repair file-drift`.
*/
-import { readFileSync } from 'node:fs';
+import { existsSync, readFileSync, realpathSync } from 'node:fs';
import { join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError, opError } from '../ops/contract.ts';
@@ -35,10 +35,10 @@ import type { PageSnapshot } from '../page-state/types.ts';
import { sha256 } from './digest.ts';
import { existingHostIdFor } from './identity.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { staleMirrorPage } from './mirror-read-only.ts';
+import { sourceMirrorReadOnly, staleMirrorPage } from './mirror-read-only.ts';
import { isOriginTwinPage } from './origin-twins.ts';
-import { prepareFileTarget } from './page-prepare.ts';
-import { readReconcileState } from './reconcile-state.ts';
+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 { recordsNoFileOrigin, slugPathFile } from './unbound-pages.ts';
@@ -86,13 +86,14 @@ export async function liveFileDrift(engine: BrainEngine, sourceId: string, slug:
const root = join(binding.local_path, binding.relative_path);
// GBRA-133 (#7931): a stale mirror page publishes database-only but reconciles against the file at its slug path.
// #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. Sync imports the file at its slug path into it (and holds it
- // file_drift when they differ), so the drift is read from that file 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 = !page.page.source_path && await isOriginTwinPage(engine, sourceId, slug);
- if (twin || await staleMirrorPage(engine, sourceId, page.page)) {
+ // 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);
+ 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 {
- const state = await readReconcileState(engine, sourceId, slug, undefined, { adoptSlugPath: twin });
+ const state = await readReconcileState(engine, sourceId, slug, undefined, { adoptSlugPath: twin === 'adopt' });
const agrees = classifyDrift(state.file, reconcileCanonical(state.snapshot.page, state.snapshot.tags)).verdict === 'no_drift';
return { still_present: !agrees, reason: agrees ? 'agrees' : 'file_database_drift', db_revision: state.snapshot.revision,
path: relative(state.root, state.path).split(sep).join('/'), file_hash: sha256(state.raw) };
@@ -122,6 +123,21 @@ 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.
+ */
+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 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
+}
+
/** The path `prepareFileTarget` compares, resolved the same way (recorded source path, captured file URI, then the slug path). */
async function canonicalFilePath(engine: BrainEngine, sourceId: string, root: string, snapshot: PageSnapshot, slug: string): Promise<string> {
const mode = await scannerSlugRootMode(engine, sourceId, root);
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index dcb48dbf45..ce33fd53ef 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -213,6 +213,18 @@ async function assertSoleFileClaim(engine: BrainEngine, target: FileClaimTarget)
{ detail: 'shared_origin', fix: readFix(`Lists the duplicate-origin group of ${target.slug} and ${claimant.slug} with the page its path names and the command that resolves each other page; writes nothing.`,
{ argv: originTwinsPreviewArgv(target.sourceId) }) });
}
+/**
+ * #6394: the file at a page's slug path that `adoptSlugPath` reconciles it against, or null when the page records a file
+ * origin, publishes database-only by design (a declared db_only slug, a never-filed derive-phase page), is mirror-only, or
+ * its slug path cannot be derived inside the source. `root` is the realpath of the source root. Throws
+ * `slug_path_ambiguous` when several files import as the slug. liveFileDrift reads an origin twin's drift with it.
+ */
+export async function adoptableSlugOrigin(engine: BrainEngine, sourceId: string, root: string, snapshot: PageSnapshot,
+ mode: 'git-root' | 'source-root'): Promise<{ path: string; sourcePath: string } | null> {
+ if (!recordsNoFileOrigin(snapshot.page) || publishesDatabaseOnly(root, snapshot.page.slug, snapshot) || await isMirrorOnlyPage(engine, sourceId, snapshot.page.slug)) return null;
+ const derived = slugDerivedOrigin(root, snapshot.page.slug, mode);
+ return derived && isWriteTargetContained(derived.path, root) ? derived : null;
+}
/**
* #6394: `adoptSlugPath` lets a live page with no recorded origin and no database-only marker reconcile against the file
* at its slug path (mode-aware, as discovery names it). A page that publishes database-only by design (a declared db_only
@@ -239,9 +251,8 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,
const recordedPath = recordedReconcilePath(root, snapshot.page, mode);
const marked = !recordedPath && (isDatabaseOnlyPage({ ...snapshot.page,
database_only_reason: await isUnboundSourcePage(engine, sourceId, slug) ? 'unbound_source' : null }) || await staleMirrorPage(engine, sourceId, snapshot.page));
- const adoptable = !recordedPath && !marked && opts.adoptSlugPath === true && recordsNoFileOrigin(snapshot.page)
- && !publishesDatabaseOnly(root, slug, snapshot) && !await isMirrorOnlyPage(engine, sourceId, slug);
- const derived = marked || adoptable ? slugDerivedOrigin(root, slug, mode) : null;
+ const adoptable = !recordedPath && !marked && opts.adoptSlugPath === true;
+ const derived = marked ? slugDerivedOrigin(root, slug, mode) : adoptable ? await adoptableSlugOrigin(engine, sourceId, root, snapshot, mode) : null;
const origin = derived ? 'slug_derived' : 'recorded';
const path = recordedPath ?? derived?.path ?? null;
if (!path || !isWriteTargetContained(path, root)) throw opError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.',
diff --git a/test/repair-file-drift-origin-twin-gbra108.test.ts b/test/repair-file-drift-origin-twin-gbra108.test.ts
index 8b24c98118..56c7567d52 100644
--- a/test/repair-file-drift-origin-twin-gbra108.test.ts
+++ b/test/repair-file-drift-origin-twin-gbra108.test.ts
@@ -44,8 +44,8 @@ const holds = (engine: BrainEngine) => engine.executeRaw<{ code: string; path: s
const row = async (engine: BrainEngine) => (await engine.executeRaw<{ source_path: string | null; database_only_reason: string | null; compiled_truth: string }>(
'SELECT source_path, database_only_reason, compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', ['default', SLUG]))[0]!;
-/** A legacy origin twin whose file then gained a timeline bullet in an external commit, held `file_drift` by sync. */
-async function heldLegacyTwin(engine: BrainEngine, root: string): Promise<void> {
+/** The imported page turned into a legacy origin twin with no recorded file and database-only edits; `extra` runs in the same write. */
+async function legacyTwin(engine: BrainEngine, extra?: (tx: BrainEngine) => Promise<unknown>): Promise<void> {
expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
await tx.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-import-provenance'");
@@ -53,10 +53,21 @@ async function heldLegacyTwin(engine: BrainEngine, root: string): Promise<void>
ingested_at=NULL, ingested_via=NULL, source_path=NULL, source_uri=NULL, database_only_reason='origin_twin',
compiled_truth=compiled_truth || E'\\nA database-only line.', frontmatter=frontmatter || '{"status":"database-only"}'::jsonb
WHERE source_id='default' AND slug=$1`, [SLUG]);
+ await extra?.(tx);
}, TEST_WRITE_ATTRIBUTION));
+}
+
+/** An external commit appends a timeline bullet to the twin's slug-path file; sync runs a full pass over it. */
+async function externalEdit(engine: BrainEngine, root: string): Promise<void> {
appendFileSync(join(root, PATH), `${BULLET}\n`);
git(root, 'commit', '-qam', 'external edit');
expect((await performManagedSync(engine, { ...OPTS, full: true })).status).toBe('synced');
+}
+
+/** A legacy origin twin whose file then gained a timeline bullet in an external commit, held `file_drift` by sync. */
+async function heldLegacyTwin(engine: BrainEngine, root: string): Promise<void> {
+ await legacyTwin(engine);
+ await externalEdit(engine, root);
expect(await holds(engine)).toEqual([{ code: 'file_drift', path: PATH }]);
}
@@ -89,11 +100,44 @@ test('a held origin twin resolved --prefer file takes the file and clears the ho
expect(after.compiled_truth).toContain(BULLET);
}, { setup: setupRepo }), 120000);
-test('an origin twin whose slug-path file another live page records stays database-only', () => managedBrain(async ({ engine, root }) => {
- expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
- await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
- await tx.executeRaw("UPDATE pages SET source_path=NULL, source_uri=NULL, database_only_reason='origin_twin' WHERE source_id='default' AND slug=$1", [SLUG]);
- await tx.executeRaw("UPDATE pages SET source_path=$1 WHERE source_id='default' AND slug='notes/keeper-example'", [PATH]);
- }, TEST_WRITE_ATTRIBUTION));
- expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject({ still_present: false, reason: 'database_only' });
-}, { setup: ({ root }) => { setupRepo({ root }); writeFileSync(join(root, 'notes', 'keeper-example.md'), '---\ntype: concept\ntitle: Keeper Example\n---\n\nThe keeper.\n'); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'keeper'); } }), 120000);
+const DATABASE_ONLY = { still_present: false, reason: 'database_only' };
+
+test('an origin twin whose slug-path file another live page records stays database-only, and sync holds nothing for it', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine, tx => tx.executeRaw("UPDATE pages SET source_path=$1 WHERE source_id='default' AND slug='notes/keeper-example'", [PATH]));
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject(DATABASE_ONLY);
+ git(root, 'rm', '-q', 'notes/keeper-example.md');
+ await externalEdit(engine, root);
+ expect(await holds(engine)).toEqual([]);
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject(DATABASE_ONLY);
+}, { setup: ({ root }) => { setupRepo({ root }); writeFileSync(join(root, 'notes', 'keeper-example.md'), FILE); git(root, 'add', '-A'); git(root, 'commit', '-qm', 'keeper'); } }), 120000);
+
+test('an origin twin in a read-only mirror source is not listed for a repair no apply could make', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine, tx => tx.executeRaw("UPDATE sources SET config=config || '{\"mirror_read_only\":\"true\"}'::jsonb WHERE id='default'"));
+ await externalEdit(engine, root);
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject(DATABASE_ONLY);
+ const planned = await preview(engine, 'database');
+ expect(planned.affected).toBe(0);
+ expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'no_drift', detail: 'database_only' }]);
+}, { setup: setupRepo }), 120000);
+
+test('a held origin twin under a declared db_only path is listed as unknown with its reason, never no_drift', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine);
+ 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: 'db_only_slug_path' });
+ const planned = await preview(engine, 'database');
+ expect(planned.residuals).toEqual({ unknown_db_only_slug_path: 1 });
+ expect(planned.listing).toEqual([{ item: `default:${SLUG}`, class: 'unknown', detail: '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);
+
+test('an origin twin whose slug-path file is missing stays database-only', () => managedBrain(async ({ engine, root }) => {
+ await legacyTwin(engine);
+ git(root, 'rm', '-q', PATH);
+ git(root, 'commit', '-qm', 'remove the file');
+ expect(await liveFileDrift(engine, 'default', SLUG)).toMatchObject(DATABASE_ONLY);
+}, { setup: setupRepo }), 120000);
+
+test('an origin twin whose slug path no file can import as stays database-only', () => managedBrain(async ({ engine }) => {
+ 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);