Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): patterns child sends expected_revision for an existing pattern page, and its refusal names the current revision (#6779)
garrytanf3eb4cfe0cbb
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex bffc3eb0d1..c4ee8ac23e 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -7,7 +7,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. #6757: the committed-outputs join (`COMMITTED_OUTPUT_REQUESTS_SQL`) compares `request_id` as a uuid within the source, served by `persistence_requests_request_id`. The phase loads it through `loadCommittedOutputsOrDefer`; a statement timeout there, or on an output's own `getWriteRequest`, defers the pass instead of failing it (`withPublishPending` with `details.postprocess_deferred`: phase warn, no cooldown stamp, no summary). Deferred and publish-pending outputs are carried by `synthesize-postprocess-deferral.ts` and finished by a later pass from the carried fields, with no child; `finishDeferredPostprocess` (run after the phase body by `runPhaseSynthesize`) finishes them when that pass returned before postprocessing.- `src/core/cycle/synthesize-postprocess-deferral.ts` — #6757: config row `dream.synthesize.postprocess_pending`, keyed by source and bound to its incarnation: each pending output (child request id, journaled and input slug, revision, job key, transcript path, content hash, seat, first write) and the source's consecutive deferred passes with the last read and its elapsed time. `isPostprocessReadTimeout` unwinds a cancelled cycle first, then accepts only SQLSTATE 57014 with the statement-timeout message (a user cancel is not deferred). `recordPostprocessPass` drops settled outputs, adds deferred and carried ones and resets the count on a pass that deferred nothing; `repeatedPostprocessDeferrals` lists sources at three or more for doctor `persistence_request_indexes`.-- `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/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`. #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`). 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.mdindex fb48218374..079a5e89d8 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -17,8 +17,8 @@ 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, 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/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`. #6779: a subagent `put_page` refused `revision_required` names the page's current revision (`rethrowWithCurrentRevision` in `put-page-result.ts`); MCP and CLI callers keep the bare refusal.+- `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, the `revision` (#6779, so a child can still append or skip), 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.mdindex cd101df465..aec50e699d 100644--- a/docs/guides/dream-patterns.md+++ b/docs/guides/dream-patterns.md@@ -22,6 +22,18 @@ anything.gbrain config set dream.patterns.subagent_timeout_ms 2400000```+## Updating an existing pattern page++Since #5385 a `put_page` of a page that already exists must send the page's+`revision` as `expected_revision`, or it is refused `revision_required`. The+child's prompt says so (#6779): it keeps an existing page's slug, skips the+page when its cited evidence already covers the pattern, and otherwise reads+it with `get_page` and writes the merged page back with that revision. If the+child still sends no revision, the refusal it gets names the page's current+revision, so it can merge and resend instead of failing the phase with+`PATTERNS_CHILD_DEAD`. Only the subagent tool path adds the revision; MCP and+CLI callers get the refusal and its `get_page` fix as before.+## Timeline appendsA patterns child often updates an existing pattern page by appending a dated@@ -86,8 +98,8 @@ The child's `get_page` output is budgeted at`dream.patterns.child_read_budget_kb` (default 200 KB). The bytes it has readare counted from the job's own tool-execution ledger, so a resumed job keepswhat 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 bytes of the rendered page) instead of the page. Writes still work, and+(`truncated: true`, `code: read_budget_exhausted`, the slug, title, type, the+page's `revision` and an excerpt of up to 400 bytes of the rendered page) instead of the page. Writes still work, andthe summary tells the child to append with `add_timeline_entry` instead ofrewriting a page it has not read in full. Reads are sized by the bytes of theresult, never by reading the body, so a segmented page is sized like anydiff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex 9ebced1607..96dfd471be 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -17,8 +17,10 @@ import { managedPersistenceEnabled } from '../persistence/ownership.ts';* - Single Sonnet subagent (no fan-out — one job per cycle is plenty).* - Idempotent: if reflection set is below `min_evidence`, phase is skipped.* - Pattern slug uses LLM's chosen topic-slug (subagent prompt instructs format).- * - Existing pattern pages are updated in place via put_page (idempotent- * ON CONFLICT semantics in importFromContent).+ * - Existing pattern pages are rewritten through put_page with the+ * revision get_page returned as expected_revision, appended to with+ * add_timeline_entry, or skipped (#6779: a put_page without the revision+ * is refused revision_required).*/import { join, dirname } from 'node:path';@@ -662,7 +664,8 @@ function buildPatternsPrompt(OUTPUT POLICY- Only name a pattern if it appears in at least ${minEvidence} DISTINCT reflections.- Each pattern page MUST cite the reflections that constitute its evidence (use [[${sourceSlugPrefix}/...]] wikilinks).-- Use \`search\` to check whether a similar pattern page already exists; if yes, update it (use the same slug). If no, create a new one.+- Use \`search\` to check whether a similar pattern page already exists. If no, create a new one.+- If one exists, keep its slug. Skip it when its cited evidence already covers the pattern. Otherwise read it with \`get_page\` and write the merged page back with \`put_page\`, passing the \`revision\` get_page returned as \`expected_revision\` (a \`put_page\` without it is refused \`revision_required\`). When the read comes back summarized (\`read_budget_exhausted\`), do not rewrite the page: append the new evidence with \`add_timeline_entry\` or skip it.- Pattern slug format: \`${outputSlugPrefix}/<topic-slug>\` (lowercase alphanumeric + hyphens; no underscores, no extension, no date).- A "pattern" is a recurring theme, anxiety, decision pattern, relationship dynamic, or self-knowledge motif. NOT a single insight. NOT a list of unrelated topics.@@ -1103,6 +1106,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 = {+ buildPatternsPrompt,collectChildTimelineAppends,countChildTimelineAppends,gatherReflections,diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex ff463ea2d8..fcc85236b8 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -31,7 +31,7 @@ import { paramDefToSchema } from '../../../mcp/tool-defs.ts';import { normalizeOptionalParams, validateParams } from '../../../mcp/validate-params.ts';import { validateSourceId } from '../../utils.ts';import type { ToolCtx, ToolDef } from '../types.ts';-import { putPageRejection } from './put-page-result.ts';+import { putPageRejection, rethrowWithCurrentRevision } from './put-page-result.ts';import { BRAIN_TOOL_ALLOWLIST } from './brain-tool-allowlist.ts';// The allow-list itself lives in a handler-free module so the MCP surface@@ -286,7 +286,9 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {if (op.name === 'get_page' && params.include_content === true) params.content_only = true;const validationError = validateParams(op, params);if (validationError) throw new Error(`${toolName}: ${validationError}`);- const output = await op.handler(opCtx, params);+ const output = op.name === 'put_page'+ ? await op.handler(opCtx, params).catch(e => rethrowWithCurrentRevision(ctx.engine, opCtx.sourceId ?? 'default', params.slug, e))+ : await op.handler(opCtx, params);const rejection = op.name === 'put_page' ? putPageRejection(output) : null;if (rejection) throw new Error(rejection);if (op.name === 'get_page' && opts.readBudgetBytes) return budgetedPageRead(ctx.engine, ctx.jobId, opts.readBudgetBytes, params.slug, output);diff --git a/src/core/minions/tools/put-page-result.ts b/src/core/minions/tools/put-page-result.tsindex a58b089143..921ce61b88 100644--- a/src/core/minions/tools/put-page-result.ts+++ b/src/core/minions/tools/put-page-result.ts@@ -1,3 +1,6 @@+import type { BrainEngine } from '../../engine.ts';+import { OperationError } from '../../ops/contract.ts';+export function putPageRejection(output: unknown): string | null {if (typeof output === 'string') {try { output = JSON.parse(output); } catch { return null; }@@ -10,3 +13,19 @@ export function putPageRejection(output: unknown): string | null {}return null;}++/**+ * #6779: a subagent's put_page refused `revision_required` names the page's+ * current revision, so the child can merge and resend (or skip) instead of+ * dying with the bare refusal. Subagent tool path only: MCP and CLI callers+ * keep the refusal and its get_page fix unchanged. A failed lookup rethrows+ * the refusal as it was.+ */+export async function rethrowWithCurrentRevision(engine: BrainEngine, sourceId: string, slug: unknown, error: unknown): Promise<never> {+ if (!(error instanceof OperationError) || error.code !== 'revision_required' || typeof slug !== 'string') throw error;+ const revision = await engine.readPageSnapshot(slug.toLowerCase(), { sourceId }).then(s => s?.revision, () => undefined);+ if (revision) {+ error.message = `${error.message} Its current revision is ${revision}: skip the page if it already covers what you would write, or read it with get_page, merge, and resend put_page with expected_revision "${revision}".`;+ }+ throw error;+}diff --git a/src/core/minions/tools/read-budget.ts b/src/core/minions/tools/read-budget.tsindex 444bdf9bdf..a21e68d60f 100644--- a/src/core/minions/tools/read-budget.ts+++ b/src/core/minions/tools/read-budget.ts@@ -39,10 +39,11 @@ export async function budgetedPageRead(engine: BrainEngine, jobId: number, budgeslug: typeof page.slug === 'string' ? page.slug : slug,...(typeof page.title === 'string' ? { title: page.title } : {}),...(typeof page.type === 'string' ? { type: page.type } : {}),+ ...(typeof page.revision === 'string' ? { revision: page.revision } : {}),truncated: true,code: 'read_budget_exhausted',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.',+ 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, or skip it when it already covers what you would add.',};}diff --git a/test/cycle-patterns-revision-6779.test.ts b/test/cycle-patterns-revision-6779.test.tsnew file mode 100644index 0000000000..05390575a5--- /dev/null+++ b/test/cycle-patterns-revision-6779.test.ts@@ -0,0 +1,84 @@+/**+ * #6779: once a pattern page exists, the next patterns child rewrote the same slug with `put_page` and no+ * `expected_revision`, the write was refused `revision_required`, and the phase died `PATTERNS_CHILD_DEAD`.+ *+ * Protects: the child is told to read an existing page and send its revision (or append to / skip a page whose+ * read came back budget-summarized); a refused subagent write names the page's current revision so the child can+ * resend without guessing; a budget-summarized read keeps the revision.+ * Fails when: the OUTPUT POLICY drops the expected_revision instruction, the subagent refusal omits the current+ * revision, or the read-budget summary drops it.+ * Seams: `__testing.buildPatternsPrompt`, `buildBrainTools` (the subagent tool path) on a PGLite brain.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import { buildBrainTools } from '../src/core/minions/tools/brain-allowlist.ts';+import { __testing } from '../src/core/cycle/patterns.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';++const SLUG = 'wiki/personal/patterns/fundraising-sprints';+const page = (body: string) => `---\ntitle: Fundraising sprints\ntype: note\n---\n${body}\n`;++let engine: PGLiteEngine;+let schemaVersion: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ schemaVersion = (await engine.getConfig('version')) ?? '7';+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+});++function childTools(readBudgetBytes?: number) {+ return buildBrainTools({ subagentId: 7, engine, config: { engine: 'pglite' } as GBrainConfig,+ allowedSlugPrefixes: ['wiki/personal/patterns/*'], sourceId: 'default', ...(readBudgetBytes ? { readBudgetBytes } : {}) });+}+const ctx = () => ({ engine, jobId: 7, remote: true as const });++describe('#6779 patterns OUTPUT POLICY', () => {+ test('tells the child to send an existing page revision as expected_revision, or append to or skip it', () => {+ const prompt = __testing.buildPatternsPrompt([], 3, 'wiki/personal/reflections', 'wiki/personal/patterns', '2026-10-16');+ expect(prompt).toContain('get_page');+ expect(prompt).toContain('expected_revision');+ expect(prompt).toContain('read_budget_exhausted');+ expect(prompt).toContain('add_timeline_entry');+ expect(prompt).toMatch(/skip/i);+ });+});++describe('#6779 subagent put_page on an existing page', () => {+ test('a write without expected_revision is refused naming the current revision; resending with it lands', async () => {+ const tools = childTools();+ const put = tools.find(t => t.name === 'brain_put_page')!;+ const created = await put.execute({ slug: SLUG, content: page('First sprint.') }, ctx()) as { revision: string };+ expect(created.revision).toMatch(/^[0-9a-f-]{36}$/);++ let refusal: (Error & { code?: string }) | undefined;+ try { await put.execute({ slug: SLUG, content: page('First sprint. Second sprint.') }, ctx()); } catch (e) { refusal = e as Error & { code?: string }; }+ expect(refusal?.code).toBe('revision_required');+ expect(refusal?.message).toContain('The page already exists; an expected revision is required.');+ expect(refusal?.message).toContain(created.revision);+ expect(refusal?.message).toContain('expected_revision');++ const updated = await put.execute({ slug: SLUG, content: page('First sprint. Second sprint.'), expected_revision: created.revision }, ctx()) as { revision: string };+ expect(updated.revision).not.toBe(created.revision);+ }, 60_000);++ test('a past-budget child gets a summary that keeps the revision and says to append or skip', async () => {+ const tools = childTools(16);+ const put = tools.find(t => t.name === 'brain_put_page')!;+ const created = await put.execute({ slug: SLUG, content: page('A long pattern page. '.repeat(50)) }, ctx()) as { revision: string };+ const summary = await tools.find(t => t.name === 'brain_get_page')!.execute({ slug: SLUG }, ctx()) as Record<string, unknown>;+ expect(summary.code).toBe('read_budget_exhausted');+ expect(summary.revision).toBe(created.revision);+ expect(String(summary.note)).toContain('add_timeline_entry');+ expect(String(summary.note)).toMatch(/skip/i);+ }, 60_000);+});