Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): multi_source_drift skips git-root-pinned sources instead of false-positiving (#4725)
Masab2f5ab89d51e
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 74bb5d1a1e..babc1cfcfd 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -5,7 +5,7 @@# Columns: path max_lines policy notesrc/cli.ts 4002 ratchet grown v0.46.26.0 megawave: SIGCHLD reaper install, silent-failure surfacing, confirm-race gate (#2443 #2898 #2297); grown wave-g (#4488 #4508): in-band error exit codes + think --source validation; grown db-availability loop: engine/db-repair dispatch, degraded-serve catch, marker choke points (bottom handler + no-config exit + doctor fallback), engine-free config-set dispatch; fix cycle: static classifier imports, resolved-brain degraded gate, guarded reconnect, help rows; +chat-connectors wiring (master merge); wave-k +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +master-merge true-up; +20 gbrain backup pre-engine dispatch + startup backup nag rail (monthly backup check); wave-k: +24 for #4083 auth self-help entry + top-level auth usage lines + takes self-help branch; +3: doctor --no-migrate probeOnly seam (#4364); +37 v0.47 gmail-loops: google/creds dispatch + waiting/loops cases + self-help entries + OPEN LOOPS help sectionsrc/commands/autopilot.ts 2648 ratchet grown v0.46.26.0 megawave (#4300 #4285 #3696) + master v0.46.27.0 env-file lane + boot warning + reload-safe install (#2608 #4443) + 1 nosemgrep dataflow annotation (path-traversal audit); +chat-connectors wiring-src/commands/doctor.ts 4593 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch+src/commands/doctor.ts 4610 ratchet grown v0.46.26.0 megawave: silent-death checks, self-upgrade honesty, noise pruning (#3944 #3925 #3958); +21 lines (#4518: don't assert "supervisor not running" when the --fast mode DB-lock fallback was never attempted); +12 lines (#2036/#4484: schema_version warns on forward DB skew); +12 lines (#4476: oversized_pages excludes embed_skip pages via canonical EMBED_SKIP_FILTER_FRAGMENT); merged wave-g-prs (#4421 #4425 #4517 #4519): one in-branch live-column diff on detectMissingColumns + engine-aware superseded upgrade-error suppression (explicit ok); grown db-availability loop: classified connection check + synthesized total-outage entry + hoisted pgbouncer helper + engine-fit check wiring + report engine/db_url_source fields; +chat-connectors wiring (master merge); +12 lines (#2036/#4484: schema_version warns on forward DB skew via schemaVersionHealth); merged wave-g-prs (#4421 #4425 #4517 #4519): in-branch live-column diff + engine-aware superseded upgrade-error suppression; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +7 backup_coverage check registration (monthly backup check); +master-merge true-up; wave-k: schema_columns emitted as its own check inside the ledger-current branch (gbrain#4421), schema_version via schemaVersionHealth module, conversation_format_coverage peeled to doctor/checks/conversation-coverage.ts (#4193); +9 v0.47 gmail-loops: google_oauth vault-health check dispatch; +17 (#4712: git-root-pinned source skip note wiring + all-skipped warn-not-ok status for multi_source_drift)src/commands/embed.ts 2147 ratchet lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment)src/commands/extract-conversation-facts.ts 2100 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption)src/commands/extract.ts 2458 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pickdiff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex 555ab5b3c3..55af4a3094 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -28,7 +28,7 @@ import { zeroTotalContradictionsCheck } from '../core/eval-contradictions/run-he// original name so existing importers (tests, scripts/live-brain-first-check.ts,// the run_doctor op's dynamic import of doctorReportRemote) keep working// unchanged.-import { multiSourceDriftAdvice } from './doctor/schema-pack-checks.ts';+import { multiSourceDriftAdvice, multiSourceDriftGitRootSkipNote } from './doctor/schema-pack-checks.ts';import { bootstrapDoctorChecks } from './doctor/bootstrap-checks.ts';import {skillConformanceCheck,@@ -39,6 +39,7 @@ import {} from './doctor/skill-checks.ts';export {multiSourceDriftAdvice,+ multiSourceDriftGitRootSkipNote,bootstrapDoctorChecks,skillConformanceCheck,skillsManifestIntegrityCheck,@@ -1700,16 +1701,32 @@ export async function buildChecks(});} else if (result.count > 0) {const sampleStr = result.sample.map(s => `${s.slug} (intended=${s.intended_source})`).join(', ');+ const skipNote = result.git_root_skipped.length > 0+ ? multiSourceDriftGitRootSkipNote(result.git_root_skipped)+ : '';checks.push({name: 'multi_source_drift',status: 'warn',- message: multiSourceDriftAdvice(result.count, sampleStr),+ message: multiSourceDriftAdvice(result.count, sampleStr) + skipNote,});} else {+ // #4712: if EVERY candidate source was skipped as git-root-pinned,+ // no walk actually ran — 'ok' would misreport "verified clean" when+ // nothing was checked at all. 'warn' only in that all-skipped case;+ // a partial skip alongside real, clean coverage stays 'ok'.+ const allSkipped =+ result.git_root_skipped.length > 0 &&+ result.git_root_skipped.length >= nonDefaultWithPath.length;checks.push({name: 'multi_source_drift',- status: 'ok',- message: 'No cross-source slug drift detected.',+ status: allSkipped ? 'warn' : 'ok',+ message: allSkipped+ ? `Multi-source drift check performed no verification` ++ multiSourceDriftGitRootSkipNote(result.git_root_skipped)+ : result.git_root_skipped.length > 0+ ? `No cross-source slug drift detected among checked sources.` ++ multiSourceDriftGitRootSkipNote(result.git_root_skipped)+ : 'No cross-source slug drift detected.',});}}diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex 81bd5fa138..4653a3f345 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -50,6 +50,7 @@ import {checkLinkResolutionOpportunity,checkFederationHealth,checkSelfUpgradeHealth,+ multiSourceDriftGitRootSkipNote,} from '../doctor.ts';import {checkSchemaPackActive,@@ -288,19 +289,35 @@ export async function doctorReportRemote(});} else if (result.count > 0) {const sampleStr = result.sample.map(s => `${s.slug} (intended=${s.intended_source})`).join(', ');+ const skipNote = result.git_root_skipped.length > 0+ ? multiSourceDriftGitRootSkipNote(result.git_root_skipped)+ : '';checks.push({name: 'multi_source_drift',status: 'warn',message:`${result.count} page slug(s) appear at 'default' but NOT at the intended source ` +`(e.g., ${sampleStr}). Likely pre-v0.30.3 misroutes OR an incomplete initial sync. ` +- `Verify on the brain host: \`gbrain sources status\` then \`gbrain sync --source <id> --full\`.`,+ `Verify on the brain host: \`gbrain sources status\` then \`gbrain sync --source <id> --full\`.` ++ skipNote,});} else {+ // #4712: see the local doctor's twin check — 'ok' would misreport+ // "verified clean" if every candidate source was skipped and no+ // walk actually ran.+ const allSkipped =+ result.git_root_skipped.length > 0 &&+ result.git_root_skipped.length >= nonDefaultWithPath.length;checks.push({name: 'multi_source_drift',- status: 'ok',- message: 'No cross-source slug drift detected.',+ status: allSkipped ? 'warn' : 'ok',+ message: allSkipped+ ? `Multi-source drift check performed no verification` ++ multiSourceDriftGitRootSkipNote(result.git_root_skipped)+ : result.git_root_skipped.length > 0+ ? `No cross-source slug drift detected among checked sources.` ++ multiSourceDriftGitRootSkipNote(result.git_root_skipped)+ : 'No cross-source slug drift detected.',});}}diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.tsindex ad76d42f96..61908d9bba 100644--- a/src/commands/doctor/schema-pack-checks.ts+++ b/src/commands/doctor/schema-pack-checks.ts@@ -156,3 +156,19 @@ export function multiSourceDriftAdvice(count: number, sampleStr: string): string`so pin it to 'default' explicitly.`);}++/**+ * #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.+ */+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(', ')}.`+ );+}diff --git a/src/core/multi-source-drift.ts b/src/core/multi-source-drift.tsindex e01f34ec4e..805e88e60b 100644--- a/src/core/multi-source-drift.ts+++ b/src/core/multi-source-drift.ts@@ -29,12 +29,23 @@* - Wrapper try/catch around the walk per OV13: ENOENT/EACCES on local_path* yields zero files, NOT a thrown crash that takes down the whole doctor* run.+ * - #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.*/import { readdirSync, lstatSync, statSync } from 'fs';import { join, relative } from 'path';import type { BrainEngine } from './engine.ts';import { pathToSlug } from './sync.ts';+import { readSlugRootMode } from './sync-anchor.ts';export interface SourceWithPath {id: string;@@ -53,6 +64,13 @@ export interface MisroutedResult {/** Per-source breakdown: slugs that appear at (default, slug) but NOT at (X, slug). */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.+ */+ git_root_skipped: string[];}const DEFAULT_FILE_LIMIT = 10_000;@@ -192,6 +210,7 @@ export async function findMisroutedPages(let totalCount = 0;let walkTruncated = false;const sample: MisroutedSample[] = [];+ const gitRootSkipped: string[] = [];for (const src of sources) {if (src.id === 'default') continue;@@ -200,6 +219,15 @@ 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 } = walkMarkdownAndMdxFiles(src.local_path, limit, deadlineMs);if (truncated) walkTruncated = true;if (files.length === 0) continue;@@ -223,5 +251,5 @@ export async function findMisroutedPages(}}- return { walk_truncated: walkTruncated, count: totalCount, sample };+ return { walk_truncated: walkTruncated, count: totalCount, sample, git_root_skipped: gitRootSkipped };}diff --git a/test/multi-source-drift.test.ts b/test/multi-source-drift.test.tsindex 1d9591ba76..7ae41cc4d9 100644--- a/test/multi-source-drift.test.ts+++ b/test/multi-source-drift.test.ts@@ -23,6 +23,7 @@ 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';let engine: PGLiteEngine;const TMP_ROOTS: string[] = [];@@ -171,4 +172,52 @@ describe('findMisroutedPages — heuristic correctness', () => {expect(result.count).toBe(1);expect(result.sample[0].slug).toBe('topics/mdx-page');});++ test('case 8 (#4712): a git-root-pinned source is skipped, not false-positived', async () => {+ const root = makeTmpRoot('case8');+ seedFile(root, 'page.md');++ await runSources(engine, ['add', 'src-case8', '--no-federated']);+ await engine.executeRaw(+ `UPDATE sources SET local_path = $1 WHERE id = $2`,+ [root, 'src-case8'],+ );+ await writeSlugRootMode(engine, 'src-case8', 'git-root');+ // Sync actually produced the git-root-prefixed slug (what import.ts's+ // importRelPath would derive) — NOT local_path-relative 'page'.+ await engine.putPage('src-case8/page', { type: 'concept', title: 'p', compiled_truth: '.' }, { sourceId: 'src-case8' });+ // An unrelated page legitimately owns the local_path-relative slug at+ // default — this is exactly the #4712 false-positive shape pre-fix.+ await engine.putPage('page', { type: 'concept', title: 'unrelated', compiled_truth: '.' });++ const result = await findMisroutedPages(engine, [{ id: 'src-case8', local_path: root }]);+ expect(result.count).toBe(0);+ expect(result.sample).toEqual([]);+ expect(result.git_root_skipped).toEqual(['src-case8']);+ });++ test('case 9 (#4712): git-root skip does not mask real drift on a sibling source-root source', async () => {+ const gitRootRoot = makeTmpRoot('case9-gitroot');+ seedFile(gitRootRoot, 'page.md');+ await runSources(engine, ['add', 'src-case9-gr', '--no-federated']);+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = $2`, [gitRootRoot, 'src-case9-gr']);+ await writeSlugRootMode(engine, 'src-case9-gr', 'git-root');+ await engine.putPage('src-case9-gr/page', { type: 'concept', title: 'p', compiled_truth: '.' }, { sourceId: 'src-case9-gr' });+ await engine.putPage('page', { type: 'concept', title: 'unrelated', compiled_truth: '.' });++ const sourceRootRoot = makeTmpRoot('case9-srcroot');+ seedFile(sourceRootRoot, 'people/eve.md');+ await runSources(engine, ['add', 'src-case9-sr', '--no-federated']);+ await engine.executeRaw(`UPDATE sources SET local_path = $1 WHERE id = $2`, [sourceRootRoot, 'src-case9-sr']);+ // Genuine misroute: exists at default, missing from the intended source.+ await engine.putPage('people/eve', { type: 'person', title: 'Eve', compiled_truth: '.' });++ const result = await findMisroutedPages(engine, [+ { id: 'src-case9-gr', local_path: gitRootRoot },+ { id: 'src-case9-sr', local_path: sourceRootRoot },+ ]);+ expect(result.count).toBe(1);+ expect(result.sample[0]).toMatchObject({ slug: 'people/eve', intended_source: 'src-case9-sr' });+ expect(result.git_root_skipped).toEqual(['src-case9-gr']);+ });});