Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(maintenance,dream): run-scoped phase stops, budget-skip estimate, over-budget transcript, shadow decide re-spend (#7307 audit)
garrytan51e00ec90aa7
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex e7895d0f92..9bfde597f4 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -15,7 +15,7 @@ Patterns, drift reports and the cycle modules listed after them.- `src/core/cycle/attribution-checks.ts` — #5425 [UC4]: `dream.attribution_checks` (`ATTRIBUTION_CHECKS_KEY`, registered in `KNOWN_CONFIG_KEYS`; `config set` takes a boolean word through `CYCLE_GUARDED_KEYS` in `cycle/config-guards.ts`), the one default-off switch for the two mechanical attribution checks: the propose_takes holder downgrade (`propose-takes-attribution.ts`) and the synthesis `superseded_in_source` quarantine (`synthesize-verify.ts`). `attributionChecksEnabled(engine)` is `isConfigTruthy` over the stored value and false on any read error. The default flips only on a held-out gbrain-evals receipt, the same bar as the prompt rules `dream.synthesize.attribution_rules` / `dream.propose_takes.attribution_rules`.- `src/core/cycle/propose-takes-attribution.ts` — #5425 [UC4]: `downgradeAssistantOnlyHolders(proposals, pageBody)`, called once from `propose-takes.ts` right after the extractor returns when `dream.attribution_checks` is on. `claimContentTokens` takes a claim's numeric keys (`numericClaims`: currency, scaled amounts, percents, dates, 4+ digit numbers; bare years dropped) and its quoted phrases (`extractQuoteSpans`, normalized); `statedBySpeaker` credits each token to the speakers whose turns state it, plus a speaker who explicitly accepted the previous turn. A `people/<slug>` proposal every one of whose stated tokens was stated only by `assistant` is returned with holder `brain`; a token the user stated or accepted, a claim with no tokens, tokens no turn states, a page without speaker turns, and non-person holders leave the proposal untouched. Pure: returns the input array when nothing changes. Pinned by `test/propose-takes-attribution.test.ts` (standalone) and `test/propose-takes-attribution-callsite.test.ts` (the call, `test.todo` until the wave 13 hunk lands).- `src/core/cycle/synthesize-verify-epochs.ts` — the scope side of dream-page verification, peeled move-only from `synthesize-verify.ts` (module-size ratchet) and re-exported from it: `readVerifyEpoch`, `loadChildWriteEpochs`, `loadPreRunRevision`, `isDreamOwnedPage`, `resolveVerifyPrior`, exactly as described under `synthesize-verify.ts` above. Pure database reads; no claim check lives here.-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the... (line truncated to 2000 chars) #7240: a transcript whose child cannot be queued (any error but a lost connection or cancellation) is skipped `submit_failed (<code>)` with its own fresh chunks rolled back, and the fan-out continues instead of failing the phase, whose private-queue cleanup would cancel every child already queued (`test/dream-synthesize-submit-failure-7240.test.ts`).+- `src/core/cycle/synthesize.ts` — Synthesize phase (a transcript whose estimate alone exceeds `dream.synthesize.budget_usd` is skipped as `over_budget_alone`, never a budget deferral of the rest): conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the... (line truncated to 2000 chars) #7240: a transcript whose child cannot be queued (any error but a lost connection or cancellation) is skipped `submit_failed (<code>)` with its own fresh chunks rolled back, and the fan-out continues instead of failing the phase, whose private-queue cleanup would cancel every child already queued (`test/dream-synthesize-submit-failure-7240.test.ts`).- `src/core/cycle/transcript-discovery.ts` — Pure filesystem walk for synthesize. `discoverTranscripts(opts)` filters `.txt` files by date range, min_chars, and word-boundary regex `excludePatterns` (`medical` matches "medical advice" but NOT "comedical"; power users may pass full regex). `readSingleTranscript(path)` is the `gbrain dream --input <file>` ad-hoc path. Self-consumption guard: `DREAM_OUTPUT_MARKER_RE` (anchored at frontmatter open `---\n`, optional BOM + CRLF tolerance, scans first 2000 chars for `dream_generated: true` with case-insensitive value and word boundary on `true`) drives `isDreamOutput(content, bypass=false)`. Both functions skip matching files and emit a `[dream] skipped <basename>: dream_generated marker` stderr log (no silent skips). An `excludePatterns` hit is never logged per file (the matching files are sensitive by definition); instead both functions emit ONE `[dream] excluded N transcript(s) matching exclude_patterns (<label>: n, ...)` stderr line at the end of discovery, naming only the count and the configured pattern labels that fired, never a path, basename, or content. `DEFAULT_EXCLUDE_PATTERNS` is unchanged (`medical`, `therapy`). `bypassGuard?: boolean` on `DiscoverOpts` and `readSingleTranscript`'s opts disables the guard for the explicit `--unsafe-bypass-dream-guard` escape hatch only — never auto-applied for `--input`. Two path-level guards run before the content read: `selfCaptureSessionIds` (from `claudeCliSelfSessionIds`) skips a `.txt` corpus file (session-end, checkpoint segment or writeback form, via `corpusFileSessionId`) captured from gbrain's own claude-cli call, and `excludeDirs` (synthesize passes the reflections, originals, patterns-output and cycle-summary directories under `brainDir`, empty under `--unsafe-bypass-dream-guard`) skips any file whose resolved path sits inside one, so an output a failed postprocess left unmarked is never re-synthesized while a transcript that merely names such a path is still disc... (line truncated to 2000 chars)diff --git a/docs/architecture/key-files/core-decide.md b/docs/architecture/key-files/core-decide.mdindex 6043082442..e8d0457a18 100644--- a/docs/architecture/key-files/core-decide.md+++ b/docs/architecture/key-files/core-decide.md@@ -54,7 +54,7 @@ The capability contract (API, providers, egress, extension points) is `docs/arch- `src/core/cycle/decide-slot.ts` — `resolveCycleDecideSlot(engine, 'triage' | 'grounding')`: undefined when the slot is off (all-off cycles do no decide work); otherwise the slot policy (unpacked pack shape, calibrations, last resolved models, key presence).-- `src/core/cycle/triage-decide.ts` — S7: `splitTurnWindows` (whole turns from speaker anchors, `[role]` lines or role headings, else paragraphs; ~1,500 chars; a turn over 24,000 chars splits at paragraphs, marked), one `noul` per window through `runDecideUnpacked`, transcript score = max window p, `reduceTriage` (pass / margin_hold / reject; null = incomplete) shared with qualify and `whatIfTriage`. Complete pass/reject verdicts are cached with model `decide:<provider>@<resolved>#<fingerprint8>` (the S7-only cache identity; `TRIAGE_VERSION` unchanged), segments = top windows' first 300 chars cut at a turn boundary, entities from `extractEntities`, content type from one extra `choice` request; margin_hold and every incomplete decision return no verdict so `runTriagePass` runs today's LLM triage (no judge → pass). #7307: before any request, a scored row at the current `TRIAGE_VERSION` (and not older than `staleBefore`) from either judge (the decide identity, or `llmModel`, today's triage model that `runTriagePass` passes) is a cache hit; a margin hold writes a marker row (score NULL, content_type `decide_margin_hold`, never over an LLM backoff marker) that keeps the transcript off the provider for `DECIDE_MARGIN_HOLD_TTL_MS` (24 h), and an active LLM backoff also holds it (both counted in `stats.held`). Shadow/inactive: receipts only. `estimateTriageDecideUsd` prices retriage.+- `src/core/cycle/triage-decide.ts` — S7: `splitTurnWindows` (whole turns from speaker anchors, `[role]` lines or role headings, else paragraphs; ~1,500 chars; a turn over 24,000 chars splits at paragraphs, marked), one `noul` per window through `runDecideUnpacked`, transcript score = max window p, `reduceTriage` (pass / margin_hold / reject; null = incomplete) shared with qualify and `whatIfTriage`. Complete pass/reject verdicts are cached with model `decide:<provider>@<resolved>#<fingerprint8>` (the S7-only cache identity; `TRIAGE_VERSION` unchanged), segments = top windows' first 300 chars cut at a turn boundary, entities from `extractEntities`, content type from one extra `choice` request; margin_hold and every incomplete decision return no verdict so `runTriagePass` runs today's LLM triage (no judge → pass). #7307: before any request, a scored row at the current `TRIAGE_VERSION` (and not older than `staleBefore`) from either judge (the decide identity, or `llmModel`, today's triage model that `runTriagePass` passes) is a cache hit; a margin hold writes a marker row (score NULL, content_type `decide_margin_hold`, never over an LLM backoff marker) that keeps the transcript off the provider for `DECIDE_MARGIN_HOLD_TTL_MS` (24 h), and an active LLM backoff also holds it (both counted in `stats.held`). Shadow/inactive: receipts only, observed only for transcripts today's triage judged this pass (never a cache hit). `estimateTriageDecideUsd` prices retriage.- `src/core/cycle/grounding-decide.ts` — S8: `GroundingPass` for both verify call sites; per unit up to three source windows (`selectSourceWindows`: normalized 4-gram substring hits, best keyword overlap, nearest embedding when an embedding provider is configured), coverage weak when no window reaches the 0.25 keyword floor; one `noul` per unit; `reduceGrounding` (pass / margin_hold / insufficient_context on weak coverage / quarantine) shared with qualify and `whatIfGrounding` (receipt `protected` = weak coverage). Only quarantines when on; timeout (30 s per page, 10 min per phase), 429, 5xx, budget, egress and drift keep the mechanical result. Coverage is judged over the distinct content words of the selected windows together (a substring window still counts), against the same 25% floor.diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.mdindex 03e1eab58b..14fd4f7dc7 100644--- a/docs/guides/troubleshooting.md+++ b/docs/guides/troubleshooting.md@@ -672,7 +672,14 @@ for two global intervals, then four, up to a day. A `deferred` streak(synthesize triage left transcripts for the next pass) lets a pass stamp pastit once the deferred count has not shrunk for three passes in a row; while thecount keeps shrinking, the stamp waits. Budget and child blockers never let a-pass stamp past them; child failures back off too.+pass stamp past them; child failures back off too. A phase that fails with a+run-scoped code (a missing table, `permission_denied`, `write_quota_exhausted`,+`recovery_required`) is a `fail:<code>` streak like any other failure, and+the pass goes on to the next phase. A lost connection or contention stops the+job and the next job retries that phase first, at most three jobs in a row;+after that it is the phase's streak and the pass goes on. A phase skipped for+`insufficient_cycle_budget` after another phase ran in the same job moves to+the next job instead of counting as a `budget` streak.Doctor warns when the stamp is older than three global intervals(`autopilot.global_floor_min`, 60 minutes by default) while maintenance jobsdiff --git a/llms-full.txt b/llms-full.txtindex ac3141ee82..482a4f5b2b 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -11112,7 +11112,14 @@ for two global intervals, then four, up to a day. A `deferred` streak(synthesize triage left transcripts for the next pass) lets a pass stamp pastit once the deferred count has not shrunk for three passes in a row; while thecount keeps shrinking, the stamp waits. Budget and child blockers never let a-pass stamp past them; child failures back off too.+pass stamp past them; child failures back off too. A phase that fails with a+run-scoped code (a missing table, `permission_denied`, `write_quota_exhausted`,+`recovery_required`) is a `fail:<code>` streak like any other failure, and+the pass goes on to the next phase. A lost connection or contention stops the+job and the next job retries that phase first, at most three jobs in a row;+after that it is the phase's streak and the pass goes on. A phase skipped for+`insufficient_cycle_budget` after another phase ran in the same job moves to+the next job instead of counting as a `budget` streak.Doctor warns when the stamp is older than three global intervals(`autopilot.global_floor_min`, 60 minutes by default) while maintenance jobsdiff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 28bf5a92f4..a9e5f50c63 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1101,6 +1101,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'With System One triage (the decide `triage` slot) acting, the Dream synthesize phase and `gbrain dream retriage` no longer send a transcript to the decide provider when the verdict cache already holds a verdict for that exact content from today\'s LLM triage (the current triage model and triage version), so transcripts the LLM triage judged after a borderline decide answer are not re-judged and paid for every pass. A borderline (margin hold) decide answer is now cached for 24 hours: the transcript goes to today\'s LLM triage, and decide is not asked again for it in that time even when the LLM step ran out of its `dream.triage.max_ms` window. A transcript in unreliable-verdict backoff is not sent to decide either until its backoff ends. `gbrain dream retriage --force` still re-judges everything.' },{ since: 'TBD', text: 'Brain-wide maintenance stamps `autopilot.last_global_at` past a synthesize triage deferral that has stopped making progress: when the number of transcripts triage leaves for the next pass did not shrink across three passes in a row, the fourth pass stamps (the job result lists it under `pass_completed_with_failing_phase`), as it already did for a phase failing the same way. While the deferred count keeps shrinking, the stamp is still withheld. Doctor `global_maintenance_stalled` names `gbrain dream retriage` (preview with `--dry-run`; it asks before paid spend) for a deferral streak instead of rerunning the phase, which stops at the same time window.' },{ since: 'TBD', text: '`gbrain dream retriage` triages the same transcript list as the synthesize phase: on a brain with `dream.synthesize.conversation_pages true` and no `session_corpus_dir` it no longer refuses with config_error, and on a brain with a corpus dir and conversation pages left on by default it now also re-scores and reconciles those conversation pages (from source `default`, or the source named by `--source`). Judging stays behind the existing spend estimate and consent gate.' },+ { since: 'TBD', text: 'Brain-wide maintenance no longer stops every job at a phase that fails with a run-scoped error such as a missing table, `permission_denied`, `write_quota_exhausted` or `recovery_required` (before, each later job resumed at that phase and stopped again, so later phases never ran and `autopilot.last_global_at` was never stamped): the failure is that phase\'s `fail:<code>` streak and the job goes on to the next phase, so it backs off and is stamped past after three passes like any other failing phase. A lost connection or database contention still stops the job and the next job retries that phase first, at most three jobs in a row before it counts as the streak. A phase skipped for `insufficient_cycle_budget` after another phase ran in the same job now moves to the next job, where it runs first with the whole budget, instead of counting as a `budget` blocker on every pass; its skip no longer replaces its measured duration.' },+ { since: 'TBD', text: 'The Dream synthesize phase skips a transcript whose estimated synthesis cost alone exceeds `dream.synthesize.budget_usd` (reported as `over_budget_alone` in its skips), instead of deferring it and every transcript after it on every pass, which kept the synthesize cooldown and brain-wide maintenance from completing. Raise the cap or use a cheaper synthesis model to synthesize it. A cap of 0 still defers everything.' },+ { since: 'TBD', text: 'With the System One triage slot in shadow mode (or on without a calibration), Dream now asks the decide provider only about transcripts the LLM triage judged in that pass, not about every transcript whose verdict was already cached, so a shadow brain stops paying the provider for its whole backlog on every pass.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex e1d79ffa61..58de3168f0 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -902,8 +902,8 @@ async function runPhaseSynthesizeInner(label: `synthesize:${basename(t.filePath)}`,});if (!spend.allowed) {- process.stderr.write(`[dream] synthesize budget: ${spend.reason}; deferring ${basename(t.filePath)} and the rest of this run\n`);- budgetExhaustedDeferrals.push(basename(t.filePath));+ const alone = overBudgetAloneReason(spend, t.basename);+ if (alone) skipReports.push({ filePath: t.filePath, reason: alone }); else { process.stderr.write(`[dream] synthesize budget: ${spend.reason}; deferring ${basename(t.filePath)} and the rest of this run\n`); budgetExhaustedDeferrals.push(basename(t.filePath)); }continue;}for (let i = 0; i < chunks.length; i++) {@@ -2254,6 +2254,13 @@ export function parseSynthV2Key(key: string): ParsedSynthV2Key | null {}}+/** A transcript over the whole synthesis cap on its own is skipped (like oversize_after_split), never a deferral of the rest; null for a cumulative denial or a 0 cap. */+function overBudgetAloneReason(spend: { estimatedCostUsd: number; budgetUsd: number }, name: string): string | null {+ if (spend.budgetUsd <= 0 || spend.estimatedCostUsd <= spend.budgetUsd) return null;+ process.stderr.write(`[dream] transcript ${name} alone is estimated at $${spend.estimatedCostUsd.toFixed(4)}, over the $${spend.budgetUsd.toFixed(2)} dream.synthesize.budget_usd cap; skipping it. Raise the cap or use a cheaper synthesis model.\n`);+ return `over_budget_alone: $${spend.estimatedCostUsd.toFixed(4)} > $${spend.budgetUsd.toFixed(2)}`;+}+// ── Triage pass (#4152) — shared by the synthesize phase and dream retriage ──/**@@ -2470,9 +2477,11 @@ export async function runTriagePass(const gate = (v: RescueVerdictLike, content: string) =>passesTriageGate(v, content, cfg.threshold, rescueCfg, cfg.decide?.gate);+ // Shadow / inactive decide observes only transcripts today's triage judged this pass, never a cache hit.+ const freshlyJudged = new Set<number>();const processOne = async (idx: number): Promise<void> => {const d = cfg.decide;- if (!d?.acting) { await processLlm(idx); if (d) await d.observe(transcripts[idx]); return; }+ if (!d?.acting) { await processLlm(idx); if (d && freshlyJudged.has(idx)) await d.observe(transcripts[idx]); return; }const t = transcripts[idx];const r = await d.triage(t, { triageVersion: TRIAGE_VERSION, llmModel: cfg.model, force: cfg.force, staleBefore: cfg.staleBefore, signal: cfg.signal, budgetExhausted });if (!r.verdict) {@@ -2624,6 +2633,7 @@ export async function runTriagePass(reasons: triage.reasons,cached: false,};+ freshlyJudged.add(idx);} catch (e) {// AIConfigError at chat time = provider auth/config went bad mid-run// (revoked key, recipe misconfig surfacing at first real call). Skipdiff --git a/src/core/cycle/triage-decide.ts b/src/core/cycle/triage-decide.tsindex e7f43e813e..f6e1d77a91 100644--- a/src/core/cycle/triage-decide.ts+++ b/src/core/cycle/triage-decide.ts@@ -278,7 +278,7 @@ export interface TriageDecide {stats: TriageDecideStats;/** `llmModel`: today's triage model; its stored verdicts are cache hits too. */triage(t: DiscoveredTranscript, opts: { triageVersion: number; llmModel?: string; force?: boolean; staleBefore?: Date; signal?: AbortSignal; budgetExhausted: () => boolean }): Promise<TriageDecideResult>;- /** After today's path ran (shadow or inactive on): receipts only, nothing else changes. */+ /** After today's path judged the transcript this pass (shadow or inactive on; never a cache hit): receipts only, nothing else changes. */observe(t: DiscoveredTranscript): Promise<void>;}diff --git a/src/core/minions/handlers/autopilot-global-maintenance.ts b/src/core/minions/handlers/autopilot-global-maintenance.tsindex 88261bb911..b9fb87e18f 100644--- a/src/core/minions/handlers/autopilot-global-maintenance.ts+++ b/src/core/minions/handlers/autopilot-global-maintenance.ts@@ -5,7 +5,7 @@ import type { BrainEngine } from '../../engine.ts';import type { MinionHandler } from '../types.ts';import type { CycleReport, PhaseResult } from '../../cycle.ts';import { CODES } from '../../error-registry.ts';-import { ItemRun } from '../../item-failure.ts';+import { ItemRun, classifyItemFailure } from '../../item-failure.ts';import { OperationError } from '../../ops/contract.ts';import { VERSION } from '../../../version.ts';import { reportJobProgress } from './job-progress.ts';@@ -31,6 +31,17 @@ import { reportJobProgress } from './job-progress.ts';* by another gbrain version is dropped, a new blocker key starts a new streak,* and `gbrain autopilot --retry-global` ends the back-off. A job whose* failures look systemic (ItemRun breaker) persists no streak.+ *+ * A phase failure classified run-scoped is the phase's typed blocker too+ * (`fail:<code>`), and the job goes on to the next phase, unless it may pass+ * on the next job (RETRY_NEXT_JOB_CODES, or any run-scoped error runCycle+ * threw): then the job stops and the next job retries that phase first, at+ * most STREAK_BYPASS_PASSES jobs in a row (`run_stops`) before it is recorded+ * as the blocker, so the pass can still complete. A job's own stop (abort,+ * cancel, stolen lock) always stops it. A phase skipped for+ * `insufficient_cycle_budget` after another phase ran in the same job is+ * moved to the next job (a deadline deferral) instead of counting as a+ * `budget` blocker, and its skip time is never kept as its duration estimate.*/export const GLOBAL_MAINTENANCE_PROGRESS_KEY = 'autopilot.global_maintenance.progress';/** A phase is not started when its last measured duration would end within this reserve of the job deadline. */@@ -40,6 +51,13 @@ export const GLOBAL_FLOOR_MIN = 60;/** Earlier passes with one typed failure before the pass stamps past that phase; also where back-off starts. */export const STREAK_BYPASS_PASSES = 3;const MAX_BACKOFF_MS = 24 * 60 * 60_000;+/** Run-scoped codes that may pass on the next job: the job stops and the next one retries the phase first. */+const RETRY_NEXT_JOB_CODES: ReadonlySet<string> = new Set([+ 'database_contention', 'connection_lost', 'writer_busy', 'writer_lock_unavailable', 'writer_pool_capacity', 'queue_capacity',+ 'write_capacity_backpressure', 'maintenance_backpressure', 'write_claim_lost',+]);+/** Stops that belong to the job itself: always stop it, never counted against the phase. */+const JOB_STOP_CODES: ReadonlySet<string> = new Set(['aborted', 'lock_stolen', 'cancelled']);/** One phase's consecutive passes blocked by the same kind of blocker. */export interface PhaseStreak {@@ -80,6 +98,8 @@ export interface GlobalMaintenanceProgress {pass_bypassed?: string[];/** Blocker streak per phase; cleared when the phase passes. */failures?: Record<string, PhaseStreak>;+ /** Consecutive jobs a phase stopped with the same retryable run-scoped code; cleared when the phase completes. */+ run_stops?: Record<string, { code: string; count: number; last_at: string }>;}export async function readGlobalMaintenanceProgress(engine: BrainEngine): Promise<GlobalMaintenanceProgress> {@@ -178,6 +198,7 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps:progress.timeouts ??= {};progress.skip_this_pass ??= [];progress.failures ??= {};+ progress.run_stops ??= {};for (const [phase, streak] of Object.entries(progress.failures)) {if (streak.version !== VERSION) delete progress.failures[phase];}@@ -228,6 +249,18 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps:progress.failures![phase] = streak;return streak;};+ /** Whether a run-scoped failure stops the job (the next job retries the phase first) rather than becoming the phase's blocker. */+ const stopsJob = (phase: string, code: string, thrown: boolean): boolean => {+ if (JOB_STOP_CODES.has(code)) return true;+ if (!thrown && !RETRY_NEXT_JOB_CODES.has(code)) return false;+ const prev = progress.run_stops![phase];+ const count = prev?.code === code ? prev.count : 0;+ if (count >= STREAK_BYPASS_PASSES) return false;+ progress.run_stops![phase] = { code, count: count + 1, last_at: new Date().toISOString() };+ return true;+ };+ /** A run-scoped failure recorded as the phase's own: counted by the breaker, never rethrown by it. */+ const contained = (phase: string, code: string) => new Error(`phase ${phase} failed with run-scoped ${code}; recorded as its blocker`);const blockStamp = (phase: string, streak: PhaseStreak, earlierPasses: number) => {if (!streakStampsPast(streak, earlierPasses)) { progress.pass_failed = true; return; }if (!progress.pass_bypassed!.includes(phase)) progress.pass_bypassed!.push(phase);@@ -284,19 +317,30 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps:yieldBetweenPhases: async () => { await new Promise<void>((r) => setImmediate(r)); },});} catch (e) {+ const classified = classifyItemFailure(e);+ const runScoped = classified.scope === 'run';+ if (runScoped && stopsJob(phase, classified.code, true)) return stopRun(e, phase);let failure;- try { failure = itemRun.fail(phase, e); } catch (stop) { return stopRun(stop, phase); }+ try { failure = itemRun.fail(phase, runScoped ? contained(phase, classified.code) : e); } catch (stop) { return stopRun(stop, phase); }+ const code = runScoped ? classified.code : failure.code;+ const message = runScoped ? classified.message.slice(0, 500) : failure.message;progress.running_phase = undefined;progress.running_job = undefined;- ran.push({ phase, status: 'fail', duration_ms: 0, summary: `error: ${failure.message}`, details: {},- error: { class: 'InternalError', code: failure.code, message: failure.message } });- const blocked = recordBlocker(phase, `fail:${failure.code}`);+ ran.push({ phase, status: 'fail', duration_ms: 0, summary: `error: ${message}`, details: {},+ error: { class: 'InternalError', code, message } });+ const blocked = recordBlocker(phase, `fail:${code}`);blockStamp(phase, blocked, blocked.count - 1);continue;}- reports.push(report);progress.running_phase = undefined;progress.running_job = undefined;+ if (i > start && report.phases.some(r => r.phase === phase && r.details.reason === 'insufficient_cycle_budget')) {+ deferred = phases.slice(i);+ stopReason = 'deadline';+ progress.next_phase = phase;+ break;+ }+ reports.push(report);if (report.status === 'skipped' || report.reason === 'aborted' || report.reason === 'lock_stolen') {// A phase cut off by the job deadline would be cut off again next run.if (report.reason === 'aborted' && deadline !== null && Date.now() >= phaseDeadline!) {@@ -311,11 +355,17 @@ export function makeAutopilotGlobalMaintenanceHandler(engine: BrainEngine, deps:for (const result of report.phases) {ran.push(result);if (result.phase !== phase) continue;- progress.durations[phase] = result.duration_ms;+ if (result.details.reason !== 'insufficient_cycle_budget') progress.durations[phase] = result.duration_ms;delete progress.timeouts[phase];if (result.status === 'fail') {- try { itemRun.fail(phase, phaseFailureError(result)); } catch (stop) { return stopRun(stop, phase); }- } else itemRun.succeed();+ const error = phaseFailureError(result);+ const classified = classifyItemFailure(error);+ if (classified.scope === 'run' && stopsJob(phase, classified.code, false)) return stopRun(error, phase);+ try { itemRun.fail(phase, classified.scope === 'run' ? contained(phase, classified.code) : error); } catch (stop) { return stopRun(stop, phase); }+ } else {+ delete progress.run_stops[phase];+ itemRun.succeed();+ }const key = phaseBlocker(result);if (!key) { delete progress.failures[phase]; continue; }const deferredCount = (result.details.triage as { deferred?: unknown } | undefined)?.deferred;diff --git a/test/cycle-synthesize-daily-cap.test.ts b/test/cycle-synthesize-daily-cap.test.tsindex bd346179b4..67ed352d57 100644--- a/test/cycle-synthesize-daily-cap.test.ts+++ b/test/cycle-synthesize-daily-cap.test.ts@@ -438,22 +438,62 @@ describe('USD budget gate (C-13)', () => {}}, 60_000);+ /** The meter's estimate for one seeded file under the default cap (a throwaway rig on the shared engine). */+ async function oneFileEstimate(name: string): Promise<number> {+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+ await seedPassingFile(rig, name);+ return (await runPhase(rig) as CapDetails & { estimated_spend_usd: number }).estimated_spend_usd;+ } finally {+ await rig.cleanup();+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+ }+ }+test('a submission whose estimate crosses dream.synthesize.budget_usd is deferred before any spend', async () => {+ // #7307 audit: two files that each fit the cap but not together (a file over the cap alone is skipped, below).+ const each = await oneFileEstimate('2026-08-11-a.txt');+ expect(each).toBeGreaterThan(0);const rig = await setupRig();try {await rig.engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');- await rig.engine.setConfig('dream.synthesize.budget_usd', '0.0001');+ await rig.engine.setConfig('dream.synthesize.budget_usd', (each * 1.5).toFixed(6));await seedPassingFile(rig, '2026-08-11-a.txt');await seedPassingFile(rig, '2026-08-12-b.txt');const details = await runPhase(rig) as CapDetails & { budget_deferred_transcripts: string[] };- expect(details.children_submitted).toBe(0);- expect(details.budget_deferred_transcripts.sort()).toEqual(['2026-08-11-a.txt', '2026-08-12-b.txt']);+ expect(details.children_submitted).toBe(1);+ expect(details.budget_deferred_transcripts).toEqual(['2026-08-12-b.txt']);expect(await rig.engine.getConfig('dream.synthesize.last_completion_ts')).toBeNull();} finally {await rig.cleanup();}}, 60_000);+ test('#7307 audit: a transcript over the cap on its own is skipped with its reason, and later transcripts still submit', async () => {+ const small = await oneFileEstimate('2026-08-12-small.txt');+ const rig = await setupRig();+ try {+ await rig.engine.setConfig('models.dream.synthesize', 'anthropic:claude-sonnet-4-6');+ await rig.engine.setConfig('dream.synthesize.budget_usd', (small * 1.2).toFixed(6));+ const bigName = '2026-08-01-big.txt';+ const big = `conversation in ${bigName} with a long planning thread for acme-example\n`.repeat(4000);+ const bigPath = join(rig.corpusDir, bigName);+ writeFileSync(bigPath, big);+ await rig.engine.putDreamVerdict(bigPath, createHash('sha256').update(big, 'utf8').digest('hex'), {+ worth_processing: true, reasons: ['seed'], score: 0.9, content_type: null, segments: [], entities: [], model: TIER_DEFAULTS.utility, triage_version: TRIAGE_VERSION,+ });+ await seedPassingFile(rig, '2026-08-12-small.txt');+ const details = await runPhase(rig) as CapDetails & { budget_deferred_transcripts: string[] };+ expect({ submitted: details.children_submitted, deferred: details.budget_deferred_transcripts }).toEqual({ submitted: 1, deferred: [] });+ const skip = details.skips.find(s => s.filePath === bigPath);+ expect(skip?.reason).toMatch(/^over_budget_alone: \$[0-9.]+ > \$[0-9.]+$/);+ } finally {+ await rig.cleanup();+ }+ }, 60_000);+test('"0" spends nothing; "unlimited" removes the cap', async () => {const rig = await setupRig();try {diff --git a/test/decide/triage-decide-recheck-7307.serial.test.ts b/test/decide/triage-decide-recheck-7307.serial.test.tsindex 7d0d1f093e..fdca472572 100644--- a/test/decide/triage-decide-recheck-7307.serial.test.ts+++ b/test/decide/triage-decide-recheck-7307.serial.test.ts@@ -172,6 +172,21 @@ for (const kind of testBackends()) {expect(windowRequests).toBeGreaterThan(0);});+ test('#7307 audit: shadow mode asks decide only for transcripts the LLM triage judged this pass, never for cache hits', async () => {+ await engine.setConfig('decide.slots.triage.mode', 'shadow');+ transport(0.9);+ const cached = transcript('shadow-cached');+ await seedLlm(cached);+ const out = await pass([cached]);+ expect({ windowRequests, judgeCalls, cacheHits: out.cacheHits }).toEqual({ windowRequests: 0, judgeCalls: 0, cacheHits: 1 });+ const fresh = transcript('shadow-fresh');+ await pass([fresh]);+ expect({ asked: windowRequests > 0, judgeCalls }).toEqual({ asked: true, judgeCalls: 1 });+ windowRequests = 0;+ const again = await pass([fresh]);+ expect({ windowRequests, judgeCalls, cacheHits: again.cacheHits }).toEqual({ windowRequests: 0, judgeCalls: 1, cacheHits: 1 });+ });+test('an LLM backoff marker after a margin hold is kept, and decide is not asked again while it runs', async () => {transport(0.47);const t = transcript('held-unreliable');diff --git a/test/pathological/a10-global-maintenance-stamp.test.ts b/test/pathological/a10-global-maintenance-stamp.test.tsindex bf401a2aac..accc9f9836 100644--- a/test/pathological/a10-global-maintenance-stamp.test.ts+++ b/test/pathological/a10-global-maintenance-stamp.test.ts@@ -157,7 +157,7 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect(Date.parse(streak.retry_at) - Date.parse(streak.last_at)).toBe(4 * 60 * 60_000);}, 120_000);- test('budget, deferral and child blockers never stop withholding the stamp', async () => {+ test('a budget skip as a job\'s first phase, a shrinking deferral and child blockers never stop withholding the stamp', async () => {// #7307: a deferral stops withholding only when its backlog stops shrinking; this one shrinks every pass.const cases: Array<[string, (n: number) => Outcome, string]> = [['synthesize', () => ({ status: 'ok', details: { reason: 'insufficient_cycle_budget' } }), 'budget'],@@ -220,6 +220,76 @@ for (const { backend, databaseUrl } of pathologicalArms()) {expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'dream', 'retriage']);}, 120_000);+ test('a contained run-scoped phase failure (42P01, write_quota_exhausted) is the phase\'s blocker: later phases run, the streak bypasses and backs off', async () => {+ for (const code of ['42P01', 'write_quota_exhausted']) {+ await resetState();+ calls = [];+ outcomes = { purge: fail(code) };+ for (let n = 1; n <= 3; n++) {+ const result = await expectUnitNotAborted(() => pass(['orphans', 'purge', 'embed']));+ expect({ code, n, embedRan: calls.filter(p => p === 'embed').length, stamped: await stamped(), status: result.status })+ .toEqual({ code, n, embedRan: n, stamped: null, status: 'partial' });+ }+ const fourth = await expectUnitNotAborted(() => pass(['orphans', 'purge', 'embed']));+ expect({ code, stamped: (await stamped()) !== null, embedRan: calls.filter(p => p === 'embed').length, purgeRan: purgeRuns() })+ .toEqual({ code, stamped: true, embedRan: 4, purgeRan: 3 });+ expect(fourth.pass_completed_with_failing_phase).toEqual([expect.objectContaining({ phase: 'purge', key: `fail:${code}`, count: 3 })]);+ expect(Date.parse((await progress()).failures.purge.retry_at)).toBeGreaterThan(Date.now());+ const check = await stalledCheck();+ expect({ code, status: check.status, phase: check.message.includes('purge'), key: check.message.includes(code) }).toEqual({ code, status: 'warn', phase: true, key: true });+ expect(JSON.stringify(check.fix)).toContain('"dream","--phase","purge"');+ }+ }, 120_000);++ test('a retryable run-scoped phase failure stops the job and the next job retries it first, three jobs at most; then it is the blocker and the pass goes on', async () => {+ outcomes = { purge: fail('08006') };+ for (let n = 1; n <= 3; n++) await expect(pass(['orphans', 'purge', 'embed'])).rejects.toBeDefined();+ expect({ next: (await progress()).next_phase, streak: (await progress()).failures.purge ?? null, embedRan: calls.filter(p => p === 'embed').length })+ .toEqual({ next: 'purge', streak: null, embedRan: 0 });+ const fourth = await expectUnitNotAborted(() => pass(['orphans', 'purge', 'embed']));+ expect({ status: fourth.status, embedRan: calls.filter(p => p === 'embed').length, streak: (await progress()).failures.purge?.key })+ .toEqual({ status: 'partial', embedRan: 1, streak: 'fail:08006' });+ for (let n = 0; n < 3; n++) await expectUnitNotAborted(() => pass(['orphans', 'purge', 'embed']));+ expect(await stamped()).not.toBeNull();+ delete outcomes.purge;+ await patchStreak('purge', { retry_at: new Date(Date.now() - 1000).toISOString() });+ await pass(['orphans', 'purge', 'embed']);+ expect({ runStops: (await progress()).run_stops?.purge ?? null, streak: (await progress()).failures.purge ?? null }).toEqual({ runStops: null, streak: null });+ }, 120_000);++ test('a phase budget-skipped after another phase ran in the job moves to a fresh job instead of blocking the stamp forever', async () => {+ const MIN = 60_000;+ const realNow = Date.now;+ let clock = realNow();+ Date.now = () => clock;+ try {+ const budgeted = async (_engine: BrainEngine, opts: { phases?: string[]; deadlineAtMs?: number }): Promise<CycleReport> => {+ const phase = opts.phases![0]!;+ calls.push(phase);+ let result: PhaseResult;+ if (phase === 'synthesize') { clock += 25 * MIN; result = { phase, status: 'ok', duration_ms: 25 * MIN, summary: 'ok', details: {} } as PhaseResult; }+ else if (phase === 'patterns' && opts.deadlineAtMs! - clock < 15 * MIN) {+ clock += 5;+ result = { phase, status: 'skipped', duration_ms: 5, summary: 'budget', details: { reason: 'insufficient_cycle_budget' } } as PhaseResult;+ } else { clock += phase === 'patterns' ? 12 * MIN : 5_000; result = { phase, status: 'ok', duration_ms: 1, summary: 'ok', details: { child_outcome: 'completed' } } as PhaseResult; }+ return { schema_version: '1', timestamp: new Date(clock).toISOString(), duration_ms: 1, status: 'ok', phases: [result], totals: {} } as unknown as CycleReport;+ };+ const job = () => makeAutopilotGlobalMaintenanceHandler(engine, { runCycle: budgeted as never })(+ { id: ++jobId, attempts_made: 0, signal: undefined, deadlineAtMs: clock + 30 * MIN, data: { phases: ['synthesize', 'patterns', 'purge'], repoPath: null } } as never) as Promise<any>;+ const first = await job();+ expect({ resume: first.report.resume_phase, streak: (await progress()).failures.patterns ?? null, stamped: await stamped() })+ .toEqual({ resume: 'patterns', streak: null, stamped: null });+ expect((await progress()).durations.patterns).toBeUndefined();+ clock += 60 * MIN;+ await job();+ expect({ patternsOk: calls.filter(p => p === 'patterns').length, stamped: (await stamped()) !== null, streak: (await progress()).failures.patterns ?? null })+ .toEqual({ patternsOk: 2, stamped: true, streak: null });+ expect((await progress()).durations.patterns).toBe(1);+ } finally {+ Date.now = realNow;+ }+ }, 120_000);+test('a run-scoped failure at the phase loop stops the job and records no streak', async () => {for (const { name, error } of runScopedErrors()) {await resetState();