Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): size in-cycle patterns runs from the recorded run cost (#6177)

garrytan4fff03c77993
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.md
index e29da96b83..8452e34f90 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. 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`.
-- `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`.
+- `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`.
- `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. 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.
diff --git a/docs/guides/dream-patterns.md b/docs/guides/dream-patterns.md
new file mode 100644
index 0000000000..6fed736285
--- /dev/null
+++ b/docs/guides/dream-patterns.md
@@ -0,0 +1,58 @@
+# Dream patterns
+
+The `patterns` phase of the dream cycle reads your recent reflections and
+writes pattern pages for themes that recur across at least
+`dream.patterns.min_evidence` (default 3) distinct reflections. It runs one
+paid subagent per run. Inside the cycle it is sized to the time the cycle has
+left, so a run that cannot finish is shrunk or skipped before it spends
+anything.
+
+## Settings
+
+| Key | Type | Default | Meaning |
+|---|---|---|---|
+| `dream.patterns.enabled` | boolean | `true` | Turns the phase off (`gbrain dream --phase patterns --once` still forces one run). |
+| `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. |
+
+```bash
+gbrain config set dream.patterns.subagent_timeout_ms 2400000
+```
+
+## Budget sizing
+
+After every child, finished, timed out or failed, the phase records its cost
+in `dream.patterns.last_run`:
+
+```json
+{ "duration_ms": 1801000, "reflections": 100, "at": "2026-10-06T19:00:00.000Z", "outcome": "completed", "budget_skips": 0 }
+```
+
+This is state, not a setting: `gbrain config set` refuses it, and
+`gbrain config unset dream.patterns.last_run` resets it.
+
+An in-cycle run sizes itself from that record:
+
+- With history, it estimates milliseconds per reflection with a 1.25× margin
+ and submits the newest reflections that fit in the remaining budget. A
+ timed-out run counts as a lower bound on cost, so the next run is also at
+ most half its size. A completed run after shrinking restores the estimate.
+- With no history (or after a failed child), it submits a conservative first
+ batch: 25 reflections, or `min_evidence` if larger.
+- When fewer than `min_evidence` reflections fit, the run is skipped with
+ `insufficient_cycle_budget` (`cause: budget_below_recent_runtime`) before
+ anything is submitted. The skip reports the selected and fitting counts.
+- After 3 consecutive budget skips, or when the record is more than 7 days
+ old, the next cycle submits a `min_evidence`-sized probe, so the phase
+ never skips forever.
+
+A direct `gbrain dream --phase patterns` has no cycle deadline: it keeps its
+full size (up to 100 reflections) and records `last_run` like an in-cycle
+run. It is the skip's `fix`; it is a paid run, so ask the user first.
+
+The linear cost model has not been measured on a real paid run yet.
+
+## Changelog
+
+- Fix wave 11: budget sizing from `dream.patterns.last_run` (#6177).
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 4dd9c19a9b..d08ec9210a 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -306,6 +306,16 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
|---|---|---|---|---|---|---|
| The configured storage bucket does not exist. | A capability this request needs is not configured or not reachable on this brain. | A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing. | agent | `gbrain doctor --json` | 1 | no |
+### budget_below_recent_runtime
+
+<a id="budget_below_recent_runtime"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend. | An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed. | Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`. | agent | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/dream-patterns.md#budget-sizing](../../docs/guides/dream-patterns.md#budget-sizing)
+
### budget_unsatisfiable
<a id="budget_unsatisfiable"></a>
diff --git a/llms.txt b/llms.txt
index 6ce9f2e170..a0bd86b8e8 100644
--- a/llms.txt
+++ b/llms.txt
@@ -43,6 +43,7 @@ Repo: https://github.com/garrytan/gbrain
- [docs/guides/quiet-hours.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/quiet-hours.md): Notification hold + timezone-aware delivery.
- [docs/guides/scaling-skills.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/scaling-skills.md): Three-tier architecture for agents with 300+ skills: always-loaded, resolver-routed, and dormant. Per-turn token math, the compact list-format resolver, and the `gbrain doctor` safety net. 306 skills, ~21K tokens freed per turn, zero capability loss.
- [docs/guides/life-chronicle.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/life-chronicle.md): Life Chronicle automatic event extraction (on by default): what qualifies, per-page cost and daily ceiling, privacy, the receipt -> `gbrain dream --phase chronicle` -> `gbrain day` check, skip/failure codes with fixes, opt-out `gbrain config set auto_chronicle false`, history backfill.
+- [docs/guides/dream-patterns.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/dream-patterns.md): Dream patterns phase: settings (min_evidence, subagent timeouts), in-cycle budget sizing from the recorded `dream.patterns.last_run` (first batch, timeout halving, `insufficient_cycle_budget` skip, probe after 3 skips), reset with `gbrain config unset dream.patterns.last_run`.
- [docs/guides/facts-drain.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/facts-drain.md): Automatic facts drain on PGLite (on by default): queued facts-absorb jobs run inside gbrain serve, serve --http and the facts_drain cycle phase with no command; per-run, daily and job-count caps, deferrals that never drop work, doctor facts_drain, opt-out `gbrain config set facts.extraction_enabled false`.
- [docs/guides/push-context.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/push-context.md): Push-based context: the brain volunteers confidence-gated pages from the rolling conversation window. Three channels (ambient reflex, volunteer_context op, gbrain watch), config knobs, and the volunteered-vs-used feedback loop.
- [docs/guides/time-aware-recall.md](https://raw.githubusercontent.com/garrytan/gbrain/master/docs/guides/time-aware-recall.md): Time-aware recall in `gbrain think`: the current date in brain.timezone (or `--reference-date`) and content dates on each page block, with the measured accuracy gain.
diff --git a/scripts/llms-config.ts b/scripts/llms-config.ts
index 6bb7113156..01b0054be2 100644
--- a/scripts/llms-config.ts
+++ b/scripts/llms-config.ts
@@ -202,6 +202,13 @@ export const SECTIONS: DocSection[] = [
path: "docs/guides/life-chronicle.md",
includeInFull: false,
},
+ {
+ title: "docs/guides/dream-patterns.md",
+ description:
+ "Dream patterns phase: settings (min_evidence, subagent timeouts), in-cycle budget sizing from the recorded `dream.patterns.last_run` (first batch, timeout halving, `insufficient_cycle_budget` skip, probe after 3 skips), reset with `gbrain config unset dream.patterns.last_run`.",
+ path: "docs/guides/dream-patterns.md",
+ includeInFull: false,
+ },
{
title: "docs/guides/facts-drain.md",
description:
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 47f5d72415..924d098e69 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1204,6 +1204,17 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }
}
+ // #6177: dream.patterns.last_run is state the patterns phase records, not a setting.
+ if (key === 'dream.patterns.last_run') {
+ const { opError } = await import('../core/ops/contract.ts');
+ (await import('../cli/cli-error.ts')).exitCliError(opError('invalid_params', 'dream.patterns.last_run is recorded by the patterns phase and cannot be set.',
+ 'To forget the recorded run cost, unset it: gbrain config unset dream.patterns.last_run', {
+ why: 'The phase sizes in-cycle runs from the cost of the last child it ran; a hand-written value would mis-size them. Nothing was written.',
+ fix: { argv: ['gbrain', 'config', 'unset', 'dream.patterns.last_run'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Unsetting resets the record; the next in-cycle run submits a conservative first batch.', verify: { argv: ['gbrain', 'config', 'get', 'dream.patterns.last_run'] } },
+ }), 'config');
+ }
+
// #6134: a path in cycle.lint_exclude would never match a basename.
if (key === 'cycle.lint_exclude') {
try { (await import('../core/cycle/lint-fix-setting.ts')).parseCycleLintExclude(value); }
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 57b808e443..6e766630f7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -261,6 +261,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.0.0-wave11', text: 'Facts the sweep extracts from a saved session file are dated when the file was written, not when the sweep ran; facts saved earlier keep their dates.' },
{ since: '0.0.0-wave11', text: '`gbrain waiting --json` and MCP `open_loops` changed shape: loops that name no counterparty are no longer ranked as the person "unknown" but returned in `no_counterparty`, and each group lists at most 5 loops with `loops_omitted` counting the rest (`loop_count` stays the total).' },
{ since: '0.0.0-wave11', text: 'Link extraction no longer types a link to a person, meeting or calendar page as `works_at` (or a meeting/calendar link as `founded`/`invested_in`) from a nearby role phrase; it becomes `mentions`. Existing edges change on re-extraction: `gbrain extract --stale`.' },
+ { since: '0.0.0-wave11', text: 'In-cycle dream patterns runs are sized to the cycle budget from the last run\'s recorded cost (`dream.patterns.last_run`): a first run submits at most 25 reflections, and a run that cannot fit `min_evidence` reflections is skipped as `insufficient_cycle_budget` before any spend; `gbrain dream --phase patterns` still runs at full size.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/patterns-plan.ts b/src/core/cycle/patterns-plan.ts
new file mode 100644
index 0000000000..376fe91135
--- /dev/null
+++ b/src/core/cycle/patterns-plan.ts
@@ -0,0 +1,92 @@
+/**
+ * #6177: size an in-cycle dream patterns run to the cycle budget.
+ *
+ * A patterns child at the 100-reflection cap can need about 30 minutes; an
+ * in-cycle run with less budget spent tokens and was killed. The phase records
+ * each child's cost in the DB-only state key `dream.patterns.last_run`
+ * (`{duration_ms, reflections, at, outcome, budget_skips}`; not a user
+ * setting: `config set` refuses it and `config unset` resets it), and
+ * `planPatternsRun` sizes the next in-cycle run from it before any spend.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.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). */
+export const PATTERNS_FIRST_BATCH = 25;
+/** Margin over the recorded milliseconds per reflection. */
+const MARGIN = 1.25;
+/** Consecutive budget skips after which the next cycle probes. */
+const PROBE_AFTER_SKIPS = 3;
+/** A record older than this no longer predicts cost; the next cycle probes. */
+const STALE_MS = 7 * 86_400_000;
+
+export interface PatternsLastRun {
+ duration_ms: number;
+ /** Reflections the child was given. */
+ reflections: number;
+ /** ISO time the child ended. */
+ at: string;
+ /** `timeout` = the child was still running at its budget, so duration is a lower bound. */
+ outcome: 'completed' | 'timeout' | 'failed';
+ /** In-cycle runs skipped for budget since this child. */
+ budget_skips: number;
+}
+
+export type PatternsPlan =
+ | { kind: 'submit'; n: number; basis: 'full' | 'first_batch' | 'history' | 'probe' }
+ | { kind: 'skip'; reason: 'budget_below_recent_runtime'; n: number };
+
+/**
+ * Pure. `budgetMs` null = a direct run with no cycle deadline: full size.
+ * With history, n = budget / (ms per reflection × 1.25); a timed-out run is a
+ * lower bound on cost, so the next submission is also at most half of it.
+ * With no usable history (none, or a failed child), a conservative first
+ * batch. Three budget skips or a week-old record decay to a min_evidence
+ * probe, so the planner cannot skip forever. Below min_evidence it skips.
+ */
+export function planPatternsRun(input: { budgetMs: number | null; lastRun: PatternsLastRun | null; reflections: number;
+ minEvidence: number; nowMs: number }): PatternsPlan {
+ const { budgetMs, lastRun, reflections, minEvidence } = input;
+ if (budgetMs === null) return { kind: 'submit', n: reflections, basis: 'full' };
+ if (!lastRun || lastRun.outcome === 'failed' || lastRun.reflections <= 0) {
+ return { kind: 'submit', n: Math.min(reflections, Math.max(PATTERNS_FIRST_BATCH, minEvidence)), basis: 'first_batch' };
+ }
+ const age = input.nowMs - Date.parse(lastRun.at);
+ if (lastRun.budget_skips >= PROBE_AFTER_SKIPS || !(age <= STALE_MS)) {
+ return { kind: 'submit', n: Math.min(reflections, minEvidence), basis: 'probe' };
+ }
+ const msPerReflection = Math.max(1, lastRun.duration_ms / lastRun.reflections) * MARGIN;
+ let n = Math.min(reflections, Math.floor(budgetMs / msPerReflection));
+ if (lastRun.outcome === 'timeout') n = Math.min(n, Math.floor(lastRun.reflections / 2));
+ return n < minEvidence ? { kind: 'skip', reason: 'budget_below_recent_runtime', n } : { kind: 'submit', n, basis: 'history' };
+}
+
+/** The recorded last run, or null when unset or unreadable. */
+export async function readPatternsLastRun(engine: BrainEngine): Promise<PatternsLastRun | null> {
+ try {
+ const value = JSON.parse((await engine.getConfig(PATTERNS_LAST_RUN_KEY)) ?? '') as Partial<PatternsLastRun>;
+ if (typeof value.duration_ms !== 'number' || typeof value.reflections !== 'number' || typeof value.at !== 'string') return null;
+ const outcome = value.outcome === 'completed' || value.outcome === 'timeout' ? value.outcome : 'failed';
+ return { duration_ms: value.duration_ms, reflections: value.reflections, at: value.at, outcome, budget_skips: Number(value.budget_skips) || 0 };
+ } catch {
+ return null;
+ }
+}
+
+export async function recordPatternsLastRun(engine: BrainEngine, run: Omit<PatternsLastRun, 'budget_skips'>): Promise<void> {
+ await engine.setConfig(PATTERNS_LAST_RUN_KEY, JSON.stringify({ ...run, budget_skips: 0 })).catch(() => undefined);
+}
+
+export async function recordPatternsBudgetSkip(engine: BrainEngine, lastRun: PatternsLastRun): Promise<void> {
+ await engine.setConfig(PATTERNS_LAST_RUN_KEY, JSON.stringify({ ...lastRun, budget_skips: lastRun.budget_skips + 1 })).catch(() => undefined);
+}
+
+/** The skip's next step: a direct run has no cycle deadline, so it is not sized, and records last_run when it ends. */
+export function patternsBudgetSkipFix(): Action {
+ return {
+ argv: ['gbrain', 'dream', '--phase', 'patterns'], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: 'A direct run is not limited by the cycle budget and records its cost for the next cycle. It is a paid model run, so ask the user first. To forget the recorded cost instead: gbrain config unset dream.patterns.last_run',
+ docs: 'docs/guides/dream-patterns.md#budget-sizing',
+ };
+}
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index bda339ef86..46d12cefb3 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -102,6 +102,7 @@ export interface PatternsPhaseOpts {
* working.
*/
import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';
+import { patternsBudgetSkipFix, planPatternsRun, readPatternsLastRun, recordPatternsBudgetSkip, recordPatternsLastRun } from './patterns-plan.ts';
export { CYCLE_DEADLINE_RESERVE_MS };
/**
@@ -242,6 +243,22 @@ export async function runPhasePatterns(
);
}
+ // #6177: size an in-cycle run to its budget from the recorded cost of recent runs; skip before any spend.
+ const lastRun = await readPatternsLastRun(engine);
+ const plan = planPatternsRun({ budgetMs: opts.deadlineAtMs == null ? null : budgets.timeoutMs, lastRun,
+ reflections: reflections.length, minEvidence: config.minEvidence, nowMs: Date.now() });
+ if (plan.kind === 'skip') {
+ if (lastRun) await recordPatternsBudgetSkip(engine, lastRun);
+ return { phase: 'patterns', status: 'skipped', duration_ms: 0,
+ summary: `patterns: the ${Math.round(budgets.timeoutMs / 1000)}s cycle budget fits ${plan.n} of ${reflections.length} reflections ` +
+ `at the recorded runtime (need ≥${config.minEvidence}); nothing was submitted. Run it outside the cycle: gbrain dream --phase patterns`,
+ details: { reason: 'insufficient_cycle_budget', cause: 'budget_below_recent_runtime', reflections_selected: reflections.length,
+ reflections_submitted: 0, reflections_fit: plan.n, budget_ms: budgets.timeoutMs, last_run: lastRun,
+ fix: patternsBudgetSkipFix(), reset_command: 'gbrain config unset dream.patterns.last_run' } };
+ }
+ const selected = reflections.length;
+ const submitted = reflections.slice(0, plan.n);
+
const queue = new MinionQueue(engine);
// #2050: children drain inline on BOTH engines (see runSubagentsInline),
// so give this job a private per-run queue: the inline drain must never
@@ -259,7 +276,7 @@ export async function runPhasePatterns(
);
const cycleDate = opts.cycleDate ?? await resolveCycleDate(engine);
const data: SubagentHandlerData = {
- prompt: buildPatternsPrompt(reflections, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix, cycleDate),
+ prompt: buildPatternsPrompt(submitted, config.minEvidence, config.sourceSlugPrefix, config.outputSlugPrefix, cycleDate),
model: config.model,
max_turns: 30,
// #4217/CDX-12: a patterns child whose every put_page failed must
@@ -277,7 +294,7 @@ export async function runPhasePatterns(
};
const submitOpts: Partial<MinionJobInput> = {
...(maintenance ? { idempotency_key: `dream:patterns:${digest({ source: maintenance.writer.sourceIncarnation,
- authority: maintenance.writer, reflections: withoutSeats(reflections), model: config.model, output: config.outputSlugPrefix })}` } : {}),
+ authority: maintenance.writer, reflections: withoutSeats(submitted), model: config.model, output: config.outputSlugPrefix })}` } : {}),
max_stalled: 3,
timeout_ms: budgets.timeoutMs,
queue: childQueueName,
@@ -293,6 +310,7 @@ export async function runPhasePatterns(
return skipped('dream_breaker_tripped', refusal);
}
let job: Awaited<ReturnType<typeof queue.add>>;
+ const submittedAt = Date.now();
try {
job = await queue.add('subagent', data as unknown as Record<string, unknown>, submitOpts, {
allowProtectedSubmit: true,
@@ -346,6 +364,10 @@ export async function runPhasePatterns(
}
}
+ // #6177: every child records its cost, timed-out and failed ones included.
+ await recordPatternsLastRun(engine, { duration_ms: Date.now() - submittedAt, reflections: submitted.length, at: new Date().toISOString(),
+ outcome: outcome === 'completed' ? 'completed' : outcome === 'timeout' ? 'timeout' : 'failed' });
+
if (opts.yieldDuringPhase) {
try { await opts.yieldDuringPhase(); } catch { /* best-effort */ }
}
@@ -363,10 +385,10 @@ export async function runPhasePatterns(
const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);
// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.
- const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, reflections, config, cycleSourceId, cycleDate, opts.signal);
+ const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, submitted, config, cycleSourceId, cycleDate, opts.signal);
const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, finalized)
: await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);
- const details = { reflections_considered: reflections.length, patterns_written: finalized.length,
+ const details = { reflections_considered: submitted.length, reflections_selected: selected, plan_basis: plan.basis, patterns_written: finalized.length,
...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held,
child_outcome: outcome, job_id: job.id };
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index b950221cc7..c61cf5ce33 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -60,6 +60,7 @@ export const CODES = {
api_not_enabled: { class: 'host_only', summary: "Google connect credential error: api not enabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },
approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },
autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },
+ budget_below_recent_runtime: { class: 'unavailable', summary: "The cycle's remaining budget fits fewer reflections than dream patterns needs at the recorded runtime, so the in-cycle run was skipped before any spend.", why: 'An in-cycle patterns run is sized from dream.patterns.last_run; a run that cannot finish in the budget would spend tokens and be killed.', docs: 'docs/guides/dream-patterns.md#budget-sizing', suggestion: 'Run `gbrain dream --phase patterns` outside the cycle after the user agrees to the paid run (it is not budget-limited and records its cost), or reset the record with `gbrain config unset dream.patterns.last_run`.' },
benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },
benchmark_empty: { class: 'caller', summary: "The benchmark file has no tasks." },
benchmark_exists: { class: 'caller', summary: "A benchmark already exists at the target path." },
diff --git a/test/cycle-patterns-plan.test.ts b/test/cycle-patterns-plan.test.ts
new file mode 100644
index 0000000000..c8bec4bbfd
--- /dev/null
+++ b/test/cycle-patterns-plan.test.ts
@@ -0,0 +1,123 @@
+/**
+ * #6177 — in-cycle dream patterns runs are sized to the cycle budget from the
+ * recorded cost of recent runs (`dream.patterns.last_run`), so a run that
+ * cannot finish is shrunk or skipped before any spend.
+ *
+ * Protects: a first run with no history submits a conservative batch;
+ * consecutive timed-out cycles shrink the submission each time and stop
+ * before spending once below min_evidence; three budget skips or a stale
+ * record decay to a min_evidence-sized probe; a successful run after
+ * shrinking restores the estimate; direct runs keep their full size; every
+ * child (failed ones included) records last_run.
+ * Fails when: the planner ignores history, never decays, or a skip spends.
+ * Seams: planPatternsRun is pure; the phase cases stop before the model call
+ * (budget skip) or use a fake key whose child dies immediately.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, 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 { runPhasePatterns } from '../src/core/cycle/patterns.ts';
+import { PATTERNS_LAST_RUN_KEY, planPatternsRun, type PatternsLastRun } from '../src/core/cycle/patterns-plan.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { __setChatTransportForTests, resetGateway } from '../src/core/ai/gateway.ts';
+
+const MIN = 60_000;
+const NOW = Date.parse('2026-10-06T12:00:00Z');
+const run = (over: Partial<PatternsLastRun>): PatternsLastRun =>
+ ({ duration_ms: 30 * MIN, reflections: 100, at: new Date(NOW - 3_600_000).toISOString(), outcome: 'completed', budget_skips: 0, ...over });
+
+describe('planPatternsRun', () => {
+ test('a first run with no history submits a conservative batch', () => {
+ expect(planPatternsRun({ budgetMs: 28 * MIN, lastRun: null, reflections: 100, minEvidence: 3, nowMs: NOW })).toMatchObject({ kind: 'submit', n: 25, basis: 'first_batch' });
+ expect(planPatternsRun({ budgetMs: 28 * MIN, lastRun: null, reflections: 100, minEvidence: 40, nowMs: NOW })).toMatchObject({ n: 40 });
+ expect(planPatternsRun({ budgetMs: 28 * MIN, lastRun: null, reflections: 10, minEvidence: 3, nowMs: NOW })).toMatchObject({ n: 10 });
+ });
+
+ test('history sizes the run with a 1.25x margin', () => {
+ expect(planPatternsRun({ budgetMs: 28 * MIN, lastRun: run({}), reflections: 100, minEvidence: 3, nowMs: NOW }))
+ .toEqual({ kind: 'submit', n: 74, basis: 'history' });
+ });
+
+ test('consecutive timeouts shrink each submission, then skip before spending below min_evidence', () => {
+ const sizes: number[] = [];
+ let last = run({ outcome: 'timeout', reflections: 100, duration_ms: 28 * MIN });
+ for (let i = 0; i < 6; i++) {
+ const plan = planPatternsRun({ budgetMs: 28 * MIN, lastRun: last, reflections: 100, minEvidence: 8, nowMs: NOW });
+ if (plan.kind === 'skip') { expect(plan.reason).toBe('budget_below_recent_runtime'); break; }
+ sizes.push(plan.n);
+ last = run({ outcome: 'timeout', reflections: plan.n, duration_ms: 28 * MIN });
+ }
+ expect(sizes).toEqual([50, 25, 12]);
+ });
+
+ test('three budget skips, or a record older than 7 days, decay to a min_evidence probe', () => {
+ const tooSlow = run({ duration_ms: 60 * MIN, reflections: 10 });
+ expect(planPatternsRun({ budgetMs: 10 * MIN, lastRun: tooSlow, reflections: 100, minEvidence: 3, nowMs: NOW }).kind).toBe('skip');
+ expect(planPatternsRun({ budgetMs: 10 * MIN, lastRun: { ...tooSlow, budget_skips: 3 }, reflections: 100, minEvidence: 3, nowMs: NOW }))
+ .toEqual({ kind: 'submit', n: 3, basis: 'probe' });
+ expect(planPatternsRun({ budgetMs: 10 * MIN, lastRun: { ...tooSlow, at: new Date(NOW - 8 * 86_400_000).toISOString() }, reflections: 100, minEvidence: 3, nowMs: NOW }))
+ .toEqual({ kind: 'submit', n: 3, basis: 'probe' });
+ });
+
+ test('a successful run after shrinking restores the estimate', () => {
+ expect(planPatternsRun({ budgetMs: 28 * MIN, lastRun: run({ reflections: 12, duration_ms: 3 * MIN }), reflections: 100, minEvidence: 8, nowMs: NOW }))
+ .toEqual({ kind: 'submit', n: 89, basis: 'history' });
+ });
+
+ test('a direct run (no cycle budget) keeps its full size', () => {
+ expect(planPatternsRun({ budgetMs: null, lastRun: run({ outcome: 'timeout' }), reflections: 100, minEvidence: 3, nowMs: NOW }))
+ .toEqual({ kind: 'submit', n: 100, basis: 'full' });
+ });
+});
+
+describe('runPhasePatterns budget sizing (#6177)', () => {
+ let engine: PGLiteEngine;
+ let schemaVersion: string;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_url: '' });
+ await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version')) ?? '7';
+ }, 60_000);
+ afterAll(async () => { await engine.disconnect(); resetGateway(); });
+ afterEach(() => { resetGateway(); });
+ beforeEach(async () => {
+ resetGateway();
+ __setChatTransportForTests(null);
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+ for (let i = 0; i < 5; i++) {
+ await engine.executeRaw(`INSERT INTO pages (slug, type, title, compiled_truth) VALUES ($1, 'note', $2, $3)`,
+ [`wiki/personal/reflections/2026-10-0${i + 1}-reflection`, `Reflection ${i + 1}`, `Recurring theme fixture ${i + 1}.`]);
+ }
+ });
+ const jobs = async () => (await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM minion_jobs WHERE name = 'subagent'`))[0].n;
+
+ test('a budget below the recent runtime skips before any submit and counts the skip', async () => {
+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-plan-'));
+ try {
+ await engine.setConfig(PATTERNS_LAST_RUN_KEY, JSON.stringify(run({ duration_ms: 60 * MIN, reflections: 5, at: new Date().toISOString() })));
+ const result = await withEnv({ ANTHROPIC_API_KEY: 'sk-ant-test' }, () =>
+ runPhasePatterns(engine, { brainDir, dryRun: false, deadlineAtMs: Date.now() + 15 * MIN }));
+ expect(result.status).toBe('skipped');
+ expect(result.details).toMatchObject({ reason: 'insufficient_cycle_budget', cause: 'budget_below_recent_runtime',
+ reflections_selected: 5, reflections_submitted: 0 });
+ expect((result.details.fix as { argv: string[] }).argv).toEqual(['gbrain', 'dream', '--phase', 'patterns']);
+ expect(await jobs()).toBe(0);
+ expect(JSON.parse((await engine.getConfig(PATTERNS_LAST_RUN_KEY))!).budget_skips).toBe(1);
+ } finally { rmSync(brainDir, { recursive: true, force: true }); }
+ });
+
+ test('a child that ends without completing still records last_run', async () => {
+ const brainDir = mkdtempSync(join(tmpdir(), 'gbrain-patterns-plan-'));
+ try {
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-ant-test' }, () => runPhasePatterns(engine, { brainDir, dryRun: false }));
+ const last = JSON.parse((await engine.getConfig(PATTERNS_LAST_RUN_KEY)) ?? 'null') as PatternsLastRun;
+ expect(last).toMatchObject({ reflections: 5, outcome: 'failed', budget_skips: 0 });
+ expect(last.duration_ms).toBeGreaterThanOrEqual(0);
+ } finally { rmSync(brainDir, { recursive: true, force: true }); }
+ }, 60_000);
+});