Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cycle): dream phases never replace a differing file or database body without a trace (#6982, GBRA-131 D-5..D-9)
garrytanaf8302da2966
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex ff5780f53b..a7ab886c5d 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.Patterns, drift reports and the cycle modules listed after them.-- `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`. In the phase each page is one item (`cycle/pattern-grounding.ts`, sites `patterns.ground_pages`, `patterns.ground_timeline_appends`): a failed page is listed in `details.grounding_failed` with code and fix, left unstamped and out of `patterns_written`, the watermark still stamps and the phase warns; a leftover page refused with a content error on 3 runs at one `content_hash` and gbrain version is held in `dream.patterns.grounding_holds.<source>` out of the leftover query and listed in `details.grounding_held` (warn) until the page or version changes or that key is unset; a timeline-append page whose write-back fails is stored with its entries and reflections in `dream.patterns.grounding_appends.<source>` (before the watermark stamps) and `retryPendingAppends` grounds it at the start of every later run, before the evidence and paid-child gates, at those reflections' derivation, then reverse-writes or verifies it (`details.timeline_append_retry`; a failed or held retry warns, a skipped pass included); the same 3-run content rule holds a page's appends (`grounding_held` rows with `timeline_appends`) until the page or version changes; run-scoped or systemic failures fail the phase and record nothing (`test/pathological/a23-patterns-grounding.test.ts`). 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`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Segmented storage: `loadGroundingSources` reads a segmented reflection through `materializeSegmentedBody` (over `PAGE_MAX_BYTES` it is not a source, logged), and `groundTimelineAppends` reads pattern pages through `materializedSnapshot`, skipping an over-ceiling page (`segmented_skipped`). Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts` and `test/cycle-patterns-segmented.test.ts` (both engines). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`. #6297: an in-cycle run (not `--once`, not a direct `--phase patterns`, `CycleOpts.directPhases`) is skipped with `patterns_min_interval` while the partition's last COMPLETED child ended less than `dream.patterns.min_interval_hours` (default 6, 0 off) ago (`patternsCadenceSkip` in `patterns-plan.ts`; stamp `dream.patterns.last_completed_at.<source>.<incarnation>`, `.external` for the external partition), and the child gets `read_budget_bytes` from `dream.patterns.child_read_budget_kb` (default 200). Pinned by `test/cycle-patterns-cadence.serial.test.ts` and `test/cycle-patterns-read-budget.serial.test.ts`. #6779: the OUTPUT POLICY tells the child to keep an existing page's slug, skip it when its evidence covers the pattern, else rewrite it with get_page's `revision` as `expected_revision`, and to append with `add_timeline_entry` or skip a `read_budget_exhausted` summary (`test/cycle-patterns-revision-6779.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`. In the phase each page is one item (`cycle/pattern-grounding.ts`, sites `patterns.ground_pages`, `patterns.ground_timeline_appends`): a failed page is listed in `details.grounding_failed` with code and fix, left unstamped and out of `patterns_written`, the watermark still stamps and the phase warns; a leftover page refused with a content error on 3 runs at one `content_hash` and gbrain version is held in `dream.patterns.grounding_holds.<source>` out of the leftover query and listed in `details.grounding_held` (warn) until the page or version changes or that key is unset; a timeline-append page whose write-back fails is stored with its entries and reflections in `dream.patterns.grounding_appends.<source>` (before the watermark stamps) and `retryPendingAppends` grounds it at the start of every later run, before the evidence and paid-child gates, at those reflections' derivation, then reverse-writes or verifies it (`details.timeline_append_retry`; a failed or held retry warns, a skipped pass included); the same 3-run content rule holds a page's appends (`grounding_held` rows with `timeline_appends`) until the page or version changes; run-scoped or systemic failures fail the phase and record nothing (`test/pathological/a23-patterns-grounding.test.ts`). 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`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Segmented storage: `loadGroundingSources` reads a segmented reflection through `materializeSegmentedBody` (over `PAGE_MAX_BYTES` it is not a source, logged), and `groundTimelineAppends` reads pattern pages through `materializedSnapshot`, skipping an over-ceiling page (`segmented_skipped`). Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts` and `test/cycle-patterns-segmented.test.ts` (both engines). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`. #6297: an in-cycle run (not `--once`, not a direct `--phase patterns`, `CycleOpts.directPhases`) is skipped with `patterns_min_interval` while the partition's last COMPLETED child ended less than `dream.patterns.min_interval_hours` (default 6, 0 off) ago (`patternsCadenceSkip` in `patterns-plan.ts`; stamp `dream.patterns.last_completed_at.<source>.<incarnation>`, `.external` for the external partition), and the child gets `read_budget_bytes` from `dream.patterns.child_read_budget_kb` (default 200). Pinned by `test/cycle-patterns-cadence.serial.test.ts` and `test/cycle-patterns-read-budget.serial.test.ts`. #6779: the OUTPUT POLICY tells the child to keep an existing page's slug, skip it when its evidence covers the pattern, else rewrite it with get_page's `revision` as `expected_revision`, and to append with `add_timeline_entry` or skip a `read_budget_exhausted` summary (`test/cycle-patterns-revision-6779.test.ts`). #6982 (GBRA-131 D-8): `reverseWriteRefs` writes each file through `writeDreamPageFile` (derived-write-through.ts); a page whose file holds an edit the database lacks keeps its file and is listed in `details.file_holds` (`file_database_drift`, with its fix), which turns an ok phase into warn; the pending-append retry reports its holds the same way (`test/pathological/d8-patterns-reverse-write.test.ts`, both engines).- `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. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. 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. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each new take at the cluster's tier: `insert` writes it and `recordFlaggedRow` in the same transaction, `hold` records a `write_gate_holds` row and leaves the facts unconsolidated, `reject` skips the cluster (`details.clusters_gate_held` / `clusters_gate_rejected`); a re-promotion inserts nothing and is not gated; managed takes are gated in takes-prepare. Clustering (`clusterFacts`): typed metric facts cluster at `cycle.consolidate.cluster_threshold` (0.85) when `claimsCompatible` (same metric, unit, period); untyped facts cluster only at `untypedClusterThreshold` (max of the configured threshold and the 0.95 explicit-duplicate bar) and never when `claimsDiverge` (a differing negation, number, date or amount token), so two event facts about different invoices or amounts stay separate and the `valid_until` writeback never expires a true fact. `details.untyped_cluster_threshold` reports the bar; a dry run adds `details.clusters` (at most 50: source, entity, would-be claim, member ids and visibility; private text only when `opts.remote === false`). Each bucket is one item (ItemRun site `consolidate.buckets`): a bucket that throws (managed: an entity or evidence page private or deleted while its world facts stay active, `page_not_found`) counts in `details.buckets_failed`, samples up to 10 `details.bucket_failures` `{source_id, entity_slug, code, message, fix}` and makes the phase `warn` while later buckets consolidate; run-scoped errors, an accepted pending write and `item_failures_systemic` still end it (`test/pathological/a22-consolidate-buckets.test.ts`). Pinned by `test/trust-taint-dream.test.ts` and `test/consolidate-divergence.test.ts`.@@ -15,13 +15,13 @@ Patterns, drift reports and the cycle modules listed after them.- `src/core/cycle/attribution-checks.ts` — #5425 [UC4]: `dream.attribution_checks` (`ATTRIBUTION_CHECKS_KEY`, registered in `KNOWN_CONFIG_KEYS`; `config set` takes a boolean word through `CYCLE_GUARDED_KEYS` in `cycle/config-guards.ts`), the one default-off switch for the two mechanical attribution checks: the propose_takes holder downgrade (`propose-takes-attribution.ts`) and the synthesis `superseded_in_source` quarantine (`synthesize-verify.ts`). `attributionChecksEnabled(engine)` is `isConfigTruthy` over the stored value and false on any read error. The default flips only on a held-out gbrain-evals receipt, the same bar as the prompt rules `dream.synthesize.attribution_rules` / `dream.propose_takes.attribution_rules`.- `src/core/cycle/propose-takes-attribution.ts` — #5425 [UC4]: `downgradeAssistantOnlyHolders(proposals, pageBody)`, called once from `propose-takes.ts` right after the extractor returns when `dream.attribution_checks` is on. `claimContentTokens` takes a claim's numeric keys (`numericClaims`: currency, scaled amounts, percents, dates, 4+ digit numbers; bare years dropped) and its quoted phrases (`extractQuoteSpans`, normalized); `statedBySpeaker` credits each token to the speakers whose turns state it, plus a speaker who explicitly accepted the previous turn. A `people/<slug>` proposal every one of whose stated tokens was stated only by `assistant` is returned with holder `brain`; a token the user stated or accepted, a claim with no tokens, tokens no turn states, a page without speaker turns, and non-person holders leave the proposal untouched. Pure: returns the input array when nothing changes. Pinned by `test/propose-takes-attribution.test.ts` (standalone) and `test/propose-takes-attribution-callsite.test.ts` (the call, `test.todo` until the wave 13 hunk lands).- `src/core/cycle/synthesize-verify-epochs.ts` — the scope side of dream-page verification, peeled move-only from `synthesize-verify.ts` (module-size ratchet) and re-exported from it: `readVerifyEpoch`, `loadChildWriteEpochs`, `loadPreRunRevision`, `isDreamOwnedPage`, `resolveVerifyPrior`, exactly as described under `synthesize-verify.ts` above. Pure database reads; no claim check lives here.-- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the 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 (plus `created: <summary date>`, #6773, so the summary passes temporal lint) — 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. A phase that throws fails with `SYNTH_PHASE_FAIL`; when the throw is an `OperationError` its suggestion becomes `error.hint` and its code `details.error_code`, so a postprocess `revision_conflict` names the slug, source and revision. 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. #6860: triage string cuts use `truncateUtf8`.+- `src/core/cycle/synthesize.ts` — Synthesize phase: conversation-transcript-to-brain pipeline, a two-stage cascade where cheap scored triage gates frontier synthesis. Reads `dream.synthesize.session_corpus_dir`, runs `runTriagePass` (exported; bounded pool `dream.triage.concurrency` default 4, wall-clock cache-MISS budget `dream.triage.max_ms` default 5 min — cache hits are free and deferred files report `deferred: true`, never cached, so the next pass continues) whose judge `judgeSignificance` emits `{score 0-1 ordinal salience, content_type, segments ≤8 verbatim quotes, entities ≤12, reasons}` (non-overlapping bands LOW 0-0.29 / MEDIUM 0.30-0.69 / HIGH 0.70-1.0; head 50%/middle 20%/tail 30% sample within `dream.triage.max_chars` default 24K via `safeSplitIndex`; out-of-[0,1] scores are `unparseable`, never clamped) cached in `dream_verdicts` with the judging `model` + `TRIAGE_VERSION` — cache validity requires BOTH to match (switching `models.dream.triage` re-judges; `max_chars`/`max_tokens` deliberately excluded from validity — `dream retriage --force` re-judges under new sampling knobs). Degenerate verdicts (`truncated`/`refusal`/`unparseable`) are never cached as verdicts: `triage-backoff.ts` upserts a score-NULL backoff marker instead and the next passes report the file `deferred` with `code: 'triage_unreliable_backoff'` (counted in `details.triage.unreliable_backoff`, not in `deferred`, so the cooldown and autopilot's maintenance stamp are not held) without a judge call until the backoff ends; nor is a verdict a `chat_fallback_chain` model gave (`TriageResult.answeredBy`, from the judge client's `answered_by` marker): it decides the run and the next cycle re-judges on the configured model. THE gate is `passesTriageGate` (triage-rescue.ts): `score >= dream.triage.threshold` (default 0.5) OR the verified-segment rescue, applied at report construction inside `runTriagePass` at READ time — retuning the threshold or rescue knobs re-gates with zero re-judging; the 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 (plus `created: <summary date>`, #6773, so the summary passes temporal lint) — 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. A phase that throws fails with `SYNTH_PHASE_FAIL`; when the throw is an `OperationError` its suggestion becomes `error.hint` and its code `details.error_code`, so a postprocess `revision_conflict` names the slug, source and revision. 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. #6860: triage string cuts use `truncateUtf8`. #6982 (GBRA-131 D-7/D-9): the reverse-write and the unmanaged summary file go through `writeDreamPageFile` (derived-write-through.ts), so a file holding an edit the database lacks is kept and listed in `details.file_holds` (the phase warns); `writeSummaryPage` returns the summary's hold and its database row keeps the replaced body in page_versions (`putDerivedPage`). Pinned by `test/pathological/d7-synthesize-reverse-write.test.ts` and `test/pathological/d9-dream-summary-overwrite.test.ts` (both engines).- `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`. #6091: `.txt` corpus files pass through `withoutOffPeriodTurns` (capture-consent.ts), so turns captured or retired under writeback off never feed synthesis.- `src/core/cycle/triage-rescue.ts` — THE dream triage gate (`passesTriageGate`) + the verified-segment rescue (`applyTriageRescue`). Rescue fires only for scores in `[floor, threshold)` (floor inclusive; at/above threshold is the plain gate's job) with content_type in the buried-signal allowlist (default mixed/reflection/idea/strategy/people — never routine/technical) and ≥ minSegments of the judge's own segments verifying as normalized transcript substrings (`normForGrounding`, ≥40 chars, deduped by normalized quote — repetition is not more evidence). $0 — no LLM calls; fabricated segments cannot fire it; works on cached verdicts (gate-time only). Fail-closed on every malformed shape (null score, missing/short/non-string segments), never throws. `minSegments: 0` is the kill switch (gate degenerates to the plain threshold). ONE-GATE RULE: `runTriagePass` (report construction — `worth`/`rescued`/telemetry/dry-run), the synthesize fan-out, and `dream retriage` (reconcile-queue cancels + `--audit-rejects` sampling) all read this predicate — a second hand-rolled `score >= threshold` check is how an operator sweep cancels exactly the jobs the rescue admitted. Config: `dream.triage.rescue_floor` / `rescue_min_segments` / `rescue_content_types`. Pinned by `test/cycle-triage-rescue.test.ts` + the rescue suites in `test/cycle-synthesize-triage.test.ts` / `test/dream-retriage.test.ts`. System One S7: a decide verdict (`model` starting with `DECIDE_VERDICT_PREFIX`) is gated against the S7 slot threshold (the optional fifth argument) and never enters the rescue band.-- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory, then calls `writePageThrough` (which honours `sync.write_through=off`) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. Tests: `test/cycle/derived-write-through.test.ts`.+- `src/core/cycle/derived-write-through.ts` — opt-in markdown write-through for generated pages on an unmanaged brain (#5041). `cycle.extract_atoms.write_through` / `cycle.synthesize_concepts.write_through` (off by default; `true`/`1`/`yes`/`on`) make `derivedWriteThrough` return a hook (null when off, managed or dry run): `extract_atoms` writes each item's atoms after the completion flip and removes the files of atoms it retired; `synthesize_concepts` writes through `publishClassicConcept`, which also rewrites a concept that already has a file whatever the key says. Creating the hook writes up to 200 generated pages per run that have no file yet (`source_path` NULL; pending atoms excluded), so enabling the key backfills. `writeDerivedPageThrough` keeps a page database-only when its target is ignored by git or sits in a declared `storage.db_only` directory, then calls `writePageThrough` (which honours `sync.write_through=off`) and returns its result (`written`, `skipped`, `error`) so `publishClassicConcept` can surface a failed write. Tests: `test/cycle/derived-write-through.test.ts`. #6982: `writeDreamPageFile` is the dream reverse-write (synthesize, patterns, the cycle summary): nothing with `sync.write_through` off, for an owned url clone or a `storage.db_only` slug; the path is `resolvePageWriteTarget`'s (recorded source_path), falling back to the caller's brainDir layout when the source has no root or its root is missing; the file is replaced only when `replaceableFile` (facts/file-body-guard.ts) finds nothing in it the database lacks and still holds the compared bytes right before a staged rename, else the result carries the `file_database_drift` hold. It writes directly (not `writePageThrough`/`atomicWriteFileSync`) because a checkout a subagent tool write claimed through the coordinator refuses those with `writer_coordinator_required`. `withFileHolds` lists holds in `details.file_holds` and turns ok into warn.- `src/core/cycle/concept-publication.ts` — managed `synthesize_concepts` publication: `publishManagedConcept` publishes through `publishMaintenancePage` (a concept with a recorded `source_path` republishes to its file unless a `db_only` tier covers it; new concepts are database-only), and `composeConceptRepublication` keeps an existing concept's facts/takes fences, timeline, tags and other frontmatter, holding the concept (`concept_preservation_hold`) when a fence is duplicated, unbalanced, unparseable or below the timeline sentinel. `addManagedProvenanceLinks` commits the concept-provenance edges inside a coordinated transaction. On an unmanaged brain `publishClassicConcept` writes under the page lock the fence writers take: it re-reads the page, defers (`revision_conflict`) when the narrative changed since synthesis started, another writer owns it, or the page's file holds an edit the database has not imported (narrative, frontmatter, tags, type or title; formatting is ignored), and otherwise composes the new narrative with the latest fences (from the page's file when it has one), so a take added during synthesis survives. The file write after `importPage` passes the bytes read under the lock as `expectedFileBytes`, so an edit landing during the import is kept and the concept deferred; a failed file write holds the concept (`concept_write_through_failed`) instead of reporting success (W9F item 3, `test/cycle/concept-publication-file-recheck.test.ts`). `stripFenceSections` is the shared narrative view. Tests: `test/cycle/synthesize-concepts-fences.test.ts`. The phase keeps the private-first, provenance, then promotion order; revision races are deferred and holds reported in the phase details. Tests: `test/managed-writers-w3.test.ts`. #6161: `preserveCanonicalFences` also carries curated `## Facets` / `## Merged` sections verbatim (`cycle/concept-sections.ts`; a model-written copy is dropped, and the lossless check covers them), and `synthesize-concepts.ts` groups atoms through `cycle/concept-redirects.ts` `loadConceptRedirects` (`merged_into` on any live concept page, `aliases` on phase-owned ones; one hop, two-way redirects ignored) and skips a tombstoned concept page as `skipped_deleted` instead of resurrecting it (`test/cycle/synthesize-concepts-merge.test.ts`). #5965: the same module folds spelling variants for one run: `addSpellingRedirects` groups the post-redirect stems by `spellingFoldKey` (ASCII `-`, `_` and `.` removed; Unicode kept), and a group of two or more stems redirects every stem to the one that already has a live top-level `concepts/<stem>` page (`loadLiveConceptStems`), else to the most frequent spelling (tie: the hyphenated one, then alphabetical); a group where two or more spellings already have live pages is left alone ([R28]: `re-sign` / `resign` are different concepts and only the human merge path joins them). The redirects are in-memory only (no `merged_into` write); the grouping applies `canonicalConceptStem` twice (human hop, then spelling hop), and the phase receipt lists the folds in `details.folded_spellings`. Pinned by `test/cycle-synthesize-concepts-grouping.test.ts`.- `src/core/cycle/connector-atoms.ts` — the connector atom setting (#5856). `CONNECTOR_ATOM_PAGES_KEY` (`cycle.extract_atoms.connector_pages`, on when unset; `connectorAtomPagesEnabled` treats only false/0/off/no as opted out) gates `CONNECTOR_ATOM_PAGE_TYPES` (`email`, `meeting`) of sources whose `config.kind` is a connector kind (`CONNECTOR_SOURCE_KINDS`). `connectorAtomExclusionSql` returns the `pages p` predicate atom discovery and the backlog count append (empty unless opted out), so the routine cycle, `dream --drain` and autopilot auto-drain extract connector mail and calendar pages under the auto-drain budget until the user opts out. Other page types of a connector source and every checkout-backed page are unaffected. Tests: `test/connector-atom-pages.test.ts`, `test/autopilot-auto-drain-dispatch.test.ts`, and the `atom_drain_default_on` / `atom_drain_opted_out` cases of `test/helpers/managed-connector-job-contract.ts`, run by `test/managed-connector-job-contract.test.ts` and its Postgres twin `test/e2e/managed-connector-job-contract.test.ts`.diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.mdindex f86dbf97f3..c87940b5c3 100644--- a/docs/architecture/key-files/core-cycle.md+++ b/docs/architecture/key-files/core-cycle.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/cycle/dream-provenance.ts` — `summaryProvenanceLines` (#6642) writes the cycle summary's provenance section: `dream_cycle_date` is first-write provenance, so it reports the count the recovery query returns and, separately, the pages this cycle rewrote that keep an earlier cycle's date. `stampDreamProvenance`, the unmanaged dream-output identity stamp shared by synthesize and patterns: sets `dream_generated`, a stable `dream_cycle_date` / `dream_created_cycle_date` and an optional `raw_source` in page frontmatter, and leaves a page that existed before the child's first write to it (`first_write_at`) unstamped. Managed brains stamp through maintenance writes instead. A ref's optional `seat` is stamped beside `raw_source` (the capturing agent seat, #4618). #5575 I2: a ref carrying `derivation` is stamped in `derivedMaintenanceTransaction` at the child's derived tier, and the page is lowered to it and gets its `derivation_inputs` edges even when it is not dream-owned (the child wrote it from that prompt). Pinned by `test/trust-taint-dream.test.ts`.-- `src/core/cycle/dream-taint.ts` — #5575 I2 taint for the dream derivers (ENG-3): `transcriptDerivation` gives a synthesis transcript's tier (a `gbrain-page://` conversation page = that page's stored tier, with an edge to it; a file under `dream.synthesize.meeting_transcripts_dir` = external_untrusted; any other corpus file = the cap its frontmatter names, else agent_written); `transcriptsDerivation` takes the least trusted of several; `withTranscriptTaint` attaches it to unmanaged output refs; `summaryDerivation` / `putDerivedPage` write the dream summary at the tier of the pages it indexes; `patternsDerivation` is one patterns pass's tier over the reflections in its prompt. The tier is read when outputs are stamped (a page can only be lowered meanwhile). Pinned by `test/trust-taint-dream.test.ts`.+- `src/core/cycle/dream-taint.ts` — #5575 I2 taint for the dream derivers (ENG-3): `transcriptDerivation` gives a synthesis transcript's tier (a `gbrain-page://` conversation page = that page's stored tier, with an edge to it; a file under `dream.synthesize.meeting_transcripts_dir` = external_untrusted; any other corpus file = the cap its frontmatter names, else agent_written); `transcriptsDerivation` takes the least trusted of several; `withTranscriptTaint` attaches it to unmanaged output refs; `summaryDerivation` / `putDerivedPage` write the dream summary at the tier of the pages it indexes; `patternsDerivation` is one patterns pass's tier over the reflections in its prompt. The tier is read when outputs are stamped (a page can only be lowered meanwhile). Pinned by `test/trust-taint-dream.test.ts`. #6982 (GBRA-131 D-9): `putDerivedPage` keeps a live body it replaces with a different one in page_versions first (raw putPage keeps none).- `src/core/cycle/extract-atoms-schema.ts` — shared atom-type vocabulary and the extraction response schema. The private model prompt requests an object containing `atoms`; the schema uses closed objects and nullable optional metadata. `extract-atoms.ts` passes it through the gateway's capability gate and existing schema-rejection fallback, while its tolerant parser still accepts legacy bare arrays. Schema submission does not replace grounding or malformed-output checks. Covered by `test/cycle/extract-atoms-structured-output.test.ts` using a local HTTP protocol fixture and isolated PGLite, without live model inference.- `src/core/cycle/extract-atoms-parse.ts` — extract_atoms response parsing, re-exported by `extract-atoms.ts`. `parseAtomsOutcome` returns a typed outcome (`ok: false` with a stable reason string for malformed output, `ok: true, atoms: []` for an honest zero-yield), retrying once with reasoning blocks stripped. `parseAtomsOutcome(text, stopReason)` takes the gateway stop reason: `length`/`refusal`/`content_filter` are never parsed, and an empty answer under `other`/`tool_calls` is not taken as complete; both return `ok: false, stopped: true`, which `extract-atoms.ts` counts in `details.stopped_outputs` and fails like malformed output (unmanaged: the bounded streak; managed: a failure receipt that never retires earlier atoms; `test/cycle/extract-atoms-stop-reason.test.ts`, `test/managed-atoms-stop-reason.test.ts`). A bounded anchor scan (`MAX_ARRAY_ANCHOR_CANDIDATES`) tries successive `[` offsets; each candidate ends at its own closing bracket (`matchingCloseBracket` in `llm-json.ts`), the first array yielding an atom-shaped element wins, a literal `[]` is zero-yield only when no earlier `[` is still open at its offset (an atom's own `"concepts": []` inside a clipped or malformed array is malformed output, `test/extract-atoms-nested-empty-array.test.ts`), and failure reasons always describe the first bracket. `atomsFromParsedArray` is the single atom shape gate.@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `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 → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → 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; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `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. GBRA-130 A-24: the pass resumes after the last slug it examined (`slug > cursor`, op_checkpoints op `PHANTOM_REDIRECT_CURSOR_OP` = `phantom-redirect-cursor`, fingerprint the source id, via `rotationAfter`/`saveRotation`), so root prose notes that are not phantoms no longer starve later phantoms; the cursor resets to `''` after a full pass and stays put on a dry run, an abort or a stop. Phantoms run as `ItemRun` items (`extract_facts.phantom_redirect`): an item error is a `failures[]` entry (`key`, `code`, `message`, `fix` `gbrain dream --phase extract_facts --source <id>`) and the next phantom still runs; a run-scoped error rethrows and `item_failures_systemic` sets `stopped`. `extract-facts.ts` turns them into `phantom_redirect_failed: <slug> (<code>); retry: <fix>` and `phantom_redirect_stopped: …` warnings. Pinned by `test/pathological/a24-phantom-redirect-cursor.test.ts` (both engines).+- `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 → a phantom fence that parses with warnings is `drift` (its skipped rows would go with the deleted phantom, #6385 R12) → 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; throws `FenceRewriteRefusal` on a canonical fence that parses with warnings, which the pass records as `drift`), `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. GBRA-130 A-24: the pass resumes after the last slug it examined (`slug > cursor`, op_checkpoints op `PHANTOM_REDIRECT_CURSOR_OP` = `phantom-redirect-cursor`, fingerprint the source id, via `rotationAfter`/`saveRotation`), so root prose notes that are not phantoms no longer starve later phantoms; the cursor resets to `''` after a full pass and stays put on a dry run, an abort or a stop. Phantoms run as `ItemRun` items (`extract_facts.phantom_redirect`): an item error is a `failures[]` entry (`key`, `code`, `message`, `fix` `gbrain dream --phase extract_facts --source <id>`) and the next phantom still runs; a run-scoped error rethrows and `item_failures_systemic` sets `stopped`. `extract-facts.ts` turns them into `phantom_redirect_failed: <slug> (<code>); retry: <fix>` and `phantom_redirect_stopped: …` warnings. Pinned by `test/pathological/a24-phantom-redirect-cursor.test.ts` (both engines). #6982 (GBRA-131 D-5/D-6): with `sync.write_through` off the phantom's rows merge into the canonical's database body under a row lock (prior body in page_versions) and no file is written or removed. With it on, the phantom's file is removed only when `replaceableFile` finds nothing in it its row lacks (re-read right before the unlink; a changed file is kept and reported), and the canonical file takes the rows only when its body and timeline equal the canonical's database body; the mirror then runs under the row lock (`mirrorFileBody`, prior body in page_versions, importer hash) with the `.tmp` renamed last, and a body or file that moved holds the phantom. Holds are `drift` outcomes listed in `PhantomPassResult.held` (`<slug> (file_database_drift: …)` with its fix), which extract_facts turns into `phantom_redirect_held:` warnings. Pinned by `test/pathological/d5-phantom-canonical-overwrite.test.ts` and `test/pathological/d6-phantom-file-unlink.test.ts` (both engines).- `src/core/cycle/phantom-redirect-managed.ts` — managed-brain phantom redirect (#5280). After the same gates, `redirectManagedPhantom` runs `maintenancePreflight`, renders the canonical body with the phantom's fence rows appended and submits `managed_maintenance_phantom_merge` on the canonical page (keyed by its intent): `preparePhantomMerge` rechecks the phantom's id and revision, and its publication moves withdrawals, the phantom's fact rows by id, links and the rename alias in the canonical page's publication transaction. It then submits `managed_maintenance_phantom_delete` on the phantom, bound to the merged revision: `preparePhantomDelete` holds both page keys, moves any edge added to the phantom since the merge, defers if timeline rows appeared, then soft-deletes and removes the file. A missing canonical page or a changed phantom is reported as `drift`. Tests: `test/managed-facts-writers.test.ts`.diff --git a/src/core/cycle/derived-write-through.ts b/src/core/cycle/derived-write-through.tsindex de1bf55fea..beff5fadd6 100644--- a/src/core/cycle/derived-write-through.ts+++ b/src/core/cycle/derived-write-through.ts@@ -15,12 +15,14 @@* phase retires has its file removed, so sync cannot bring it back.*/import { execFileSync } from '../spawn.ts';-import { existsSync, mkdirSync, readFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';import { dirname, join, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';import type { PhaseResult } from '../cycle.ts';-import { atomicWriteFileSync } from '../atomic-write.ts';-import { fileDatabaseDriftFix, replaceableFile } from '../facts/file-body-guard.ts';+import type { Page } from '../types.ts';+import { throwIfAborted } from '../abort-check.ts';+import { validateSourceId } from '../utils.ts';+import { fileDatabaseDriftToken, replaceableFile } from '../facts/file-body-guard.ts';import { isDbOnly, loadStorageConfig } from '../storage-config.ts';import { deletePageThrough, isWriteThroughDisabled, resolvePageWriteTarget, writePageThrough } from '../write-through.ts';import { urlCloneReadOnly } from '../url-clone.ts';@@ -109,9 +111,10 @@ export type DreamPageFileWrite = { written: true; path: string } | { written: fa* foreign sources under `.sources/<id>/`). The file is replaced only when `replaceableFile` finds nothing in it the* database lacks, and is re-read right before the atomic write, so an edit that lands in between is kept as well.*- * This is the reverse-write's own direct write, not `writePageThrough`: once a subagent's tool write has gone through- * the coordinator, the checkout carries an owner marker and `writePageThrough` refuses `writer_coordinator_required`,- * which would leave the file behind the database for the next coordinated write to refuse as drift.+ * This is the reverse-write's own direct write (a staged sibling renamed over the file), as before, not+ * `writePageThrough` or `atomicWriteFileSync`: once a subagent's tool write has gone through the coordinator, the+ * checkout carries an owner marker and both refuse `writer_coordinator_required`, which would leave the file behind the+ * database for the next coordinated write to refuse as drift.*/export async function writeDreamPageFile(engine: BrainEngine, brainDir: string, slug: string, sourceId: string,opts: { nativeSourceId: string; markdown: string }): Promise<DreamPageFileWrite> {@@ -131,14 +134,15 @@ export async function writeDreamPageFile(engine: BrainEngine, brainDir: string,return { written: false, held: dreamFileDriftToken(slug, sourceId, 'during') };}mkdirSync(dirname(filePath), { recursive: true });- atomicWriteFileSync(filePath, opts.markdown);+ const staged = `${filePath}.${process.pid}.tmp`;+ writeFileSync(staged, opts.markdown, 'utf-8');+ renameSync(staged, filePath);return { written: true, path: filePath };}/** #6982: the hold entry for a dream page whose file holds an edit the database lacks. */function dreamFileDriftToken(slug: string, sourceId: string, when: 'before' | 'during'): string {- return `${slug} (file_database_drift: the file ${when === 'before' ? 'holds an edit the database lacks' : 'changed while the dream cycle wrote it'}, `- + `so the dream output stays in the database only and the file was not replaced. ${fileDatabaseDriftFix(slug, sourceId)})`;+ return fileDatabaseDriftToken(slug, sourceId, when, 'the dream output stays in the database only', 'the dream reverse-write');}/** A dream phase result with its held page files: listed in `details.file_holds`, and an ok phase warns. */@@ -147,3 +151,36 @@ export function withFileHolds(result: PhaseResult, held: readonly string[]): Phareturn { ...result, status: result.status === 'ok' ? 'warn' : result.status, details: { ...result.details, file_holds: [...new Set([...((result.details.file_holds as string[] | undefined) ?? []), ...held])] },summary: `${result.summary}; ${held.length} page file(s) held because they differ from the database (details.file_holds)` };}++/**+ * The dream reverse-write loop (synthesize, patterns, #6982): each ref's page rendered by `render` and written through+ * `writeDreamPageFile`. A page whose file holds an edit the database lacks keeps that file and its `file_database_drift`+ * entry is pushed to `held`; an abort stops before the next file; other per-page failures are logged and skipped.+ * Returns the number of files written.+ */+export async function reverseWriteDreamRefs<R extends { slug: string; source_id: string }>(engine: BrainEngine, brainDir: string, refs: R[],+ opts: { phase: string; nativeSourceId: string; render: (page: Page, tags: string[], ref: R) => string; signal?: AbortSignal; held?: string[] }): Promise<number> {+ let count = 0;+ for (const ref of refs) {+ const { slug, source_id } = ref;+ throwIfAborted(opts.signal, `[dream] ${opts.phase} reverse-write`);+ // v0.32.8 F6: validate source_id is filesystem-safe before any join().+ validateSourceId(source_id);+ const page = await engine.getPage(slug, { sourceId: source_id });+ if (!page) continue;+ const tags = await engine.getTags(slug, { sourceId: source_id });+ // #4077: re-check after the row reads — an abort that lands during+ // getPage/getTags must not reach this ref's file write.+ throwIfAborted(opts.signal, `[dream] ${opts.phase} reverse-write`);+ try {+ const file = await writeDreamPageFile(engine, brainDir, slug, source_id, { nativeSourceId: opts.nativeSourceId, markdown: opts.render(page, tags, ref) });+ if (file.written) count++;+ else if (file.held) opts.held?.push(file.held);+ else if (file.error) process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${file.error}\n`);+ } catch (e) {+ // Per-slug failures are non-fatal — phase continues.+ process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${e instanceof Error ? e.message : String(e)}\n`);+ }+ }+ return count;+}diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex f28ee52c6c..fc5b4f329a 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -44,7 +44,7 @@ import type { Page, PageType } from '../types.ts';// slot and can deadlock a fully-occupied worker (#2050). synthesize.ts// drains its own children the same way.import { loadAllowedSlugPrefixes, loadOutputRoot, runSubagentsInline } from './synthesize.ts';-import { withFileHolds, writeDreamPageFile } from './derived-write-through.ts';+import { reverseWriteDreamRefs, withFileHolds } from './derived-write-through.ts';import { stampDreamProvenance } from './dream-provenance.ts';import { probeChatModelWithKey } from '../ai/chat-key-probe.ts';import { normalizeModelId } from '../model-id.ts';@@ -425,8 +425,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, conconst reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized): await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds);const details = { reflections_considered: submitted.length, reflections_selected: selected, plan_basis: plan.basis, patterns_written: finalized.length,- ...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held, ...grounding.details,- ...(fileHolds.length ? { file_holds: fileHolds } : {}),+ ...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held, ...grounding.details, ...(fileHolds.length ? { file_holds: fileHolds } : {}),timeline_appends: appends.length, appended_unverified: appendedUnverified, child_outcome: outcome, job_id: job.id };const appendedNote = appends.length > 0 ? `; ${appends.length} timeline entr${appends.length === 1 ? 'y' : 'ies'} appended${quoteVerify ? ' (quote-verified)' : ''}` : '';@@ -1086,50 +1085,13 @@ async function countChildTimelineAppends(engine: BrainEngine, childIds: number[]// ── Reverse-write ────────────────────────────────────────────────────-import { validateSourceId } from '../utils.ts';import { renderTimelineEntry } from '../timeline-write-through.ts';import { materializedMarker } from '../timeline-marker.ts';-/**- * Reverse-render each pattern page to its markdown file (`writeDreamPageFile`, #6982): a page whose file holds an edit- * the database lacks keeps that file and its `file_database_drift` entry is pushed to `held`.- */-async function reverseWriteRefs(- engine: BrainEngine,- brainDir: string,- refs: Array<{ slug: string; source_id: string }>,- nativeSourceId = 'default',- signal?: AbortSignal,- held?: string[],-): Promise<number> {- let count = 0;- for (const { slug, source_id } of refs) {- throwIfAborted(signal, '[dream] patterns reverse-write');- // v0.32.8 F6: guard against malformed source_id (would let join() break- // out of brainDir). validateSourceId throws on `..`, `/`, etc.- validateSourceId(source_id);- const page = await engine.getPage(slug, { sourceId: source_id });- if (!page) continue;- const tags = await engine.getTags(slug, { sourceId: source_id });- // #4077: re-check after the row reads — an abort that lands during- // getPage/getTags must not reach this ref's file write.- throwIfAborted(signal, '[dream] patterns reverse-write');- try {- // v0.32.8 F6: with no checkout root, foreign-source pages land under- // brainDir/.sources/<id>/<slug>.md so same-slug-different-source pages- // don't collide on disk; the cycle's own source (#1586: brainDir IS that- // source's checkout) stays at brainDir/<slug>.md. `.sources/` is a- // reserved prefix; walkBrainRepo skips dot-dirs.- const file = await writeDreamPageFile(engine, brainDir, slug, source_id, { nativeSourceId, markdown: renderPageToMarkdown(page, tags) });- if (file.written) count++;- else if (file.held) held?.push(file.held);- else if (file.error) process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${file.error}\n`);- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${msg}\n`);- }- }- return count;+/** Reverse-render each pattern page to its markdown file (`reverseWriteDreamRefs`, #6982); holds go to `held`. */+async function reverseWriteRefs(engine: BrainEngine, brainDir: string, refs: Array<{ slug: string; source_id: string }>,+ nativeSourceId = 'default', signal?: AbortSignal, held?: string[]): Promise<number> {+ return reverseWriteDreamRefs(engine, brainDir, refs, { phase: 'patterns', nativeSourceId, signal, held, render: renderPageToMarkdown });}function renderPageToMarkdown(page: Page, tags: string[]): string {diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 97036c59ac..9973e5bee0 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -61,7 +61,7 @@ import { isAborted } from '../abort-check.ts';import { logPhantomEvent, type PhantomOutcome } from '../facts/phantom-audit.ts';import { MOVE_WITHDRAWAL_SUBJECT_SQL } from '../facts/withdrawal-schema.ts';import { isWriteThroughDisabled, resolvePageWriteTarget } from '../write-through.ts';-import { fileBodyMatchesStored, fileDatabaseDriftFix, mirrorFileBody, readStoredBody, replaceStoredBody, replaceableFile } from '../facts/file-body-guard.ts';+import { fileBodyMatchesStored, fileDatabaseDriftToken, mirrorFileBody, readStoredBody, replaceStoredBody, replaceableFile } from '../facts/file-body-guard.ts';import { recordRenameAlias } from '../page-state/rename-alias.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';@@ -309,22 +309,18 @@ async function mergeIntoCanonicalBody(if (body === null) return { renumber };const written = await maintenanceTransaction(engine, tx =>replaceStoredBody(tx, sourceId, canonical.slug, { compiled_truth: body, timeline: expected.timeline ?? '' }, expected));- return written ? { renumber } : { held: `${canonical.slug} (file_database_drift: the canonical's database body changed while the phantom was redirected, so nothing was written; the next cycle retries)` };+ return written ? { renumber } : { held: fileDatabaseDriftToken(canonical.slug, sourceId, 'during', 'the phantom was not redirected; the next cycle retries', 'the phantom redirect') };}/** #6982: the hold entry for a phantom whose canonical file and database body differ (or moved during the redirect). */function canonicalDriftToken(canonical: string, phantomSlug: string, sourceId: string, when: 'before' | 'during'): string {- return `${canonical} (file_database_drift: the canonical file and the database body ${when === 'before' ? 'differ' : 'changed while the phantom was redirected'}, `- + `so the phantom ${phantomSlug} was not redirected and neither copy changed. ${fileDatabaseDriftFix(canonical, sourceId)})`;+ return fileDatabaseDriftToken(canonical, sourceId, when, `the phantom ${phantomSlug} was not redirected`, 'the phantom redirect');}-/** #6982: the hold entry for a phantom whose own file holds content its database row lacks. */+/** #6982: the hold entry for a phantom whose own file holds content its database row lacks (or changed before the unlink). */function phantomFileDriftToken(phantomSlug: string, sourceId: string, when: 'before' | 'during'): string {- return when === 'before'- ? `${phantomSlug} (file_database_drift: the phantom's file holds content its database row lacks, so it was not redirected and the file was kept. `- + `gbrain sync --source ${sourceId} imports the file; ask the user before discarding it)`- : `${phantomSlug} (file_database_drift: the phantom's file changed while it was redirected, so the file was kept. `- + `gbrain sync --source ${sourceId} imports it again as a page; ask the user whether to keep it or delete the file)`;+ return fileDatabaseDriftToken(phantomSlug, sourceId, when, when === 'before' ? 'the phantom was not redirected'+ : 'the redirect moved its rows to the canonical page but kept the file, which sync imports again as a page until the user deletes it', 'the phantom redirect');}/** A phantom left in place by a `file_database_drift` hold: audited as drift and reported by the pass. */diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex 3b9a3e3c4c..b2678073b5 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -1,7 +1,7 @@import { observationDateLine, observationDateRule } from '../ai/date-grounding.ts';import { isConsumerDateGroundingOn } from '../facts/extract.ts';import { maintenancePreflight, publishMaintenancePage, type MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';-import { withFileHolds, writeDreamPageFile } from './derived-write-through.ts';+import { reverseWriteDreamRefs, withFileHolds, writeDreamPageFile } from './derived-write-through.ts';import { deferPublishOrThrow, finishDeferredPostprocess, loadCommittedOutputsOrDefer, postprocessManagedSynthesis, withPostprocessConflicts, withPublishPending, type PostprocessConflict, type RetainedOutput } from './synthesize-postprocess.ts';/*** Synthesize phase (v0.23; #4152 two-stage cascade) — conversation-to-brain@@ -89,7 +89,6 @@ import { discoverTranscripts, DEFAULT_EXCLUDE_PATTERNS, type DiscoveredTranscripimport { loadStorageConfig, isDbOnly } from '../storage-config.ts';import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';import type { Page, PageType } from '../types.ts';-import { validateSourceId } from '../utils.ts';import { safeSplitIndex, truncateUtf8 } from '../text-safe.ts';import { PAGE_SLUG_SEG } from '../cjk.ts';import { withChatPhase, estimateChatCostUsd } from '../ai/chat-usage.ts';@@ -1175,16 +1174,14 @@ async function runPhaseSynthesizeInner(// Dual-write: reverse-render each DB row → markdown file.const fileHolds: string[] = [];- const reverseWriteCount = maintenance ? (maintenance.binding ? writtenRefs.length : 0)- : await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds);+ const reverseWriteCount = maintenance ? (maintenance.binding ? writtenRefs.length : 0) : await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal, fileHolds);const summarySlug = buildDreamSummarySlug(config.outputRoot, summaryDate);const writtenSlugs = writtenRefs.map(r => r.slug);if (SUMMARY_SLUG_RE.test(summarySlug) && !publishPending) {const preserveSummary = maintenance && !writtenRefs.length && await engine.readPageSnapshot(summarySlug, { sourceId: cycleSourceId });- const summaryHeld = preserveSummary ? undefined : await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance)- .catch((e: unknown) => { deferPublishOrThrow(e, summarySlug); publishPending++; return undefined; });- if (summaryHeld) fileHolds.push(summaryHeld);+ if (!preserveSummary) await writeSummaryPage(engine, opts.brainDir, summarySlug, summaryDate, finalizedRefs.map(r => r.slug), childOutcomes, cycleSourceId, opts.signal, maintenance)+ .then(held => held && fileHolds.push(held), (e: unknown) => { deferPublishOrThrow(e, summarySlug); publishPending++; });}// #4077: nothing below runs for a cancelled cycle — no phase-end embed@@ -2977,46 +2974,11 @@ async function collectChildPutPageSlugs(// ── Reverse-write DB rows → markdown files ───────────────────────────-/**- * Reverse-render each page a child wrote to its markdown file (`writeDreamPageFile`, #6982): a page whose file holds an- * edit the database lacks keeps that file and its `file_database_drift` entry is pushed to `held`.- */-async function reverseWriteRefs(- engine: BrainEngine,- brainDir: string,- refs: Array<{ slug: string; source_id: string; first_write_at?: Date }>,- nativeSourceId = 'default',- signal?: AbortSignal,- held?: string[],-): Promise<number> {- let count = 0;- for (const { slug, source_id, first_write_at } of refs) {- throwIfAborted(signal, '[dream] synthesize reverse-write');- // v0.32.8 F6: validate source_id is filesystem-safe before any join().- validateSourceId(source_id);- const page = await engine.getPage(slug, { sourceId: source_id });- if (!page) continue;- const tags = await engine.getTags(slug, { sourceId: source_id });- // #4077: re-check after the row reads — an abort that lands during- // getPage/getTags must not reach this ref's file write.- throwIfAborted(signal, '[dream] synthesize reverse-write');- try {- // v0.32.8 F6: with no checkout root, foreign-source pages land at- // brainDir/.sources/<id>/<slug>.md so same-slug-different-source pages- // don't collide; the cycle's own source (#1586: brainDir IS that- // source's checkout) stays at brainDir/<slug>.md.- const markdown = isDreamOwnedPage(page, first_write_at) ? renderPageToMarkdown(page, tags) : serializePageToMarkdown(page, tags);- const file = await writeDreamPageFile(engine, brainDir, slug, source_id, { nativeSourceId, markdown });- if (file.written) count++;- else if (file.held) held?.push(file.held);- else if (file.error) process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${file.error}\n`);- } catch (e) {- // Per-slug failures are non-fatal — phase continues.- const msg = e instanceof Error ? e.message : String(e);- process.stderr.write(`[dream] reverse-write ${slug}@${source_id} failed: ${msg}\n`);- }- }- return count;+/** Reverse-render each page a child wrote to its markdown file (`reverseWriteDreamRefs`, #6982); holds go to `held`. */+async function reverseWriteRefs(engine: BrainEngine, brainDir: string, refs: Array<{ slug: string; source_id: string; first_write_at?: Date }>,+ nativeSourceId = 'default', signal?: AbortSignal, held?: string[]): Promise<number> {+ return reverseWriteDreamRefs(engine, brainDir, refs, { phase: 'synthesize', nativeSourceId, signal, held,+ render: (page, tags, ref) => isDreamOwnedPage(page, ref.first_write_at) ? renderPageToMarkdown(page, tags) : serializePageToMarkdown(page, tags) });}/**diff --git a/src/core/facts/file-body-guard.ts b/src/core/facts/file-body-guard.tsindex bc8f0bfc31..b6c1fe5901 100644--- a/src/core/facts/file-body-guard.ts+++ b/src/core/facts/file-body-guard.ts@@ -24,8 +24,8 @@ export interface StoredBody {/** The diagnostic and repair choices for a held unmanaged file/body mirror. */export function fileDatabaseDriftToken(slug: string, sourceId: string, when: 'before' | 'during',- disposition = 'its rows stay unfenced, active and searchable until they agree'): string {- return `${slug} (file_database_drift: the canonical file and the database body ${when === 'before' ? 'differ' : 'changed while the fence step ran'}, `+ disposition = 'its rows stay unfenced, active and searchable until they agree', step = 'the fence step'): string {+ return `${slug} (file_database_drift: the canonical file and the database body ${when === 'before' ? 'differ' : `changed while ${step} ran`}, `+ `so neither was replaced and ${disposition}. If the file holds the newer edit, `+ `gbrain sync --source ${sourceId} imports it; if the database copy is newer, re-save it with write-through on `+ `(gbrain get ${slug} --source ${sourceId}, then gbrain put ${slug} --source-id ${sourceId}); when both changed, ask the user which edit wins)`;@@ -75,12 +75,6 @@ export async function mirrorFileBody(tx: BrainEngine, sourceId: string, slug: streturn replaceStoredBody(tx, sourceId, slug, mirroredBody(fileBytes, slug), expected, hash);}-/** The fix sentence of a `file_database_drift` hold: which command settles each side, and when to ask the user. */-export function fileDatabaseDriftFix(slug: string, sourceId: string): string {- return `If the file holds the newer edit, gbrain sync --source ${sourceId} imports it; if the database copy is newer, re-save it with write-through on `- + `(gbrain get ${slug} --source ${sourceId}, then gbrain put ${slug} --source-id ${sourceId}); when both changed, ask the user which edit wins`;-}-/** Page states a checkout file is compared with: the live row, then its newest page_versions rows. */const HISTORY_ROWS = 20;@@ -91,7 +85,7 @@ function fileHeldBy(fileBytes: string, slug: string, state: StoredState): booleaif (!fileBodyMatchesStored(fileBytes, slug, state)) return false;const file = contentHashFrontmatterAndTags({ frontmatter: parseMarkdown(fileBytes, `${slug}.md`).frontmatter });const stored = contentHashFrontmatterAndTags({ frontmatter: state.frontmatter ?? {} });- return Object.entries(file.frontmatter).every(([key, value]) => stableJson(value) === stableJson(stored.frontmatter[key]));+ return Object.entries(file.frontmatter).every(([key, value]) => stored.frontmatter[key] !== undefined && stableJson(value) === stableJson(stored.frontmatter[key]));}/**diff --git a/test/cycle-patterns-timeline-appends.serial.test.ts b/test/cycle-patterns-timeline-appends.serial.test.tsindex 6eeb60150f..6c969e4fe2 100644--- a/test/cycle-patterns-timeline-appends.serial.test.ts+++ b/test/cycle-patterns-timeline-appends.serial.test.ts@@ -9,7 +9,7 @@* tool-execution ledger, so request ids and receipts are the production ones.*/import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -85,6 +85,8 @@ afterAll(async () => {beforeEach(async () => {await resetPgliteState(engine);+ rmSync(brainDir, { recursive: true, force: true });+ mkdirSync(brainDir);await engine.setConfig('version', schemaVersion);await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');await engine.setConfig('dream.quote_verify', 'true');diff --git a/test/pathological/d5-phantom-canonical-overwrite.test.ts b/test/pathological/d5-phantom-canonical-overwrite.test.tsindex 35c4d2c34a..a4b9c6732b 100644--- a/test/pathological/d5-phantom-canonical-overwrite.test.ts+++ b/test/pathological/d5-phantom-canonical-overwrite.test.ts@@ -144,9 +144,9 @@ for (const { backend, databaseUrl } of pathologicalArms()) {writeFileSync(b.path(CANONICAL), edited);const bodyBefore = await b.body(CANONICAL);const result = await expectUnitNotAborted(() => b.pass());- expect({ redirected: result.redirected, held: heldFor(result, CANONICAL).length }).toEqual({ redirected: 0, held: 1 });expect({ body: (await b.body(CANONICAL)) === bodyBefore, file: b.file(CANONICAL) === edited }).toEqual({ body: true, file: true });expect(await b.live(PHANTOM)).toBe(true);+ expect({ redirected: result.redirected, held: heldFor(result, CANONICAL).length }).toEqual({ redirected: 0, held: 1 });});}, 180_000);@@ -157,12 +157,13 @@ for (const { backend, databaseUrl } of pathologicalArms()) {await b.dbEdit(CANONICAL, DB_EDIT);const [canonicalFile, phantomFile] = [b.file(CANONICAL), b.file(PHANTOM)];const result = await expectUnitNotAborted(() => b.pass());- expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });const body = await b.body(CANONICAL);expect({ edit: body.includes(DB_EDIT), fence: claims(body) }).toEqual({ edit: true, fence: [CLAIM] });- expect({ canonicalFile: b.file(CANONICAL) === canonicalFile, phantomFile: b.file(PHANTOM) === phantomFile }).toEqual({ canonicalFile: true, phantomFile: true });+ expect({ canonicalFile: b.file(CANONICAL) === canonicalFile, phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === phantomFile })+ .toEqual({ canonicalFile: true, phantomFile: true });expect(await b.versionsHolding(CANONICAL, DB_EDIT)).toBeGreaterThan(0);expect(await b.live(PHANTOM)).toBe(false);+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });});}, 180_000);@@ -170,9 +171,9 @@ for (const { backend, databaseUrl } of pathologicalArms()) {await withBrain(databaseUrl, async b => {const versionsBefore = await b.versionsHolding(CANONICAL, 'works at acme-example');const result = await expectUnitNotAborted(() => b.pass());- expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });expect({ file: claims(b.file(CANONICAL)), db: claims(await b.body(CANONICAL)) }).toEqual({ file: [CLAIM], db: [CLAIM] });expect(await b.versionsHolding(CANONICAL, 'works at acme-example')).toBe(versionsBefore + 1);+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });expect({ phantomLive: await b.live(PHANTOM), phantomFile: existsSync(b.path(PHANTOM)) }).toEqual({ phantomLive: false, phantomFile: false });});}, 180_000);diff --git a/test/pathological/d6-phantom-file-unlink.test.ts b/test/pathological/d6-phantom-file-unlink.test.tsindex 2efe26993c..3feb00eb11 100644--- a/test/pathological/d6-phantom-file-unlink.test.ts+++ b/test/pathological/d6-phantom-file-unlink.test.ts@@ -130,10 +130,10 @@ for (const { backend, databaseUrl } of pathologicalArms()) {writeFileSync(b.path(PHANTOM), edited);const [canonicalFile, canonicalBody] = [b.file(CANONICAL), await b.body(CANONICAL)];const result = await expectUnitNotAborted(() => b.pass());+ expect({ phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === edited, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: true });const held = heldFor(result, PHANTOM);expect({ redirected: result.redirected, held: held.length, fix: held.some(h => h.includes('gbrain sync --source default')) }).toEqual({ redirected: 0, held: 1, fix: true });- expect({ phantomFile: b.file(PHANTOM) === edited, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: true });expect({ canonicalFile: b.file(CANONICAL) === canonicalFile, canonicalBody: (await b.body(CANONICAL)) === canonicalBody }).toEqual({ canonicalFile: true, canonicalBody: true });});@@ -144,8 +144,8 @@ for (const { backend, databaseUrl } of pathologicalArms()) {const edited = `---\naliases: [alice-ex]\n---\n${PHANTOM_BODY}`;writeFileSync(b.path(PHANTOM), edited);const result = await expectUnitNotAborted(() => b.pass());+ expect({ phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === edited, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: true });expect({ redirected: result.redirected, held: heldFor(result, PHANTOM).length }).toEqual({ redirected: 0, held: 1 });- expect({ phantomFile: b.file(PHANTOM) === edited, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: true });});}, 180_000);@@ -155,10 +155,10 @@ for (const { backend, databaseUrl } of pathologicalArms()) {_resetWriteThroughCacheForTest();const phantomFile = b.file(PHANTOM);const result = await expectUnitNotAborted(() => b.pass());- expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });expect({ phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === phantomFile, phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: true, phantomLive: false });expect(claims(await b.body(CANONICAL))).toEqual([CLAIM]);+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });});}, 180_000);@@ -169,17 +169,17 @@ for (const { backend, databaseUrl } of pathologicalArms()) {const racing = editsBeforePhantomDelete(b.engine, async () => { writeFileSync(b.path(PHANTOM), edited); landed = true; });const result = await expectUnitNotAborted(() => b.pass(racing));expect(landed).toBe(true);- expect({ redirected: result.redirected, held: heldFor(result, PHANTOM).length }).toEqual({ redirected: 1, held: 1 });expect({ phantomFile: existsSync(b.path(PHANTOM)) && b.file(PHANTOM) === edited }).toEqual({ phantomFile: true });+ expect({ redirected: result.redirected, held: heldFor(result, PHANTOM).length }).toEqual({ redirected: 1, held: 1 });});}, 180_000);test('D-6 agreeing copies: the phantom is redirected and its file is removed', async () => {await withBrain(databaseUrl, async b => {const result = await expectUnitNotAborted(() => b.pass());- expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });expect({ phantomFile: existsSync(b.path(PHANTOM)), phantomLive: await b.live(PHANTOM) }).toEqual({ phantomFile: false, phantomLive: false });expect({ file: claims(b.file(CANONICAL)), db: claims(await b.body(CANONICAL)) }).toEqual({ file: [CLAIM], db: [CLAIM] });+ expect({ redirected: result.redirected, held: result.held }).toEqual({ redirected: 1, held: [] });});}, 180_000);});diff --git a/test/pathological/d7-synthesize-reverse-write.test.ts b/test/pathological/d7-synthesize-reverse-write.test.tsnew file mode 100644index 0000000000..bdf0f8a700--- /dev/null+++ b/test/pathological/d7-synthesize-reverse-write.test.ts@@ -0,0 +1,22 @@+/**+ * D-7 (GBRA-131, #6982): the synthesize phase's reverse-write never replaces a+ * checkout file that holds an edit the database lacks.+ *+ * Protects: after the synthesize child wrote a page in the database, its markdown+ * file is written only when the file is absent or holds nothing the database+ * lacks (it equals the live page or one of its page_versions rows); otherwise+ * the file keeps its bytes and the phase reports the page with+ * `file_database_drift` and its fix. The write honors `sync.write_through` off+ * and `storage.db_only` (no file), lands in the page's recorded source_path,+ * and is bound to the bytes it compared, so an edit landing in between is kept.+ * Fails when: the reverse-write (synthesize.ts reverseWriteRefs) writes every page's file+ * unconditionally with writeFileSync at a slug-derived path, ignoring write-through, db_only and the recorded source_path.+ * Seams: an engine proxy that edits the file once the reverse-write has read the+ * page history it compares against. PGLite always, Postgres when DATABASE_URL+ * is set.+ */+import { __testing } from '../../src/core/cycle/synthesize.ts';+import { reverseWriteCases, type ReverseWrite } from './dream-reverse-write-fixture.ts';+import { pathologicalArms } from './harness.ts';++for (const arm of pathologicalArms()) reverseWriteCases('D-7', 'synthesize', __testing.reverseWriteRefs as ReverseWrite, arm);diff --git a/test/pathological/d8-patterns-reverse-write.test.ts b/test/pathological/d8-patterns-reverse-write.test.tsnew file mode 100644index 0000000000..82826a9dc7--- /dev/null+++ b/test/pathological/d8-patterns-reverse-write.test.ts@@ -0,0 +1,22 @@+/**+ * D-8 (GBRA-131, #6982): the patterns phase's reverse-write never replaces a+ * checkout file that holds an edit the database lacks.+ *+ * Protects: after the patterns child wrote a page in the database, its markdown+ * file is written only when the file is absent or holds nothing the database+ * lacks (it equals the live page or one of its page_versions rows); otherwise+ * the file keeps its bytes and the phase reports the page with+ * `file_database_drift` and its fix. The write honors `sync.write_through` off+ * and `storage.db_only` (no file), lands in the page's recorded source_path,+ * and is bound to the bytes it compared, so an edit landing in between is kept.+ * Fails when: the reverse-write (patterns.ts reverseWriteRefs) writes every page's file+ * unconditionally with writeFileSync at a slug-derived path, ignoring write-through, db_only and the recorded source_path.+ * Seams: an engine proxy that edits the file once the reverse-write has read the+ * page history it compares against. PGLite always, Postgres when DATABASE_URL+ * is set.+ */+import { __testing } from '../../src/core/cycle/patterns.ts';+import { reverseWriteCases, type ReverseWrite } from './dream-reverse-write-fixture.ts';+import { pathologicalArms } from './harness.ts';++for (const arm of pathologicalArms()) reverseWriteCases('D-8', 'patterns', __testing.reverseWriteRefs as ReverseWrite, arm);diff --git a/test/pathological/d9-dream-summary-overwrite.test.ts b/test/pathological/d9-dream-summary-overwrite.test.tsnew file mode 100644index 0000000000..4333e146d6--- /dev/null+++ b/test/pathological/d9-dream-summary-overwrite.test.ts@@ -0,0 +1,155 @@+/**+ * D-9 (GBRA-131, #6982): a repeat synthesize run on the same date never+ * replaces the dream summary page's database body or file without a trace.+ *+ * Protects: `writeSummaryPage` keeps the summary body it replaces in+ * page_versions (the raw putPage it uses keeps none), writes the summary file+ * only when the file holds nothing the database lacks (it equals the live page+ * or one of its page_versions rows) and returns the `file_database_drift` entry+ * otherwise, binds the write to the bytes it compared, and writes no file with+ * `sync.write_through` off.+ * Fails when: the summary is replaced with putPage and writeFileSync with no+ * comparison and no page_versions row (the pre-fix path), which drops a+ * database-only edit and an unimported file edit.+ * Seams: an engine proxy that edits the file once the write has read the page+ * history it compares against. PGLite always, Postgres when DATABASE_URL is set.+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { __testing } from '../../src/core/cycle/synthesize.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectUnitNotAborted, pathologicalArms } from './harness.ts';++const SOURCE = 'default';+const SUMMARY = 'dream-cycle-summaries/2026-10-18';+const DATE = '2026-10-18';+const FIRST = ['wiki/originals/ideas/alice-example-first'];+const SECOND = ['wiki/originals/ideas/alice-example-first', 'wiki/originals/ideas/acme-example-second'];+const DB_EDIT = 'DB-ONLY-EDIT-MARKER: a note added to the summary with write-through disabled.';+const FILE_EDIT = 'FILE-ONLY-EDIT-MARKER: a note saved in the editor, not yet synced.';+const LATE_EDIT = 'CONCURRENT-EDIT-MARKER: written while the summary was written.';++type SummaryWriter = (engine: BrainEngine, brainDir: string, slug: string, date: string, written: string[],+ children: Array<{ jobId: number; status: string }>, sourceId?: string) => Promise<string | undefined>;+const writeSummaryPage = (__testing as unknown as { writeSummaryPage: SummaryWriter }).writeSummaryPage;++interface Brain {+ engine: BrainEngine;+ path: string;+ file(): string;+ body(): Promise<string>;+ versionsHolding(marker: string): Promise<number>;+ run(slugs: string[], engine?: BrainEngine): Promise<string | undefined>;+}++async function withBrain(databaseUrl: string | undefined, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-d9-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(root, { recursive: true });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ const path = join(root, `${SUMMARY}.md`);+ const b: Brain = {+ engine, path,+ file: () => readFileSync(path, 'utf8'),+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>(+ 'SELECT compiled_truth FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, SUMMARY]))[0]!.compiled_truth,+ versionsHolding: async marker => Number((await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id = v.page_id+ WHERE p.source_id = $1 AND p.slug = $2 AND v.compiled_truth LIKE '%' || $3 || '%'`, [SOURCE, SUMMARY, marker]))[0]!.n),+ run: (slugs, on = engine) => writeSummaryPage(on, root, SUMMARY, DATE, slugs, [{ jobId: 1, status: 'completed' }], SOURCE),+ };+ await run(b);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/** The engine that runs `after` once the summary write has read the page history it compares the file with. */+function editsAfterComparison(engine: BrainEngine, after: () => void): BrainEngine {+ let fired = false;+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') return async (sql: string, ...rest: unknown[]) => {+ const rows = await (target.executeRaw as (...a: unknown[]) => Promise<unknown>).call(target, sql, ...rest);+ if (!fired && /UNION ALL[\s\S]*page_versions/.test(sql)) { fired = true; after(); }+ return rows;+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++const drift = (held: string | undefined) => held?.startsWith(`${SUMMARY} (file_database_drift`) === true;++for (const { backend, databaseUrl } of pathologicalArms()) {+ describe(`D-9 dream summary rewritten by a repeat run on the same date (${backend})`, () => {+ test('D-9 file-newer: an unimported summary file edit is kept and reported; the replaced database body is kept in page_versions', async () => {+ await withBrain(databaseUrl, async b => {+ await b.run(FIRST);+ const edited = b.file().replace('**Pages written:** 1.', `**Pages written:** 1.\n\n${FILE_EDIT}`);+ writeFileSync(b.path, edited);+ const held = await expectUnitNotAborted(() => b.run(SECOND));+ expect({ drift: drift(held), fix: held?.includes('gbrain sync --source default') }).toEqual({ drift: true, fix: true });+ expect({ file: b.file() === edited, body: (await b.body()).includes('acme-example-second') }).toEqual({ file: true, body: true });+ expect(await b.versionsHolding('**Pages written:** 1.')).toBeGreaterThan(0);+ });+ }, 180_000);++ test('D-9 db-newer: a database-only summary edit is kept in page_versions, and the file it never reached is not replaced blind', async () => {+ await withBrain(databaseUrl, async b => {+ await b.run(FIRST);+ const fileBefore = b.file();+ const page = (await b.engine.getPage(SUMMARY, { sourceId: SOURCE }))!;+ await b.engine.putPage(SUMMARY, { type: page.type, title: page.title, compiled_truth: `${page.compiled_truth}\n\n${DB_EDIT}\n`,+ timeline: page.timeline, frontmatter: page.frontmatter }, { sourceId: SOURCE });+ const held = await expectUnitNotAborted(() => b.run(SECOND));+ expect(await b.versionsHolding(DB_EDIT)).toBeGreaterThan(0);+ expect({ drift: drift(held), file: b.file() === fileBefore }).toEqual({ drift: true, file: true });+ });+ }, 180_000);++ test('D-9 write-through off: the database row is replaced (prior body versioned) and the file is not written', async () => {+ await withBrain(databaseUrl, async b => {+ await b.run(FIRST);+ const fileBefore = b.file();+ await b.engine.setConfig('sync.write_through', 'false');+ _resetWriteThroughCacheForTest();+ const held = await expectUnitNotAborted(() => b.run(SECOND));+ expect({ held, file: b.file() === fileBefore, body: (await b.body()).includes('acme-example-second') }).toEqual({ held: undefined, file: true, body: true });+ expect(await b.versionsHolding('**Pages written:** 1.')).toBeGreaterThan(0);+ });+ }, 180_000);++ test('D-9 concurrent file edit after the comparison: the editor\'s bytes survive and the summary file is reported', async () => {+ await withBrain(databaseUrl, async b => {+ await b.run(FIRST);+ const edited = `${b.file()}\n${LATE_EDIT}\n`;+ const held = await expectUnitNotAborted(() => b.run(SECOND, editsAfterComparison(b.engine, () => writeFileSync(b.path, edited))));+ expect({ drift: drift(held), file: b.file() === edited }).toEqual({ drift: true, file: true });+ });+ }, 180_000);++ test('D-9 control, agreeing copies: the repeat run rewrites the file and keeps the replaced body in page_versions', async () => {+ await withBrain(databaseUrl, async b => {+ await b.run(FIRST);+ const versionsBefore = await b.versionsHolding('**Pages written:** 1.');+ const held = await expectUnitNotAborted(() => b.run(SECOND));+ expect({ held, file: b.file().includes('acme-example-second') }).toEqual({ held: undefined, file: true });+ expect(await b.versionsHolding('**Pages written:** 1.')).toBe(versionsBefore + 1);+ });+ }, 180_000);+ });+}diff --git a/test/pathological/dream-reverse-write-fixture.ts b/test/pathological/dream-reverse-write-fixture.tsnew file mode 100644index 0000000000..67083c3e43--- /dev/null+++ b/test/pathological/dream-reverse-write-fixture.ts@@ -0,0 +1,167 @@+/**+ * Shared fixture for the dream reverse-write probes (GBRA-131 D-7 synthesize, D-8 patterns, #6982): a brain whose+ * source checkout is a temp directory, one dream output page imported twice (the second import is the child's write,+ * which keeps the first in page_versions), and the reverse-write under test run against it.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { serializePageToMarkdown } from '../../src/core/markdown.ts';+import { managedPersistenceEnabled } from '../../src/core/persistence/ownership.ts';+import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';+import { withEnv } from '../helpers/with-env.ts';+import { expectUnitNotAborted } from './harness.ts';++export type ReverseWrite = (engine: BrainEngine, brainDir: string, refs: Array<{ slug: string; source_id: string }>,+ nativeSourceId?: string, signal?: AbortSignal, held?: string[]) => Promise<number>;++const SOURCE = 'default';+export const DREAM_SLUG = 'wiki/originals/ideas/alice-example-idea';+const V1 = 'FIRST-RUN-MARKER: Alice Example prefers small launches.';+const V2 = 'CHILD-WRITE-MARKER: Alice Example now ships weekly at acme-example.';+const FILE_EDIT = 'FILE-ONLY-EDIT-MARKER: a paragraph saved in the editor, not yet synced.';+const LATE_EDIT = 'CONCURRENT-EDIT-MARKER: written while the reverse-write ran.';+const page = (body: string) => `---\ntype: note\ntitle: Alice Example idea\n---\n# Alice Example idea\n\n${body}\n`;++interface Brain {+ engine: BrainEngine;+ root: string;+ file(path?: string): string;+ path: string;+ body(): Promise<string>;+ /** The first run's file: the page as it was before the child's write. */+ writeFirstRunFile(extra?: string): string;+ run(engine?: BrainEngine): Promise<{ written: number; held: string[] }>;+}++async function withBrain(databaseUrl: string | undefined, reverseWrite: ReverseWrite, run: (b: Brain) => Promise<void>): Promise<void> {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-dream-rw-'));+ try {+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {+ _resetWriteThroughCacheForTest();+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);+ try {+ expect(await managedPersistenceEnabled(engine)).toBe(false);+ const root = join(home, 'brain');+ mkdirSync(root, { recursive: true });+ await engine.executeRaw("UPDATE sources SET local_path = $1 WHERE id = 'default'", [root]);+ await importFromContent(engine, DREAM_SLUG, page(V1), { noEmbed: true, sourceId: SOURCE });+ const first = (await engine.readPageSnapshot(DREAM_SLUG, { sourceId: SOURCE }))!;+ const firstRunFile = serializePageToMarkdown(first.page, first.tags);+ await importFromContent(engine, DREAM_SLUG, page(`${V1}\n\n${V2}`), { noEmbed: true, sourceId: SOURCE });+ const path = join(root, `${DREAM_SLUG}.md`);+ const b: Brain = {+ engine, root, path,+ file: (p = path) => readFileSync(p, 'utf8'),+ body: async () => (await engine.executeRaw<{ compiled_truth: string }>(+ 'SELECT compiled_truth FROM pages WHERE source_id = $1 AND slug = $2', [SOURCE, DREAM_SLUG]))[0]!.compiled_truth,+ writeFirstRunFile(extra) {+ const bytes = extra ? firstRunFile.replace(V1, `${V1}\n\n${extra}`) : firstRunFile;+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, bytes);+ return bytes;+ },+ async run(on = engine) {+ const held: string[] = [];+ const written = await reverseWrite(on, root, [{ slug: DREAM_SLUG, source_id: SOURCE }], SOURCE, undefined, held);+ return { written, held };+ },+ };+ await run(b);+ } finally { await close(); }+ });+ } finally { rmSync(home, { recursive: true, force: true }); }+}++/** The engine that runs `after` once the reverse-write has read the page history it compares the file with. */+function editsAfterComparison(engine: BrainEngine, after: () => void): BrainEngine {+ let fired = false;+ return new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') return async (sql: string, ...rest: unknown[]) => {+ const rows = await (target.executeRaw as (...a: unknown[]) => Promise<unknown>).call(target, sql, ...rest);+ if (!fired && /UNION ALL[\s\S]*page_versions/.test(sql)) { fired = true; after(); }+ return rows;+ };+ const value = Reflect.get(target, prop, target);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+}++const heldFor = (held: string[]) => held.filter(h => h.startsWith(`${DREAM_SLUG} (file_database_drift`));++/** The reverse-write cases every dream phase's writer must pass, on one engine arm (from `pathologicalArms()`). */+export function reverseWriteCases(id: string, phase: string, reverseWrite: ReverseWrite, { backend, databaseUrl }: { backend: string; databaseUrl: string | undefined }): void {+ describe(`${id} ${phase} reverse-write and a file that differs from the database (${backend})`, () => {+ test(`${id} file-newer: an unimported file edit is kept, the page is held with file_database_drift and the database is untouched`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ const edited = b.writeFirstRunFile(FILE_EDIT);+ const bodyBefore = await b.body();+ const result = await expectUnitNotAborted(() => b.run());+ const held = heldFor(result.held);+ expect({ written: result.written, held: held.length, fix: held.some(h => h.includes('gbrain sync --source default')) })+ .toEqual({ written: 0, held: 1, fix: true });+ expect({ file: b.file() === edited, body: (await b.body()) === bodyBefore }).toEqual({ file: true, body: true });+ });+ }, 180_000);++ test(`${id} db-newer: a file the child's write replaced (kept in page_versions) is rewritten with the new body`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ b.writeFirstRunFile();+ const result = await expectUnitNotAborted(() => b.run());+ expect({ written: result.written, held: result.held }).toEqual({ written: 1, held: [] });+ expect({ v1: b.file().includes(V1), v2: b.file().includes(V2) }).toEqual({ v1: true, v2: true });+ });+ }, 180_000);++ test(`${id} write-through off: no file is written or replaced`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ await b.engine.setConfig('sync.write_through', 'false');+ _resetWriteThroughCacheForTest();+ const before = b.writeFirstRunFile();+ const result = await expectUnitNotAborted(() => b.run());+ expect({ written: result.written, held: result.held, file: b.file() === before }).toEqual({ written: 0, held: [], file: true });+ });+ }, 180_000);++ test(`${id} storage.db_only: a page in a db_only directory gets no file`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ writeFileSync(join(b.root, 'gbrain.yml'), 'storage:\n db_only:\n - wiki/originals\n');+ const result = await expectUnitNotAborted(() => b.run());+ expect({ written: result.written, file: existsSync(b.path) }).toEqual({ written: 0, file: false });+ });+ }, 180_000);++ test(`${id} recorded source_path: the file of record is written and no slug-named twin appears`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ await b.engine.executeRaw('UPDATE pages SET source_path = $1 WHERE source_id = $2 AND slug = $3', ['Ideas/Alice Example idea.md', SOURCE, DREAM_SLUG]);+ const recorded = join(b.root, 'Ideas/Alice Example idea.md');+ const result = await expectUnitNotAborted(() => b.run());+ expect({ written: result.written, recorded: existsSync(recorded) && b.file(recorded).includes(V2), twin: existsSync(b.path) })+ .toEqual({ written: 1, recorded: true, twin: false });+ });+ }, 180_000);++ test(`${id} concurrent file edit after the comparison: the editor's bytes survive and the page is held`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ b.writeFirstRunFile();+ const edited = `${b.file()}\n${LATE_EDIT}\n`;+ const racing = editsAfterComparison(b.engine, () => writeFileSync(b.path, edited));+ const result = await expectUnitNotAborted(() => b.run(racing));+ expect({ written: result.written, held: heldFor(result.held).length, file: b.file() === edited }).toEqual({ written: 0, held: 1, file: true });+ });+ }, 180_000);++ test(`${id} control, no file yet: the page's file is written`, async () => {+ await withBrain(databaseUrl, reverseWrite, async b => {+ const result = await expectUnitNotAborted(() => b.run());+ expect({ written: result.written, held: result.held, v2: existsSync(b.path) && b.file().includes(V2) }).toEqual({ written: 1, held: [], v2: true });+ });+ }, 180_000);+ });+}diff --git a/test/phantom-redirect.test.ts b/test/phantom-redirect.test.tsindex c873f790a5..f6ef164453 100644--- a/test/phantom-redirect.test.ts+++ b/test/phantom-redirect.test.ts@@ -12,6 +12,7 @@ import * as os from 'node:os';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { resetPgliteState } from './helpers/reset-pglite.ts';import { withEnv } from './helpers/with-env.ts';+import { parseMarkdown } from '../src/core/markdown.ts';import { runExtractFacts } from '../src/core/cycle/extract-facts.ts';import {runPhantomRedirectPass,@@ -248,7 +249,7 @@ describe('tryRedirectPhantom (single phantom orchestration)', () => {);await putPage('alice', phantomBody);writeMd(brainDir, 'alice', phantomBody);- writeMd(brainDir, 'people/alice-example', '# alice-example\n');+ writeMd(brainDir, 'people/alice-example', '# alice-example\n\n## Facts\n\n');const phantom = await engine.getPage('alice', { sourceId: 'default' });expect(phantom).not.toBeNull();@@ -795,7 +796,8 @@ describe('tryRedirectPhantom — fence placement above the timeline sentinel (#4// to reconcile a fence (FACTS_FENCE_BELOW_SENTINEL) — a blind EOF// append froze the redirected rows permanently.const canonicalBody = `# alice-example\n\nAlice runs acme-example.\n\n---\n\n## Timeline\n\n- 2026-01-01: Founded Acme\n`;- await putPage('people/alice-example', canonicalBody, { type: 'person' });+ const split = parseMarkdown(canonicalBody, 'people/alice-example.md');+ await engine.putPage('people/alice-example', { title: 'people/alice-example', type: 'person' as never, compiled_truth: split.compiled_truth, timeline: split.timeline, frontmatter: {} });writeMd(brainDir, 'people/alice-example', canonicalBody);const phantomBody = FACT_FENCE(diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex ed4254c19a..6fc29460ea 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -281,6 +281,11 @@ test/pathological/d22-legacy-hash-body-history.test.tstest/pathological/d23-extract-atoms-db-only.test.tstest/pathological/d3-forget-overwrite.test.tstest/pathological/d4-proposal-overwrite.test.ts+test/pathological/d5-phantom-canonical-overwrite.test.ts+test/pathological/d6-phantom-file-unlink.test.ts+test/pathological/d7-synthesize-reverse-write.test.ts+test/pathological/d8-patterns-reverse-write.test.ts+test/pathological/d9-dream-summary-overwrite.test.tstest/persistence-background-pause.test.tstest/persistence-bounded-read-session.test.tstest/persistence-capacity-forecast.test.tsdiff --git a/test/regression-strict-source-id.test.ts b/test/regression-strict-source-id.test.tsindex cc0135d04a..ef55963514 100644--- a/test/regression-strict-source-id.test.ts+++ b/test/regression-strict-source-id.test.ts@@ -40,6 +40,8 @@ const pageEngine = {slug, type: 'note', title: slug, compiled_truth: 'body', timeline: '', frontmatter: {},}),getTags: async () => [],+ getConfig: async () => null,+ executeRaw: async () => [],} as unknown as BrainEngine;describe('strict-regex blast radius — patterns.ts + synthesize.ts (codex r2 P1-D)', () => {