Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(propose_takes): skip the dream cycle's own output (#5212)
time-attack4ad1414c053a
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.mdindex be220576e3..f5c501482e 100644--- a/docs/architecture/key-files/hindsight.md+++ b/docs/architecture/key-files/hindsight.md@@ -22,7 +22,7 @@ round-trip suite (CHECK admits unresolvable+NULL, still rejects partial+true andunresolvable+true|false, pre-v80 NULL/NULL rows survive).- `src/core/cycle/base-phase.ts` — abstract `BaseCyclePhase` class. Enforces `sourceScopeOpts(ctx)` threading at the type level; rules out the source-isolation leak class structurally for every new phase. Inherits source-scope, budget meter, error envelope, progress reporter. propose_takes / grade_takes / calibration_profile all extend it. `run()` honors dry-run for every subclass at once: when `opts.dryRun` or `ctx.dryRun === true`, it returns `status: 'skipped'` / `reason: 'no_dry_run_support'` before `process()` (no LLM calls, no take_proposals / take_grade_cache / calibration_profiles writes) — the same skip shape extract and resolve_symbol_edges use; runCycle threads `dryRun` into all three call sites. The ONE home of `CYCLE_DEADLINE_RESERVE_MS` (60s carved out of the enclosing job's remaining wall-clock — wait-poll + worker force-evict grace + cleanup headroom; patterns.ts re-exports it) and of `BasePhaseOpts.deadlineAtMs` (the enclosing minion job's absolute deadline, threaded via runCycle; null/unset for direct `gbrain dream` callers — phases then fall back to their derived defaults).-- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`. `dream.propose_takes.call_timeout_ms` (whole ms 1000..300000; `config set` refuses others, a stored out-of-range value is clamped and a non-number ignored, each with a named-key phase warning) replaces the output-cap scaling for every extractor call, held to the phase time left (never below 90 s); a call its own bound stops fails per page with an error naming the key. Pinned by `test/propose-takes-config-max-tokens.test.ts` + `test/propose-takes-truncation.test.ts`.+- `src/core/cycle/propose-takes.ts` — LLM scans markdown prose, proposes gradeable claims to the `take_proposals` queue. Candidate discovery excludes `extract_receipt` pages before the LLM call so the phase never re-ingests its own operational receipts; nullable legacy page types remain eligible. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. Fence-dedup: existing canonical takes passed to the extractor as context. Opt-in `dream.propose_takes.attribution_rules=true` adds `EXTRACT_TAKES_ATTRIBUTION_RULES` (withdrawn claims, assistant-authored judgments not attributed to the user) under prompt version suffix `+attribution5425`; off by default because it measured lower cat15 recall. Ships a stub prompt; tuned prompt arrives via the synthetic corpus build. Per-page extractor failures log a warning and continue, but a whole-run condition (per `classifyGlobalLlmError` in `src/core/ai/errors.ts`) breaks the page loop with a single combined warning line, sets `aborted_global_error`, and records a halt in the rollup — auth/billing on the first hit, bare rate_limit only after `RATE_LIMIT_HALT_STREAK` (3) consecutive hits (a successful call resets the streak). Status: `fail` when the halt happened with ZERO successful extractor calls (the whole LLM lane is down), otherwise any warnings fold into `warn` + ` (N warning(s))` summary suffix, so swallowed failures can't read as a clean `ok`. `llm_calls_succeeded`/`llm_calls_failed`/`halted` land in details. The phase wall-clock deadline is DERIVED, never a literal (a literal equal to the autopilot-cycle handler anchor, with non-co-started clocks, would make the clean `deadline_hit` partial-completion path structurally unreachable): explicit `opts.deadlineMs` wins (test seam), else `resolveProposeTakesDeadlineMs(deadlineAtMs, now)` = `PHASE_DEADLINE_FRACTION_OF_JOB` (0.8, headroom for grade_takes + calibration_profile which run after it with no deadline of their own) × (remaining job budget − `CYCLE_DEADLINE_RESERVE_MS`), clamped to the fallback (0.8 × the `autopilot-cycle` entry in `HANDLER_DEFAULT_TIMEOUT_MS` — a missing anchor throws at module LOAD, failing the whole cycle visibly). A fractioned value under `MIN_PROPOSE_TAKES_BUDGET_MS` (2 min) resolves to null and the phase returns an honest `skipped` with `reason: 'insufficient_cycle_budget'` (after the cheap provider probe, before any rollup/DB write — records neither a halt nor a completed round; next cycle retries with a fresh budget). Pinned by `test/propose-takes.test.ts` + `test/propose-takes-per-claim.test.ts` + `test/cycle-phase-deadline-drift.test.ts`. The kind vocabulary is `TAKE_KIND_VALUES` imported from `src/core/takes-fence.ts` (the fence enum — no hand-copied set); an unknown kind maps through the legacy-kind table, else `take`. `dream.propose_takes.call_timeout_ms` (whole ms 1000..300000; `config set` refuses others, a stored out-of-range value is clamped and a non-number ignored, each with a named-key phase warning) replaces the output-cap scaling for every extractor call, held to the phase time left (never below 90 s); a call its own bound stops fails per page with an error naming the key. Pinned by `test/propose-takes-config-max-tokens.test.ts` + `test/propose-takes-truncation.test.ts`. #5212: `listCandidatePages` also skips the dream cycle's own output by its writer stamps (`dream_generated = true`, `extracted_by LIKE 'extract_atoms%'`, `synthesized_by LIKE 'synthesize_concepts%'`), pinned on PGLite (`test/propose-takes-per-claim.test.ts`) and Postgres (`test/e2e/propose-takes-jsonb-postgres.test.ts`).- `src/core/cycle/grade-takes.ts` — walks unresolved takes older than 6 months, retrieves evidence, asks judge model, caches verdict. Auto-resolve DISABLED by default. Conservative thresholds: >=0.95 single OR >=0.85 ensemble 3/3 unanimous. `aggregateEnsemble` reuses the cross-modal substrate; fires on the borderline 0.6-0.95 band. Writes to `take_grade_cache`. Same global-error posture as propose-takes: a judge failure that classifies as a whole-run condition breaks the take loop with `aborted_global_error` (auth/billing first hit; rate_limit after 3 consecutive takes; `fail` status when zero judge calls succeeded, else `warn` + warning count; `judge_calls_succeeded`/`judge_calls_failed`/`halted` in details). Rejected ensemble judges are classified the same way — `Promise.allSettled` never flattens a revoked key or exhausted spend limit into a silent null verdict. Per-take auto-apply failures stay per-take.- `src/core/cycle/calibration-profile.ts` — aggregates resolved takes into 2-4 narrative pattern statements + active bias tags. Voice-gated via `gateVoice()`. Cold-brain skip when <5 resolved. Writes to `calibration_profiles` with audit columns (`voice_gate_passed`, `voice_gate_attempts`, `grade_completion`).- `src/core/calibration/voice-gate.ts` — single `gateVoice()` function, mode parameter (`pattern_statement` | `nudge` | `forecast_blurb` | `dashboard_caption` | `morning_pulse`). 2 regens then template fallback from `src/core/calibration/templates.ts`. Haiku judge with mode-specific rubrics; all rubrics structurally forbid clinical/preachy voice.diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex de348e7edd..ef410f7ee9 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -296,6 +296,10 @@ async function listCandidatePages(const where = ['deleted_at IS NULL',"type IS DISTINCT FROM 'extract_receipt'",+ // #5212: never propose takes from the dream cycle's own output.+ "COALESCE(frontmatter->>'dream_generated', '') <> 'true'",+ "COALESCE(frontmatter->>'extracted_by', '') NOT LIKE 'extract_atoms%'",+ "COALESCE(frontmatter->>'synthesized_by', '') NOT LIKE 'synthesize_concepts%'",];const params: unknown[] = [];if (scope.sourceIds && scope.sourceIds.length > 0) {diff --git a/test/e2e/propose-takes-jsonb-postgres.test.ts b/test/e2e/propose-takes-jsonb-postgres.test.tsindex 976e92ffb5..a90b1b2888 100644--- a/test/e2e/propose-takes-jsonb-postgres.test.ts+++ b/test/e2e/propose-takes-jsonb-postgres.test.ts@@ -135,4 +135,21 @@ describeIfDB('propose_takes dedup_against_fence_rows JSONB — Postgres regressiexpect(tomb[0]!.kind).toBe('array');expect(tomb[0]!.first_claim).toBe('Cities send messages');});++ test('the dream cycle\'s own output is never a candidate: JSONB predicates on Postgres (#5212)', async () => {+ const own: Array<[string, string, Record<string, unknown>]> = [+ ['wiki/personal/reflections/2026-10-01-dream', 'note', { dream_generated: true }],+ ['atoms/acme-example-claim', 'atom', { extracted_by: 'extract_atoms-v0.41.2.1' }],+ ['concepts/founder-mode', 'concept', { synthesized_by: 'synthesize_concepts-v1' }],+ ];+ for (const [slug, type, frontmatter] of own) {+ await engine.putPage(slug, { title: slug, type: type as never, compiled_truth: 'A strong claim the dream cycle wrote.', frontmatter, timeline: '' });+ }+ await engine.putPage('wiki/essays/human-thesis', { title: 'Human thesis', type: 'analysis' as never, compiled_truth: 'A claim a person wrote.', frontmatter: { synthesized_by: null }, timeline: '' });+ const scanned: string[] = [];+ const result = await runPhaseProposeTakes(buildCtx(engine), { extractor: async ({ pagePath }) => { scanned.push(pagePath); return []; }, pageLimit: 50 });+ expect(result.error?.message ?? '').toBe('');+ expect(scanned).toContain('wiki/essays/human-thesis');+ for (const [slug] of own) expect(scanned).not.toContain(slug);+ });});diff --git a/test/propose-takes-per-claim.test.ts b/test/propose-takes-per-claim.test.tsindex ff4a87616f..312dd512c1 100644--- a/test/propose-takes-per-claim.test.ts+++ b/test/propose-takes-per-claim.test.ts@@ -84,6 +84,22 @@ describe('#2138 per-claim proposal idempotency', () => {expect((result.details as Record<string, unknown>).pages_scanned).toBe(1);});+ test('skips the dream cycle\'s own output: dream-generated, atom and concept pages (#5212)', async () => {+ await putThesis();+ const own: Array<[string, string, Record<string, unknown>]> = [+ ['wiki/personal/reflections/2026-10-01-dream', 'note', { dream_generated: true }],+ ['atoms/acme-example-claim', 'atom', { extracted_by: 'extract_atoms-v0.41.2.1' }],+ ['concepts/founder-mode', 'concept', { synthesized_by: 'synthesize_concepts-v1' }],+ ];+ for (const [slug, type, frontmatter] of own) {+ await engine.putPage(slug, { title: slug, type: type as never, compiled_truth: 'A strong claim the dream cycle wrote.', frontmatter, timeline: '' });+ }+ const scannedPages: string[] = [];+ const result = await runPhaseProposeTakes(context(), { extractor: async ({ pagePath }) => { scannedPages.push(pagePath); return []; } });+ expect(scannedPages).toEqual(['wiki/essays/thesis']);+ expect((result.details as Record<string, unknown>).pages_scanned).toBe(1);+ });+test('keeps distinct claims, drops repeated claim, then page-cache hits', async () => {await putThesis();const result = await runPhaseProposeTakes(context(), { extractor: proposals });