Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(propose_takes): one reply outcome decides takes and the empty tombstone, so [] with trailing prose is memoized (#6782)
garrytan40896f557e0f
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.mdindex 7d10a90e50..d59a663364 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. `cycle.propose_takes.types` (#5213; `proposeTakesTypes`, a JSON array of page types in the `cycle.enrich_thin.types` shape) narrows the candidate query to those types with `type = ANY(...)` on top of the source scope; unset keeps every type eligible and a malformed value is ignored with one stderr line. 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`). The mechanical holder check of #5425 [UC4] (`cycle/propose-takes-attribution.ts`, one call after the extractor returns, behind `dream.attribution_checks`, default off) is separate from the prompt rule and documented with that module.+- `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. `cycle.propose_takes.types` (#5213; `proposeTakesTypes`, a JSON array of page types in the `cycle.enrich_thin.types` shape) narrows the candidate query to those types with `type = ANY(...)` on top of the source scope; unset keeps every type eligible and a malformed value is ignored with one stderr line. Idempotency cache on `(source_id, page_slug, content_hash, prompt_version)` composite unique index. `extractorOutcome` (#6782) is the one reading of a reply, used for both the takes and the tombstone decision: it locates the first JSON value (after `<think>` and whole-reply fence stripping, the whole remainder or up to its own closing bracket) and returns `valid_empty` only for a complete empty array not followed by a JSON object or an array of take-shaped objects (a `[1]` citation does not count), `valid_nonempty` for at least one take, else `invalid`, which `defaultExtractor` throws as transient (no tombstone). A zero-claim tombstone is keyed by the page's content hash, so any edit to the page extracts it again on the next cycle. 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`). The mechanical holder check of #5425 [UC4] (`cycle/propose-takes-attribution.ts`, one call after the extractor returns, behind `dream.attribution_checks`, default off) is separate from the prompt rule and documented with that module.- `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/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.mdindex e4435a0afe..eb5a6bf98f 100644--- a/docs/guides/cron-schedule.md+++ b/docs/guides/cron-schedule.md@@ -175,6 +175,12 @@ per-transcript synthesis subagents. The dials:still apply; a value that is not a JSON array is ignored with one stderrline and the phase scans every type. Note that a page with no `type` hasno type to match, so it is excluded whenever the list is set.+ A page whose reply is a complete empty array (`[]`, even with an+ explanation after it) gets a "no gradeable claims" tombstone and is not+ sent again while its content is unchanged; a reply that is truncated,+ prose only, or empty and then followed by takes is retried next cycle.+ To extract a tombstoned page again, edit the page: the tombstone is keyed+ by its content hash, so the next cycle sends the changed page.- `dream.synthesize.attribution_rules` and `dream.propose_takes.attribution_rules`(default off) — extra prompt rules from #5425: keep who proposed what andlater corrections explicit; an assistant-authored judgment is not thediff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.tsindex ca944e23f1..7f11515b87 100644--- a/src/core/cycle/propose-takes.ts+++ b/src/core/cycle/propose-takes.ts@@ -563,19 +563,16 @@ export async function defaultExtractor(}}- // ChatResult.text is already the concatenated text content.- const takes = parseExtractorOutput(result.text);- // A parse-level `[]` is AMBIGUOUS: it means either "the model genuinely- // found no gradeable claims" OR "the model returned malformed/prose/- // truncated output we couldn't parse." The caller memoizes empty- // extractions with a tombstone, so a transient parse failure would- // PERMANENTLY suppress a page that actually has claims. Only a cleanly- // parsed empty array is a real "no claims" result worth memoizing; treat- // anything else as a transient error and throw, so the phase's catch- // retries the page next cycle (writing no tombstone).- if (takes.length === 0 && !isWellFormedEmptyExtraction(result.text)) {+ // ChatResult.text is already the concatenated text content. The caller+ // memoizes an empty extraction with a tombstone, so only a reply whose first+ // JSON value is a complete empty array (and that carries no takes after it)+ // counts as "no claims"; anything unparseable is transient and throws, so the+ // phase retries the page next cycle (writing no tombstone).+ const outcome = extractorOutcome(result.text);+ if (outcome.kind === 'invalid') {throw new Error('propose_takes extractor: no parseable takes JSON (transient — retry)');}+ const takes = outcome.kind === 'valid_nonempty' ? outcome.takes : [];// #4737: model_id provenance comes from the RESPONSE, not the request —// ChatResult.model is the 'provider:modelId' that actually answered.const servedModel =@@ -583,34 +580,6 @@ export async function defaultExtractor(return servedModel ? takes.map((t) => ({ ...t, served_model: servedModel })) : takes;}-/**- * True only when `raw` is a cleanly-parseable EMPTY JSON array — the- * well-behaved "no gradeable claims" response (the prompt instructs the model- * to return `[]`). Distinguishes a genuine empty extraction (safe to memoize- * via a tombstone) from malformed / prose / truncated output (transient —- * must be retried, never tombstoned). Mirrors parseExtractorOutput's- * think-strip + fence-strip + first-array handling so both agree on what- * "the model returned []" means.- */-export function isWellFormedEmptyExtraction(raw: string): boolean {- if (!raw || raw.trim().length === 0) return false;- let text = raw.trim();- // Strip <think>...</think> reasoning tags (MiniMax-M3, DeepSeek-R1, etc.),- // same as parseExtractorOutput (#2559).- text = text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();- const fenced = text.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/);- if (fenced) text = (fenced[1] ?? '').trim();- const arrStart = text.indexOf('[');- if (arrStart === -1) return false;- try {- const parsed = JSON.parse(text.slice(arrStart));- return Array.isArray(parsed) && parsed.length === 0;- } catch {- return false;- }-}--/*** #4736: kinds the pre-fix EXTRACT_TAKES_PROMPT asked for. Cached and* old-model outputs still emit them; map them onto the fence vocabulary@@ -623,40 +592,81 @@ const LEGACY_EXTRACTOR_KIND_MAP: Record<string, ProposedTake['kind']> = {};/**- * Parse extractor output into ProposedTake[]. Handles common LLM output- * sins (markdown fence wrapping, leading/trailing prose, single-object- * instead of array). Returns [] on any unrecoverable parse error rather- * than throwing. Kind tokens are case/whitespace-normalized, matched- * against the fence vocabulary (with the #4736 legacy mapping), and- * anything else coerces to 'take'.+ * #6782: what one extractor reply holds. `valid_empty` only when the reply's+ * first JSON value is a complete empty array and no JSON object, and no array+ * holding a take-shaped object, follows it (a later `[1]` citation does not+ * count); `valid_nonempty` when the first value (an array, or a lone object)+ * yields at least one take; `invalid` for everything else (prose only,+ * truncated or malformed JSON, a claim-less value, or an empty array followed+ * by takes), which the caller retries and never tombstones.+ */+export type ExtractorOutcome = { kind: 'valid_empty' } | { kind: 'valid_nonempty'; takes: ProposedTake[] } | { kind: 'invalid' };++export function extractorOutcome(raw: string): ExtractorOutcome {+ const located = locateFirstJsonValue(raw);+ if (!located) return { kind: 'invalid' };+ if (Array.isArray(located.value) && located.value.length === 0) {+ return carriesLaterTakes(located.rest) ? { kind: 'invalid' } : { kind: 'valid_empty' };+ }+ const takes = takesOf(located.value);+ return takes.length ? { kind: 'valid_nonempty', takes } : { kind: 'invalid' };+}++/**+ * Parse extractor output into ProposedTake[] (the takes of a `valid_nonempty`+ * outcome, else none). Handles common LLM output sins (markdown fence+ * wrapping, leading/trailing prose, single-object instead of array). Kind+ * tokens are case/whitespace-normalized, matched against the fence vocabulary+ * (with the #4736 legacy mapping), and anything else coerces to 'take'.*/export function parseExtractorOutput(raw: string): ProposedTake[] {- if (!raw || raw.trim().length === 0) return [];- let text = raw.trim();- // Strip <think>...</think> reasoning tags (MiniMax-M3, DeepSeek-R1, etc.).- text = text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();- // Strip markdown code fence wrapper.+ const outcome = extractorOutcome(raw);+ return outcome.kind === 'valid_nonempty' ? outcome.takes : [];+}++/**+ * The reply's first JSON array or object after stripping `<think>` reasoning+ * (#2559) and a whole-reply code fence: the whole remainder when it parses,+ * else only up to the value's own closing bracket (#5209), with the text after it.+ */+function locateFirstJsonValue(raw: string): { value: unknown; rest: string } | null {+ if (!raw || raw.trim().length === 0) return null;+ let text = raw.trim().replace(/<think>[\s\S]*?<\/think>/g, '').trim();const fenced = text.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?```$/);if (fenced) text = (fenced[1] ?? '').trim();- // First-array-or-object substring extraction (defends against leading prose).const firstArr = text.indexOf('[');const firstObj = text.indexOf('{');- if (firstArr === -1 && firstObj === -1) return [];+ if (firstArr === -1 && firstObj === -1) return null;const start = firstArr !== -1 && (firstObj === -1 || firstArr < firstObj) ? firstArr : firstObj;- let parsed: unknown;try {- parsed = JSON.parse(text.slice(start));+ return { value: JSON.parse(text.slice(start)), rest: '' };} catch {- // Trailing noise (a leftover fence, a `[Source: X]` citation): parse only- // up to the value's own closing bracket, never the last bracket in the text.const end = matchingCloseBracket(text, start);- if (end === -1) return [];+ if (end === -1) return null;try {- parsed = JSON.parse(text.slice(start, end + 1));+ return { value: JSON.parse(text.slice(start, end + 1)), rest: text.slice(end + 1) };} catch {- return [];+ return null;}}+}++/** True when `text` holds a parseable JSON object, or an array holding a take-shaped object. */+function carriesLaterTakes(text: string): boolean {+ for (let i = 0; i < text.length; i++) {+ if (text[i] !== '[' && text[i] !== '{') continue;+ const end = matchingCloseBracket(text, i);+ if (end === -1) continue;+ let value: unknown;+ try { value = JSON.parse(text.slice(i, end + 1)); } catch { continue; }+ if (!Array.isArray(value) && value !== null && typeof value === 'object') return true;+ if (Array.isArray(value) && value.some(v => v !== null && typeof v === 'object' && typeof (v as Record<string, unknown>).claim_text === 'string')) return true;+ i = end;+ }+ return false;+}++function takesOf(parsed: unknown): ProposedTake[] {const arr = Array.isArray(parsed) ? parsed : [parsed];const out: ProposedTake[] = [];for (const raw of arr) {diff --git a/test/propose-takes-empty-outcome-6782.test.ts b/test/propose-takes-empty-outcome-6782.test.tsnew file mode 100644index 0000000000..7e320bd8fd--- /dev/null+++ b/test/propose-takes-empty-outcome-6782.test.ts@@ -0,0 +1,117 @@+/**+ * #6782: propose_takes recognized a complete empty extraction only when the+ * whole remainder of the reply parsed as JSON, while the take parser stopped+ * at the value's own closing bracket. A reply of `[]` followed by an+ * explanation therefore threw "no parseable takes JSON (transient — retry)":+ * no tombstone was written and the page re-paid an extractor call every cycle.+ * One outcome function now locates and parses the reply for both decisions.+ *+ * Protects: a complete empty array with trailing prose (the reporter's three+ * retained samples) is memoized with a tombstone; output that is empty and then+ * carries takes, truncated output and prose-only output are still retried and+ * never tombstoned. Existing coverage tested the empty check only on clean or+ * leading-prose input, so the trailing-prose disagreement went unseen.+ */+import { afterAll, beforeEach, describe, expect, test } from 'bun:test';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { defaultExtractor, extractorOutcome, runPhaseProposeTakes, EMPTY_EXTRACTION_TOMBSTONE_TEXT } from '../src/core/cycle/propose-takes.ts';+import type { OperationContext } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const REPORTED_EMPTY = [+ '[]\n\nNo gradeable claims—this is purely factual (purpose, ownership, dates, source links).',+ '[]\n\nThis prose is purely factual (biographical/state facts), with no predictions, recommendations, or interpretive judgments to extract.',+ 'This prose is purely factual/registry content (project statuses, file locations) with no predictions, judgments, or wagers.\n\n```json\n[]\n```',+];+const take = (claim: string) => JSON.stringify({ claim_text: claim, kind: 'take', holder: 'brain', weight: 0.6 });++beforeEach(() => {+ resetGateway();+ __setChatTransportForTests(null);+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });+});+afterAll(() => {+ __setChatTransportForTests(null);+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });+ resetGateway();+});++function reply(text: string) {+ __setChatTransportForTests(async () => ({ text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' }) as ChatResult);+}+const extract = () => defaultExtractor({ pagePath: 'wiki/registry-example', pageBody: 'Project statuses and file locations.', existingTakes: [] });++describe('#6782 defaultExtractor: a complete empty array with trailing prose is an empty extraction', () => {+ for (const [i, text] of REPORTED_EMPTY.entries()) {+ test(`reported sample ${i + 1} returns no takes instead of throwing`, async () => {+ reply(text);+ expect(await extract()).toEqual([]);+ });+ }++ test('an empty array followed by prose that carries a real takes array is retried, not memoized', async () => {+ reply(`[]\n\nOn reflection, these qualify:\n[${take('Demand will rise next year')}]`);+ await expect(extract()).rejects.toThrow('no parseable takes JSON (transient — retry)');+ });++ test('truncated and prose-only replies are still retried', async () => {+ for (const text of ['[', `[${take('A')},{"claim_text":"B"`, 'There are no gradeable claims here.', '']) {+ reply(text);+ await expect(extract()).rejects.toThrow('transient — retry');+ }+ });++ test('a non-empty array with trailing prose keeps its takes', async () => {+ reply(`[${take('Demand will rise next year')}]\n\nExplanation.`);+ expect((await extract()).map(t => t.claim_text)).toEqual(['Demand will rise next year']);+ });+});++describe('#6782 extractorOutcome', () => {+ test('the reported samples are valid_empty', () => {+ for (const text of REPORTED_EMPTY) expect(extractorOutcome(text)).toEqual({ kind: 'valid_empty' });+ });++ test('a later numeric citation or empty array does not make an empty reply non-empty', () => {+ expect(extractorOutcome('[]\nSee [1] and [2].')).toEqual({ kind: 'valid_empty' });+ expect(extractorOutcome('[]\n\n[]')).toEqual({ kind: 'valid_empty' });+ });++ test('empty followed by a takes array, a lone object or a later object is invalid', () => {+ expect(extractorOutcome(`[]\n[${take('A')}]`)).toEqual({ kind: 'invalid' });+ expect(extractorOutcome(`[] then ${take('A')}`)).toEqual({ kind: 'invalid' });+ expect(extractorOutcome('[]\n{"note":"more"}')).toEqual({ kind: 'invalid' });+ });++ test('object-first output still parses as non-empty and is never counted as empty', () => {+ const outcome = extractorOutcome(`Here is one:\n${take('Churn is seasonal')}\n]`);+ expect(outcome.kind).toBe('valid_nonempty');+ expect(outcome.kind === 'valid_nonempty' && outcome.takes.map(t => t.claim_text)).toEqual(['Churn is seasonal']);+ expect(extractorOutcome('{}')).toEqual({ kind: 'invalid' });+ });+});++describe('#6782 the phase memoizes a reported empty reply with a tombstone', () => {+ test('one extractor call, one tombstone, no failure', async () => {+ reply(REPORTED_EMPTY[0]!);+ const captured: Array<{ sql: string; params: unknown[] }> = [];+ const engine = {+ kind: 'pglite',+ async executeRaw<T>(sql: string, params?: unknown[]): Promise<T[]> {+ captured.push({ sql, params: params ?? [] });+ if (sql.includes('FROM persistence_brain')) return [{ enabled: false } as unknown as T];+ if (sql.includes('SELECT slug, source_id, compiled_truth')) return [{ slug: 'wiki/registry-example', source_id: 'default', compiled_truth: 'Project statuses and file locations.' }] as T[];+ if (sql.includes('INSERT INTO take_proposals')) return [{ id: 1 } as unknown as T];+ return [];+ },+ } as unknown as BrainEngine;+ const ctx = { engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never, dryRun: false, remote: false, sourceId: 'default' } as OperationContext;+ const result = await runPhaseProposeTakes(ctx, {});+ const details = result.details as Record<string, unknown>;+ expect(details.tombstones_written).toBe(1);+ expect(details.proposals_inserted).toBe(0);+ const tombstones = captured.filter(c => c.sql.includes('INSERT INTO take_proposals') && c.params.includes(EMPTY_EXTRACTION_TOMBSTONE_TEXT));+ expect(tombstones).toHaveLength(1);+ });+});diff --git a/test/propose-takes.test.ts b/test/propose-takes.test.tsindex fc5ef3826f..10b683f2eb 100644--- a/test/propose-takes.test.ts+++ b/test/propose-takes.test.ts@@ -23,7 +23,7 @@ import {contentHash,hasCompleteFence,extractExistingTakesForDedup,- isWellFormedEmptyExtraction,+ extractorOutcome,PROPOSE_TAKES_PROMPT_VERSION,EMPTY_EXTRACTION_TOMBSTONE_TEXT,resolveProposeTakesDeadlineMs,@@ -277,49 +277,49 @@ describe('parseExtractorOutput', () => {});});-// ─── isWellFormedEmptyExtraction ────────────────────────────────────+// ─── extractorOutcome: the empty-extraction decision ───────────────// Guards the tombstone against permanently memoizing a transient parse// failure as "no claims". Only a cleanly-parsed empty array counts as a// genuine empty extraction; malformed/prose/truncated output must not.-describe('isWellFormedEmptyExtraction', () => {+describe('extractorOutcome valid_empty (the tombstone decision)', () => {test('true for a clean empty array (the well-behaved "no claims" response)', () => {- expect(isWellFormedEmptyExtraction('[]')).toBe(true);- expect(isWellFormedEmptyExtraction(' [] ')).toBe(true);- expect(isWellFormedEmptyExtraction('[ ]')).toBe(true);+ expect(extractorOutcome('[]').kind).toBe('valid_empty');+ expect(extractorOutcome(' [] ').kind).toBe('valid_empty');+ expect(extractorOutcome('[ ]').kind).toBe('valid_empty');});test('true for a fenced empty array', () => {- expect(isWellFormedEmptyExtraction('```json\n[]\n```')).toBe(true);+ expect(extractorOutcome('```json\n[]\n```').kind).toBe('valid_empty');});test('true for leading prose then an empty array', () => {- expect(isWellFormedEmptyExtraction('No gradeable claims.\n\n[]')).toBe(true);+ expect(extractorOutcome('No gradeable claims.\n\n[]').kind).toBe('valid_empty');});test('false for empty / whitespace output (transient, must retry)', () => {- expect(isWellFormedEmptyExtraction('')).toBe(false);- expect(isWellFormedEmptyExtraction(' \n ')).toBe(false);+ expect(extractorOutcome('').kind).not.toBe('valid_empty');+ expect(extractorOutcome(' \n ').kind).not.toBe('valid_empty');});test('false for prose-only / non-JSON output (transient, must retry)', () => {- expect(isWellFormedEmptyExtraction('There are no gradeable claims here.')).toBe(false);- expect(isWellFormedEmptyExtraction('null')).toBe(false);+ expect(extractorOutcome('There are no gradeable claims here.').kind).not.toBe('valid_empty');+ expect(extractorOutcome('null').kind).not.toBe('valid_empty');});test('false for malformed / truncated JSON (transient, must retry)', () => {- expect(isWellFormedEmptyExtraction('[')).toBe(false);- expect(isWellFormedEmptyExtraction('[{"claim_text":"x"')).toBe(false);+ expect(extractorOutcome('[').kind).not.toBe('valid_empty');+ expect(extractorOutcome('[{"claim_text":"x"').kind).not.toBe('valid_empty');});test('false for a NON-empty array (has content — not an empty extraction)', () => {- expect(isWellFormedEmptyExtraction('[{"claim_text":"x","kind":"take","holder":"brain","weight":0.5}]')).toBe(false);+ expect(extractorOutcome('[{"claim_text":"x","kind":"take","holder":"brain","weight":0.5}]').kind).not.toBe('valid_empty');// Parseable but claim-less array is ambiguous garbage → not a genuine empty.- expect(isWellFormedEmptyExtraction('[{"foo":"bar"}]')).toBe(false);+ expect(extractorOutcome('[{"foo":"bar"}]').kind).not.toBe('valid_empty');});test('false for an empty object (model ignored the array-format instruction)', () => {- expect(isWellFormedEmptyExtraction('{}')).toBe(false);+ expect(extractorOutcome('{}').kind).not.toBe('valid_empty');});});