Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): checks that verified nothing warn 'not verified'; push state is per-root (#5432)
garrytan4df9e0269d92
diff --git a/src/commands/doctor/bootstrap-checks.ts b/src/commands/doctor/bootstrap-checks.tsindex e36d3f4049..88a4bc52f3 100644--- a/src/commands/doctor/bootstrap-checks.ts+++ b/src/commands/doctor/bootstrap-checks.ts@@ -93,7 +93,7 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promiseconst receipt = readReceipt(home);// One reader for every push-status surface [D8]; per-root files [D13].- const { readPushStatuses, pushStatusFilesExist } = await import('../../core/workspace-push.ts');+ const { readPushStatuses, pushStatusFilesExist, pushStatusForWorkspace } = await import('../../core/workspace-push.ts');const pushStatuses = readPushStatuses();const statusFilesOnDisk = pushStatusFilesExist();const heartbeatFile = join(home, 'integrations', 'hooks', 'heartbeat.jsonl');@@ -320,11 +320,11 @@ export async function bootstrapDoctorChecks(engine: BrainEngine | null): Promise}} catch { dirty = false; known = false; }}- if (stale && dirty) {+ if (dirty && ws && Date.now() - Date.parse(pushStatusForWorkspace(pushStatuses, ws)?.ts ?? '') > PUSH_STALE_MS) { // #5432: this root's own receiptchecks.push({name: 'bootstrap_push_health',status: 'fail',- message: `last successful push ${staleIso} (>48h) with a DIRTY workspace tree — recent agent memory is unpushed [B4]. Run \`gbrain sources push --path ${ws}\`.`,+ message: `last successful push ${pushStatusForWorkspace(pushStatuses, ws)?.ts} (>48h) with a DIRTY workspace tree — recent agent memory is unpushed [B4]. Run \`gbrain sources push --path ${ws}\`.`,});} else if (stale && !targetMatchesWs) {// Multiple tracked push targets (or the one target names adiff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.tsindex 57506a3662..e969d6f2d5 100644--- a/src/commands/doctor/checks/calibration.ts+++ b/src/commands/doctor/checks/calibration.ts@@ -669,7 +669,10 @@ export async function checkRerankerHealth(engine: BrainEngine, now: Date = new Dreturn {name: 'reranker_health',status: 'warn',- message: `${authFails.length} reranker auth failure(s) in last 7 days (key present but rejected). Fix: verify the reranker provider's API key (e.g. ${readiness.requiredKey ?? 'VOYAGE_API_KEY'}) and run \`gbrain models doctor\`.`,+ // #5432: the audit log records failures only and this check runs no+ // live probe, so it reports history, not the key's current state.+ message: `${authFails.length} reranker auth failure(s) recorded in the last 7 days (key present but rejected at the time). This is audit-log history; no live probe was run, so the key may have recovered since. Fix: verify the reranker provider's API key (e.g. ${readiness.requiredKey ?? 'VOYAGE_API_KEY'}) and run \`gbrain models doctor\`.`,+ details: { live_probe_performed: false, failures_recorded: authFails.length, window_days: 7 },};}diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex 259c38adcb..ff111f8265 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -934,7 +934,8 @@ export async function computeAtomProvenanceDriftCheck(`${drifted}/${total} atom(s) (${details.drift_pct}%) reference a source_hash no live page carries ` +`— ${sourceChanged} whose source page still exists (edited), ${sourceGone} whose source page is gone` +(oldestDays != null ? `; oldest ${oldestDays}d` : '') + su +- `. These still surface in search with a source_quote that no current page contains. Fix: ${fix}`,+ `. This compares source_hash only (any edit to the source page changes it); it does not re-check whether ` ++ `the atom's source_quote still appears in the page, so edited-source atoms may still be accurate. Fix: ${fix}`,details,};}diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.tsindex 3aa60fa985..be95f30fa5 100644--- a/src/commands/doctor/checks/local-audits.ts+++ b/src/commands/doctor/checks/local-audits.ts@@ -9,7 +9,7 @@import { join } from 'path';import { gbrainPath } from '../../../core/config.ts';-import { multiSourceDriftGitRootSkipNote, multiSourceDriftAdvice } from '../schema-pack-checks.ts';+import { multiSourceDriftCheck, multiSourceDriftNotVerified } from '../schema-pack-checks.ts';import { computeConversationFormatCoverageCheck } from './conversation-coverage.ts';import {computeExtractHealthCheck,@@ -497,49 +497,12 @@ async function runDefaultSourcePath(ctx: DoctorContext): Promise<Check[]> {engine!,nonDefaultWithPath.map(s => ({ id: s.id, local_path: s.local_path as string })),);- if (result.walk_truncated) {- checks.push({- name: 'multi_source_drift',- status: 'warn',- message:- `Multi-source drift check skipped — FS walk hit limit/timeout. ` +- `Re-run on a quieter brain or shorter walk via GBRAIN_DRIFT_LIMIT/GBRAIN_DRIFT_TIMEOUT_MS.`,- });- } 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) + 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: 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.',- });- }+ checks.push(multiSourceDriftCheck(result, nonDefaultWithPath.length, 'local'));}- } catch {- // Best-effort. A broken sources table or unreadable local_path should- // not stop doctor. The walk itself catches per-directory errors; this- // outer try covers the executeRaw path.+ } catch (e) {+ // A broken sources table must not stop doctor, but the check still+ // reports that it verified nothing (#5432).+ checks.push(multiSourceDriftNotVerified(e));}// 3c. Orphan clone temp dirs (v0.28 P1). `gbrain sources add --url` clonesdiff --git a/src/commands/doctor/checks/search-eval.ts b/src/commands/doctor/checks/search-eval.tsindex 1a80494a05..e87c004440 100644--- a/src/commands/doctor/checks/search-eval.ts+++ b/src/commands/doctor/checks/search-eval.ts@@ -291,7 +291,11 @@ export async function checkSubagentCapability(engine: BrainEngine): Promise<Checstatus: 'warn',message:`${source} is "${resolved}" but that provider/model lacks native tool calling. ` +- `The subagent loop cannot run on this model — runtime will fall back to claude-sonnet-4-6. ` ++ `The subagent loop cannot run on this model — ` ++ // #5432: an explicit models.subagent is not swapped; dispatch refuses it.+ (source === 'models.subagent'+ ? `jobs are refused at dispatch. `+ : `runtime will fall back to claude-sonnet-4-6. `) +`Fix: \`gbrain config set ${source} <provider>:<model-with-tools>\` (e.g. anthropic:claude-sonnet-4-6 or openai:gpt-5.2).`,};}diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex 8937bd96b9..3beae69131 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -53,13 +53,14 @@ import {checkLinkResolutionOpportunity,checkFederationHealth,checkSelfUpgradeHealth,- multiSourceDriftGitRootSkipNote,computeExtractAtomsBacklogCheck,} from '../doctor.ts';import {checkSchemaPackActive,checkSchemaPackConsistency,checkSchemaPackSourceDrift,+ multiSourceDriftCheck,+ multiSourceDriftNotVerified,} from './schema-pack-checks.ts';// Same alias the local doctor keeps for its own freshness checks; the alias@@ -287,48 +288,11 @@ export async function doctorReportRemote(engine,nonDefaultWithPath.map(s => ({ id: s.id, local_path: s.local_path as string })),);- if (result.walk_truncated) {- checks.push({- name: 'multi_source_drift',- status: 'warn',- message: 'Multi-source drift check skipped — FS walk hit limit/timeout on the brain server.',- });- } 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\`.` +- 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: 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.',- });- }+ checks.push(multiSourceDriftCheck(result, nonDefaultWithPath.length, 'remote'));}- } catch {- // Best-effort, like the rest of doctorReportRemote.+ } catch (e) {+ // Best-effort, but the check reports that it verified nothing (#5432).+ checks.push(multiSourceDriftNotVerified(e));}// 5. Queue health (Postgres-only). PGLite has no minion_jobs in the samediff --git a/src/commands/doctor/schema-pack-checks.ts b/src/commands/doctor/schema-pack-checks.tsindex a538797d79..93233cd150 100644--- a/src/commands/doctor/schema-pack-checks.ts+++ b/src/commands/doctor/schema-pack-checks.ts@@ -5,6 +5,7 @@*/import type { BrainEngine } from '../../core/engine.ts';import type { Check } from '../doctor.ts';+import type { MisroutedResult } from '../../core/multi-source-drift.ts';import { redactConnectionInfo } from '../../core/audit/redact-connection-info.ts';import { loadActivePackForLocalEngine } from '../../core/schema-pack/best-effort.ts';import { sanitizeTypeForDisplay, storedTypeMissesPack } from '../../core/schema-pack/type-usage.ts';@@ -53,12 +54,12 @@ const SCHEMA_PACK_DOCS = 'docs/architecture/schema-packs.md#undeclared-page-type* #5432: a check that could not read its input says "not verified" (warn),* never ok. The redacted reason rides in `details.reason` for `--json`.*/-function notVerified(err: unknown, fix: string): Omit<Check, 'name'> {+function notVerified(err: unknown, fix: string, docs = SCHEMA_PACK_DOCS): Omit<Check, 'name'> {const reason = redactConnectionInfo(err instanceof Error ? err.message : String(err)).slice(0, 200);return {status: 'warn',message: `Not verified: the check could not run (${reason}). Fix the cause, then re-run \`${fix}\`.`,- details: { code: 'not_verified', verified: false, reason, fix, docs: SCHEMA_PACK_DOCS },+ details: { code: 'not_verified', verified: false, reason, fix, docs },};}@@ -221,3 +222,84 @@ export function multiSourceDriftGitRootSkipNote(skippedIds: string[]): string {`matching not yet implemented — #4712): ${skippedIds.join(', ')}.`);}++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.+ */+export function multiSourceDriftCheck(+ result: MisroutedResult,+ candidateSources: number,+ host: 'local' | 'remote',+): Check {+ const details = {+ walk_truncated: result.walk_truncated,+ unreadable_sources: result.unreadable_sources,+ git_root_skipped: result.git_root_skipped,+ limit: result.limit,+ timeout_ms: result.timeout_ms,+ docs: DRIFT_DOCS,+ };+ const skipNote = result.git_root_skipped.length > 0 ? multiSourceDriftGitRootSkipNote(result.git_root_skipped) : '';+ const unreadable = result.unreadable_sources;+ const unreadableNote = unreadable.length > 0+ ? ` Not verified for ${unreadable.length} source(s) whose local_path could not be read: ` ++ unreadable.map((u) => `${u.source_id} (${u.reason === 'root_unreadable' ? 'root unreadable' : `${u.dirs} unreadable dir(s)`})`).join(', ') ++ `. Fix the path or permissions (\`gbrain sources status\`), then re-run \`gbrain doctor\`.`+ : '';+ if (result.walk_truncated) {+ 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\`.` ++ unreadableNote,+ details: { ...details, code: 'not_verified', verified: false },+ };+ }+ if (result.count > 0) {+ const sampleStr = result.sample.map((s) => `${s.slug} (intended=${s.intended_source})`).join(', ');+ const advice = host === 'local'+ ? multiSourceDriftAdvice(result.count, sampleStr)+ : `${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\`.`;+ return { name: 'multi_source_drift', status: 'warn', message: advice + skipNote + unreadableNote, details: { ...details, code: 'drift_detected' } };+ }+ if (unreadable.length > 0) {+ return {+ name: 'multi_source_drift',+ status: 'warn',+ message: `No cross-source slug drift among readable sources.${unreadableNote}${skipNote}`,+ 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) {+ return {+ name: 'multi_source_drift',+ status: 'warn',+ message: `Multi-source drift check performed no verification${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,+ };+}++/** #5432: the drift check itself failed (e.g. the sources query); report it instead of dropping the check. */+export function multiSourceDriftNotVerified(err: unknown): Check {+ return { name: 'multi_source_drift', ...notVerified(err, 'gbrain doctor', DRIFT_DOCS) };+}diff --git a/src/core/bootstrap/status.ts b/src/core/bootstrap/status.tsindex 041977e63f..f330621366 100644--- a/src/core/bootstrap/status.ts+++ b/src/core/bootstrap/status.ts@@ -537,14 +537,13 @@ export async function statusReport(ws: string, opts: StatusReportOpts = {}): Pro}}- // Support blob [B5]. Push status via the shared per-root reader [D8/D13]:- // a failing workspace wins over another's success; else the newest record.+ // Support blob [B5]. Push status of THIS workspace's root via the shared+ // per-root reader [D8/D13] (#5432): another root's failure or success is+ // never reported as this workspace's; no receipt for this root is null.let lastPush: StatusSupport['last_push'] = null;try {- const { readPushStatuses, summarizePushStatuses } = await import('../workspace-push.ts');- const entries = readPushStatuses();- const { failing } = summarizePushStatuses(entries);- const pick = failing[0] ?? entries.sort((a, b) => Date.parse(b.ts ?? '') - Date.parse(a.ts ?? ''))[0];+ const { readPushStatuses, pushStatusForWorkspace } = await import('../workspace-push.ts');+ const pick = pushStatusForWorkspace(readPushStatuses(), ws);if (pick) {lastPush = {...(pick.ts !== undefined ? { ts: pick.ts } : {}),diff --git a/src/core/multi-source-drift.ts b/src/core/multi-source-drift.tsindex 805e88e60b..7e691496af 100644--- a/src/core/multi-source-drift.ts+++ b/src/core/multi-source-drift.ts@@ -28,7 +28,8 @@* skipped, walk too large" status instead of letting doctor hang.* - 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.+ * 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@@ -71,10 +72,24 @@ export interface MisroutedResult {* rather than checked against the wrong slug shape.*/git_root_skipped: string[];+ /**+ * #5432: sources whose walk could not read their root (`root_unreadable`)+ * or some directory below it (`subdirs_unreadable`). Their result is not+ * verified: an unreadable root is not an empty source.+ */+ unreadable_sources: Array<{ source_id: string; reason: 'root_unreadable' | 'subdirs_unreadable'; dirs: number }>;+ /** Walk bounds actually used (opts, else GBRAIN_DRIFT_LIMIT / GBRAIN_DRIFT_TIMEOUT_MS, else defaults). */+ limit: number;+ timeout_ms: number;}const DEFAULT_FILE_LIMIT = 10_000;const DEFAULT_TIMEOUT_MS = 5_000;++function positiveIntEnv(name: string): number | undefined {+ const n = Number(process.env[name]);+ return Number.isInteger(n) && n > 0 ? n : undefined;+}const SAMPLE_LIMIT = 5;/**@@ -83,16 +98,18 @@ 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. The root-not-readable case- * surfaces as `truncated=false, files=[]` (caller treats as "no candidates").+ * with `truncated=true` if either bound 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".*/function walkMarkdownAndMdxFiles(root: string,limit: number,deadlineMs: number,-): { files: { relPath: string }[]; truncated: boolean } {+): { files: { relPath: string }[]; truncated: boolean; rootUnreadable: boolean; unreadableDirs: number } {const files: { relPath: string }[] = [];let truncated = false;+ let unreadableDirs = 0;function walk(d: string): void {if (truncated) return;let entries: string[];@@ -100,6 +117,7 @@ function walkMarkdownAndMdxFiles(entries = readdirSync(d);} catch {// Unreadable directory; skip without crashing the whole walk.+ unreadableDirs++;return;}for (const entry of entries) {@@ -145,12 +163,12 @@ function walkMarkdownAndMdxFiles(// the root would throw and crash the whole doctor run).try {statSync(root); // probe readable; throws ENOENT/EACCES if not- walk(root);+ readdirSync(root);} catch {- // local_path is unreadable; return zero files, NOT truncated. Caller- // surfaces this as "ok with note" rather than an error.+ return { files, truncated: false, rootUnreadable: true, unreadableDirs: 0 };}- return { files, truncated };+ walk(root);+ return { files, truncated, rootUnreadable: false, unreadableDirs };}/**@@ -203,14 +221,15 @@ export async function findMisroutedPages(sources: SourceWithPath[],opts: { limit?: number; timeoutMs?: number } = {},): Promise<MisroutedResult> {- const limit = opts.limit ?? DEFAULT_FILE_LIMIT;- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ const limit = opts.limit ?? positiveIntEnv('GBRAIN_DRIFT_LIMIT') ?? DEFAULT_FILE_LIMIT;+ const timeoutMs = opts.timeoutMs ?? positiveIntEnv('GBRAIN_DRIFT_TIMEOUT_MS') ?? DEFAULT_TIMEOUT_MS;const deadlineMs = Date.now() + timeoutMs;let totalCount = 0;let walkTruncated = false;const sample: MisroutedSample[] = [];const gitRootSkipped: string[] = [];+ const unreadable: MisroutedResult['unreadable_sources'] = [];for (const src of sources) {if (src.id === 'default') continue;@@ -228,8 +247,10 @@ export async function findMisroutedPages(gitRootSkipped.push(src.id);continue;}- const { files, truncated } = walkMarkdownAndMdxFiles(src.local_path, limit, deadlineMs);+ 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;// Convert FS paths to canonical slugs (lowercased, extension stripped).@@ -251,5 +272,8 @@ export async function findMisroutedPages(}}- return { walk_truncated: walkTruncated, count: totalCount, sample, git_root_skipped: gitRootSkipped };+ return {+ walk_truncated: walkTruncated, count: totalCount, sample, git_root_skipped: gitRootSkipped,+ unreadable_sources: unreadable, limit, timeout_ms: timeoutMs,+ };}diff --git a/src/core/onboard/checks.ts b/src/core/onboard/checks.tsindex 06b39a4a58..014bb6fafe 100644--- a/src/core/onboard/checks.ts+++ b/src/core/onboard/checks.ts@@ -15,6 +15,7 @@// process.exit. SQL via engine.executeRaw with `sourceScopeOpts(ctx)`// when ctx threads — onboard surface threads explicitly per A26.+import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import type { BrainEngine } from '../engine.ts';import type { RemediationStep } from '../remediation-step.ts';import { makeRemediationStep } from '../remediation-step.ts';@@ -26,6 +27,7 @@ export interface OnboardCheckResult {name: string;status: 'ok' | 'warn' | 'fail';message: string;+ details?: Record<string, unknown>;};remediations: RemediationStep[];}@@ -120,16 +122,29 @@ function coverageWithConfidence(sample: EntityCoverageSample): { coverage: numbe/*** embed_staleness: count of chunks awaiting embedding.*- * Backed by content_chunks_stale_idx partial index (v100) so the count- * is cheap even on big brains.+ * Uses `engine.countStaleChunks()`, the embed worker's own predicate (the+ * registry-active embedding column plus its embed_skip/quarantine+ * exclusions), so the check and the worker agree. A failed count is "not+ * verified" (#5432), never "No stale chunks".*/export async function checkEmbedStaleness(engine: BrainEngine,): Promise<OnboardCheckResult> {- const staleCount = await safeCount(- engine,- `SELECT COUNT(*) AS count FROM content_chunks WHERE embedding IS NULL`,- );+ let staleCount: number;+ try {+ staleCount = await engine.countStaleChunks();+ } catch (e) {+ const reason = redactConnectionInfo(e instanceof Error ? e.message : String(e)).slice(0, 200);+ return {+ check: {+ name: 'embed_staleness',+ status: 'warn',+ message: `Not verified: the stale-chunk count failed (${reason}). Fix the cause, then re-run \`gbrain doctor\`.`,+ details: { code: 'not_verified', verified: false, reason, fix: 'gbrain doctor', docs: 'docs/guides/troubleshooting.md#not-verified-doctor-checks' },+ },+ remediations: [],+ };+ }const remediations: RemediationStep[] = [];let status: 'ok' | 'warn' | 'fail' = 'ok';let message: string;diff --git a/src/core/workspace-push.ts b/src/core/workspace-push.tsindex c1696c89e4..2c46f9969a 100644--- a/src/core/workspace-push.ts+++ b/src/core/workspace-push.ts@@ -53,7 +53,7 @@ import { OperationError } from './ops/contract.ts';*/import {- existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync,+ existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync,} from 'fs';import { dirname, join, resolve } from 'path';import { createHash, randomBytes } from 'crypto';@@ -495,6 +495,20 @@ export function readPushStatusForRoot(root: string): PushStatusEntry | null {return readPushStatuses().find((e) => e.repoRoot === root) ?? null;}+/**+ * #5432: the push-status record that belongs to workspace `ws`, or null. A+ * record matches by its repoRoot (symlinks resolved on both sides); a single+ * legacy record with no repoRoot is attributed to `ws`. Another root's record+ * is never reported as this workspace's push state.+ */+export function pushStatusForWorkspace(entries: readonly PushStatusEntry[], ws: string): PushStatusEntry | null {+ const real = (p: string) => { try { return realpathSync(p); } catch { return resolve(p); } };+ const target = real(ws);+ const own = entries.find((e) => e.repoRoot !== undefined && real(e.repoRoot) === target);+ if (own) return own;+ return entries.length === 1 && entries[0]!.repoRoot === undefined ? entries[0]! : null;+}+/** One aggregation for every status surface (SessionStart note, doctor,* banner counting): the failing entries and the stalest success timestamp. *//** Failure reasons carry remote-influenced text (git stderr → rung log →diff --git a/test/doctor-atom-provenance-drift.test.ts b/test/doctor-atom-provenance-drift.test.tsindex 04d2cae6ad..6308f37258 100644--- a/test/doctor-atom-provenance-drift.test.ts+++ b/test/doctor-atom-provenance-drift.test.ts@@ -283,6 +283,9 @@ describe('computeAtomProvenanceDriftCheck', () => {expect(c.status).toBe('warn');expect(c.message).toContain('30/30');expect(c.message).toContain('source page is gone');+ // #5432: says what was measured (hash comparison), not a quote verdict.+ expect(c.message).toContain('compares source_hash only');+ expect(c.message).not.toContain('no current page contains');});it('does not count a slug-unbound atom (source_path only, no source_slug) as source_gone — or as drift at all (#4806)', async () => {// Transcript-origin atoms carry `source_path` but no `source_slug`diff --git a/test/doctor-not-verified-5432.test.ts b/test/doctor-not-verified-5432.test.tsnew file mode 100644index 0000000000..9073610763--- /dev/null+++ b/test/doctor-not-verified-5432.test.ts@@ -0,0 +1,212 @@+/**+ * #5432 — doctor / bootstrap status checks never report ok for state they did+ * not verify, and never attribute another workspace's push state to this one.+ *+ * - multi_source_drift: an unreadable source root or subdirectory is+ * "not verified" (warn), not an empty source; GBRAIN_DRIFT_LIMIT /+ * GBRAIN_DRIFT_TIMEOUT_MS bound the walk; a failed check is reported.+ * - onboard embed_staleness: counts with engine.countStaleChunks (the embed+ * worker's predicate); a failed count warns "not verified".+ * - bootstrap_push_health / bootstrap status last_push: scoped to the+ * receipt workspace's own push record.+ * - subagent_capability: an explicit models.subagent without tool calling+ * is refused at dispatch, not "falls back".+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { findMisroutedPages } from '../src/core/multi-source-drift.ts';+import { multiSourceDriftCheck, multiSourceDriftNotVerified } from '../src/commands/doctor/schema-pack-checks.ts';+import { checkEmbedStaleness } from '../src/core/onboard/checks.ts';+import { bootstrapDoctorChecks, checkSubagentCapability } from '../src/commands/doctor.ts';+import { statusReport } from '../src/core/bootstrap/status.ts';+import { workspaceRootHash } from '../src/core/workspace-push.ts';+import { withEnv } from './helpers/with-env.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const dirs: string[] = [];+const tmp = (label: string) => {+ const d = mkdtempSync(join(tmpdir(), `gbrain-5432-${label}-`));+ dirs.push(d);+ return d;+};+afterAll(() => {+ for (const d of dirs) {+ try { chmodSync(d, 0o700); } catch { /* ignore */ }+ rmSync(d, { recursive: true, force: true });+ }+});++describe('#5432 multi_source_drift is not verified when it could not read', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 60_000);+ afterAll(async () => {+ await engine.disconnect();+ });++ test('missing root -> root_unreadable; an empty dir is clean', async () => {+ const empty = tmp('empty');+ const result = await findMisroutedPages(engine, [+ { id: 'src-missing', local_path: join(tmpdir(), 'gbrain-5432-does-not-exist') },+ { id: 'src-empty', local_path: empty },+ ]);+ expect(result.unreadable_sources).toEqual([{ source_id: 'src-missing', reason: 'root_unreadable', dirs: 1 }]);+ const check = multiSourceDriftCheck(result, 2, 'local');+ expect(check.status).toBe('warn');+ expect(check.details?.code).toBe('not_verified');+ expect(check.message).toContain('src-missing (root unreadable)');+ expect(check.message).not.toContain('No cross-source slug drift detected.');++ const clean = await findMisroutedPages(engine, [{ id: 'src-empty', local_path: empty }]);+ expect(multiSourceDriftCheck(clean, 1, 'local')).toMatchObject({ status: 'ok', message: 'No cross-source slug drift detected.' });+ });++ test('an unreadable subdirectory is reported, not silently skipped', async () => {+ const root = tmp('subdir');+ mkdirSync(join(root, 'locked'));+ writeFileSync(join(root, 'locked', 'page.md'), 'x\n');+ chmodSync(join(root, 'locked'), 0o000);+ try {+ const result = await findMisroutedPages(engine, [{ id: 'src-locked', local_path: root }]);+ expect(result.unreadable_sources).toEqual([{ source_id: 'src-locked', reason: 'subdirs_unreadable', dirs: 1 }]);+ expect(multiSourceDriftCheck(result, 1, 'remote').status).toBe('warn');+ } finally {+ chmodSync(join(root, 'locked'), 0o700);+ }+ });++ test('GBRAIN_DRIFT_LIMIT bounds the walk when opts do not', async () => {+ const root = tmp('limit');+ for (let i = 0; i < 12; i++) writeFileSync(join(root, `p-${i}.md`), 'x\n');+ const result = await withEnv({ GBRAIN_DRIFT_LIMIT: '5', GBRAIN_DRIFT_TIMEOUT_MS: '4000' },+ () => findMisroutedPages(engine, [{ id: 'src-limit', local_path: root }]));+ expect(result.walk_truncated).toBe(true);+ expect(result.limit).toBe(5);+ expect(result.timeout_ms).toBe(4000);+ const check = multiSourceDriftCheck(result, 1, 'local');+ expect(check.status).toBe('warn');+ expect(check.message).toContain('5 files / 4000 ms');+ expect(check.message).toContain('GBRAIN_DRIFT_LIMIT=<files>');+ });++ test('a failed drift check is reported as not verified', () => {+ const check = multiSourceDriftNotVerified(new Error('relation "sources" does not exist'));+ expect(check).toMatchObject({ name: 'multi_source_drift', status: 'warn' });+ expect(check.details).toMatchObject({ code: 'not_verified', reason: 'relation "sources" does not exist' });+ });+});++describe('#5432 onboard embed_staleness', () => {+ test('counts with the embed worker predicate (countStaleChunks), not raw SQL', async () => {+ const engine = {+ countStaleChunks: async () => 7,+ executeRaw: async () => { throw new Error('raw SQL must not be used'); },+ } as unknown as BrainEngine;+ const r = await checkEmbedStaleness(engine);+ expect(r.check.status).toBe('warn');+ expect(r.check.message).toContain('7 stale chunks');+ });++ test('a failed count warns not verified instead of "No stale chunks"', async () => {+ const engine = {+ countStaleChunks: async () => { throw new Error('permission denied for table content_chunks'); },+ executeRaw: async () => { throw new Error('permission denied for table content_chunks'); },+ } as unknown as BrainEngine;+ const r = await checkEmbedStaleness(engine);+ expect(r.check.status).toBe('warn');+ expect(r.check.message).toContain('Not verified');+ expect(r.check.message).not.toContain('No stale chunks');+ expect(r.check.details).toMatchObject({ code: 'not_verified', reason: 'permission denied for table content_chunks' });+ expect(r.remediations).toEqual([]);+ });+});++describe('#5432 push status is scoped to this workspace', () => {+ const STALE = new Date(Date.now() - 72 * 3600_000).toISOString();+ const FRESH = new Date(Date.now() - 3600_000).toISOString();++ function home(): { parent: string; home: string } {+ const parent = tmp('home');+ const h = join(parent, '.gbrain');+ mkdirSync(join(h, 'bootstrap'), { recursive: true });+ return { parent, home: h };+ }+ function receipt(h: string, ws: string): void {+ writeFileSync(join(h, 'bootstrap', 'receipt.json'), JSON.stringify({+ receipt_version: 1, workspace_dir: ws, source_id: 'workspace', agent_name: 'Testy',+ created_at: new Date().toISOString(), created_by: 'test', brain_created_by_bootstrap: false,+ created_paths: [], registrations: [],+ }));+ }+ function pushStatus(h: string, root: string, body: Record<string, unknown>): void {+ writeFileSync(join(h, 'bootstrap', `push-status-${workspaceRootHash(root)}.json`), JSON.stringify({ ...body, repoRoot: root }));+ }+ function dirtyWorkspace(): string {+ const ws = tmp('ws');+ execFileSync('git', ['init', '-q', ws], { stdio: 'ignore' });+ writeFileSync(join(ws, 'unpushed-note.md'), 'recent agent memory\n');+ return ws;+ }++ test('another root stale + this root fresh and dirty -> never a current-root FAIL', async () => {+ const { parent, home: h } = home();+ const ws = dirtyWorkspace();+ const other = tmp('other-root');+ receipt(h, ws);+ pushStatus(h, ws, { ts: FRESH, ok: true });+ pushStatus(h, other, { ts: STALE, ok: true });+ const checks = await withEnv({ GBRAIN_HOME: parent }, () => bootstrapDoctorChecks(null));+ const c = checks.find((x) => x.name === 'bootstrap_push_health');+ expect(c?.status).toBe('warn');+ expect(c?.message).toContain('2 tracked workspace');+ });++ test('this root stale + dirty -> FAIL naming this root and its own timestamp', async () => {+ const { parent, home: h } = home();+ const ws = dirtyWorkspace();+ const other = tmp('other-root');+ receipt(h, ws);+ pushStatus(h, ws, { ts: STALE, ok: true });+ pushStatus(h, other, { ts: FRESH, ok: true });+ const checks = await withEnv({ GBRAIN_HOME: parent }, () => bootstrapDoctorChecks(null));+ const c = checks.find((x) => x.name === 'bootstrap_push_health');+ expect(c?.status).toBe('fail');+ expect(c?.message).toContain(STALE);+ expect(c?.message).toContain(ws);+ });++ test('bootstrap status last_push reports this root only, both directions', async () => {+ const { parent, home: h } = home();+ const ws = tmp('status-ws');+ const other = tmp('status-other');+ pushStatus(h, ws, { ts: FRESH, ok: true });+ pushStatus(h, other, { ts: FRESH, ok: false, reason: 'remote rejected' });+ const a = await withEnv({ GBRAIN_HOME: parent }, () => statusReport(ws, { gbrainHomeDir: h }));+ expect(a.support.last_push).toEqual({ ts: FRESH, ok: true });++ const { parent: p2, home: h2 } = home();+ pushStatus(h2, other, { ts: FRESH, ok: true });+ const b = await withEnv({ GBRAIN_HOME: p2 }, () => statusReport(ws, { gbrainHomeDir: h2 }));+ expect(b.support.last_push).toBeNull();+ });+});++describe('#5432 subagent_capability no_tools', () => {+ const engineWith = (entries: Record<string, string>) => ({+ getConfig: async (k: string) => entries[k] ?? null,+ }) as unknown as BrainEngine;++ test('explicit models.subagent without tool calling is refused at dispatch, not a fallback', async () => {+ const c = await checkSubagentCapability(engineWith({ 'models.subagent': 'nvidia:nvidia/nemotron-3-super-120b-a12b' }));+ expect(c.status).toBe('warn');+ expect(c.message).toContain('jobs are refused at dispatch');+ expect(c.message).not.toContain('fall back');+ });+});diff --git a/test/doctor-reranker-health.test.ts b/test/doctor-reranker-health.test.tsindex 087ac0a9b6..1c376feb2a 100644--- a/test/doctor-reranker-health.test.ts+++ b/test/doctor-reranker-health.test.ts@@ -159,6 +159,9 @@ describe('reranker_health (v0.48.2 readiness-aware)', () => {expect(c.status).toBe('warn');expect(c.message).toContain('auth failure');expect(c.message).toContain('key present but rejected');+ // #5432: audit-log history, not a live verdict.+ expect(c.message).toContain('no live probe was run');+ expect(c.details?.live_probe_performed).toBe(false);});});