Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
doctor, sync status: bounded reads (#6803 lane C, wip rebuild)
garrytan5a3ba912963c
diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.tsindex 33f037e10b..0e794b1eef 100644--- a/src/cli/commands/doctor.ts+++ b/src/cli/commands/doctor.ts@@ -57,6 +57,10 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<voidconst { startDoctorDeadline } = await import('../../commands/doctor/budget.ts');let deadline: import('../../commands/doctor/budget.ts').DoctorDeadline;try { deadline = startDoctorDeadline(args); } catch (error) { await renderDoctorParamError(error, args); return; }+ // #6803 C5: a plain non-interactive --json run caps its check run (started after connect and migrations).+ const { nonInteractiveDefaultBudget, defaultBudgetNotice } = await import('../../commands/doctor/default-budget.ts');+ const deferred = nonInteractiveDefaultBudget(args, { stderrIsTty: !!process.stderr.isTTY });+ if (deferred !== null) Object.assign(deadline, { deferredBudgetMs: deferred, deferredNotice: defaultBudgetNotice(deferred) });// Doctor runs filesystem checks first (no DB needed), then DB checks.// --fast skips DB checks entirely.diff --git a/src/cli/main.ts b/src/cli/main.tsindex ca0958f278..a397b94119 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -2436,7 +2436,7 @@ async function prepareConnectedDispatch(command: string, args: string[]): Promis// the only thing that stops the cron orphan-pileup. Disposed in the finally.let syncWatchdog: { dispose(): void } | null = null;// #6340: `sync status` / `sync unblock` read and schedule on the brain's own engine: no watchdog, no serve delegation (a delegate would refuse the subcommand).- const syncOperator = command === 'sync' && (args[0] === 'status' || args[0] === 'unblock');+ const syncOperator = command === 'sync' && (await import('../commands/sync/operator.ts')).syncOperatorVerb(args) !== null;if (command === 'sync' && !syncOperator) {try {const { resolveSyncHardDeadline } = await import('../commands/sync.ts');diff --git a/src/cli/op-notices.ts b/src/cli/op-notices.tsindex 4d562857fc..992be0d2de 100644--- a/src/cli/op-notices.ts+++ b/src/cli/op-notices.ts@@ -20,8 +20,8 @@ export function captureOpNotice(n: Notice): void {/** #6696 (A4): a local write's output carries the capacity notices (60 s snapshot, hourly per scope); a failed read adds none. */export async function captureCapacityNotices(engine: import('../core/engine.ts').BrainEngine): Promise<void> {- const { capacityNotices } = await import('../core/persistence/capacity-snapshot.ts');- for (const notice of await capacityNotices(engine).catch(() => [])) pending.push(notice);+ const { capacityNotices, CAPACITY_READ_WAIT_MS } = await import('../core/persistence/capacity-snapshot.ts');+ for (const notice of await capacityNotices(engine, { throttle: true, deadlineAt: Date.now() + CAPACITY_READ_WAIT_MS }).catch(() => [])) pending.push(notice);}/** Drain the captured notices into the result (`--json` objects) and/or a stderr string. */diff --git a/src/commands/config.ts b/src/commands/config.tsindex 26da2f2166..9764d11dfe 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -66,7 +66,7 @@ const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set([// #5232: the CLI resolves its write wait before choosing a transport, engine-free.'persistence.write_wait_ms',// Engine graduation opt-out: the pre-connect migrate router reads it engine-free.- 'migrate.graduation',+ 'migrate.graduation', 'doctor.default_budget_ms', // #6803: the CLI doctor reads it pre-connect (commands/doctor/default-budget.ts)]);/** #5489: every self_upgrade.* reader (cli.ts startup check, autopilot,@@ -108,7 +108,7 @@ async function unsetFilePlaneKey(key: string): Promise<boolean> {const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');const cfg = loadConfigFileOnly();const dot = key.indexOf('.');- const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade' | 'persistence' | 'migrate';+ const top = key.slice(0, dot) as 'push' | 'hooks' | 'backup' | 'mcp' | 'self_upgrade' | 'persistence' | 'migrate' | 'doctor';const leaf = key.slice(dot + 1);const branch = cfg?.[top] as Record<string, unknown> | undefined;if (!cfg || !branch || !(leaf in branch)) return false;@@ -546,8 +546,8 @@ async function setFilePlaneKey(key: string, value: string, tail: string[]): Promcfg.backup = { ...(cfg.backup ?? {}), check_enabled: on };saveConfig(cfg);console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);- } else if (key === 'persistence.write_wait_ms') {- await setFileWriteWait(cfg, value, saveConfig);+ } else if (key === 'persistence.write_wait_ms') { await setFileWriteWait(cfg, value, saveConfig);+ } else if (key === 'doctor.default_budget_ms') { (await import('./doctor/default-budget.ts')).setDoctorDefaultBudget(cfg, value, saveConfig);} else if (key === 'migrate.graduation') {const on = isConfigTruthy(value);cfg.migrate = { ...(cfg.migrate ?? {}), graduation: on };diff --git a/src/commands/doctor/budget.ts b/src/commands/doctor/budget.tsindex 27e565b072..4be5e137ed 100644--- a/src/commands/doctor/budget.ts+++ b/src/commands/doctor/budget.ts@@ -4,20 +4,29 @@* `--tier ops|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). Every entry also has its own budget- * (`doctor.entry_budget_ms`, default 15000; the remaining overall time when- * that is shorter).+ * for the other tiers; `--budget-ms 0`: none). A plain non-interactive CLI+ * `gbrain doctor --json` caps its check run at `doctor.default_budget_ms`+ * (./default-budget.ts), started after connect and migrations. Every entry also+ * has its own budget (`doctor.entry_budget_ms`, default 15000; the remaining+ * overall time when that is shorter; under `--only` with an explicit+ * `--budget-ms`, the overall budget).** An entry past its budget reports each check it emits with the shared unknown* convention: `status: 'warn'`, `details.health: 'unknown'`,- * `details.reason: 'budget'`, `details.exact: false`, `elapsed_ms`. Under- * `--tier ops` the entry reads through `deadlineEngine`, whose raw statements- * carry the absolute deadline to the server (a transaction-local+ * `details.reason: 'budget'`, `details.limit` (which budget), `details.exact:+ * false`, `elapsed_ms`. On every tier the entry reads through the run's+ * deadline-bound engine (src/core/statement-deadline.ts) under its own deadline:+ * its raw statements carry that deadline to the server (a transaction-local* `statement_timeout` recomputed after the pool wait, and an abort of the pool- * wait itself at the deadline), so no doctor backend outlives the report.+ * wait itself), a statement after it is never sent, and a cancelled statement+ * marks the entry expired even when the check caught the error, so no doctor+ * backend outlives its entry and the next entry starts with a fresh deadline.+ * PGLite gets only the refusal before each statement: one already running+ * cannot be pre-empted.*/-import type { BrainEngine } from '../../core/engine.ts';+import { AGENT_TOOL_LIMIT_MS } from '../../core/agent-output.ts';import { opError } from '../../core/ops/contract.ts';+import { StatementDeadlineError } from '../../core/statement-deadline.ts';import type { Check, DoctorReport } from '../doctor.ts';import { agentFix } from './check-fix.ts';import type { DoctorTier } from './context.ts';@@ -29,18 +38,27 @@ export const OPS_BUDGET_MS_DEFAULT = 4000;export const ENTRY_BUDGET_KEY = 'doctor.entry_budget_ms';export const ENTRY_BUDGET_MS_DEFAULT = 15_000;-/** The deadline of one doctor run: `deadlineAt` is absolute epoch ms, null without an overall budget. */+/**+ * The deadline of one doctor run: `deadlineAt` is absolute epoch ms, null without an overall budget.+ * `explicit`: `--budget-ms` was given. `deferredBudgetMs`: the non-interactive default, started when the+ * check run starts (`startDeferredDeadline`), so connect and migrations stay outside it.+ */export interface DoctorDeadline {startedAt: number;budgetMs: number | null;deadlineAt: number | null;+ explicit?: boolean;+ deferredBudgetMs?: number;+ /** The stderr line the deferred default prints when the check run starts (a run refused before it prints nothing). */+ deferredNotice?: string;+ nonInteractiveDefault?: boolean;}/** Thrown (and caught by the runner) when a read starts after the deadline passed. */-export class DoctorBudgetError extends Error {- readonly code = 'doctor_budget';- constructor(readonly elapsedMs: number) {- super(`The doctor budget ran out after ${elapsedMs} ms.`);+export class DoctorBudgetError extends StatementDeadlineError {+ override readonly code = 'doctor_budget';+ constructor(elapsedMs: number) {+ super(elapsedMs, `The doctor budget ran out after ${elapsedMs} ms.`);this.name = 'DoctorBudgetError';}}@@ -63,21 +81,38 @@ export function parseDoctorTier(args: readonly string[]): DoctorTier {why: 'The ops tier answers the operational questions (capacity, failures, embedding, sync, compaction, serve build) in seconds.' } });}-/** `--budget-ms <n>` (a positive integer), else the tier default. */+/** `--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;const n = Number(raw);- if (!Number.isSafeInteger(n) || n < 1) {- throw opError('invalid_params', `--budget-ms must be a positive integer number of milliseconds (got ${raw}).`, 'Example: --budget-ms 4000.');+ 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.');}- return n;+ return n === 0 ? null : n;}/** The deadline of a run starting now (call it before connecting). */export function startDoctorDeadline(args: readonly string[], now = Date.now()): DoctorDeadline {const budgetMs = parseBudgetMs(args, parseDoctorTier(args));- return { startedAt: now, budgetMs, deadlineAt: budgetMs === null ? null : now + budgetMs };+ return { startedAt: now, budgetMs, deadlineAt: budgetMs === null ? null : now + budgetMs, explicit: flagValue(args, '--budget-ms') !== undefined };+}++/** The non-interactive default starts with the check run (after connect and migrations), and says so then. */+export function startDeferredDeadline(deadline: DoctorDeadline | undefined, now = Date.now()): void {+ if (!deadline || deadline.deferredBudgetMs === undefined || deadline.deadlineAt !== null) return;+ Object.assign(deadline, { startedAt: now, budgetMs: deadline.deferredBudgetMs, deadlineAt: now + deadline.deferredBudgetMs, nonInteractiveDefault: true });+ if (deadline.deferredNotice) process.stderr.write(deadline.deferredNotice);+ delete deadline.deferredBudgetMs;+ delete deadline.deferredNotice;+}++/** Time a scan keeps before its entry's deadline to report what it read. */+export const SCAN_REPORT_RESERVE_MS = 250;++/** #6803 C3: a scan's wall-clock end: its own timeout, or its entry's (and so the run's) deadline less the report reserve when sooner. */+export function scanDeadline(ctx: { entryDeadlineAt?: number }, ownTimeoutMs: number, now = Date.now()): number {+ 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). */@@ -88,28 +123,6 @@ export function entryRunsAt(entryTier: DoctorTier | undefined, tier: DoctorTier)return true;}-/**- * The engine an ops entry reads through: every raw statement carries the- * absolute deadline (server-side bound recomputed after the pool wait; the pool- * wait aborts at the deadline). A statement that would start after the deadline- * is not sent. PGLite has one in-process connection and no other session to wait- * on, so it is returned as it is.- */-export function deadlineEngine(engine: BrainEngine, deadline: DoctorDeadline): BrainEngine {- const deadlineAt = deadline.deadlineAt;- if (deadlineAt === null || engine.kind !== 'postgres') return engine;- return new Proxy(engine, { get(target, key) {- if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: { signal?: AbortSignal; timeoutMs?: number }) => {- const left = deadlineAt - Date.now();- if (left <= 0) throw new DoctorBudgetError(Date.now() - deadline.startedAt);- const signal = opts?.signal ? AbortSignal.any([opts.signal, AbortSignal.timeout(left)]) : AbortSignal.timeout(left);- return target.executeRaw(sql, params, { signal, timeoutMs: Math.min(left, opts?.timeoutMs ?? left), deadlineAt });- };- const value = Reflect.get(target, key, target);- return typeof value === 'function' ? value.bind(target) : value;- } });-}-const EXPIRED: unique symbol = Symbol('doctor_budget_expired');/** Resolves `work`, or `EXPIRED` once `ms` passes (the work keeps running; its result is dropped). */@@ -130,13 +143,33 @@ export function budgetExpired(value: unknown): value is BudgetExpired {return value === EXPIRED;}-/** One check an entry could not finish within its budget, in the shared unknown convention. */-export function budgetUnknownCheck(name: string, elapsedMs: number, budgetMs: number): Check {+/** Which budget stopped an entry: its own (`doctor.entry_budget_ms`) or the run's overall deadline. */+export type BudgetLimit = 'entry' | 'overall';++/** A rerun alone gets this many times the budget it ran out of (the time it needs is unknown: the budget cut it off). */+const RERUN_BUDGET_FACTOR = 10;++/** Headroom under AGENT_TOOL_LIMIT_MS for the process start and connect around a rerun. */+const AGENT_RERUN_HEADROOM_MS = 10_000;++/**+ * One check an entry could not finish within its budget, in the shared unknown convention. The fix reruns the+ * check alone with `--budget-ms N` (which `--only` makes its entry budget), N ten times the budget it ran out of:+ * the agent's while N fits an agent tool call (AGENT_TOOL_LIMIT_MS), else the user's to run in a terminal.+ */+export function budgetUnknownCheck(name: string, elapsedMs: number, budgetMs: number, limit: BudgetLimit = 'entry'): Check {+ const agentCap = AGENT_TOOL_LIMIT_MS - AGENT_RERUN_HEADROOM_MS;+ const wanted = Math.ceil(Math.max(elapsedMs, budgetMs, 1) * RERUN_BUDGET_FACTOR / 1000) * 1000;+ const n = wanted <= agentCap || elapsedMs >= agentCap ? wanted : agentCap;+ const argv = ['gbrain', 'doctor', '--only', name, '--budget-ms', String(n), '--json'];+ const which = limit === 'overall' ? `the run's overall budget (${budgetMs} ms: --budget-ms or doctor.default_budget_ms)` : `its per-check budget (${budgetMs} ms, doctor.entry_budget_ms)`;+ const why = `Runs only this check with a ${n} ms budget, above the ${elapsedMs} ms it already took; read-only.`;return {name, status: 'warn', elapsed_ms: elapsedMs,- message: `Not finished within the doctor budget (${budgetMs} ms). Health is unknown, not clear; rerun this check alone: gbrain doctor --only ${name} --json`,- details: { health: 'unknown', reason: 'budget', exact: false, elapsed_ms: elapsedMs, budget_ms: budgetMs },- fix: agentFix(['gbrain', 'doctor', '--only', name, '--json'], 'Runs only this check, without the deadline of a full run; read-only.', name),+ message: `Not finished within ${which}. Health is unknown, not clear; rerun this check alone: ${argv.join(' ')}`,+ details: { health: 'unknown', reason: 'budget', limit, exact: false, elapsed_ms: elapsedMs, budget_ms: budgetMs, rerun_budget_ms: n },+ fix: n <= agentCap ? agentFix(argv, why, name)+ : { argv, consent: [], actor: 'user', requires_exclusive: false, why: `${why} It can run longer than an agent tool call, so run it in a terminal.` },};}@@ -162,8 +195,8 @@ export function tierFields(checks: Check[], run: DoctorRunSummary): Pick<DoctorRreturn { tier: run.tier, complete: unknown.length === 0, unknown_sections: unknown, elapsed_ms: Date.now() - run.startedAt, budget_ms: run.budgetMs };}-/** The run summary a report carries: only when the caller chose a tier or a budget, so default output keeps its shape. */+/** The run summary a report carries: when the caller chose a tier or a budget, or the non-interactive default capped the run. */export function doctorRunSummary(args: readonly string[], deadline: DoctorDeadline): DoctorRunSummary | undefined {- if (!args.some((a) => a === '--tier' || a.startsWith('--tier=') || a === '--budget-ms' || a.startsWith('--budget-ms='))) return undefined;+ if (!deadline.nonInteractiveDefault && !args.some((a) => a === '--tier' || a.startsWith('--tier=') || a === '--budget-ms' || a.startsWith('--budget-ms='))) return undefined;return { tier: parseDoctorTier(args), startedAt: deadline.startedAt, budgetMs: deadline.budgetMs };}diff --git a/src/commands/doctor/capacity-memo.ts b/src/commands/doctor/capacity-memo.tsnew file mode 100644index 0000000000..78be10ed71--- /dev/null+++ b/src/commands/doctor/capacity-memo.ts@@ -0,0 +1,39 @@+/**+ * #6803 C4: one capacity forecast per doctor run, shared by persistence_capacity+ * and persistence_request_growth (it used to run twice, each a whole-table read).+ * It reads under the run's overall deadline, not the deadline of the entry that+ * started it, so an entry that runs out of time mid-forecast does not cancel it+ * for a later entry. A forecast the deadline refused or cancelled is dropped+ * from the memo and marks the waiting entry expired, so a later entry reads it+ * again or reports unknown, never a counter-only verdict. Outside a doctor run+ * (no run memo) it reads directly.+ */+import { readCapacityForecast, type CapacityForecast } from '../../core/persistence/capacity-forecast.ts';+import type { JournalLimits, SqlEngine } from '../../core/persistence/model.ts';+import { currentStatementDeadline, deadlineBoundEngine, deadlineFailure, withStatementDeadline } from '../../core/statement-deadline.ts';++const KEY = 'capacity_forecast';++export function doctorCapacityForecast(engine: SqlEngine & { kind?: string }, opts: { limits: JournalLimits }): Promise<CapacityForecast> {+ const scope = currentStatementDeadline();+ const memo = scope?.memo;+ if (!scope || !memo) return readCapacityForecast(engine, opts);+ let shared = memo.get(KEY) as Promise<CapacityForecast> | undefined;+ if (!shared) {+ const created: Promise<CapacityForecast> = withStatementDeadline({ startedAt: Date.now(), deadlineAt: scope.runDeadlineAt ?? null, expired: false, memo },+ () => readCapacityForecast(deadlineBoundEngine(engine), opts));+ created.catch((error: unknown) => { if (deadlineFailure(error) && memo.get(KEY) === created) memo.delete(KEY); });+ memo.set(KEY, created);+ shared = created;+ }+ return shared.catch((error: unknown) => {+ if (deadlineFailure(error)) scope.expired = true;+ throw error;+ });+}++/** A check's `.catch` for the forecast: no forecast (null) on an ordinary failure; a deadline failure propagates, so the check is unknown. */+export function forecastOrNull(error: unknown): null {+ if (deadlineFailure(error)) throw error;+ return null;+}diff --git a/src/commands/doctor/checks/content-quality.ts b/src/commands/doctor/checks/content-quality.tsindex 14c833edb8..23d329576a 100644--- a/src/commands/doctor/checks/content-quality.ts+++ b/src/commands/doctor/checks/content-quality.ts@@ -13,6 +13,7 @@ import { checkUnverifiedExtractions } from './extraction-sync.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';import { agentFix, checkError, doctorVerify } from '../check-fix.ts';+import { scanDeadline } from '../budget.ts';async function runContentSanity(ctx: DoctorContext): Promise<Check[]> {const { args, progress } = ctx;@@ -357,10 +358,11 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {progress.heartbeat('frontmatter_integrity');const fmHb = startHeartbeat(progress, 'scanning frontmatter…');const { frontmatterScanTimeoutMs, frontmatterRepairableFromReport } = await import('./frontmatter-repairable.ts');- const fmTimeoutMs = frontmatterScanTimeoutMs();+ // #6803 C3: the walk also stops at the entry's (and so the run's) deadline, and reports what it read.+ const fmDeadline = scanDeadline(ctx, frontmatterScanTimeoutMs());+ const fmTimeoutMs = Math.max(0, fmDeadline - Date.now());try {const { scanBrainSources } = await import('../../../core/brain-writer.ts');- const fmDeadline = Date.now() + fmTimeoutMs;const fmAbort = AbortSignal.timeout(fmTimeoutMs);// Per-source DB denominator. Coarse — DB pages and on-disk syncable// files are overlapping but not identical (unsynced disk files,@@ -368,6 +370,7 @@ async function runFrontmatter(ctx: DoctorContext): Promise<Check[]> {// message makes the mismatch honest. Failure of the COUNT degrades to// null and the message falls back to bare numerator.const dbPageCountForSource = async (sourceId: string): Promise<number | null> => {+ if (Date.now() >= fmDeadline) return null;try {const rows = await engine.executeRaw<{ n: string }>(`SELECT COUNT(*)::text AS n FROM pages WHERE source_id = $1 AND deleted_at IS NULL`,diff --git a/src/commands/doctor/checks/fence-integrity.ts b/src/commands/doctor/checks/fence-integrity.tsindex ee19f42ab7..03569101f7 100644--- a/src/commands/doctor/checks/fence-integrity.ts+++ b/src/commands/doctor/checks/fence-integrity.ts@@ -34,6 +34,7 @@import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { agentFix, doctorVerify } from '../check-fix.ts';+import { scanDeadline } from '../budget.ts';import { auditUnadoptableFacts, planUnfencedFacts, unboundRefusedSentence, type UnadoptableFactRecord, type UnfencedFactsOutcome } from '../../../core/facts/unfenced-facts.ts';import { UNBOUND_SOURCE_DOCS, UNBOUND_WRITE_KEY } from '../../../core/persistence/unbound-source.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -141,10 +142,13 @@ function unrenderableSentence(found: Omit<UnrenderableLegacyFacts, 'unbound'>):+ (found.complete ? '' : ' The scan did not finish within its time budget, so more rows may be affected; run gbrain doctor --only fence_integrity again.');}-/** The check's verdict after a bounded census scan (`sourceIds`: only those sources, for a scoped remote caller). */-export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMs?: number; now?: () => Date; sourceIds?: string[] } = {}): Promise<Omit<Check, 'name'>> {+/**+ * The check's verdict after a bounded census scan (`sourceIds`: only those sources, for a scoped remote caller).+ * `deadlineAt` (wall clock): the doctor entry's deadline; both scans stop at it when it comes before their timeout.+ */+export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutMs?: number; now?: () => Date; sourceIds?: string[]; deadlineAt?: number } = {}): Promise<Omit<Check, 'name'>> {const now = opts.now ?? (() => new Date());- const timeoutMs = opts.timeoutMs ?? fenceScanTimeoutMs();+ const timeoutMs = Math.max(0, Math.min(opts.timeoutMs ?? fenceScanTimeoutMs(), (opts.deadlineAt ?? Infinity) - Date.now()));const runs = await runFenceCensus(engine, { deadline: now().getTime() + timeoutMs, now, ...(opts.sourceIds ? { sourceIds: opts.sourceIds } : {}) });const census = await summarizeFenceCensus(engine, opts.sourceIds, runs);const from = new Date(now().getTime() - (TREND_DAYS - 1) * 86_400_000).toISOString().slice(0, 10);@@ -159,7 +163,7 @@ export async function fenceIntegrityResult(engine: BrainEngine, opts: { timeoutM// T2: legacy fence repairs written and imported but not committed yet (counts for a scoped remote caller, paths locally).const uncommitted = await readUncommittedFenceRepairs(engine, opts.sourceIds ?? census.map(c => c.source_id)).catch(() => []);// The audit's deadline is on the wall clock (it bounds real work; the census's `now` is for dates).- const { unbound, ...unrenderable } = await unrenderableLegacyFacts(engine, opts.sourceIds, Date.now() + timeoutMs)+ const { unbound, ...unrenderable } = await unrenderableLegacyFacts(engine, opts.sourceIds, Math.min(Date.now() + timeoutMs, opts.deadlineAt ?? Infinity)).catch((): UnrenderableLegacyFacts => ({ total: 0, complete: false, pages: [], unbound: [] }));const details = {total, partial: partial.length > 0, partial_sources: partial.map(c => c.source_id), sources: census, trend, warn_at_normalized_7d: FENCE_NORMALIZATION_WARN_7D,@@ -228,7 +232,7 @@ async function runFenceIntegrity(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];ctx.progress.heartbeat('fence_integrity');try {- checks.push({ name: 'fence_integrity', ...await fenceIntegrityResult(engine) });+ checks.push({ name: 'fence_integrity', ...await fenceIntegrityResult(engine, { deadlineAt: scanDeadline(ctx, fenceScanTimeoutMs()) }) });} catch (error) {checks.push({ name: 'fence_integrity', status: 'warn', fix_unavailable_reason: 'check_errored', details: { health: 'unknown' },message: `The fence census could not run: ${error instanceof Error ? error.message : String(error)}. Fence health is unknown; run gbrain doctor --only fence_integrity again.` });diff --git a/src/commands/doctor/checks/persistence-capacity.ts b/src/commands/doctor/checks/persistence-capacity.tsindex 64b7c38957..d9f8574567 100644--- a/src/commands/doctor/checks/persistence-capacity.ts+++ b/src/commands/doctor/checks/persistence-capacity.ts@@ -2,7 +2,8 @@ import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';import { capacityDiagnostics } from '../../../core/persistence/diagnostics.ts';import { oneYearCapacity, readJournalLimits } from '../../../core/persistence/limits.ts';-import { readCapacityForecast, type CapacityForecast } from '../../../core/persistence/capacity-forecast.ts';+import type { CapacityForecast } from '../../../core/persistence/capacity-forecast.ts';+import { doctorCapacityForecast, forecastOrNull } from '../capacity-memo.ts';import { capacityVerify } from '../../../core/persistence/capacity-view.ts';import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from '../../../core/persistence/admission-origin.ts';@@ -25,7 +26,7 @@ export async function checkPersistenceCapacity(engine: BrainEngine): Promise<Cheterminal_bytes: string; recovery_bytes: string }>(`SELECT key,outstanding_count::text,intent_bytes::text,lifetime_ids::text,terminal_bytes::text,recovery_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%' ORDER BY key`);const limits = await readJournalLimits(engine);- const forecast: CapacityForecast | null = await readCapacityForecast(engine, { limits }).catch(() => null);+ const forecast: CapacityForecast | null = await doctorCapacityForecast(engine, { limits }).catch(forecastOrNull);const pause = await readBackgroundPauseShare(engine);const cumulative = capacityDiagnostics(counters, limits).filter(row => row.resource === 'lifetime_ids' || row.resource === 'terminal_bytes');const resources = [];diff --git a/src/commands/doctor/checks/persistence-requests.ts b/src/commands/doctor/checks/persistence-requests.tsindex 8c85fcbafe..0c9cd28067 100644--- a/src/commands/doctor/checks/persistence-requests.ts+++ b/src/commands/doctor/checks/persistence-requests.ts@@ -8,7 +8,9 @@ import { readPreparationPolicy } from '../../../core/persistence/switches.ts';import { resolvePrepare, resolveSessionTimeouts } from '../../../core/db.ts';import { agentFix, checkError, doctorVerify } from '../check-fix.ts';import { lostCallerWrites } from '../../../core/repair/failed-writes.ts';-import { readCapacityForecast, readCapacityThresholds } from '../../../core/persistence/capacity-forecast.ts';+import { readCapacityThresholds } from '../../../core/persistence/capacity-forecast.ts';+import { doctorCapacityForecast, forecastOrNull } from '../capacity-memo.ts';+import { withStatementDeadline } from '../../../core/statement-deadline.ts';const WINDOW_DAYS = 7;const SAMPLE = 10_000;@@ -83,7 +85,7 @@ export async function requestGrowthCheck(engine: BrainEngine): Promise<Check> {const soon = scopes.filter(scope => scope.days_to_exhaustion !== null && scope.days_to_exhaustion < warnDays);// Every principal shares one brain-wide key, so each key gets the largest value any scope needs.const needed = new Map<string, number>();- const forecast = soon.length ? await readCapacityForecast(engine, { limits }).catch(() => null) : null;+ const forecast = soon.length ? await doctorCapacityForecast(engine, { limits }).catch(forecastOrNull) : null;for (const scope of soon) {const predicted = forecast?.rows.find(row => row.scope === scope.scope && row.resource === 'lifetime_ids');const value = predicted && predicted.per_day_7d > 0 ? predicted.recommended_limit@@ -191,7 +193,9 @@ export async function sessionTimeoutsCheck(engine: BrainEngine): Promise<Check>message: configured === null ? 'No session statement_timeout is configured (GBRAIN_STATEMENT_TIMEOUT=0).' : 'PGLite has no session to time out.' };}try {- const [row] = await engine.executeRaw<{ statement_timeout: string }>('SHOW statement_timeout');+ // #6803: read outside the doctor entry's statement deadline, whose transaction-local statement_timeout would+ // otherwise be what SHOW reports (a pooler's 0 would read as applied). SHOW touches no table.+ const [row] = await withStatementDeadline(null, () => engine.executeRaw<{ statement_timeout: string }>('SHOW statement_timeout'));const applied = row?.statement_timeout ?? null;// #6278: the live stall ran through a transaction-mode pooler (Supavisor :6543), which can also leave a cancelled// round-trip incomplete (backend in ClientRead). The engine settles those client-side; the pooler mode is still worth naming.diff --git a/src/commands/doctor/checks/sync-search.ts b/src/commands/doctor/checks/sync-search.tsindex d224778999..c81a29fb81 100644--- a/src/commands/doctor/checks/sync-search.ts+++ b/src/commands/doctor/checks/sync-search.ts@@ -47,7 +47,7 @@ import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';async function runSyncFreshness(ctx: DoctorContext): Promise<Check[]> {- const { orphanRatioSourceId, progress } = ctx;+ const { progress } = ctx;const engine = connectedEngine(ctx);const checks: Check[] = [];@@ -75,10 +75,6 @@ async function runSyncFreshness(ctx: DoctorContext): Promise<Check[]> {// v0.41.19.0 (Issue 5): sync --all consolidation nudge.progress.heartbeat('sync_consolidation');checks.push(await checkSyncConsolidation(engine));- // v0.42.7 (#1696): link-extraction lag. --source scopes it (explicit-only- // parse, like orphan_ratio); bare doctor stays brain-wide. Fix: extract --stale.- progress.heartbeat('links_extraction_lag');- checks.push(await checkLinksExtractionLag(engine, { sourceId: orphanRatioSourceId }));// v0.38 — full-cycle freshness, sibling to sync_freshness. Reads// last_full_cycle_at from sources.config; mirrors what autopilot's// per-source dispatch gate sees.@@ -108,7 +104,6 @@ export const syncFreshnessEntry: DoctorEntry = {'shared_skills_sources','backup_coverage','sync_consolidation',- 'links_extraction_lag','cycle_freshness','content_hash_duplicates','code_chunk_metadata',@@ -118,6 +113,27 @@ export const syncFreshnessEntry: DoctorEntry = {run: runSyncFreshness,};+/**+ * v0.42.7 (#1696): link-extraction lag. --source scopes it (explicit-only parse, like orphan_ratio); bare+ * doctor stays brain-wide. Fix: extract --stale. #6803 C2: its own entry, run with the cheap incident checks,+ * so a slow sync-freshness scan cannot take it down with it.+ */+async function runLinksExtractionLag(ctx: DoctorContext): Promise<Check[]> {+ const engine = connectedEngine(ctx);+ const checks: Check[] = [];+ if (engine !== null) {+ ctx.progress.heartbeat('links_extraction_lag');+ checks.push(await checkLinksExtractionLag(engine, { sourceId: ctx.orphanRatioSourceId }));+ }+ return checks;+}++export const linksExtractionLagEntry: DoctorEntry = {+ name: 'links_extraction_lag',+ emits: ['links_extraction_lag'],+ run: runLinksExtractionLag,+};+async function runSearchMode(ctx: DoctorContext): Promise<Check[]> {const { doFix, dryRun, progress } = ctx;const engine = connectedEngine(ctx);diff --git a/src/commands/doctor/context.ts b/src/commands/doctor/context.tsindex 27fc985bab..0afbeb655f 100644--- a/src/commands/doctor/context.ts+++ b/src/commands/doctor/context.ts@@ -78,6 +78,8 @@ export interface DoctorContext {deadline?: DoctorDeadline;/** #6696 B2: the remote caller's readable sources (run_doctor tier/only); undefined: brain-wide or `--source`. */sourceIds?: string[];+ /** #6803 C3: the running entry's absolute deadline (scans stop at it and report what they read); undefined: unbounded. */+ entryDeadlineAt?: number;/** #6696 B1: one `getHealth()` per run, shared by every entry that reads it (`doctorHealth`). */healthMemo?: Promise<BrainHealth>;}diff --git a/src/commands/doctor/default-budget.ts b/src/commands/doctor/default-budget.tsnew file mode 100644index 0000000000..7713e3d698--- /dev/null+++ b/src/commands/doctor/default-budget.ts@@ -0,0 +1,56 @@+/**+ * #6803 C5 (Decision 1): a plain non-interactive CLI `gbrain doctor --json`+ * (stderr not a terminal; no `--budget-ms`, `--tier`, `--remediate`,+ * `--remediation-plan` or `--fix`) caps its check run at+ * `doctor.default_budget_ms` (default 90000 ms, 0 off), so an agent's tool call+ * gets a report, with unknown checks named, instead of a timeout. The key is on+ * the file plane (~/.gbrain/config.json) and read before connecting; connect+ * and migrations are not counted. `--budget-ms 0` turns it off for one run.+ * MCP `run_doctor`, remote and ops paths never apply it.+ */+import type { GBrainConfig } from '../../core/config.ts';+import { loadConfigFileOnly } from '../../core/config.ts';++export const DEFAULT_BUDGET_KEY = 'doctor.default_budget_ms';+export const DEFAULT_BUDGET_MS = 90_000;+const EXPLICIT_MODE_FLAGS = ['--budget-ms', '--tier', '--remediate', '--remediation-plan', '--fix'];++/** A configured value: a whole number of ms (0: off), else null (not a valid value). */+export function parseDefaultBudgetValue(raw: unknown): number | null {+ const text = typeof raw === 'number' ? String(raw) : typeof raw === 'string' ? raw.trim() : '';+ if (!/^\d+$/.test(text)) return null;+ const n = Number(text);+ return Number.isSafeInteger(n) ? n : null;+}++/** `doctor.default_budget_ms` from the file plane; unset or not a whole number: the 90000 ms default. */+export function readDefaultBudgetMs(cfg: GBrainConfig | null = loadConfigFileOnly()): number {+ return parseDefaultBudgetValue(cfg?.doctor?.default_budget_ms) ?? DEFAULT_BUDGET_MS;+}++/** The check-run cap this CLI doctor run gets by default, or null (an interactive run, an explicit mode, or the key set to 0). */+export function nonInteractiveDefaultBudget(args: readonly string[], opts: { stderrIsTty: boolean; configuredMs?: number }): number | null {+ if (opts.stderrIsTty || !args.includes('--json')) return null;+ if (args.some(a => EXPLICIT_MODE_FLAGS.some(flag => a === flag || a.startsWith(`${flag}=`)))) return null;+ const ms = opts.configuredMs ?? readDefaultBudgetMs();+ return ms > 0 ? ms : null;+}++/** The one stderr line a capped run prints when its check run starts. */+export function defaultBudgetNotice(ms: number): string {+ return `[gbrain doctor] non-interactive run: the check run (not connect or migrations) is capped at ${ms} ms (${DEFAULT_BUDGET_KEY}); `+ + 'checks past it report health unknown. Off for one run: --budget-ms 0; off for good: gbrain config set doctor.default_budget_ms 0. '+ + 'On PGLite a statement already running cannot be stopped, so a check can finish late.\n';+}++/** `gbrain config set doctor.default_budget_ms <n>` (file plane). */+export function setDoctorDefaultBudget(cfg: GBrainConfig, value: string, saveConfig: (cfg: GBrainConfig) => void): void {+ const n = parseDefaultBudgetValue(value);+ if (n === null) {+ console.error(`[config] ${DEFAULT_BUDGET_KEY} must be a whole number of milliseconds (0 turns the non-interactive doctor budget off)`);+ process.exit(1);+ }+ cfg.doctor = { ...(cfg.doctor ?? {}), default_budget_ms: n };+ saveConfig(cfg);+ console.log(`Set ${DEFAULT_BUDGET_KEY} = ${n} (file plane: ~/.gbrain/config.json; --budget-ms overrides it for one run)`);+}diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex e0aafeab7f..87bdd3f471 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -89,7 +89,7 @@ import { connectorAccountMismatchEntry } from './checks/connector-account-mismatimport { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';import { grantNewOpsEntry } from './checks/grant-new-ops.ts';-import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';+import { linksExtractionLagEntry, syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';import { persistenceConsumersEntry, serveBuildDriftEntry } from './checks/persistence-consumers.ts';import { gitConvergenceEntry } from './checks/git-convergence.ts';import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';@@ -130,9 +130,10 @@ import {} from './checks/ops-sections.ts';import { STOP_DOCTOR, type DoctorContext, type DoctorEntry, type DoctorTier } from './context.ts';import {- BUDGET_EXPIRED, DoctorBudgetError, budgetExpired, type BudgetExpired, ENTRY_BUDGET_KEY, ENTRY_BUDGET_MS_DEFAULT, budgetUnknownCheck, deadlineEngine, entryRunsAt,- opsNotApplicableCheck, raceBudget,+ BUDGET_EXPIRED, DoctorBudgetError, budgetExpired, type BudgetExpired, ENTRY_BUDGET_KEY, ENTRY_BUDGET_MS_DEFAULT, budgetUnknownCheck, entryRunsAt,+ 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';@@ -170,6 +171,9 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [serveBuildDriftEntry,schemaPackConsistencyEntry,embeddingStateEntry,+ // #6803 C2: then the cheap incident checks, before any full scan (CHEAP_INCIDENT_CHECKS, pinned by name in test/doctor-entry-deadline-6803.test.ts).+ linksExtractionLagEntry,+ contentSanityEntry,pgvectorEntry,rlsEntry,schemaVersionEntry,@@ -195,7 +199,6 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [whoknowsEntry,crossModalEntry,markdownBodyEntry,- contentSanityEntry,quarantineEntry,frontmatterEntry,evalCaptureEntry,@@ -240,6 +243,15 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [searchModeEntry,];+/**+ * #6803 C2: checks that answer an incident in a few cheap reads. Every entry that emits one runs before the+ * first full scan, whichever topic module it lives in (keyed by check name, so a new entry emitting one of+ * these must join the group: test/doctor-entry-deadline-6803.test.ts).+ */+export const CHEAP_INCIDENT_CHECKS: ReadonlySet<string> = new Set([+ 'persistence_capacity', 'managed_sync_not_moving', 'text_projection_readiness', 'partial_embedding', 'links_extraction_lag',+]);+const CONNECTION_LANE: ReadonlySet<DoctorEntry> = new Set([offlineConnectionEntry, dbChecksGateEntry, connectionEntry, connectionGateEntry]);/** Every check name the registry can emit (the `--only` vocabulary). */@@ -293,22 +305,29 @@ function onlyResult(checks: Check[], only: ReadonlySet<string>, stopped: boolean* one `withGitListingCache` scope, so entries that list the same source* checkout share one `git ls-files` per listing.*- * #6696 B1: `ctx.tier` selects entries (`entryRunsAt`; the connection lane runs- * at every tier). Each entry runs under its budget: the per-entry budget- * (`doctor.entry_budget_ms`) clipped to the overall deadline, or under `--tier- * ops` the overall deadline alone with raw reads bounded on the server- * (`deadlineEngine`). An entry past its budget reports each check it emits as- * an unknown; an ops entry that is not applicable on PGLite reports- * `not_applicable`. Every check carries its entry's `elapsed_ms`.+ * #6696 B1 / #6803 C2: `ctx.tier` selects entries (`entryRunsAt`; the+ * connection lane runs at every tier). Each entry runs under its own deadline:+ * the per-entry budget (`doctor.entry_budget_ms`, read with a bounded+ * statement) clipped to the overall deadline; under `--tier ops`, or under+ * `--only` with an explicit `--budget-ms`, the overall deadline alone. The+ * entry reads through the run's deadline-bound engine with that deadline in+ * its async context, so its statements stop at it (src/core/statement-deadline.ts).+ * An entry past its budget, or whose statement was refused or cancelled at its+ * deadline (even when the check caught the error), reports each check it emits+ * as an unknown naming the budget that limited it; an ops entry that is not+ * applicable on PGLite reports `not_applicable`. Every check carries its+ * entry's `elapsed_ms`. `entries` defaults to the registry.*/-export function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {+export function runDoctorRegistry(ctx: DoctorContext, entries: readonly DoctorEntry[] = DOCTOR_CHECK_REGISTRY): Promise<Check[]> {return withGitListingCache(async () => {const tier = ctx.tier ?? 'standard';- // Under ops every entry, the connection lane included, reads through the deadline-bound engine.- if (tier === 'ops' && ctx.engine && ctx.deadline) ctx.engine = deadlineEngine(ctx.engine, ctx.deadline);+ startDeferredDeadline(ctx.deadline);+ if (ctx.engine) ctx.engine = deadlineBoundEngine(ctx.engine);+ const memo = new Map<string, Promise<unknown>>();+ const gateAt = entries.indexOf(connectionGateEntry);const checks: Check[] = [];let entryBudgetMs: number | null = null;- for (const entry of DOCTOR_CHECK_REGISTRY) {+ for (const entry of entries) {if (!selected(entry, ctx.only)) continue;if (!CONNECTION_LANE.has(entry) && !entryRunsAt(entry.tier, tier)) continue;const started = Date.now();@@ -317,29 +336,35 @@ export function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {checks.push(...emitted.map(opsNotApplicableCheck));continue;}- if (entryBudgetMs === null && ctx.engine && !ctx.fastMode && !ctx.connectionFailed && DOCTOR_CHECK_REGISTRY.indexOf(entry) > DOCTOR_CHECK_REGISTRY.indexOf(connectionGateEntry)) {+ if (entryBudgetMs === null && ctx.engine && !ctx.fastMode && !ctx.connectionFailed && gateAt >= 0 && entries.indexOf(entry) > gateAt) {entryBudgetMs = await readEntryBudget(ctx);}- const budgetMs = entryBudget(ctx, tier, CONNECTION_LANE.has(entry) ? null : entryBudgetMs, started);+ const overallOnly = tier === 'ops' || (!!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)));+ checks.push(...emitted.map((n) => budgetUnknownCheck(n, 0, ctx.deadline?.budgetMs ?? 0, 'overall')));continue;}- const run = entry.run(ctx)- .catch((error: unknown): BudgetExpired => { if (error instanceof DoctorBudgetError) return BUDGET_EXPIRED; throw error; });+ const scope: StatementDeadline = { startedAt: started, deadlineAt: budgetMs === null ? null : started + budgetMs, expired: false, memo, runDeadlineAt: ctx.deadline?.deadlineAt ?? null };+ ctx.entryDeadlineAt = scope.deadlineAt ?? undefined;+ const run = withStatementDeadline(scope, () => entry.run(ctx))+ .catch((error: unknown): BudgetExpired => { if (error instanceof StatementDeadlineError || scope.expired) return BUDGET_EXPIRED; throw error; });const result = budgetMs === null ? await run : await raceBudget(run, budgetMs);+ ctx.entryDeadlineAt = undefined;const elapsed = Date.now() - started;- if (budgetExpired(result)) {- checks.push(...emitted.map((n) => budgetUnknownCheck(n, elapsed, budgetMs ?? ctx.deadline?.budgetMs ?? 0)));+ 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)));continue;}if (result === STOP_DOCTOR) {// A connect the deadline ended: every check this tier would have run is unknown, so the report says what it does not know.if (ctx.connectError instanceof DoctorBudgetError) {- const at = DOCTOR_CHECK_REGISTRY.indexOf(entry);- for (const later of DOCTOR_CHECK_REGISTRY.slice(at + 1)) {+ const at = entries.indexOf(entry);+ for (const later of entries.slice(at + 1)) {if (CONNECTION_LANE.has(later) || !entryRunsAt(later.tier, tier) || !selected(later, ctx.only)) continue;- checks.push(...later.emits.filter((n) => !ctx.only || ctx.only.has(n)).map((n) => budgetUnknownCheck(n, ctx.connectError instanceof DoctorBudgetError ? ctx.connectError.elapsedMs : 0, ctx.deadline?.budgetMs ?? 0)));+ checks.push(...later.emits.filter((n) => !ctx.only || ctx.only.has(n)).map((n) => budgetUnknownCheck(n, ctx.connectError instanceof DoctorBudgetError ? ctx.connectError.elapsedMs : 0, ctx.deadline?.budgetMs ?? 0, 'overall')));}}return ctx.only ? onlyResult(checks, ctx.only, true) : checks;@@ -347,7 +372,7 @@ export function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {const pastDeadline = ctx.deadline?.deadlineAt != null && Date.now() >= ctx.deadline.deadlineAt;checks.push(...result.map((c) => {if (pastDeadline && c.details?.health === 'unknown' && c.details.reason === undefined) {- const unknown = budgetUnknownCheck(c.name, elapsed, ctx.deadline!.budgetMs ?? 0);+ 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;@@ -358,19 +383,27 @@ export function runDoctorRegistry(ctx: DoctorContext): Promise<Check[]> {});}-/** The time this entry may take: the per-entry budget (not under ops) clipped to the overall deadline; null: unbounded. */-function entryBudget(ctx: DoctorContext, tier: DoctorTier, perEntry: number | null, now: number): number | null {+/** 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 = tier === 'ops' ? null : perEntry;+ const own = overallOnly ? null : perEntry;if (overall === null) return own;return own === null ? overall : Math.min(own, overall);}-/** `doctor.entry_budget_ms` (a positive integer), else the default; an unreadable config keeps the default. */+/** Bound of the budget-config read (clipped to the overall deadline); past it the default applies. */+const SETUP_READ_MS = 2_000;++/** `doctor.entry_budget_ms` (a positive integer), else the default; a config read that is unreadable or outlives its bound keeps the default. */async function readEntryBudget(ctx: DoctorContext): Promise<number> {+ const startedAt = Date.now();+ const deadlineAt = Math.min(startedAt + SETUP_READ_MS, ctx.deadline?.deadlineAt ?? Infinity);try {- const raw = await ctx.engine!.getConfig(ENTRY_BUDGET_KEY);- const n = raw === null || raw === undefined ? NaN : Number(raw);+ const read = withStatementDeadline({ startedAt, deadlineAt, expired: false }, () =>+ ctx.engine!.executeRaw<{ value: string }>('SELECT value FROM config WHERE key=$1', [ENTRY_BUDGET_KEY]));+ const rows = await raceBudget(read, deadlineAt - startedAt);+ if (budgetExpired(rows)) { read.catch(() => undefined); return ENTRY_BUDGET_MS_DEFAULT; }+ const n = rows[0] === undefined ? NaN : Number(rows[0].value);return Number.isSafeInteger(n) && n > 0 ? n : ENTRY_BUDGET_MS_DEFAULT;} catch {return ENTRY_BUDGET_MS_DEFAULT;diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex d05022b78a..bdd9ce0226 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -193,6 +193,8 @@ Subcommands:committed in the last 10 minutes, each hold and thelast error with class / safe_actions / needs_human,and the next action (for an operator agent's loop).+ 'gbrain sync --status' is the same read (never a sync);+ sync refuses --preview, which it never reads.gbrain sync unblock --source <id> [--apply] [--no-llm] [--no-repair] [--json]Performs the safe action for every hold (re-screens aheld file whose edit is now committed, retries adiff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex c12ac5e28a..a993f8aadc 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -83,6 +83,35 @@ Runbook: docs/guides/sync-unblock-runbook.md`);}+/**+ * #6803: the operator verb a `gbrain sync` argument vector asks for, shared by+ * the CLI's pre-connect preflight (no watchdog, no owner delegation) and+ * `runSyncInner`. `gbrain sync --status` is the status read, the same as+ * `gbrain sync status` (it used to run a full sync, because nothing read the+ * flag). `--preview` and `--check` are read by no sync path, so a sync that+ * would silently run past them is refused.+ */+export function syncOperatorVerb(args: readonly string[]): 'status' | 'unblock' | null {+ if (args[0] === 'status' || args[0] === 'unblock') return args[0];+ if (args[0] === 'trigger') return null;+ const unread = args.find(a => a === '--preview' || a === '--check' || a.startsWith('--preview=') || a.startsWith('--check='));+ if (unread) {+ const flag = unread.split('=')[0];+ throw opError('invalid_params', `gbrain sync does not read ${flag}; it would have run a full sync.`,+ 'Preview a sync with --dry-run, or read where a source stands with gbrain sync status --source <id>.',+ { fix: { argv: ['gbrain', 'sync', ...args.filter(a => a !== unread && a !== '--dry-run'), '--dry-run'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'The same sync with --dry-run reports what it would import and writes nothing.' } });+ }+ return args.includes('--status') ? 'status' : null;+}++/** `runSyncInner`'s operator route: `sync --status` prints one hint, then runs exactly `sync status`. */+export async function runSyncOperator(engine: BrainEngine, verb: 'status' | 'unblock', args: string[]): Promise<void> {+ if (args[0] === verb) return verb === 'status' ? runSyncStatus(engine, args.slice(1)) : runSyncUnblock(engine, args.slice(1));+ process.stderr.write('[gbrain] sync --status is the status read, the same as gbrain sync status (it never syncs).\n');+ return runSyncStatus(engine, args.filter(a => a !== '--status'));+}+function sourceOf(args: string[]): string {const explicit = args.find((a, i) => args[i - 1] === '--source') ?? null;const source = resolveSourceIdEngineFree(explicit, process.cwd());@@ -97,10 +126,11 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisconst status = await readSyncStatus(engine, sourceId, { detail: args.includes('--detail') });const ctx = cliRenderContext();// #6696 (A4): the capacity picture rides every status read (unthrottled), from the 60 s snapshot.- const { cachedCapacitySnapshot, capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');+ // #6803 C4: one bounded wait per status read, shared with its notices; a slow snapshot reads unknown for this call only.+ const { capacitySnapshotWithin, capacityNotices, CAPACITY_READ_WAIT_MS } = await import('../../core/persistence/capacity-snapshot.ts');const { renderNotice } = await import('../../core/agent-output.ts');- const snapshot = await cachedCapacitySnapshot(engine);- const notices = (await capacityNotices(engine, { throttle: false })).map(notice => renderNotice(notice, ctx));+ const snapshot = await capacitySnapshotWithin(engine, Date.now() + CAPACITY_READ_WAIT_MS);+ const notices = (await capacityNotices(engine, { throttle: false, snapshot })).map(notice => renderNotice(notice, ctx));const read = (r: typeof status.cursors_read) => r.status === 'read' ? r : { ...r, fix: renderAction(r.fix, ctx) };const rendered = { ...status, holds: status.holds.map(hold => ({ ...hold, fix: renderAction(hold.fix, ctx) })), next: status.next ? renderAction(status.next, ctx) : null,checkpoint_blockers_read: read(status.checkpoint_blockers_read), cursors_read: read(status.cursors_read), terminal_failures_read: read(status.terminal_failures_read),diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex 7e2f857a6d..6de41d4ff8 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -62,9 +62,10 @@ type PerSourceResult = {* scope): under `--json` as rendered `notices`, otherwise as stderr lines.*/async function syncCapacityNotices(engine: BrainEngine, json: boolean, result?: SyncResult): Promise<{ notices?: unknown[] }> {- const { capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');- // #6712 PR 2 (L5): a degraded post-checkpoint tail rides the same notices.- const notices = [...(result?.tail?.notice ? [result.tail.notice] : []), ...await capacityNotices(engine).catch(() => [])].map(notice => renderNotice(notice, cliRenderContext()));+ const { capacityNotices, CAPACITY_READ_WAIT_MS } = await import('../../core/persistence/capacity-snapshot.ts');+ // #6712 PR 2 (L5): a degraded post-checkpoint tail rides the same notices. #6803 C4: the snapshot wait is bounded.+ const capacity = await capacityNotices(engine, { throttle: true, deadlineAt: Date.now() + CAPACITY_READ_WAIT_MS }).catch(() => []);+ const notices = [...(result?.tail?.notice ? [result.tail.notice] : []), ...capacity].map(notice => renderNotice(notice, cliRenderContext()));if (!json) for (const notice of notices) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);return notices.length ? { notices } : {};}@@ -89,10 +90,10 @@ export async function runSyncInner(engine: BrainEngine, args: string[]) {return runSyncTrigger(engine, args.slice(1));}// #6340: the operator contract (status / unblock) reads and schedules; it never runs a sync.- if (args[0] === 'status' || args[0] === 'unblock') {- const { runSyncStatus, runSyncUnblock } = await import('./operator.ts');- return args[0] === 'status' ? runSyncStatus(engine, args.slice(1)) : runSyncUnblock(engine, args.slice(1));- }+ // #6803: `sync --status` is canonicalized to `sync status` by the same classifier the CLI preflight uses.+ const { syncOperatorVerb, runSyncOperator } = await import('./operator.ts');+ const operatorVerb = syncOperatorVerb(args);+ if (operatorVerb) return runSyncOperator(engine, operatorVerb, args);// v0.37 fix wave (Lane D.4 + CDX2-12): print usage when `--help`/`-h` is// passed. Pre-fix this was unreachable because the dispatcher's genericdiff --git a/src/core/config.ts b/src/core/config.tsindex 50bfceb191..2ed38b11c8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -72,6 +72,7 @@ export interface GBrainConfig {/** #5232: CLI write wait in ms (file plane; persistence/write-wait.ts). */persistence?: { write_wait_ms?: number | string };migrate?: { graduation?: boolean }; // `migrate.graduation false`: legacy copier instead of graduation (file plane, read pre-connect)+ doctor?: { default_budget_ms?: number | string }; // #6803: non-interactive CLI doctor --json check-run cap (file plane, read pre-connect; 0 off)/** A4 user preapprovals (file plane only; set by the trusted local CLI; read by core/consent.ts). */consent?: { preapprove?: { paid?: { max_usd_per_run?: number }; persistent_install?: boolean } };database_url?: string;@@ -1783,6 +1784,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries', 'shared_skills.migration.enabled', // #6466: false declines the 0.53.0 migration (commands/migrations/opt-out.ts)'persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.ts'migrate.graduation', // file plane, src/commands/migrate-graduation.ts (engine graduation opt-out)+ 'doctor.default_budget_ms', 'doctor.entry_budget_ms', 'doctor.orphan_ratio.full_scan_max_pages', // #6803: file plane (commands/doctor/default-budget.ts); DB plane (doctor/budget.ts, checks/orphan-estimate.ts)'consent.preapprove.paid.max_usd_per_run', 'consent.preapprove.persistent_install', // A4: file plane, core/consent.ts// F4b: PGLite row-delta ANALYZE (src/core/planner-stats.ts); F4a: get_health memo TTL (src/core/health-memo.ts, 0 disables).'planner.auto_analyze', 'planner.first_read_budget_ms', 'import.analyze_every_pages', 'health.cache_ttl_ms',diff --git a/src/core/persistence/capacity-snapshot.ts b/src/core/persistence/capacity-snapshot.tsindex c79e04300b..e7a46fa3af 100644--- a/src/core/persistence/capacity-snapshot.ts+++ b/src/core/persistence/capacity-snapshot.ts@@ -11,15 +11,29 @@* `write_capacity_backpressure` (kind `degraded`, never muted) fires once* when a scope passes the background pause line (A5), again only after it* clears and passes it anew.+ *+ * #6803 C4: the shared fetch carries its own server-side bound+ * (CAPACITY_FETCH_BOUND_MS) and a timed-out fetch is never cached, so the next+ * caller fetches again. Read paths that must answer quickly (`gbrain sync+ * status`, write and sync receipts) wait on the shared fetch only until one+ * absolute deadline (`capacitySnapshotWithin`, CAPACITY_READ_WAIT_MS) and get+ * `unknown` for that call alone. An unknown snapshot yields no notices and+ * leaves the throttle and pause-transition state as it was, so a pause that+ * continues across a slow read is neither cleared nor announced again.*/import type { Notice } from '../agent-output.ts';import { principalKey, type Principal, type SqlEngine } from './model.ts';import { BACKGROUND_PRODUCERS, readBackgroundPauseShare } from './admission-origin.ts';import { readCapacityForecast } from './capacity-forecast.ts';import { CAPACITY_VERIFY } from './capacity-verify.ts';+import { deadlineBoundEngine, deadlineFailure, engineCacheKey, withStatementDeadline } from '../statement-deadline.ts';export const CAPACITY_SNAPSHOT_TTL_MS = 60_000;export const CAPACITY_NOTICE_INTERVAL_MS = 60 * 60_000;+/** Server-side bound of the shared snapshot fetch. */+export const CAPACITY_FETCH_BOUND_MS = 10_000;+/** How long a status read or receipt waits for the shared fetch. */+export const CAPACITY_READ_WAIT_MS = 1_500;export interface CapacityAttention {scope: string; resource: 'lifetime_ids' | 'terminal_bytes'; used: number; limit: number; pct: number;@@ -40,21 +54,46 @@ const snapshots = new WeakMap<object, { at: number; value: Promise<CapacitySnapsconst lowShownAt = new Map<string, number>();const pausedShown = new Set<string>();-/** The snapshot for `engine`, shared by every caller within CAPACITY_SNAPSHOT_TTL_MS (in flight included); a failed read is cached as `unknown`. */+const UNKNOWN: CapacitySnapshot = { rows: [], low: [], paused: [], pause_pct: 0, status: 'unknown' };++/**+ * The snapshot for `engine`, shared by every caller within CAPACITY_SNAPSHOT_TTL_MS (in flight included), keyed on the real+ * engine behind any deadline wrapper. The fetch is bounded at CAPACITY_FETCH_BOUND_MS; a fetch that timed out is dropped from+ * the cache (the next caller fetches again), any other failed read is cached as `unknown`.+ */export function cachedCapacitySnapshot(engine: SqlEngine, now: number = Date.now()): Promise<CapacitySnapshot> {- const hit = snapshots.get(engine);+ const cacheKey = engineCacheKey(engine);+ const hit = snapshots.get(cacheKey);if (hit && now - hit.at < CAPACITY_SNAPSHOT_TTL_MS) return hit.value;- const value = Promise.all([readCapacityForecast(engine, { light: true }), readBackgroundPauseShare(engine)]).then(([forecast, share]): CapacitySnapshot => {+ const bounded = deadlineBoundEngine(engine);+ const startedAt = Date.now();+ const fetch = withStatementDeadline({ startedAt, deadlineAt: startedAt + CAPACITY_FETCH_BOUND_MS, expired: false },+ () => Promise.all([readCapacityForecast(bounded, { light: true }), readBackgroundPauseShare(bounded)]));+ const value: Promise<CapacitySnapshot> = fetch.then(([forecast, share]): CapacitySnapshot => {const attention = (row: typeof forecast.rows[number]): CapacityAttention => ({ scope: row.scope, resource: row.resource, used: row.used, limit: row.limit,pct: row.pct, days_to_exhaustion: row.days_to_exhaustion, config_key: row.config_key, recommended_limit: row.recommended_limit,command: `gbrain config set ${row.config_key} ${row.recommended_limit}` });return { rows: forecast.rows.map(attention), low: forecast.rows.filter(row => row.status !== 'ok').map(attention),paused: forecast.rows.filter(row => row.used >= Math.floor(row.limit * share)).map(attention), pause_pct: Math.round(share * 100), status: 'ok' };- }).catch((): CapacitySnapshot => ({ rows: [], low: [], paused: [], pause_pct: 0, status: 'unknown' }));- snapshots.set(engine, { at: now, value });+ }).catch((error: unknown): CapacitySnapshot => {+ if (deadlineFailure(error) && snapshots.get(cacheKey)?.value === value) snapshots.delete(cacheKey);+ return UNKNOWN;+ });+ snapshots.set(cacheKey, { at: now, value });return value;}+/** The shared snapshot, or `unknown` for this call alone when it is not ready by `deadlineAt` (the fetch keeps going for later callers). */+export async function capacitySnapshotWithin(engine: SqlEngine, deadlineAt: number, now: number = Date.now()): Promise<CapacitySnapshot> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const late = new Promise<CapacitySnapshot>((resolve) => { timer = setTimeout(() => resolve(UNKNOWN), Math.max(0, deadlineAt - Date.now())); });+ try {+ return await Promise.race([cachedCapacitySnapshot(engine, now), late]);+ } finally {+ clearTimeout(timer);+ }+}+const key = (row: CapacityAttention) => `${row.scope}|${row.resource}`;const describe = (row: CapacityAttention) => `${row.scope} ${row.resource} ${row.used}/${row.limit} (${row.pct}%`+ `${row.days_to_exhaustion !== null ? `, about ${row.days_to_exhaustion} day(s) left` : ''})`;@@ -87,10 +126,13 @@ function pausedNotice(rows: CapacityAttention[], pausePct: number): Notice {* whenever a cap needs attention. The pause notice fires on each transition* into the pause, in either mode. `scopes` limits both to the scopes a* caller may see (a remote client: the brain and its own principal).+ * `deadlineAt` bounds the wait for the shared snapshot (`capacitySnapshotWithin`); `snapshot` reuses one the caller+ * already read. An unknown snapshot yields no notices and changes no throttle or pause-transition state.*/-export async function capacityNotices(engine: SqlEngine, opts: { throttle: boolean; now?: number; scopes?: string[] } = { throttle: true }): Promise<Notice[]> {+export async function capacityNotices(engine: SqlEngine, opts: { throttle: boolean; now?: number; scopes?: string[]; deadlineAt?: number; snapshot?: CapacitySnapshot } = { throttle: true }): Promise<Notice[]> {const now = opts.now ?? Date.now();- const snapshot = await cachedCapacitySnapshot(engine, now);+ const snapshot = opts.snapshot ?? (opts.deadlineAt !== undefined ? await capacitySnapshotWithin(engine, opts.deadlineAt, now) : await cachedCapacitySnapshot(engine, now));+ if (snapshot.status === 'unknown') return [];const visible = (row: CapacityAttention) => !opts.scopes || opts.scopes.includes(row.scope);const notices: Notice[] = [];const candidates = snapshot.low.filter(visible);@@ -117,5 +159,5 @@ export function __resetCapacityNoticesForTests(): void {/** #6696 (A4): a write receipt's capacity notices, throttled hourly per scope; a remote caller sees only the brain and its own principal. Never throws. */export async function writeReceiptCapacityNotices(engine: SqlEngine, ctx: { remote?: boolean; auth?: { principal?: Principal } }): Promise<Notice[]> {const scopes = ctx.remote === false ? undefined : ['brain', ...(ctx.auth?.principal ? [principalKey(ctx.auth.principal)] : [])];- return capacityNotices(engine, { throttle: true, scopes }).catch(() => []);+ return capacityNotices(engine, { throttle: true, scopes, deadlineAt: Date.now() + CAPACITY_READ_WAIT_MS }).catch(() => []);}diff --git a/src/core/statement-deadline.ts b/src/core/statement-deadline.tsnew file mode 100644index 0000000000..8938c1c7a7--- /dev/null+++ b/src/core/statement-deadline.ts@@ -0,0 +1,123 @@+/**+ * #6803: an absolute statement deadline carried by the async context, and the+ * engine wrapper that honours it.+ *+ * `withStatementDeadline(scope, run)` runs `run` with `scope` as the current+ * deadline; every continuation of `run` keeps it, so work that outlives its+ * caller (a check whose result the doctor runner already dropped) still stops+ * at its own deadline instead of borrowing the next caller's.+ * `deadlineBoundEngine(engine)` returns one stable wrapper per real engine+ * that reads the current scope on every call:+ *+ * - past the deadline, a statement (and any other engine method) is not+ * sent: it throws `StatementDeadlineError` and marks the scope `expired`;+ * - on Postgres a raw statement carries the deadline to the server (a+ * transaction-local statement_timeout recomputed after the pool wait, and+ * an abort of the pool wait itself), and a statement cancelled at the+ * deadline marks the scope `expired` even when the caller catches the+ * error, so the caller's owner can still report the result as unknown;+ * - PGLite has one in-process connection and no cancellation: it gets only+ * the refusal before each statement, and a statement already running+ * finishes.+ *+ * Without a scope (or with `deadlineAt: null`) the wrapper passes every call+ * through. Engine methods with their own SQL (e.g. `getStats`) get only the+ * refusal before the call. The wrapper exposes the engine it wraps under+ * `RAW_ENGINE`, and `engineCacheKey` maps either to the same object, so+ * engine-keyed caches keep one entry per real engine.+ */+import { AsyncLocalStorage } from 'node:async_hooks';++export interface StatementDeadline {+ startedAt: number;+ /** Absolute epoch ms; null: no deadline (the scope still carries `memo`). */+ deadlineAt: number | null;+ /** Set when a statement was refused or cancelled for this deadline. */+ expired: boolean;+ /** Values shared by every scope of one run (e.g. one doctor run's capacity forecast). */+ memo?: Map<string, Promise<unknown>>;+ /** The run's overall deadline, for work shared across the run's scopes; null: none. */+ runDeadlineAt?: number | null;+}++/** A statement that would start after its deadline. */+export class StatementDeadlineError extends Error {+ readonly code: string = 'statement_deadline';+ constructor(readonly elapsedMs: number, message = `The statement deadline passed after ${elapsedMs} ms.`) {+ super(message);+ this.name = 'StatementDeadlineError';+ }+}++export const RAW_ENGINE: unique symbol = Symbol.for('gbrain.engine.raw');++const wrappers = new WeakMap<object, object>();+/** wrapper -> the engine it wraps (looked up here, never through a property of the engine, which a stub may answer). */+const rawEngines = new WeakMap<object, object>();++/** The object an engine-keyed cache should use: the real engine behind a deadline wrapper. */+export function engineCacheKey<T extends object>(engine: T): object {+ return rawEngines.get(engine) ?? engine;+}++const scopes = new AsyncLocalStorage<StatementDeadline | undefined>();++export function withStatementDeadline<T>(scope: StatementDeadline | null, run: () => Promise<T>): Promise<T> {+ return scopes.run(scope ?? undefined, run);+}++export function currentStatementDeadline(): StatementDeadline | undefined {+ return scopes.getStore();+}++/** Whether an error is a deadline refusal, a statement the server cancelled (57014) or an aborted pool wait. */+export function deadlineFailure(error: unknown): boolean {+ return error instanceof StatementDeadlineError || cancelled(error);+}++function cancelled(error: unknown): boolean {+ const e = error as { code?: unknown; name?: unknown; message?: unknown } | null;+ return e?.code === '57014' || e?.name === 'AbortError' || /canceling statement|statement timeout/i.test(String(e?.message ?? ''));+}++function refuse(scope: StatementDeadline): never {+ scope.expired = true;+ throw new StatementDeadlineError(Date.now() - scope.startedAt);+}++type RawCall = (sql: string, params?: unknown[], opts?: Record<string, unknown> & { signal?: AbortSignal; timeoutMs?: number }) => Promise<unknown[]>;++export function deadlineBoundEngine<E extends object>(engine: E): E {+ const raw = engineCacheKey(engine) as E;+ const known = wrappers.get(raw);+ if (known) return known as E;+ const wrapper = new Proxy(raw, { get(target, key) {+ if (key === RAW_ENGINE) return target;+ const value = Reflect.get(target, key, target);+ if (typeof value !== 'function') return value;+ if (key === 'executeRaw') return async (sql: string, params?: unknown[], opts?: Parameters<RawCall>[2]) => {+ const scope = scopes.getStore();+ const call = (value as RawCall).bind(target);+ if (!scope || scope.deadlineAt === null) return call(sql, params, opts);+ const left = scope.deadlineAt - Date.now();+ if (left <= 0) refuse(scope);+ if ((target as { kind?: string }).kind !== 'postgres') return call(sql, params, opts);+ const signal = opts?.signal ? AbortSignal.any([opts.signal, AbortSignal.timeout(left)]) : AbortSignal.timeout(left);+ try {+ return await call(sql, params, { ...opts, signal, timeoutMs: Math.min(left, opts?.timeoutMs ?? left), deadlineAt: scope.deadlineAt });+ } catch (error) {+ if (cancelled(error) && Date.now() >= scope.deadlineAt - 100) scope.expired = true;+ throw error;+ }+ };+ // A function proxy, not a bare wrapper: a function-valued property keeps its own properties (the Postgres sql getter keeps reserve).+ return new Proxy(value as (...a: unknown[]) => unknown, { apply(fn, _self, args) {+ const scope = scopes.getStore();+ if (scope && scope.deadlineAt !== null && Date.now() >= scope.deadlineAt) refuse(scope);+ return Reflect.apply(fn, target, args);+ } });+ } });+ wrappers.set(raw, wrapper);+ rawEngines.set(wrapper, raw);+ return wrapper;+}diff --git a/test/doctor-tier-6696.test.ts b/test/doctor-tier-6696.test.tsindex 4623fc7f63..f6eda30366 100644--- a/test/doctor-tier-6696.test.ts+++ b/test/doctor-tier-6696.test.ts@@ -78,7 +78,9 @@ describe('#6696 B1 doctor tiers', () => {expect(parseBudgetMs(['--tier', 'ops'], 'ops')).toBe(OPS_BUDGET_MS_DEFAULT);expect(parseBudgetMs([], 'standard')).toBeNull();expect(parseBudgetMs(['--budget-ms', '900'], 'standard')).toBe(900);- expect(() => parseBudgetMs(['--budget-ms', '0'], 'ops')).toThrow(/positive integer/);+ expect(parseBudgetMs(['--budget-ms', '0'], 'ops')).toBeNull();+ expect(() => parseBudgetMs(['--budget-ms', '-1'], 'ops')).toThrow(/whole number of milliseconds/);+ expect(() => parseBudgetMs(['--budget-ms', '1.5'], 'ops')).toThrow(/whole number of milliseconds/);});test('--tier ops on a 2,000-page PGLite brain: only ops sections, no page aggregates, complete, PGLite skips are not_applicable info', async () => {