Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): patterns grounding and the child read budget handle segmented pages (#6302, #6297, #6787)

garrytan022d009fb836
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index c41c609a9e..63601eaec8 100644
--- a/docs/architecture/key-files/core-cycle-continued.md
+++ b/docs/architecture/key-files/core-cycle-continued.md
@@ -6,7 +6,7 @@ Synthesis, patterns, consolidation and connector atom gating.
- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. `loadCommittedSynthesisOutputs` finds each child's committed output by canonicalizing the retained `brain_put_page` input (`parseWriteRequestId` for the request id, `journaledPageSlug` for the slug) before matching request id, source, incarnation, committed put_page, slug and revision (#6616); slug discovery (`collectChildPutPageSlugs`) and postprocessing share that set. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`. #5575 I2: each output publishes with `derivation` from its transcript (`dream-taint.ts` `transcriptDerivation`; `meetingTranscriptsDir` in opts); a retained request replays the declaration it was admitted with. #6360: when the page moved after the child commit, a drift made only by committed local `managed_maintenance_page` requests (for example the next cycle's lint `created:` fix) over a body equal to the child's is adopted: the postprocess runs on the current snapshot under a request id that also binds that base revision (found again on replay among the later requests). Any other later write leaves the page alone as a `PostprocessConflict` (`withPostprocessConflicts`: phase `warn`, `details.postprocess_conflicts` with the read-only `gbrain get` fix); it is reported once (config `dream.synthesize.postprocess_conflicts`, 30-day memory) and does not block the cooldown stamp.
-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #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. Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts`. #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`.
+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #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`.
- `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`). Pinned by `test/trust-taint-dream.test.ts` and `test/consolidate-divergence.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 570ae78750..fb48218374 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `awaitCommittedToolWrite(job, toolName, dispatch)` wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through `replayWhilePending` (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than `WIRE_WRITE_WAIT_MAX_MS` plus `WRITE_ADMISSION_HEADROOM_MS` (45 s); a job without a deadline replays for the `MaintenanceWriteWait` base (30 s). Only then does the write leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-handler.test.ts`, `test/minions/subagent-pending-write-runners.test.ts`, `test/minions/subagent-oneshot.test.ts` and `test/e2e/subagent-gateway-resume-reconciliation.test.ts`.
- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list in the handler-free `brain-tool-allowlist.ts`, which `src/mcp/surface.ts` reads, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagent `get_page` with `include_content: true` is forced to `content_only: true`, so the body arrives once (as `content`) instead of also as parsed `compiled_truth`/`timeline`. `BuildBrainToolsOpts.readBudgetBytes` (from trusted `SubagentHandlerData.read_budget_bytes`) routes `get_page` results through `read-budget.ts`.
-- `src/core/minions/tools/read-budget.ts` — #6297 per-job `get_page` byte budget: `budgetedPageRead` counts bytes already returned from the job's `subagent_tool_executions` rows (`brain_get_page`, `complete`), so a replayed job keeps its spend, and past the budget returns a summary (`truncated: true`, `code: read_budget_exhausted`, slug/title/type, an excerpt of at most `READ_BUDGET_EXCERPT_CHARS`) instead of the page.
+- `src/core/minions/tools/read-budget.ts` — #6297 per-job `get_page` byte budget: `budgetedPageRead` counts bytes already returned from the job's `subagent_tool_executions` rows (`brain_get_page`, `complete`), so a replayed job keeps its spend, and past the budget returns a summary (`truncated: true`, `code: read_budget_exhausted`, slug/title/type, a bounded prefix of the result's rendered `content`/`text` of at most `READ_BUDGET_EXCERPT_BYTES`; sizes are result bytes, never a body read, so segmented pages need no body string) instead of the page.
- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `(message_idx, tool_use_id)` — raw provider tool ids may repeat across turns, so `tool_use_id` alone is not an identity; echoed `tool_result` blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.
diff --git a/docs/guides/dream-patterns.md b/docs/guides/dream-patterns.md
index 18b2910b83..cd101df465 100644
--- a/docs/guides/dream-patterns.md
+++ b/docs/guides/dream-patterns.md
@@ -37,6 +37,13 @@ those pages as written:
rewritten page. Everything else on the page, including quotes an earlier
run verified against older reflections, stays as it is.
- The page gets the dream provenance stamp and counts in `patterns_written`.
+- Segmented pages (bodies stored in segments) work too. A segmented reflection
+ is read back through the segment reader, so its quotes still ground, and a
+ segmented pattern page is read back as text, checked and rewritten. A page
+ over the single-string ceiling (24 MiB) is skipped instead: a reflection
+ that large is not checked against, and a pattern page that large keeps its
+ appended entries unchecked, counted in
+ `quote_verify.timeline_appends.segmented_skipped` and logged.
`timeline_appends` counts the new entries, and `quote_verify.timeline_appends`
reports how many were checked, quarantined and repaired.
@@ -80,9 +87,12 @@ The child's `get_page` output is budgeted at
are counted from the job's own tool-execution ledger, so a resumed job keeps
what it already spent. Past the budget a read returns a short summary
(`truncated: true`, `code: read_budget_exhausted`, the slug, title, type and an
-excerpt of up to 400 characters) instead of the page. Writes still work, and
+excerpt of up to 400 bytes of the rendered page) instead of the page. Writes still work, and
the summary tells the child to append with `add_timeline_entry` instead of
-rewriting a page it has not read in full.
+rewriting a page it has not read in full. Reads are sized by the bytes of the
+result, never by reading the body, so a segmented page is sized like any
+other read. Its summary also names the stored `body_bytes` when the result
+carries them (`get_page` with `body: 'none'`).
## Budget sizing
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index d300b51f40..e017af45e6 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -134,7 +134,10 @@ src/core/cycle/patterns.ts gatherReflections field LEAD bounded prefix row
src/core/cycle/patterns.ts gatherReflections sql LEAD boundedBodyPrefixSql, truncated to a 600-byte excerpt
src/core/cycle/patterns.ts groundPatternPages call:serializePageToMarkdown SEGW
src/core/cycle/patterns.ts groundPatternPages field LEAD
-src/core/cycle/patterns.ts groundPatternPages sql LEAD
+src/core/cycle/patterns.ts groundTimelineAppends call:serializePageToMarkdown SEGW rewrite of a page read back by materializedSnapshot; the import or maintenance publish stores it by body policy; pages over the single-string ceiling are skipped before this
+src/core/cycle/patterns.ts groundTimelineAppends field STREAM materializedSnapshot reads a segmented page within the single-string ceiling back as strings; over it the page is skipped (timeline_appends.segmented_skipped, logged)
+src/core/cycle/patterns.ts loadGroundingSources field STREAM segmented reflection read through materializeSegmentedBody within PAGE_MAX_BYTES; over it not a grounding source (logged), so its quotes go to unverified_claims
+src/core/cycle/patterns.ts loadGroundingSources sql STREAM inline body columns plus body_storage/body_bytes; a segmented row's NULL columns are replaced by the segment reader
src/core/cycle/patterns.ts renderPageToMarkdown call:serializeMarkdown SEGW
src/core/cycle/patterns.ts renderPageToMarkdown field LEAD
src/core/cycle/phantom-redirect-managed.ts redirectManagedPhantom call:serializePageToMarkdown SEGW spread of a segmented page throws
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index b08d019fae..9ebced1607 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -33,6 +33,7 @@ import { waitForCompletionRenewing, TimeoutError } from '../minions/wait-for-com
import type { MinionJobInput, MinionJobStatus, SubagentHandlerData } from '../minions/types.ts';
import { serializeMarkdown } from '../markdown.ts';
import { truncateUtf8 } from '../text-safe.ts';
+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
import type { Page, PageType } from '../types.ts';
// #2415: allow-list + output-root resolution shared with the synthesize
// phase — both phases must agree on the configured namespace.
@@ -768,13 +769,29 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: Maint
return stats;
}
-/** The full reflection pages a run read, grounded for quote verification. */
+/**
+ * The full reflection pages a run read, grounded for quote verification. A segmented reflection is read back
+ * through the segment reader (its body columns are NULL); one over the single-string ceiling is not a grounding
+ * source, so a quote only it holds goes to unverified_claims, and the skip is logged.
+ */
async function loadGroundingSources<T>(engine: BrainEngine, sourceId: string, reflections: ReflectionRef[],
groundSource: (path: string, content: string, opts: { tolerant: boolean }) => T): Promise<T[]> {
- const sourcePages = await engine.executeRaw<{ slug: string; compiled_truth: string; timeline: string }>(
- 'SELECT slug, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL',
+ const sourcePages = await engine.executeRaw<{ id: number; slug: string; body_storage: string | null; body_bytes: number | string | null; compiled_truth: string | null; timeline: string | null }>(
+ 'SELECT id, slug, body_storage, body_bytes, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL',
[sourceId, reflections.map(r => r.slug)]);
- return sourcePages.map(p => groundSource(p.slug, `${p.compiled_truth}\n\n${p.timeline ?? ''}`, { tolerant: true }));
+ const sources: T[] = [];
+ for (const p of sourcePages) {
+ let body = { compiled_truth: p.compiled_truth ?? '', timeline: p.timeline ?? '' };
+ if (p.body_storage === 'segmented') {
+ if (Number(p.body_bytes ?? 0) > PAGE_MAX_BYTES) {
+ process.stderr.write(`[dream] patterns quote verify: reflection ${p.slug} is a segmented page over ${PAGE_MAX_BYTES} bytes; it is not a grounding source.\n`);
+ continue;
+ }
+ body = await (await import('../page-body/ingest.ts')).materializeSegmentedBody(engine, Number(p.id), sourceId);
+ }
+ sources.push(groundSource(p.slug, `${body.compiled_truth}\n\n${body.timeline}`, { tolerant: true }));
+ }
+ return sources;
}
/** Write a grounded page back at its read revision: a managed maintenance publish (held when pending or contended), else an import. */
@@ -813,17 +830,24 @@ async function writeGroundedPage(engine: BrainEngine, maintenance: MaintenanceAu
*/
export async function groundTimelineAppends(engine: BrainEngine, maintenance: MaintenanceAuthority | null, appends: TimelineAppend[],
reflections: ReflectionRef[], sourceId: string, cycleDate: string, signal?: AbortSignal, heldSlugs?: Set<string>,
- derivation?: Derivation & { declaration: DerivationDeclaration }): Promise<{ entries: number; quarantined: number; repaired: number } | null> {
+ derivation?: Derivation & { declaration: DerivationDeclaration }): Promise<{ entries: number; quarantined: number; repaired: number; segmented_skipped: number } | null> {
const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');
if (!await dreamQuoteVerifyEnabled(engine)) return null;
- const stats = { entries: 0, quarantined: 0, repaired: 0 };
+ const stats = { entries: 0, quarantined: 0, repaired: 0, segmented_skipped: 0 };
if (appends.length === 0) return stats;
const sources = await loadGroundingSources(engine, sourceId, reflections, groundSource);
const { serializePageToMarkdown } = await import('../markdown.ts');
+ const [{ materializedSnapshot }, { bodyUnread }] = await Promise.all([import('../persistence/segmented-apply.ts'), import('../page-body/page-shape.ts')]);
for (const slug of [...new Set(appends.map(a => a.slug))]) {
throwIfAborted(signal, '[dream] patterns timeline quote verify');
- const snapshot = await engine.readPageSnapshot(slug, { sourceId });
+ // A segmented page within the single-string ceiling is read back as strings; over it, its appends stay as written (counted, logged).
+ const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(slug, { sourceId }));
if (!snapshot) continue;
+ if (bodyUnread(snapshot.page)) {
+ stats.segmented_skipped++;
+ process.stderr.write(`[dream] patterns quote verify: ${slug} is a segmented page over the single-string ceiling; its timeline appends were not verified.\n`);
+ continue;
+ }
let timeline = snapshot.page.timeline ?? '';
const quarantined: Array<Record<string, unknown>> = [];
const removed: TimelineAppend['entry'][] = [];
diff --git a/src/core/minions/tools/read-budget.ts b/src/core/minions/tools/read-budget.ts
index 4cb506e5cf..444bdf9bdf 100644
--- a/src/core/minions/tools/read-budget.ts
+++ b/src/core/minions/tools/read-budget.ts
@@ -5,11 +5,18 @@
* window. Bytes already returned are counted from the job's own
* tool-execution ledger (so a crash replay keeps its spent budget); a read
* that would pass the budget comes back as a short summary instead.
+ *
+ * Sizes are the bytes of the returned result, never a page body read here, so
+ * a segmented page (no body string) is sized like any other read; the summary
+ * names its stored `size.body_bytes` when the result carries it. The excerpt
+ * is a bounded prefix of the rendered `content` (or a window's `text`) the
+ * result already holds.
*/
import type { BrainEngine } from '../../engine.ts';
+import { boundedRawPrefix } from '../../page-window/bounded-lead.ts';
-/** Characters of body text a summary keeps, at most (less when the budget has less left). */
-export const READ_BUDGET_EXCERPT_CHARS = 400;
+/** UTF-8 bytes of rendered text a summary keeps, at most (less when the budget has less left). */
+export const READ_BUDGET_EXCERPT_BYTES = 400;
/** Bytes of `get_page` output this job has already been given. */
async function spentReadBytes(engine: BrainEngine, jobId: number): Promise<number> {
@@ -25,16 +32,17 @@ export async function budgetedPageRead(engine: BrainEngine, jobId: number, budge
const pageBytes = Buffer.byteLength(JSON.stringify(output) ?? '', 'utf8');
if (used + pageBytes <= budgetBytes) return output;
const page = (output && typeof output === 'object' ? output : {}) as Record<string, unknown>;
- const body = typeof page.compiled_truth === 'string' ? page.compiled_truth : typeof page.content === 'string' ? page.content : '';
- const room = Math.max(0, Math.min(READ_BUDGET_EXCERPT_CHARS, budgetBytes - used));
+ const rendered = typeof page.content === 'string' ? page.content : typeof page.text === 'string' ? page.text : '';
+ const excerpt = boundedRawPrefix(rendered, Math.max(0, Math.min(READ_BUDGET_EXCERPT_BYTES, budgetBytes - used)));
+ const bodyBytes = (page.size as { body_bytes?: unknown } | undefined)?.body_bytes;
return {
slug: typeof page.slug === 'string' ? page.slug : slug,
...(typeof page.title === 'string' ? { title: page.title } : {}),
...(typeof page.type === 'string' ? { type: page.type } : {}),
truncated: true,
code: 'read_budget_exhausted',
- read_budget: { limit_bytes: budgetBytes, used_bytes: used, page_bytes: pageBytes },
- ...(room > 0 && body ? { excerpt: body.slice(0, room) } : {}),
+ read_budget: { limit_bytes: budgetBytes, used_bytes: used, page_bytes: pageBytes, ...(typeof bodyBytes === 'number' ? { body_bytes: bodyBytes } : {}) },
+ ...(excerpt ? { excerpt } : {}),
note: 'This job has used its get_page read budget, so the page is summarized. Work from the pages already read; writes still work. To update this page, append with add_timeline_entry instead of rewriting it.',
};
}
diff --git a/test/cycle-patterns-segmented.test.ts b/test/cycle-patterns-segmented.test.ts
new file mode 100644
index 0000000000..eccd3ef24c
--- /dev/null
+++ b/test/cycle-patterns-segmented.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Lane 3 code on segmented page storage (#6787): a segmented page keeps its
+ * body in segments, so its body columns are NULL and its page object's body
+ * fields throw `page_body_segmented`.
+ *
+ * - Patterns quote verification (#6302) reads a segmented reflection through
+ * the segment reader, so its quotes still ground; one over the
+ * single-string ceiling is not a grounding source.
+ * - A segmented pattern page with appended entries is read back as strings,
+ * verified and rewritten; over the ceiling it is skipped
+ * (`segmented_skipped`) and left as written.
+ * - The child read budget (#6297) sizes a read from its result, never the
+ * body, and names a segmented page's stored `body_bytes`.
+ *
+ * Runs on PGLite, and on Postgres with a safe DATABASE_URL
+ * (test/e2e/cycle-patterns-segmented-postgres.test.ts).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { groundTimelineAppends, type TimelineAppend } from '../src/core/cycle/patterns.ts';
+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';
+import { budgetedPageRead } from '../src/core/minions/tools/read-budget.ts';
+import { PAGE_MAX_BYTES } from '../src/core/page-size-policy.ts';
+import { createSegmentedPage } from './helpers/segmented-page.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const STAGING = '- **2026-10-10** | wiki/personal/reflections/r1 — You wrote "always test on staging" again';
+const DIARY = '- **2026-10-11** | wiki/personal/reflections/r2 — You keep a "weekly launch diary"';
+
+const append = (slug: string, block: string): TimelineAppend => ({ slug, requestId: randomUUID(), block, marker: '<!-- none -->',
+ entry: { date: block.slice(4, 14), source: block.split(' | ')[1]!.split(' — ')[0]!, summary: block.split(' — ')[1]! } });
+
+for (const kind of testBackends()) {
+ describe(`patterns grounding and read budget on segmented pages (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let n = 0;
+ /** Fresh slugs per test: reflections r1 (inline, no diary quote) and r2 (segmented, holds it). */
+ const fixture = async () => {
+ n++;
+ const r1 = `wiki/personal/reflections/t${n}-r1`;
+ const r2 = `wiki/personal/reflections/t${n}-r2`;
+ await importFromContent(engine, r1, '---\ntype: note\ntitle: r1\n---\nShipping went fine.\n', { noEmbed: true, sourceId: 'default' });
+ const segmented = await createSegmentedPage(engine, { slug: r2, truth: 'Mondays I update my "weekly launch diary".\n' });
+ return { r1, r2, reflections: [{ slug: r1 }, { slug: r2 }] as never, segmentedId: segmented.id,
+ staging: STAGING.replace('reflections/r1', `reflections/t${n}-r1`), diary: DIARY.replace('reflections/r2', `reflections/t${n}-r2`) };
+ };
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ await engine.setConfig('dream.quote_verify', 'true');
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('a segmented reflection grounds a quote through the segment reader', async () => {
+ const f = await fixture();
+ const slug = `wiki/personal/patterns/t${n}-diary`;
+ await importFromContent(engine, slug, `---\ntype: note\ntitle: Diary\ndream_generated: true\n---\nA diary theme.\n\n## Timeline\n\n${f.diary}\n`, { noEmbed: true, sourceId: 'default' });
+ const stats = await groundTimelineAppends(engine, null, [append(slug, f.diary)], f.reflections, 'default', '2026-10-15');
+ expect(stats).toEqual({ entries: 1, quarantined: 0, repaired: 0, segmented_skipped: 0 });
+ expect((await engine.getPage(slug))!.timeline).toContain('weekly launch diary');
+ });
+
+ test('a segmented reflection over the single-string ceiling is not a grounding source', async () => {
+ const f = await fixture();
+ await engine.executeRaw('UPDATE pages SET body_bytes = $2 WHERE id = $1', [f.segmentedId, PAGE_MAX_BYTES + 1]);
+ const slug = `wiki/personal/patterns/t${n}-diary`;
+ await importFromContent(engine, slug, `---\ntype: note\ntitle: Diary\ndream_generated: true\n---\nA diary theme.\n\n## Timeline\n\n${f.diary}\n`, { noEmbed: true, sourceId: 'default' });
+ const stats = await groundTimelineAppends(engine, null, [append(slug, f.diary)], f.reflections, 'default', '2026-10-15');
+ expect(stats).toEqual({ entries: 1, quarantined: 1, repaired: 0, segmented_skipped: 0 });
+ expect((await engine.getPage(slug))!.timeline).not.toContain('weekly launch diary');
+ });
+
+ test('an appended segmented pattern page is read back as strings, verified and rewritten', async () => {
+ const f = await fixture();
+ const slug = `wiki/personal/patterns/t${n}-segmented`;
+ await createSegmentedPage(engine, { slug, truth: 'A theme stored in segments.\n', timeline: `${f.staging}\n${f.diary}\n`,
+ meta: { type: 'note', title: 'Segmented theme', frontmatter: { dream_generated: true } } });
+ const stats = await groundTimelineAppends(engine, null, [append(slug, f.staging), append(slug, f.diary)], f.reflections, 'default', '2026-10-15');
+ expect(stats).toEqual({ entries: 2, quarantined: 1, repaired: 0, segmented_skipped: 0 });
+ const page = (await engine.getPage(slug))!;
+ expect(page.timeline).not.toContain('always test on staging');
+ expect(page.timeline).toContain('weekly launch diary');
+ expect((page.frontmatter.unverified_claims as Array<{ text: string }>)[0]!.text).toContain('always test on staging');
+ });
+
+ test('a segmented pattern page over the ceiling is skipped and left as written', async () => {
+ const f = await fixture();
+ const slug = `wiki/personal/patterns/t${n}-huge`;
+ const { id } = await createSegmentedPage(engine, { slug, truth: 'A huge theme.\n', timeline: `${f.staging}\n` });
+ await engine.executeRaw('UPDATE pages SET body_bytes = $2 WHERE id = $1', [id, PAGE_MAX_BYTES + 1]);
+ const stats = await groundTimelineAppends(engine, null, [append(slug, f.staging)], f.reflections, 'default', '2026-10-15');
+ expect(stats).toEqual({ entries: 0, quarantined: 0, repaired: 0, segmented_skipped: 1 });
+ const [row] = await engine.executeRaw<{ body_storage: string; frontmatter: Record<string, unknown> | string }>('SELECT body_storage, frontmatter FROM pages WHERE id = $1', [id]);
+ expect(row!.body_storage).toBe('segmented');
+ const fm = typeof row!.frontmatter === 'string' ? JSON.parse(row!.frontmatter) : row!.frontmatter;
+ expect(fm.unverified_claims).toBeUndefined();
+ });
+
+ test('the read budget sizes a segmented page from its result and names its stored body_bytes', async () => {
+ const slug = `wiki/personal/patterns/t${++n}-read`;
+ const { id } = await createSegmentedPage(engine, { slug, truth: 'A theme stored in segments.\n'.repeat(50) });
+ const [row] = await engine.executeRaw<{ body_bytes: number | string }>('SELECT body_bytes FROM pages WHERE id = $1', [id]);
+ const tools = buildBrainTools({ subagentId: 999, engine, config: { engine: engine.kind } as GBrainConfig,
+ allowedSlugPrefixes: ['wiki/personal/patterns/*'], sourceId: 'default', readBudgetBytes: 64 });
+ const out = await tools.find(t => t.name === 'brain_get_page')!.execute({ slug, body: 'none' }, { engine, jobId: 999, remote: true }) as Record<string, any>;
+ expect(out).toMatchObject({ truncated: true, code: 'read_budget_exhausted', slug });
+ expect(out.read_budget.body_bytes).toBe(Number(row!.body_bytes));
+ expect(out.excerpt).toBeUndefined();
+ });
+
+ test('the read-budget excerpt is a bounded prefix of the rendered content, cut on a code point', async () => {
+ const out = await budgetedPageRead(engine, 998, 300, 'wiki/personal/patterns/x', { slug: 'wiki/personal/patterns/x', content: '思'.repeat(1000) }) as Record<string, any>;
+ expect(out.truncated).toBe(true);
+ expect(Buffer.byteLength(out.excerpt, 'utf8')).toBeLessThanOrEqual(300);
+ expect(out.excerpt).toMatch(/^思+$/);
+ });
+ });
+}
diff --git a/test/cycle-patterns-timeline-appends.serial.test.ts b/test/cycle-patterns-timeline-appends.serial.test.ts
index ab67a11209..6eeb60150f 100644
--- a/test/cycle-patterns-timeline-appends.serial.test.ts
+++ b/test/cycle-patterns-timeline-appends.serial.test.ts
@@ -17,6 +17,7 @@ import { importFromContent } from '../src/core/import-file.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import type { GBrainConfig } from '../src/core/config.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { createSegmentedPage } from './helpers/segmented-page.ts';
const PATTERN = 'wiki/personal/patterns/small-pieces';
const REPLAYED = '0b6a3f52-7d1e-4c8a-9f10-2a6b5c4d3e21';
@@ -140,3 +141,17 @@ describe('patterns timeline appends are quote-verified and counted (#6302)', ()
expect(result.details.quote_verify).toMatchObject({ timeline_appends: { entries: 1, quarantined: 0, repaired: 0 } });
});
});
+
+describe('segmented reflections in an in-cycle patterns run (#6302 on segmented storage; direct cases on both engines in cycle-patterns-segmented.test.ts)', () => {
+ test('a segmented reflection still grounds a quote: the segment reader supplies its body', async () => {
+ await createSegmentedPage(engine, { slug: 'wiki/personal/reflections/r4', truth: 'Mondays I update my "weekly launch diary".\n',
+ meta: { type: 'note', title: 'r4', frontmatter: {} } });
+ script = [{ slug: PATTERN, date: '2026-10-11', summary: 'You keep a "weekly launch diary"', source: 'wiki/personal/reflections/r4' }];
+ const result = await runPhasePatterns(engine, { brainDir, dryRun: false, cycleDate: '2026-10-15' });
+ expect(result.status).toBe('ok');
+ const page = (await engine.getPage(PATTERN))!;
+ expect(page.timeline).toContain('weekly launch diary');
+ expect(page.frontmatter.unverified_claims).toBeUndefined();
+ expect(result.details.quote_verify).toMatchObject({ timeline_appends: { entries: 1, quarantined: 0, segmented_skipped: 0 } });
+ });
+});
diff --git a/test/e2e/cycle-patterns-segmented-postgres.test.ts b/test/e2e/cycle-patterns-segmented-postgres.test.ts
new file mode 100644
index 0000000000..3b8adf27f5
--- /dev/null
+++ b/test/e2e/cycle-patterns-segmented-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../cycle-patterns-segmented.test.ts'));