Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): patterns quote-verifies and counts timeline appends by write receipt (#6302)
garrytan07c189c56bd9
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 739ba33de1..43709ef4ab 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 Part A [R17]: completed `brain_add_timeline_entry` calls of the child are counted (`countChildTimelineAppends`) and reported as `details.appended_unverified` and in the summary; they get no quote verification or provenance stamp (Part B, grounding appended entries, is deferred). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`.+- `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`.- `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/guides/dream-patterns.md b/docs/guides/dream-patterns.mdindex df442edd52..27e063c0c2 100644--- a/docs/guides/dream-patterns.md+++ b/docs/guides/dream-patterns.md@@ -20,6 +20,32 @@ anything.gbrain config set dream.patterns.subagent_timeout_ms 2400000```+## Timeline appends++A patterns child often updates an existing pattern page by appending a dated+entry (`add_timeline_entry`) instead of rewriting the page. The phase treats+those pages as written:++- It finds the entries the child newly published from their write receipts.+ An entry that was already on the page, or a replayed call, is not a new+ append.+- With `dream.quote_verify` on (the default), only the new entries are+ checked against the reflections this run read. An entry whose quote is not+ in them moves to the page's `unverified_claims`, like a failing claim on a+ 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`.+ `timeline_appends` counts the new entries, and `quote_verify.timeline_appends`+ reports how many were checked, quarantined and repaired.++`appended_unverified` (the number of completed `add_timeline_entry` calls) is+deprecated and will be removed two releases after this one; read+`timeline_appends` and `patterns_written` instead.++**Say to your agent:** *"Did the last dream patterns run check the quotes it added to my pattern pages?"*+The agent reads the phase result (`gbrain dream --phase patterns --json` on a+direct run) and reports `quote_verify.timeline_appends`.+## Budget sizingAfter every child, finished, timed out or failed, the phase records its cost@@ -64,5 +90,8 @@ slowly than the reflection count and halving may take several cycles to fit.- Fix wave 13: a child stopped at its own timeout records `timeout`, so thenext plan halves (#6296). Timeline entries a child appends with`add_timeline_entry` are counted in the phase result as- `appended_unverified`; unlike pages written with `put_page`, they are not+ `appended_unverified`; unlike pages written with `put_page`, they were notquote-verified or provenance-stamped yet (#6302).+- Fix wave 18b: appended timeline entries are quote-verified, their pages are+ provenance-stamped and counted in `patterns_written`; `appended_unverified`+ is deprecated (#6302).diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.mdindex c58a9fa4cc..b4efb1d91d 100644--- a/docs/mcp/TOOL_REFERENCE.md+++ b/docs/mcp/TOOL_REFERENCE.md@@ -16,7 +16,7 @@ the row shape per call.## `add_timeline_entry`-Append an entry to the canonical Markdown timeline and structured timeline store in one committed write. Exact replay changes neither store. The receipt returns `bullet`, the rendered Markdown line. There is no update or remove verb: the page is the system of record, so to change or remove an entry read the page with `get_page include_content: true`, replace or delete that bullet with `edit_page` (passing `expected_revision`), and the timeline row follows the page.+Append an entry to the canonical Markdown timeline and structured timeline store in one committed write. Exact replay changes neither store. The receipt returns `bullet`, the rendered Markdown line. Entries a dream patterns child appends are quote-verified against that run's reflections; an entry whose quote is not found moves to the page's `unverified_claims`, and the phase result counts the page in `patterns_written` (`appended_unverified` there is a deprecated alias, removed two releases after fix wave 18b). There is no update or remove verb: the page is the system of record, so to change or remove an entry read the page with `get_page include_content: true`, replace or delete that bullet with `edit_page` (passing `expected_revision`), and the timeline row follows the page.| Parameter | Type | Guidance || --- | --- | --- |diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 42c4786099..53837a685a 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -96,6 +96,7 @@ test/cycle-lock-release-diagnostic.serial.test.ts R1 R1: mutates process.env (GBtest/cycle-lock-steal.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_CYCLE_LOCK_REFRESH_MS)test/cycle-patterns-completed-outcome.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the processtest/cycle-patterns-evidence-gate.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process+test/cycle-patterns-timeline-appends.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the processtest/cycle-pglite-lock-ordering.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)test/cycle-start-recovery-throw.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts) replaces modules for every file in the processtest/cycle/cycle-sync-uncommitted-warn.serial.test.ts R2 R2: mock.module(../../src/commands/sync.ts) replaces modules for every file in the processdiff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex a522dd3c16..f7fe862fc2 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -397,25 +397,29 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// #4077: no post-abort derived-state writes (collection is a read, but// the reverse-write below dual-writes files).throwIfAborted(opts.signal, '[dream] patterns output');- const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);- // #6302 Part A [R17]: timeline appends are counted and reported, never quote-verified or provenance-stamped.+ const putPageRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);+ // #6302: pages the child changed only through add_timeline_entry get their new entries verified and count as written.+ const appends = (await collectChildTimelineAppends(engine, [job.id], cycleSourceId))+ .filter(a => a.slug.startsWith(`${config.outputSlugPrefix}/`) && !putPageRefs.some(ref => ref.slug === a.slug));+ const writtenRefs = [...putPageRefs, ...[...new Set(appends.map(a => a.slug))].map(slug => ({ slug, source_id: cycleSourceId }))];+ // Deprecated alias (#6302): completed add_timeline_entry calls, kept two releases for readers of the old field.const appendedUnverified = await countChildTimelineAppends(engine, [job.id]);// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.- const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);+ const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, putPageRefs, appends, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized): await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);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,- appended_unverified: appendedUnverified, child_outcome: outcome, job_id: job.id };- const appendedNote = appendedUnverified > 0 ? `; ${appendedUnverified} timeline entr${appendedUnverified === 1 ? 'y' : 'ies'} appended (unverified)` : '';+ 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)' : ''}` : '';// #2782: the phase status must reflect the child outcome. Pre-fix this// returned status:ok even when the subagent timed out (e.g. no// subagent-capable worker slot free for the whole wait window) and zero// pattern pages were written — a silent no-op for days.if (outcome !== 'completed') {- if (finalized.length === 0 && appendedUnverified === 0) {+ if (finalized.length === 0 && appends.length === 0 && appendedUnverified === 0) {return {phase: 'patterns',status: 'fail',@@ -682,14 +686,16 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag* publications all landed, and the number of pages whose publication is held for a later cycle.*/async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null, written: Array<{ slug: string; source_id: string }>,- reflections: ReflectionRef[], derivation: Derivation & { declaration: DerivationDeclaration }, config: { outputSlugPrefix: string; sourceSlugPrefix: string },- sourceId: string, cycleDate: string, signal?: AbortSignal) {+ appends: TimelineAppend[], reflections: ReflectionRef[], derivation: Derivation & { declaration: DerivationDeclaration },+ config: { outputSlugPrefix: string; sourceSlugPrefix: string }, sourceId: string, cycleDate: string, signal?: AbortSignal) {const heldSlugs = new Set<string>();- const quoteVerify = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs, derivation);- await stampProvenance(engine, maintenance, written.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal, heldSlugs, derivation);+ const pages = await groundPatternPages(engine, maintenance, written, reflections, config.outputSlugPrefix, sourceId, cycleDate, signal, heldSlugs, derivation);+ const appended = await groundTimelineAppends(engine, maintenance, appends, reflections, sourceId, cycleDate, signal, heldSlugs, derivation);+ const outputs = [...written, ...[...new Set(appends.map(a => a.slug))].map(slug => ({ slug, source_id: sourceId }))];+ await stampProvenance(engine, maintenance, outputs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), signal, heldSlugs, derivation);// Holds are recorded for this cycle's source only, so a ref in any other source is never excused from verification.- const finalized = written.filter(ref => ref.source_id !== sourceId || !heldSlugs.has(ref.slug));- return { quoteVerify, finalized, held: heldSlugs.size };+ const finalized = outputs.filter(ref => ref.source_id !== sourceId || !heldSlugs.has(ref.slug));+ return { quoteVerify: pages ? { ...pages, ...(appended ? { timeline_appends: appended } : {}) } : null, finalized, held: heldSlugs.size };}async function stampProvenance(engine: BrainEngine, maintenance: MaintenanceAuthority | null,@@ -730,10 +736,7 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: MaintAND frontmatter->>'dream_generated' = 'true' AND frontmatter->>'quote_verified_at' IS NULL`, [sourceId, `${outputSlugPrefix}/%`]);const slugs = [...new Set([...refs.map(r => r.slug).filter(slug => slug.startsWith(`${outputSlugPrefix}/`)), ...leftover.map(r => r.slug)])];if (slugs.length === 0) return { pages: 0, quarantined: 0, repaired: 0 };- 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',- [sourceId, reflections.map(r => r.slug)]);- const sources = sourcePages.map(p => groundSource(p.slug, `${p.compiled_truth}\n\n${p.timeline ?? ''}`, { tolerant: true }));+ const sources = await loadGroundingSources(engine, sourceId, reflections, groundSource);const stats = { pages: 0, quarantined: 0, repaired: 0 };const { serializePageToMarkdown } = await import('../markdown.ts');for (const slug of slugs) {@@ -753,23 +756,105 @@ export async function groundPatternPages(engine: BrainEngine, maintenance: Maintconst page = { ...snapshot.page,compiled_truth: ct.body.trim() ? ct.body : (await import('./synthesize-verify.ts')).ALL_CLAIMS_QUARANTINED_BODY,timeline: tl.body, frontmatter };- const content = serializePageToMarkdown(page, snapshot.tags);- if (maintenance) {- const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');- const publish = () => publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision,- ...(derived ? { derivation: derived.declaration } : {}) });- if (!heldSlugs) await publish();- else if (await publishOrHold(publish)) heldSlugs.add(slug);- } else {- const [{ importFromContent }, { isAvailable }] = await Promise.all([import('../import-file.ts'), import('../ai/gateway.ts')]);- const write = (tx: BrainEngine) => importFromContent(tx, slug, content, { noEmbed: !isAvailable('embedding'), sourceId, preserveGateMarkers: true });- if (!derived) await write(engine);- else await derivedMaintenanceTransaction(engine, derived, async tx => ({ result: await write(tx), rows: [{ table: 'pages' as const, id: snapshot.page.id, sourceId }] }));+ await writeGroundedPage(engine, maintenance, snapshot, serializePageToMarkdown(page, snapshot.tags), sourceId, heldSlugs, derived);+ }+ return stats;+}++/** The full reflection pages a run read, grounded for quote verification. */+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',+ [sourceId, reflections.map(r => r.slug)]);+ return sourcePages.map(p => groundSource(p.slug, `${p.compiled_truth}\n\n${p.timeline ?? ''}`, { tolerant: true }));+}++/** Write a grounded page back at its read revision: a managed maintenance publish (held when pending or contended), else an import. */+async function writeGroundedPage(engine: BrainEngine, maintenance: MaintenanceAuthority | null, snapshot: { page: Page; revision: string },+ content: string, sourceId: string, heldSlugs?: Set<string>, derived?: Derivation & { declaration: DerivationDeclaration },+ removedEntries: TimelineAppend['entry'][] = []): Promise<void> {+ const slug = snapshot.page.slug;+ if (maintenance) {+ const { publishMaintenancePage } = await import('../persistence/prepared-maintenance.ts');+ const publish = () => publishMaintenancePage(engine, maintenance, slug, content, { expectedRevision: snapshot.revision,+ ...(derived ? { derivation: derived.declaration } : {}) });+ if (!heldSlugs) await publish();+ else if (await publishOrHold(publish)) heldSlugs.add(slug);+ return;+ }+ const [{ importFromContent }, { isAvailable }] = await Promise.all([import('../import-file.ts'), import('../ai/gateway.ts')]);+ // A managed publish projects timeline rows from the Markdown; an import does not, so a removed entry's row goes here.+ const write = async (tx: BrainEngine) => {+ const result = await importFromContent(tx, slug, content, { noEmbed: !isAvailable('embedding'), sourceId, preserveGateMarkers: true });+ for (const e of removedEntries) {+ await tx.executeRaw('DELETE FROM timeline_entries WHERE page_id = $1 AND event_page_id IS NULL AND date = $2::date AND source = $3 AND summary = $4',+ [snapshot.page.id, e.date, e.source, e.summary]);}+ return result;+ };+ if (!derived) await (removedEntries.length ? engine.transaction(write) : write(engine));+ else await derivedMaintenanceTransaction(engine, derived, async tx => ({ result: await write(tx), rows: [{ table: 'pages' as const, id: snapshot.page.id, sourceId }] }));+}++/**+ * #6302: quote-verify only the entries a patterns child appended with add_timeline_entry (on pages it did not+ * put_page) against this run's reflections. A failing entry leaves the timeline for frontmatter `unverified_claims`+ * (a materialized marker line in front of it goes with it); a near or normalized quote is repaired in place. Every+ * other byte of the page, earlier verified content and its stored claim sources included, is kept, and an entry no+ * longer on the page is skipped. Returns null when dream.quote_verify is off. Holds and derivation as groundPatternPages.+ */+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> {+ const { dreamQuoteVerifyEnabled, groundSource, verifyBody } = await import('./synthesize-verify.ts');+ if (!await dreamQuoteVerifyEnabled(engine)) return null;+ const stats = { entries: 0, quarantined: 0, repaired: 0 };+ if (appends.length === 0) return stats;+ const sources = await loadGroundingSources(engine, sourceId, reflections, groundSource);+ const { serializePageToMarkdown } = await import('../markdown.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 });+ if (!snapshot) continue;+ let timeline = snapshot.page.timeline ?? '';+ const quarantined: Array<Record<string, unknown>> = [];+ const removed: TimelineAppend['entry'][] = [];+ for (const append of appends.filter(a => a.slug === slug)) {+ const at = timeline.indexOf(append.block);+ if (at < 0) continue;+ stats.entries++;+ const verified = verifyBody(append.block, sources, { checks: 'quotes' });+ if (verified.quarantined.length > 0) {+ stats.quarantined += verified.quarantined.length;+ quarantined.push(...verified.quarantined.map(c => ({ ...c, detected_at: cycleDate })));+ timeline = removeTimelineBlock(timeline, at, append.block.length, append.marker);+ removed.push(append.entry);+ } else if (verified.changed) {+ stats.repaired += verified.normalized + verified.near;+ timeline = timeline.slice(0, at) + verified.body + timeline.slice(at + append.block.length);+ }+ }+ if (timeline === (snapshot.page.timeline ?? '')) continue;+ const frontmatter = quarantined.length+ ? withClaimSources(snapshot.page.frontmatter as Record<string, unknown>, quarantined, sources.map(x => x.path)).frontmatter+ : snapshot.page.frontmatter;+ await writeGroundedPage(engine, maintenance, snapshot, serializePageToMarkdown({ ...snapshot.page, timeline, frontmatter }, snapshot.tags),+ sourceId, heldSlugs, derivation, removed);}return stats;}+/** Cut one entry block (and the materialized marker line in front of it, when present) out of a timeline. */+function removeTimelineBlock(timeline: string, at: number, length: number, marker: string): string {+ let before = timeline.slice(0, at);+ let after = timeline.slice(at + length);+ if (before.endsWith(`${marker}\n`)) before = before.slice(0, -(marker.length + 1));+ if (after.startsWith('\n')) after = after.slice(1);+ else if (before.endsWith('\n')) before = before.slice(0, -1);+ return before + after;+}+// ── Provenance via put_page tool execution rows ─────────────────────async function collectChildPutPageSlugs(@@ -799,7 +884,43 @@ async function collectChildPutPageSlugs(.map(slug => ({ slug, source_id: sourceId }));}-/** Completed `brain_add_timeline_entry` calls of the given children (#6302 Part A). */+/** #6302: one entry a patterns child newly published with add_timeline_entry. */+export interface TimelineAppend { slug: string; requestId: string; block: string; marker: string; entry: { date: string; source: string; summary: string } }++/**+ * #6302: the timeline entries the given children newly published, selected by their write receipts, not by tool+ * completion: the request committed with outcome status `ok` (an entry already on the page commits as `skipped`).+ * A replayed call returns its original receipt, so each request id counts once, and two requests for one entry+ * identity (slug, date, source, summary) count once. The entry block is rendered from the call's input.+ */+async function collectChildTimelineAppends(engine: BrainEngine, childIds: number[], sourceId = 'default'): Promise<TimelineAppend[]> {+ if (childIds.length === 0) return [];+ const rows = await engine.executeRaw<{ request_id: string; slug: string; input: unknown }>(+ `SELECT r.request_id::text AS request_id, r.slug, e.input+ FROM subagent_tool_executions e+ JOIN persistence_requests r ON r.request_id::text = COALESCE(e.input->>'request_id', (e.input #>> '{}')::jsonb->>'request_id')+ WHERE e.job_id = ANY($1::int[]) AND e.tool_name = 'brain_add_timeline_entry'+ AND r.operation = 'add_timeline_entry' AND r.source_id = $2 AND r.state = 'committed' AND r.outcome->>'status' = 'ok'+ ORDER BY e.id`,+ [childIds, sourceId],+ );+ const out: TimelineAppend[] = [];+ const seen = new Set<string>();+ for (const row of rows) {+ const input = (typeof row.input === 'string' ? JSON.parse(row.input) : row.input) as Record<string, unknown>;+ if (input.slug !== row.slug) continue;+ const rendered = renderTimelineEntry({ date: String(input.date), summary: String(input.summary ?? ''),+ source: String(input.source ?? ''), detail: String(input.detail ?? '') }, row.slug);+ if (!rendered) continue;+ const identity = [row.slug, rendered.canonical.date, rendered.canonical.source, rendered.canonical.summary].join('\0');+ if (seen.has(row.request_id) || seen.has(identity)) continue;+ seen.add(row.request_id).add(identity);+ out.push({ slug: row.slug, requestId: row.request_id, block: rendered.block, marker: materializedMarker(rendered.canonical), entry: rendered.canonical });+ }+ return out;+}++/** Completed `brain_add_timeline_entry` calls of the given children: the deprecated `appended_unverified` alias (#6302). */async function countChildTimelineAppends(engine: BrainEngine, childIds: number[]): Promise<number> {if (childIds.length === 0) return 0;const [row] = await engine.executeRaw<{ n: number }>(@@ -813,6 +934,8 @@ 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';async function reverseWriteRefs(engine: BrainEngine,@@ -937,6 +1060,7 @@ function makeError(cls: string, code: string, message: string, hint?: string): P// source-scoping contract (#1586) without driving a whole dream cycle.// Mirrors synthesize.ts's `__testing` block.export const __testing = {+ collectChildTimelineAppends,countChildTimelineAppends,gatherReflections,collectChildPutPageSlugs,diff --git a/test/cycle-patterns-timeline-appends.serial.test.ts b/test/cycle-patterns-timeline-appends.serial.test.tsnew file mode 100644index 0000000000..ab67a11209--- /dev/null+++ b/test/cycle-patterns-timeline-appends.serial.test.ts@@ -0,0 +1,142 @@+/**+ * #6302: a patterns child mostly updates existing pattern pages with+ * add_timeline_entry. The phase now selects the entries it newly published by+ * write receipt, quote-verifies only those entries against this run's+ * reflections, stamps provenance on their pages and counts them in+ * `patterns_written`. Earlier verified content (a quote outside this run's+ * reflections, an older timeline entry the child re-appends) is left alone.+ * The child is scripted through the real brain tool and the subagent's+ * 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 { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+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';++const PATTERN = 'wiki/personal/patterns/small-pieces';+const REPLAYED = '0b6a3f52-7d1e-4c8a-9f10-2a6b5c4d3e21';+let script: Array<Record<string, unknown>> = [];++mock.module('../src/core/ai/gateway.ts', () => ({+ probeChatModel: () => ({ ok: true }),+ isAvailable: () => false,+}));++mock.module('../src/core/cycle/synthesize.ts', () => ({+ loadAllowedSlugPrefixes: async () => ['wiki/personal/patterns/*'],+ loadOutputRoot: async () => 'wiki',+ runSubagentsInline: async (engine: BrainEngine, _queue: unknown, queueName: string) => runScriptedChild(engine, queueName),+}));++mock.module('../src/core/minions/wait-for-completion.ts', () => ({+ TimeoutError: class TimeoutError extends Error {},+ waitForCompletion: async (_queue: unknown, jobId: number) => ({ id: jobId, status: 'completed' }),+ waitForCompletionRenewing: async (_queue: unknown, jobId: number, opts?: { renew?: () => Promise<void> }) => {+ if (opts?.renew) await opts.renew();+ return { id: jobId, status: 'completed' };+ },+}));++const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');+const { buildBrainTools } = await import('../src/core/minions/tools/brain-allowlist.ts');+const { retainToolWriteRequestId } = await import('../src/core/minions/tool-write-identity.ts');+const { persistToolExecComplete, persistToolExecPending } = await import('../src/core/minions/handlers/subagent-persistence.ts');++/** The subagent handler's tool path for each scripted call: stable request id, pending row, execute, complete row. */+async function runScriptedChild(engine: BrainEngine, queueName: string): Promise<void> {+ const [job] = await engine.executeRaw<{ id: number }>('SELECT id FROM minion_jobs WHERE queue = $1 ORDER BY id DESC LIMIT 1', [queueName]);+ const jobId = Number(job!.id);+ const tools = buildBrainTools({ subagentId: jobId, engine, config: { engine: 'pglite' } as GBrainConfig,+ allowedSlugPrefixes: ['wiki/personal/patterns/*'], sourceId: 'default' });+ const tool = tools.find(t => t.name === 'brain_add_timeline_entry')!;+ for (const [ordinal, call] of script.entries()) {+ const input = { ...call };+ const toolUseId = `toolu_${ordinal}`;+ retainToolWriteRequestId(input, jobId, 1, ordinal, toolUseId, tool.name);+ await persistToolExecPending(engine, jobId, 1, ordinal, toolUseId, tool.name, input);+ const output = await tool.execute(input, { engine, jobId, remote: true });+ await persistToolExecComplete(engine, jobId, 1, ordinal, toolUseId, output);+ }+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'completed' WHERE id = $1`, [jobId]);+}++let engine: PGLiteEngine;+let schemaVersion: string;+let brainDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ schemaVersion = (await engine.getConfig('version')) ?? '7';+ brainDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-appends-'));+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');+ await engine.setConfig('dream.quote_verify', 'true');+ for (const [i, body] of ['I keep saying "ship smaller pieces" when projects stall.', 'Again I told myself to ship smaller pieces.', 'Shipping smaller pieces worked this week.'].entries()) {+ await importFromContent(engine, `wiki/personal/reflections/r${i + 1}`, `---\ntype: note\ntitle: r${i + 1}\n---\n${body}\n`, { noEmbed: true, sourceId: 'default' });+ }+ // Verified by an earlier run against reflections this run does not read.+ await importFromContent(engine, PATTERN,+ `---\ntype: note\ntitle: Small pieces\ndream_generated: true\nquote_verified_at: '2026-10-01'\n---\nAn earlier run quoted "never ship on Fridays".\n\n<!-- timeline -->\n## Timeline\n\n- **2026-09-01** | wiki/personal/reflections/old — You said "keep a launch diary".\n`,+ { noEmbed: true, sourceId: 'default' });+ script = [];+});++describe('patterns timeline appends are quote-verified and counted (#6302)', () => {+ test('an append quoting text absent from the reflections is quarantined; earlier verified content survives', async () => {+ script = [+ { slug: PATTERN, date: '2026-10-10', summary: 'You wrote "always test on staging" again', source: 'wiki/personal/reflections/r3' },+ { slug: PATTERN, date: '2026-10-11', summary: 'You repeat "ship smaller pieces"', source: 'wiki/personal/reflections/r1', request_id: REPLAYED },+ // The child re-appends an entry already on the page: its receipt says skipped, so it is not a new append.+ { slug: PATTERN, date: '2026-09-01', summary: 'You said "keep a launch diary".', source: 'wiki/personal/reflections/old' },+ // A replayed call returns its original receipt (status ok again); it is the same append, counted once.+ { slug: PATTERN, date: '2026-10-11', summary: 'You repeat "ship smaller pieces"', source: 'wiki/personal/reflections/r1', request_id: REPLAYED },+ ];+ 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).not.toContain('always test on staging');+ expect(page.timeline).toContain('ship smaller pieces');+ expect(page.timeline).toContain('keep a launch diary');+ expect(page.compiled_truth).toContain('never ship on Fridays');+ const claims = page.frontmatter.unverified_claims as Array<{ text: string; reason: string }>;+ expect(claims).toHaveLength(1);+ expect(claims[0]!.text).toContain('always test on staging');+ expect(claims[0]!.reason).toBe('quote_not_in_source');+ expect(page.frontmatter.quote_verified_at).toBe('2026-10-01');+ expect(page.frontmatter.dream_cycle_date).toBe('2026-10-15');+ expect(page.frontmatter.raw_trace_exempt).toBe(true);+ const rows = await engine.getTimeline(PATTERN, { sourceId: 'default' });+ expect(rows.map(r => r.summary).join('\n')).not.toContain('always test on staging');+ expect(result.details.patterns_written).toBe(1);+ expect(result.details.timeline_appends).toBe(2);+ expect(result.details.appended_unverified).toBe(4);+ expect(result.details.quote_verify).toMatchObject({ timeline_appends: { entries: 2, quarantined: 1, repaired: 0 } });+ expect(result.summary).toContain('1 pattern page(s) written/updated');+ });++ test('appends that all ground change nothing on the page but still count it as written', async () => {+ script = [{ slug: PATTERN, date: '2026-10-11', summary: 'You repeat "ship smaller pieces"', source: 'wiki/personal/reflections/r1' }];+ const result = await runPhasePatterns(engine, { brainDir, dryRun: false, cycleDate: '2026-10-15' });+ const page = (await engine.getPage(PATTERN))!;+ expect(page.frontmatter.unverified_claims).toBeUndefined();+ expect(page.timeline).toContain('ship smaller pieces');+ expect(result.details.patterns_written).toBe(1);+ expect(result.details.quote_verify).toMatchObject({ timeline_appends: { entries: 1, quarantined: 0, repaired: 0 } });+ });+});