Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): dedupe managed roots and the #2018 leak guard by filesystem identity (#7203)

garrytan42dd322c9fc1
diff --git a/src/commands/doctor/checks/default-source-path.ts b/src/commands/doctor/checks/default-source-path.ts
index af81413ade..96d759c57c 100644
--- a/src/commands/doctor/checks/default-source-path.ts
+++ b/src/commands/doctor/checks/default-source-path.ts
@@ -16,6 +16,7 @@ import { existsSync, statSync } from 'fs';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
import { assessDefaultSourcePath } from '../../../core/default-source-path-check.ts';
+import { otherSourceAtPath } from '../../../core/write-through.ts';
export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<Check | null> {
const [defaultSource] = await engine.executeRaw<{ local_path: string | null }>(
@@ -27,6 +28,7 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<
let repoPath: string | null = null;
let repoPathIsDir = false;
let collidingSourceId: string | null = null;
+ let sharedPages = 0;
// Only gather the fallback-topology inputs when the pointer is actually
// null — the set case resolves from the row alone.
if (defaultSource && !defaultSource.local_path) {
@@ -47,11 +49,16 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<
}
// Mirror resolvePageWriteTarget's #2018 leak guard: sync.repo_path
// being another source's own working tree silently skips the write.
- const collide = await engine.executeRaw<{ id: string }>(
- `SELECT id FROM sources WHERE id <> 'default' AND local_path = $1 LIMIT 1`,
- [repoPath],
- );
- collidingSourceId = collide[0]?.id ?? null;
+ collidingSourceId = await otherSourceAtPath(engine, 'default', repoPath);
+ if (collidingSourceId) {
+ const [shared] = await engine.executeRaw<{ n: number }>(
+ `SELECT COUNT(*)::int AS n FROM pages a
+ WHERE a.source_id = 'default' AND a.deleted_at IS NULL AND a.source_path IS NOT NULL
+ AND EXISTS (SELECT 1 FROM pages b WHERE b.source_id = $1 AND b.source_path = a.source_path AND b.deleted_at IS NULL)`,
+ [collidingSourceId],
+ );
+ sharedPages = Number(shared?.n ?? 0);
+ }
}
}
@@ -62,6 +69,7 @@ export async function defaultSourceLocalPathCheck(engine: BrainEngine): Promise<
repoPath,
repoPathIsDir,
collidingSourceId,
+ sharedPages,
});
if (assessment.status === 'skip') return null;
return {
diff --git a/src/core/default-source-path-check.ts b/src/core/default-source-path-check.ts
index fbc133b765..5e1e963643 100644
--- a/src/core/default-source-path-check.ts
+++ b/src/core/default-source-path-check.ts
@@ -41,8 +41,10 @@ export interface DefaultSourcePathInput {
repoPath: string | null;
/** True when repoPath exists on disk and is a directory. */
repoPathIsDir: boolean;
- /** A non-default source whose own local_path equals repoPath (#2018 leak guard), if any. */
+ /** A non-default source whose own local_path is repoPath under any spelling (#2018 leak guard, #7203), if any. */
collidingSourceId: string | null;
+ /** Live default-source pages whose source_path also names a live page of collidingSourceId. */
+ sharedPages?: number;
}
export interface DefaultSourcePathAssessment {
@@ -53,7 +55,7 @@ export interface DefaultSourcePathAssessment {
export function assessDefaultSourcePath(
input: DefaultSourcePathInput,
): DefaultSourcePathAssessment {
- const { defaultSource, livePages, fileBackedPages, repoPath, repoPathIsDir, collidingSourceId } = input;
+ const { defaultSource, livePages, fileBackedPages, repoPath, repoPathIsDir, collidingSourceId, sharedPages = 0 } = input;
if (!defaultSource) {
// No `default` row at all is a different, more fundamental problem than
// this check's scope — leave it to whatever check owns sources-table
@@ -85,7 +87,13 @@ export function assessDefaultSourcePath(
`"${collidingSourceId}"'s own working tree — the #2018 leak guard silently SKIPS every ` +
`unscoped write-through for the ${livePages} default-source page(s), so \`gbrain put\`/` +
'`gbrain capture` writes never reach disk. Fix with `gbrain sources set-path default <path>` ' +
- '(non-destructive pointer repair).',
+ '(non-destructive pointer repair).' +
+ (sharedPages > 0
+ ? ` ${sharedPages} default-source page(s) share a file path with a live "${collidingSourceId}" page: an earlier ` +
+ `write-through under another spelling of this path (a symlink, a trailing slash, a case or /private alias) may have ` +
+ `written them into "${collidingSourceId}"'s tree, where its sync imported them as its own pages. Compare those files ` +
+ 'with their default-source pages before deleting anything; nothing was changed.'
+ : ''),
};
}
if (rootResolvable) {
diff --git a/src/core/persistence/filesystem-guard.ts b/src/core/persistence/filesystem-guard.ts
index 4ae4d7049e..d814aae69d 100644
--- a/src/core/persistence/filesystem-guard.ts
+++ b/src/core/persistence/filesystem-guard.ts
@@ -25,15 +25,15 @@ function encloses(root: string, path: string): boolean {
export async function refreshManagedFilesystemRoots(engine: SqlEngine, databasePath = datastorePaths.get(engine), signal?: AbortSignal): Promise<void> {
// Mode and epoch come from one snapshot, so roots are never recorded under the epoch of a concurrent deactivation.
const brain = await readPersistenceBrain(engine, { signal });
- const roots = brain.enabled ? await engine.executeRaw<ManagedRootRecord>(`SELECT DISTINCT ON (local_path) * FROM (
- SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
+ if (!brain.enabled) { managedRoots.set(brain.brain_id, new Map()); return; }
+ // Rows are deduplicated by filesystem identity in recordManagedRoots, never by the stored spelling (#7203).
+ const rows = await engine.executeRaw<ManagedRootRecord>(`SELECT h.local_path,s.source_id,s.source_incarnation,s.worktree_id,s.topology_generation
FROM persistence_host_bindings h JOIN persistence_source_bindings s ON s.worktree_id=h.worktree_id WHERE h.host_id=$1::uuid
- UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL
- ) roots ORDER BY local_path,worktree_id NULLS LAST,source_id,source_incarnation,topology_generation`, [localHostId()], { signal }) : [];
+ UNION SELECT local_path,id,incarnation,NULL,NULL FROM sources WHERE local_path IS NOT NULL`, [localHostId()], { signal });
signal?.throwIfAborted();
- if (brain.enabled && databasePath) roots.push({ local_path: databasePath });
- if (brain.enabled) recordManagedRoots(brain.brain_id, roots, brain.mode_epoch == null ? undefined : Number(brain.mode_epoch));
- managedRoots.set(brain.brain_id, new Map(roots.map(row => [resolve(row.local_path), row.source_id])));
+ if (databasePath) rows.push({ local_path: databasePath });
+ const roots = recordManagedRoots(brain.brain_id, rows, brain.mode_epoch == null ? undefined : Number(brain.mode_epoch));
+ managedRoots.set(brain.brain_id, new Map(roots.map(row => [row.local_path, row.source_id])));
}
export function hasFilesystemPublication(path: string): boolean {
const held = active.getStore();
diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.ts
index 0c7adb60c8..a5c4c53904 100644
--- a/src/core/persistence/root-registry.ts
+++ b/src/core/persistence/root-registry.ts
@@ -97,21 +97,45 @@ function resolveFilesystemPath(path: string, realpath: (path: string) => string)
}
}
}
+const rootRank = (record: ManagedRootRecord) => [record.worktree_id ? 0 : 1, record.worktree_id, record.source_id, record.source_incarnation, record.topology_generation]
+ .map(value => value == null ? '\u{10FFFF}' : String(value));
+/**
+ * #7203: one record per filesystem identity. Aliases of one directory (a
+ * symlink, macOS /var vs /private/var, a case variant) collapse to its
+ * canonical path, and a bound worktree row outranks an unbound source path
+ * regardless of spelling or input order.
+ */
+export function canonicalManagedRoots(records: ManagedRootRecord[]): ManagedRootRecord[] {
+ const byRoot = new Map<string, ManagedRootRecord>();
+ for (const record of records) {
+ const root = canonicalFilesystemPath(record.local_path);
+ const held = byRoot.get(root);
+ if (held) {
+ const [next, current] = [rootRank(record), rootRank(held)];
+ const at = next.findIndex((value, i) => value !== current[i]);
+ if (at < 0 || next[at]! > current[at]!) continue;
+ }
+ byRoot.set(root, { ...record, local_path: root });
+ }
+ return [...byRoot.values()];
+}
/**
* One private immutable path identity per brain/root; topology metadata can be
* refreshed but stale roots stay fenced until an explicit verified drain clears
* them. Per-root files prevent independent registration from dropping siblings.
+ * Returns the canonical records it holds, one per root.
*/
-export function recordManagedRoots(brainId: string, records: ManagedRootRecord[], modeEpoch?: number): void {
+export function recordManagedRoots(brainId: string, records: ManagedRootRecord[], modeEpoch?: number): ManagedRootRecord[] {
if (!/^[a-f0-9-]{36}$/i.test(brainId)) {
throw opError('storage_error', 'Invalid managed-root brain identity.',
'The managed-root registry was given a brain identity that is not a UUID, so nothing was recorded. This is an internal fault: run gbrain doctor --json and report it to the user.');
}
- if (!records.length) return;
+ const canonical = canonicalManagedRoots(records);
+ if (!canonical.length) return canonical;
const directory = registryDirectory(); mkdirSync(directory, { recursive: true, mode: 0o700 }); ensureMode(directory, 0o700);
let changed = false;
- for (const record of records) {
- const root = canonicalFilesystemPath(record.local_path);
+ for (const record of canonical) {
+ const root = record.local_path;
const key = createHash('sha256').update(root).digest('hex');
const file = join(directory, `${brainId}.${key}.json`);
const value = JSON.stringify({ version: 1, brain_id: brainId, root, ...record, local_path: root,
@@ -125,6 +149,7 @@ export function recordManagedRoots(brainId: string, records: ManagedRootRecord[]
}
}
if (changed) flushDirectory(directory);
+ return canonical;
}
/** Available before connect, including while another process owns local PGLite. */
export function registeredManagedRoots(): string[] {
diff --git a/src/core/write-through.ts b/src/core/write-through.ts
index 804c7972a0..62f1d89d5e 100644
--- a/src/core/write-through.ts
+++ b/src/core/write-through.ts
@@ -31,6 +31,7 @@ import { isWriteTargetContained, msysToNativePath } from './path-confine.ts';
import { readSlugRootMode, resolveSlugRootMode, type SlugRootMode } from './sync-anchor.ts';
import { resolveSlugForPath } from './sync.ts';
import { PUSH_SCAN_MAX_FILE_BYTES } from './page-size-policy.ts';
+import { canonicalFilesystemPath } from './persistence/root-registry.ts';
import {
isDurabilityHardened, commitWriteThroughFile, currentBranch, getLastPushOutcome,
type PushLogOutcome,
@@ -279,6 +280,25 @@ export async function scannerSlugRootMode(engine: BrainEngine, sourceId: string,
return resolveSlugRootMode(engine, { sourceId, explicitGitRoot: false, slugPrefix: resolveSlugForPath(`${scope}/x.md`).slice(0, -2), dryRun: true });
}
+/**
+ * #2018/#7203: the other source whose own working tree is `path`, compared by
+ * filesystem identity, so a symlink, a trailing slash, or a macOS case or
+ * /private alias still matches. A spelling that cannot be resolved counts as a
+ * match: the leak guard fails closed.
+ */
+export async function otherSourceAtPath(engine: BrainEngine, sourceId: string, path: string): Promise<string | null> {
+ const rows = await engine.executeRaw<{ id: string; local_path: string }>(
+ `SELECT id, local_path FROM sources WHERE id <> $1 AND local_path IS NOT NULL AND local_path <> '' ORDER BY id`,
+ [sourceId],
+ );
+ const identity = (spelling: string) => { try { return canonicalFilesystemPath(msysToNativePath(spelling)); } catch { return null; } };
+ const target = identity(path);
+ return rows.find(row => {
+ const other = identity(row.local_path);
+ return target === null || other === null || other === target;
+ })?.id ?? null;
+}
+
/**
* Compute the ONE file a (source, slug) pair lives in on disk.
*
@@ -368,12 +388,8 @@ export async function resolvePageWriteTarget(
return { ok: false, skipped: 'repo_not_found' };
}
// Leak guard: refuse to write into a path that is some OTHER source's
- // own working tree (#2018).
- const collide = await engine.executeRaw<{ one: number }>(
- `SELECT 1 AS one FROM sources WHERE id <> $1 AND local_path = $2 LIMIT 1`,
- [sourceId, repoPath],
- );
- if (collide.length > 0) {
+ // own working tree (#2018), under any spelling of it (#7203).
+ if (await otherSourceAtPath(engine, sourceId, repoPath)) {
return { ok: false, skipped: 'source_repo_belongs_to_other_source' };
}
const pageRoot = sourceId === 'default' ? repoPath : join(repoPath, '.sources', sourceId);
diff --git a/test/managed-root-aliases-7203.test.ts b/test/managed-root-aliases-7203.test.ts
new file mode 100644
index 0000000000..a578786de7
--- /dev/null
+++ b/test/managed-root-aliases-7203.test.ts
@@ -0,0 +1,110 @@
+/**
+ * #7203: managed filesystem roots are deduplicated by filesystem identity, not
+ * by the stored spelling. A bound worktree and an unbound source path that
+ * alias one directory (a symlink, a trailing slash, macOS /var vs /private/var,
+ * a case variant) leave one canonical record that keeps the bound identity,
+ * whichever spelling sorts first, and an idle refresh rewrites nothing.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { assertManagedFilesystemWrite, managedFilesystemRootFor, refreshManagedFilesystemRoots } from '../src/core/persistence/filesystem-guard.ts';
+import { readPersistenceBrain } from '../src/core/persistence/managed-mode.ts';
+import { canonicalFilesystemPath, canonicalManagedRoots, recordManagedRoots } from '../src/core/persistence/root-registry.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const caseInsensitive = (() => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-case-probe-'));
+ try { mkdirSync(join(dir, 'probe')); return existsSync(join(dir, 'PROBE')); } finally { rmSync(dir, { recursive: true, force: true }); }
+})();
+
+async function setSourcePath(engine: BrainEngine, kind: 'same' | 'other', path: string): Promise<void> {
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ if (kind === 'same') await tx.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [path]);
+ else await tx.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['alias-source', path]);
+ });
+}
+
+function registry(home: string) {
+ const dir = join(home, '.gbrain', 'persistence', 'managed-roots');
+ return readdirSync(dir).filter(file => file.endsWith('.json')).map(file => {
+ const stat = statSync(join(dir, file), { bigint: true });
+ return { file, stamp: `${stat.ino}:${stat.mtimeNs}:${stat.ctimeNs}`, record: JSON.parse(readFileSync(join(dir, file), 'utf8')) };
+ });
+}
+
+type Spelling = { name: string; make: (home: string, root: string) => string; skip?: boolean };
+const spellings: Spelling[] = [
+ { name: 'symlink sorting before the real path', make: (home, root) => { const alias = join(home, 'aaa-alias'); symlinkSync(root, alias); return alias; } },
+ { name: 'symlink sorting after the real path', make: (home, root) => { const alias = join(home, 'zzz-alias'); symlinkSync(root, alias); return alias; } },
+ { name: 'trailing slash', make: (_home, root) => `${root}/` },
+ { name: 'case variant (case-insensitive filesystem only)', make: (home, root) => join(home, basename(root).toUpperCase()), skip: !caseInsensitive },
+];
+
+for (const backend of testBackends()) {
+ describe(`managed-root aliases keep the bound record (${backend})`, () => {
+ for (const spelling of spellings) for (const kind of ['same', 'other'] as const) {
+ test.skipIf(!!spelling.skip)(`${spelling.name}, ${kind === 'same' ? 'same source' : 'second source'}`, async () => {
+ await managedBrain(async ({ engine, root }) => {
+ const home = join(root, '..');
+ const alias = spelling.make(home, root);
+ const [bound] = await engine.executeRaw<{ worktree_id: string; topology_generation: string }>(
+ "SELECT worktree_id::text AS worktree_id, topology_generation::text AS topology_generation FROM persistence_source_bindings WHERE source_id='default'");
+ await setSourcePath(engine, kind, alias);
+ await refreshManagedFilesystemRoots(engine);
+ const first = registry(home);
+ const records = first.filter(entry => entry.record.root === canonicalFilesystemPath(root));
+ expect(records).toHaveLength(1);
+ expect(records[0]!.record).toMatchObject({ source_id: 'default', worktree_id: bound!.worktree_id, topology_generation: bound!.topology_generation });
+ expect(managedFilesystemRootFor(join(alias, 'note.md'))?.sourceId).toBe('default');
+ for (const path of [join(root, 'note.md'), join(alias, 'note.md')]) {
+ expect(() => assertManagedFilesystemWrite(path)).toThrow('managed canonical worktree');
+ }
+ // Past the filesystem timestamp tick, so a rewrite with a recycled inode still shows.
+ await new Promise(resolve => setTimeout(resolve, 50));
+ await refreshManagedFilesystemRoots(engine);
+ expect(registry(home).map(entry => entry.stamp)).toEqual(first.map(entry => entry.stamp));
+ }, { databaseUrl: backend === 'pglite' ? undefined : requirePostgresTestDatabase() });
+ }, 120_000);
+ }
+
+ test('a record an alias already overwrote heals to the bound identity on the next refresh', async () => {
+ await managedBrain(async ({ engine, root }) => {
+ const home = join(root, '..');
+ const alias = join(home, 'zzz-alias'); symlinkSync(root, alias);
+ await setSourcePath(engine, 'other', alias);
+ const brain = await readPersistenceBrain(engine);
+ recordManagedRoots(brain.brain_id, [{ local_path: alias, source_id: 'alias-source' }], Number(brain.mode_epoch));
+ expect(registry(home).find(entry => entry.record.root === canonicalFilesystemPath(root))?.record.source_id).toBe('alias-source');
+ await refreshManagedFilesystemRoots(engine);
+ const healed = registry(home).filter(entry => entry.record.root === canonicalFilesystemPath(root));
+ expect(healed).toHaveLength(1);
+ expect(healed[0]!.record.source_id).toBe('default');
+ expect(typeof healed[0]!.record.worktree_id).toBe('string');
+ expect(managedFilesystemRootFor(join(alias, 'note.md'))?.sourceId).toBe('default');
+ }, { databaseUrl: backend === 'pglite' ? undefined : requirePostgresTestDatabase() });
+ }, 120_000);
+ });
+}
+
+test('canonicalManagedRoots is independent of input order and spelling', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-canonical-roots-'));
+ try {
+ const real = join(home, 'real'); mkdirSync(real);
+ const alias = join(home, 'alias'); symlinkSync(real, alias);
+ const rows = [
+ { local_path: alias, source_id: 'source-b', source_incarnation: 'b1' },
+ { local_path: `${real}/`, source_id: 'source-c', source_incarnation: 'c1' },
+ { local_path: real, source_id: 'source-a', source_incarnation: 'a1', worktree_id: '00000000-0000-4000-8000-000000000001', topology_generation: 3 },
+ ];
+ const expected = [{ ...rows[2]!, local_path: canonicalFilesystemPath(real) }];
+ expect(canonicalManagedRoots(rows)).toEqual(expected);
+ expect(canonicalManagedRoots([...rows].reverse())).toEqual(expected);
+ expect(canonicalManagedRoots([rows[1]!, rows[2]!, rows[0]!])).toEqual(expected);
+ expect(canonicalManagedRoots([rows[0]!, rows[1]!])).toEqual(canonicalManagedRoots([rows[1]!, rows[0]!]));
+ } finally { rmSync(home, { recursive: true, force: true }); }
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6583180d80..ad609f264d 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -201,6 +201,7 @@ test/managed-facts-withdrawal-recovery-6506.test.ts
test/managed-facts-withdrawn-skip-6506.test.ts
test/managed-lint.test.ts
test/managed-maintenance-links.test.ts
+test/managed-root-aliases-7203.test.ts
test/managed-sweep-corpus-windows.test.ts
test/managed-sweep-refused-window-retry.test.ts
test/managed-sweep-timeline.test.ts
@@ -446,5 +447,6 @@ test/vector-manifest-probe-bound.test.ts
test/withdrawal-overlay-concurrency.test.ts
test/withdrawal-publication-file.test.ts
test/worktree-refresh-recovery-row-gbra130.test.ts
+test/write-through-leak-guard-alias-7203.test.ts
test/writer-status-movement-not-read-gbra130.test.ts
test/writer-status-owner-backends.test.ts
diff --git a/test/write-through-leak-guard-alias-7203.test.ts b/test/write-through-leak-guard-alias-7203.test.ts
new file mode 100644
index 0000000000..2daed62d05
--- /dev/null
+++ b/test/write-through-leak-guard-alias-7203.test.ts
@@ -0,0 +1,92 @@
+/**
+ * #2018/#7203: the write-through leak guard compares \`sync.repo_path\` with
+ * every other source's own working tree by filesystem identity. A symlink, a
+ * trailing slash or a case variant of another source's checkout is still that
+ * checkout, so a page of a source with no local_path is never written into it;
+ * a spelling that cannot be resolved fails closed. The doctor check
+ * default_source_local_path names the same collision and counts pages that an
+ * earlier misrouted write may already have duplicated.
+ */
+import { describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, join } from 'node:path';
+import { defaultSourceLocalPathCheck } from '../src/commands/doctor/checks/default-source-path.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { resolvePageWriteTarget } from '../src/core/write-through.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const caseInsensitive = (() => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-case-probe-'));
+ try { mkdirSync(join(dir, 'probe')); return existsSync(join(dir, 'PROBE')); } finally { rmSync(dir, { recursive: true, force: true }); }
+})();
+
+async function brain(backend: string, run: (engine: BrainEngine, home: string, tree: string) => Promise<void>): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-leak-guard-'));
+ const { engine, close } = await isolatedSharedSkillsEngine(backend === 'pglite' ? undefined : requirePostgresTestDatabase());
+ try {
+ const tree = join(home, 'source-b-tree'); mkdirSync(tree);
+ await engine.executeRaw("UPDATE sources SET local_path=NULL WHERE id='default'");
+ await run(engine, home, tree);
+ } finally { await close(); rmSync(home, { recursive: true, force: true }); }
+}
+
+type Spelling = { name: string; make: (home: string, tree: string) => string; skip?: boolean };
+const spellings: Spelling[] = [
+ { name: 'symlink', make: (home, tree) => { const alias = join(home, 'alias'); symlinkSync(tree, alias); return alias; } },
+ { name: 'trailing slash', make: (_home, tree) => `${tree}/` },
+ { name: 'case variant (case-insensitive filesystem only)', make: (home, tree) => join(home, basename(tree).toUpperCase()), skip: !caseInsensitive },
+];
+
+for (const backend of testBackends()) {
+ describe(`write-through leak guard compares filesystem identity (${backend})`, () => {
+ for (const spelling of spellings) for (const side of ['sync.repo_path', 'source local_path'] as const) {
+ test.skipIf(!!spelling.skip)(`${spelling.name} on ${side} is refused`, async () => {
+ await brain(backend, async (engine, home, tree) => {
+ const alias = spelling.make(home, tree);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', side === 'source local_path' ? alias : tree]);
+ await engine.setConfig('sync.repo_path', side === 'sync.repo_path' ? alias : tree);
+ expect(await resolvePageWriteTarget(engine, 'notes/x', 'default')).toEqual({ ok: false, skipped: 'source_repo_belongs_to_other_source' });
+ expect(await resolvePageWriteTarget(engine, 'notes/x', 'source-c')).toEqual({ ok: false, skipped: 'source_repo_belongs_to_other_source' });
+ });
+ }, 60_000);
+ }
+
+ test('a distinct checkout is not a collision', async () => {
+ await brain(backend, async (engine, home, tree) => {
+ const repo = join(home, 'repo'); mkdirSync(repo);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', tree]);
+ await engine.setConfig('sync.repo_path', repo);
+ const target = await resolvePageWriteTarget(engine, 'notes/x', 'default');
+ expect(target).toMatchObject({ ok: true, filePath: join(repo, 'notes', 'x.md') });
+ });
+ }, 60_000);
+
+ test('another source path that cannot be resolved fails closed', async () => {
+ await brain(backend, async (engine, home) => {
+ const repo = join(home, 'repo'); mkdirSync(repo);
+ const loop = join(home, 'loop'); symlinkSync(loop, loop);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', loop]);
+ await engine.setConfig('sync.repo_path', repo);
+ expect(await resolvePageWriteTarget(engine, 'notes/x', 'default')).toEqual({ ok: false, skipped: 'source_repo_belongs_to_other_source' });
+ });
+ }, 60_000);
+
+ test('doctor names the aliased collision and counts pages a misrouted write may have duplicated', async () => {
+ await brain(backend, async (engine, home, tree) => {
+ const alias = join(home, 'alias'); symlinkSync(tree, alias);
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['source-b', tree]);
+ await engine.setConfig('sync.repo_path', alias);
+ for (const [source, slug] of [['default', 'notes/x'], ['source-b', 'notes/x'], ['default', 'notes/y']] as const) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'body', timeline: '', frontmatter: {} }, { sourceId: source });
+ }
+ await engine.executeRaw("UPDATE pages SET source_path='notes/x.md' WHERE slug='notes/x'");
+ const check = await defaultSourceLocalPathCheck(engine);
+ expect(check?.status).toBe('warn');
+ expect(check?.message).toContain('"source-b"\'s own working tree');
+ expect(check?.message).toContain('1 default-source page(s) share a file path with a live "source-b" page');
+ });
+ }, 60_000);
+ });
+}