Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): multi_source_drift checks git-root-pinned sources from their git toplevel (#6060)
time-attack0abf5e69d9ba
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 33a835f684..63e36a0356 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -62,7 +62,7 @@| Check | What it could not read | Fix || --- | --- | --- |-| `multi_source_drift` | a source's `local_path` root or a directory below it (`details.unreadable_sources`), or the walk hit its bound (`details.limit` files / `details.timeout_ms`) | fix the path or permissions (`gbrain sources status`); for a large source re-run with `GBRAIN_DRIFT_LIMIT=<files> GBRAIN_DRIFT_TIMEOUT_MS=<ms> gbrain doctor` |+| `multi_source_drift` | a source's `local_path` root or a directory below it (`details.unreadable_sources`), the walk hit its bound (`details.limit` files / `details.timeout_ms`), or the git toplevel of a source pinned to git-root slugs could not be resolved (`details.git_root_skipped`) | fix the path or permissions (`gbrain sources status`); for a large source re-run with `GBRAIN_DRIFT_LIMIT=<files> GBRAIN_DRIFT_TIMEOUT_MS=<ms> gbrain doctor`; for a git-root source, make its `local_path` a git checkout that `git` can read || `embed_staleness` | the stale-chunk count (the embed worker's own predicate) | the reason names the database error; re-run `gbrain doctor` once it is fixed || `schema_pack_consistency`, `schema_pack_source_drift` | the pages or config query, or a source's active schema pack | `gbrain schema lint --with-db` runs the same classification locally; `gbrain schema active` debugs pack resolution |diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.tsindex 56dc705942..0c21e3b80c 100644--- a/src/commands/doctor/schema-pack-checks.ts+++ b/src/commands/doctor/schema-pack-checks.ts@@ -213,18 +213,17 @@ export function multiSourceDriftAdvice(count: number, sampleStr: string, managed}/**- * #4712 — note appended when one or more sources were excluded from the- * multi_source_drift walk because they're pinned to slug_root_mode='git-root'- * (#4342). The check only derives local_path-relative ('source-root')- * slugs; comparing a git-root-pinned source against that shape produced- * false-positive drift (and dangerous delete advice naming an unrelated- * default page). Skipped, not mismatched — this is disclosure of reduced- * coverage, not a problem to fix.+ * Note appended when one or more sources were excluded from the+ * multi_source_drift walk: pinned to slug_root_mode='git-root' (#4342) with a+ * local_path whose git toplevel could not be resolved, so the git-root prefix+ * their slugs carry cannot be derived. Comparing them against+ * local_path-relative slugs would produce false-positive drift (and delete+ * advice naming an unrelated default page). Skipped, not mismatched.*/export function multiSourceDriftGitRootSkipNote(skippedIds: string[]): string {return (- ` ${skippedIds.length} source(s) not checked (git-root-pinned, prefix-aware ` +- `matching not yet implemented — #4712): ${skippedIds.join(', ')}.`+ ` ${skippedIds.length} source(s) not checked (pinned to git-root slugs, but the git toplevel ` ++ `of local_path could not be resolved, so their slug prefix cannot be derived): ${skippedIds.join(', ')}.`);}@@ -232,9 +231,9 @@ const DRIFT_DOCS = 'docs/guides/troubleshooting.md#not-verified-doctor-checks';/*** #5432: one multi_source_drift verdict for the local and remote doctor. A- * truncated walk or an unreadable source root/subdirectory is "not- * verified" (warn), never "no drift"; the walk bounds and unreadable sources- * ride in details.+ * truncated walk, an unreadable source root/subdirectory or a skipped+ * git-root source is "not verified" (warn), never "no drift"; the walk+ * bounds, unreadable and skipped sources ride in details.*/export function multiSourceDriftCheck(result: MisroutedResult,@@ -286,23 +285,21 @@ export function multiSourceDriftCheck(details: { ...details, code: 'not_verified', verified: false },};}- // #4712: if EVERY candidate source was skipped as git-root-pinned, no walk- // ran — 'ok' would misreport "verified clean" when nothing was checked.- const allSkipped = result.git_root_skipped.length > 0 && result.git_root_skipped.length >= candidateSources;- if (allSkipped) {+ // A skipped source (git-root-pinned, git toplevel unresolvable) was not+ // verified, so 'ok' would misreport "verified clean"; when EVERY candidate+ // was skipped, no source was checked at all.+ if (result.git_root_skipped.length > 0) {+ const allSkipped = result.git_root_skipped.length >= candidateSources;return {name: 'multi_source_drift',status: 'warn',- message: `Multi-source drift check performed no verification${skipNote}`,+ message: allSkipped+ ? `Multi-source drift check performed no verification${skipNote}`+ : `No cross-source slug drift among checked sources.${skipNote}`,details: { ...details, code: 'not_verified', verified: false },};}- return {- name: 'multi_source_drift',- status: 'ok',- message: skipNote ? `No cross-source slug drift detected among checked sources.${skipNote}` : 'No cross-source slug drift detected.',- details,- };+ return { name: 'multi_source_drift', status: 'ok', message: 'No cross-source slug drift detected.', details };}/** #5432: the drift check itself failed (e.g. the sources query); report it instead of dropping the check. */diff --git a/src/core/multi-source-drift.ts b/src/core/multi-source-drift.tsindex 7e691496af..28969a3e34 100644--- a/src/core/multi-source-drift.ts+++ b/src/core/multi-source-drift.ts@@ -30,23 +30,24 @@* yields zero files, NOT a thrown crash that takes down the whole doctor* run; the source is reported in `unreadable_sources` (#5432) so doctor* says "not verified" instead of "no drift".- * - #4712: the slug derivation below is `local_path`-relative only, which- * is the `'source-root'` slug-root shape (#4342, src/core/sync-anchor.ts).- * A source pinned to `'git-root'` mode produces slugs prefixed with its- * subdir under the repo root instead — this module has no git-root- * discovery of its own, so it CANNOT compute the slug sync actually- * produces for such a source. Rather than compare against the wrong- * slug (false-positive drift, with delete advice naming an unrelated- * page), a git-root-pinned source is skipped entirely and reported via- * `git_root_skipped`. True prefix-aware matching is tracked as a- * follow-up, not attempted here.+ * - Slug shape follows the source's slug-root pin (#4342, src/core/sync-anchor.ts).+ * Unpinned and `'source-root'` sources get `local_path`-relative slugs.+ * A `'git-root'` pin means sync minted slugs from the git-root-relative+ * path, so the walk's paths are prefixed with `local_path`'s subdir under+ * the git toplevel. That prefix is empty when `local_path` IS the+ * toplevel, which is what managed sync pins for a source at its repo root.+ * Comparing against the wrong shape would false-positive (with delete+ * advice naming an unrelated page), so a git-root-pinned source whose git+ * toplevel cannot be resolved is skipped and reported via+ * `git_root_skipped` instead.*/-import { readdirSync, lstatSync, statSync } from 'fs';+import { readdirSync, lstatSync, statSync, realpathSync } from 'fs';import { join, relative } from 'path';import type { BrainEngine } from './engine.ts';import { pathToSlug } from './sync.ts';import { readSlugRootMode } from './sync-anchor.ts';+import { discoverGitRoot, gitRelativePath, isWithinRoot } from './sync-git.ts';export interface SourceWithPath {id: string;@@ -66,10 +67,10 @@ export interface MisroutedResult {count: number;sample: MisroutedSample[];/**- * #4712: source IDs skipped because their persisted slug_root_mode is- * 'git-root' — this check only knows how to derive 'source-root'-shaped- * (local_path-relative) slugs, so a git-root-pinned source is excluded- * rather than checked against the wrong slug shape.+ * Source IDs pinned to slug_root_mode 'git-root' whose local_path is readable+ * but whose git toplevel cannot be resolved: the git-root prefix sync used+ * cannot be derived, so the source is excluded rather than checked against+ * the wrong slug shape.*/git_root_skipped: string[];/**@@ -208,6 +209,28 @@ async function batchProbeExistence(return map;}+/**+ * The git-root-relative scope of `localPath`, '/'-separated and '' when it IS+ * the toplevel, from the realpaths of both ends as managed sync computes it+ * (src/core/persistence/sync-discovery.ts). null when the git toplevel of+ * `localPath` cannot be resolved (not a repository, git missing or refusing+ * the directory), so the caller reports the source instead of guessing a+ * slug shape.+ */+function gitRootScope(localPath: string): string | null {+ let gitRoot: string;+ let root: string;+ try {+ gitRoot = realpathSync.native(discoverGitRoot(localPath));+ root = realpathSync.native(localPath);+ } catch {+ // discoverGitRoot rethrows every git failure as one error: the caller+ // reports the source in git_root_skipped, so doctor says it was not checked.+ return null;+ }+ return isWithinRoot(root, gitRoot) ? gitRelativePath(gitRoot, root) : null;+}+/*** Find pages that appear misrouted from intended source X to source 'default'.* For each non-default source with a configured local_path, walk the@@ -238,23 +261,27 @@ export async function findMisroutedPages(walkTruncated = true;break;}- // #4712: local_path-relative slugs are only correct for 'source-root'-- // pinned sources. A 'git-root' pin means sync produces subdir-prefixed- // slugs this module doesn't know how to reconstruct — skip rather than- // compare against a slug shape that will never match.- const rootMode = await readSlugRootMode(engine, src.id);- if (rootMode === 'git-root') {- gitRootSkipped.push(src.id);- continue;- }const { files, truncated, rootUnreadable, unreadableDirs } = walkMarkdownAndMdxFiles(src.local_path, limit, deadlineMs);if (truncated) walkTruncated = true;if (rootUnreadable) unreadable.push({ source_id: src.id, reason: 'root_unreadable', dirs: 1 });else if (unreadableDirs > 0) unreadable.push({ source_id: src.id, reason: 'subdirs_unreadable', dirs: unreadableDirs });if (files.length === 0) continue;+ // A 'git-root' pin prefixes the walk's paths with local_path's subdir+ // under the git toplevel ('' at the toplevel); see the header. Resolved+ // after the walk, so an unreadable local_path reports as root_unreadable.+ let gitScope = '';+ if (await readSlugRootMode(engine, src.id) === 'git-root') {+ const scope = gitRootScope(src.local_path);+ if (scope === null) {+ gitRootSkipped.push(src.id);+ continue;+ }+ gitScope = scope;+ }+// Convert FS paths to canonical slugs (lowercased, extension stripped).- const slugs = Array.from(new Set(files.map(f => pathToSlug(f.relPath))));+ const slugs = Array.from(new Set(files.map(f => pathToSlug(gitScope ? `${gitScope}/${f.relPath}` : f.relPath))));const existenceMap = await batchProbeExistence(engine, slugs, src.id);for (const slug of slugs) {diff --git a/test/multi-source-drift.test.ts b/test/multi-source-drift.test.tsindex 7ae41cc4d9..4935087822 100644--- a/test/multi-source-drift.test.ts+++ b/test/multi-source-drift.test.ts@@ -17,13 +17,15 @@*/import { describe, test, expect, beforeAll, afterAll } from 'bun:test';-import { mkdirSync, rmSync, writeFileSync } from 'fs';+import { mkdirSync, rmSync, symlinkSync, writeFileSync } from 'fs';+import { execFileSync } from 'child_process';import { join } from 'path';import { tmpdir } from 'os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runSources } from '../src/commands/sources.ts';import { findMisroutedPages } from '../src/core/multi-source-drift.ts';import { writeSlugRootMode } from '../src/core/sync-anchor.ts';+import { multiSourceDriftCheck } from '../src/commands/doctor/schema-pack-checks.ts';let engine: PGLiteEngine;const TMP_ROOTS: string[] = [];@@ -173,7 +175,8 @@ describe('findMisroutedPages — heuristic correctness', () => {expect(result.sample[0].slug).toBe('topics/mdx-page');});- test('case 8 (#4712): a git-root-pinned source is skipped, not false-positived', async () => {+ test('case 8 (#4712, #5862): a git-root-pinned source outside any git repository is skipped, and doctor says why', async () => {+ // Not a git repository: the git-root prefix sync used cannot be derived.const root = makeTmpRoot('case8');seedFile(root, 'page.md');@@ -194,6 +197,43 @@ describe('findMisroutedPages — heuristic correctness', () => {expect(result.count).toBe(0);expect(result.sample).toEqual([]);expect(result.git_root_skipped).toEqual(['src-case8']);+ const check = multiSourceDriftCheck(result, 1, 'local');+ expect(check).toMatchObject({ status: 'warn', details: { code: 'not_verified', verified: false } });+ expect(check.message).toContain('git toplevel of local_path could not be resolved');+ expect(check.message).not.toContain('#4712');+ });++ test('case 8b (#5862): a skipped git-root source keeps doctor at not verified when a sibling is checked clean', async () => {+ const skippedRoot = makeTmpRoot('case8b-skipped');+ seedFile(skippedRoot, 'page.md');+ await runSources(engine, ['add', 'src-case8b-gr', '--no-federated']);+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = $2`, [skippedRoot, 'src-case8b-gr']);+ await writeSlugRootMode(engine, 'src-case8b-gr', 'git-root');+ const cleanRoot = makeTmpRoot('case8b-clean');+ seedFile(cleanRoot, 'topics/clean.md');+ await runSources(engine, ['add', 'src-case8b-sr', '--no-federated']);+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = $2`, [cleanRoot, 'src-case8b-sr']);++ const result = await findMisroutedPages(engine, [+ { id: 'src-case8b-gr', local_path: skippedRoot },+ { id: 'src-case8b-sr', local_path: cleanRoot },+ ]);+ expect(result).toMatchObject({ count: 0, git_root_skipped: ['src-case8b-gr'], unreadable_sources: [] });+ const check = multiSourceDriftCheck(result, 2, 'local');+ expect(check).toMatchObject({ status: 'warn', details: { code: 'not_verified', verified: false } });+ expect(check.message).toStartWith('No cross-source slug drift among checked sources.');+ expect(check.message).toContain('src-case8b-gr');+ });++ test('case 8c (#5862): a git-root source whose local_path is missing reports root_unreadable, not a git-root skip', async () => {+ await runSources(engine, ['add', 'src-case8c', '--no-federated']);+ const missing = join(makeTmpRoot('case8c'), 'gone');+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = $2`, [missing, 'src-case8c']);+ await writeSlugRootMode(engine, 'src-case8c', 'git-root');++ const result = await findMisroutedPages(engine, [{ id: 'src-case8c', local_path: missing }]);+ expect(result.git_root_skipped).toEqual([]);+ expect(result.unreadable_sources).toEqual([{ source_id: 'src-case8c', reason: 'root_unreadable', dirs: 1 }]);});test('case 9 (#4712): git-root skip does not mask real drift on a sibling source-root source', async () => {@@ -220,4 +260,42 @@ describe('findMisroutedPages — heuristic correctness', () => {expect(result.sample[0]).toMatchObject({ slug: 'people/eve', intended_source: 'src-case9-sr' });expect(result.git_root_skipped).toEqual(['src-case9-gr']);});++ // #5862: inside a git repository every pin is checkable. A 'git-root' pin+ // means sync minted slugs from the git-root-relative path: no prefix when+ // local_path is the repo root (what managed sync pins there), the subdir+ // in slug spelling otherwise. Each row seeds a healthy page at the source,+ // a misrouted one at default, and an unrelated default page at the+ // local_path-relative slug that only the wrong slug shape would flag.+ const GIT_REPO_CASES: Array<{ label: string; scope: string; pin: 'git-root' | 'source-root' | null; slugPrefix: string; viaSymlink?: boolean }> = [+ { label: 'unpinned source at the repo root', scope: '', pin: null, slugPrefix: '' },+ { label: 'git-root source at the repo root (empty prefix)', scope: '', pin: 'git-root', slugPrefix: '' },+ { label: 'git-root source in a subdir (prefixed slugs)', scope: 'Team Notes', pin: 'git-root', slugPrefix: 'team-notes/' },+ { label: 'git-root source whose local_path is a symlink into a subdir', scope: 'Team Notes', pin: 'git-root', slugPrefix: 'team-notes/', viaSymlink: true },+ { label: 'source-root source in a subdir', scope: 'Team Notes', pin: 'source-root', slugPrefix: '' },+ ];+ for (const [i, c] of GIT_REPO_CASES.entries()) {+ test(`case 10.${i} (#5862): ${c.label}: misroute detected, no false positive`, async () => {+ const repo = makeTmpRoot(`case10-${i}`);+ execFileSync('git', ['-C', repo, 'init', '-q'], { stdio: 'pipe' });+ const root = c.scope ? join(repo, c.scope) : repo;+ seedFile(root, 'people/alice.md');+ seedFile(root, 'people/bob.md');+ // Sync derives the prefix from the realpath, so a symlinked local_path must too.+ const localPath = c.viaSymlink ? join(makeTmpRoot(`case10-${i}-link`), 'link') : root;+ if (c.viaSymlink) symlinkSync(root, localPath);+ const id = `src-case10-${i}`;+ await runSources(engine, ['add', id, '--no-federated']);+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = $2`, [localPath, id]);+ if (c.pin) await writeSlugRootMode(engine, id, c.pin);+ await engine.putPage(`${c.slugPrefix}people/alice`, { type: 'person', title: 'Alice', compiled_truth: '.' }, { sourceId: id });+ await engine.putPage('people/alice', { type: 'person', title: 'Unrelated', compiled_truth: '.' });+ await engine.putPage(`${c.slugPrefix}people/bob`, { type: 'person', title: 'Bob', compiled_truth: '.' });++ const result = await findMisroutedPages(engine, [{ id, local_path: localPath }]);+ expect(result.git_root_skipped).toEqual([]);+ expect(result.count).toBe(1);+ expect(result.sample).toEqual([{ slug: `${c.slugPrefix}people/bob`, intended_source: id, local_path: localPath }]);+ });+ }});