Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(reconcile): adopt a canonical file that differs from its slug only by case (#6670)
time-attackf07a0d98aada
diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex c83d28caf5..e248be1329 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -69,7 +69,13 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringfor (const candidate of rows.slice(0, limit)) {report.inspected++;if (isDatabaseOnlyPage(candidate)) {- const origin = slugDerivedOrigin(root, candidate.slug, mode);+ let origin: ReturnType<typeof slugDerivedOrigin>;+ try { origin = slugDerivedOrigin(root, candidate.slug, mode); } catch (error) {+ if (!(error instanceof OperationError)) throw error;+ report.errors++;+ report.findings.push({ slug: candidate.slug, reason: error.detail ?? error.code, suggestion: error.suggestion ?? error.message });+ continue;+ }if (!origin || !existsSync(origin.path)) {report.database_only++;report.findings.push({ slug: candidate.slug, reason: 'database_only',diff --git a/src/core/persistence/unbound-pages.ts b/src/core/persistence/unbound-pages.tsindex 40f5cf85c3..61f5b19166 100644--- a/src/core/persistence/unbound-pages.ts+++ b/src/core/persistence/unbound-pages.ts@@ -11,7 +11,10 @@* stamped in the publication transaction), so an ordinary page that merely* lacks a recorded origin is never matched to a slug-derived file.*/+import { readdirSync, type Dirent } from 'node:fs';+import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';import { resolveSourceLocalFilePath } from '../markdown.ts';+import { opError } from '../ops/contract.ts';import { scannerSourcePath } from '../write-through.ts';import { resolveSlugForPath } from '../sync.ts';@@ -31,10 +34,38 @@ export function databaseOnlyPageSql(alias: string): string {* `source_path` a scan of that file records. Null when it resolves outside the* source, or when a scan of the candidate would give it a different slug (a* legacy source-relative fallback in a Git subfolder source names another page).+ *+ * #6670: the importer lowercases a file's path into its slug, so `HEARTBEAT.md`+ * is page `heartbeat`. When no file is spelled exactly `<slug>.md`, the slug's+ * directory chain is read case-insensitively per segment (ordinary directories+ * and `.md`/`.mdx` files only, never symlinks) for files a scan maps to this+ * slug, and the result is the on-disk spelling, on case-insensitive filesystems+ * too. One match is the origin; several refuse `source_changed` with detail+ * `slug_path_ambiguous`, naming each; none keeps the expected path (the caller+ * reports it missing).*/export function slugDerivedOrigin(root: string, slug: string, mode: 'git-root' | 'source-root'): { path: string; sourcePath: string } | null {const path = resolveSourceLocalFilePath(root, `${slug}.md`, slug, mode);if (!path) return null;const sourcePath = scannerSourcePath(root, path, mode);- return resolveSlugForPath(sourcePath) === slug ? { path, sourcePath } : null;+ if (resolveSlugForPath(sourcePath) !== slug) return null;+ const base = resolve(root), segments = relative(base, path).split(sep);+ if (segments[0] === '..' || isAbsolute(segments.join(sep))) return { path, sourcePath };+ let dirs = [base];+ for (const segment of segments.slice(0, -1)) {+ dirs = dirs.flatMap(dir => entries(dir).filter(entry => entry.isDirectory() && entry.name.toLowerCase() === segment.toLowerCase()).map(entry => join(dir, entry.name)));+ }+ const files = dirs.flatMap(dir => entries(dir).filter(entry => entry.isFile() && /\.mdx?$/i.test(entry.name)).map(entry => join(dir, entry.name)));+ if (files.includes(path)) return { path, sourcePath };+ const matches = files.map(file => ({ path: file, sourcePath: scannerSourcePath(root, file, mode) })).filter(file => resolveSlugForPath(file.sourcePath) === slug);+ if (matches.length > 1) {+ throw opError('source_changed', `Several files map to page ${slug}; none is spelled exactly ${basename(path)}.`,+ `Files ${matches.map(file => file.sourcePath).join(', ')} all import as ${slug}, so none can be adopted as its canonical file and nothing changed. `+ + 'Ask the user which one is the page\'s file; rename or remove the others, commit, then preview again.', { detail: 'slug_path_ambiguous' });+ }+ return matches[0] ?? { path, sourcePath };+}++function entries(dir: string): Dirent[] {+ try { return readdirSync(dir, { withFileTypes: true }); } catch { return []; }}diff --git a/test/reconcile-unbound-collision.test.ts b/test/reconcile-unbound-collision.test.tsindex 204f4dc585..88530bd2aa 100644--- a/test/reconcile-unbound-collision.test.ts+++ b/test/reconcile-unbound-collision.test.ts@@ -9,7 +9,7 @@import { afterAll, beforeAll, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -221,3 +221,39 @@ test('reconcile of a marked page with a recorded origin clears the unbound_sourc}});}, 180_000);++// #6670: the canonical file differs from the slug only by case (HEARTBEAT.md is page heartbeat on import).+test('a marked page adopts a file whose name differs from its slug only by case, and records the on-disk spelling', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ const f = await collision(engine);+ const cased = join(f.file, '..', 'Example.md');+ renameSync(f.file, cased);+ await withVerifiedLocalRegistration(engine, f.registration, async () => {+ const preview = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug });+ expect(preview.relative_path).toBe('notes/Example.md');+ const resolved = await runReconcilePreview(engine, { source_id: f.id, slug: f.slug, from: preview.preview,+ decisions: (preview.conflict_paths as string[]).map(path => ({ path, action: 'take_database' })) });+ const receipt = await runReconcileApply(engine, { source_id: f.id, slug: f.slug, preview: resolved.preview, request_id: randomUUID() });+ expect(receipt.state).toBe('committed');+ const [page] = await engine.executeRaw<{ source_path: string | null }>('SELECT source_path FROM pages WHERE source_id=$1 AND slug=$2', [f.id, f.slug]);+ expect(page!.source_path).toBe('notes/Example.md');+ expect(readFileSync(cased, 'utf8')).toContain('no canonical owner');+ });+ }+ });+}, 180_000);++test('two case variants and no exact spelling refuse slug_path_ambiguous and change nothing', async () => {+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {+ for (const engine of engines) {+ const f = await collision(engine);+ renameSync(f.file, join(f.file, '..', 'Example.md'));+ writeFileSync(join(f.file, '..', 'EXAMPLE.md'), fileSide);+ await withVerifiedLocalRegistration(engine, f.registration, async () => {+ await expect(runReconcilePreview(engine, { source_id: f.id, slug: f.slug })).rejects.toMatchObject({ code: 'source_changed', detail: 'slug_path_ambiguous' });+ });+ expect(readFileSync(join(f.file, '..', 'EXAMPLE.md'), 'utf8')).toBe(fileSide);+ }+ });+}, 180_000);diff --git a/test/unbound-pages-6670.test.ts b/test/unbound-pages-6670.test.tsnew file mode 100644index 0000000000..c29cff8ac8--- /dev/null+++ b/test/unbound-pages-6670.test.ts@@ -0,0 +1,47 @@+/**+ * #6670: `slugDerivedOrigin` only built `<slug>.md`, so a page whose file is+ * `HEARTBEAT.md` (the importer lowercases it into page `heartbeat`) pointed at+ * a file that does not exist on a case-sensitive filesystem, and+ * `sources reconcile --adopt-slug-path` refused it as missing. The lookup now+ * reads the slug's directory chain case-insensitively and returns the on-disk+ * spelling.+ */+import { afterAll, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { slugDerivedOrigin } from '../src/core/persistence/unbound-pages.ts';++const dirs: string[] = [];+afterAll(() => { for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); });+function root(files: string[]): string {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-6670-'))); dirs.push(dir);+ for (const file of files) { mkdirSync(join(dir, file, '..'), { recursive: true }); writeFileSync(join(dir, file), '# Heartbeat\n'); }+ return dir;+}++test('a file that differs from its slug only by case is the origin, with its on-disk spelling', () => {+ const dir = root(['HEARTBEAT.md', 'Notes/Daily/Standup.md']);+ expect(slugDerivedOrigin(dir, 'heartbeat', 'source-root')).toEqual({ path: join(dir, 'HEARTBEAT.md'), sourcePath: 'HEARTBEAT.md' });+ expect(slugDerivedOrigin(dir, 'notes/daily/standup', 'source-root')).toEqual({ path: join(dir, 'Notes/Daily/Standup.md'), sourcePath: 'Notes/Daily/Standup.md' });+});++test('an exactly spelled file wins over a case variant, as the importer keeps <slug>.md on a collision', () => {+ const dir = root(['heartbeat.md', 'HEARTBEAT.md']);+ expect(slugDerivedOrigin(dir, 'heartbeat', 'source-root')).toEqual({ path: join(dir, 'heartbeat.md'), sourcePath: 'heartbeat.md' });+});++test('several case variants and no exact spelling refuse slug_path_ambiguous naming each', () => {+ const dir = root(['HEARTBEAT.md', 'Heartbeat.md']);+ let error: { code?: string; detail?: string; suggestion?: string } | undefined;+ try { slugDerivedOrigin(dir, 'heartbeat', 'source-root'); } catch (caught) { error = caught as typeof error; }+ expect(error).toMatchObject({ code: 'source_changed', detail: 'slug_path_ambiguous' });+ expect(error!.suggestion).toContain('HEARTBEAT.md');+ expect(error!.suggestion).toContain('Heartbeat.md');+});++test('no match keeps the expected path, and a symlink is never adopted', () => {+ const dir = root(['other.md']);+ symlinkSync(join(dir, 'other.md'), join(dir, 'HEARTBEAT.md'));+ expect(slugDerivedOrigin(dir, 'heartbeat', 'source-root')).toEqual({ path: join(dir, 'heartbeat.md'), sourcePath: 'heartbeat.md' });+});