Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(doctor): --tier fast and last known results with a background doctor-refresh job (#7142)

garrytan8e4ce20dbcfd
diff --git a/src/cli/help/doctor.ts b/src/cli/help/doctor.ts
index 2473f20247..7d872a0327 100644
--- a/src/cli/help/doctor.ts
+++ b/src/cli/help/doctor.ts
@@ -5,7 +5,7 @@ export const help: CliHelpSpec = {
summary: 'Check brain health; preview and run remediation.',
usage: [
'gbrain doctor [--fast] [--json] [--fix [--dry-run]] [--scope=brain] [--source <id>] [--no-migrate] [--locks]',
- 'gbrain doctor --tier ops|standard|deep [--budget-ms <n>] [--json]',
+ 'gbrain doctor --tier ops|fast|standard|deep [--budget-ms <n>] [--json]',
'gbrain doctor --only <check>[,<check>…] [--tier ops] [--json]',
'gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]',
'gbrain doctor --remediate [--yes [--expect <plan_hash>]] [--include-repairs] [--max-usd <n>] [--target-score <n>]',
@@ -15,7 +15,7 @@ export const help: CliHelpSpec = {
{ name: '--json', type: 'boolean', desc: 'Print one JSON document (checks, score, findings) on stdout.' },
{ name: '--only', type: 'string', desc: 'Read-only: run just the named checks (comma-separated or repeated; no migrations). The usual fix.verify. An unknown name exits 2 with the valid list.' },
{ name: '--fast', type: 'boolean', desc: 'Skip database checks; filesystem and config checks only.' },
- { name: '--tier', type: 'enum', values: ['ops', 'standard', 'deep'], desc: 'ops: only the operational sections (capacity, write failures, embedding state, sync movement, compaction, serve build, schema pack) under a 4 s deadline, observational (no migrations). standard (default): ops first, then the rest. deep: adds full scans (orphan_ratio on brains over 50,000 pages).' },
+ { name: '--tier', type: 'enum', values: ['ops', 'fast', 'standard', 'deep'], desc: 'ops: only the operational sections (capacity, write failures, embedding state, sync movement, compaction, serve build, schema pack) under a 4 s deadline, observational (no migrations). fast: the health gate for agents on large brains: the ops sections plus schema version, sync failures, queue health, link-extraction lag and partial embeddings under a 10 s deadline; every other check is reported from its last known result with its age, checks with none from the last 24 h are named as unknown, and a background doctor-refresh job is queued to measure them. standard (default): ops first, then the rest; a brain-wide run records each finished check as its last known result. deep: adds full scans (orphan_ratio on brains over 50,000 pages).' },
{ name: '--budget-ms', type: 'number', desc: 'Absolute end-to-end deadline in ms, counted from before the connect (default 4000 with --tier ops; 0: none). A plain non-interactive --json run caps its check run at doctor.default_budget_ms (file plane, default 90000, 0 off) instead. With --only, the named checks get the whole budget. Checks past it report health unknown (reason budget, which budget in details.limit); the report says complete: false.' },
{ name: '--fix', type: 'boolean', desc: 'Apply the local fixes doctor knows (skill files, stale locks); pair with --dry-run to preview.' },
{ name: '--dry-run', type: 'boolean', desc: 'Preview --fix or --remediate without changing anything.' },
diff --git a/src/commands/doctor.ts b/src/commands/doctor.ts
index d27f8eca52..7d21b3f076 100644
--- a/src/commands/doctor.ts
+++ b/src/commands/doctor.ts
@@ -138,7 +138,7 @@ export {
import type { DoctorContext, DoctorTier } from './doctor/context.ts';
import { doctorRunSummary, parseDoctorTier, startDoctorDeadline, tierFields, type DoctorDeadline, type DoctorRunSummary } from './doctor/budget.ts';
export { doctorRunSummary, type DoctorRunSummary } from './doctor/budget.ts';
-import { runDoctorRegistry, parseOnlyChecks } from './doctor/registry.ts';
+import { runDoctorRegistry, parseOnlyChecks, doctorRefreshRegistry } from './doctor/registry.ts';
import { finalizeCheckFixes, fixLine, unknownScoreCategories, type CheckAgentFields } from './doctor/check-fix.ts';
import { throttleDoctorHeartbeat } from './doctor/heartbeat.ts';
import type { RenderContext } from '../core/agent-output.ts';
@@ -247,6 +247,8 @@ export interface DoctorReport {
tier?: DoctorTier;
complete?: boolean;
unknown_sections?: string[];
+ /** #7142: checks reported from their last known result (with its age in `details.last_known`), not measured by this run. */
+ last_known_sections?: string[];
elapsed_ms?: number;
budget_ms?: number | null;
}
@@ -396,7 +398,8 @@ export async function buildChecks(
connectError?: unknown,
// #6696: the run's deadline (started by the CLI before connecting) and a remote caller's readable sources.
deadline: DoctorDeadline = startDoctorDeadline(args),
- remoteScope: { sourceIds?: string[] } = {},
+ // #7142: lastKnown / entryBudgetOverrideMs / refreshOnly: the CLI run and the doctor-refresh job (./doctor/last-known.ts).
+ remoteScope: { sourceIds?: string[]; lastKnown?: 'cli' | 'refresh'; entryBudgetOverrideMs?: number; refreshOnly?: boolean } = {},
): Promise<Check[]> {
const jsonOutput = args.includes('--json');
const fastMode = args.includes('--fast');
@@ -474,9 +477,11 @@ export async function buildChecks(
tier: parseDoctorTier(args),
deadline,
...(remoteScope.sourceIds ? { sourceIds: remoteScope.sourceIds } : {}),
+ ...(remoteScope.lastKnown ? { lastKnown: remoteScope.lastKnown } : {}),
+ ...(remoteScope.entryBudgetOverrideMs ? { entryBudgetOverrideMs: remoteScope.entryBudgetOverrideMs } : {}),
};
- return runDoctorRegistry(ctx);
+ return remoteScope.refreshOnly ? runDoctorRegistry(ctx, doctorRefreshRegistry()) : runDoctorRegistry(ctx);
}
/**
@@ -517,7 +522,7 @@ export async function runDoctor(
}
if (args.includes('--probe') && !(await (await import('./doctor/probe-consent.ts')).authorizeProviderProbe(engine, args, jsonOutput))) return;
- const checks = await buildChecks(engine, args, dbSource, connectError, deadline);
+ const checks = await buildChecks(engine, args, dbSource, connectError, deadline, { lastKnown: 'cli' });
const run = doctorRunSummary(args, deadline);
const hasFail = outputResults(checks, jsonOutput, { engine: engine?.kind, db_url_source: dbSource ?? null, run });
@@ -615,7 +620,7 @@ function outputResults(
console.log(`Ops checks: ${report.category_scores.ops}/100`);
console.log(`Meta checks: ${report.category_scores.meta}/100`);
if (brainScoreLine) console.log(brainScoreLine);
- if (report.tier) console.log(`Tier: ${report.tier}, ${report.complete ? 'complete' : `incomplete (unknown: ${report.unknown_sections!.join(', ')})`}, ${report.elapsed_ms} ms${report.budget_ms ? ` of ${report.budget_ms} ms` : ''}`);
+ if (report.tier) console.log(`Tier: ${report.tier}, ${report.complete ? 'complete' : `incomplete (${[report.unknown_sections!.length ? `unknown: ${report.unknown_sections!.join(', ')}` : '', report.last_known_sections?.length ? `${report.last_known_sections.length} from last known results` : ''].filter(Boolean).join('; ')})`}, ${report.elapsed_ms} ms${report.budget_ms ? ` of ${report.budget_ms} ms` : ''}`);
console.log('');
if (hasFail) {
diff --git a/src/commands/doctor/budget.ts b/src/commands/doctor/budget.ts
index 4be5e137ed..2df94c1353 100644
--- a/src/commands/doctor/budget.ts
+++ b/src/commands/doctor/budget.ts
@@ -1,7 +1,7 @@
/**
* #6696 B1: doctor tiers and budgets.
*
- * `--tier ops|standard|deep` selects which registry entries run (see
+ * `--tier ops|fast|standard|deep` selects which registry entries run (see
* `DoctorTier` in ./context.ts); `--budget-ms <n>` is one absolute end-to-end
* deadline that starts before the CLI connects (default 4000 for `ops`, none
* for the other tiers; `--budget-ms 0`: none). A plain non-interactive CLI
@@ -31,9 +31,11 @@ import type { Check, DoctorReport } from '../doctor.ts';
import { agentFix } from './check-fix.ts';
import type { DoctorTier } from './context.ts';
-export const DOCTOR_TIERS: readonly DoctorTier[] = ['ops', 'standard', 'deep'];
+export const DOCTOR_TIERS: readonly DoctorTier[] = ['ops', 'fast', 'standard', 'deep'];
/** Default `--budget-ms` for `--tier ops`; the other tiers have no overall deadline unless one is given. */
export const OPS_BUDGET_MS_DEFAULT = 4000;
+/** #7142: default `--budget-ms` for `--tier fast` (connect included). */
+export const FAST_BUDGET_MS_DEFAULT = 10_000;
/** Config key and default of the per-entry budget (standard and deep tiers; ops entries use the overall deadline). */
export const ENTRY_BUDGET_KEY = 'doctor.entry_budget_ms';
export const ENTRY_BUDGET_MS_DEFAULT = 15_000;
@@ -84,7 +86,7 @@ export function parseDoctorTier(args: readonly string[]): DoctorTier {
/** `--budget-ms <n>` (a non-negative integer; 0: no overall budget), else the tier default. */
export function parseBudgetMs(args: readonly string[], tier: DoctorTier): number | null {
const raw = flagValue(args, '--budget-ms');
- if (raw === undefined) return tier === 'ops' ? OPS_BUDGET_MS_DEFAULT : null;
+ if (raw === undefined) return tier === 'ops' ? OPS_BUDGET_MS_DEFAULT : tier === 'fast' ? FAST_BUDGET_MS_DEFAULT : null;
const n = Number(raw);
if (!Number.isSafeInteger(n) || n < 0) {
throw opError('invalid_params', `--budget-ms must be a whole number of milliseconds, 0 for no overall budget (got ${raw}).`, 'Example: --budget-ms 4000.');
@@ -115,10 +117,11 @@ export function scanDeadline(ctx: { entryDeadlineAt?: number }, ownTimeoutMs: nu
return Math.min(now + ownTimeoutMs, (ctx.entryDeadlineAt ?? Infinity) - SCAN_REPORT_RESERVE_MS);
}
-/** Whether a registry entry runs at `tier` (`standard` includes `ops`; `deep` includes both). */
+/** Whether a registry entry runs at `tier` (each tier includes the ones before it: ops, fast, standard, deep). */
export function entryRunsAt(entryTier: DoctorTier | undefined, tier: DoctorTier): boolean {
const own = entryTier ?? 'standard';
if (tier === 'ops') return own === 'ops';
+ if (tier === 'fast') return own === 'ops' || own === 'fast';
if (tier === 'standard') return own !== 'deep';
return true;
}
@@ -190,9 +193,13 @@ export function isBudgetUnknown(check: Pick<Check, 'details'>): boolean {
/** #6696 B1: what the report says about the run's tier and deadline (`--tier` / `--budget-ms` given). */
export interface DoctorRunSummary { tier: DoctorTier; startedAt: number; budgetMs: number | null }
-export function tierFields(checks: Check[], run: DoctorRunSummary): Pick<DoctorReport, 'tier' | 'complete' | 'unknown_sections' | 'elapsed_ms' | 'budget_ms'> {
- const unknown = checks.filter((c) => c.status !== 'ok' && c.details?.health === 'unknown').map((c) => c.name);
- return { tier: run.tier, complete: unknown.length === 0, unknown_sections: unknown, elapsed_ms: Date.now() - run.startedAt, budget_ms: run.budgetMs };
+export function tierFields(checks: Check[], run: DoctorRunSummary): Pick<DoctorReport, 'tier' | 'complete' | 'unknown_sections' | 'last_known_sections' | 'elapsed_ms' | 'budget_ms'> {
+ // #7142: the doctor_last_known warning stands for the checks it names; a last known result is known, but not from this run.
+ const unknown = checks.filter((c) => c.status !== 'ok' && c.details?.health === 'unknown')
+ .flatMap((c) => Array.isArray(c.details?.unknown_checks) ? c.details.unknown_checks as string[] : [c.name]);
+ const lastKnown = checks.filter((c) => c.details?.last_known !== undefined).map((c) => c.name);
+ return { tier: run.tier, complete: unknown.length === 0 && lastKnown.length === 0, unknown_sections: unknown,
+ ...(lastKnown.length ? { last_known_sections: lastKnown } : {}), elapsed_ms: Date.now() - run.startedAt, budget_ms: run.budgetMs };
}
/** The run summary a report carries: when the caller chose a tier or a budget, or the non-interactive default capped the run. */
diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.ts
index b84c92d53a..6d4b5cd9ec 100644
--- a/src/commands/doctor/checks/content-quality.ts
+++ b/src/commands/doctor/checks/content-quality.ts
@@ -269,6 +269,7 @@ async function runPartialEmbedding(ctx: DoctorContext): Promise<Check[]> {
export const partialEmbeddingEntry: DoctorEntry = {
name: 'partial_embedding',
emits: ['partial_embedding'],
+ tier: 'fast',
run: runPartialEmbedding,
};
diff --git a/src/commands/doctor/checks/db-connection.ts b/src/commands/doctor/checks/db-connection.ts
index 6594246ec9..1ca7e5d76c 100644
--- a/src/commands/doctor/checks/db-connection.ts
+++ b/src/commands/doctor/checks/db-connection.ts
@@ -23,7 +23,7 @@ import { BACKUP_SIZE_WARN_RATIO, PHYSICAL_COPY_RUNBOOK, estimatedTarBytes, forma
import type { Check } from '../../doctor.ts';
import { classifyPgAccessError } from '../../../core/pg-access-classify.ts';
import { dbRepairRecurrenceCheck } from './engine-fit.ts';
-import { STOP_DOCTOR, connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { STOP_DOCTOR, connectedEngine, quickTier, type DoctorContext, type DoctorEntry } from '../context.ts';
import { DoctorBudgetError, budgetUnknownCheck } from '../budget.ts';
async function runPgliteDataDir(ctx: DoctorContext): Promise<Check[]> {
@@ -313,9 +313,9 @@ async function runConnection(ctx: DoctorContext): Promise<Check[]> {
progress.heartbeat('connection');
try {
// #6696 B1: the ops tier proves the round trip only; the page count is a full count the deadline does not afford.
- if (ctx.tier === 'ops') {
+ if (quickTier(ctx.tier)) {
await engine.executeRaw('SELECT 1 AS ok');
- checks.push({ name: 'connection', status: 'ok', message: 'Connected (ops tier: page count not read).' });
+ checks.push({ name: 'connection', status: 'ok', message: `Connected (${ctx.tier} tier: page count not read).` });
} else {
const stats = await engine.getStats();
checks.push({ name: 'connection', status: 'ok', message: `Connected, ${stats.page_count} pages` });
@@ -324,7 +324,7 @@ async function runConnection(ctx: DoctorContext): Promise<Check[]> {
// A round trip the ops deadline ended (a saturated pool, a blocked server) is unknown, not a classified outage.
const deadlineAt = ctx.deadline?.deadlineAt;
if (e instanceof DoctorBudgetError) throw e;
- if (ctx.tier === 'ops' && deadlineAt != null && Date.now() >= deadlineAt) throw new DoctorBudgetError(Date.now() - ctx.deadline!.startedAt);
+ if (quickTier(ctx.tier) && deadlineAt != null && Date.now() >= deadlineAt) throw new DoctorBudgetError(Date.now() - ctx.deadline!.startedAt);
// db-availability loop (2c): classified + redacted, with the fix hint.
checks.push(classifiedConnectionCheck(e));
progress.finish();
diff --git a/src/commands/doctor/checks/embedding-state.ts b/src/commands/doctor/checks/embedding-state.ts
index da0b6b3ca5..a7766318ae 100644
--- a/src/commands/doctor/checks/embedding-state.ts
+++ b/src/commands/doctor/checks/embedding-state.ts
@@ -13,7 +13,7 @@
* still inside the window and a brain keyless by choice are information.
*/
import type { Check } from '../../doctor.ts';
-import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { connectedEngine, quickTier, type DoctorContext, type DoctorEntry } from '../context.ts';
import { agentFix, checkError, doctorVerify, infoCheck, keylessEnablementFix } from '../check-fix.ts';
import { EMBEDDING_STATE_DOCS, embeddingStateFix, readEmbeddingState, type EmbeddingState } from '../../../core/embedding-state.ts';
@@ -27,7 +27,7 @@ async function runEmbeddingState(ctx: DoctorContext): Promise<Check[]> {
const checks: Check[] = [];
ctx.progress.heartbeat('embedding_state');
try {
- const state = await readEmbeddingState(engine, { mode: ctx.tier === 'ops' ? 'ops' : 'full', ...(ctx.sourceIds ? { sourceIds: ctx.sourceIds } : {}) });
+ const state = await readEmbeddingState(engine, { mode: quickTier(ctx.tier) ? 'ops' : 'full', ...(ctx.sourceIds ? { sourceIds: ctx.sourceIds } : {}) });
const details: Record<string, unknown> = { ...state, exact: state.basis === 'exact' };
if (state.status === 'unknown') {
checks.push({ name: 'embedding_state', status: 'warn',
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index d80c51fbf1..e6e2aaad49 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -125,6 +125,7 @@ export const stubGuardEntry: DoctorEntry = {
name: 'stub_guard_24h',
emits: ['stub_guard_24h', 'sync_failures', 'managed_sync_backlog', 'slug_fallback_audit'],
engineChecks: ['sync_failures', 'managed_sync_backlog'],
+ tier: 'fast',
run: runStubGuard,
};
diff --git a/src/commands/doctor/checks/queue-assets.ts b/src/commands/doctor/checks/queue-assets.ts
index 7a33549593..da8f7c79a0 100644
--- a/src/commands/doctor/checks/queue-assets.ts
+++ b/src/commands/doctor/checks/queue-assets.ts
@@ -88,6 +88,7 @@ async function runQueueHealth(ctx: DoctorContext): Promise<Check[]> {
export const queueHealthEntry: DoctorEntry = {
name: 'queue_health',
emits: ['queue_health', 'subagent_capability', 'facts_health'],
+ tier: 'fast',
run: runQueueHealth,
};
diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.ts
index d02af2e213..9b7241f42c 100644
--- a/src/commands/doctor/checks/schema-health.ts
+++ b/src/commands/doctor/checks/schema-health.ts
@@ -311,6 +311,7 @@ function missingTablesFields(report: MissingTablesReport): Omit<Check, 'name'> {
export const schemaVersionEntry: DoctorEntry = {
name: 'schema_version',
emits: ['schema_version', 'schema_columns', 'schema_missing_tables'],
+ tier: 'fast',
run: runSchemaVersion,
};
diff --git a/src/commands/doctor/context.ts b/src/commands/doctor/context.ts
index 0afbeb655f..0b712e218f 100644
--- a/src/commands/doctor/context.ts
+++ b/src/commands/doctor/context.ts
@@ -21,11 +21,18 @@ import type { BrainHealth } from '../../core/types.ts';
export const STOP_DOCTOR: unique symbol = Symbol('STOP_DOCTOR');
/**
- * #6696 B1: `--tier ops|standard|deep`. `ops` runs only the entries tagged
- * `ops` (observational, under one absolute deadline); `standard` (default) runs
- * ops entries first, then the rest; `deep` adds the entries tagged `deep`.
+ * #6696 B1: `--tier ops|fast|standard|deep`. `ops` runs only the entries tagged
+ * `ops` (observational, under one absolute deadline); `fast` (#7142) adds the
+ * entries tagged `fast` under its own deadline and reports every other check
+ * from its last known result; `standard` (default) runs ops entries first, then
+ * the rest; `deep` adds the entries tagged `deep`.
*/
-export type DoctorTier = 'ops' | 'standard' | 'deep';
+export type DoctorTier = 'ops' | 'fast' | 'standard' | 'deep';
+
+/** #7142: the tiers that answer from cheap reads only (a round-trip connection check, counter-mode sections). */
+export function quickTier(tier: DoctorTier | undefined): boolean {
+ return tier === 'ops' || tier === 'fast';
+}
export interface DoctorEntry {
/** The entry's primary check name (an entry that only stops names the check it gates on). */
@@ -80,6 +87,10 @@ export interface DoctorContext {
sourceIds?: string[];
/** #6803 C3: the running entry's absolute deadline (scans stop at it and report what they read); undefined: unbounded. */
entryDeadlineAt?: number;
+ /** #7142: a brain-wide local CLI run (or the background refresh) that reads and records last known results (./last-known.ts). */
+ lastKnown?: 'cli' | 'refresh';
+ /** #7142: the per-entry budget of the background refresh, instead of `doctor.entry_budget_ms`. */
+ entryBudgetOverrideMs?: number;
/** #6696 B1: one `getHealth()` per run, shared by every entry that reads it (`doctorHealth`). */
healthMemo?: Promise<BrainHealth>;
}
diff --git a/src/commands/doctor/last-known.ts b/src/commands/doctor/last-known.ts
new file mode 100644
index 0000000000..8a49104ae0
--- /dev/null
+++ b/src/commands/doctor/last-known.ts
@@ -0,0 +1,163 @@
+/**
+ * #7142: last known doctor results.
+ *
+ * On a large brain a standard run cannot finish every check inside the
+ * non-interactive default budget, and the fast tier does not run the slow
+ * checks at all. Every completed standard or deep entry records the checks it
+ * emitted in `op_checkpoints` (op `doctor-last-known`, one row per entry, so
+ * the jobs worker and the CLI share it whatever GBRAIN_HOME each has). A later
+ * run that did not finish an entry, or a fast-tier run that did not run it,
+ * reports that entry's last known checks with their age instead of nothing or
+ * an unknown. A result older than LAST_KNOWN_MAX_AGE_MS is not served: those
+ * checks are named as unknown in one `doctor_last_known` check (status warn,
+ * so the report is never healthy on them), and a `doctor-refresh` job is
+ * queued to measure them in the background with a long per-check budget.
+ *
+ * Only a brain-wide local CLI run (no --only, no --source, not remote) reads or
+ * writes these rows; writing is best-effort and never fails the run.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+import type { Check } from '../doctor.ts';
+import type { DoctorContext, DoctorEntry } from './context.ts';
+
+export const LAST_KNOWN_OP = 'doctor-last-known';
+/** A last known result older than this is not served; its checks are unknown. */
+export const LAST_KNOWN_MAX_AGE_MS = 24 * 60 * 60_000;
+/** An entry whose last known result is older than this is measured again by the background refresh. */
+export const REFRESH_AFTER_MS = 60 * 60_000;
+/** The background refresh job and its per-check budget (the time a slow check needs on a large brain, not 15 s). */
+export const REFRESH_JOB = 'doctor-refresh';
+export const REFRESH_ENTRY_BUDGET_MS = 600_000;
+const REFRESH_TIMEOUT_MS = 2 * 60 * 60_000;
+/** Bound of the cache read and write (they run outside every entry's deadline). */
+const IO_BOUND_MS = 3_000;
+
+export interface LastKnownEntry { checks: Check[]; measured_at: string; elapsed_ms: number }
+
+/** What a run asks of the last known results: `serve` reports them for entries it did not finish; `record` stores the ones it did. */
+export interface LastKnownMode { serve: boolean; record: boolean; refresh: boolean }
+
+/** One entry's outcome in this run. */
+export interface EntryOutcome { entry: DoctorEntry; state: 'done' | 'expired' | 'not_run'; checks: Check[]; elapsed_ms: number }
+
+async function bounded<T>(work: Promise<T>): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expiry = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('doctor last-known I/O timed out')), IO_BOUND_MS); });
+ try { return await Promise.race([work, expiry]); } finally { if (timer) clearTimeout(timer); }
+}
+
+/** Every entry's last known result; an unreadable store reads as empty (nothing is served, so nothing reads as healthy). */
+export async function readLastKnown(engine: BrainEngine): Promise<Map<string, LastKnownEntry>> {
+ try {
+ const rows = await bounded(engine.executeRaw<{ fingerprint: string; entry: unknown }>(
+ 'SELECT fingerprint, completed_keys->0 AS entry FROM op_checkpoints WHERE op = $1', [LAST_KNOWN_OP]));
+ const out = new Map<string, LastKnownEntry>();
+ for (const row of rows) {
+ const value = (typeof row.entry === 'string' ? JSON.parse(row.entry) : row.entry) as LastKnownEntry | null;
+ if (value && Array.isArray(value.checks) && typeof value.measured_at === 'string') out.set(row.fingerprint, value);
+ }
+ return out;
+ } catch {
+ return new Map();
+ }
+}
+
+/** Store the entries this run finished (best-effort: a read-only role or an old schema just keeps the previous results). */
+export async function writeLastKnown(engine: BrainEngine, outcomes: readonly EntryOutcome[], now = Date.now()): Promise<void> {
+ const rows = outcomes.filter(o => o.state === 'done').map(o => ({ entry: o.entry.name,
+ value: { checks: o.checks.filter(c => c.details?.last_known === undefined), measured_at: new Date(now).toISOString(), elapsed_ms: o.elapsed_ms } satisfies LastKnownEntry }));
+ if (!rows.length) return;
+ try {
+ await bounded(engine.executeRaw(
+ `INSERT INTO op_checkpoints (op, fingerprint, completed_keys, updated_at)
+ SELECT $1, e->>'entry', jsonb_build_array(e->'value'), now() FROM jsonb_array_elements($2::text::jsonb) AS e
+ ON CONFLICT (op, fingerprint) DO UPDATE SET completed_keys = EXCLUDED.completed_keys, updated_at = EXCLUDED.updated_at`,
+ [LAST_KNOWN_OP, JSON.stringify(rows)]));
+ } catch { /* the previous results stay; the next run that can write records them */ }
+}
+
+function ageText(ms: number): string {
+ const min = Math.round(ms / 60_000);
+ if (min < 1) return 'under a minute';
+ if (min < 120) return `${min} min`;
+ return `${Math.round(min / 60)} h`;
+}
+
+/** One check from a last known result, with its age; its status is the one it had then. */
+export function lastKnownCheck(check: Check, measuredAt: string, reason: 'not_in_tier' | 'budget', now = Date.now()): Check {
+ const age = Math.max(0, now - Date.parse(measuredAt));
+ const why = reason === 'budget' ? 'not finished within this run\'s budget' : 'not run by the fast tier';
+ return { ...check, message: `Last known, ${ageText(age)} ago (${why}): ${check.message}`,
+ details: { ...check.details, last_known: { measured_at: measuredAt, age_ms: age, reason } } };
+}
+
+/**
+ * Apply the last known results to a finished run: an entry that expired or was not run at this tier reports its
+ * last known checks when they are fresh; otherwise its checks are listed in one `doctor_last_known` warning (and an
+ * expired entry keeps its unknown checks). Returns the checks to report and the entries a refresh should measure.
+ */
+export function applyLastKnown(checks: Check[], outcomes: readonly EntryOutcome[], cache: ReadonlyMap<string, LastKnownEntry>, now = Date.now()): { checks: Check[]; stale: EntryOutcome[]; refresh: string[] } {
+ const replaced = new Set<string>();
+ const served: Check[] = [];
+ const stale: EntryOutcome[] = [];
+ const refresh: string[] = [];
+ for (const outcome of outcomes) {
+ const last = cache.get(outcome.entry.name);
+ const age = last ? now - Date.parse(last.measured_at) : Infinity;
+ if (outcome.state === 'done') continue;
+ if (!last || !(age <= REFRESH_AFTER_MS)) refresh.push(outcome.entry.name);
+ if (last && age <= LAST_KNOWN_MAX_AGE_MS) {
+ if (outcome.state === 'expired') for (const name of outcome.entry.emits) replaced.add(name);
+ served.push(...last.checks.map(c => lastKnownCheck(c, last.measured_at, outcome.state === 'expired' ? 'budget' : 'not_in_tier', now)));
+ } else if (outcome.state === 'not_run') {
+ stale.push(outcome);
+ }
+ }
+ return { checks: [...checks.filter(c => !replaced.has(c.name)), ...served], stale, refresh };
+}
+
+/** The one warning that names the checks with no result inside LAST_KNOWN_MAX_AGE_MS (never measured, or too old). */
+export function unmeasuredCheck(stale: readonly EntryOutcome[], cache: ReadonlyMap<string, LastKnownEntry>, refreshJob: { id: number } | null, engineKind: string | undefined): Check | null {
+ if (!stale.length) return null;
+ const names = [...new Set(stale.flatMap(o => o.entry.emits))].sort();
+ const old = stale.filter(o => cache.has(o.entry.name)).length;
+ const argv = ['gbrain', 'doctor', '--tier', 'standard', '--budget-ms', '0', '--json'];
+ const queued = refreshJob ? ` A background refresh is queued (job #${refreshJob.id}); it needs a running jobs worker${engineKind === 'pglite' ? ' (gbrain jobs work)' : ''}.` : '';
+ return {
+ name: 'doctor_last_known', status: 'warn',
+ message: `${names.length} check(s) have no result from the last ${LAST_KNOWN_MAX_AGE_MS / 3_600_000} h (${old === stale.length ? 'their last results are too old' : old ? `${old} of ${stale.length} entries have only an older result, the rest were never measured` : 'never measured'}); their health is unknown, not clear.${queued} Measure them now with: ${argv.join(' ')}`,
+ details: { health: 'unknown', reason: 'not_measured', exact: false, unknown_checks: names, ...(refreshJob ? { refresh_job: refreshJob.id } : {}) },
+ fix: { argv, consent: [], actor: 'user', requires_exclusive: false, why: 'Runs every standard check with no overall budget and records each result, so later fast runs report them; read-only, and it can take minutes on a large brain.' },
+ };
+}
+
+/** Queue one background refresh (deduplicated per hour); null when it cannot be queued. */
+export async function queueRefresh(engine: BrainEngine, now = Date.now()): Promise<{ id: number } | null> {
+ try {
+ const { MinionQueue } = await import('../../core/minions/queue.ts');
+ const slot = new Date(now).toISOString().slice(0, 13);
+ const job = await bounded(new MinionQueue(engine).add(REFRESH_JOB, {}, { queue: 'default', idempotency_key: `${REFRESH_JOB}:${slot}`, max_attempts: 1, timeout_ms: REFRESH_TIMEOUT_MS, maxWaiting: 1 }));
+ return { id: Number(job.id) };
+ } catch {
+ return null;
+ }
+}
+
+/** Whether this run reads or writes the last known results (only a brain-wide local run, never `--only`). */
+export function lastKnownMode(ctx: Pick<DoctorContext, 'only' | 'sourceIds' | 'orphanRatioSourceId' | 'doFix' | 'tier' | 'lastKnown'>): LastKnownMode | null {
+ if (!ctx.lastKnown || ctx.only || ctx.sourceIds || ctx.orphanRatioSourceId || ctx.doFix || ctx.tier === 'ops') return null;
+ return { serve: true, record: ctx.tier === 'standard' || ctx.tier === 'deep', refresh: ctx.lastKnown === 'cli' };
+}
+
+/**
+ * The `doctor-refresh` job: every standard-tier database check, each with REFRESH_ENTRY_BUDGET_MS, recorded as last
+ * known results. Read-only apart from that record; it never queues another refresh.
+ */
+export async function runDoctorRefresh(engine: BrainEngine): Promise<{ recorded: number; unfinished: string[]; elapsed_ms: number }> {
+ const started = Date.now();
+ const { buildChecks } = await import('../doctor.ts');
+ const checks = await buildChecks(engine, ['--json', '--tier', 'standard', '--scope=brain'], undefined, undefined, undefined, { lastKnown: 'refresh', entryBudgetOverrideMs: REFRESH_ENTRY_BUDGET_MS, refreshOnly: true });
+ const unfinished = [...new Set(checks.filter(c => c.details?.health === 'unknown' && c.details.reason === 'budget').map(c => c.name))];
+ return { recorded: checks.length - unfinished.length, unfinished, elapsed_ms: Date.now() - started };
+}
+
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index f060e60d7f..a5e25d543f 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -140,15 +140,17 @@ import {
soakCountersEntry,
schemaPackConsistencyEntry,
} from './checks/ops-sections.ts';
-import { STOP_DOCTOR, type DoctorContext, type DoctorEntry, type DoctorTier } from './context.ts';
+import { STOP_DOCTOR, quickTier, type DoctorContext, type DoctorEntry, type DoctorTier } from './context.ts';
import {
BUDGET_EXPIRED, DoctorBudgetError, budgetExpired, type BudgetExpired, ENTRY_BUDGET_KEY, ENTRY_BUDGET_MS_DEFAULT, budgetUnknownCheck, entryRunsAt,
- opsNotApplicableCheck, raceBudget, startDeferredDeadline,
+ isBudgetUnknown, opsNotApplicableCheck, raceBudget, startDeferredDeadline,
} from './budget.ts';
import { StatementDeadlineError, deadlineBoundEngine, withStatementDeadline, type StatementDeadline } from '../../core/statement-deadline.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
import { withGitListingCache } from '../../core/git-visible-files.ts';
+import type { BrainEngine } from '../../core/engine.ts';
+import { applyLastKnown, lastKnownMode, queueRefresh, readLastKnown, unmeasuredCheck, writeLastKnown, type EntryOutcome, type LastKnownMode } from './last-known.ts';
export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
resolverHealthEntry,
@@ -290,6 +292,12 @@ export function opsCheckNames(): Set<string> {
return new Set(DOCTOR_CHECK_REGISTRY.filter((e) => e.tier === 'ops').flatMap((e) => e.emits));
}
+/** #7142: what the doctor-refresh job runs: the connection lane, then every standard-tier entry after the connection gate (filesystem entries depend on the caller's environment, so only the CLI records them). */
+export function doctorRefreshRegistry(): DoctorEntry[] {
+ const gateAt = DOCTOR_CHECK_REGISTRY.indexOf(connectionGateEntry);
+ return DOCTOR_CHECK_REGISTRY.filter((entry, i) => CONNECTION_LANE.has(entry) || (i > gateAt && entryRunsAt(entry.tier, 'standard')));
+}
+
/** `--only a,b` / `--only=a,b` (repeatable) → the requested check names, or null when absent. */
export function parseOnlyChecks(args: readonly string[]): Set<string> | null {
const raw: string[] = [];
@@ -348,14 +356,20 @@ export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEn
return withGitListingCache(async () => {
const tier = ctx.tier ?? 'standard';
startDeferredDeadline(ctx.deadline);
+ const rawEngine = ctx.engine;
if (ctx.engine) ctx.engine = deadlineBoundEngine(ctx.engine);
+ const lastKnown = lastKnownMode(ctx);
+ const outcomes: EntryOutcome[] = [];
const memo = new Map<string, Promise<unknown>>();
const gateAt = entries.indexOf(connectionGateEntry);
const checks: Check[] = [];
let entryBudgetMs: number | null = null;
for (const entry of entries) {
if (!selected(entry, ctx.only)) continue;
- if (!CONNECTION_LANE.has(entry) && !entryRunsAt(entry.tier, tier)) continue;
+ if (!CONNECTION_LANE.has(entry) && !entryRunsAt(entry.tier, tier)) {
+ if (lastKnown && entryRunsAt(entry.tier, 'standard')) outcomes.push({ entry, state: 'not_run', checks: [], elapsed_ms: 0 });
+ continue;
+ }
const started = Date.now();
const emitted = entry.emits.filter((n) => !ctx.only || ctx.only.has(n));
if (tier === 'ops' && entry.opsPglite === 'not_applicable' && ctx.engine?.kind === 'pglite') {
@@ -365,11 +379,12 @@ export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEn
if (entryBudgetMs === null && ctx.engine && !ctx.fastMode && !ctx.connectionFailed && gateAt >= 0 && entries.indexOf(entry) > gateAt) {
entryBudgetMs = await readEntryBudget(ctx);
}
- const overallOnly = tier === 'ops' || (!!ctx.only && ctx.deadline?.explicit === true);
+ const overallOnly = quickTier(tier) || (!!ctx.only && ctx.deadline?.explicit === true);
const budgetMs = entryBudget(ctx, overallOnly, CONNECTION_LANE.has(entry) ? null : entryBudgetMs, started);
const limit = budgetMs !== null && ctx.deadline?.deadlineAt != null && (overallOnly || entryBudgetMs === null || started + budgetMs >= ctx.deadline.deadlineAt) ? 'overall' : 'entry';
if (budgetMs !== null && budgetMs <= 0) {
checks.push(...emitted.map((n) => budgetUnknownCheck(n, 0, ctx.deadline?.budgetMs ?? 0, 'overall')));
+ if (lastKnown && !CONNECTION_LANE.has(entry)) outcomes.push({ entry, state: 'expired', checks: [], elapsed_ms: 0 });
continue;
}
const scope: StatementDeadline = { startedAt: started, deadlineAt: budgetMs === null ? null : started + budgetMs, expired: false, memo, runDeadlineAt: ctx.deadline?.deadlineAt ?? null };
@@ -382,6 +397,7 @@ export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEn
if (budgetExpired(result) || (scope.expired && result !== STOP_DOCTOR)) {
const shown = limit === 'overall' ? ctx.deadline?.budgetMs ?? budgetMs ?? 0 : budgetMs ?? 0;
checks.push(...emitted.map((n) => budgetUnknownCheck(n, elapsed, shown, limit)));
+ if (lastKnown && !CONNECTION_LANE.has(entry)) outcomes.push({ entry, state: 'expired', checks: [], elapsed_ms: elapsed });
continue;
}
if (result === STOP_DOCTOR) {
@@ -396,23 +412,40 @@ export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEn
return ctx.only ? onlyResult(checks, ctx.only, true) : checks;
}
const pastDeadline = ctx.deadline?.deadlineAt != null && Date.now() >= ctx.deadline.deadlineAt;
- checks.push(...result.map((c) => {
+ const produced = result.map((c) => {
if (pastDeadline && c.details?.health === 'unknown' && c.details.reason === undefined) {
const unknown = budgetUnknownCheck(c.name, elapsed, ctx.deadline!.budgetMs ?? 0, 'overall');
return { ...unknown, details: { ...unknown.details, cause: c.message } };
}
return c.elapsed_ms === undefined ? { ...c, elapsed_ms: elapsed } : c;
- }));
+ });
+ checks.push(...produced);
+ if (lastKnown && !CONNECTION_LANE.has(entry)) {
+ outcomes.push({ entry, state: produced.some(isBudgetUnknown) ? 'expired' : 'done', checks: produced, elapsed_ms: elapsed });
+ }
}
ctx.progress.finish();
+ if (lastKnown && rawEngine && !ctx.connectionFailed) return withLastKnown(rawEngine, checks, outcomes, lastKnown);
return ctx.only ? onlyResult(checks, ctx.only, false) : checks;
});
}
+/** #7142: report last known results for the entries this run did not finish, record the ones it did, and queue a refresh of the rest. */
+async function withLastKnown(engine: BrainEngine, checks: Check[], outcomes: EntryOutcome[], mode: LastKnownMode): Promise<Check[]> {
+ const unfinished = outcomes.some((o) => o.state !== 'done');
+ const cache = unfinished ? await readLastKnown(engine) : new Map();
+ if (mode.record) await writeLastKnown(engine, outcomes);
+ if (!unfinished) return checks;
+ const applied = applyLastKnown(checks, outcomes, cache);
+ const job = mode.refresh && applied.refresh.length && engine.kind === 'postgres' ? await queueRefresh(engine) : null;
+ const unmeasured = unmeasuredCheck(applied.stale, cache, job, engine.kind);
+ return unmeasured ? [...applied.checks, unmeasured] : applied.checks;
+}
+
/** The time this entry may take: the per-entry budget (unless only the overall deadline applies) clipped to the overall deadline; null: unbounded. */
function entryBudget(ctx: DoctorContext, overallOnly: boolean, perEntry: number | null, now: number): number | null {
const overall = ctx.deadline?.deadlineAt != null ? ctx.deadline.deadlineAt - now : null;
- const own = overallOnly ? null : perEntry;
+ const own = overallOnly ? null : ctx.entryBudgetOverrideMs ?? perEntry;
if (overall === null) return own;
return own === null ? overall : Math.min(own, overall);
}
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index efd2902307..f521b42966 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -599,6 +599,8 @@ export async function registerBuiltinHandlers(
worker.register('reindex', makeReindexHandler(engine));
worker.register('repair-jsonb', repairJsonbHandler);
worker.register('orphans', makeOrphansHandler(engine));
+ // #7142: measures the slow doctor checks in the background and records them as last known results (read-only otherwise).
+ worker.register('doctor-refresh', async () => (await import('./doctor/last-known.ts')).runDoctorRefresh(engine));
worker.register('integrity', integrityHandler);
worker.register('purge', makePurgeHandler(engine));
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 5e46399ecd..6ce8815e28 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -386,6 +386,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
export const META_CHECK_NAMES: ReadonlySet<string> = new Set([
// The one-time behavior-change disclosure, readable again here (read-only).
'behavior_changes',
+ // #7142: checks with no result from the last 24 h on a fast-tier or capped run (doctor/last-known.ts).
+ 'doctor_last_known',
// Agent operator wave E11: recent agent dead ends from the agent-contract event log.
'agent_contract',
'cycle_phase_scope',
diff --git a/test/doctor-fast-tier-7142.test.ts b/test/doctor-fast-tier-7142.test.ts
new file mode 100644
index 0000000000..bad9651f53
--- /dev/null
+++ b/test/doctor-fast-tier-7142.test.ts
@@ -0,0 +1,171 @@
+/**
+ * #7142: on a large brain most doctor checks reported unknown at the 90 s non-interactive budget, every run.
+ *
+ * - `--tier fast` runs only the ops and fast entries under a 10 s deadline and never a standard-only entry.
+ * - Every other check reports its last known result with its age (a recorded fail stays a fail); a check with no
+ * result from the last 24 h is named, with the others like it, in one doctor_last_known warning, so the report is
+ * never healthy or complete on it.
+ * - A standard entry that runs out of its budget reports its fresh last known checks instead of an unknown.
+ * - Only brain-wide runs read or write the results (`--only` and source-scoped runs do neither).
+ * - The doctor-refresh job records every standard database entry and no filesystem entry, and queues nothing;
+ * a fast run on Postgres queues one refresh per hour for the entries it could not report.
+ *
+ * Postgres arm: test/e2e/doctor-fast-tier-7142-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { computeDoctorReport, type Check } from '../src/commands/doctor.ts';
+import { runDoctorRegistry, DOCTOR_CHECK_REGISTRY, doctorRefreshRegistry } from '../src/commands/doctor/registry.ts';
+import { DOCTOR_TIERS, FAST_BUDGET_MS_DEFAULT, entryRunsAt, parseBudgetMs, startDoctorDeadline } from '../src/commands/doctor/budget.ts';
+import { LAST_KNOWN_OP, REFRESH_JOB, runDoctorRefresh } from '../src/commands/doctor/last-known.ts';
+import { resolverHealthEntry } from '../src/commands/doctor/checks/skill-group.ts';
+import { graphCoverageEntry } from '../src/commands/doctor/checks/graph-health.ts';
+import type { DoctorContext, DoctorEntry, DoctorTier } from '../src/commands/doctor/context.ts';
+import { help } from '../src/cli/help/doctor.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+
+const noProgress = new Proxy({}, { get: () => () => undefined }) as DoctorContext['progress'];
+
+function ctxFor(engine: BrainEngine, tier: DoctorTier, extra: Partial<DoctorContext> = {}): DoctorContext {
+ const args = ['--json', '--tier', tier];
+ return {
+ engine, args, jsonOutput: true, fastMode: false, doFix: false, dryRun: false, scope: 'brain', orphanRatioSourceId: undefined,
+ progress: noProgress, skillsDirResolution: { dir: null, source: 'none' }, skillsDir: null, autoFixReport: null, schemaVersion: 0,
+ connectionFailed: false, only: null, tier, deadline: startDoctorDeadline(args), lastKnown: 'cli', ...extra,
+ };
+}
+
+const ok = (name: string, message = 'fine'): Check => ({ name, status: 'ok', message });
+let standardRuns = 0;
+let slowStatus: Check['status'] = 'fail';
+let slowDelayMs = 0;
+const opsEntry: DoctorEntry = { name: 'ops_a', emits: ['ops_a'], tier: 'ops', run: async () => [ok('ops_a')] };
+const fastEntry: DoctorEntry = { name: 'fast_a', emits: ['fast_a'], tier: 'fast', run: async () => [ok('fast_a')] };
+const standardEntry: DoctorEntry = { name: 'slow_a', emits: ['slow_a', 'slow_b'], run: async () => {
+ standardRuns++;
+ if (slowDelayMs) await new Promise((r) => setTimeout(r, slowDelayMs));
+ return [{ name: 'slow_a', status: slowStatus, message: 'two pages broke' }];
+} };
+const entries = [opsEntry, fastEntry, standardEntry];
+const byName = (checks: Check[], name: string) => checks.find((c) => c.name === name);
+
+test('the CLI accepts every tier and --tier fast defaults to a 10 s deadline', () => {
+ const tierFlag = help.flags?.find((f) => f.name === '--tier') as { values?: string[] } | undefined;
+ expect(tierFlag?.values).toEqual([...DOCTOR_TIERS]);
+ expect(parseBudgetMs(['--tier', 'fast'], 'fast')).toBe(FAST_BUDGET_MS_DEFAULT);
+ expect([entryRunsAt('fast', 'fast'), entryRunsAt('ops', 'fast'), entryRunsAt(undefined, 'fast'), entryRunsAt('fast', 'standard'), entryRunsAt('fast', 'ops')]).toEqual([true, true, false, true, false]);
+});
+
+for (const kind of testBackends()) {
+ describe(`#7142 doctor fast tier and last known results (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void> = async () => undefined;
+
+ beforeAll(async () => {
+ if (kind === 'pglite') {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ } else {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engine = pg.engine; close = pg.close;
+ }
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ const clear = () => engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [LAST_KNOWN_OP]);
+ const recorded = async () => (await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op = $1 ORDER BY fingerprint', [LAST_KNOWN_OP])).map((r) => r.fingerprint);
+
+ test('fast runs never run a standard entry; unmeasured checks are one unknown warning, then last known results with their status and age', async () => {
+ await clear();
+ standardRuns = 0; slowStatus = 'fail'; slowDelayMs = 0;
+ const first = await runDoctorRegistry(ctxFor(engine, 'fast'), entries);
+ expect(standardRuns).toBe(0);
+ expect(first.map((c) => c.name)).toEqual(['ops_a', 'fast_a', 'doctor_last_known']);
+ const unmeasured = byName(first, 'doctor_last_known')!;
+ expect(unmeasured.status).toBe('warn');
+ expect(unmeasured.details).toMatchObject({ health: 'unknown', unknown_checks: ['slow_a', 'slow_b'] });
+ expect(unmeasured.message).toContain('never measured');
+ const firstReport = computeDoctorReport(first, { run: { tier: 'fast', startedAt: Date.now(), budgetMs: FAST_BUDGET_MS_DEFAULT } });
+ expect(firstReport.status).not.toBe('healthy');
+ expect(firstReport.complete).toBe(false);
+ expect(firstReport.unknown_sections).toEqual(['slow_a', 'slow_b']);
+ expect(await recorded()).toEqual([]);
+
+ await runDoctorRegistry(ctxFor(engine, 'standard'), entries);
+ expect(standardRuns).toBe(1);
+ expect(await recorded()).toEqual(['fast_a', 'ops_a', 'slow_a']);
+
+ const second = await runDoctorRegistry(ctxFor(engine, 'fast'), entries);
+ expect(standardRuns).toBe(1);
+ const served = byName(second, 'slow_a')!;
+ expect(served.status).toBe('fail');
+ expect(served.message).toMatch(/^Last known, under a minute ago \(not run by the fast tier\): two pages broke/);
+ expect(served.details?.last_known).toMatchObject({ reason: 'not_in_tier' });
+ expect(byName(second, 'doctor_last_known')).toBeUndefined();
+ const secondReport = computeDoctorReport(second, { run: { tier: 'fast', startedAt: Date.now(), budgetMs: FAST_BUDGET_MS_DEFAULT } });
+ expect(secondReport.status).toBe('unhealthy');
+ expect(secondReport.complete).toBe(false);
+ expect(secondReport.last_known_sections).toEqual(['slow_a']);
+
+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys = jsonb_set(completed_keys, '{0,measured_at}', '"2020-01-01T00:00:00.000Z"') WHERE op = $1`, [LAST_KNOWN_OP]);
+ const stale = await runDoctorRegistry(ctxFor(engine, 'fast'), entries);
+ expect(byName(stale, 'slow_a')).toBeUndefined();
+ expect(byName(stale, 'doctor_last_known')!.message).toContain('their last results are too old');
+ }, 60_000);
+
+ test('a standard entry that runs out of its budget reports its fresh last known checks instead of an unknown', async () => {
+ await clear();
+ slowStatus = 'warn'; slowDelayMs = 0;
+ await runDoctorRegistry(ctxFor(engine, 'standard'), entries);
+ slowDelayMs = 800;
+ const checks = await runDoctorRegistry(ctxFor(engine, 'standard', { entryBudgetOverrideMs: 200 }), entries);
+ const slow = checks.filter((c) => c.name === 'slow_a' || c.name === 'slow_b');
+ expect(slow).toHaveLength(1);
+ expect(slow[0]!.status).toBe('warn');
+ expect(slow[0]!.details?.last_known).toMatchObject({ reason: 'budget' });
+ expect(slow[0]!.message).toContain('not finished within this run\'s budget');
+ slowDelayMs = 0;
+ }, 60_000);
+
+ test('--only and source-scoped runs neither read nor write last known results', async () => {
+ await clear();
+ await runDoctorRegistry(ctxFor(engine, 'standard', { only: new Set(['slow_a']) }), entries);
+ await runDoctorRegistry(ctxFor(engine, 'standard', { sourceIds: ['default'] }), entries);
+ await runDoctorRegistry(ctxFor(engine, 'standard', { orphanRatioSourceId: 'default' }), entries);
+ expect(await recorded()).toEqual([]);
+ const scoped = await runDoctorRegistry(ctxFor(engine, 'fast', { sourceIds: ['default'] }), entries);
+ expect(byName(scoped, 'doctor_last_known')).toBeUndefined();
+ }, 60_000);
+
+ test('the doctor-refresh job records every standard database entry, no filesystem entry, and queues nothing', async () => {
+ await clear();
+ const jobsBefore = (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs WHERE name = $1', [REFRESH_JOB]))[0]!.n;
+ const result = await runDoctorRefresh(engine);
+ const rows = await recorded();
+ expect(rows).toContain(graphCoverageEntry.name);
+ expect(rows).not.toContain(resolverHealthEntry.name);
+ const refreshNames = new Set(doctorRefreshRegistry().map((e) => e.name));
+ expect(rows.every((r) => refreshNames.has(r))).toBe(true);
+ expect(DOCTOR_CHECK_REGISTRY.indexOf(resolverHealthEntry)).toBeGreaterThanOrEqual(0);
+ expect(result.recorded).toBeGreaterThan(0);
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs WHERE name = $1', [REFRESH_JOB]))[0]!.n).toBe(jobsBefore);
+ }, 180_000);
+
+ if (kind === 'postgres') {
+ test('a fast run queues one background refresh per hour for the checks it could not report', async () => {
+ await clear();
+ await engine.executeRaw('DELETE FROM minion_jobs WHERE name = $1', [REFRESH_JOB]);
+ const first = await runDoctorRegistry(ctxFor(engine, 'fast'), entries);
+ await runDoctorRegistry(ctxFor(engine, 'fast'), entries);
+ const jobs = await engine.executeRaw<{ id: number }>('SELECT id FROM minion_jobs WHERE name = $1', [REFRESH_JOB]);
+ expect(jobs).toHaveLength(1);
+ expect(byName(first, 'doctor_last_known')!.details?.refresh_job).toBe(Number(jobs[0]!.id));
+ }, 60_000);
+ }
+ });
+}
diff --git a/test/e2e/doctor-fast-tier-7142-postgres.test.ts b/test/e2e/doctor-fast-tier-7142-postgres.test.ts
new file mode 100644
index 0000000000..0f9fcc4f9e
--- /dev/null
+++ b/test/e2e/doctor-fast-tier-7142-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../doctor-fast-tier-7142.test.ts'));