Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): multi_source_drift stopped at its walk bound reports health unknown naming the bound (#7145)
garrytan4ff4a115ba16
diff --git a/src/commands/doctor/bounded-unknown.ts b/src/commands/doctor/bounded-unknown.tsnew file mode 100644index 0000000000..c45f2a14f9--- /dev/null+++ b/src/commands/doctor/bounded-unknown.ts@@ -0,0 +1,11 @@+/**+ * #7145: a check that stopped at one of its own bounds (a file-walk limit, a+ * row cap, a scan timeout) did not see everything, so its health is unknown:+ * never clear, and never a known problem. Same shape as the runner's budget+ * unknowns in ./budget.ts (`status: 'warn'`, `details.health: 'unknown'`,+ * `details.exact: false`), with `reason: 'bound'` and `bound` naming which+ * bound stopped it; each check keeps its own limit fields beside it.+ */+export function boundUnknownDetails(bound: string): { health: 'unknown'; reason: 'bound'; bound: string; exact: false } {+ return { health: 'unknown', reason: 'bound', bound, exact: false };+}diff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.tsindex 6cb68542a8..38e8d8cf2a 100644--- a/src/commands/doctor/schema-pack-checks.ts+++ b/src/commands/doctor/schema-pack-checks.ts@@ -6,6 +6,7 @@import type { BrainEngine } from '../../core/engine.ts';import type { Check } from '../doctor.ts';import type { MisroutedResult } from '../../core/multi-source-drift.ts';+import { boundUnknownDetails } from './bounded-unknown.ts';import { statSync } from 'node:fs';import { redactConnectionInfo } from '../../core/audit/redact-connection-info.ts';import { formatPackBytes, OVERSIZED_PACK_RUNBOOK, schemaPackMaxBytes } from '../../core/schema-pack/loader.ts';@@ -291,15 +292,24 @@ export function multiSourceDriftCheck(`. Fix the path or permissions (\`gbrain sources status\`), then re-run \`gbrain doctor\`.`: '';if (result.walk_truncated) {+ // #7145: a walk stopped at its bound did not compare every file, so drift is unknown, not detected and not clear;+ // slugs already found before the bound are a floor, kept so the bound does not hide them.+ const bound = result.truncated_by === 'time' ? 'time' : 'files';+ const which = bound === 'files'+ ? `its file limit (${result.limit} files per source, GBRAIN_DRIFT_LIMIT)`+ : `its time limit (${result.timeout_ms} ms, GBRAIN_DRIFT_TIMEOUT_MS)`;+ const found = result.count > 0+ ? ` At least ${result.count} misrouted slug(s) were already found before it stopped (e.g., ${result.sample.map((s) => `${s.slug} (intended=${s.intended_source})`).join(', ')}).`+ : '';return {name: 'multi_source_drift',status: 'warn',message:- `Multi-source drift not verified — the FS walk hit its bound (${result.limit} files / ${result.timeout_ms} ms)` +- (host === 'remote' ? ' on the brain server' : '') +- `. Re-run with a larger bound: \`GBRAIN_DRIFT_LIMIT=<files> GBRAIN_DRIFT_TIMEOUT_MS=<ms> gbrain doctor\`.` ++ `Multi-source drift unknown: the FS walk stopped at ${which}` + (host === 'remote' ? ' on the brain server' : '') ++ ` before comparing every file, so health is unknown, not clear (bounds: ${result.limit} files / ${result.timeout_ms} ms).${found}` ++ ` Re-run with a larger bound: \`GBRAIN_DRIFT_LIMIT=<files> GBRAIN_DRIFT_TIMEOUT_MS=<ms> gbrain doctor --only multi_source_drift\`.` +unreadableNote,- details: { ...details, code: 'not_verified', verified: false },+ details: { ...details, ...boundUnknownDetails(bound), code: 'not_verified', verified: false, drift_found_so_far: result.count },};}if (result.count > 0) {diff --git a/src/core/multi-source-drift.ts b/src/core/multi-source-drift.tsindex 16649224ce..3ab5c54197 100644--- a/src/core/multi-source-drift.ts+++ b/src/core/multi-source-drift.ts@@ -63,6 +63,8 @@ export interface MisroutedSample {export interface MisroutedResult {/** True when the FS walk hit the limit/timeout and the result is partial. */walk_truncated: boolean;+ /** Which bound stopped the walk: the per-source file limit or the shared deadline; null when it finished. */+ truncated_by?: 'files' | 'time' | null;/** Per-source breakdown: slugs that appear at (default, slug) but NOT at (X, slug). */count: number;sample: MisroutedSample[];@@ -99,7 +101,7 @@ const SAMPLE_LIMIT = 5;* read errors on individual entries. Returns relative paths from `root`.** Bounded by `limit` (max files) and `deadlineMs` (epoch ms). Returns early- * with `truncated=true` if either bound is hit. An unreadable root sets+ * with `truncated` naming the bound (`files` or `time`) if either is hit. An unreadable root sets* `rootUnreadable`; each unreadable directory below it counts in* `unreadableDirs`, so callers can tell "nothing to check" from "could not read".*/@@ -107,9 +109,9 @@ function walkMarkdownAndMdxFiles(root: string,limit: number,deadlineMs: number,-): { files: { relPath: string }[]; truncated: boolean; rootUnreadable: boolean; unreadableDirs: number } {+): { files: { relPath: string }[]; truncated: 'files' | 'time' | null; rootUnreadable: boolean; unreadableDirs: number } {const files: { relPath: string }[] = [];- let truncated = false;+ let truncated: 'files' | 'time' | null = null;let unreadableDirs = 0;function walk(d: string): void {if (truncated) return;@@ -139,7 +141,7 @@ function walkMarkdownAndMdxFiles(if (isDir) {// Time check on directory descent too, so a deep dependency-free// tree still respects the deadline even before any .md is found.- if (Date.now() >= deadlineMs) { truncated = true; return; }+ if (Date.now() >= deadlineMs) { truncated = 'time'; return; }walk(full);continue;}@@ -148,13 +150,13 @@ function walkMarkdownAndMdxFiles(if (entry.startsWith('_')) continue; // matches extract.ts conventionfiles.push({ relPath: relative(root, full) });if (files.length >= limit) {- truncated = true;+ truncated = 'files';return;}// Time check is cheap; do it on every push so a slow filesystem can't// run unbounded.if (Date.now() >= deadlineMs) {- truncated = true;+ truncated = 'time';return;}}@@ -166,7 +168,7 @@ function walkMarkdownAndMdxFiles(statSync(root); // probe readable; throws ENOENT/EACCES if notreaddirSync(root);} catch {- return { files, truncated: false, rootUnreadable: true, unreadableDirs: 0 };+ return { files, truncated: null, rootUnreadable: true, unreadableDirs: 0 };}walk(root);return { files, truncated, rootUnreadable: false, unreadableDirs };@@ -244,7 +246,7 @@ export async function findMisroutedPages(const deadlineMs = Date.now() + timeoutMs;let totalCount = 0;- let walkTruncated = false;+ let truncatedBy: MisroutedResult['truncated_by'] = null;const sample: MisroutedSample[] = [];const gitRootSkipped: string[] = [];const unreadable: MisroutedResult['unreadable_sources'] = [];@@ -253,11 +255,11 @@ export async function findMisroutedPages(if (src.id === 'default') continue;if (!src.local_path) continue;if (Date.now() >= deadlineMs) {- walkTruncated = true;+ truncatedBy ??= 'time';break;}const { files, truncated, rootUnreadable, unreadableDirs } = walkMarkdownAndMdxFiles(src.local_path, limit, deadlineMs);- if (truncated) walkTruncated = true;+ if (truncated) truncatedBy ??= truncated;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;@@ -296,7 +298,7 @@ export async function findMisroutedPages(}return {- walk_truncated: walkTruncated, count: totalCount, sample, git_root_skipped: gitRootSkipped,+ walk_truncated: truncatedBy !== null, truncated_by: truncatedBy, count: totalCount, sample, git_root_skipped: gitRootSkipped,unreadable_sources: unreadable, limit, timeout_ms: timeoutMs,};}diff --git a/test/doctor-bound-unknown-7145.test.ts b/test/doctor-bound-unknown-7145.test.tsnew file mode 100644index 0000000000..413459c167--- /dev/null+++ b/test/doctor-bound-unknown-7145.test.ts@@ -0,0 +1,65 @@+/**+ * #7145: a doctor check that stops at one of its own bounds reports health unknown, naming the bound+ * (`details.reason: 'bound'`, `details.bound`, `details.exact: false`), never a known warn or a clear ok.+ * Synthetic directories and an in-memory PGLite brain.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { findMisroutedPages } from '../src/core/multi-source-drift.ts';+import { multiSourceDriftCheck } from '../src/commands/doctor/schema-pack-checks.ts';++const dirs: string[] = [];+const tmp = (label: string) => {+ const d = mkdtempSync(join(tmpdir(), `gbrain-7145-${label}-`));+ dirs.push(d);+ return d;+};++describe('multi_source_drift stopped at its bound is unknown', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('src-a','src-a')");+ }, 60_000);+ afterAll(async () => {+ await engine.disconnect();+ for (const d of dirs) rmSync(d, { recursive: true, force: true });+ });++ test('the file limit: health unknown with the bound named, not drift detected', async () => {+ const root = tmp('files');+ for (let i = 0; i < 12; i++) writeFileSync(join(root, `p-${i}.md`), 'x\n');+ const result = await findMisroutedPages(engine, [{ id: 'src-a', local_path: root }], { limit: 5, timeoutMs: 60_000 });+ expect(result.truncated_by).toBe('files');+ const check = multiSourceDriftCheck(result, 1, 'local');+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ health: 'unknown', reason: 'bound', bound: 'files', limit: 5, exact: false, verified: false });+ expect(check.message).toContain('unknown');+ expect(check.message).toContain('file limit (5 files per source, GBRAIN_DRIFT_LIMIT)');+ });++ test('the time limit is named as the time bound', async () => {+ const root = tmp('time');+ mkdirSync(join(root, 'sub'));+ writeFileSync(join(root, 'sub', 'p.md'), 'x\n');+ const timed = await findMisroutedPages(engine, [{ id: 'src-a', local_path: root }], { limit: 1000, timeoutMs: 0 });+ expect(timed.truncated_by).toBe('time');+ const check = multiSourceDriftCheck(timed, 1, 'remote');+ expect(check.details).toMatchObject({ health: 'unknown', reason: 'bound', bound: 'time', exact: false });+ expect(check.message).toContain('GBRAIN_DRIFT_TIMEOUT_MS');+ });++ test('drift found before the bound is kept as a floor', () => {+ const check = multiSourceDriftCheck({ walk_truncated: true, truncated_by: 'files', count: 2,+ sample: [{ slug: 'notes/alice-example', intended_source: 'src-a', local_path: '/synthetic' }],+ git_root_skipped: [], unreadable_sources: [], limit: 5, timeout_ms: 5000 }, 1, 'local');+ expect(check.details).toMatchObject({ health: 'unknown', drift_found_so_far: 2 });+ expect(check.message).toContain('At least 2 misrouted slug(s)');+ expect(check.message).toContain('notes/alice-example');+ });+});