Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs(patterns): pending timeline-append retry and its hold (GBRA-130 A-23)

garrytanfbee632d3b83
diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.md
index c18520d5f9..ff5780f53b 100644
--- a/docs/architecture/key-files/core-cycle-patterns.md
+++ b/docs/architecture/key-files/core-cycle-patterns.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Patterns, drift reports and the cycle modules listed after them.
-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. In the phase each page is one item (`cycle/pattern-grounding.ts`, sites `patterns.ground_pages`, `patterns.ground_timeline_appends`): a failed page is listed in `details.grounding_failed` with code and fix, left unstamped and out of `patterns_written`, the watermark still stamps and the phase warns; a leftover page refused with a content error on 3 runs at one `content_hash` and gbrain version is held in `dream.patterns.grounding_holds.<source>` out of the leftover query and listed in `details.grounding_held` (warn) until the page or version changes or that key is unset; run-scoped or systemic failures fail the phase and record nothing (`test/pathological/a23-patterns-grounding.test.ts`). Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Segmented storage: `loadGroundingSources` reads a segmented reflection through `materializeSegmentedBody` (over `PAGE_MAX_BYTES` it is not a source, logged), and `groundTimelineAppends` reads pattern pages through `materializedSnapshot`, skipping an over-ceiling page (`segmented_skipped`). Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts` and `test/cycle-patterns-segmented.test.ts` (both engines). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`. #6297: an in-cycle run (not `--once`, not a direct `--phase patterns`, `CycleOpts.directPhases`) is skipped with `patterns_min_interval` while the partition's last COMPLETED child ended less than `dream.patterns.min_interval_hours` (default 6, 0 off) ago (`patternsCadenceSkip` in `patterns-plan.ts`; stamp `dream.patterns.last_completed_at.<source>.<incarnation>`, `.external` for the external partition), and the child gets `read_budget_bytes` from `dream.patterns.child_read_budget_kb` (default 200). Pinned by `test/cycle-patterns-cadence.serial.test.ts` and `test/cycle-patterns-read-budget.serial.test.ts`. #6779: the OUTPUT POLICY tells the child to keep an existing page's slug, skip it when its evidence covers the pattern, else rewrite it with get_page's `revision` as `expected_revision`, and to append with `add_timeline_entry` or skip a `read_budget_exhausted` summary (`test/cycle-patterns-revision-6779.test.ts`).
+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. In the phase each page is one item (`cycle/pattern-grounding.ts`, sites `patterns.ground_pages`, `patterns.ground_timeline_appends`): a failed page is listed in `details.grounding_failed` with code and fix, left unstamped and out of `patterns_written`, the watermark still stamps and the phase warns; a leftover page refused with a content error on 3 runs at one `content_hash` and gbrain version is held in `dream.patterns.grounding_holds.<source>` out of the leftover query and listed in `details.grounding_held` (warn) until the page or version changes or that key is unset; a timeline-append page whose write-back fails is stored with its entries and reflections in `dream.patterns.grounding_appends.<source>` (before the watermark stamps) and `retryPendingAppends` grounds it at the start of every later run, before the evidence and paid-child gates, at those reflections' derivation, then reverse-writes or verifies it (`details.timeline_append_retry`; a failed or held retry warns, a skipped pass included); the same 3-run content rule holds a page's appends (`grounding_held` rows with `timeline_appends`) until the page or version changes; run-scoped or systemic failures fail the phase and record nothing (`test/pathological/a23-patterns-grounding.test.ts`). Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Segmented storage: `loadGroundingSources` reads a segmented reflection through `materializeSegmentedBody` (over `PAGE_MAX_BYTES` it is not a source, logged), and `groundTimelineAppends` reads pattern pages through `materializedSnapshot`, skipping an over-ceiling page (`segmented_skipped`). Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts` and `test/cycle-patterns-segmented.test.ts` (both engines). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`. #6297: an in-cycle run (not `--once`, not a direct `--phase patterns`, `CycleOpts.directPhases`) is skipped with `patterns_min_interval` while the partition's last COMPLETED child ended less than `dream.patterns.min_interval_hours` (default 6, 0 off) ago (`patternsCadenceSkip` in `patterns-plan.ts`; stamp `dream.patterns.last_completed_at.<source>.<incarnation>`, `.external` for the external partition), and the child gets `read_budget_bytes` from `dream.patterns.child_read_budget_kb` (default 200). Pinned by `test/cycle-patterns-cadence.serial.test.ts` and `test/cycle-patterns-read-budget.serial.test.ts`. #6779: the OUTPUT POLICY tells the child to keep an existing page's slug, skip it when its evidence covers the pattern, else rewrite it with get_page's `revision` as `expected_revision`, and to append with `add_timeline_entry` or skip a `read_budget_exhausted` summary (`test/cycle-patterns-revision-6779.test.ts`).
- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.
- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically. Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each new take at the cluster's tier: `insert` writes it and `recordFlaggedRow` in the same transaction, `hold` records a `write_gate_holds` row and leaves the facts unconsolidated, `reject` skips the cluster (`details.clusters_gate_held` / `clusters_gate_rejected`); a re-promotion inserts nothing and is not gated; managed takes are gated in takes-prepare. Clustering (`clusterFacts`): typed metric facts cluster at `cycle.consolidate.cluster_threshold` (0.85) when `claimsCompatible` (same metric, unit, period); untyped facts cluster only at `untypedClusterThreshold` (max of the configured threshold and the 0.95 explicit-duplicate bar) and never when `claimsDiverge` (a differing negation, number, date or amount token), so two event facts about different invoices or amounts stay separate and the `valid_until` writeback never expires a true fact. `details.untyped_cluster_threshold` reports the bar; a dry run adds `details.clusters` (at most 50: source, entity, would-be claim, member ids and visibility; private text only when `opts.remote === false`). Each bucket is one item (ItemRun site `consolidate.buckets`): a bucket that throws (managed: an entity or evidence page private or deleted while its world facts stay active, `page_not_found`) counts in `details.buckets_failed`, samples up to 10 `details.bucket_failures` `{source_id, entity_slug, code, message, fix}` and makes the phase `warn` while later buckets consolidate; run-scoped errors, an accepted pending write and `item_failures_systemic` still end it (`test/pathological/a22-consolidate-buckets.test.ts`). Pinned by `test/trust-taint-dream.test.ts` and `test/consolidate-divergence.test.ts`.
diff --git a/docs/guides/dream-patterns.md b/docs/guides/dream-patterns.md
index 4e11833d51..0491f58ea5 100644
--- a/docs/guides/dream-patterns.md
+++ b/docs/guides/dream-patterns.md
@@ -84,6 +84,17 @@ page whose write-back is refused does not fail the run:
`gbrain config unset dream.patterns.grounding_holds.<source>` followed by
`gbrain dream --phase patterns --once --source <source>` retries every held
page now.
+- A page the child only appended timeline entries to is different: those
+ entries exist in that run alone. When its write-back is refused, the entries
+ and the reflections they are checked against are saved in
+ `dream.patterns.grounding_appends.<source>` before the evidence watermark is
+ stamped. Every later run retries them first, before the evidence check and
+ before any paid child, and reports the retry in `timeline_append_retry`. A
+ retry that fails warns (even when the run otherwise skips). After 3 content
+ refusals at the same page content and gbrain version the page's entries are
+ held: they stay saved, are listed in `grounding_held` with
+ `timeline_appends`, and editing the page or upgrading gbrain retries them.
+ Don't unset that key: it is the only copy of the entries still to check.
- A lost database connection, a cancelled run, or most pages failing at once
still fails the phase and holds nothing.