Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(patterns): count timeline appends as appended_unverified (#6302 Part A)
time-attack9ceeed3f7ab8
diff --git a/docs/architecture/key-files/core-cycle-continued.md b/docs/architecture/key-files/core-cycle-continued.mdindex 33f6d88435..ddeb012035 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`. #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.-- `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`.+- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still stamps. Managed local evidence is source-incarnation-scoped and live/non-private; unchanged evidence coalesces the admitted child request instead of inventing a remote maintenance grant. Maintenance runs (the only keyed patterns runs) consult the paid-loop breaker before submission and skip with `dream_breaker_tripped`. A managed grounding publish or provenance stamp that is accepted-but-pending or rolled back by admission contention is held (`publishOrHold`): a held page is not provenance-stamped, it is left out of `patterns_written` and of `verifyMaintenanceOutputs` (only for refs in the cycle's own source, so a ref in another source is always verified), `publish_deferred` counts held pages, the phase returns `warn`, and the evidence watermark stays unstamped so the next cycle retries; other publication errors still fail. `groundPatternPages` holds only when its caller passes the `heldSlugs` set; direct callers keep the throwing behavior. Pages the child wrote under `dream.patterns.output_slug_prefix` get the dream-output identity stamp (`dream_generated`, `dream_cycle_date`, `dream_created_cycle_date`) before the reverse-write: through `stampMaintenancePage` on a managed brain, through `stampDreamProvenance` (`dream-provenance.ts`) otherwise. A pattern page also gets `seat` when every input reflection carries the same seat, and none otherwise; the managed submission key digests the reflections without their seats. Quote grounding (`groundPatternPages`, `dream.quote_verify`, default on): right after the subagent's writes and before provenance stamping, pattern pages are checked against the full reflection pages with `verifyBody(…, { checks: 'quotes' })`; failing units move to frontmatter `unverified_claims`, `quote_verified_at` marks the page, and pages a crashed run left without it are verified on the next run. Write-back goes through `publishMaintenancePage` on managed brains, else `importFromContent`. Phase details carry `quote_verify` counts. Pinned by `test/cycle-patterns-quote-verify.test.ts`. #6177: `cycle/patterns-plan.ts` — every child records `dream.patterns.last_run` (`{duration_ms, reflections, at, outcome, budget_skips}`, DB-only state; `config set` refuses it, `config unset` resets it) and pure `planPatternsRun` sizes an in-cycle run from it (1.25× margin; a timeout halves the next submission; no usable history → first batch of max(25, min_evidence); 3 budget skips or a 7-day-old record → a min_evidence probe; below min_evidence → skip `insufficient_cycle_budget` with `cause: budget_below_recent_runtime` before any submit); the newest n reflections are submitted; direct runs (no deadline) keep full size. Guide: `docs/guides/dream-patterns.md`; tests `test/cycle-patterns-plan.test.ts`. Quarantined claim records store the run's reflection list once per page in `unverified_claim_sources` and reference it (`cycle/pattern-claim-sources.ts`: `withClaimSources`, `resolveClaimSources` recovers every path); before submitting the child the phase de-duplicates pages still carrying inline lists (`dedupePatternClaimSources`, frontmatter-only maintenance writes) and skips as `pattern_claims_pending`, with no child and no model call, while any rewrite is held (`test/cycle-patterns-quote-verify.test.ts`, `test/managed-maintenance.test.ts`). #5575 ENG-3 partition: `gatherReflections` reads each reflection's `trust_tier` (`ReflectionRef.taint`, never in the submission key); `runPhasePatterns` runs the owner pass (`runPatternsPass`) over every non-external reflection and, when the external_untrusted reflections reach `min_evidence` on their own, a separate pass with watermark `<evidence key>.external`; `details.reflections_external`, `details.external_pass`, and `patterns_written` sums both. Each pass's outputs are written back (grounding publish or `importFromContent`, provenance stamp) at `patternsDerivation(submitted)` with edges to that pass's reflections. Pinned by `test/trust-taint-dream.test.ts`. #6302 Part A [R17]: completed `brain_add_timeline_entry` calls of the child are counted (`countChildTimelineAppends`) and reported as `details.appended_unverified` and in the summary; they get no quote verification or provenance stamp (Part B, grounding appended entries, is deferred). #6296: `recordPatternsLastRun` maps a `dead` child whose error is `timeout exceeded` / `wall-clock timeout exceeded` to `timeout`.- `src/core/cycle/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. #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. Pinned by `test/trust-taint-dream.test.ts`.diff --git a/docs/guides/dream-patterns.md b/docs/guides/dream-patterns.mdindex f56b705973..df442edd52 100644--- a/docs/guides/dream-patterns.md+++ b/docs/guides/dream-patterns.md@@ -62,4 +62,7 @@ slowly than the reflection count and halving may take several cycles to fit.- Fix wave 11: budget sizing from `dream.patterns.last_run` (#6177).- Fix wave 13: a child stopped at its own timeout records `timeout`, so the- next plan halves (#6296).+ next plan halves (#6296). Timeline entries a child appends with+ `add_timeline_entry` are counted in the phase result as+ `appended_unverified`; unlike pages written with `put_page`, they are not+ quote-verified or provenance-stamped yet (#6302).diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex aec9544449..aada7543d2 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -398,6 +398,8 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// the reverse-write below dual-writes files).throwIfAborted(opts.signal, '[dream] patterns output');const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);+ // #6302 Part A [R17]: timeline appends are counted and reported, never quote-verified or provenance-stamped.+ const appendedUnverified = await countChildTimelineAppends(engine, [job.id]);// #6052: `finalized` leaves out outputs whose managed publication is held (pending or contended); `held` counts them.const { quoteVerify, finalized, held } = await stampPatternOutputs(engine, maintenance, writtenRefs, submitted, derivation, config, cycleSourceId, cycleDate, opts.signal);@@ -405,14 +407,15 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con: await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);const details = { reflections_considered: submitted.length, reflections_selected: selected, plan_basis: plan.basis, patterns_written: finalized.length,...(quoteVerify ? { quote_verify: quoteVerify } : {}), reverse_write_count: reverseWriteCount, publish_deferred: held,- child_outcome: outcome, job_id: job.id };+ appended_unverified: appendedUnverified, child_outcome: outcome, job_id: job.id };+ const appendedNote = appendedUnverified > 0 ? `; ${appendedUnverified} timeline entr${appendedUnverified === 1 ? 'y' : 'ies'} appended (unverified)` : '';// #2782: the phase status must reflect the child outcome. Pre-fix this// returned status:ok even when the subagent timed out (e.g. no// subagent-capable worker slot free for the whole wait window) and zero// pattern pages were written — a silent no-op for days.if (outcome !== 'completed') {- if (finalized.length === 0) {+ if (finalized.length === 0 && appendedUnverified === 0) {return {phase: 'patterns',status: 'fail',@@ -434,13 +437,13 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, conphase: 'patterns',status: 'warn',duration_ms: 0,- summary: `${finalized.length} pattern page(s) written but subagent job ${job.id} ended '${outcome}'`,+ summary: `${finalized.length} pattern page(s) written${appendedNote} but subagent job ${job.id} ended '${outcome}'`,details,};}// A held output is unfinished: warn and leave the evidence watermark unstamped so the next cycle retries.if (held > 0) return { phase: 'patterns', status: 'warn', duration_ms: 0, details,- summary: `${finalized.length} pattern page(s) written; ${held} publication(s) held by the writer (pending or contended), retried next cycle` };+ summary: `${finalized.length} pattern page(s) written${appendedNote}; ${held} publication(s) held by the writer (pending or contended), retried next cycle` };// #4879: stamp the EVIDENCE watermark (not now()) only on a completed// child — fail/warn/timeout above must retry next tick. A reflection@@ -449,7 +452,7 @@ async function runPatternsPass(engine: BrainEngine, opts: PatternsPhaseOpts, con// named nothing; re-running it is exactly the spend bug.await engine.setConfig(evidenceKey, new Date(newestEvidenceMs).toISOString());- return ok(`${writtenRefs.length} pattern page(s) written/updated (${outcome})`, details);+ return ok(`${writtenRefs.length} pattern page(s) written/updated${appendedNote} (${outcome})`, details);} catch (e) {return failed(makeError('InternalError', 'PATTERNS_PHASE_FAIL',e instanceof Error ? (e.message || 'patterns phase threw') : String(e)));@@ -796,6 +799,17 @@ async function collectChildPutPageSlugs(.map(slug => ({ slug, source_id: sourceId }));}+/** Completed `brain_add_timeline_entry` calls of the given children (#6302 Part A). */+async function countChildTimelineAppends(engine: BrainEngine, childIds: number[]): Promise<number> {+ if (childIds.length === 0) return 0;+ const [row] = await engine.executeRaw<{ n: number }>(+ `SELECT count(*)::int AS n FROM subagent_tool_executions+ WHERE job_id = ANY($1::int[]) AND tool_name = 'brain_add_timeline_entry' AND status = 'complete'`,+ [childIds],+ );+ return Number(row?.n ?? 0);+}+// ── Reverse-write ────────────────────────────────────────────────────import { validateSourceId } from '../utils.ts';@@ -923,6 +937,7 @@ function makeError(cls: string, code: string, message: string, hint?: string): P// source-scoping contract (#1586) without driving a whole dream cycle.// Mirrors synthesize.ts's `__testing` block.export const __testing = {+ countChildTimelineAppends,gatherReflections,collectChildPutPageSlugs,reverseWriteRefs,diff --git a/test/cycle-patterns-source-scope.test.ts b/test/cycle-patterns-source-scope.test.tsindex d7cf56f062..42b4edb916 100644--- a/test/cycle-patterns-source-scope.test.ts+++ b/test/cycle-patterns-source-scope.test.ts@@ -24,7 +24,7 @@ import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { __testing } from '../src/core/cycle/patterns.ts';-const { collectChildPutPageSlugs, reverseWriteRefs } = __testing;+const { collectChildPutPageSlugs, countChildTimelineAppends, reverseWriteRefs } = __testing;const SOURCE_ID = 'coast';const SLUG = 'wiki/personal/patterns/a-pattern';@@ -152,3 +152,23 @@ describe('#1586: the patterns phase scopes its writes to the cycle source', () =}});});++describe('#6302 Part A: timeline appends are counted, never stamped', () => {+ test('completed add_timeline_entry calls count as appended_unverified; put_page refs are unchanged', async () => {+ const db = (engine as any).db;+ await db.exec(`+ INSERT INTO minion_jobs (submission_authority, id, queue, name, data, status)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 2002, 'default', 'subagent', '{}'::jsonb, 'completed')+ ON CONFLICT (id) DO NOTHING;+ `);+ for (const [i, status] of (['complete', 'complete', 'failed'] as const).entries()) {+ await db.query(+ `INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, status, input)+ VALUES (2002, $1, $2, 'brain_add_timeline_entry', $3, $4::jsonb)`,+ [i, `tool_t${i}`, status, JSON.stringify({ slug: SLUG, date: '2026-10-01', summary: `recurring theme ${i}` })],+ );+ }+ expect(await countChildTimelineAppends(engine as any, [2002])).toBe(2);+ expect(await collectChildPutPageSlugs(engine as any, [2002], SOURCE_ID)).toEqual([]);+ });+});