Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cycle): skip extract receipts in propose_takes candidate discovery (#4621) (#4644)

arisgysel-design1e7093aca54d
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 72cb837087..d1a28d507f 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -515,7 +515,7 @@ round-trip suite (CHECK admits unresolvable+NULL, still rejects partial+true and
unresolvable+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; closes 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. 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, #4168) 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. 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. 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 (#4168 — the old 30-min literal was bit-identical to the autopilot-cycle handler anchor with non-co-started clocks, making the clean `deadline_hit` partial-completion path structurally unreachable in production): 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/cycle-phase-deadline-drift.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. 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 (#4168 — the old 30-min literal was bit-identical to the autopilot-cycle handler anchor with non-co-started clocks, making the clean `deadline_hit` partial-completion path structurally unreachable in production): 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`.
- `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` no longer 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.ts
index 93f44aab4d..da964615c2 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -235,7 +235,10 @@ async function listCandidatePages(
scope: ScopedReadOpts,
limit: number,
): Promise<ProposeTakesPageRow[]> {
- const where = ['deleted_at IS NULL'];
+ const where = [
+ 'deleted_at IS NULL',
+ "type IS DISTINCT FROM 'extract_receipt'",
+ ];
const params: unknown[] = [];
if (scope.sourceIds && scope.sourceIds.length > 0) {
params.push(scope.sourceIds);
diff --git a/test/propose-takes-per-claim.test.ts b/test/propose-takes-per-claim.test.ts
index 79e551fb99..ff4a87616f 100644
--- a/test/propose-takes-per-claim.test.ts
+++ b/test/propose-takes-per-claim.test.ts
@@ -62,6 +62,28 @@ async function putThesis(): Promise<void> {
}
describe('#2138 per-claim proposal idempotency', () => {
+ test('skips extract receipts before invoking the extractor (#4621)', async () => {
+ await putThesis();
+ await engine.putPage('extracts/2026-08-27/takes.proposed/default/propose/round-single', {
+ title: 'propose_takes receipt',
+ type: 'extract_receipt',
+ compiled_truth: 'Operational receipt with no gradeable claims.',
+ frontmatter: { type: 'extract_receipt', dream_generated: true },
+ timeline: '',
+ });
+
+ const scannedPages: string[] = [];
+ const extractor: ProposeTakesExtractor = async ({ pagePath }) => {
+ scannedPages.push(pagePath);
+ return [];
+ };
+
+ const result = await runPhaseProposeTakes(context(), { extractor });
+
+ 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 });
diff --git a/test/takes-propose-drain.test.ts b/test/takes-propose-drain.test.ts
index a170911d3e..0d10135457 100644
--- a/test/takes-propose-drain.test.ts
+++ b/test/takes-propose-drain.test.ts
@@ -118,6 +118,14 @@ describe('propose_takes → takes propose drain (#4102)', () => {
expect((gated.details as Record<string, unknown>).reason).toBe('disabled');
expect(calls).toBe(0);
+ // Change the page body so the once-run has a real uncached candidate.
+ // The preceding test already cached the original content hash.
+ await engine.putPage(SLUG, {
+ type: 'company',
+ title: 'Drain Example',
+ compiled_truth: 'I bet drain-example expands into a second market within 12 months.',
+ });
+
const once = await runPhaseProposeTakes(ctx(), { extractor, once: true });
expect(once.status).not.toBe('skipped');
expect(calls).toBeGreaterThan(0);