Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor: keep wave 9 lane W within the size ratchets; release notes

time-attack4ff464bfbfd3
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 61342ffcbb..7ad6b6f12f 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
-- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun`), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run.
+- `src/commands/autopilot-dispatch.ts` — one autopilot tick's submissions (`dispatchAutopilotTick`): freshness syncs, the extract_atoms auto-drain, the remediation plan, and full-cycle fan-out or targeted submits. The auto-drain (`dispatchAutoDrain` → `submitAutoDrains`) runs on Postgres only, unless `autopilot.auto_drain.enabled` is `false`, and only when the active pack does not run extract_atoms in the routine cycle. It submits a bounded, protected `extract-atoms-drain` job per source with a backlog under a per-source UTC-day idempotency key, so a structural refusal costs at most one dead job per source per day. The daily cap (`autopilot.auto_drain.max_usd_per_day` / the per-attempt `cycle.extract_atoms.budget_usd` estimate) counts attempts, not jobs (`autoDrainUnitsToday`: a waiting job one, a retried job one per started attempt), and excludes a job whose only attempt dead-lettered with `structural_refusal:`. Checkout-backed and connector sources alternate for free slots, with the next kind persisted in `AUTO_DRAIN_NEXT_KIND_KEY` (`autopilot.auto_drain.next_kind`) across ticks and days; a source whose writer preflight would refuse (`atomDrainOwnerRefusal`) is skipped with a logged reason; connector sources need no `local_path` and submit no `repoPath`. Tests: `test/autopilot-auto-drain*.test.ts`, `test/e2e/autopilot-auto-drain-dispatch.test.ts`. #5028: the auto-drain no longer skips when the active pack declares extract_atoms (the daemon's per-source cycles run only SOURCE_FRESHNESS_PHASES, so the declaration never made the routine cycle drain it); extract_atoms runs stamp `sources.config.last_extract_atoms_at` (`stampExtractAtomsRun` in `src/core/cycle/extract-atoms-stamp.ts`, which also builds the doctor warning), and the `extract_atoms_backlog` doctor check's declared branch warns when a backlog source's stamp is missing or older than 48h even though cycles run.
- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index fd856c81e1..9457608df1 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -12,7 +12,7 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/synthesize-verify.ts` — Mechanical claim verification on every page a synthesis child wrote (zero LLM). Exports the shared grounding primitive `normalizeForGrounding` (whitespace/curly-quote/dash/ellipsis/case folding WITH an offset map back to the original string, so every replacement is a verbatim transcript slice) + `normForGrounding` (plain form, also used by `buildTriageMapBlock` and triage-rescue). `groundSource(path, content)` prepares a transcript: offset map, speaker turns (`parseSpeakerTurns`: bold `**Name** (ts):` anchors and standalone `[user]` / `[assistant]` / `[system]` role lines (the session-corpus renderer's turn boundaries, so a `Name:` label inside one turn never carries into the next) always, plain `Label:` anchors when the label is a role word or opens two or more lines), canonical numbers and dates (`numericFacts`: `$250K` = `$250,000` = `250 thousand`, `2026-03-14` = `March 14th`; the file basename counts), and speaker-mention patterns. `groundQuote` runs the ladder exact → normalized → near (word-trigram anchors, window clipped to the anchor's speaker turn, ≥0.8 token overlap, ambiguity within 0.05 falls through, trimmed to the first/last shared token, refused above 1.3x the quote length) and never accepts a match that touches a speaker label (`reason: 'crosses_speakers'`). `verifyBody` splits a body into claim units (`claimUnits`: sentences within a line, whole list items, whole table rows; no boundary inside a quote) and checks each NEW unit: every quote must ground in some source, a quote whose sentence names a transcript speaker must name the speaker of the matched turn, and every numeric/date claim (outside grounded quotes, code, wikilinks and link targets) must appear in a source; a unit saying a named speaker decided, agreed, committed or will act (and recording no proposal, refusal or negation) must carry only numbers and dates that speaker stated, or that the turn they explicitly accepted stated (`numbersBySpeaker`; bare years and numbers no turn states are not attributed). Any failure removes the whole unit from the body; `verifyDreamPage` records it in frontmatter `unverified_claims` (`text`, `reason` = `quote_not_in_source` / `quote_crosses_speakers` / `speaker_mismatch` / `number_not_in_source` / `decision_misattributed`, `detail`, `sources`, `detected_at`) and records every grounded quote's source path, character span and speaker in `grounding.quotes`; records from the pre-run revision carry forward, capped at 100 / 200. Frontmatter is neither chunked nor searched, so quarantined claims stay reviewable through `get_page` but out of search, recall, think and context packs. A page whose every unit failed keeps `ALL_CLAIMS_QUARANTINED_BODY`. Scope (`verifyAndRepairDreamPages(engine, refs, transcriptsByPath, { since, sinceByTranscript, checkedAt })`): sources are the transcripts of every child that wrote the page; the page epoch is the child's first write to that page (`first_write_at` on the ref) when known, so a page another writer created while the child ran is diffed rather than treated as the run's own; otherwise the earliest `loadChildWriteEpochs` entry of its sources (child job `created_at`, so resumed or coalesced children keep their original epoch), else `since` (`readVerifyEpoch`, taken before fan-out). Pages created at or after the epoch are verified whole; older pages are verified only on units absent from their pre-epoch revision (`loadPreRunRevision`: the first `page_versions` snapshot at or after the epoch; none means the page was not overwritten → `skipped_unchanged`). Write-back goes through `importFromContent` (`noEmbed`; the phase-end embed sweep backfills) with a `beforeCommit` that re-projects timeline entries, facts, takes (`prepareCanonicalProjections` as a `preserving` writer bound to the page's current snapshot) and automatic links (`prepareAutomaticLinks`) from the verified body in the same transaction, so no derived row outlives its quarantined claim while database-only timeline history is kept. `verifyBody` skips units inside a validly marked bullet (`materializedHistoryRanges`) only when that bullet is absent from the pre-run revision, i.e. it was materialized from the database during the run; a new page gets no exemption, and a claim added under a marked bullet that already existed is verified. Fail-open per page (read-back miss / write throw → `errors` + continue; abort still unwinds). Kill switch `dream.synthesize.quote_verify` (default on). Telemetry shape = `QuoteVerifyStats` in `details.synthesis.quote_verify`. Pinned by `test/cycle-synthesize-verify.test.ts`, the write-path mini-eval `test/cycle-write-path-mini-eval.test.ts`, and the three-cycle repeated-consolidation pin `test/cycle-repeated-consolidation.test.ts` (harness `test/helpers/repeated-consolidation.ts`, printable run `scripts/repeated-consolidation-experiment.ts`). System One S8: `verifyBody` also returns `groundingUnits` (new units that pass only because they carry no quote, number or attribution; ≥5 words, not headings) without changing any other field; `verifyDreamPage` returns them per body, `verifyAndRepairDreamPages` takes an optional `grounding: GroundingPass` applied before write-back, and `quarantineUnits` removes S8-rejected units into `unverified_claims` with reason `unsupported_paraphrase`.
-- `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, 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 stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`).
+- `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, 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 stored `worth_processing` boolean derives from the fixed `DEFAULT_TRIAGE_THRESHOLD` constant (back-compat only, never the live dial). Passing files fan out one subagent per chunk with `max_turns` from `dream.synthesize.max_turns` (default 16) and a bounded advisory `buildTriageMapBlock` (exported; score/type/entities + chunk-filtered segments, '' for legacy/degraded verdicts so the prompt is unchanged for those) spliced into `buildSynthesisPrompt`, with `allowed_slug_prefixes` (sourced from `skills/_brain-filing-rules.json` `dream_synthesize_paths.globs`; when `dream.synthesize.output_root` is set, `loadAllowedSlugPrefixes(outputRoot)` remaps the `wiki/`-rooted globs to the configured namespace, and the same root drives the prompt slug templates; default 'wiki', validated against the slug grammar via the exported `loadOutputRoot`). The phase is source-scoped: cycle.ts threads `cycleSourceId` as `opts.sourceId` → each child's `SubagentHandlerData.source_id` → the subagent tool registry's `OperationContext.sourceId`, so put_page writes, collected refs, the summary page, and reverse-writes all target the cycle's resolved source ('default' when unscoped; reverse-writes for the cycle's own source land at `brainDir/<slug>.md`, foreign sources under `brainDir/.sources/<id>/`). Orchestrator collects slugs from `subagent_tool_executions` (NOT `pages.updated_at`) and reverse-renders DB → markdown via `serializeMarkdown`. Cooldown via `dream.synthesize.last_completion_ts`, written only when children completed and neither synthesis-budget nor triage-budget deferrals remain. Idempotency keys `dream:synth-v2:<enc source>:filename:<enc basename>:<hash16>[:c<i>of<n>]` (byte-stable, pinned by `test/dream-synthesize-chunking.serial.test.ts`; grammar parsed by exported `parseSynthV2Key`). Fan-out self-heals idempotency-coalesced rows stranded `waiting` in a FOREIGN dead `dream-inline-*` queue (cancel releases the key slot → re-add into the live run's queue) instead of burning the 35-min wait on a row no worker will ever claim. Opt-in per-source daily submission cap `dream.synthesize.max_submissions_per_source_per_day` (default 0 = off; skips whole files — never partial chunk sets; bypassed for explicit `--input/--date/--from/--to` targets; count-query failure fails CLOSED: the run submits nothing and reports `daily_cap_unavailable`). Every transcript's whole chunk set is checked against a per-run USD `BudgetMeter` before submission (`dream.synthesize.budget_usd`, default 5; `0` submits nothing, `unlimited` removes the cap; estimate = prompt chars/4 plus the child output cap, times `max_turns` in agentic mode); a denied transcript and the rest of the run are deferred into `budget_deferred_transcripts` without a cooldown stamp, and `details.budget_usd` / `estimated_spend_usd` report the gate. `--dry-run` runs triage, skips synthesis; deferral-aware headlines append "(N not yet triaged — time budget...)" so a time-boxed cold pass never reads as mass rejection. `details.triage` (threshold/judged/cache_hits/unreliable/degraded/deferred/below_threshold + rescue_band/rescue_checked/rescue_fired + tokens_in/tokens_out/cost_usd) + `details.synthesis` (jobs/avg_turns/max_turns_config + quote_verify/spend/children_zero_pages) carry the phase telemetry. Subagent never gets fs-write access. The child prompt's date hint and the summary are dated by the cycle date (`cycleDate` from runCycle, else `resolveCycleDate`); opt-in `dream.synthesize.attribution_rules=true` adds `SYNTH_ATTRIBUTION_RULE` (keep who proposed what and later corrections explicit). `renderPageToMarkdown` (exported) stamps `dream_generated: true` + `dream_cycle_date` into every reverse-written dream-owned page (`isDreamOwnedPage`: created at or after the child's first put_page, or already stamped; a human page a child edited is rendered without the marker); `writeSummaryPage` does the same on the summary index — this marker is the explicit identity surface `isDreamOutput` checks in `transcript-discovery.ts`. `stampDreamProvenance` additionally persists the same marker into the `pages.frontmatter` JSONB row (merge via `executeRawJsonb`, raw object bound to `$N::jsonb`) for every page a child created (the refs from `collectChildPutPageSlugs` carry `first_write_at`, the child's earliest put_page `started_at` per slug) or that is already stamped, BEFORE reverse-rendering; a pre-existing human page is never stamped, so generated pages are DB-queryable and a later put_page write-through (which re-renders from the DB row) can't erase the stamp. `judgeSignificance`, `JudgeClient`, `runTriagePass`, `buildTriageMapBlock`, `parseSynthV2Key`, `loadSynthConfig`, `TRIAGE_VERSION`, and `DEFAULT_TRIAGE_THRESHOLD` are exported; the triage model resolves via an explicit pre-read of `models.dream.triage` (preferred; through exported `resolveAlias`) falling back to the standard `resolveModel` chain (`models.dream.synthesize_verdict` → deprecated `dream.synthesize.verdict_model` → tier `utility`). `splitTranscriptByBudget(content, contentHash, maxChars)` splits oversized transcripts at paragraph boundaries (`## Topic:` → `---` → `\n` ladder) using a deterministic offset seeded from the first 32 bits of `contentHash` so retries chunk identically; per-chunk char budget = `MODEL_CONTEXT_TOKENS[resolvedModel] × 0.9 × 3.5 chars/token` (non-Anthropic ids fall back to a 180K-token safe default + once-per-process stderr warn); operator overrides `dream.synthesize.max_prompt_tokens` (floor 100K, wins) and `dream.synthesize.max_chunks_per_transcript` (default 24); per-chunk subagent job/wait timeouts are `dream.synthesize.subagent_timeout_ms` / `dream.synthesize.subagent_wait_timeout_ms` (defaults 30/35 min). Legacy `dream:synth:` keys are never produced — `loadSuccessfulSynthesisKeys(engine, sourceId, keyPrefix)` reads the completed rows of BOTH key families once per phase, unioned with `dream_synthesis_completions` (where `MinionQueue.prune` archives completed `dream:synth%` keys before deleting their rows, so `jobs prune` never makes a synthesized transcript eligible again), so existing brains skip with `already_synthesized_legacy_single_chunk`/`_chunked` instead of re-spending the synthesis model, and a transcript whose synth-v2 children already completed skips with `already_synthesized_v2_single_chunk`/`_chunked` (`findSynthV2Completion`; a cancelled row never counts) BEFORE its link manifest is built — otherwise queue.add's idempotency fast path coalesces onto the completed children and they re-enter writtenRefs, so their old pages get quote-repaired, restamped, reverse-written and re-embedded every night. `collectChildPutPageSlugs` raw-fetches every (job_id, slug) pair (not `SELECT DISTINCT`) and rewrites bare-hash6 slugs to `<hash6>-c<idx>` for chunked children (orchestrator-side, zero Sonnet trust). Cap-hit skips write nothing new to `dream_verdicts` (the pass's cached triage verdict remains — a free cache hit on retry) and record no synthesis job, so raising the cap on next run re-attempts cleanly. Bounds INITIAL prompt size only; tool-loop turn-N accumulation is caught by terminal-error classification in `subagent.ts`. Verdict routing is gateway-routed: `makeJudgeClient(verdictModel)` (exported) mirrors `tryBuildGatewayClient` in `src/core/think/index.ts` — a construction-time provider/key probe returns `null` on a clear miss (unknown provider id via `resolveRecipe` AIConfigError, or Anthropic provider with no key via `hasAnthropicKey()`). The verdict loop wraps `judgeSignificance` in try/catch for `AIConfigError` so mid-run provider failures surface as per-transcript `worth=false, reasons=['gateway error: ...']` instead of crashing the phase. Canonical config key `models.dream.synthesize_verdict` (per `PER_TASK_KEYS` in `src/core/model-config.ts`); `JudgeClient` signature preserved verbatim for test-seam stability; CI guard `scripts/check-gateway-routed-no-direct-anthropic.sh` prevents reintroducing `new Anthropic()` here or in `think/index.ts`. At the queue.add boundary a conditional `anthropic:` prefix is applied ONLY when the resolved model has no colon AND starts with `claude-` (because `resolveModel` returns bare ids from `TIER_DEFAULTS`/`DEFAULT_ALIASES` and the subagent validator requires `provider:model` form) — avoids changing the shared constants which would ripple across every `resolveModel` caller. Pinned by `test/cycle/synthesize-gateway-adapter.test.ts`, `test/e2e/dream-synthesize-pglite.test.ts` (gateway-adapter mid-run AIConfigError catch), `test/cycle/regression-pr-wave-r1-r2-r4.test.ts`. Drain-loop lock renewal runs through exported `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) — a hung renewLock cannot stack one checked-out slot per interval firing. Pinned by `test/cycle-drain-renewal.test.ts`. Execution mode: `dream.synthesize.mode` (default `oneshot`) threads to every child as `data.mode` alongside `oneshot_slug_suffix` (the structural suffix contract) and `require_writes: true`; `details.synthesis` adds mode/oneshot_jobs/fallback_jobs/agentic_jobs/fallback_reasons plus the drain telemetry (inline_concurrency_config/effective, drain_ms, queue-wait + runtime p50/p95, dead_jobs, degraded). Pre-retrieval LINK CANDIDATES manifest (link-manifest.ts, `dream.synthesize.link_manifest` default on) is built once per transcript from the cached triage entities/segment notes and spliced into `buildSynthesisPrompt` together with an ALLOWED WRITE PATHS block rendered from the trusted allow-list (the oneshot path never sees a tool schema, so the fence lives in the prompt; rule 2 points at the candidates first). Phase outcome gate: ALL children dead/cancelled → phase fails with SYNTH_ALL_CHILDREN_DEAD (fan-out details preserved on the failure); ANY non-completed child → the cooldown stamp is skipped so released idempotency keys retry next run; 'timeout' (parent stopped waiting) degrades but never triggers the all-dead error. Phase-end deferred-embed closure: whenever the phase wrote pages (regardless of mode — an agentic revert still sweeps debt left by earlier oneshot runs), a 120s-bounded `embedStalePages` (embed-stale.ts) embeds the NULL-embedding chunks of exactly the pages this phase wrote — never a source-wide sweep; the pre-existing stale backlog stays with the budget-tracked embed-backfill machinery — closing the gap on invocation shapes that never reach the global embed phase (`--phase synthesize`, autopilot per-source NON_GLOBAL_PHASES). Best-effort (never fails a phase that wrote its pages) and stamps the current embedding signature on fully-re-embedded pages so they stay inside the model-drift invalidation contract. The inline drain lives in `src/core/cycle/inline-drain.ts` (re-exported here for patterns.ts + `__testing`). Budget clamping: clamped to the remaining parent-job budget when `opts.deadlineAtMs` is threaded (via patterns.ts's `clampSubagentBudgets` template): the clamp re-runs against the live clock PER SUBMIT (the phase is a fan-out with claim-time-anchored child kill switches, so one phase-start clamp only bounds the first child); under the minimum child budget the phase skips honestly (`insufficient_cycle_budget`) or defers the remaining transcripts (`details.budget_deferred_transcripts`), the inline drain stops CLAIMING when the budget can't fit another child and unclaimed children are cancelled + deferred (they'd otherwise strand forever in the run's private queue), each completion wait is additionally bounded by the remaining parent budget (floored at 1s so already-terminal children still resolve), and a deferring run neither writes the 12h cooldown timestamp nor counts deferred transcripts as processed — deferral genuinely retries next cycle. THE gate is `passesTriageGate` (triage-rescue.ts) applied at report construction inside `runTriagePass`: threshold pass OR the verified-segment rescue for band scores `[dream.triage.rescue_floor (0.30), threshold)` with content_type in `dream.triage.rescue_content_types` and ≥ `dream.triage.rescue_min_segments` (default 2; 0 = off) of the judge's segments verifying as normalized transcript substrings (≥40 chars, deduped) — reports carry `rescued`/`verified_segments`, `details.triage` adds rescue_band/rescue_checked/rescue_fired + judge tokens_in/tokens_out/cost_usd (null when unpriced), and dream-retriage's reconcile/audit read the SAME predicate. TRIAGE_VERSION is 2 (peak-not-average rubric; segment selection prefers concrete facts/decisions). After slug collection and BEFORE the provenance stamp/reverse-write/embed sweep, the claim verification pass (synthesize-verify.ts, `dream.synthesize.quote_verify` default on) runs on every page the children wrote, scoped by `readVerifyEpoch` (taken before fan-out) and `loadChildWriteEpochs`; the phase is wrapped in `withChatPhase('phase:synthesize')` (children keep their own job tag — minion_jobs stays the child-spend authority) and `details.synthesis` adds `quote_verify`, `children_zero_pages` (completed children with zero put_page writes — the rule-D disposition), and `spend` (`cost_basis: 'in+out+cache_read'`; children summed from minion_jobs tokens_input/output/cache_read priced at the configured synth model, triage from the pass usage; total_usd null unless both price) `buildSynthesisPrompt` is mode-aware (`mode: 'agentic' | 'oneshot'`, passed from `config.mode` at the sole submit site): agentic children keep the search-tool and final-summary guidance; tool-less oneshot children receive neither, so the prompt never contradicts `ONESHOT_SYSTEM`'s JSON-only rule (the oneshot prompt is stored as `data.prompt` and reused verbatim by the in-job agentic fallback, whose tools stay in the schema). Pinned by `test/cycle-dream-output-root.test.ts`. Managed enabled local synthesis uses durable page admission with original authority and canonical-mirror validation; completed source-incarnation-qualified children survive restart. Quote-repair failure cannot silently certify grounded publication. Remote maintenance remains unsupported. Before submitting a transcript's chunk set, the phase asks the paid-loop breaker (`dream-breaker.ts`) and records a `dream_breaker_tripped` skip with the reset command instead of submitting; the opt-in daily cap counts dead rows through their released key. System One: `runTriagePass` takes `cfg.decide` (S7, `triage-decide.ts`; undefined when the slot is off) — when S7 acts, `processOne` delegates to it and falls back to the LLM path (`processLlm`) for margin_hold/incomplete decisions; the phase passes `grounding` (S8, `grounding-decide.ts`) to both verify call sites and adds `triage.decide` / `synthesis.grounding` details only when a slot is not off. Discovery is the corpus walk plus imported `type: conversation` pages from the database (`transcript-discovery.ts`, `dream.synthesize.conversation_pages`). Each written page is credited to its transcript's capturing seat (`seat` frontmatter, #4618) on both write paths; the `dream:synth-v2:` idempotency key never includes the seat, so a sidecar that appears after synthesis triggers no re-run (`test/session-seat-synthesize.test.ts`). #5145: completed synthesis is partitioned out BEFORE the triage pass on every path (classic, managed and dry run) by `partitionCompletedSynthesis` in `src/core/cycle/synthesize-completion.ts` (which also holds the legacy / synth-v2 completion-key helpers); details carry `synthesis_state: {candidates, already_synthesized}` and the triage counters cover only screened candidates.
- `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 discovered; each class is reported as one count-only stderr line. Its conversation-page section is the DB discovery (#4419): `discoverConversationPages(engine, opts)` returns the cycle source's live `type: conversation` pages (date filter on the `date` frontmatter, min_chars, exclude_patterns, `dream_generated`/`mode: lsd` and gbrain-self-session guards) as transcripts keyed `gbrain-page://<source>/<slug>` with a sha256 of the body; `withConversationPages(engine, opts, config, corpus)` appends them to the corpus list when the setting is on and drops a page whose body hash a corpus file already carries; `conversationPagesNotConsumed` returns the `conversation_pages_not_consumed` warn when synthesis is unconfigured but such pages exist. Gated by `dream.synthesize.conversation_pages` (on by default with a corpus dir, `true` opts in without one, `false` off). Pinned by `test/dream-conversation-pages.test.ts`. Each discovered corpus file carries `seat` when its session's `<sessionId>.seat.json` sidecar (`context/seat.ts`, keyed through `corpusFileSessionId`, so segments and writeback files share the session's seat) holds a valid label; the sidecar itself is never a transcript. `withTranscriptSeats` credits synthesis output refs to the seat of the transcript in their `raw_source`. Pinned by `test/transcript-discovery-seat.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 9c51a06cbd..95f9d04d1b 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -29,4 +29,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/worker-registry.ts` — live worker registry backing niceness observability. Each running `gbrain jobs work` self-registers `worker-<pid>.json` under `gbrainPath('workers')` (brain-isolated via `GBRAIN_HOME`; entries tagged with `currentBrainId()` so multiple DBs under one home don't cross-report). `registerWorker(info)` is best-effort (never blocks the worker) and returns a cleanup fn the caller wires to BOTH the shutdown `finally` AND `process.on('exit')` (the unhealthy `process.exit(1)` bypasses the awaited finally). `readWorkers(getNice?)` enumerates the dir, drops confirmed-dead pids (`classifyLiveness`: ESRCH = dead/prune, EPERM = alive/keep), applies a pid-reuse start-time guard (zone-free `ps -o etime=` parsed by `parseEtimeToMs`, start = now - elapsed; rejects a pid that started >5s after the entry was written), and re-measures each live worker's niceness now. Reports the worker's REAL pid, sidestepping the tini-wrapper-pid problem. Pinned by `test/worker-registry.serial.test.ts`.
- `src/core/minions/no-worker.ts` — queue honesty (agent-first operator wave E5). `queueWorkerAlive(queue, read?)` (a live registered worker serves the queue on this host; undefined when the registry is unreadable), `runWaitingJobsFix(engineKind, queue)` (PGLite: `gbrain jobs work [--queue Q]`, a foreground drain, `requires_exclusive`; Postgres: `gbrain jobs supervisor start`), `noWorkerNotice(...)` (code `no_worker`, kind `degraded`). Consumers: CLI `jobs submit` on PGLite refuses without `--follow` unless `--queue-only` (`src/commands/jobs/submit.ts`); `gbrain jobs work` on PGLite drains via `drainPgliteQueue` (`src/commands/jobs/work.ts`) and exits; MCP `submit_job` / `get_job_stats` emit the notice (`src/core/ops/jobs.ts`, PGLite fix wrapped by readiness `exclusiveFix` behind a running serve); `deriveWedgeSignal(wedge, {workerAlive})` returns `no_worker` and never calls that case wedged (`jobs stats`, `get_job_stats`); doctor `queue_health` counts PGLite waiting rows (`src/commands/doctor/checks/queue-jobs.ts`). Pinned by `test/queue-no-worker.test.ts`.
-- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`queue.releaseShutdownJob`, token-fenced, no attempt burned), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17).
+- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). The `ready` event follows final startup checks; listener failure stops startup before claims or timers. The renewal adapter latches typed configuration faults before the generic retry tick consumes them, including deadline verification. Configuration shutdown stops claims, tracks actual executions separately from scheduling slots, and releases only confirmed stopped work through `MinionQueue.releaseConfigurationJob` within one bounded shutdown envelope. The active/token-fenced release returns `released`, `no_op` or `unconfirmed`, leaves attempt/stall counters unchanged, and delays released work for 30 seconds; an unconfirmed stop or DB write falls back to lease expiry. Outstanding claims register their token before the post-claim configuration check so late claims cannot launch handlers. Aborted jobs call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`); `shutdownAbort` (instance field) fires on SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` (shell handler listens; non-shell handlers don't). Per-job timeout fires `abort.abort(new Error('timeout'))` then a 30s grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead if the handler ignores the abort signal (the generic abort listener fires for ANY abort reason). The `launchJob` lock-renewal block is a thin sync wrapper around the pure `runLockRenewalTick` from `src/core/minions/lock-renewal-tick.ts` (NEVER `setInterval(async () => await renewLock(...))` — that shape surfaces an unhandledRejection during PgBouncer rotation). Guarantees: (1) `cancelled` flag captured in the timer closure stops in-flight IIFEs writing misleading audit events after the job ended; (2) re-entrancy guard `tickInFlight` (skips counted as `overlapSkips` telemetry) + per-call `Promise.race` timeout with best-effort AbortSignal cancellation; (3) verify-before-evict: eviction requires a fenced-false (certain loss) or the `hardEvictMs` backstop — never bare local arithmetic; the per-job lease (`job.lock_duration_ms ?? opts.lockDuration`) drives the renewal state, and the cadence clamps to `min(lease/2, 60s)`; (4) explicit `.catch()` on the stored `executeJob(...).finally(...)` promise closes the second unhandledRejection vector; (5) exported `INFRASTRUCTURE_ABORT_REASONS = new Set(['lock-renewal-failed', 'lock-lost'])` so executeJob's catch skips `failJob` for these (PgBouncer blips don't dead-letter healthy jobs; the stall detector reclaims); worker configuration shutdown is not in this set — it is gated separately by the typed `configurationError` latch; (6) inFlight generation-safety — force-evict and the handler's finally delete the inFlight entry ONLY when it still carries their own lockToken (the token is the generation; an evicted execution's late delete cannot remove a same-worker re-claim's entry); (7) eviction observability — the worker keeps a `perf_hooks.monitorEventLoopDelay` histogram (reset on every successful renewal, sampled ns→ms at eviction) plus raw loadavg, and both the abort and grace-evict log lines carry cause / since-last-success / tick-lateness / overlap-skips / load / event-loop-delay from the stashed `abortMeta`. CI guard `scripts/check-worker-lock-renewal-shape.sh` (in `bun run verify`) asserts the bug pattern stays absent AND `launchJob` keeps calling `runLockRenewalTick`. Engine-ownership invariant: `start()` does NOT call `engine.disconnect()` on shutdown — the CLI handler in `src/commands/jobs.ts case 'work'` owns engine lifecycle via try/finally with loud error logging. RSS watchdog uses non-file-backed pages on Linux: exported `parseRssFromProcStatus(status)` (pure parser; field-presence regex so `RssAnon: 0 + RssShmem: 512` parses correctly) and `getAccurateRss(readStatus?)` (reads `/proc/self/status` for `RssAnon + RssShmem`, falls back to `process.memoryUsage().rss` on macOS / restricted containers / kernel <4.5); the default `getRss` in `WorkerOpts` is `getAccurateRss`. `checkMemoryLimit` tracks peak RSS, fires an 80%-of-cap soft-warn (once per crossing, carrying peak + in-flight job kinds), and on exceed sets `_rssWatchdogTriggered=true` (exposed via `get rssWatchdogTriggered()`) so `jobs work`'s finally can `process.exit(WORKER_EXIT_RSS_WATCHDOG)` after disconnect (drain self-identifying instead of an opaque code-0 exit). The poll loop wraps `claim` in try/catch: on a retryable conn error it reconnects ONCE and continues to the next tick rather than blind-retrying (a retry after `UPDATE...RETURNING` committed but the socket died would double-claim). `LockRenewalDeps` is wired with `reconnect` when the engine supports it. The self-health DB-liveness probe runs EVEN under a supervisor (`GBRAIN_SUPERVISED=1`): the outer guard is `if (this.opts.healthCheckInterval > 0)` and only the STALL-detection block is wrapped in `if (!isSupervisedChild)` — so a supervised worker whose own pool dies self-exits `unhealthy(db_dead)` after `dbFailExitAfter` probes (the supervisor watches a different connection and can't see this worker's dead pool), while the supervisor's progress watchdog owns forward-progress. Pinned by the `test/worker-lock-renewal.test.ts` hermetic suite, `test/audit/lock-renewal-audit.test.ts`, `test/scripts/check-worker-lock-renewal-shape.test.ts`, `test/worker-shutdown-disconnect.test.ts` (asserts `disconnectSpy).not.toHaveBeenCalled()`), `test/worker-rss.test.ts` (11), `test/worker-supervised-db-probe.test.ts` (3). Per-job process isolation: `MinionWorkerOpts.jobIsolation` (`inline`|`process`) + `childCliInvocation`/`childTiniPath` swap `handler(context)` for `runJobInChild(...)` in executeJob — every reporting branch (completeJob, failJob, lease release, infra no-burn) is reused on the child outcome; when isolated the parent-side context is not built at all. Three extra no-burn child classes in the catch: `ChildSpawnInfraError` + `ChildWorkerShutdownError` (released, no attempt burned) and `ChildNotClaimedError` (the child proved the claim was already gone — reclaimed/cancelled before the handler ran — so nothing is recorded against it). The health probe delegates to `runDbProbe` (db-probe.ts) with a cancellation signal on every probe and emits a `verdict` (`pool_starved`/`server_unreachable`/`unknown`/`client_misconfigured`); typed configuration faults block immediately instead of burning the transient DB failure threshold. `getHandler(name)` is the read-only registry accessor run-child uses. Inline handlers run under `runWithJobSpend`; an isolated spend-authorized job passes `spendAuthorized` to the child runner's capability gate. #5062: `requestShutdown()` is the signal entry point (the `jobs work` signal owner calls it for SIGHUP/broken pipe too); a handler that ends because of the shutdown signal hands its claim back (`worker-shutdown.ts`: token-fenced, no attempt burned), and claims still running after the 30s drain are handed back the same way with `drainForced` set, which `jobs work` turns into exit `WORKER_EXIT_DRAIN_FORCED` (17).
diff --git a/docs/wave9/W.md b/docs/wave9/W.md
new file mode 100644
index 0000000000..59c4f40444
--- /dev/null
+++ b/docs/wave9/W.md
@@ -0,0 +1,26 @@
+# Wave 9, lane W (workers and job lifecycle): release notes for the integrator
+
+No version bump, no CHANGELOG header, no migration. These lines are for the
+integrator to fold into the wave 9 CHANGELOG entry and its upgrade section.
+
+## CHANGELOG lines
+
+- **`gbrain jobs supervisor stop` no longer reports `drained` while work survives (#5062).** A SIGTERM used to reach the generic CLI cleanup handler first: it deleted the supervisor's queue lock and exited 143 before the supervisor said `stopped`, the worker died the same way, its in-flight job stayed `active`, and the job's children were orphaned to PID 1. The supervisor and `jobs work` now own their termination signals: repeated signals join one ordered shutdown that keeps the queue lock through the drain (a second supervisor is refused mid-drain), stops the worker (SIGTERM, 35s, SIGKILL by liveness, confirmed exit), hands interrupted claims back to the queue without burning an attempt, releases the lock and only then emits `stopped`, now carrying `drained`, `worker_forced`, `worker_exit_code` and `lock_released`. `stop` reports `drained` only when the supervisor's own `stopped` row says so, every worker it spawned is gone and its lock row is released; otherwise it names the failing check (`no_stopped_event`, `worker_still_running`, `lock_unverified`, `lock_still_held`, `forced`) and exits 1.
+- **Shell jobs no longer leave processes behind (#5062).** On Linux and macOS a shell job runs in its own process group. Cancel, timeout and worker shutdown reach every descendant, a process that ignores SIGTERM is SIGKILLed after 5 seconds (the old check never escalated), and when the job's shell exits, anything it left running in its group is terminated before the job settles.
+- **Declaring `extract_atoms` in a schema pack no longer stops autopilot from running it (#5028).** On Postgres the daemon's routine cycles run only the freshness phases, so the auto-drain was the only thing that ran `extract_atoms`, and it skipped every brain whose pack declared the phase. It now runs regardless, within the existing threshold, `autopilot.auto_drain.max_usd_per_day` cap and one slot per source per UTC day. `gbrain doctor`'s `extract_atoms_backlog` check now reads the phase's own `last_extract_atoms_at` stamp, so a brain whose cycles run but whose atoms never get extracted warns instead of reporting OK.
+- **Dry runs and classic brains no longer pay to triage transcripts that are already synthesized (#5145).** Completed synthesis (both key families) is checked before the triage pass on every path. Synthesize details gain `synthesis_state: {candidates, already_synthesized}`; the triage counters and the "not yet triaged" note now cover only screened candidates.
+- **`cycle.consolidate.cluster_threshold` sets consolidate's cosine threshold (#5363),** default 0.85, any value in (0, 1], validated by `gbrain config set`. The old option was never wired. Facts with typed claims now share a take only when metric, unit and period all match: monthly vs annual, USD vs EUR, and typed vs untyped facts stay separate.
+- **`gbrain eval <subcommand> --help` prints that subcommand's usage (D-N1)** instead of the generic `eval --qrels` block (replay, gate, whoknows, trajectory, suspected-contradictions, retrieval-quality, compare, export, prune and the rest).
+- **The v0.28.0 migration's re-chunk reminder names a command that exists (D-N5):** `gbrain reindex --markdown`, not the nonexistent `gbrain extract takes --rebuild`. The v0.28.0 skill no longer cites two doctor checks that never shipped.
+
+## Upgrade notes (behavior changes worth a one-time notice)
+
+| Change | Who notices | What to do |
+|---|---|---|
+| `jobs work` exits 0 after a SIGTERM drain (was 143); exit 17 (`WORKER_EXIT_DRAIN_FORCED`) when claims still running after 30s had to be handed back | process managers and scripts that read the worker's exit code | treat 0 as a clean stop and 17 as a stop that interrupted work |
+| `jobs supervisor stop --json` gains `drained`, `checks`, `queue`; reason `timeout_40s` is now `timeout` (wait 45s); exits 1 unless the drain is verified | scripts parsing `stop` output | key on `drained` / `reason` |
+| A shell job's backgrounded processes (`cmd &` with no `wait`) are terminated when the job ends | shell jobs that intentionally start daemons | start long-lived processes under your service manager, or detach them into their own session (`setsid`) |
+| Brains whose pack declares `extract_atoms` start receiving the daily atom auto-drain on Postgres autopilot (bounded by `autopilot.auto_drain.max_usd_per_day`, default $2) | owners of declaring packs | `gbrain config set autopilot.auto_drain.enabled false` to opt out |
+| `extract_atoms_backlog` may warn right after upgrade on declaring-pack brains until the phase runs once and stamps the source | doctor readers | run the drain command the warning names, or wait for the next auto-drain |
+
+Recommended for the wave's `behavior_changes` notice: the shell-job process-group change and the declaring-pack auto-drain (spend that starts without a new opt-in, inside the existing default cap).
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index bdbc617b5b..98182ebba7 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -48,7 +48,6 @@ src/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 8
src/core/minions/handlers/subagent.ts runSubagentViaGateway 328 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/queue.ts MinionQueue.add 498 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/minions/queue.ts MinionQueue.add>result=this.engine.transaction(#0) 359 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/minions/worker.ts MinionWorker.executeJob 304 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 GBRA-40 Lane D: JobDeferredError routes to deferJob
src/core/minions/worker.ts MinionWorker.start 470 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/ops/facts.ts recall.handler 348 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/ops/search.ts query.handler 330 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index fe1ee6649d..8e3915b504 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -14,7 +14,7 @@ src/commands/serve-http.ts 926 ratchet refactor wave 1 W4 split into serve-http-
src/core/ai/gateway.ts 4408 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts)
src/commands/sync.ts 510 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured)
src/core/cycle.ts 3253 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge
-src/core/cycle/synthesize.ts 3312 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict)
+src/core/cycle/synthesize.ts 3200 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition
src/core/cycle/extract-atoms.ts 1809 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement)
src/core/engine.ts 2707 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso
src/core/import-file.ts 2179 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1864 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts)
+src/core/config.ts 1865 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 295cb8c9c3..fb79c5eb6d 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -58,7 +58,7 @@ test/check-bootstrap-guards.test.ts check-grok-pin.sh 9 readFileSync
test/check-bootstrap-guards.test.ts check-opencode-pin.sh 6 readFileSync
test/check-bootstrap-guards.test.ts verify + workflow wiring 4 readFileSync
test/check-update.test.ts check-update CLI 3 source-surface-helper
-test/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 3 readFileSync
+test/child-worker-supervisor.test.ts issue #1801 — restartCurrentChild + killChild liveness fix 4 readFileSync
test/chronicle-extract.test.ts runChronicleExtract 9 readFileSync
test/chronicle-upgrade-notice-5876.test.ts opt-out wording guard 1 exec-scan
test/chunkers/symbol-resolver.test.ts symbol-resolver source hygiene 1 readFileSync
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 673dbce106..f29e1f4407 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -118,7 +118,7 @@
"migrations/v0.23.0.md": "f0363274e5071fa35d0c60e3981c4caee0494c43adb254d65acf6b743d4762d5",
"migrations/v0.25.1.md": "981ef49abadf19a891cb68b655b9f35ee67d9f4ac232ceb29d83dfc3b1c9982e",
"migrations/v0.27.1.md": "719dd4ebcc7ac81413ee79af20f80de5141577e3860e5049a49fc8f6d09ddf89",
- "migrations/v0.28.0.md": "21929a392af2e1f454272e80aade6c58c5f6ccd7253d24344d08c6b53bcdf4f9",
+ "migrations/v0.28.0.md": "9b2e0b78ca3fef7bd590ecab8902b1120d7fdc37cc711cc71c65297cb4ceb3a1",
"migrations/v0.29.1.md": "7b85373a62a8500ee8c4238ffc9878318b44ee62543adb8b2462049c6c0cd1f8",
"migrations/v0.32.2.md": "88069b6ede3933aacb0555480bb730f75ca67602a5ae953f9f2a95a2bf6418a2",
"migrations/v0.32.6.md": "e9438a910afe8a1f7861c5222fd7db04a0f8d8b8283778476b07b7c3d539d3f0",
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 394daf92b6..e0dc115ab8 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -646,38 +646,6 @@ async function latestFullCycleEvidence(
}
}
-/** #5028: a backlog source whose extract_atoms stamp is older than this is stale. */
-const EXTRACT_ATOMS_PHASE_WARN_HOURS = 48;
-
-/**
- * #5028: backlog sources with no recent `last_extract_atoms_at` stamp (written
- * by stampExtractAtomsRun after the phase actually runs, from a dream cycle
- * or an auto-drain). The 48h window allows for the auto-drain's one slot per
- * UTC day. Fail-open: an unreadable sources table returns null (no warn).
- */
-async function sourcesWithStaleExtractAtomsRun(
- engine: BrainEngine,
- bySource: Array<{ source_id: string; backlog: number }>,
- nowMs = Date.now(),
-): Promise<Array<{ source_id: string; backlog: number; last_extract_atoms_at: string | null }> | null> {
- try {
- const { LAST_EXTRACT_ATOMS_AT_KEY } = await import('../../../core/cycle/extract-atoms.ts');
- const rows = await engine.executeRaw<{ id: string; stamp: string | null }>(
- `SELECT id, config->>$2 AS stamp FROM sources WHERE id = ANY($1::text[])`,
- [bySource.map((row) => row.source_id), LAST_EXTRACT_ATOMS_AT_KEY],
- );
- const stamps = new Map(rows.map((r) => [r.id, r.stamp]));
- return bySource
- .map((row) => ({ ...row, last_extract_atoms_at: stamps.get(row.source_id) ?? null }))
- .filter((row) => {
- const t = row.last_extract_atoms_at ? new Date(row.last_extract_atoms_at).getTime() : NaN;
- return !Number.isFinite(t) || nowMs - t > EXTRACT_ATOMS_PHASE_WARN_HOURS * 3_600_000;
- });
- } catch {
- return null;
- }
-}
-
/**
* #4576 review fix: can this brain's shape produce per-source
* last_full_cycle_at stamps at all? Two lanes write them:
@@ -734,6 +702,7 @@ export async function computeExtractAtomsBacklogCheck(
}
const { packDeclaresPhase } = await import('../../../core/cycle.ts');
+ const { extractAtomsPhaseStaleWarning } = await import('../../../core/cycle/extract-atoms-stamp.ts');
let declared = false;
try { declared = await packDeclaresPhase(engine, 'extract_atoms'); } catch { declared = false; }
@@ -800,35 +769,11 @@ export async function computeExtractAtomsBacklogCheck(
},
};
}
- // #5028: a recent cycle is not evidence that THIS phase ran: the
- // autopilot daemon's per-source cycles run only the freshness phases
- // yet stamp last_full_cycle_at. Require each backlog source's own
- // last_extract_atoms_at stamp to be recent.
+ // #5028: a recent cycle does not prove THIS phase ran; check each backlog source's own stamp.
if (evidence && evidence.state === 'fresh') {
- const backlogBySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog, opts.sourceIds);
- const phaseStale = backlogBySource ? await sourcesWithStaleExtractAtomsRun(engine, backlogBySource) : null;
- if (phaseStale && phaseStale.length > 0) {
- const drain = buildExtractAtomsDrainCommand(phaseStale);
- const ids = phaseStale.map((row) => row.source_id).join(', ');
- return {
- name, status: 'warn',
- message:
- `${backlog} page(s) pending and cycles run, but extract_atoms has not run in the last ` +
- `${EXTRACT_ATOMS_PHASE_WARN_HOURS}h for source(s) ${ids} (routine autopilot cycles run only the ` +
- `freshness phases; the daily auto-drain needs autopilot on Postgres and a backlog above ` +
- `autopilot.auto_drain.threshold). Drain now: ${drain}`,
- details: {
- backlog,
- backlog_by_source: backlogBySource ?? undefined,
- pack_declares_phase: true,
- cycle_evidence: 'fresh',
- phase_evidence: 'stale',
- phase_stale_sources: phaseStale,
- fix_hint: drain,
- known_approximation: approx,
- },
- };
- }
+ const bySource = await countExtractAtomsBacklogBySource(engine, countExtractAtomsBacklog, opts.sourceIds);
+ const phaseWarn = bySource ? await extractAtomsPhaseStaleWarning(engine, backlog, bySource, buildExtractAtomsDrainCommand, approx) : null;
+ if (phaseWarn) return { name, status: 'warn', ...phaseWarn };
}
// Pack runs it AND the phase ran recently (or the backlog is small,
// or evidence is unreadable — fail-open). Informational.
diff --git a/src/core/config.ts b/src/core/config.ts
index 1f547eae27..284483ec2f 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1520,9 +1520,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #4348: IANA timezone that owns the dream-cycle calendar day (summary
// bucketing). Unset → host timezone → UTC. Validated at set time.
'cycle.timezone',
- // #5363: consolidate phase cosine cluster threshold, (0, 1], default 0.85.
- // Read in src/core/cycle/phases/consolidate.ts; validated at set time.
- 'cycle.consolidate.cluster_threshold',
+ 'cycle.consolidate.cluster_threshold', // #5363: (0, 1], default 0.85; read + validated in cycle/phases/consolidate.ts
// A11: IANA timezone for offset-less frontmatter datetimes in effective_date.
// Unset → UTC (date-only values are always UTC calendar dates). Validated at set time.
'brain.timezone',
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index e15399b06c..e286cd6dbc 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -2394,7 +2394,7 @@ export async function runCycle(
});
} else {
progress.start('cycle.extract_atoms');
- const { runPhaseExtractAtoms } = await import('./cycle/extract-atoms.ts');
+ const { runPhaseExtractAtomsStamped: runPhaseExtractAtoms } = await import('./cycle/extract-atoms-stamp.ts');
const xaSourceId = cycleSourceId ?? 'default';
// v0.41.2.1 (D9 #5): union sync + synthesize affected slugs so the
// incremental discovery path doesn't miss pages just-written by the
@@ -2423,10 +2423,6 @@ export async function runCycle(
signal: xaSignal?.signal,
}), 'extract_atoms').finally(() => xaSignal?.dispose());
result.duration_ms = duration_ms;
- if (!dryRun) {
- const { stampExtractAtomsRun } = await import('./cycle/extract-atoms.ts');
- await stampExtractAtomsRun(engine, xaSourceId, result);
- }
phaseResults.push(result);
progress.finish();
}
diff --git a/src/core/cycle/extract-atoms-drain.ts b/src/core/cycle/extract-atoms-drain.ts
index 896f2a6aa6..5dc2423f28 100644
--- a/src/core/cycle/extract-atoms-drain.ts
+++ b/src/core/cycle/extract-atoms-drain.ts
@@ -457,7 +457,8 @@ export async function runExtractAtomsDrainForSource(
opts: DrainForSourceOpts,
): Promise<ExtractAtomsDrainResult> {
const { withRefreshingLock } = await import('../db-lock.ts');
- const { runPhaseExtractAtoms, countExtractAtomsBacklog, stampExtractAtomsRun } = await import('./extract-atoms.ts');
+ const { countExtractAtomsBacklog } = await import('./extract-atoms.ts');
+ const { runPhaseExtractAtomsStamped } = await import('./extract-atoms-stamp.ts');
const { cycleLockIdFor } = await import('../cycle.ts');
const { MaintenanceWriteWait } = await import('../persistence/maintenance-wait.ts');
@@ -472,7 +473,7 @@ export async function runExtractAtomsDrainForSource(
{
withLock: (work) => withRefreshingLock(engine, lockId, (signal) => work(signal), { ttlMinutes: 5 }),
runBatch: async ({ signal, stopSignal }) => {
- const r = await runPhaseExtractAtoms(engine, {
+ const r = await runPhaseExtractAtomsStamped(engine, {
sourceId: extractionSourceId,
dryRun: false,
brainDir: opts.brainDir,
@@ -480,7 +481,6 @@ export async function runExtractAtomsDrainForSource(
stopSignal,
attempt,
});
- await stampExtractAtomsRun(engine, extractionSourceId, r);
const d = (r.details ?? {}) as Record<string, unknown>;
// issue #3218: `r.status` collapses to 'warn' whether ONE item failed
// (partial success — leave the drain's existing ok/no_progress path
diff --git a/src/core/cycle/extract-atoms-stamp.ts b/src/core/cycle/extract-atoms-stamp.ts
new file mode 100644
index 0000000000..fd54ad866c
--- /dev/null
+++ b/src/core/cycle/extract-atoms-stamp.ts
@@ -0,0 +1,87 @@
+/**
+ * #5028: per-source evidence that extract_atoms actually ran. Freshness-only
+ * autopilot cycles stamp `last_full_cycle_at` without running this phase, so
+ * doctor judges the phase by its own `last_extract_atoms_at` stamp, written
+ * here by both runners (the dream cycle and the extract-atoms drain).
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
+import { runPhaseExtractAtoms, type ExtractAtomsOpts } from './extract-atoms.ts';
+
+/** sources.config key stamped after a pass of extract_atoms that ran. */
+export const LAST_EXTRACT_ATOMS_AT_KEY = 'last_extract_atoms_at';
+/** A backlog source whose stamp is older than this is stale (the auto-drain opens one slot per UTC day). */
+export const EXTRACT_ATOMS_PHASE_WARN_HOURS = 48;
+
+/**
+ * Stamp the source when the pass ran: status ok, or warn with at least one
+ * item processed. A pass where every item failed, or a skip, does not count.
+ * Best-effort: the stamp is evidence only and never fails the phase.
+ */
+export async function stampExtractAtomsRun(engine: BrainEngine, sourceId: string, result: PhaseResult): Promise<void> {
+ const d = (result.details ?? {}) as Record<string, unknown>;
+ const processed = Number(d.transcripts_processed ?? 0) + Number(d.pages_processed ?? 0);
+ if (result.status !== 'ok' && !(result.status === 'warn' && processed > 0)) return;
+ try { await engine.updateSourceConfig(sourceId, { [LAST_EXTRACT_ATOMS_AT_KEY]: new Date().toISOString() }); }
+ catch { /* evidence only */ }
+}
+
+/** runPhaseExtractAtoms, then stamp the source unless it was a dry run. */
+export async function runPhaseExtractAtomsStamped(engine: BrainEngine, opts: ExtractAtomsOpts = {}): Promise<PhaseResult> {
+ const result = await runPhaseExtractAtoms(engine, opts);
+ if (!opts.dryRun) await stampExtractAtomsRun(engine, opts.sourceId ?? 'default', result);
+ return result;
+}
+
+/**
+ * Backlog sources with no `last_extract_atoms_at` inside the warn window.
+ * Fail-open: an unreadable sources table returns null (callers do not warn).
+ */
+export async function sourcesWithStaleExtractAtomsRun(
+ engine: BrainEngine,
+ bySource: Array<{ source_id: string; backlog: number }>,
+ nowMs = Date.now(),
+): Promise<Array<{ source_id: string; backlog: number; last_extract_atoms_at: string | null }> | null> {
+ try {
+ const rows = await engine.executeRaw<{ id: string; stamp: string | null }>(
+ `SELECT id, config->>$2 AS stamp FROM sources WHERE id = ANY($1::text[])`,
+ [bySource.map((row) => row.source_id), LAST_EXTRACT_ATOMS_AT_KEY],
+ );
+ const stamps = new Map(rows.map((r) => [r.id, r.stamp]));
+ return bySource
+ .map((row) => ({ ...row, last_extract_atoms_at: stamps.get(row.source_id) ?? null }))
+ .filter((row) => {
+ const t = row.last_extract_atoms_at ? new Date(row.last_extract_atoms_at).getTime() : NaN;
+ return !Number.isFinite(t) || nowMs - t > EXTRACT_ATOMS_PHASE_WARN_HOURS * 3_600_000;
+ });
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The `extract_atoms_backlog` warning for a brain whose cycles run but whose
+ * backlog sources have no recent extract_atoms stamp, or null when every
+ * backlog source ran the phase inside the window (or the read failed).
+ */
+export async function extractAtomsPhaseStaleWarning(
+ engine: BrainEngine,
+ backlog: number,
+ bySource: Array<{ source_id: string; backlog: number }>,
+ drainCommand: (rows: Array<{ source_id: string; backlog: number }>) => string,
+ approx: string,
+): Promise<{ message: string; details: Record<string, unknown> } | null> {
+ const stale = await sourcesWithStaleExtractAtomsRun(engine, bySource);
+ if (!stale || stale.length === 0) return null;
+ const drain = drainCommand(stale);
+ return {
+ message:
+ `${backlog} page(s) pending and cycles run, but extract_atoms has not run in the last ${EXTRACT_ATOMS_PHASE_WARN_HOURS}h ` +
+ `for source(s) ${stale.map((r) => r.source_id).join(', ')} (routine autopilot cycles run only the freshness phases; ` +
+ `the daily auto-drain needs autopilot on Postgres and a backlog above autopilot.auto_drain.threshold). Drain now: ${drain}`,
+ details: {
+ backlog, backlog_by_source: bySource, pack_declares_phase: true, cycle_evidence: 'fresh',
+ phase_evidence: 'stale', phase_stale_sources: stale, fix_hint: drain, known_approximation: approx,
+ },
+ };
+}
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 72b67356bd..a3ea434086 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -684,26 +684,6 @@ export async function resolveExtractAtomsModel(engine: BrainEngine): Promise<str
* discoverTranscripts + discoverExtractablePages (both lazy-imported
* to avoid circular module loads and to keep PGLite-only tests fast).
*/
-/** #5028: sources.config key stamped after a pass of extract_atoms that ran. */
-export const LAST_EXTRACT_ATOMS_AT_KEY = 'last_extract_atoms_at';
-
-/**
- * #5028: record that extract_atoms actually ran for a source, so doctor can
- * judge the phase's own freshness instead of `last_full_cycle_at` (which
- * freshness-only cycles stamp without running this phase). Counts a pass
- * that finished ok, or warned with at least one item processed; a pass where
- * every item failed, or a skip, does not stamp; callers skip dry runs.
- * Best-effort.
- */
-export async function stampExtractAtomsRun(engine: BrainEngine, sourceId: string, result: PhaseResult): Promise<void> {
- const d = (result.details ?? {}) as Record<string, unknown>;
- const processed = Number(d.transcripts_processed ?? 0) + Number(d.pages_processed ?? 0);
- const ran = result.status === 'ok' || (result.status === 'warn' && processed > 0);
- if (!ran) return;
- try { await engine.updateSourceConfig(sourceId, { [LAST_EXTRACT_ATOMS_AT_KEY]: new Date().toISOString() }); }
- catch { /* the stamp is evidence only; never fail the phase over it */ }
-}
-
export async function runPhaseExtractAtoms(
engine: BrainEngine,
opts: ExtractAtomsOpts = {},
diff --git a/src/core/cycle/synthesize-completion.ts b/src/core/cycle/synthesize-completion.ts
new file mode 100644
index 0000000000..b45a592ecd
--- /dev/null
+++ b/src/core/cycle/synthesize-completion.ts
@@ -0,0 +1,171 @@
+/**
+ * Synthesis completion keys: which transcripts a prior dream run already
+ * synthesized (the legacy `dream:synth:` path-keyed family and the synth-v2
+ * source-identity family), read from completed subagent jobs and the durable
+ * dream_synthesis_completions archive. Peeled from synthesize.ts with #5145,
+ * which moved the completion check ahead of the paid triage pass.
+ */
+import { basename } from 'node:path';
+import type { BrainEngine } from '../engine.ts';
+import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import type { DiscoveredTranscript } from './transcript-discovery.ts';
+
+/**
+ * #5145: split transcripts into already-synthesized and candidates BEFORE the
+ * paid triage pass. Classic brains (no maintenance) and dry runs (maintenance
+ * forced null) used to triage completed transcripts first and only skip them
+ * afterwards, re-buying triage whenever the verdict cache expired. Legacy
+ * `dream:synth:` keys count on classic brains only (as the fan-out always
+ * did); a dry run on a managed brain reads the source incarnation read-only
+ * so its synth-v2 keys match the identity a real run would use. The key lists
+ * are returned for the fan-out's own per-transcript checks.
+ */
+export async function partitionCompletedSynthesis(
+ engine: BrainEngine,
+ transcripts: DiscoveredTranscript[],
+ sourceId: string,
+ maintenance: MaintenanceAuthority | null,
+ dryRun: boolean,
+): Promise<{ completed: Set<string>; successfulLegacyKeys: string[]; successfulV2Keys: string[]; synthesisIdentity: string }> {
+ const incarnation = maintenance
+ ? maintenance.writer.sourceIncarnation
+ : dryRun ? await readManagedSourceIncarnation(engine, sourceId) : null;
+ const synthesisIdentity = incarnation !== null ? `${sourceId}/${incarnation}` : sourceId;
+ const successfulV2Keys = await loadSuccessfulSynthesisKeys(engine, sourceId, 'dream:synth-v2:');
+ const successfulLegacyKeys = incarnation !== null ? [] : await loadSuccessfulSynthesisKeys(engine, sourceId, 'dream:synth:');
+ const completed = new Set(transcripts.filter(t => {
+ const hash16 = t.contentHash.slice(0, 16);
+ return findLegacyCompletion(successfulLegacyKeys, t.filePath, hash16) !== null
+ || findSynthV2Completion(successfulV2Keys, t.filePath, hash16, synthesisIdentity) !== null;
+ }).map(t => t.filePath));
+ return { completed, successfulLegacyKeys, successfulV2Keys, synthesisIdentity };
+}
+
+/**
+ * #5145: the source incarnation a managed real run would key its synth-v2
+ * completions under, read without the write preflight (dry runs never
+ * register a writer). Null on a classic brain or when the read fails.
+ */
+async function readManagedSourceIncarnation(engine: BrainEngine, sourceId: string): Promise<string | null> {
+ try {
+ if (!await managedPersistenceEnabled(engine)) return null;
+ const [row] = await engine.executeRaw<{ incarnation: string | null }>('SELECT incarnation FROM sources WHERE id = $1', [sourceId]);
+ return row?.incarnation ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Load every `completed` subagent job key in one synthesis key family for
+ * one source. Called once per phase per family so the submit loop can skip
+ * transcripts already synthesized BEFORE building their link manifest:
+ * - D8 legacy `dream:synth:<filePath>:<hash16>[:c<i>of<n>]` (pre-v2 shape;
+ * must not be re-submitted under v2 keys);
+ * - current `dream:synth-v2:<source>:filename:<basename>:<hash16>[:c<i>of<n>]`
+ * (the queue's idempotency dedupe would coalesce these too, but only after
+ * the manifest build, and the coalesced children would re-enter writtenRefs).
+ * `dream:synth:%` does not match `dream:synth-v2:` keys.
+ *
+ * Plain `status = 'completed'` deliberately mirrors the queue-level
+ * idempotency semantics the legacy keys relied on: a completed job blocks
+ * re-submission regardless of `result.stop_reason` (pinned in
+ * test/minions.test.ts). Filtering on stop_reason here would re-pay for
+ * transcripts the old code path never re-ran, and reading `result` at all
+ * would need the `(result #>> '{}')` double-encoded-jsonb defense.
+ *
+ * Completed rows that `jobs prune` removed live on in
+ * `dream_synthesis_completions` (the prune archives them), so pruning never
+ * makes a synthesized transcript eligible again. Loads source-scoped
+ * completions once per phase; no repeated history scan per transcript.
+ */
+async function loadSuccessfulSynthesisKeys(
+ engine: BrainEngine,
+ sourceId: string,
+ keyPrefix: 'dream:synth:' | 'dream:synth-v2:',
+): Promise<string[]> {
+ const rows = await engine.executeRaw<{ idempotency_key: string }>(
+ `SELECT idempotency_key
+ FROM minion_jobs
+ WHERE name = 'subagent'
+ AND status = 'completed'
+ AND COALESCE(NULLIF(data->>'source_id', ''), 'default') = $1
+ AND idempotency_key LIKE $2
+ UNION
+ SELECT idempotency_key FROM dream_synthesis_completions
+ WHERE source_id = $1 AND idempotency_key LIKE $2`,
+ [sourceId, `${keyPrefix}%`],
+ );
+ return rows.map(row => row.idempotency_key);
+}
+
+/**
+ * Mirror of findLegacyCompletion for the synth-v2 key family (grammar as
+ * produced by the submit loop / parsed by `parseSynthV2Key`): `'single'` when
+ * the unchunked key completed, `'chunked'` when a FULL `:c0of<n>`..`:c<n-1>of<n>`
+ * set completed, null otherwise (a cancelled row never counts).
+ */
+export function findSynthV2Completion(
+ successfulKeys: string[],
+ filePath: string,
+ hash16: string,
+ sourceId: string,
+): 'single' | 'chunked' | null {
+ const prefix =
+ `dream:synth-v2:${encodeURIComponent(sourceId)}` +
+ `:filename:${encodeURIComponent(basename(filePath))}:${hash16}`;
+ const chunkSets = new Map<number, Set<number>>();
+ for (const key of successfulKeys) {
+ if (key === prefix) return 'single';
+ if (!key.startsWith(prefix + ':c')) continue;
+ const chunk = /:c(\d+)of(\d+)$/.exec(key);
+ if (!chunk) continue;
+ const i = Number(chunk[1]);
+ const n = Number(chunk[2]);
+ if (n < 1 || i < 0 || i >= n) continue;
+ let seen = chunkSets.get(n);
+ if (!seen) chunkSets.set(n, seen = new Set());
+ seen.add(i);
+ }
+ for (const [n, seen] of chunkSets) {
+ if (seen.size === n) return 'chunked';
+ }
+ return null;
+}
+
+/**
+ * Match a transcript (by filename + content hash) against completed legacy
+ * keys. `'single'` when a `dream:synth:<path>:<hash16>` completion exists;
+ * `'chunked'` when a FULL chunk set `:c0of<n>`..`:c<n-1>of<n>` completed
+ * (chunk indices are 0-based). Partial chunk sets return null so the
+ * transcript gets a fresh v2 synthesis instead of shipping with holes.
+ */
+export function findLegacyCompletion(
+ successfulKeys: string[],
+ filePath: string,
+ hash16: string,
+): 'single' | 'chunked' | null {
+ const filename = basename(filePath);
+ const hashSuffix = `:${hash16}`;
+ /** total chunk count n → completed 0-based chunk indices */
+ const chunkSets = new Map<number, Set<number>>();
+ for (const key of successfulKeys) {
+ const chunk = /:c(\d+)of(\d+)$/.exec(key);
+ const base = chunk ? key.slice(0, -chunk[0].length) : key;
+ if (!base.endsWith(hashSuffix)) continue;
+ const historicalPath = base.slice('dream:synth:'.length, -hashSuffix.length);
+ if (basename(historicalPath) !== filename) continue;
+ if (!chunk) return 'single';
+ const i = Number(chunk[1]);
+ const n = Number(chunk[2]);
+ if (n < 1 || i < 0 || i >= n) continue;
+ let seen = chunkSets.get(n);
+ if (!seen) chunkSets.set(n, seen = new Set());
+ seen.add(i);
+ }
+ for (const [n, seen] of chunkSets) {
+ if (seen.size === n) return 'chunked';
+ }
+ return null;
+}
diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.ts
index d7213a897a..6c02d8b215 100644
--- a/src/core/cycle/synthesize.ts
+++ b/src/core/cycle/synthesize.ts
@@ -76,7 +76,7 @@ import { resolveCycleDate, utcDate } from './cycle-date.ts';
import { throwIfAborted } from '../abort-check.ts';
import { stampDreamProvenance } from './dream-provenance.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
-import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { findLegacyCompletion, findSynthV2Completion, partitionCompletedSynthesis } from './synthesize-completion.ts';
// Re-exports: the drain was peeled to inline-drain.ts (dream-wave C7), the
// allow-list loader to filing-rules.ts (#2397); patterns.ts and the
@@ -528,24 +528,7 @@ async function runPhaseSynthesizeInner(
process.stderr.write(`[dream] warning: verdict cache sweep failed: ${e instanceof Error ? e.message : String(e)}\n`);
}
- // #5145: completed synthesis is checked BEFORE the paid triage pass on
- // every path. Classic brains (no maintenance) and dry runs (maintenance
- // forced null) used to triage completed transcripts first and only skip
- // them afterwards, re-buying triage whenever the verdict cache expired.
- // A dry run on a managed brain reads the source incarnation (read-only)
- // so its v2 keys match the identity a real run would use.
- const synthSourceId = opts.sourceId ?? 'default';
- const managedIncarnation = maintenance
- ? maintenance.writer.sourceIncarnation
- : opts.dryRun ? await readManagedSourceIncarnation(engine, synthSourceId) : null;
- const synthesisIdentity = managedIncarnation !== null ? `${synthSourceId}/${managedIncarnation}` : synthSourceId;
- const retainedKeys = await loadSuccessfulSynthesisKeys(engine, synthSourceId, 'dream:synth-v2:');
- const legacyKeys = managedIncarnation !== null ? [] : await loadSuccessfulSynthesisKeys(engine, synthSourceId, 'dream:synth:');
- const completed = new Set(transcripts.filter(t => {
- const hash16 = t.contentHash.slice(0, 16);
- return findLegacyCompletion(legacyKeys, t.filePath, hash16) !== null
- || findSynthV2Completion(retainedKeys, t.filePath, hash16, synthesisIdentity) !== null;
- }).map(t => t.filePath));
+ const { completed, successfulLegacyKeys, successfulV2Keys, synthesisIdentity } = await partitionCompletedSynthesis(engine, transcripts, opts.sourceId ?? 'default', maintenance, opts.dryRun);
const synthesisState = { candidates: transcripts.length - completed.size, already_synthesized: completed.size };
const pass = await runTriagePass(engine, transcripts.filter(t => !completed.has(t.filePath)), {
model: config.triage.model,
@@ -557,10 +540,6 @@ async function runPhaseSynthesizeInner(
signal: opts.signal,
rescue: rescueConfigOf(config.triage), decide: await resolveTriageDecide(engine),
}, opts.yieldDuringPhase);
- // Completed transcripts flow on to the fan-out loop, which records their
- // already_synthesized skip (classic) or collects their completed children
- // (managed). They are not screening results: the triage counters below
- // describe only the candidates that were actually screened.
pass.reports.push(...transcripts.filter(t => completed.has(t.filePath)).map(t => ({ filePath: t.filePath,
worth: true, score: null, content_type: null, cached: true, reasons: ['retained_completed_output'] })));
const verdicts = pass.reports;
@@ -611,9 +590,7 @@ async function runPhaseSynthesizeInner(
// synthesis. Codex finding #8: --dry-run does NOT mean "zero LLM calls";
// it means "skip the synthesis model."
if (opts.dryRun) {
- const wouldSynthesize = worthProcessing.filter(t => !completed.has(t.filePath)).length;
- const doneSuffix = completed.size > 0 ? `; ${completed.size} already synthesized` : '';
- return ok(`dry-run: ${wouldSynthesize} of ${synthesisState.candidates} transcripts would synthesize${doneSuffix}${deferralSuffix}`, {
+ return ok(`dry-run: ${worthProcessing.length - completed.size} of ${synthesisState.candidates} transcripts would synthesize${completed.size ? `; ${completed.size} already synthesized` : ''}${deferralSuffix}`, {
transcripts_discovered: transcripts.length,
transcripts_processed: 0,
pages_written: 0,
@@ -702,8 +679,6 @@ async function runPhaseSynthesizeInner(
const skipReports: Array<{ filePath: string; reason: string }> = [];
const maxCharsPerChunk = computeChunkCharBudget(config.model, config.maxPromptTokens);
- const successfulLegacyKeys = legacyKeys;
- const successfulV2Keys = retainedKeys;
// Per-source daily submission cap (D2D: default 0 = disabled; opt-in
// backstop via dream.synthesize.max_submissions_per_source_per_day).
@@ -2961,134 +2936,6 @@ async function collectChildPutPageSlugs(
});
}
-/**
- * Load every `completed` subagent job key in one synthesis key family for
- * one source. Called once per phase per family so the submit loop can skip
- * transcripts already synthesized BEFORE building their link manifest:
- * - D8 legacy `dream:synth:<filePath>:<hash16>[:c<i>of<n>]` (pre-v2 shape;
- * must not be re-submitted under v2 keys);
- * - current `dream:synth-v2:<source>:filename:<basename>:<hash16>[:c<i>of<n>]`
- * (the queue's idempotency dedupe would coalesce these too, but only after
- * the manifest build, and the coalesced children would re-enter writtenRefs).
- * `dream:synth:%` does not match `dream:synth-v2:` keys.
- *
- * Plain `status = 'completed'` deliberately mirrors the queue-level
- * idempotency semantics the legacy keys relied on: a completed job blocks
- * re-submission regardless of `result.stop_reason` (pinned in
- * test/minions.test.ts). Filtering on stop_reason here would re-pay for
- * transcripts the old code path never re-ran, and reading `result` at all
- * would need the `(result #>> '{}')` double-encoded-jsonb defense.
- *
- * Completed rows that `jobs prune` removed live on in
- * `dream_synthesis_completions` (the prune archives them), so pruning never
- * makes a synthesized transcript eligible again. Loads source-scoped
- * completions once per phase; no repeated history scan per transcript.
- */
-/**
- * #5145: the source incarnation a managed real run would key its synth-v2
- * completions under, read without the write preflight (dry runs never
- * register a writer). Null on a classic brain or when the read fails.
- */
-async function readManagedSourceIncarnation(engine: BrainEngine, sourceId: string): Promise<string | null> {
- try {
- if (!await managedPersistenceEnabled(engine)) return null;
- const [row] = await engine.executeRaw<{ incarnation: string | null }>('SELECT incarnation FROM sources WHERE id = $1', [sourceId]);
- return row?.incarnation ?? null;
- } catch {
- return null;
- }
-}
-
-async function loadSuccessfulSynthesisKeys(
- engine: BrainEngine,
- sourceId: string,
- keyPrefix: 'dream:synth:' | 'dream:synth-v2:',
-): Promise<string[]> {
- const rows = await engine.executeRaw<{ idempotency_key: string }>(
- `SELECT idempotency_key
- FROM minion_jobs
- WHERE name = 'subagent'
- AND status = 'completed'
- AND COALESCE(NULLIF(data->>'source_id', ''), 'default') = $1
- AND idempotency_key LIKE $2
- UNION
- SELECT idempotency_key FROM dream_synthesis_completions
- WHERE source_id = $1 AND idempotency_key LIKE $2`,
- [sourceId, `${keyPrefix}%`],
- );
- return rows.map(row => row.idempotency_key);
-}
-
-/**
- * Mirror of findLegacyCompletion for the synth-v2 key family (grammar as
- * produced by the submit loop / parsed by `parseSynthV2Key`): `'single'` when
- * the unchunked key completed, `'chunked'` when a FULL `:c0of<n>`..`:c<n-1>of<n>`
- * set completed, null otherwise (a cancelled row never counts).
- */
-function findSynthV2Completion(
- successfulKeys: string[],
- filePath: string,
- hash16: string,
- sourceId: string,
-): 'single' | 'chunked' | null {
- const prefix =
- `dream:synth-v2:${encodeURIComponent(sourceId)}` +
- `:filename:${encodeURIComponent(basename(filePath))}:${hash16}`;
- const chunkSets = new Map<number, Set<number>>();
- for (const key of successfulKeys) {
- if (key === prefix) return 'single';
- if (!key.startsWith(prefix + ':c')) continue;
- const chunk = /:c(\d+)of(\d+)$/.exec(key);
- if (!chunk) continue;
- const i = Number(chunk[1]);
- const n = Number(chunk[2]);
- if (n < 1 || i < 0 || i >= n) continue;
- let seen = chunkSets.get(n);
- if (!seen) chunkSets.set(n, seen = new Set());
- seen.add(i);
- }
- for (const [n, seen] of chunkSets) {
- if (seen.size === n) return 'chunked';
- }
- return null;
-}
-
-/**
- * Match a transcript (by filename + content hash) against completed legacy
- * keys. `'single'` when a `dream:synth:<path>:<hash16>` completion exists;
- * `'chunked'` when a FULL chunk set `:c0of<n>`..`:c<n-1>of<n>` completed
- * (chunk indices are 0-based). Partial chunk sets return null so the
- * transcript gets a fresh v2 synthesis instead of shipping with holes.
- */
-function findLegacyCompletion(
- successfulKeys: string[],
- filePath: string,
- hash16: string,
-): 'single' | 'chunked' | null {
- const filename = basename(filePath);
- const hashSuffix = `:${hash16}`;
- /** total chunk count n → completed 0-based chunk indices */
- const chunkSets = new Map<number, Set<number>>();
- for (const key of successfulKeys) {
- const chunk = /:c(\d+)of(\d+)$/.exec(key);
- const base = chunk ? key.slice(0, -chunk[0].length) : key;
- if (!base.endsWith(hashSuffix)) continue;
- const historicalPath = base.slice('dream:synth:'.length, -hashSuffix.length);
- if (basename(historicalPath) !== filename) continue;
- if (!chunk) return 'single';
- const i = Number(chunk[1]);
- const n = Number(chunk[2]);
- if (n < 1 || i < 0 || i >= n) continue;
- let seen = chunkSets.get(n);
- if (!seen) chunkSets.set(n, seen = new Set());
- seen.add(i);
- }
- for (const [n, seen] of chunkSets) {
- if (seen.size === n) return 'chunked';
- }
- return null;
-}
-
// ── Reverse-write DB rows → markdown files ───────────────────────────
async function reverseWriteRefs(
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index ac580289ea..6be9038c0f 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -2029,25 +2029,6 @@ export class MinionQueue {
}
}
- /**
- * #5062: hand a claim back to the queue because the worker is shutting
- * down (token-fenced; attempts_made is untouched). Returns false when the
- * claim already moved on (reclaimed, completed, cancelled).
- */
- async releaseShutdownJob(id: number, lockToken: string): Promise<boolean> {
- const rows = await this.engine.executeRaw<{ id: number }>(
- `UPDATE minion_jobs SET
- status = 'waiting',
- error_text = 'worker_shutdown',
- started_at = NULL, timeout_at = NULL,
- lock_token = NULL, lock_until = NULL, updated_at = now()
- WHERE id = $1 AND status = 'active' AND lock_token = $2
- RETURNING id`,
- [id, lockToken],
- );
- return rows.length > 0;
- }
-
/** Update job progress (token-fenced). */
async updateProgress(id: number, lockToken: string, progress: unknown): Promise<boolean> {
const rows = await this.engine.executeRaw<Record<string, unknown>>(
diff --git a/src/core/minions/worker-shutdown.ts b/src/core/minions/worker-shutdown.ts
new file mode 100644
index 0000000000..984da52896
--- /dev/null
+++ b/src/core/minions/worker-shutdown.ts
@@ -0,0 +1,61 @@
+/**
+ * #5062: settling a worker's claims when it shuts down. A claim whose handler
+ * ended because of the shutdown (the shell handler terminated its process
+ * group), or that is still running when the 30s drain expires, goes back to
+ * the queue token-fenced with no attempt burned, instead of sitting `active`
+ * until its lease expires and the stall sweep charges a stall.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { MinionJob } from './types.ts';
+
+/** Hand one claim back to `waiting`. False when the claim already moved on. */
+export async function releaseShutdownClaim(engine: BrainEngine, id: number, lockToken: string): Promise<boolean> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `UPDATE minion_jobs SET
+ status = 'waiting',
+ error_text = 'worker_shutdown',
+ started_at = NULL, timeout_at = NULL,
+ lock_token = NULL, lock_until = NULL, updated_at = now()
+ WHERE id = $1 AND status = 'active' AND lock_token = $2
+ RETURNING id`,
+ [id, lockToken],
+ );
+ return rows.length > 0;
+}
+
+/**
+ * A handler ended during shutdown. `stopped` is false only for an isolated
+ * child whose termination was not confirmed; that claim is left for the
+ * stall sweep so a still-running child cannot overlap a new claimant.
+ */
+export async function settleShutdownInterruptedJob(
+ engine: BrainEngine, job: MinionJob, lockToken: string, errorText: string, stopped: boolean,
+): Promise<void> {
+ if (!stopped) {
+ console.log(`Job ${job.id} (${job.name}) released after worker shutdown (${errorText}); stall detector will requeue (no attempt burned)`);
+ return;
+ }
+ try {
+ const released = await releaseShutdownClaim(engine, job.id, lockToken);
+ console.log(`Job ${job.id} (${job.name}) ${released ? 'handed back to the queue' : 'claim already moved on'} after worker shutdown (${errorText}; no attempt burned)`);
+ } catch (e) {
+ console.error(`[worker] shutdown release failed for job ${job.id}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+}
+
+/** After the drain window: hand back every claim still held. Returns true when any was. */
+export async function releaseUndrainedClaims(
+ engine: BrainEngine, executions: Iterable<{ job: MinionJob; lockToken: string }>,
+): Promise<boolean> {
+ let any = false;
+ for (const { job, lockToken } of executions) {
+ any = true;
+ try {
+ const released = await releaseShutdownClaim(engine, job.id, lockToken);
+ console.warn(`Job ${job.id} (${job.name}) did not finish within the shutdown drain; ${released ? 'handed back to the queue (no attempt burned).' : 'claim already moved on (lock token mismatch).'}`);
+ } catch (e) {
+ console.error(`[worker] shutdown release failed for job ${job.id}: ${e instanceof Error ? e.message : String(e)}`);
+ }
+ }
+ return any;
+}
diff --git a/src/core/minions/worker.ts b/src/core/minions/worker.ts
index 262dde6595..e366ff0117 100644
--- a/src/core/minions/worker.ts
+++ b/src/core/minions/worker.ts
@@ -86,6 +86,7 @@ export const INFRASTRUCTURE_ABORT_REASONS = new Set<string>([
import { randomUUID } from 'crypto';
import { EventEmitter } from 'events';
import { evaluateQuietHours, type QuietHoursConfig } from './quiet-hours.ts';
+import { releaseUndrainedClaims, settleShutdownInterruptedJob } from './worker-shutdown.ts';
import { readFileSync } from 'fs';
/**
@@ -235,7 +236,7 @@ export class MinionWorker extends EventEmitter {
private jobsCompleted = 0;
/** Idempotency latch for gracefulShutdown — per-job and periodic check sites can race. */
private gracefulShutdownFired = false;
- private _drainForced = false;
+ drainForced = false; // #5062: the shutdown drain expired and running claims were handed back (`jobs work` exits 17)
/**
* Set true when the RSS watchdog (not a normal SIGTERM) initiated the
* drain. The CLI handler (src/commands/jobs.ts case 'work') reads this
@@ -938,14 +939,12 @@ export class MinionWorker extends EventEmitter {
} else if (this.executions.size > 0) {
console.log(`Waiting for ${this.executions.size} in-flight job(s) to finish (30s timeout)...`);
const pending = Array.from(this.executions.values()).map(f => f.promise);
- let drainTimer: ReturnType<typeof setTimeout> | undefined;
await Promise.race([
Promise.allSettled(pending),
- new Promise(resolve => { drainTimer = setTimeout(resolve, 30000); }),
+ new Promise(resolve => setTimeout(resolve, 30000)),
]);
- clearTimeout(drainTimer);
if (this.configurationError) await this.drainConfiguration();
- else await this.releaseUndrainedClaims();
+ else this.drainForced = await releaseUndrainedClaims(this.engine, this.executions.values());
}
// The worker does NOT disconnect the engine: it doesn't own the
@@ -1042,60 +1041,11 @@ export class MinionWorker extends EventEmitter {
}
}
- /**
- * #5062: begin the signal-driven shutdown (SIGTERM / SIGINT, or the CLI's
- * signal-owner callback for SIGHUP and a broken pipe). Stops claiming and
- * fires `shutdownSignal` so handlers that own processes (shell) terminate
- * them; start() then drains in-flight jobs and resolves. Idempotent.
- */
+ /** #5062: signal-driven shutdown entry (SIGTERM/SIGINT, or the `jobs work` signal owner). Idempotent. */
requestShutdown(): void {
- if (this.shutdownAbort.signal.aborted && !this.running) return;
- console.log('Minion worker shutting down...');
+ if (this.running) console.log('Minion worker shutting down...');
this.running = false;
- if (!this.shutdownAbort.signal.aborted) {
- this.shutdownAbort.abort(new Error('shutdown'));
- }
- }
-
- /**
- * #5062: true when the shutdown drain timed out and in-flight claims had to
- * be handed back while their handlers were still running. The CLI exits
- * with WORKER_EXIT_DRAIN_FORCED so a supervisor never reports `drained`.
- */
- get drainForced(): boolean {
- return this._drainForced;
- }
-
- /** #5062: after the 30s shutdown drain, hand every claim still held back to
- * the queue (token-fenced, no attempt burned) instead of leaving it active
- * until its lease expires and the stall sweep charges a stall. */
- private async releaseUndrainedClaims(): Promise<void> {
- const remaining = Array.from(this.executions.values());
- if (remaining.length === 0) return;
- this._drainForced = true;
- for (const execution of remaining) {
- try {
- const released = await this.queue.releaseShutdownJob(execution.job.id, execution.lockToken);
- console.warn(
- `Job ${execution.job.id} (${execution.job.name}) did not finish within the shutdown drain; ` +
- (released ? 'handed back to the queue (no attempt burned).' : 'claim already moved on (lock token mismatch).'),
- );
- } catch (e) {
- console.error(`[worker] shutdown release failed for job ${execution.job.id}: ${e instanceof Error ? e.message : String(e)}`);
- }
- }
- }
-
- private async releaseAfterShutdown(job: MinionJob, lockToken: string, errorText: string): Promise<void> {
- try {
- const released = await this.queue.releaseShutdownJob(job.id, lockToken);
- console.log(
- `Job ${job.id} (${job.name}) ${released ? 'handed back to the queue' : 'claim already moved on'} ` +
- `after worker shutdown (${errorText}; no attempt burned)`,
- );
- } catch (e) {
- console.error(`[worker] shutdown release failed for job ${job.id}: ${e instanceof Error ? e.message : String(e)}`);
- }
+ if (!this.shutdownAbort.signal.aborted) this.shutdownAbort.abort(new Error('shutdown'));
}
/** Stop the worker gracefully. */
@@ -1690,23 +1640,8 @@ export class MinionWorker extends EventEmitter {
}
return;
}
- if (err instanceof ChildWorkerShutdownError) {
- if (err.executionStopped === true) {
- await this.releaseAfterShutdown(job, lockToken, errorText);
- return;
- }
- console.log(
- `Job ${job.id} (${job.name}) released after worker shutdown (${errorText}); ` +
- `stall detector will requeue (no attempt burned)`,
- );
- return;
- }
- // #5062: the handler ended because the worker is shutting down (the
- // shell handler terminated its process group), not because the job
- // failed. Hand the claim back instead of burning an attempt.
- if (!isolated && this.shutdownAbort.signal.aborted && !abort.signal.aborted) {
- await this.releaseAfterShutdown(job, lockToken, errorText);
- return;
+ if (err instanceof ChildWorkerShutdownError || (!isolated && this.shutdownAbort.signal.aborted && !abort.signal.aborted)) {
+ return settleShutdownInterruptedJob(this.engine, job, lockToken, errorText, !(err instanceof ChildWorkerShutdownError) || err.executionStopped === true);
}
if (err instanceof ChildNotClaimedError) {
// The child proved the claim is gone (reclaimed/cancelled before the
diff --git a/test/autopilot-auto-drain-declared-pack-5028.test.ts b/test/autopilot-auto-drain-declared-pack-5028.test.ts
index 1a9b79806e..be4b919bfc 100644
--- a/test/autopilot-auto-drain-declared-pack-5028.test.ts
+++ b/test/autopilot-auto-drain-declared-pack-5028.test.ts
@@ -19,7 +19,7 @@ import { SOURCE_FRESHNESS_PHASES, MAINTENANCE_PHASES, packDeclaresPhase } from '
import { __setPackLocatorForTests, _resetPackLocatorForTests } from '../src/core/schema-pack/load-active.ts';
import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
import { withEnv } from './helpers/with-env.ts';
-import { stampExtractAtomsRun } from '../src/core/cycle/extract-atoms.ts';
+import { stampExtractAtomsRun } from '../src/core/cycle/extract-atoms-stamp.ts';
let engine: PGLiteEngine;
let queue: MinionQueue;