Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(dream): in-cycle patterns cadence and a child get_page read budget (#6297)
garrytanad0b9a5caa79
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 43709ef4ab..c41c609a9e 100644--- a/docs/architecture/key-files/core-cycle-continued.md+++ b/docs/architecture/key-files/core-cycle-continued.md@@ -6,7 +6,7 @@ Synthesis, patterns, consolidation and connector atom gating.- `src/core/cycle/synthesize-postprocess.ts` — Managed synthesis quote repair and provenance stamping publish together through a deterministic maintenance request bound to the source incarnation, transcript hash, child output, and original committed page revision. `loadCommittedSynthesisOutputs` finds each child's committed output by canonicalizing the retained `brain_put_page` input (`parseWriteRequestId` for the request id, `journaledPageSlug` for the slug) before matching request id, source, incarnation, committed put_page, slug and revision (#6616); slug discovery (`collectChildPutPageSlugs`) and postprocessing share that set. The immutable committed receipt is the completion checkpoint: later runs skip finalized output rather than repairing user edits. Pending work replays its retained intent under the original revision and existing authority/file guards; missing provenance fails closed. A publish still `write_pending` after the job's shared maintenance wait is deferred, never written or finalized: `withPublishPending` turns the phase result into `warn` with `publish_pending` and `SYNTH_PUBLISH_DEFERRED` ("publish deferred (writer busy); finishes next cycle, no action needed"), `synthesize.ts` leaves `dream.synthesize.last_completion_ts` unstamped, and the next ordinary cycle resumes the same deterministic request id. Runs the same claim verification as the unmanaged path (`groundSource` + `resolveVerifyPrior` + `verifyDreamPage` from `synthesize-verify.ts`, scoped by the ref's `first_write_at`, else the child write epochs passed as `sinceByTranscript`) and stamps the dream provenance fields only on dream-owned pages (`isDreamOwnedPage`); the published page reconciles its automatic links like an ordinary put_page (`page-prepare.ts` treats `managed_maintenance_page` intents as auto-linked); the unmanaged path retains its fail-open behavior. Covered by `test/managed-synthesis-postprocess.test.ts` and its PostgreSQL E2E wrapper. The optional `grounding` pass (System One S8) runs after `verifyDreamPage` and before `publishMaintenancePage`, so the published revision never carries a unit S8 quarantined; pinned by `test/decide/writepath-phase.serial.test.ts`. The postprocess stamps the transcript's `seat` next to `raw_source` on dream-owned output. `deferPublishOrThrow` defers an output or summary publish that is still pending or whose admission gave up on database contention (`publicationHold` in `persistence/accepted-pending.ts`, one stderr line per contended publish) exactly like the pending case: `publish_pending`, phase warn, no cooldown stamp; every other error fails the phase. Pinned by `test/managed-synthesis-postprocess.test.ts`. #5575 I2: each output publishes with `derivation` from its transcript (`dream-taint.ts` `transcriptDerivation`; `meetingTranscriptsDir` in opts); a retained request replays the declaration it was admitted with. #6360: when the page moved after the child commit, a drift made only by committed local `managed_maintenance_page` requests (for example the next cycle's lint `created:` fix) over a body equal to the child's is adopted: the postprocess runs on the current snapshot under a request id that also binds that base revision (found again on replay among the later requests). Any other later write leaves the page alone as a `PostprocessConflict` (`withPostprocessConflicts`: phase `warn`, `details.postprocess_conflicts` with the read-only `gbrain get` fix); it is reported once (config `dream.synthesize.postprocess_conflicts`, 30-day memory) and does not block the cooldown stamp.-- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts`. #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`.+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302: `collectChildTimelineAppends` selects the entries the child newly published with `brain_add_timeline_entry` by write receipt (`persistence_requests` committed with outcome status `ok`, joined on the call's input `request_id`), once per request id and per entry identity, so a replay or a re-append of an existing entry (`skipped`) is not a new append. On pages the child did not `put_page`, `groundTimelineAppends` quote-verifies only those entry blocks against this run's reflections: a failing entry (with its materialized marker line) leaves the timeline for `unverified_claims` (its timeline row is deleted on the import path; a managed publish projects rows from the Markdown), a near/normalized quote is repaired in place, and everything else on the page, `quote_verified_at` and stored claim sources included, is kept. Those pages are provenance-stamped, reverse-written and counted in `patterns_written`; `details.timeline_appends` counts the entries and `quote_verify.timeline_appends` the grounding. `details.appended_unverified` (`countChildTimelineAppends`, completed calls) is a deprecated alias. Pinned by `test/cycle-patterns-timeline-appends.serial.test.ts`. #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`. #6297: an in-cycle run (not `--once`, not a direct `--phase patterns`, `CycleOpts.directPhases`) is skipped with `patterns_min_interval` while the partition's last COMPLETED child ended less than `dream.patterns.min_interval_hours` (default 6, 0 off) ago (`patternsCadenceSkip` in `patterns-plan.ts`; stamp `dream.patterns.last_completed_at.<source>.<incarnation>`, `.external` for the external partition), and the child gets `read_budget_bytes` from `dream.patterns.child_read_budget_kb` (default 200). Pinned by `test/cycle-patterns-cadence.serial.test.ts` and `test/cycle-patterns-read-budget.serial.test.ts`.- `src/core/cycle/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 1d63f2d6ca..570ae78750 100644--- a/docs/architecture/key-files/core-minions-2.md+++ b/docs/architecture/key-files/core-minions-2.md@@ -17,7 +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`.+- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list in the handler-free `brain-tool-allowlist.ts`, which `src/mcp/surface.ts` reads, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack. #6297: a subagent `get_page` with `include_content: true` is forced to `content_only: true`, so the body arrives once (as `content`) instead of also as parsed `compiled_truth`/`timeline`. `BuildBrainToolsOpts.readBudgetBytes` (from trusted `SubagentHandlerData.read_budget_bytes`) routes `get_page` results through `read-budget.ts`.+- `src/core/minions/tools/read-budget.ts` — #6297 per-job `get_page` byte budget: `budgetedPageRead` counts bytes already returned from the job's `subagent_tool_executions` rows (`brain_get_page`, `complete`), so a replayed job keeps its spend, and past the budget returns a summary (`truncated: true`, `code: read_budget_exhausted`, slug/title/type, an excerpt of at most `READ_BUDGET_EXCERPT_CHARS`) instead of the page.- `src/core/minions/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 27e063c0c2..18b2910b83 100644--- a/docs/guides/dream-patterns.md+++ b/docs/guides/dream-patterns.md@@ -15,6 +15,8 @@ anything.| `dream.patterns.min_evidence` | integer ≥ 1 | `3` | Distinct reflections a pattern needs; also the smallest run worth submitting. || `dream.patterns.subagent_timeout_ms` | milliseconds | `1800000` (30 min) | The child job's own timeout. Inside the cycle it is clamped to the time left. || `dream.patterns.subagent_wait_timeout_ms` | milliseconds | `2100000` (35 min) | How long the phase waits for the child. Clamped the same way. |+| `dream.patterns.min_interval_hours` | hours, 0 to 720 | `6` | Time an in-cycle run waits after the last completed run. `0` turns it off. See [Cadence](#cadence). |+| `dream.patterns.child_read_budget_kb` | whole KB, 0 to 100000 | `200` | `get_page` output the child reads in full before reads come back summarized. `0` turns it off. See [Child read budget](#child-read-budget). |```bashgbrain config set dream.patterns.subagent_timeout_ms 2400000@@ -46,6 +48,42 @@ deprecated and will be removed two releases after this one; readThe agent reads the phase result (`gbrain dream --phase patterns --json` on adirect run) and reports `quote_verify.timeline_appends`.+## Cadence++Every maintenance pass writes new reflections, so the evidence check alone+started a paid patterns child on every pass. An in-cycle run (autopilot or a+bare `gbrain dream`) now waits `dream.patterns.min_interval_hours` (default 6)+after the last **completed** run. A timed-out or failed child does not start+the clock, so the next pass retries it.++A skipped run reports `reason: patterns_min_interval` with+`last_completed_at` and `next_eligible_at`, and submits nothing. A direct+`gbrain dream --phase patterns` and `--once` are not held to the interval; a+direct run is paid, so ask the user first.++The stamp is state, not a setting: it lives in+`dream.patterns.last_completed_at.<source>.<incarnation>`, so a re-created+source starts fresh. Reflections from external sources run in their own pass+with their own stamp (the same key plus `.external`), so the owner pass never+holds them back.++```bash+gbrain config set dream.patterns.min_interval_hours 12 # 0 turns the cadence off+```++## Child read budget++A CLI-backed model replays the whole transcript on every turn, so a child that+read every existing pattern page in full could fill half the model window.+The child's `get_page` output is budgeted at+`dream.patterns.child_read_budget_kb` (default 200 KB). The bytes it has read+are counted from the job's own tool-execution ledger, so a resumed job keeps+what it already spent. Past the budget a read returns a short summary+(`truncated: true`, `code: read_budget_exhausted`, the slug, title, type and an+excerpt of up to 400 characters) instead of the page. Writes still work, and+the summary tells the child to append with `add_timeline_entry` instead of+rewriting a page it has not read in full.+## Budget sizingAfter every child, finished, timed out or failed, the phase records its cost@@ -94,4 +132,7 @@ slowly than the reflection count and halving may take several cycles to fit.quote-verified or provenance-stamped yet (#6302).- Fix wave 18b: appended timeline entries are quote-verified, their pages areprovenance-stamped and counted in `patterns_written`; `appended_unverified`- is deprecated (#6302).+ is deprecated (#6302). In-cycle runs wait+ `dream.patterns.min_interval_hours` after the last completed run, and the+ child's `get_page` reads are budgeted by `dream.patterns.child_read_budget_kb`+ (#6297).diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 0372844413..b7615c2bb3 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2244,6 +2244,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run. | The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing. | Wait briefly, then retry the same request (writes: reuse the same request_id). Run: gbrain write-requests --source '{source_id}' | agent | `repeat the read that failed` | 1 | yes |+### patterns_min_interval++<a id="patterns_min_interval"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An in-cycle dream patterns run was skipped because the partition's last completed patterns run ended less than dream.patterns.min_interval_hours ago; nothing was submitted. | Every maintenance pass writes new reflections, so the evidence watermark alone re-ran a paid patterns child on each pass. The skip names next_eligible_at; a direct `gbrain dream --phase patterns` or `--once` is not held to the interval, and `gbrain config set dream.patterns.min_interval_hours 0` turns it off. | Wait for next_eligible_at, or, with the user's paid authorization, run `gbrain dream --phase patterns` now. Run: gbrain dream --phase patterns | agent · paid | `repeat the read that failed` | 1 | no |++More: [docs/guides/dream-patterns.md#cadence](../../docs/guides/dream-patterns.md#cadence)+### payload_too_large<a id="payload_too_large"></a>@@ -2522,6 +2532,16 @@ More: [docs/guides/pinned-questions.md#who-can-see-pinned-questions](../../docs/|---|---|---|---|---|---|---|| The request was rate-limited; retry after the stated delay. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### read_budget_exhausted++<a id="read_budget_exhausted"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A subagent's get_page result came back as a short summary because the job has used its read budget (for the dream patterns child, dream.patterns.child_read_budget_kb). | A CLI-backed model replays the whole transcript on every turn, so a child that read every page in full filled the model window. The summary keeps the slug, title, type and a short excerpt; writes still work. | Work from the pages already read and append with add_timeline_entry instead of rewriting a summarized page. An operator who needs more reads raises dream.patterns.child_read_budget_kb (0 turns the budget off). | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/dream-patterns.md#child-read-budget](../../docs/guides/dream-patterns.md#child-read-budget)+### receipt_conflict<a id="receipt_conflict"></a>diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 03787a67cf..b072f00f30 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -13,7 +13,7 @@ src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut linesrc/commands/serve-http.ts 932 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts)src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same textsrc/commands/sync.ts 529 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts)-src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field+src/core/cycle.ts 3316 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence)src/core/cycle/synthesize.ts 3224 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.tssrc/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2796 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2)@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1979 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts)+src/core/config.ts 1980 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keyssrc/core/persistence/sync-run.ts 1690 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts)src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optiondiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 53837a685a..e3389ecd89 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -97,6 +97,8 @@ test/cycle-lock-steal.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBtest/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 processtest/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 process+test/cycle-patterns-cadence.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-read-budget.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/commands/dream.ts b/src/commands/dream.tsindex 130d63a3bb..dc6953389a 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -869,6 +869,7 @@ export async function runDream(engine: BrainEngine | null, args: string[]): PromdryRun: opts.dryRun,pull: opts.pull,phases,+ directPhases: phases !== undefined,// Undefined for legacy unscoped runs; set for explicit source cycles,// path-derived cycles, and bare default-like non-default source cycles.sourceId: resolvedSourceId,diff --git a/src/core/config.ts b/src/core/config.tsindex 5640cb2abc..676879e9ad 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1578,6 +1578,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// dream.synthesize.* pair from #1594).'dream.patterns.subagent_timeout_ms','dream.patterns.subagent_wait_timeout_ms',+ 'dream.patterns.min_interval_hours', 'dream.patterns.child_read_budget_kb', // #6297: hours (default 6) / KB (default 200), 0 = off; cycle/phase-config-values.ts// Paid-loop breaker: dead submissions of one dream key within 24h before// it is refused (default 3; 0 disables). `gbrain dream reset-key` clears one.'dream.breaker.max_dead_submissions',diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex a8623091af..f598691656 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -608,6 +608,8 @@ export interface CycleOpts {* one-shot escape hatch (`--drain` for extract_atoms).*/onceForPhase?: CyclePhase;+ /** #6297: the operator named the phases (`gbrain dream --phase`); patterns then skips its in-cycle cadence. */+ directPhases?: boolean;/*** Absolute wall-clock deadline (epoch ms) of the enclosing minion job,* from `MinionJobContext.deadlineAtMs` (the claim-time `timeout_at`@@ -2536,7 +2538,7 @@ async function runCycleUnscoped(// the cycle lock (pre-fix these sites passed the raw — in production// always-undefined — hook, so long phases never refreshed).yieldDuringPhase: buildYieldDuringPhase(lock, opts.yieldDuringPhase, onStolen),- once: opts.onceForPhase === 'patterns',+ once: opts.onceForPhase === 'patterns', direct: opts.directPhases === true,cycleDate,deadlineAtMs: opts.deadlineAtMs ?? null,privateQueueOwnerJobId: opts.privateQueueOwnerJobId ?? null,diff --git a/src/core/cycle/patterns-plan.ts b/src/core/cycle/patterns-plan.tsindex 7261f60d71..54790fdf51 100644--- a/src/core/cycle/patterns-plan.ts+++ b/src/core/cycle/patterns-plan.ts@@ -11,6 +11,9 @@import type { BrainEngine } from '../engine.ts';import type { Action } from '../agent-output.ts';import type { PhaseResult } from '../cycle.ts';+import {+ PATTERNS_CHILD_READ_BUDGET_DEFAULT_KB, PATTERNS_CHILD_READ_BUDGET_KEY, PATTERNS_MIN_INTERVAL_DEFAULT_HOURS, PATTERNS_MIN_INTERVAL_KEY, readPhaseConfigNumber,+} from './phase-config-values.ts';export const PATTERNS_LAST_RUN_KEY = 'dream.patterns.last_run';/** Reflections a first in-cycle run submits with no history (or min_evidence, if larger). */@@ -119,3 +122,52 @@ export async function sizePatternsRun(engine: BrainEngine, input: { budgetMs: nureflections_submitted: 0, reflections_fit: plan.n, budget_ms: budgetMs, last_run: lastRun,fix: patternsBudgetSkipFix(), reset_command: `gbrain config unset ${PATTERNS_LAST_RUN_KEY}` } } };}++/** #6297: state key prefix of the time each partition's last completed patterns child ended. */+export const PATTERNS_CADENCE_KEY = 'dream.patterns.last_completed_at';++/**+ * The owner partition's cadence key: per source and source incarnation, so a+ * re-created source starts fresh. The external partition appends `.external`,+ * so the owner pass never throttles it.+ */+export async function patternsCadenceKey(engine: BrainEngine, sourceId: string): Promise<string> {+ const [source] = await engine.executeRaw<{ incarnation: string | null }>('SELECT incarnation FROM sources WHERE id = $1', [sourceId]);+ return `${PATTERNS_CADENCE_KEY}.${sourceId}${source?.incarnation ? `.${source.incarnation}` : ''}`;+}++/**+ * #6297: an in-cycle run (autopilot, bare `gbrain dream`) is skipped while+ * the partition's last completed child ended less than+ * `dream.patterns.min_interval_hours` (default 6, 0 off) ago. Every+ * maintenance pass writes new reflections, so the evidence watermark alone+ * re-ran a paid child on every pass. A direct `gbrain dream --phase patterns`+ * or `--once` is not checked (the caller decides). An absent or unreadable+ * stamp fails open.+ */+export async function patternsCadenceSkip(engine: BrainEngine, cadenceKey: string, nowMs = Date.now()): Promise<PhaseResult | null> {+ const setting = await readPhaseConfigNumber(engine, PATTERNS_MIN_INTERVAL_KEY);+ if (setting.warning) process.stderr.write(`[dream] ${setting.warning}\n`);+ const hours = setting.value ?? PATTERNS_MIN_INTERVAL_DEFAULT_HOURS;+ if (hours <= 0) return null;+ const lastMs = Date.parse((await engine.getConfig(cadenceKey)) ?? '');+ if (!Number.isFinite(lastMs)) return null;+ const nextMs = lastMs + hours * 3_600_000;+ if (nowMs >= nextMs) return null;+ const next = new Date(nextMs).toISOString();+ return { phase: 'patterns', status: 'skipped', duration_ms: 0,+ summary: `patterns: the last completed run ended at ${new Date(lastMs).toISOString()}; in-cycle runs wait ${hours}h (${PATTERNS_MIN_INTERVAL_KEY}), so the next one is eligible at ${next}. Nothing was submitted.`,+ details: { reason: 'patterns_min_interval', code: 'patterns_min_interval', last_completed_at: new Date(lastMs).toISOString(), next_eligible_at: next,+ min_interval_hours: hours, cadence_key: cadenceKey,+ fix: { argv: ['gbrain', 'dream', '--phase', 'patterns'], consent: ['paid'], actor: 'agent', requires_exclusive: false,+ why: `A direct run is not held to ${PATTERNS_MIN_INTERVAL_KEY}. It is a paid model run, so ask the user first; otherwise the next in-cycle run after ${next} runs on its own.`,+ verify: { argv: ['gbrain', 'config', 'get', cadenceKey] }, docs: 'docs/guides/dream-patterns.md#cadence' } as Action } };+}++/** #6297: the patterns child's get_page budget in bytes (`dream.patterns.child_read_budget_kb`, default 200 KB), or null when off. */+export async function patternsChildReadBudgetBytes(engine: BrainEngine): Promise<number | null> {+ const setting = await readPhaseConfigNumber(engine, PATTERNS_CHILD_READ_BUDGET_KEY);+ if (setting.warning) process.stderr.write(`[dream] ${setting.warning}\n`);+ const kb = setting.value ?? PATTERNS_CHILD_READ_BUDGET_DEFAULT_KB;+ return kb > 0 ? kb * 1024 : null;+}diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex f7fe862fc2..c4240844a6 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -73,6 +73,12 @@ export interface PatternsPhaseOpts {* autopilot tick doesn't re-pay for evidence the operator just consumed.*/once?: boolean;+ /**+ * #6297: the operator named this phase (`gbrain dream --phase patterns`). A+ * direct run, like `--once`, is not held to `dream.patterns.min_interval_hours`;+ * in-cycle runs (autopilot, bare `gbrain dream`) are.+ */+ direct?: boolean;/*** Absolute deadline (epoch ms) of the enclosing minion job, or null for* direct callers (`gbrain dream`). When set, the subagent's job timeout@@ -106,7 +112,7 @@ export interface PatternsPhaseOpts {* working.*/import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';-import { recordPatternsLastRun, sizePatternsRun } from './patterns-plan.ts';+import { patternsCadenceKey, patternsCadenceSkip, patternsChildReadBudgetBytes, recordPatternsLastRun, sizePatternsRun } from './patterns-plan.ts';export { CYCLE_DEADLINE_RESERVE_MS };/**@@ -145,7 +151,7 @@ export async function runPhasePatterns(engine: BrainEngine,opts: PatternsPhaseOpts,): Promise<PhaseResult> {- let config: PatternsConfig, evidenceKey: string, reflections: ReflectionRef[];+ let config: PatternsConfig, evidenceKey: string, cadenceKey: string, reflections: ReflectionRef[];try {throwIfAborted(opts.signal, '[dream] patterns');config = await loadPatternsConfig(engine);@@ -163,6 +169,7 @@ export async function runPhasePatterns(const [source] = await managedPersistenceEnabled(engine)? await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [opts.sourceId ?? 'default']) : [];evidenceKey = source ? `${LAST_EVIDENCE_KEY}.${opts.sourceId ?? 'default'}.${source.incarnation}` : LAST_EVIDENCE_KEY;+ cadenceKey = await patternsCadenceKey(engine, opts.sourceId ?? 'default');// Gather reflections within lookback window.reflections = await gatherReflections(engine, config.lookbackDays, config.sourceSlugPrefix, opts.sourceId ?? 'default');@@ -174,16 +181,16 @@ export async function runPhasePatterns(// owner's reflections. External reflections get their own pass (only with// enough evidence of their own), and that pass's pattern pages are external.const external = reflections.filter(r => isExternalTier(r.taint?.tier ?? 'unknown'));- const owner = await runPatternsPass(engine, opts, config, reflections.filter(r => !external.includes(r)), evidenceKey);+ const owner = await runPatternsPass(engine, opts, config, reflections.filter(r => !external.includes(r)), { evidence: evidenceKey, cadence: cadenceKey });if (!external.length) return owner;const externalPass = external.length >= config.minEvidence- ? await runPatternsPass(engine, opts, config, external, `${evidenceKey}.external`) : null;+ ? await runPatternsPass(engine, opts, config, external, { evidence: `${evidenceKey}.external`, cadence: `${cadenceKey}.external` }) : null;return mergeExternalPass(owner, externalPass, external.length);}-/** One patterns child over one partition of the reflections; `evidenceKey` is that partition's watermark. */+/** One patterns child over one partition of the reflections; `keys` are that partition's evidence watermark and cadence stamp. */async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, config: PatternsConfig,- reflections: ReflectionRef[], evidenceKey: string): Promise<PhaseResult> {+ reflections: ReflectionRef[], keys: { evidence: string; cadence: string }): Promise<PhaseResult> {const start = Date.now();let ownedPrivateQueue: { queue: MinionQueue; name: string } | null = null;try {@@ -203,7 +210,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// synthesize's checkCooldown; `--once` forces past it.const newestEvidenceMs = reflections[0].updatedAt.getTime();if (!opts.once) {- const stampMs = Date.parse((await engine.getConfig(evidenceKey)) ?? '');+ const stampMs = Date.parse((await engine.getConfig(keys.evidence)) ?? '');if (Number.isFinite(stampMs) && newestEvidenceMs <= stampMs) {return skipped('no_new_evidence',@@ -213,6 +220,9 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con}}+ // #6297: an in-cycle run waits dream.patterns.min_interval_hours after the partition's last completed run.+ const cadence = opts.once || opts.direct ? null : await patternsCadenceSkip(engine, keys.cadence);+ if (cadence) return cadence;if (opts.dryRun) {return ok(`dry-run: would detect patterns over ${reflections.length} reflections`, {reflections_considered: reflections.length,@@ -303,6 +313,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, conrequire_writes: true,allow_clean_zero_writes: true,allowed_slug_prefixes: allowedSlugPrefixes,+ ...await patternsChildReadBudgetBytes(engine).then(bytes => bytes ? { read_budget_bytes: bytes } : {}), // #6297: get_page results past it come back summarized// #1586: scope every child tool call to the cycle's resolved source so// put_page writes land there instead of the hardcoded 'default'....(opts.sourceId ? { source_id: opts.sourceId } : {}),@@ -381,6 +392,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con}await recordPatternsLastRun(engine, { duration_ms: Date.now() - submittedAt, reflections: submitted.length, outcome, error_text: errorText }); // #6177: every child, timed out or failed too+ if (outcome === 'completed') await engine.setConfig(keys.cadence, new Date().toISOString()); // #6297: cadence counts from completed runsif (outcome === 'completed' && submitOpts.idempotency_key) await clearPatternsSourceDeaths(engine, opts.sourceId ?? 'default'); // #6236: only consecutive deaths tripif (opts.yieldDuringPhase) {@@ -397,13 +409,7 @@ 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 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]);+ const { putPageRefs, appends, writtenRefs, appendedUnverified } = await collectPatternOutputs(engine, job.id, cycleSourceId, config.outputSlugPrefix);// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, putPageRefs, appends, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);@@ -454,7 +460,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// edited between gather and here has updated_at > stamp, so the next run// still fires. Zero writes stamps too: the model saw this evidence and// named nothing; re-running it is exactly the spend bug.- await engine.setConfig(evidenceKey, new Date(newestEvidenceMs).toISOString());+ await engine.setConfig(keys.evidence, new Date(newestEvidenceMs).toISOString());return ok(`${writtenRefs.length} pattern page(s) written/updated${appendedNote} (${outcome})`, details);} catch (e) {@@ -884,6 +890,18 @@ async function collectChildPutPageSlugs(.map(slug => ({ slug, source_id: sourceId }));}+/**+ * What a patterns child wrote: its put_page refs, the timeline entries it newly published on other pages under the+ * output prefix (#6302), every changed page as a ref, and the deprecated `appended_unverified` count.+ */+async function collectPatternOutputs(engine: BrainEngine, jobId: number, sourceId: string, outputSlugPrefix: string) {+ const putPageRefs = await collectChildPutPageSlugs(engine, [jobId], sourceId);+ const appends = (await collectChildTimelineAppends(engine, [jobId], sourceId))+ .filter(a => a.slug.startsWith(`${outputSlugPrefix}/`) && !putPageRefs.some(ref => ref.slug === a.slug));+ const writtenRefs = [...putPageRefs, ...[...new Set(appends.map(a => a.slug))].map(slug => ({ slug, source_id: sourceId }))];+ return { putPageRefs, appends, writtenRefs, appendedUnverified: await countChildTimelineAppends(engine, [jobId]) };+}+/** #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 } }diff --git a/src/core/cycle/phase-config-values.ts b/src/core/cycle/phase-config-values.tsindex aa363ab2d0..614c33138d 100644--- a/src/core/cycle/phase-config-values.ts+++ b/src/core/cycle/phase-config-values.ts@@ -16,6 +16,15 @@ export const PROPOSE_TAKES_CALL_TIMEOUT_MIN_MS = 1_000;/** The gateway's default chat timeout; the gateway still races its own (shorter wins). */export const PROPOSE_TAKES_CALL_TIMEOUT_MAX_MS = 300_000;+/** #6297: hours between completed in-cycle patterns runs; 0 turns the cadence off. */+export const PATTERNS_MIN_INTERVAL_KEY = 'dream.patterns.min_interval_hours';+export const PATTERNS_MIN_INTERVAL_DEFAULT_HOURS = 6;+export const PATTERNS_MIN_INTERVAL_MAX_HOURS = 720;+/** #6297: kilobytes of get_page results a patterns child reads in full; 0 turns the budget off. */+export const PATTERNS_CHILD_READ_BUDGET_KEY = 'dream.patterns.child_read_budget_kb';+export const PATTERNS_CHILD_READ_BUDGET_DEFAULT_KB = 200;+export const PATTERNS_CHILD_READ_BUDGET_MAX_KB = 100_000;+interface PhaseConfigSpec {/** Human range, used in the refusal and the stored-value warnings. */expected: string;@@ -33,7 +42,28 @@ const finitePositive = (raw: string): number | null => {return text !== '' && Number.isFinite(n) && n > 0 ? n : null;};+const wholeInRange = (raw: string, max: number): number | null => {+ const text = raw.trim();+ if (!/^\d+$/.test(text)) return null;+ const n = Number(text);+ return n <= max ? n : null;+};+const SPECS: Record<string, PhaseConfigSpec> = {+ [PATTERNS_MIN_INTERVAL_KEY]: {+ expected: `a number of hours from 0 to ${PATTERNS_MIN_INTERVAL_MAX_HOURS} (0 turns the cadence off)`,+ defaultText: String(PATTERNS_MIN_INTERVAL_DEFAULT_HOURS),+ parse(raw) {+ const text = raw.trim();+ const n = Number(text);+ return text !== '' && Number.isFinite(n) && n >= 0 && n <= PATTERNS_MIN_INTERVAL_MAX_HOURS ? n : null;+ },+ },+ [PATTERNS_CHILD_READ_BUDGET_KEY]: {+ expected: `a whole number of kilobytes from 0 to ${PATTERNS_CHILD_READ_BUDGET_MAX_KB} (0 turns the budget off)`,+ defaultText: String(PATTERNS_CHILD_READ_BUDGET_DEFAULT_KB),+ parse: raw => wholeInRange(raw, PATTERNS_CHILD_READ_BUDGET_MAX_KB),+ },[SYNTHESIZE_CONCEPTS_BUDGET_KEY]: {expected: 'a finite number of US dollars above 0',defaultText: String(SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD),diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 8654057e9c..97247267c2 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -355,6 +355,7 @@ export const CODES = {pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },pattern_claims_pending: { class: 'retryable', summary: "An existing pattern page is waiting on the rewrite that de-duplicates its claim sources, so no patterns child was submitted this run.", why: "The patterns child reads existing pattern pages; until their claim records reference one shared reflection list, the pages can overflow the model's window and the run pays for nothing.", fix: { argv: ['gbrain', 'write-requests', '--source', '{source_id}'], consent: [], actor: 'agent', why: 'Lists the write receipts of the source, newest first, so the held rewrites show, read-only.', requires_exclusive: false } },+ patterns_min_interval: { class: 'consent', summary: "An in-cycle dream patterns run was skipped because the partition's last completed patterns run ended less than dream.patterns.min_interval_hours ago; nothing was submitted.", why: 'Every maintenance pass writes new reflections, so the evidence watermark alone re-ran a paid patterns child on each pass. The skip names next_eligible_at; a direct `gbrain dream --phase patterns` or `--once` is not held to the interval, and `gbrain config set dream.patterns.min_interval_hours 0` turns it off.', docs: 'docs/guides/dream-patterns.md#cadence', suggestion: 'Wait for next_eligible_at, or, with the user\'s paid authorization, run `gbrain dream --phase patterns` now.', fix: { argv: ['gbrain', 'dream', '--phase', 'patterns'], consent: ['paid'], actor: 'agent', why: 'A direct run is not held to the cadence; it is a paid model run, so ask the user first.', requires_exclusive: false } },pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },persistence_restart_required: { class: 'host_only', summary: "This gbrain serve's persistence consumer reports restart_required, so it claims no write until the process restarts; `/health?deep=1` answers 503 with this code.", why: "A preparation abandoned past the ceiling (a zombie) or a publication that never settled past its deadline makes the owner stop claiming on every root, because the abandoned work may still hold locks or write files; only a process exit releases it. The deep health probe reports it so a supervisor can restart serve; it never acts on its own (GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS opts into an exit).", docs: 'docs/ENGINES.md#serve-deep-health', suggestion: 'Restart the serve process (for the installed service: systemctl --user restart gbrain-serve; otherwise stop and start it in the foreground); to let a supervisor do it unattended, set GBRAIN_SERVE_RESTART_REQUIRED_EXIT_SECONDS=300 in the serve environment (~/.gbrain/env for the installed service). Then run gbrain sources writer status --json.' },@@ -405,6 +406,7 @@ export const CODES = {question_owner_only: { class: 'host_only', summary: "Pinned questions are owner-private: this connection cannot read private pages (or is slug-fenced or delegated), so the owner runs the command on the brain host.", docs: 'docs/guides/pinned-questions.md#who-can-see-pinned-questions' },queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },+ read_budget_exhausted: { class: 'caller', summary: "A subagent's get_page result came back as a short summary because the job has used its read budget (for the dream patterns child, dream.patterns.child_read_budget_kb).", why: 'A CLI-backed model replays the whole transcript on every turn, so a child that read every page in full filled the model window. The summary keeps the slug, title, type and a short excerpt; writes still work.', docs: 'docs/guides/dream-patterns.md#child-read-budget', suggestion: 'Work from the pages already read and append with add_timeline_entry instead of rewriting a summarized page. An operator who needs more reads raises dream.patterns.child_read_budget_kb (0 turns the budget off).' },receipt_conflict: { class: 'retryable', summary: "The ingestion receipt changed since it was read.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },receipt_fence_changed: { class: 'caller', summary: "The managed owner, topology or source binding changed while the ingestion ran.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },receipt_fence_required: { class: 'host_only', summary: "Ingestion into a managed or bound source needs the worktree owner's fence.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },diff --git a/src/core/minions/handlers/subagent.ts b/src/core/minions/handlers/subagent.tsindex e0fdfcd75d..a7e6865128 100644--- a/src/core/minions/handlers/subagent.ts+++ b/src/core/minions/handlers/subagent.ts@@ -472,7 +472,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {brainId: data.brain_id,allowedSlugPrefixes: data.allowed_slug_prefixes,// #1586: cycle-resolved source scope for tool-call OperationContexts.- sourceId: data.source_id,+ sourceId: data.source_id, readBudgetBytes: data.read_budget_bytes,});const selectedTools = selectAllowedTools(registry, data.allowed_tools);const guardTools = (tools: ToolDef[], deferEmbeds = false) => guardDelegatedTools(engine, config, submitted, ctx.id, tools, deps.toolRegistry !== undefined, deferEmbeds);@@ -538,7 +538,7 @@ export function makeSubagentHandler(deps: SubagentDeps) {brainId: data.brain_id,allowedSlugPrefixes: data.allowed_slug_prefixes,sourceId: data.source_id,- deferEmbeds: true,+ deferEmbeds: true, readBudgetBytes: data.read_budget_bytes,});// Honor allowed_tools EXACTLY like the loop registry — a submitter// that scoped its job read-only must not gain write capability bydiff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex bebf2db39a..ff463ea2d8 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -22,6 +22,7 @@* level; repeats re-derive the same embedding over identical content.*/+import { budgetedPageRead } from './read-budget.ts';import type { BrainEngine } from '../../engine.ts';import type { GBrainConfig } from '../../config.ts';import { operations } from '../../operations.ts';@@ -174,6 +175,8 @@ export interface BuildBrainToolsOpts {sourceId?: string;/** Current remote owner grant; never populated from caller tool arguments. */delegatedAuth?: Pick<AuthInfo, 'clientId' | 'scopes' | 'sourceId' | 'allowedSources' | 'allowedOperations'>;+ /** #6297: byte budget on this job's get_page results (SubagentHandlerData.read_budget_bytes); unset = none. */+ readBudgetBytes?: number;}interface OpContextDeps {@@ -286,6 +289,7 @@ export function buildBrainTools(opts: BuildBrainToolsOpts): ToolDef[] {const output = 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);return output;},};diff --git a/src/core/minions/tools/read-budget.ts b/src/core/minions/tools/read-budget.tsnew file mode 100644index 0000000000..4cb506e5cf--- /dev/null+++ b/src/core/minions/tools/read-budget.ts@@ -0,0 +1,40 @@+/**+ * #6297: a per-job byte budget on a subagent's `get_page` results. Each turn+ * of a CLI-backed model replays the whole transcript, and a dream patterns+ * child that read every existing pattern page in full filled half the model+ * window. Bytes already returned are counted from the job's own+ * tool-execution ledger (so a crash replay keeps its spent budget); a read+ * that would pass the budget comes back as a short summary instead.+ */+import type { BrainEngine } from '../../engine.ts';++/** Characters of body text a summary keeps, at most (less when the budget has less left). */+export const READ_BUDGET_EXCERPT_CHARS = 400;++/** Bytes of `get_page` output this job has already been given. */+async function spentReadBytes(engine: BrainEngine, jobId: number): Promise<number> {+ const [row] = await engine.executeRaw<{ used: number | string | null }>(+ `SELECT COALESCE(sum(octet_length(output::text)), 0) AS used FROM subagent_tool_executions+ WHERE job_id = $1 AND tool_name = 'brain_get_page' AND status = 'complete'`, [jobId]);+ return Number(row?.used ?? 0);+}++/** The read as returned when it fits the budget, else a summary naming the page, the budget and what to do next. */+export async function budgetedPageRead(engine: BrainEngine, jobId: number, budgetBytes: number, slug: unknown, output: unknown): Promise<unknown> {+ const used = await spentReadBytes(engine, jobId);+ const pageBytes = Buffer.byteLength(JSON.stringify(output) ?? '', 'utf8');+ if (used + pageBytes <= budgetBytes) return output;+ const page = (output && typeof output === 'object' ? output : {}) as Record<string, unknown>;+ const body = typeof page.compiled_truth === 'string' ? page.compiled_truth : typeof page.content === 'string' ? page.content : '';+ const room = Math.max(0, Math.min(READ_BUDGET_EXCERPT_CHARS, budgetBytes - used));+ return {+ slug: typeof page.slug === 'string' ? page.slug : slug,+ ...(typeof page.title === 'string' ? { title: page.title } : {}),+ ...(typeof page.type === 'string' ? { type: page.type } : {}),+ truncated: true,+ code: 'read_budget_exhausted',+ read_budget: { limit_bytes: budgetBytes, used_bytes: used, page_bytes: pageBytes },+ ...(room > 0 && body ? { excerpt: body.slice(0, room) } : {}),+ note: 'This job has used its get_page read budget, so the page is summarized. Work from the pages already read; writes still work. To update this page, append with add_timeline_entry instead of rewriting it.',+ };+}diff --git a/src/core/minions/types.ts b/src/core/minions/types.tsindex 947c9210fb..6fd7509627 100644--- a/src/core/minions/types.ts+++ b/src/core/minions/types.ts@@ -589,6 +589,14 @@ export interface SubagentHandlerData {* that predate the field ignore it and keep the strict behavior.*/allow_clean_zero_writes?: boolean;+ /**+ * #6297 — byte budget on this job's `get_page` results (the dream patterns+ * child, `dream.patterns.child_read_budget_kb`). Past it a read returns a+ * short summary instead of the page, so the replayed transcript stays+ * bounded. Counted from the job's own tool-execution ledger, so a crash+ * replay keeps the budget. Trusted field (PROTECTED_JOB_NAMES); unset = no budget.+ */+ read_budget_bytes?: number;/*** #4216 — synthesis execution mode. 'oneshot' = single structured* completion + programmatic validated writes, falling back to the agenticdiff --git a/test/cycle-patterns-cadence.serial.test.ts b/test/cycle-patterns-cadence.serial.test.tsnew file mode 100644index 0000000000..72c78a5566--- /dev/null+++ b/test/cycle-patterns-cadence.serial.test.ts@@ -0,0 +1,145 @@+/**+ * #6297: every maintenance pass writes new reflections, so the #4879 evidence+ * watermark never skipped and each pass paid for a patterns child. An+ * in-cycle run now waits `dream.patterns.min_interval_hours` (default 6, 0+ * off) after the partition's last COMPLETED run; a direct+ * `gbrain dream --phase patterns` and `--once` are not held to it, and the+ * external-reflections partition keeps its own stamp.+ */+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 { resetPgliteState } from './helpers/reset-pglite.ts';+import { withTrustBackfill } from '../src/core/persistence/context.ts';++let childStatus = 'completed';++mock.module('../src/core/ai/gateway.ts', () => ({+ probeChatModel: () => ({ ok: true }),+}));++mock.module('../src/core/cycle/synthesize.ts', () => ({+ loadAllowedSlugPrefixes: async () => ['wiki/personal/patterns/*'],+ loadOutputRoot: async () => 'wiki',+ runSubagentsInline: async () => undefined,+}));++mock.module('../src/core/minions/wait-for-completion.ts', () => ({+ TimeoutError: class TimeoutError extends Error {},+ waitForCompletion: async (_queue: unknown, jobId: number) => ({ id: jobId, status: childStatus }),+ waitForCompletionRenewing: async (_queue: unknown, jobId: number, opts?: { renew?: () => Promise<void> }) => {+ if (opts?.renew) await opts.renew();+ return { id: jobId, status: childStatus };+ },+}));++const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');+const { parsePhaseConfigValue } = await import('../src/core/cycle/phase-config-values.ts');++let engine: PGLiteEngine;+let schemaVersion: string;+let brainDir: string;+let seq = 0;++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-cadence-'));+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(brainDir, { recursive: true, force: true });+});++beforeEach(async () => {+ childStatus = 'completed';+ await resetPgliteState(engine);+ await engine.setConfig('version', schemaVersion);+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');+ for (let i = 0; i < 3; i++) await addReflection();+});++/** A reflection newer than every earlier one, as each maintenance pass writes. */+async function addReflection(tier: string | null = null): Promise<void> {+ seq++;+ const slug = `wiki/personal/reflections/r${seq}`;+ await engine.executeRaw(+ `INSERT INTO pages (slug, type, title, compiled_truth, updated_at) VALUES ($1, 'note', $2, $3, now() + ($4 || ' seconds')::interval)`,+ [slug, `Reflection ${seq}`, `Recurring theme fixture ${seq}.`, String(seq)],+ );+ if (tier) await engine.transaction(tx => withTrustBackfill(tx, () => tx.executeRaw('UPDATE pages SET trust_tier = $2 WHERE slug = $1', [slug, tier])));+}++describe('patterns in-cycle cadence (#6297)', () => {+ test('two in-cycle runs with a new reflection between them: the second is skipped and names the next eligible time', async () => {+ const first = await runPhasePatterns(engine, { brainDir, dryRun: false });+ expect(first.status).toBe('ok');+ await addReflection();+ const second = await runPhasePatterns(engine, { brainDir, dryRun: false });+ expect(second.status).toBe('skipped');+ expect(second.details.reason).toBe('patterns_min_interval');+ expect(second.details.code).toBe('patterns_min_interval');+ expect(second.details.min_interval_hours).toBe(6);+ const last = Date.parse(String(second.details.last_completed_at));+ expect(Date.parse(String(second.details.next_eligible_at))).toBe(last + 6 * 3_600_000);+ expect(second.summary).toContain(String(second.details.next_eligible_at));+ expect((second.details.fix as { argv: string[] }).argv).toEqual(['gbrain', 'dream', '--phase', 'patterns']);+ });++ test('a direct --phase run and --once are not held to the cadence', async () => {+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('ok');+ await addReflection();+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false, direct: true })).status).toBe('ok');+ await addReflection();+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false, once: true })).status).toBe('ok');+ });++ test('the cadence counts from the last completed run, not a failed one', async () => {+ childStatus = 'timeout';+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('fail');+ childStatus = 'completed';+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('ok');+ });++ test('0 turns the cadence off; an elapsed interval runs again', async () => {+ await engine.setConfig('dream.patterns.min_interval_hours', '0');+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('ok');+ await addReflection();+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('ok');+ await engine.setConfig('dream.patterns.min_interval_hours', '6');+ const [stamp] = await engine.executeRaw<{ key: string }>(`SELECT key FROM config WHERE key LIKE 'dream.patterns.last_completed_at.default.%'`);+ await engine.setConfig(stamp!.key, new Date(Date.now() - 7 * 3_600_000).toISOString());+ await addReflection();+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('ok');+ });++ test('the owner pass never throttles the external partition', async () => {+ for (let i = 0; i < 3; i++) await addReflection('external_untrusted');+ const first = await runPhasePatterns(engine, { brainDir, dryRun: false });+ expect(first.status).toBe('ok');+ expect((first.details.external_pass as { status: string }).status).toBe('ok');+ const keys = (await engine.executeRaw<{ key: string }>(`SELECT key FROM config WHERE key LIKE 'dream.patterns.last_completed_at.%' ORDER BY key`)).map(r => r.key);+ expect(keys).toHaveLength(2);+ expect(keys[1]).toBe(`${keys[0]}.external`);+ await engine.executeRaw('DELETE FROM config WHERE key = $1', [keys[1]]);+ await addReflection();+ await addReflection('external_untrusted');+ const second = await runPhasePatterns(engine, { brainDir, dryRun: false });+ expect((second.details.external_pass as { status: string }).status).toBe('ok');+ expect(second.summary).toContain('in-cycle runs wait 6h');+ });++ test('config set accepts the documented ranges only', () => {+ expect(parsePhaseConfigValue('dream.patterns.min_interval_hours', '0')).toBe(0);+ expect(parsePhaseConfigValue('dream.patterns.min_interval_hours', '1.5')).toBe(1.5);+ expect(() => parsePhaseConfigValue('dream.patterns.min_interval_hours', '-1')).toThrow(/min_interval_hours/);+ expect(parsePhaseConfigValue('dream.patterns.child_read_budget_kb', '0')).toBe(0);+ expect(parsePhaseConfigValue('dream.patterns.child_read_budget_kb', '200')).toBe(200);+ expect(() => parsePhaseConfigValue('dream.patterns.child_read_budget_kb', '2.5')).toThrow(/child_read_budget_kb/);+ });+});diff --git a/test/cycle-patterns-evidence-gate.serial.test.ts b/test/cycle-patterns-evidence-gate.serial.test.tsindex 891d41ab55..4be796adb3 100644--- a/test/cycle-patterns-evidence-gate.serial.test.ts+++ b/test/cycle-patterns-evidence-gate.serial.test.ts@@ -67,6 +67,8 @@ beforeEach(async () => {await resetPgliteState(engine);await engine.setConfig('version', schemaVersion);await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');+ // #6297's in-cycle cadence is its own gate (test/cycle-patterns-cadence.serial.test.ts); off here so the watermark is tested alone.+ await engine.setConfig('dream.patterns.min_interval_hours', '0');await seedReflections();});diff --git a/test/cycle-patterns-read-budget.serial.test.ts b/test/cycle-patterns-read-budget.serial.test.tsnew file mode 100644index 0000000000..cb4168c3e8--- /dev/null+++ b/test/cycle-patterns-read-budget.serial.test.ts@@ -0,0 +1,123 @@+/**+ * #6297: a patterns child that read every existing pattern page in full+ * filled half a CLI model's window, because each turn replays the whole+ * transcript. The phase now gives the child a get_page byte budget+ * (`dream.patterns.child_read_budget_kb`, default 200 KB); past it a read+ * comes back as a short summary. The child is scripted the way the subagent+ * handler runs it: the job's own data feeds buildBrainTools, and each call+ * goes through the tool-execution ledger the budget counts from.+ */+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 PAGES = 60;+const PAGE_CHARS = 20_000;++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) => readEveryPatternPage(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 { persistToolExecComplete, persistToolExecPending } = await import('../src/core/minions/handlers/subagent-persistence.ts');++let jobId = 0;++/** The child reads every existing pattern page, as the patterns prompt invites. */+async function readEveryPatternPage(engine: BrainEngine, queueName: string): Promise<void> {+ const [job] = await engine.executeRaw<{ id: number; data: Record<string, unknown> | string }>('SELECT id, data FROM minion_jobs WHERE queue = $1 ORDER BY id DESC LIMIT 1', [queueName]);+ jobId = Number(job!.id);+ const data = (typeof job!.data === 'string' ? JSON.parse(job!.data) : job!.data) as { read_budget_bytes?: number };+ const tools = buildBrainTools({ subagentId: jobId, engine, config: { engine: 'pglite' } as GBrainConfig,+ allowedSlugPrefixes: ['wiki/personal/patterns/*'], sourceId: 'default', readBudgetBytes: data.read_budget_bytes });+ const tool = tools.find(t => t.name === 'brain_get_page')!;+ for (let i = 0; i < PAGES; i++) {+ const input = { slug: `wiki/personal/patterns/theme-${i}` };+ await persistToolExecPending(engine, jobId, 1, i, `toolu_${i}`, tool.name, input);+ const output = await tool.execute(input, { engine, jobId, remote: true });+ await persistToolExecComplete(engine, jobId, 1, i, `toolu_${i}`, 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-read-budget-'));+}, 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');+ for (let i = 1; i <= 3; i++) {+ await importFromContent(engine, `wiki/personal/reflections/r${i}`, `---\ntype: note\ntitle: r${i}\n---\nA recurring theme, take ${i}.\n`, { noEmbed: true, sourceId: 'default' });+ }+ const body = 'A long pattern page with many dated observations. '.repeat(Math.ceil(PAGE_CHARS / 51)).slice(0, PAGE_CHARS);+ for (let i = 0; i < PAGES; i++) {+ await importFromContent(engine, `wiki/personal/patterns/theme-${i}`, `---\ntype: note\ntitle: Theme ${i}\ndream_generated: true\n---\n${body}\n`, { noEmbed: true, sourceId: 'default' });+ }+}, 120_000);++async function readOutputs(): Promise<Array<Record<string, unknown>>> {+ const rows = await engine.executeRaw<{ output: unknown }>('SELECT output FROM subagent_tool_executions WHERE job_id = $1 ORDER BY ordinal', [jobId]);+ return rows.map(r => (typeof r.output === 'string' ? JSON.parse(r.output) : r.output) as Record<string, unknown>);+}++describe('patterns child get_page read budget (#6297)', () => {+ test('60 large pattern pages: the child transcript stays under the default 200 KB budget plus short summaries', async () => {+ const result = await runPhasePatterns(engine, { brainDir, dryRun: false });+ expect(result.status).toBe('ok');+ const outputs = await readOutputs();+ expect(outputs).toHaveLength(PAGES);+ const bytes = outputs.reduce((n, o) => n + Buffer.byteLength(JSON.stringify(o), 'utf8'), 0);+ expect(bytes).toBeLessThan(200 * 1024 + PAGES * 1024);+ expect(outputs[0]!.truncated).toBeUndefined();+ const summarized = outputs.filter(o => o.truncated === true);+ expect(summarized.length).toBeGreaterThan(PAGES / 2);+ expect(summarized[0]).toMatchObject({ code: 'read_budget_exhausted', slug: expect.stringMatching(/^wiki\/personal\/patterns\/theme-/), title: expect.stringMatching(/^Theme /) });+ expect(String(summarized[0]!.note)).toContain('add_timeline_entry');+ }, 120_000);++ test('0 turns the budget off: every page is read in full', async () => {+ await engine.setConfig('dream.patterns.child_read_budget_kb', '0');+ expect((await runPhasePatterns(engine, { brainDir, dryRun: false })).status).toBe('ok');+ const outputs = await readOutputs();+ expect(outputs.filter(o => o.truncated === true)).toHaveLength(0);+ expect(outputs.every(o => String(o.compiled_truth ?? '').length > PAGE_CHARS * 0.9)).toBe(true);+ }, 120_000);+});