Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): pattern claims share one lossless reflection list, the patterns breaker counts deaths per source, and no child runs while a rewrite is held (#6236)

time-attack183a3239dd6e
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index ced1e3e3e6..1fbf8aa631 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) through `requireConsent` (effect `paid`; `--yes`, `--max-usd`, tokenmax or a per-run preapproval authorize it; otherwise a TTY prompt or exit 3 with the consent payload, `--json` never implying it); the budget (`--max-usd`, else the derived consent cap) soft-stops via the pass's `shouldStop` seam (estimate-based) and bounds the `--audit-rejects` half. `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).
-- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter.
+- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter. Its help names the per-source patterns key `dream:patterns:source:<id>`; doctor `dream_paid_loop` reports that prefix as the key's `key_prefix`.
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index ccdcda282c..9300fddd11 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -6,7 +6,7 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`.
-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`.
+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`).
- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.
- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index c62f1d7f0c..142ebf6aee 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -37,7 +37,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/nightly-quality-probe.ts` + `src/core/audit-quality-probe.ts` + `test/fixtures/longmemeval-nightly.jsonl` + `test/nightly-quality-probe.test.ts` — opt-in nightly cross-modal quality probe. The phase runs `gbrain eval longmemeval --by-type` against the committed 10-question placeholder fixture, pipes output through `gbrain eval cross-modal --batch --max-usd 5 --yes`, and writes one event per run to `~/.gbrain/audit/quality-probe-YYYY-Www.jsonl` (ISO-week-rotated, mirrors `audit-slug-fallback.ts`; honors `GBRAIN_AUDIT_DIR`). Default DISABLED — opt-in via `gbrain config set autopilot.nightly_quality_probe.enabled true` (prevents surprise API spend). 24h rate limit (pure `shouldRunNightly(now, recentEvents, windowMs?)`) skips without an audit row. An unreadable fixture writes `outcome: skipped` with `reason: fixture_unavailable` (exit 0, no model call; the row also holds the 24h gate). Embedding-key short-circuit: longmemeval needs `gateway.embedQuery()`, so the phase exits early with `outcome: no_embedding_key` + stderr warn when no provider configured. Full DI surface via `NightlyProbeDeps` (`isEnabled`, `hasEmbeddingProvider`, `resolveMaxUsd`, optional `resolveBudgetPolicy`, `resolveFixturePath` (wins) / `resolveRepoRoot`, `resolveSearchConfigSnapshot` and `resolveModelRoutes`, `runLongMemEval`, `runCrossModalBatch`, `now`) so the unit test stubs every external effect. `resolveModelRoutes` runs inside the run's `try` before LongMemEval and its routes reach both adapters; a rejection becomes an `error` audit row naming the model routes and LongMemEval never starts. Rows also carry the evidence behind the verdict (#5506), every field optional so older rows read unchanged (`logQualityProbeEvent` copies them from one explicit list): `reader_model` / `extractor_model` once the routes resolved; `judge_models` in slot order, `judge_scored_questions` per slot, and `distinct_judge_models` / `distinct_judge_providers` over the slots that scored, from a completed batch; on a non-pass row, up to 10 `failures` (failing dimensions with mean, slot-indexed scores and fail reason, or redacted error text) and a one-line digest `detail` counting every question that did not pass, malformed rows included, and naming a slot that scored none. One pricing `withChatCallMeter` meter wraps LongMemEval and the batch, so every row of a run that reached its model calls, a part-way failure included, records `chat_calls`, `chat_cost_usd` (reader, extractor and judges) and `unpriced_chat_calls`; `est_cost_usd` stays the batch's pre-flight estimate for its judge calls only, 0 without a summary. Run-level budget (CEO B4): one `BudgetTracker` (`withBudgetTracker`) wraps both stages with `max_usd` as the cap (`resolveProbeCap`: a configured value is a `user` cap, else the $5 `default`; `pricing.overrides` from the brain), so every gateway chat/embed call of LongMemEval and the judges reserves first. A refusal is kept by the `ProbeBudgetTracker` subclass even when LongMemEval records it as a per-question error: exhausted after LongMemEval → `budget_exceeded`, no judge call; exhausted while judging → `budget_exceeded` whatever the batch said; a user cap refuses an unpriced model with the shared no_pricing text (`reason: no_pricing`), a default cap warns and runs it. Rows carry `cap_usd` / `cap_source`. A pass or fail from a collapsed panel (one model holding two judged slots, or fewer than two models judged) becomes `inconclusive` with `reason: panel_collapsed`, the batch verdict and the slot-key remedy in `detail` (D12). A non-pass run copies `summary.json` / `lme-output.jsonl` to `<audit dir>/nightly-probe/<ts>/` (newest 7) and names it in `receipt_dir`. The `nightly_quality_probe_health` doctor check (`computeNightlyQualityProbeHealthCheck` in `src/commands/doctor/checks/search-eval.ts`, registered right after `slug_fallback_audit` by `src/commands/doctor/checks/local-audits.ts`) reads last 7 days: SKIPPED when flag off (with enable command); OK when enabled + all PASS; WARN on any non-PASS outcome with per-outcome counts (`skipped=N` appended when a run skipped), so a skipped run is never OK. OK and WARN append the latest row's judge panel and name a slot that scored no question; among the slots that scored, a model holding two or more gets the remedy (three different models in `models.eval.cross_modal.slot_a` / `slot_b` / `slot_c`), fewer than three providers get the not-cross-modal information; a row without valid panel fields keeps the plain message. Pinned by `test/nightly-quality-probe.test.ts`.
-- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`.
+- `src/core/cycle/dream-breaker.ts` — dream paid-loop circuit breaker. `countDeadDreamSubmissions` is the one counting rule shared by synthesize, patterns, `gbrain dream reset-key` and the `dream_paid_loop` doctor check: dead `subagent` rows finished in the last 24 h (partial index `idx_minion_jobs_dead_subagent_finished`, migration 173), keyed by the live or released idempotency key with the `:c<i>of<n>` chunk suffix stripped, counted as distinct queues (one per run), ignoring deaths before the key's persisted reset (`dream.breaker.resets` config JSON, database clock). A key at `dream.breaker.max_dead_submissions` (default 3; 0 disables) is refused before synthesis submission; a failed count leaves the breaker off for that run with a warning. Completed jobs, including legitimate zero-write completions, never count. Growing transcripts change their content-hashed key and unkeyed patterns runs are not covered. Contained cycle-phase failures after paid model calls (`recordContainedPaidFailure`, `dream.breaker.contained_failures` config JSON, 24 h window, database clock) are counted under `dream:phase:<phase>:<source>` keys; the breaker never refuses those phases, doctor reports them and `gbrain dream reset-key` clears them. Tests: `test/dream-breaker.test.ts`, `test/cycle-synthesize-breaker.test.ts`, `test/e2e/dream-breaker-postgres.test.ts`. Patterns rows count under the per-source key `dream:patterns:source:<data.source_id or default>` (never their content key), and a patterns child `cancelled` with recorded tokens counts as a death; `patternsBreakerSkip` returns the phase skip (`dream_breaker_tripped`, paid reset `fix`, read-only `--list --json` verify) and `clearPatternsSourceDeaths` resets the source after a completed child (`test/dream-breaker-patterns-source.test.ts`).
- `src/core/cycle/phantom-redirect.ts` — Phantom-redirect orchestrator. Exports `runPhantomRedirectPass(engine, brainDir, sourceId, dryRun): Promise<PhantomPassResult>` (per-cycle wrapper acquiring the `gbrain-sync` writer lock once for the whole pass, 30s bounded retry, walks up to `GBRAIN_PHANTOM_REDIRECT_LIMIT` unprefixed phantoms) + `tryRedirectPhantom(engine, page, sourceId, brainDir, dryRun): Promise<RedirectResult>` + `stripFenceAndFrontmatterAndLeadingH1` (pure body-shape gate helper — strips facts fence incl. preceding `## Facts` heading and the leading H1). Only fence rows migrate, so the residue gate also counts the page's timeline text, any `timeline_entries` row, and frontmatter keys beyond `title`/`type`/`tags`; any residue = not a phantom. Handler order: body-shape gate → `resolvePhantomCanonical` (bypasses exact-self-match; a fuzzy hit needs a 0.1 margin over the runner-up) → `findPrefixCandidates` ambiguity check (a canonical that is not the single prefix candidate is ambiguous too) → `fenceDbDrift` bi-directional check → dry-run early exit → canonical file resolved through `resolvePageWriteTarget` (recorded `source_path`, own-`local_path` roots; only a brain with no configured root falls back to `brainDir`) → materialize canonical via `serializeMarkdown` if DB-only → append phantom fence rows to that file with `(claim, valid_from)` dedup-guard, numbering past both the file's and the DB's highest row number and rewriting `superseded by #N` to the new numbers → `engine.refreshPageBody` → move the phantom's fact withdrawals to the canonical subject → move every phantom fact row by id (a row takes its on-disk canonical row number unless the canonical index already holds it; history, duplicates and rows absent from the fence move expired and detached, never deleted) → move the phantom's links to the canonical page id (skipping duplicates and self-links) → `recordRenameAlias` (phantom → canonical in `slug_aliases`) → `engine.softDeletePage` + unlink. `RedirectResult.canonical` populated on `'redirected'` (incl. dry-run preview) so the caller builds `touched_canonicals`. Idempotent on re-run: phantom soft-deleted → predicate fails (`deleted_at IS NULL`); migrate UPDATE matches no rows; dedup-guard prevents double-append. `mergePhantomFenceRows` (pure body merge), `movePhantomFacts` (row move inside the caller's transaction) and `mergePhantomLinks` are shared with `phantom-redirect-managed.ts`, which a managed brain uses instead of the file-first commit phase.
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index 6b7855fc9f..8ffbbaaf31 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -379,6 +379,13 @@ gbrain config set dream.breaker.max_dead_submissions 5 # raise the limit; 0 di
- The check happens before synthesis submission. Transcript triage for that run may
already have happened, so the promise is "no synthesis submission", not "no
model call at all".
+- Patterns digests its reflection set into its key, so the key changes whenever a
+ reflection does. Patterns deaths therefore count per source, under
+ `dream:patterns:source:<source id>`, whatever reflections each run read. A
+ patterns child cancelled at its timeout after paid work counts as a death; one
+ cancelled before any work does not. A completed run resets the count, so only
+ deaths in a row trip it; reset a tripped source with
+ `gbrain dream reset-key 'dream:patterns:source:<source id>'`.
- Not covered: a transcript that keeps growing gets a new content-hashed key each
cycle, and patterns runs outside maintenance carry no key.
- If the count query fails, the breaker is skipped for that run with a warning, the
diff --git a/src/commands/doctor/checks/dream-breaker.ts b/src/commands/doctor/checks/dream-breaker.ts
index 90e5905af4..715f6de068 100644
--- a/src/commands/doctor/checks/dream-breaker.ts
+++ b/src/commands/doctor/checks/dream-breaker.ts
@@ -5,7 +5,7 @@
* using the same counting function the breaker enforces with.
*/
import type { BrainEngine } from '../../../core/engine.ts';
-import { countDeadDreamSubmissions, dreamBreakerResetCommand, loadDreamBreakerThreshold, DREAM_BREAKER_CONFIG_KEY, DREAM_PHASE_KEY_PREFIX } from '../../../core/cycle/dream-breaker.ts';
+import { countDeadDreamSubmissions, dreamBreakerResetCommand, loadDreamBreakerThreshold, DREAM_BREAKER_CONFIG_KEY, DREAM_PATTERNS_SOURCE_KEY_PREFIX, DREAM_PHASE_KEY_PREFIX } from '../../../core/cycle/dream-breaker.ts';
import type { Check } from '../../doctor.ts';
export async function dreamPaidLoopCheck(engine: BrainEngine): Promise<Check> {
@@ -14,7 +14,8 @@ export async function dreamPaidLoopCheck(engine: BrainEngine): Promise<Check> {
const limit = threshold === 0 ? 3 : threshold;
const looping = rows.filter(row => row.dead_submissions >= limit);
const details = { threshold, breaker_enabled: threshold > 0, inspected_keys: rows.length, count_exact: true,
- keys: looping.map(row => ({ key_prefix: row.base_key.startsWith('dream:patterns:') ? 'dream:patterns:'
+ keys: looping.map(row => ({ key_prefix: row.base_key.startsWith(DREAM_PATTERNS_SOURCE_KEY_PREFIX) ? DREAM_PATTERNS_SOURCE_KEY_PREFIX
+ : row.base_key.startsWith('dream:patterns:') ? 'dream:patterns:'
: row.base_key.startsWith(DREAM_PHASE_KEY_PREFIX) ? DREAM_PHASE_KEY_PREFIX : 'dream:synth-v2:', ...row })) };
if (looping.length === 0) {
return { name: 'dream_paid_loop', status: 'ok', message: `No dream key died ${limit}+ times in 24h`, details };
diff --git a/src/commands/dream-reset-key.ts b/src/commands/dream-reset-key.ts
index 4b77e8820b..44fb4e2c3b 100644
--- a/src/commands/dream-reset-key.ts
+++ b/src/commands/dream-reset-key.ts
@@ -5,7 +5,7 @@
import type { BrainEngine } from '../core/engine.ts';
import {
countDeadDreamSubmissions, dreamBreakerBaseKey, dreamBreakerResetCommand, loadDreamBreakerThreshold,
- resetDreamBreakerKey, DREAM_BREAKER_CONFIG_KEY, DREAM_BREAKER_KEY_PREFIXES,
+ resetDreamBreakerKey, DREAM_BREAKER_CONFIG_KEY, DREAM_BREAKER_KEY_PREFIXES, DREAM_PATTERNS_SOURCE_KEY_PREFIX,
} from '../core/cycle/dream-breaker.ts';
import { setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
import { opError } from '../core/ops/contract.ts';
@@ -16,6 +16,9 @@ const HELP = `Usage: gbrain dream reset-key <base-key>
The paid-loop breaker refuses to resubmit a dream synthesize or patterns key
whose submissions died ${'`'}${DREAM_BREAKER_CONFIG_KEY}${'`'} times (default 3) within 24 hours.
+Patterns deaths (and patterns runs cancelled at their timeout after paid work)
+count under ${'`'}${DREAM_PATTERNS_SOURCE_KEY_PREFIX}<source id>${'`'}, whatever reflections each
+run read; a completed run resets it, so only consecutive deaths trip it.
<base-key> Re-enable one key (without any :c<i>of<n> chunk suffix). The reset
is stored in the brain and survives restarts; deaths after it
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d997a6f1a8..be52f660be 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -291,6 +291,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.103.0', text: 'With retrieval feedback on, MCP search and query results carry one visible line with the answer id (`Rate after use: rate_answer { answer_id: "ans_…", rating: 1-5 }`), so hosts that hide `_meta` can still rate.' },
{ since: '0.60.103.0', text: 'Imported transcript pages now also redact a password typed after a credential label (`password: …`, `login alice / …`) as `<REDACTED:labeled_credential>`; pages imported earlier are not rewritten, so run `gbrain transcripts audit-secrets --json` to list them (doctor `transcript_secret_exposure`).' },
{ since: 'WAVE12', text: 'Dream atom and concept extraction no longer accept a model answer that stopped at the output cap or was refused (claude-cli included): such an answer counts as a failure, never as "nothing to extract" or a new concept narrative. On a managed brain the failed atom batch keeps the page\'s earlier atoms and waits for an approved retry (`gbrain jobs submit extract-atoms-drain --params \'{"sourceId":"<id>","retryRequestId":"<request>"}\'`); a concept that fails 3 times on unchanged atoms is skipped until they change (`gbrain config unset dream.concepts.failed_attempts` retries it now).' },
+ { since: 'WAVE12', text: 'The dream patterns breaker now counts deaths per source (`dream:patterns:source:<id>`), including runs cancelled at their timeout after paid work, so a brain whose patterns runs keep dying is refused at once after the upgrade; fix the cause, then `gbrain dream reset-key \'dream:patterns:source:<id>\'`. Pattern pages store a quarantined claim\'s reflection list once per page (`unverified_claim_sources`); the first patterns run rewrites existing pages that way (frontmatter only, no model call) before it pays for a run.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/dream-breaker.ts b/src/core/cycle/dream-breaker.ts
index 9588932962..8742902006 100644
--- a/src/core/cycle/dream-breaker.ts
+++ b/src/core/cycle/dream-breaker.ts
@@ -10,12 +10,28 @@
* Only dead rows count: a completed job, including a legitimate zero-write
* completion, is never a death.
*
- * Not covered: content-hashed keys change whenever a transcript grows, and
- * patterns runs outside maintenance carry no key.
+ * Patterns (#6236): the patterns key digests the reflection set, so it
+ * changes whenever a reflection does. Patterns deaths therefore count under
+ * the stable per-source key `dream:patterns:source:<source id>` (the job's
+ * `source_id`, else `default`), and a patterns child cancelled at its timeout
+ * after paid work (tokens recorded) counts as a death too; one cancelled
+ * before any work does not. A completed patterns run resets its source key,
+ * so only consecutive deaths trip it.
+ *
+ * Not covered: content-hashed synthesize keys change whenever a transcript
+ * grows, and patterns runs outside maintenance carry no key.
*/
import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
export const DREAM_BREAKER_KEY_PREFIXES = ['dream:synth-v2:', 'dream:patterns:'] as const;
+/** Base-key prefix of the per-source patterns count, whatever each run's content key. */
+export const DREAM_PATTERNS_SOURCE_KEY_PREFIX = 'dream:patterns:source:';
+
+/** The stable key every patterns death of this source counts under. */
+export function dreamPatternsSourceKey(sourceId: string): string {
+ return `${DREAM_PATTERNS_SOURCE_KEY_PREFIX}${sourceId}`;
+}
/** Base-key prefix of a contained cycle-phase failure after paid model calls. */
export const DREAM_PHASE_KEY_PREFIX = 'dream:phase:';
export const DREAM_BREAKER_CONFIG_KEY = 'dream.breaker.max_dead_submissions';
@@ -61,19 +77,25 @@ async function loadResets(engine: BrainEngine): Promise<Record<string, string>>
export async function countDeadDreamSubmissions(engine: BrainEngine): Promise<DeadDreamSubmissions[]> {
const resets = await loadResets(engine);
const dead = await engine.executeRaw<DeadDreamSubmissions>(
- `WITH dead AS (
+ `WITH ended AS (
SELECT regexp_replace(COALESCE(idempotency_key, data->>'__released_idempotency_key'), ':c[0-9]+of[0-9]+$', '') AS base_key,
- queue, finished_at
+ COALESCE(data->>'source_id', 'default') AS source_id, status, queue, finished_at
FROM minion_jobs
- WHERE name = 'subagent' AND status = 'dead' AND finished_at > now() - interval '24 hours'
+ WHERE name = 'subagent' AND finished_at > now() - interval '24 hours'
+ AND (status = 'dead' OR (status = 'cancelled' AND tokens_input + tokens_output > 0))
+ ), counted AS (
+ SELECT base_key, queue, finished_at FROM ended
+ WHERE status = 'dead' AND left(base_key, ${DREAM_BREAKER_KEY_PREFIXES[0].length}) = $1
+ UNION ALL
+ SELECT $4::text || source_id, queue, finished_at FROM ended
+ WHERE left(base_key, ${DREAM_BREAKER_KEY_PREFIXES[1].length}) = $2
)
SELECT base_key, COUNT(DISTINCT queue)::int AS dead_submissions, MAX(finished_at)::text AS last_dead_at
- FROM dead
- WHERE (left(base_key, ${DREAM_BREAKER_KEY_PREFIXES[0].length}) = $1 OR left(base_key, ${DREAM_BREAKER_KEY_PREFIXES[1].length}) = $2)
- AND finished_at > COALESCE(($3::text::jsonb ->> base_key)::timestamptz, '-infinity'::timestamptz)
+ FROM counted
+ WHERE finished_at > COALESCE(($3::text::jsonb ->> base_key)::timestamptz, '-infinity'::timestamptz)
GROUP BY base_key
ORDER BY dead_submissions DESC, base_key`,
- [DREAM_BREAKER_KEY_PREFIXES[0], DREAM_BREAKER_KEY_PREFIXES[1], JSON.stringify(resets)],
+ [DREAM_BREAKER_KEY_PREFIXES[0], DREAM_BREAKER_KEY_PREFIXES[1], JSON.stringify(resets), DREAM_PATTERNS_SOURCE_KEY_PREFIX],
);
const cutoff = Date.now() - 24 * 3_600_000;
for (const [baseKey, times] of Object.entries(await loadContained(engine))) {
@@ -141,6 +163,39 @@ export async function loadDreamBreaker(engine: BrainEngine): Promise<DreamBreake
}
}
+/**
+ * #6236: the patterns phase's skip result when its source key is tripped, or
+ * null (breaker off, count failed, or not tripped). The skip carries the reset
+ * as a paid `fix` and a read-only verify.
+ */
+export async function patternsBreakerSkip(engine: BrainEngine, sourceId: string): Promise<PhaseResult | null> {
+ const breaker = await loadDreamBreaker(engine);
+ const key = dreamPatternsSourceKey(sourceId);
+ const refusal = breaker && dreamBreakerRefusal(breaker, key);
+ if (!refusal) return null;
+ process.stderr.write(`[dream] patterns: ${refusal}\n`);
+ return { phase: 'patterns', status: 'skipped', duration_ms: 0, summary: refusal, details: { reason: 'dream_breaker_tripped', code: 'dream_breaker_tripped',
+ base_key: key, why: 'The patterns phase died (or was cancelled after paid work) that many times in a row for this source within 24 hours, so it is not submitted again until reset.',
+ fix: { argv: ['gbrain', 'dream', 'reset-key', key], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: 'Re-enables patterns runs for this source; the next cycle pays for a run, so fix the cause and ask the user first.',
+ verify: { argv: ['gbrain', 'dream', 'reset-key', '--list', '--json'] } } } };
+}
+
+/**
+ * A completed patterns run ends its source's death count, so only consecutive
+ * deaths trip it. A failed reset is logged; the earlier deaths then keep
+ * counting until they leave the 24 h window.
+ */
+export async function clearPatternsSourceDeaths(engine: BrainEngine, sourceId: string): Promise<void> {
+ const key = dreamPatternsSourceKey(sourceId);
+ try {
+ await resetDreamBreakerKey(engine, key);
+ } catch (error) {
+ process.stderr.write(`[dream] patterns: could not clear ${key} after a completed run; its earlier deaths keep counting `
+ + `until they are 24h old (${error instanceof Error ? error.message : String(error)})\n`);
+ }
+}
+
/** Refusal line for the cycle summary and the autopilot log. */
export function dreamBreakerRefusal(breaker: DreamBreaker, baseKey: string): string | null {
const count = breaker.tripped.get(baseKey);
diff --git a/src/core/cycle/pattern-claim-sources.ts b/src/core/cycle/pattern-claim-sources.ts
new file mode 100644
index 0000000000..bc38f55df0
--- /dev/null
+++ b/src/core/cycle/pattern-claim-sources.ts
@@ -0,0 +1,134 @@
+/**
+ * #6236: lossless storage of the reflections a quarantined pattern claim was
+ * checked against.
+ *
+ * A pattern claim is grounded against every reflection the run read (up to
+ * 100), so writing that list onto every claim grew pattern pages to hundreds
+ * of kilobytes, and the next patterns child read them back until its replayed
+ * transcript overflowed the model's window. The list is now stored once per
+ * page in frontmatter `unverified_claim_sources` (`{ "@<digest>": [slug, …] }`,
+ * one entry per distinct reflection set) and each claim's `sources` holds the
+ * reference. No path is dropped: `resolveClaimSources` returns the original
+ * list. A claim with one source keeps it inline.
+ *
+ * `dedupePatternClaimSources` rewrites pages still carrying inline lists
+ * (frontmatter only, zero LLM, body untouched) before the patterns child runs.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';
+import { publishOrHold } from '../persistence/accepted-pending.ts';
+import { throwIfAborted } from '../abort-check.ts';
+
+export const CLAIM_SOURCES_KEY = 'unverified_claim_sources';
+const CLAIMS_KEY = 'unverified_claims';
+/** Claim records a page keeps (oldest dropped first), as before. */
+export const MAX_PATTERN_CLAIM_RECORDS = 100;
+
+type SourceMap = Record<string, string[]>;
+type ClaimRecord = Record<string, unknown> & { sources?: unknown };
+
+function sourceSetRef(paths: string[]): string {
+ return `@${createHash('sha256').update([...paths].sort().join('\n')).digest('hex').slice(0, 12)}`;
+}
+
+function readMap(frontmatter: Record<string, unknown>): SourceMap {
+ const raw = frontmatter[CLAIM_SOURCES_KEY];
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ return Object.fromEntries(Object.entries(raw as Record<string, unknown>)
+ .filter((entry): entry is [string, string[]] => Array.isArray(entry[1]) && entry[1].every(path => typeof path === 'string')));
+}
+
+/** The reflection paths a claim was checked against, read through the page's source map. */
+export function resolveClaimSources(frontmatter: Record<string, unknown>, claim: { sources?: unknown }): string[] {
+ if (!Array.isArray(claim.sources)) return [];
+ const map = readMap(frontmatter);
+ return claim.sources.flatMap(source => typeof source === 'string' && map[source] ? map[source] : [source as string]);
+}
+
+/**
+ * The page's claim records with every multi-path `sources` list moved into
+ * the shared map, new records appended (sharing one reference for this run's
+ * reflection set), the oldest dropped past MAX_PATTERN_CLAIM_RECORDS, and map
+ * entries no kept record references removed. `changed` is false when nothing
+ * would be rewritten.
+ */
+export function withClaimSources(frontmatter: Record<string, unknown>, added: Array<Record<string, unknown>> = [], addedSources: string[] = []):
+ { frontmatter: Record<string, unknown>; changed: boolean } {
+ const map = readMap(frontmatter);
+ let changed = added.length > 0;
+ const refFor = (paths: string[]): string[] => {
+ if (paths.length <= 1) return paths;
+ const ref = sourceSetRef(paths);
+ map[ref] = [...paths];
+ return [ref];
+ };
+ const prior = Array.isArray(frontmatter[CLAIMS_KEY]) ? frontmatter[CLAIMS_KEY] as unknown[] : [];
+ const records: unknown[] = prior.map((record) => {
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return record;
+ const sources = (record as ClaimRecord).sources;
+ if (!Array.isArray(sources) || sources.length <= 1 || !sources.every(source => typeof source === 'string')) return record;
+ changed = true;
+ return { ...record, sources: refFor(sources as string[]) };
+ });
+ const addedRef = refFor(addedSources);
+ for (const record of added) records.push({ ...record, sources: addedRef });
+ const kept = records.slice(-MAX_PATTERN_CLAIM_RECORDS);
+ if (kept.length !== records.length) changed = true;
+ const referenced = new Set(kept.flatMap(record => record && typeof record === 'object' && Array.isArray((record as ClaimRecord).sources)
+ ? (record as ClaimRecord).sources as unknown[] : []));
+ const prunedMap = Object.fromEntries(Object.entries(map).filter(([ref]) => referenced.has(ref)));
+ if (Object.keys(prunedMap).length !== Object.keys(readMap(frontmatter)).length) changed = true;
+ const next: Record<string, unknown> = { ...frontmatter };
+ if (kept.length) next[CLAIMS_KEY] = kept; else delete next[CLAIMS_KEY];
+ if (Object.keys(prunedMap).length) next[CLAIM_SOURCES_KEY] = prunedMap; else delete next[CLAIM_SOURCES_KEY];
+ return { frontmatter: next, changed };
+}
+
+/**
+ * Rewrite every pattern page whose claim records still list their sources
+ * inline, before the patterns child reads them. Returns the slugs rewritten
+ * and the slugs whose managed publication is held (pending or contended);
+ * the phase submits no paid child while any is held. A page that fails for
+ * another reason is logged and left for the next run.
+ */
+export async function dedupePatternClaimSources(engine: BrainEngine, maintenance: MaintenanceAuthority | null, outputSlugPrefix: string,
+ sourceId: string, signal?: AbortSignal): Promise<{ rewritten: string[]; held: string[] }> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages
+ WHERE source_id = $1 AND slug LIKE $2 AND deleted_at IS NULL AND jsonb_typeof(frontmatter->'${CLAIMS_KEY}') = 'array'
+ AND EXISTS (SELECT 1 FROM jsonb_array_elements(frontmatter->'${CLAIMS_KEY}') AS c
+ WHERE jsonb_typeof(c.value->'sources') = 'array' AND jsonb_array_length(c.value->'sources') > 1)
+ ORDER BY slug`,
+ [sourceId, `${outputSlugPrefix}/%`]);
+ const rewritten: string[] = [];
+ const held: string[] = [];
+ for (const { slug } of rows) {
+ throwIfAborted(signal, '[dream] patterns claim de-duplication');
+ try {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ if (!snapshot) continue;
+ const { frontmatter, changed } = withClaimSources(snapshot.page.frontmatter as Record<string, unknown>);
+ if (!changed) continue;
+ const { serializePageToMarkdown } = await import('../markdown.ts');
+ const content = serializePageToMarkdown({ ...snapshot.page, frontmatter }, snapshot.tags);
+ if (maintenance) {
+ const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');
+ if (await publishOrHold(() => publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision }))) {
+ held.push(slug);
+ continue;
+ }
+ } else {
+ const [{ importFromContent }, { isAvailable }] = await Promise.all([import('../import-file.ts'), import('../ai/gateway.ts')]);
+ await importFromContent(engine, slug, content, { noEmbed: !isAvailable('embedding'), sourceId });
+ }
+ rewritten.push(slug);
+ } catch (error) {
+ if (signal?.aborted) throw error;
+ process.stderr.write(`[dream] patterns: could not de-duplicate the claim sources of ${slug}; the next run retries `
+ + `(${error instanceof Error ? error.message : String(error)})\n`);
+ }
+ }
+ if (rewritten.length) process.stderr.write(`[dream] patterns: de-duplicated the claim sources of ${rewritten.length} pattern page(s)\n`);
+ return { rewritten, held };
+}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 7a187823e3..80d235bc2e 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -47,7 +47,8 @@ import { probeChatModel } from '../ai/gateway.ts';
import { normalizeModelId } from '../model-id.ts';
import { throwIfAborted } from '../abort-check.ts';
import { resolveCycleDate } from './cycle-date.ts';
-import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';
+import { clearPatternsSourceDeaths, patternsBreakerSkip } from './dream-breaker.ts';
+import { dedupePatternClaimSources, withClaimSources } from './pattern-claim-sources.ts';
import { publishOrHold } from '../persistence/accepted-pending.ts';
export interface PatternsPhaseOpts {
@@ -291,13 +292,12 @@ export async function runPhasePatterns(
private_queue_owner_token: privateQueueOwnerToken,
private_queue_lease_ms: DEFAULT_PRIVATE_QUEUE_LEASE_MS,
};
- // Paid-loop breaker: only maintenance runs carry a key, so only they are covered.
- const breaker = submitOpts.idempotency_key ? await loadDreamBreaker(engine) : null;
- const refusal = breaker && dreamBreakerRefusal(breaker, submitOpts.idempotency_key!);
- if (refusal) {
- process.stderr.write(`[dream] patterns: ${refusal}\n`);
- return skipped('dream_breaker_tripped', refusal);
- }
+ // Paid-loop breaker (#6236): deaths count per source, whatever reflections each run read; only maintenance runs carry a key.
+ const breakerSkip = submitOpts.idempotency_key ? await patternsBreakerSkip(engine, opts.sourceId ?? 'default') : null;
+ if (breakerSkip) return breakerSkip;
+ // #6236: the child reads existing pattern pages, so their claim sources are de-duplicated first; never pay while a rewrite is held.
+ const claimHeld = await dedupePatternsBeforeChild(engine, maintenance, config.outputSlugPrefix, opts.sourceId ?? 'default', opts.signal);
+ if (claimHeld) return claimHeld;
let job: Awaited<ReturnType<typeof queue.add>>;
const submittedAt = Date.now();
try {
@@ -354,6 +354,7 @@ export async function runPhasePatterns(
}
await recordPatternsLastRun(engine, { duration_ms: Date.now() - submittedAt, reflections: submitted.length, outcome }); // #6177: every child, timed out or failed too
+ if (outcome === 'completed' && submitOpts.idempotency_key) await clearPatternsSourceDeaths(engine, opts.sourceId ?? 'default'); // #6236: only consecutive deaths trip
if (opts.yieldDuringPhase) {
try { await opts.yieldDuringPhase(); } catch { /* best-effort */ }
@@ -709,12 +710,12 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: Maint
stats.pages++;
stats.quarantined += quarantined.length;
stats.repaired += ct.normalized + ct.near + tl.normalized + tl.near;
- const prior = Array.isArray(snapshot.page.frontmatter.unverified_claims) ? snapshot.page.frontmatter.unverified_claims as unknown[] : [];
+ // #6236: the reflection list is stored once per page (lossless), not on every claim.
+ const { frontmatter } = withClaimSources({ ...snapshot.page.frontmatter, quote_verified_at: cycleDate },
+ quarantined.map(c => ({ ...c, detected_at: cycleDate })), sources.map(x => x.path));
const page = { ...snapshot.page,
compiled_truth: ct.body.trim() ? ct.body : (await import('./synthesize-verify.ts')).ALL_CLAIMS_QUARANTINED_BODY,
- timeline: tl.body,
- frontmatter: { ...snapshot.page.frontmatter, quote_verified_at: cycleDate,
- ...(quarantined.length ? { unverified_claims: [...prior, ...quarantined.map(c => ({ ...c, sources: sources.map(x => x.path), detected_at: cycleDate }))].slice(-100) } : {}) } };
+ timeline: tl.body, frontmatter };
const content = serializePageToMarkdown(page, snapshot.tags);
if (maintenance) {
const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');
@@ -822,6 +823,21 @@ function ok(summary: string, details: Record<string, unknown> = {}): PhaseResult
return { phase: 'patterns', status: 'ok', duration_ms: 0, summary, details };
}
+/** #6236: de-duplicate the claim sources of existing pattern pages; a skip result while any rewrite is held (no paid child then). */
+async function dedupePatternsBeforeChild(engine: BrainEngine, maintenance: MaintenanceAuthority | null, outputSlugPrefix: string,
+ sourceId: string, signal?: AbortSignal): Promise<PhaseResult | null> {
+ const { held } = await dedupePatternClaimSources(engine, maintenance, outputSlugPrefix, sourceId, signal);
+ if (!held.length) return null;
+ const summary = `patterns: ${held.length} pattern page(s) are waiting on a claim-source rewrite (${held.slice(0, 3).join(', ')}); `
+ + 'no patterns child was submitted, so it never reads the oversized pages. The next cycle retries.';
+ process.stderr.write(`[dream] ${summary}\n`);
+ return { phase: 'patterns', status: 'skipped', duration_ms: 0, summary, details: { reason: 'pattern_claims_pending', code: 'pattern_claims_pending', held,
+ why: 'Existing pattern pages carried a full reflection list on every quarantined claim; the child reads those pages, so it runs only after they are rewritten.',
+ fix: { argv: ['gbrain', 'dream', '--phase', 'patterns', '--source', sourceId], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: 'Re-runs the patterns phase once the held rewrites have landed; it is a paid model run, so ask the user first.',
+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] } } } };
+}
+
function skipped(reason: string, summary: string): PhaseResult {
return {
phase: 'patterns',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5e21a4f879..32b6f717c8 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -132,6 +132,7 @@ export const CODES = {
demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },
derived_cap_exhausted: { class: 'server', summary: "Paid work stopped at the cost cap derived from its estimate; the run is resumable." },
destination_not_ready: { class: 'host_only', summary: "The destination brain is not initialized for this operation." },
+ dream_breaker_tripped: { class: 'unavailable', summary: "A dream synthesize or patterns submission died (or, for patterns, was cancelled at its timeout after paid work) the breaker limit of times within 24 hours, so it was not submitted again.", why: "A run that keeps dying keeps paying; the breaker stops resubmitting until the cause is fixed and the key is reset. Patterns count per source (`dream:patterns:source:<id>`) whatever reflections each run read, and a completed run resets that count.", docs: 'docs/operations/spend-controls.md#dream-paid-loop-breaker-dreambreakermax_dead_submissions', fix: { argv: ['gbrain', 'dream', 'reset-key', '--list', '--json'], consent: [], actor: 'agent', why: 'Lists the tripped keys with their counts and reset commands, read-only.', requires_exclusive: false } },
dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },
effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },
embedding_auth_failed: { class: 'unavailable', summary: "The embedding provider rejected the credentials." },
@@ -254,6 +255,7 @@ export const CODES = {
parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `sync.parser_regression=hold` such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again with --retry-failed.' },
pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },
payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },
+ pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: "Shows the source's maintenance writer and the requests still in flight, read-only.", requires_exclusive: false } },
pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },
permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },
persistence_write_stall: { class: 'host_only', summary: "A managed write request has held its claim longer than persistence.max_claim_ms, so later writes on its root wait behind it.", why: "The owner renews a claim for as long as its work is unsettled, so a preparation or publication that hangs never lets the lease lapse; doctor names the stuck phase, the root, the claim's age and whether the same request resumes on its own.", docs: 'docs/guides/troubleshooting.md#persistence-write-stall', suggestion: 'Inspect the request with the command in fix, then restart the gbrain serve that owns the root; attach that status output when reporting the hang.', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Shows the owner, the stuck request's claim phase and the writes waiting behind it, read-only.", requires_exclusive: false } },
diff --git a/test/cycle-patterns-quote-verify.test.ts b/test/cycle-patterns-quote-verify.test.ts
index 216757d727..e80d859ebb 100644
--- a/test/cycle-patterns-quote-verify.test.ts
+++ b/test/cycle-patterns-quote-verify.test.ts
@@ -10,6 +10,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { importFromContent } from '../src/core/import-file.ts';
import { groundPatternPages } from '../src/core/cycle/patterns.ts';
+import { CLAIM_SOURCES_KEY, dedupePatternClaimSources, resolveClaimSources } from '../src/core/cycle/pattern-claim-sources.ts';
let engine: PGLiteEngine;
@@ -44,4 +45,38 @@ describe('patterns quote grounding', () => {
const again = await groundPatternPages(engine, null, [], reflections, 'wiki/personal/patterns', 'default', '2026-10-05');
expect(again).toEqual({ pages: 0, quarantined: 0, repaired: 0 });
});
+
+ test('#6236: a quarantined claim references the page\'s shared reflection list instead of carrying it, losslessly', async () => {
+ await importFromContent(engine, 'wiki/personal/patterns/fridays',
+ '---\ntype: note\ntitle: Fridays\ndream_generated: true\n---\nYou wrote "never ship on Fridays" and "always test first".\n',
+ { noEmbed: true, sourceId: 'default' });
+ const reflections = ['r1', 'r2'].map(r => ({ slug: `wiki/personal/reflections/${r}`, title: r, excerpt: '', updatedAt: new Date(), seat: null }));
+ await groundPatternPages(engine, null, [{ slug: 'wiki/personal/patterns/fridays', source_id: 'default' }], reflections, 'wiki/personal/patterns', 'default', '2026-10-06');
+ const fm = (await engine.getPage('wiki/personal/patterns/fridays'))!.frontmatter as Record<string, unknown>;
+ const claims = fm.unverified_claims as Array<{ sources: string[] }>;
+ expect(claims.length).toBeGreaterThan(0);
+ for (const claim of claims) {
+ expect(claim.sources).toHaveLength(1);
+ expect(resolveClaimSources(fm, claim)).toEqual(reflections.map(r => r.slug));
+ }
+ expect(Object.keys(fm[CLAIM_SOURCES_KEY] as object)).toHaveLength(1);
+ });
+
+ test('#6236: a page written with inline reflection lists is de-duplicated before the child runs, body untouched', async () => {
+ const list = Array.from({ length: 100 }, (_, i) => `wiki/personal/reflections/x${i}`);
+ const claims = Array.from({ length: 5 }, (_, i) => ` - text: claim ${i}\n reason: quote_not_in_source\n sources:\n${list.map(p => ` - ${p}`).join('\n')}`).join('\n');
+ await importFromContent(engine, 'wiki/personal/patterns/legacy',
+ `---\ntype: note\ntitle: Legacy\ndream_generated: true\nquote_verified_at: '2026-10-01'\nunverified_claims:\n${claims}\n---\nA legacy pattern body.\n`,
+ { noEmbed: true, sourceId: 'default' });
+ const before = (await engine.getPage('wiki/personal/patterns/legacy'))!;
+ const result = await dedupePatternClaimSources(engine, null, 'wiki/personal/patterns', 'default');
+ expect(result.rewritten).toEqual(['wiki/personal/patterns/legacy']);
+ expect(result.held).toEqual([]);
+ const after = (await engine.getPage('wiki/personal/patterns/legacy'))!;
+ expect(after.compiled_truth).toBe(before.compiled_truth);
+ const fm = after.frontmatter as Record<string, unknown>;
+ for (const claim of fm.unverified_claims as Array<{ sources: string[] }>) expect(resolveClaimSources(fm, claim)).toEqual(list);
+ expect(JSON.stringify(fm).length).toBeLessThan(JSON.stringify(before.frontmatter).length / 3);
+ expect((await dedupePatternClaimSources(engine, null, 'wiki/personal/patterns', 'default')).rewritten).toEqual([]);
+ });
});
diff --git a/test/dream-breaker-patterns-source.test.ts b/test/dream-breaker-patterns-source.test.ts
new file mode 100644
index 0000000000..17476feee9
--- /dev/null
+++ b/test/dream-breaker-patterns-source.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #6236: patterns deaths count per source, whatever reflection set (content
+ * key) each run read. A patterns child cancelled at its timeout after paid
+ * work counts too; one cancelled before any work does not. A completed run
+ * resets the source; another source is unaffected.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import {
+ clearPatternsSourceDeaths, countDeadDreamSubmissions, dreamPatternsSourceKey, patternsBreakerSkip,
+} from '../src/core/cycle/dream-breaker.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetPgliteState(engine); });
+
+async function seed(opts: { key: string; status: string; queue: string; source?: string; tokens?: number }): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, idempotency_key, tokens_input, created_at, finished_at)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'subagent', $1, $2, $3::text::jsonb, $4, $5, now() - interval '1 hour', now() - interval '1 hour')`,
+ [opts.queue, opts.status, JSON.stringify(opts.source ? { source_id: opts.source } : {}), opts.key, opts.tokens ?? 0],
+ );
+}
+
+describe('patterns breaker per source (#6236)', () => {
+ test('three deaths under three different content keys trip the source key and skip the run', async () => {
+ for (const n of [1, 2]) await seed({ key: `dream:patterns:digest-${n}`, status: 'dead', queue: `dream-inline-${n}` });
+ expect(await patternsBreakerSkip(engine, 'default')).toBeNull();
+ await seed({ key: 'dream:patterns:digest-3', status: 'dead', queue: 'dream-inline-3' });
+ const rows = await countDeadDreamSubmissions(engine);
+ expect(rows).toEqual([expect.objectContaining({ base_key: dreamPatternsSourceKey('default'), dead_submissions: 3 })]);
+ const skip = await patternsBreakerSkip(engine, 'default');
+ expect(skip?.status).toBe('skipped');
+ expect(skip?.details).toMatchObject({ reason: 'dream_breaker_tripped', code: 'dream_breaker_tripped',
+ fix: { argv: ['gbrain', 'dream', 'reset-key', 'dream:patterns:source:default'], consent: ['paid'], verify: { argv: ['gbrain', 'dream', 'reset-key', '--list', '--json'] } } });
+ });
+
+ test('a paid timeout-cancel counts; a cancel before any work does not', async () => {
+ await seed({ key: 'dream:patterns:a', status: 'dead', queue: 'q1' });
+ await seed({ key: 'dream:patterns:b', status: 'cancelled', queue: 'q2', tokens: 1500 });
+ await seed({ key: 'dream:patterns:c', status: 'cancelled', queue: 'q3', tokens: 0 });
+ expect(await countDeadDreamSubmissions(engine)).toEqual([expect.objectContaining({ base_key: 'dream:patterns:source:default', dead_submissions: 2 })]);
+ await seed({ key: 'dream:patterns:d', status: 'cancelled', queue: 'q4', tokens: 10 });
+ expect(await patternsBreakerSkip(engine, 'default')).not.toBeNull();
+ });
+
+ test('a completed run resets the source; another source is unaffected', async () => {
+ for (const n of [1, 2, 3]) await seed({ key: `dream:patterns:x${n}`, status: 'dead', queue: `a${n}`, source: 'alpha' });
+ for (const n of [1, 2]) await seed({ key: `dream:patterns:y${n}`, status: 'dead', queue: `b${n}`, source: 'beta' });
+ expect(await patternsBreakerSkip(engine, 'alpha')).not.toBeNull();
+ expect(await patternsBreakerSkip(engine, 'beta')).toBeNull();
+ await clearPatternsSourceDeaths(engine, 'alpha');
+ expect(await patternsBreakerSkip(engine, 'alpha')).toBeNull();
+ expect((await countDeadDreamSubmissions(engine)).find(r => r.base_key === 'dream:patterns:source:beta')?.dead_submissions).toBe(2);
+ });
+
+ test('synthesize keys still count per key and only dead rows', async () => {
+ const key = 'dream:synth-v2:default:filename:t.txt:0123456789abcdef';
+ await seed({ key, status: 'dead', queue: 's1' });
+ await seed({ key: `${key}:c0of2`, status: 'cancelled', queue: 's2', tokens: 100 });
+ expect(await countDeadDreamSubmissions(engine)).toEqual([expect.objectContaining({ base_key: key, dead_submissions: 1 })]);
+ });
+});
diff --git a/test/managed-maintenance.test.ts b/test/managed-maintenance.test.ts
index 9d4553031a..a7285559ba 100644
--- a/test/managed-maintenance.test.ts
+++ b/test/managed-maintenance.test.ts
@@ -605,3 +605,35 @@ test('managed patterns scopes evidence and publishes through the real admitted s
} finally { __setChatTransportForTests(null); }
});
}, 90_000);
+
+test('#6236: a held claim-source rewrite of an existing pattern page submits no patterns child (0 model calls)', async () => {
+ await fixture(async (engine, sourceId) => {
+ for (let i = 0; i < 3; i++) await seed(engine, sourceId, `wiki/personal/reflections/example-${i}`);
+ const list = Array.from({ length: 50 }, (_, i) => ` - wiki/personal/reflections/old-${i}`).join('\n');
+ const ctx = { engine, sourceId, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } };
+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'wiki/personal/patterns/legacy', request_id: randomUUID(),
+ content: `---\ntitle: Legacy\ntype: note\ndream_generated: true\nunverified_claims:\n - text: a claim\n reason: quote_not_in_source\n sources:\n${list}\n---\nA legacy pattern.` } });
+ await engine.setConfig('dream.patterns.enabled', 'true');
+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');
+ await engine.setConfig('agent.use_gateway_loop', 'true');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ let calls = 0;
+ __setChatTransportForTests(async opts => {
+ calls++;
+ return { text: 'done', blocks: [{ type: 'text', text: 'done' }], stopReason: 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: opts.model!, providerId: 'anthropic' };
+ });
+ const lock = (await acquireWorktree((await getWorktreeBinding(engine, sourceId))!, 5000))!;
+ expect(lock).not.toBeNull();
+ try {
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-maintenance' }, async () => {
+ const result = await pendingWait(() => runPhasePatterns(engine, { brainDir: null, sourceId, dryRun: false, once: true, cycleDate: '2026-02-03' }));
+ expect(result.status).toBe('skipped');
+ expect(result.details).toMatchObject({ reason: 'pattern_claims_pending', held: ['wiki/personal/patterns/legacy'] });
+ expect(calls).toBe(0);
+ expect(await engine.executeRaw("SELECT id FROM minion_jobs WHERE name='subagent' AND data->>'source_id'=$1", [sourceId])).toHaveLength(0);
+ });
+ } finally { await lock.release(); __setChatTransportForTests(null); }
+ });
+}, 90_000);
diff --git a/test/pattern-claim-sources.test.ts b/test/pattern-claim-sources.test.ts
new file mode 100644
index 0000000000..70305b6125
--- /dev/null
+++ b/test/pattern-claim-sources.test.ts
@@ -0,0 +1,47 @@
+/**
+ * #6236: pattern claim records store the reflection list once per page
+ * (lossless), not on every claim. Every path stays recoverable.
+ */
+import { describe, expect, test } from 'bun:test';
+import { CLAIM_SOURCES_KEY, MAX_PATTERN_CLAIM_RECORDS, resolveClaimSources, withClaimSources } from '../src/core/cycle/pattern-claim-sources.ts';
+
+const paths = (n: number, tag = 'r') => Array.from({ length: n }, (_, i) => `wiki/personal/reflections/${tag}-${i}`);
+
+describe('pattern claim sources (#6236)', () => {
+ test('new claims share one reference to the run\'s reflection set; every path is recoverable', () => {
+ const run = paths(100);
+ const { frontmatter } = withClaimSources({ title: 'p' }, [{ text: 'a', reason: 'quote_not_in_source' }, { text: 'b', reason: 'quote_not_in_source' }], run);
+ const claims = frontmatter.unverified_claims as Array<{ sources: string[] }>;
+ expect(claims).toHaveLength(2);
+ expect(claims[0].sources).toHaveLength(1);
+ expect(claims[0].sources).toEqual(claims[1].sources);
+ expect(Object.keys(frontmatter[CLAIM_SOURCES_KEY] as object)).toHaveLength(1);
+ for (const claim of claims) expect(resolveClaimSources(frontmatter, claim)).toEqual(run);
+ });
+
+ test('legacy records listing every path are de-duplicated with no path lost, and the page shrinks', () => {
+ const runA = paths(100, 'a');
+ const runB = paths(100, 'b');
+ const legacy = { title: 'p', unverified_claims: [
+ ...Array.from({ length: 30 }, (_, i) => ({ text: `a${i}`, sources: runA })),
+ ...Array.from({ length: 11 }, (_, i) => ({ text: `b${i}`, sources: runB })),
+ { text: 'single', sources: ['wiki/personal/reflections/only'] },
+ ] };
+ const { frontmatter, changed } = withClaimSources(legacy);
+ expect(changed).toBe(true);
+ const claims = frontmatter.unverified_claims as Array<{ text: string; sources: string[] }>;
+ expect(claims).toHaveLength(42);
+ for (const [i, claim] of claims.entries()) expect(resolveClaimSources(frontmatter, claim)).toEqual(legacy.unverified_claims[i].sources);
+ expect(Object.keys(frontmatter[CLAIM_SOURCES_KEY] as object)).toHaveLength(2);
+ expect(JSON.stringify(frontmatter).length).toBeLessThan(JSON.stringify(legacy).length / 10);
+ expect(withClaimSources(frontmatter).changed).toBe(false);
+ });
+
+ test('records past the cap drop oldest first and unreferenced sets are pruned', () => {
+ const first = withClaimSources({}, Array.from({ length: MAX_PATTERN_CLAIM_RECORDS }, (_, i) => ({ text: `old${i}` })), paths(5, 'old')).frontmatter;
+ const second = withClaimSources(first, Array.from({ length: MAX_PATTERN_CLAIM_RECORDS }, (_, i) => ({ text: `new${i}` })), paths(5, 'new')).frontmatter;
+ expect((second.unverified_claims as unknown[])).toHaveLength(MAX_PATTERN_CLAIM_RECORDS);
+ const sets = Object.values(second[CLAIM_SOURCES_KEY] as Record<string, string[]>);
+ expect(sets).toEqual([paths(5, 'new')]);
+ });
+});