Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(GBRA-130 A-25): propose_takes retries failing pages last and holds content-class poison pages with a failure tombstone; takes propose --failed/--retry-failed

garrytan401c7c3cde82
diff --git a/docs/architecture/key-files/hindsight.md b/docs/architecture/key-files/hindsight.md
index d7bdeca3b4..4dd0b2cc5a 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 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; 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. `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/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. GBRA-130 A-25: extractor failures go through `ProposeTakesFailures` (`cycle/propose-takes-failures.ts`, op_checkpoints op `propose-takes-failures` per source): a page that failed before at the same content hash and prompt version is retried after the fresh pages, only fresh failures feed the #3763 halt and the `propose_takes.pages` ItemRun breaker, and a run-scoped error rethrows. A content-class failure (`request_too_large`, `content_rejected`) repeated in `PROPOSE_TAKES_HOLD_RUNS` (3) counted runs, each with extractor success evidence, writes a failure tombstone: a `rejected` take_proposals row whose claim is `(extraction failed: <code>)`, distinct from an empty extraction; transient failures never hold, and a systemic run or global halt counts nothing. The result adds `failed_pages`, `failure_tombstones_written` and `systemic`; the summary names `gbrain takes propose --failed`. A content or prompt-version change, or `gbrain takes propose --retry-failed`, retries a held page. Pinned by `test/pathological/a25-propose-takes-poison-pages.test.ts` (both engines).
- `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/grade-takes-measured.ts` — `GRADE_TAKES_MEASURED_MODELS` (the judges that met the W6 take-grading eval's preregistered rule, `evals/take-grading/PREREGISTRATION.md`; `openai:gpt-6.1-sol` since the 2026-10-16 counted run) and `gradeJudgeMeasured()`, which `gbrain takes grades` (`cmdGrades` in `src/commands/takes.ts`, trusted local, no MCP op) uses to mark cached verdicts no measurement backs. Auto-resolve stays unwired.
- `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`).
@@ -34,7 +34,7 @@ unresolvable+true|false, pre-v80 NULL/NULL rows survive).
- `src/core/think/prompt.ts` — anti-bias prompt shaping. `withCalibration` option on `buildThinkSystemPrompt` adds anti-bias rules. `buildCalibrationBlock()` emits the `<calibration>` XML. `buildThinkUserMessage` has TWO shapes: default (question first), and with-calibration (retrieval → calibration → question) when opt-in. Wired into `runThink` via `opts.withCalibration` + `opts.calibrationHolder`.
- `src/commands/calibration.ts` — CLI: `gbrain calibration` (read + print), `--regenerate`, `--undo-wave <ver>`, `ab-report`. MCP op `get_calibration_profile` (scope: read) backs the same data path. Source-scoped via `sourceScopeOpts(ctx)`.
- `src/core/owner-holder.ts` — single source of truth for "the brain owner" holder string. `DEFAULT_OWNER_HOLDER = 'self'` (matches the consolidate facts→takes writer + `docs/takes-vs-facts.md`); `resolveOwnerHolder({override, configValue})` returns override > `emotional_weight.user_holder` config > `'self'`. Consumed by the calibration_profile cycle phase, `gbrain calibration` CLI, the `get_calibration_profile` op, `think`'s calibration block, `emotional-weight`'s `DEFAULT_USER_HOLDER`, and doctor's `calibration_freshness`. Pure; unit-tested in `test/owner-holder.test.ts`. Does NOT unify owner-identity fragmentation (`self`/`brain`/`people-<owner>`) — tracked separately.
-- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the takes table and its fence row becomes a reservation row (`| N | ~~(removed)~~ | take | world | 0.0 | | removed |`, W9F item 4) in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. Reservations: `parseTakesFence` returns them in `reservedRowNums`, never in `takes`, so no reader or projection sees a take there; `renderTakesFence(takes, reservedRowNums)` puts them back in row order, and `upsertTakeRow`, `supersedeRow` and `takesPreparation.replaceFence` keep the reservations of the body they rewrite. Every new take row number comes from GBRA-54's `nextFreeRowNum` (`fence-repair/normalize.ts`): one more than every fence row on the page (facts and takes, live, struck and reserved) and, in `takes-prepare.ts`, every stored facts/takes row (`storedFenceRows`), revalidated under the publication lock; the promise holds while the reservation row exists. #6450: `takes_add` and an explicit `takes_supersede` holder override are trimmed and checked with `isValidHolder` at the write boundary (syntax before authority: `invalid_params` naming the grammar, before `assertHolderAllowed`); the inherited supersede holder is not re-validated (the existing fence already round-tripped). Every prepared takes fence is parsed again before publication and refused `invalid_params` on any warning, so no write can leave a fence the next write would refuse. Test: `test/takes-holder-validation-6450.test.ts`. `test/takes-row-reservation.test.ts` (both engines), `test/takes-reservation-callers.test.ts` (census of `parseTakesFence` callers). `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`.
+- `src/commands/takes.ts` — the full `gbrain takes` subcommand dispatcher (list/search/embed/add/update/supersede/resolve/propose/scorecard/calibration/extract/revisit). `takes list --limit N --offset N` validates integers at the CLI; the engine clamps limit (default 100, cap 500) and floors offset at 0. `takes revisit <slug>` opens $EDITOR on the source page with a `<!-- gbrain:revisit -->` cursor marker. #5167: `takes remove <slug> --row N` goes through `takes-mutation.ts` to the local-only `takes_remove` op (persistence `takes-prepare.ts`): the row leaves the takes table and its fence row becomes a reservation row (`| N | ~~(removed)~~ | take | world | 0.0 | | removed |`, W9F item 4) in one coordinated publication, other row numbers stay, and a resolved row, a row another row cites as "superseded by" it, or a row whose DB claim disagrees with the fence is refused (the last names `takes rebuild`); thin clients are refused. Reservations: `parseTakesFence` returns them in `reservedRowNums`, never in `takes`, so no reader or projection sees a take there; `renderTakesFence(takes, reservedRowNums)` puts them back in row order, and `upsertTakeRow`, `supersedeRow` and `takesPreparation.replaceFence` keep the reservations of the body they rewrite. Every new take row number comes from GBRA-54's `nextFreeRowNum` (`fence-repair/normalize.ts`): one more than every fence row on the page (facts and takes, live, struck and reserved) and, in `takes-prepare.ts`, every stored facts/takes row (`storedFenceRows`), revalidated under the publication lock; the promise holds while the reservation row exists. #6450: `takes_add` and an explicit `takes_supersede` holder override are trimmed and checked with `isValidHolder` at the write boundary (syntax before authority: `invalid_params` naming the grammar, before `assertHolderAllowed`); the inherited supersede holder is not re-validated (the existing fence already round-tripped). Every prepared takes fence is parsed again before publication and refused `invalid_params` on any warning, so no write can leave a fence the next write would refuse. Test: `test/takes-holder-validation-6450.test.ts`. `test/takes-row-reservation.test.ts` (both engines), `test/takes-reservation-callers.test.ts` (census of `parseTakesFence` callers). `takes rebuild <slug> [--source-id]` runs the local-only `takes_rebuild` op (W9F item 8; `runTakesRebuild` in `takes-mutation.ts`, delegated to a resident `gbrain serve` owner over persistence IPC, else the local engine, with the same JSON, warnings and exit 1 on a missing page or a warning), which calls `extractTakes({source:"db", slugs:[slug], sourceId, rebuild:true})`, whose rebuild now deletes only indexed rows whose (row_num, claim) left the fence, so matching rows keep resolutions and vectors. The v0_28_0 hint names `gbrain reindex --markdown` instead of the nonexistent `extract takes --rebuild`. GBRA-130 A-25: `takes propose --failed [--source <id>] [--json]` lists pages propose_takes held with a failure tombstone (`listFailedProposals`); `takes propose --retry-failed [--slug <slug>] [--source <id>] [--json]` deletes their tombstones and ledger records (`retryFailedProposals`) so the next run re-extracts them.
- `src/core/extract-takes-from-pages.ts` — bootstrap extraction selects uncovered pages newest first. Managed pages capture their revision before classification and publish the complete appended takes fence through coordinated `put_page`, whose canonical projection commits the takes rows with the page; conflicts skip that page. Unmanaged pages retain the md-first writer. Pinned by `test/persistence-managed-takes-extract.test.ts` and `test/extract-takes-md-first.test.ts`. `takes extract --before <updated_at>,<id>` (CLI-only) continues strictly below a prior run's `next_before`, an `(updated_at, id)` keyset with exact timestamptz text, so zero-claim pages no longer starve older ones; a budget stop resumes at the first unclassified page, a failed page stays uncovered for the next run without `--before`, and a malformed cursor is an exit-2 `invalid_params` refusal before any page is read. Pinned by `test/extract-takes-from-pages-progression.test.ts`, `test/takes-extract-json.test.ts` and `test/e2e/takes-extract-cursor-postgres.test.ts`.
- `src/core/take-proposals.ts` — owns the `take_proposals` queue's row contract. `normalizeTakeProposalRow` coerces Postgres driver BigInt/string values (`id`, `weight`, `promoted_row_num`) to numbers at the query boundary so both engines return the same numeric row shape. `acceptProposal` promotes through a coordinated `takes_add` mutation (`submitPageMutation`, the same path `gbrain takes add` uses), so accept works on a managed brain where a direct fence write is refused with `writer_coordinator_required` (`test/takes-propose-accept-managed.test.ts`). #5214: an accepted proposal's take records `take_proposals#<id>` as its source; `acceptProposal(target, id, edits)` (`takes propose --accept <id> --claim/--weight/--who/--kind`) applies the edits as a plain takes_add with source `take_proposals#<id> (edited)` while the queue row keeps the original claim text.
- `admin/src/pages/Calibration.tsx` — Calibration tab. Single-column layout. `<TrustedSVG>` wrapper handles `dangerouslySetInnerHTML` for the server-rendered SVG.
diff --git a/docs/guides/cron-schedule.md b/docs/guides/cron-schedule.md
index d9f387d9d0..8e607d40ea 100644
--- a/docs/guides/cron-schedule.md
+++ b/docs/guides/cron-schedule.md
@@ -192,6 +192,13 @@ per-transcript synthesis subagents. The dials:
There is no per-page force flag: the tombstone is keyed by a hash of the
page body, so any edit to the body re-extracts the page on the next cycle,
and that is the only way to send one tombstoned page again.
+ A page the model refuses the same way in 3 cycles (a prompt too long for
+ the model, a content block) gets a separate failure tombstone and is
+ skipped while its body and the prompt version are unchanged; pages that
+ failed before are retried after the fresh ones, so they never block the
+ rest. `gbrain takes propose --failed` lists held pages and
+ `gbrain takes propose --retry-failed [--slug <slug>]` releases them.
+ Timeouts, rate limits and other transient errors are never held.
- `dream.synthesize.attribution_rules` and `dream.propose_takes.attribution_rules`
(default off) — extra prompt rules from #5425: keep who proposed what and
later corrections explicit; an assistant-authored judgment is not the
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index 1d61787e44..cb544fbd3a 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -476,6 +476,26 @@ async function cmdCalibration(engine: BrainEngine, args: string[]): Promise<void
*/
async function cmdPropose(engine: BrainEngine, args: string[], sourceId: string): Promise<void> {
const json = flagPresent(args, '--json');
+ // GBRA-130 A-25: pages propose_takes held with a failure tombstone after
+ // repeated deterministic extractor failures: list them, or release one page
+ // (or every page) so the next run re-extracts it.
+ if (flagPresent(args, '--failed') || flagPresent(args, '--retry-failed')) {
+ const explicit = flagValue(args, '--source');
+ const target = explicit ? await resolveSourceId(engine, explicit) : sourceId;
+ const { listFailedProposals, retryFailedProposals } = await import('../core/cycle/propose-takes-failures.ts');
+ if (flagPresent(args, '--retry-failed')) {
+ const { released } = await retryFailedProposals(engine, target, flagValue(args, '--slug'));
+ if (json) console.log(JSON.stringify({ source_id: target, released }, null, 2));
+ else console.log(released.length ? `Released ${released.length} page(s) in ${target}; the next propose_takes run re-extracts them: ${released.join(', ')}` : `No held pages in ${target}.`);
+ return;
+ }
+ const failed = await listFailedProposals(engine, target);
+ if (json) { console.log(JSON.stringify(failed, null, 2)); return; }
+ if (failed.length === 0) { console.log(`No pages held by propose_takes in ${target}.`); return; }
+ for (const f of failed) console.log(`${f.slug} (${f.code}, prompt ${f.prompt_version}, held ${f.proposed_at})`);
+ console.log(`Retry one with \`gbrain takes propose --retry-failed --slug <slug> --source ${target}\`, or every page by omitting --slug.`);
+ return;
+ }
const acceptRaw = flagValue(args, '--accept');
const rejectRaw = flagValue(args, '--reject');
if (acceptRaw !== undefined && rejectRaw !== undefined) {
@@ -604,6 +624,10 @@ Subcommands:
Promote a proposal into the page's takes fence (source take_proposals#<id>;
edits mark it "(edited)" and the queue keeps the original text)
takes propose --reject <id> Dismiss a proposal
+ takes propose --failed [--source <id>] [--json]
+ Pages propose_takes held after repeated extractor failures
+ takes propose --retry-failed [--slug <slug>] [--source <id>] [--json]
+ Release held pages so the next propose_takes run re-extracts them
takes scorecard [<holder>] [--domain <prefix>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--json]
Aggregate calibration scorecard (v0.30.0)
[--group-by holder|source] [--min-n N] [--source-id <id>]
diff --git a/src/core/cycle/propose-takes-failures.ts b/src/core/cycle/propose-takes-failures.ts
new file mode 100644
index 0000000000..ba28080835
--- /dev/null
+++ b/src/core/cycle/propose-takes-failures.ts
@@ -0,0 +1,208 @@
+/**
+ * propose_takes failure ledger (GBRA-130 A-25).
+ *
+ * One op_checkpoints row per source (op `propose-takes-failures`, fingerprint
+ * the source id) records each page whose extractor call failed: the content
+ * hash and prompt version it failed at, the failure code and class, and the
+ * number of counted runs in a row it failed the same way (`attempts`). The
+ * phase retries a recorded page after its fresh candidates, and a page whose
+ * content-class failure (a prompt too long for the model, a provider content
+ * block) repeats in PROPOSE_TAKES_HOLD_RUNS counted runs at the same hash and
+ * prompt version gets a failure tombstone in take_proposals: a `rejected` row
+ * whose claim text names the code, so the idempotency check skips the page
+ * until its content or the prompt version changes, and which stays distinct
+ * from a successful empty extraction. `gbrain takes propose --retry-failed`
+ * deletes the tombstones and records so the next run re-extracts.
+ *
+ * A run's failures count only when the run is not systemic (most fresh pages
+ * failing trips the ItemRun breaker) and the extractor has succeeded on another
+ * page since the failing page first failed (this run, or a stored success
+ * after it), so a dead extractor lane never tombstones pages.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Action } from '../agent-output.ts';
+import { ItemRun, classifyItemFailure, type ClassifiedItemFailure } from '../item-failure.ts';
+
+export const PROPOSE_TAKES_FAILURE_OP = 'propose-takes-failures';
+export const PROPOSE_TAKES_HOLD_RUNS = 3;
+/** Recorded pages kept per source; the oldest failures drop first. */
+const MAX_RECORDS = 500;
+const TOMBSTONE_PREFIX = '(extraction failed: ';
+
+export interface ProposeTakesFailureRecord {
+ content_hash: string;
+ prompt_version: string;
+ code: string;
+ class: 'content' | 'transient';
+ message: string;
+ /** Counted runs in a row that failed with `code` (content class only; 0 while only observed). */
+ attempts: number;
+ first_failed_at: string;
+ last_failed_at: string;
+}
+
+export interface ProposeTakesFailureLedger {
+ /** The last run that had an extractor success: a prompt version and ISO time. */
+ success: { prompt_version: string; at: string } | null;
+ pages: Record<string, ProposeTakesFailureRecord>;
+}
+
+export const failureTombstoneText = (code: string) => `${TOMBSTONE_PREFIX}${code})`;
+
+/** The command that releases a tombstoned page so the next propose_takes run re-extracts it (one extractor call). */
+export function retryFailedAction(sourceId: string, slug: string): Action {
+ return {
+ argv: ['gbrain', 'takes', 'propose', '--retry-failed', '--slug', slug, '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Deletes the failure tombstone of ${slug} in source ${sourceId}; the next propose_takes run calls the extractor on it again, and `
+ + `it is tombstoned again after ${PROPOSE_TAKES_HOLD_RUNS} counted runs failing the same way.`,
+ verify: { argv: ['gbrain', 'takes', 'propose', '--failed', '--json', '--source', sourceId] },
+ };
+}
+
+export async function loadFailureLedger(engine: BrainEngine, sourceId: string): Promise<ProposeTakesFailureLedger> {
+ const [row] = await engine.executeRaw<{ ledger: ProposeTakesFailureLedger | string | null }>(
+ "SELECT completed_keys->0 AS ledger FROM op_checkpoints WHERE op = $1 AND fingerprint = $2", [PROPOSE_TAKES_FAILURE_OP, sourceId]);
+ const stored = typeof row?.ledger === 'string' ? JSON.parse(row.ledger) as ProposeTakesFailureLedger : row?.ledger;
+ return { success: stored?.success ?? null, pages: stored?.pages && typeof stored.pages === 'object' ? stored.pages : {} };
+}
+
+export async function saveFailureLedger(engine: BrainEngine, sourceId: string, ledger: ProposeTakesFailureLedger): Promise<void> {
+ const pages = Object.fromEntries(Object.entries(ledger.pages)
+ .sort((a, b) => b[1].last_failed_at.localeCompare(a[1].last_failed_at)).slice(0, MAX_RECORDS));
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ($1, $2, $3::text::jsonb)
+ ON CONFLICT (op, fingerprint) DO UPDATE SET completed_keys = EXCLUDED.completed_keys, updated_at = now()`,
+ [PROPOSE_TAKES_FAILURE_OP, sourceId, JSON.stringify([{ success: ledger.success, pages }])]);
+}
+
+/** Pages of a source that carry a failure tombstone, with the code it names. */
+export async function listFailedProposals(engine: BrainEngine, sourceId: string): Promise<Array<{ slug: string; code: string; prompt_version: string; proposed_at: string }>> {
+ const rows = await engine.executeRaw<{ slug: string; claim_text: string; prompt_version: string; proposed_at: string }>(
+ `SELECT page_slug AS slug, claim_text, prompt_version, proposed_at::text AS proposed_at FROM take_proposals
+ WHERE source_id = $1 AND status = 'rejected' AND acted_at IS NULL AND starts_with(claim_text, $2) ORDER BY page_slug`, [sourceId, TOMBSTONE_PREFIX]);
+ return rows.map(row => ({ slug: row.slug, code: row.claim_text.slice(TOMBSTONE_PREFIX.length, -1), prompt_version: row.prompt_version, proposed_at: row.proposed_at }));
+}
+
+/** Deletes the failure tombstones (and ledger records) of one page or every page of a source, so the next run re-extracts them. */
+export async function retryFailedProposals(engine: BrainEngine, sourceId: string, slug?: string): Promise<{ released: string[] }> {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `DELETE FROM take_proposals WHERE source_id = $1 AND status = 'rejected' AND acted_at IS NULL AND starts_with(claim_text, $2)
+ AND ($3::text IS NULL OR page_slug = $3) RETURNING page_slug AS slug`, [sourceId, TOMBSTONE_PREFIX, slug ?? null]);
+ const ledger = await loadFailureLedger(engine, sourceId);
+ const pages = slug === undefined ? {} : Object.fromEntries(Object.entries(ledger.pages).filter(([key]) => key !== slug));
+ if (Object.keys(pages).length !== Object.keys(ledger.pages).length) await saveFailureLedger(engine, sourceId, { ...ledger, pages });
+ return { released: [...new Set(rows.map(row => row.slug))].sort() };
+}
+
+/** One page whose extractor call failed this run, as the phase reports it. */
+export interface FailedPage {
+ slug: string;
+ key: string;
+ code: string;
+ class: 'content' | 'transient';
+ message: string;
+ /** Counted runs in a row this page failed the same way; a page reaching PROPOSE_TAKES_HOLD_RUNS is `held`. */
+ attempts: number;
+ held: boolean;
+ /** Set on a held page: the command that releases it. */
+ fix: Action | null;
+}
+
+type RunFailure = { sourceId: string; slug: string; contentHash: string; failure: ClassifiedItemFailure };
+
+/** The failure ledgers of every source one run touches, and that run's extractor outcomes. */
+export class ProposeTakesFailures {
+ private readonly itemRun = new ItemRun('propose_takes.pages');
+ private readonly failures: RunFailure[] = [];
+ private readonly succeeded: Array<{ sourceId: string; slug: string }> = [];
+ /** Failures of pages not recorded before; only these feed the breaker and the #3763 halt. */
+ freshFailures = 0;
+
+ private constructor(private readonly ledgers: Map<string, ProposeTakesFailureLedger>, private readonly promptVersion: string) {}
+
+ static async load(engine: BrainEngine, sourceIds: Iterable<string>, promptVersion: string): Promise<ProposeTakesFailures> {
+ const ledgers = new Map<string, ProposeTakesFailureLedger>();
+ for (const id of new Set(sourceIds)) ledgers.set(id, await loadFailureLedger(engine, id));
+ return new ProposeTakesFailures(ledgers, promptVersion);
+ }
+
+ /** The page's record when it failed before at this content hash and prompt version. */
+ known(sourceId: string, slug: string, contentHash: string): ProposeTakesFailureRecord | undefined {
+ const record = this.ledgers.get(sourceId)?.pages[slug];
+ return record && record.content_hash === contentHash && record.prompt_version === this.promptVersion ? record : undefined;
+ }
+
+ /** Fresh pages first; a page that failed before at this hash and prompt version is retried after them. */
+ order<T extends { slug: string }>(pages: T[], key: (page: T) => [sourceId: string, contentHash: string]): T[] {
+ const failing = (page: T) => this.known(key(page)[0], page.slug, key(page)[1]) !== undefined;
+ return [...pages.filter(page => !failing(page)), ...pages.filter(failing)];
+ }
+
+ /** Records an extractor failure; a run-scoped error (abort, lost connection, failed transaction) is rethrown. */
+ fail(sourceId: string, slug: string, contentHash: string, err: unknown): void {
+ const known = this.known(sourceId, slug, contentHash) !== undefined;
+ const failure = known ? classifyItemFailure(err) : this.itemRun.record(slug, err).failure;
+ if (failure.scope === 'run') throw err;
+ this.failures.push({ sourceId, slug, contentHash, failure });
+ if (!known) this.freshFailures += 1;
+ }
+
+ succeed(sourceId: string, slug: string, contentHash: string): void {
+ if (this.known(sourceId, slug, contentHash) === undefined) this.itemRun.succeed();
+ this.succeeded.push({ sourceId, slug });
+ }
+
+ /**
+ * Folds the run into the ledgers and returns the failed pages. A systemic run
+ * (most fresh pages failed) or a whole-run LLM halt (`counted` false) records its failures
+ * (so the pages are retried after fresh ones) but neither count nor reset.
+ * A counted content failure counts only with evidence that the extractor
+ * works: a success in this run, or a stored success no earlier than the run
+ * in which the page first failed. A page reaching PROPOSE_TAKES_HOLD_RUNS gets a failure
+ * tombstone (a `rejected` take_proposals row) and leaves the ledger.
+ */
+ async settle(engine: BrainEngine, run: { counted: boolean; proposalRunId: string; modelId: string }):
+ Promise<{ failed: FailedPage[]; tombstones: number; systemic?: { code: string; message: string } }> {
+ const now = new Date().toISOString();
+ const systemic = this.itemRun.systemic();
+ const counted = run.counted && !systemic;
+ const changed = new Set<string>();
+ const out: FailedPage[] = [];
+ let tombstones = 0;
+ for (const { sourceId, slug } of this.succeeded) {
+ const ledger = this.ledgers.get(sourceId)!;
+ ledger.success = { prompt_version: this.promptVersion, at: now };
+ if (Object.keys(ledger.pages).length > 0) changed.add(sourceId);
+ delete ledger.pages[slug];
+ }
+ for (const { sourceId, slug, contentHash, failure } of this.failures) {
+ const ledger = this.ledgers.get(sourceId)!;
+ const prior = this.known(sourceId, slug, contentHash);
+ const evidence = this.succeeded.length > 0
+ || (prior !== undefined && ledger.success?.prompt_version === this.promptVersion && ledger.success.at >= prior.first_failed_at);
+ const attempts = !counted || !evidence ? prior?.attempts ?? 0
+ : failure.class !== 'content' ? 0
+ : (prior?.code === failure.code ? prior.attempts : 0) + 1;
+ const held = attempts >= PROPOSE_TAKES_HOLD_RUNS;
+ if (held) {
+ await engine.executeRaw(
+ `INSERT INTO take_proposals
+ (source_id, page_slug, content_hash, prompt_version, proposal_run_id,
+ claim_text, kind, holder, weight, domain, dedup_against_fence_rows, model_id, status)
+ VALUES ($1, $2, $3, $4, $5, $6, 'fact', 'brain', 0, NULL, '[]'::jsonb, $7, 'rejected')
+ ON CONFLICT (source_id, page_slug, content_hash, prompt_version, md5(claim_text)) DO NOTHING`,
+ [sourceId, slug, contentHash, this.promptVersion, run.proposalRunId, failureTombstoneText(failure.code), run.modelId],
+ );
+ tombstones += 1;
+ delete ledger.pages[slug];
+ } else {
+ ledger.pages[slug] = { content_hash: contentHash, prompt_version: this.promptVersion, code: failure.code, class: failure.class,
+ message: failure.message.slice(0, 300), attempts, first_failed_at: prior?.first_failed_at ?? now, last_failed_at: now };
+ }
+ changed.add(sourceId);
+ out.push({ slug, key: slug, code: failure.code, class: failure.class, message: failure.message.slice(0, 300), attempts, held,
+ fix: held ? retryFailedAction(sourceId, slug) : null });
+ }
+ for (const sourceId of changed) await saveFailureLedger(engine, sourceId, this.ledgers.get(sourceId)!);
+ return { failed: out, tombstones, systemic: systemic ? { code: 'item_failures_systemic', message: systemic.message } : undefined };
+ }
+}
diff --git a/src/core/cycle/propose-takes.ts b/src/core/cycle/propose-takes.ts
index 7f11515b87..f868cbebaf 100644
--- a/src/core/cycle/propose-takes.ts
+++ b/src/core/cycle/propose-takes.ts
@@ -58,6 +58,7 @@ import { matchingCloseBracket } from '../llm-json.ts';
import { TAKE_KIND_VALUES } from '../takes-fence.ts';
import { attributionChecksEnabled } from './attribution-checks.ts';
import { downgradeAssistantOnlyHolders } from './propose-takes-attribution.ts';
+import { ProposeTakesFailures, PROPOSE_TAKES_HOLD_RUNS, type FailedPage } from './propose-takes-failures.ts';
import type { OperationContext } from '../operations.ts';
import type { BrainEngine } from '../engine.ts';
import type { PhaseStatus, CyclePhase } from '../cycle.ts';
@@ -271,6 +272,12 @@ export interface ProposeTakesResult {
llm_calls_succeeded: number;
/** Extractor calls that threw (global or per-page alike). */
llm_calls_failed: number;
+ /** GBRA-130 A-25: every page whose extractor call failed this run, with its counted attempts; a `held` page got a failure tombstone. */
+ failed_pages: FailedPage[];
+ /** Failure tombstones written this run (pages held after PROPOSE_TAKES_HOLD_RUNS counted runs failing the same way). */
+ failure_tombstones_written: number;
+ /** Set when most fresh pages failed (item_failures_systemic): this run's failures were recorded but not counted. */
+ systemic?: { code: string; message: string };
warnings: string[];
}
@@ -909,6 +916,8 @@ class ProposeTakesPhase extends BaseCyclePhase {
budget_exhausted: false,
llm_calls_succeeded: 0,
llm_calls_failed: 0,
+ failed_pages: [],
+ failure_tombstones_written: 0,
warnings: callTimeout.warning ? [callTimeout.warning] : [],
deadline_hit: false,
};
@@ -927,7 +936,12 @@ class ProposeTakesPhase extends BaseCyclePhase {
}
// Load pages eligible for proposal. Source-scoped per BaseCyclePhase; #5213 types narrow it.
- const pages = await listCandidatePages(engine, scope, pageLimit, await proposeTakesTypes(engine));
+ // GBRA-130 A-25: a page that failed before at this content hash and prompt
+ // version is retried after the fresh pages, so failing pages at the head of
+ // the list cannot halt the run before the rest are tried.
+ const listed = await listCandidatePages(engine, scope, pageLimit, await proposeTakesTypes(engine));
+ const failures = await ProposeTakesFailures.load(engine, listed.map(page => page.source_id ?? scope.sourceId ?? 'default'), promptVersion);
+ const pages = failures.order(listed, page => [page.source_id ?? scope.sourceId ?? 'default', contentHash(page.compiled_truth ?? '')]);
if (opts.reporter) {
opts.reporter.start('propose_takes.pages' as never, pages.length);
@@ -1011,6 +1025,10 @@ class ProposeTakesPhase extends BaseCyclePhase {
attributionRules, dateGrounding,
});
} catch (err) {
+ // GBRA-130: a run-scoped error (abort, lost connection, failed
+ // transaction) stops the phase and records nothing. Fresh pages feed
+ // the breaker; a page retried after an earlier failure does not.
+ failures.fail(sourceId, page.slug, ch, err);
result.llm_calls_failed += 1;
const msg = err instanceof Error ? err.message : String(err);
const detail = `extractor failed on ${page.slug}: ${msg}`;
@@ -1028,9 +1046,11 @@ class ProposeTakesPhase extends BaseCyclePhase {
// Halt instead of spending an LLM call on every remaining page. A
// single success anywhere in the run keeps llm_calls_succeeded > 0
// and permanently disarms this halt (mixed runs are per-page noise).
+ // GBRA-130 A-25: only fresh pages count; pages that failed before are
+ // retried last and their failures are the expected outcome.
if (
result.llm_calls_succeeded === 0 &&
- result.llm_calls_failed >= EXTRACTOR_FAILURE_HALT_STREAK
+ failures.freshFailures >= EXTRACTOR_FAILURE_HALT_STREAK
) {
result.aborted_failure_streak = true;
result.warnings.push(
@@ -1043,6 +1063,7 @@ class ProposeTakesPhase extends BaseCyclePhase {
continue;
}
result.llm_calls_succeeded += 1;
+ failures.succeed(sourceId, page.slug, ch);
llmHalt.reset();
if (attributionChecks) proposals = downgradeAssistantOnlyHolders(proposals, body);
@@ -1117,53 +1138,17 @@ class ProposeTakesPhase extends BaseCyclePhase {
if (opts.reporter) opts.reporter.finish();
- // v0.42 Wave B3: receipt + rollup for propose_takes. Source-scoped
- // via the read scope. Receipt only when proposals actually written.
- const sourceIdForReceipt = scope.sourceId ?? 'default';
- // Managed brains skip the receipt page (a legacy putPage the coordinator
- // refuses), like extract_atoms and synthesize_concepts; the rollup stays.
- if (result.proposals_inserted > 0 && !await managedPersistenceEnabled(engine)) {
- try {
- await writeReceipt(engine, {
- kind: 'takes.proposed',
- source_id: sourceIdForReceipt,
- run_id: proposalRunId,
- round: 'single',
- extracted_at: new Date().toISOString(),
- total_rows: result.proposals_inserted,
- cost_usd: 0, // tracker isn't exposed at this layer; cost tracked centrally
- summary:
- `Proposed ${result.proposals_inserted} new takes from ${result.pages_scanned} pages ` +
- `(${result.cache_hits} cached).`,
- });
- } catch (err) {
- console.error(`[propose_takes] receipt write failed: ${(err as Error).message}`);
- }
- }
- // #4482: three-way stop classification. A budget/deadline cap is the
- // extractor working as designed (partial progress banked; the rest
- // drains over future runs) — recorded as expected_limit_delta, a
- // capacity signal doctor's failure rate excludes. A global-error abort
- // (#3044) or an all-failures streak (#3763) is a REAL halt, unchanged
- // from today. An error alongside a cap counts as the error.
- // `halted` (any incomplete round, caps included) is kept for the phase
- // result's status/details below — the diagnostic split is rollup-only.
- const halted =
- result.budget_exhausted ||
- result.deadline_hit === true ||
- result.aborted_global_error !== undefined ||
- result.aborted_failure_streak === true;
- await upsertExtractRollup(engine, {
- kind: 'takes.proposed',
- source_id: sourceIdForReceipt,
- ...classifyRunStop({
- budget_exhausted: result.budget_exhausted === true,
- deadline_hit: result.deadline_hit === true,
- error:
- result.aborted_global_error !== undefined ? providerHaltReason(result.aborted_global_error) ?? 'item_error'
- : result.aborted_failure_streak === true ? 'item_error' : false,
- }),
- });
+ // GBRA-130 A-25: fold this run into the failure ledgers. A page failing the
+ // same content-class way in PROPOSE_TAKES_HOLD_RUNS counted runs gets a
+ // failure tombstone (the idempotency check then skips it until its content
+ // or the prompt version changes); a systemic run or a whole-run LLM halt
+ // counts nothing.
+ const settled = await failures.settle(engine, { counted: result.aborted_global_error === undefined, proposalRunId, modelId });
+ result.failed_pages = settled.failed;
+ result.failure_tombstones_written = settled.tombstones;
+ if (settled.systemic) result.systemic = settled.systemic;
+
+ const halted = await recordProposeTakesRun(engine, result, scope.sourceId ?? 'default', proposalRunId);
// Status folds warnings in (the extract_facts precedent from #1928): a
// run with swallowed per-page failures must not read as a clean 'ok'.
@@ -1181,6 +1166,9 @@ class ProposeTakesPhase extends BaseCyclePhase {
return {
summary:
`propose_takes: scanned ${result.pages_scanned} pages, ${result.cache_hits} cached, ${result.proposals_inserted} new proposals, ${result.tombstones_written} empty (run ${proposalRunId})` +
+ (result.failure_tombstones_written > 0
+ ? `; ${result.failure_tombstones_written} page(s) held after ${PROPOSE_TAKES_HOLD_RUNS} failed runs (gbrain takes propose --failed)`
+ : '') +
(result.aborted_global_error
? `; aborted on ${result.aborted_global_error} error after ${result.pages_scanned} page(s)`
: '') +
@@ -1194,6 +1182,57 @@ class ProposeTakesPhase extends BaseCyclePhase {
}
}
+/** The takes.proposed receipt and rollup of one run; returns whether the run halted (any cap or halt). */
+async function recordProposeTakesRun(engine: BrainEngine, result: ProposeTakesResult, sourceIdForReceipt: string, proposalRunId: string): Promise<boolean> {
+ // v0.42 Wave B3: receipt + rollup for propose_takes. Source-scoped
+ // via the read scope. Receipt only when proposals actually written.
+ // Managed brains skip the receipt page (a legacy putPage the coordinator
+ // refuses), like extract_atoms and synthesize_concepts; the rollup stays.
+ if (result.proposals_inserted > 0 && !await managedPersistenceEnabled(engine)) {
+ try {
+ await writeReceipt(engine, {
+ kind: 'takes.proposed',
+ source_id: sourceIdForReceipt,
+ run_id: proposalRunId,
+ round: 'single',
+ extracted_at: new Date().toISOString(),
+ total_rows: result.proposals_inserted,
+ cost_usd: 0, // tracker isn't exposed at this layer; cost tracked centrally
+ summary:
+ `Proposed ${result.proposals_inserted} new takes from ${result.pages_scanned} pages ` +
+ `(${result.cache_hits} cached).`,
+ });
+ } catch (err) {
+ console.error(`[propose_takes] receipt write failed: ${(err as Error).message}`);
+ }
+ }
+ // #4482: three-way stop classification. A budget/deadline cap is the
+ // extractor working as designed (partial progress banked; the rest
+ // drains over future runs) — recorded as expected_limit_delta, a
+ // capacity signal doctor's failure rate excludes. A global-error abort
+ // (#3044) or an all-failures streak (#3763) is a REAL halt, unchanged
+ // from today. An error alongside a cap counts as the error.
+ // `halted` (any incomplete round, caps included) is kept for the phase
+ // result's status/details below — the diagnostic split is rollup-only.
+ const halted =
+ result.budget_exhausted ||
+ result.deadline_hit === true ||
+ result.aborted_global_error !== undefined ||
+ result.aborted_failure_streak === true;
+ await upsertExtractRollup(engine, {
+ kind: 'takes.proposed',
+ source_id: sourceIdForReceipt,
+ ...classifyRunStop({
+ budget_exhausted: result.budget_exhausted === true,
+ deadline_hit: result.deadline_hit === true,
+ error:
+ result.aborted_global_error !== undefined ? providerHaltReason(result.aborted_global_error) ?? 'item_error'
+ : result.aborted_failure_streak === true ? 'item_error' : false,
+ }),
+ });
+ return halted;
+}
+
/**
* Public entry point — mirrors the v0.23 `runPhaseSynthesize` shape so the
* cycle orchestrator in cycle.ts can call it uniformly.
diff --git a/test/pathological/a25-propose-takes-poison-pages.test.ts b/test/pathological/a25-propose-takes-poison-pages.test.ts
new file mode 100644
index 0000000000..3d6d5a055b
--- /dev/null
+++ b/test/pathological/a25-propose-takes-poison-pages.test.ts
@@ -0,0 +1,176 @@
+/**
+ * GBRA-130 A-25: propose_takes (src/core/cycle/propose-takes.ts) listed the
+ * newest pages first, never memoized a failed extraction and halted after 5
+ * failures with zero successes. A page whose extractor call fails the same
+ * way every time (a prompt too long for the model, a provider content block)
+ * was re-billed every cycle, and when the 5 newest uncached pages all failed,
+ * the zero-success halt fired before any older page every run.
+ *
+ * Authoring gate: (1) protects "a deterministically failing page stops being
+ * billed and never blocks the rest": a page that failed before is retried
+ * after the fresh pages, the halt streak counts fresh pages only, and a page
+ * failing with the same content-class code in 3 counted runs at the same
+ * content hash and prompt version gets a failure tombstone (distinct from a
+ * successful empty extraction) that `gbrain takes propose --retry-failed`
+ * releases and that a content or prompt-version change bypasses; a
+ * run-scoped extractor error stops the phase and records nothing; a run where
+ * most fresh pages fail counts nothing. (2) Reverting the ordering or the
+ * counting makes the item case red (the healthy page never gets a proposal).
+ * (3) test/propose-takes.test.ts pins the #3763 halt on a mock engine, never
+ * a failing head of the list across runs. (4) No production seam: the
+ * extractor is the phase's existing injection point.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { AIConfigError } from '../../src/core/ai/errors.ts';
+import { runPhaseProposeTakes, type ProposeTakesExtractor } from '../../src/core/cycle/propose-takes.ts';
+import { retryFailedProposals } from '../../src/core/cycle/propose-takes-failures.ts';
+import { runTakes } from '../../src/commands/takes.ts';
+import { isolatedSharedSkillsEngine } from '../helpers/shared-skills-engine.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const SOURCE = 'default';
+const PAGES = ['page-01', 'page-02', 'page-03', 'page-04', 'page-05', 'page-06'];
+const POISON = new Set(PAGES.slice(0, 5));
+const HEALTHY = 'page-06';
+const tooLong = () => Object.assign(new AIConfigError('[chat(anthropic:claude-example)] prompt is too long: 250000 tokens > 200000 maximum'), { status: 400 });
+
+interface Failed { slug: string; key: string; code: string; class: string; attempts: number; held: boolean; fix: unknown }
+
+async function withBrain(databaseUrl: string | undefined, run: (engine: BrainEngine) => Promise<void>, pages = PAGES): Promise<void> {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ for (const [i, slug] of pages.entries()) {
+ await engine.putPage(slug, { type: 'note' as never, title: slug, compiled_truth: `Body of ${slug}: liquidity decides which marketplace wins.`, timeline: '', frontmatter: {} });
+ await engine.executeRaw(`UPDATE pages SET updated_at = now() - ($1::int * interval '1 hour') WHERE source_id = $2 AND slug = $3`, [i + 1, SOURCE, slug]);
+ }
+ await run(engine);
+ } finally { await close(); }
+}
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, config: {} as never, logger: { info() {}, warn() {}, error() {} } as never,
+ dryRun: false, remote: false, sourceId: SOURCE });
+
+function extractor(failing: (slug: string) => unknown | null, calls: string[] = []): ProposeTakesExtractor {
+ return async ({ pagePath }) => {
+ calls.push(pagePath);
+ const error = failing(pagePath);
+ if (error) throw error;
+ return [{ claim_text: `Claim from ${pagePath}`, kind: 'take', holder: 'brain', weight: 0.6 }];
+ };
+}
+
+const poison = (slug: string) => POISON.has(slug) ? tooLong() : null;
+const run = async (engine: BrainEngine, ex: ProposeTakesExtractor, extra: Record<string, unknown> = {}) => {
+ const result = await expectUnitNotAborted(() => runPhaseProposeTakes(ctx(engine), { extractor: ex, deadlineMs: 600_000, ...extra }));
+ return { result, details: result.details as Record<string, unknown> & { failed_pages?: Failed[] } };
+};
+
+async function proposals(engine: BrainEngine): Promise<Record<string, string[]>> {
+ const rows = await engine.executeRaw<{ page_slug: string; claim_text: string }>(
+ 'SELECT page_slug, claim_text FROM take_proposals WHERE source_id = $1 ORDER BY page_slug, claim_text', [SOURCE]);
+ const out: Record<string, string[]> = {};
+ for (const row of rows) (out[row.page_slug] ??= []).push(row.claim_text);
+ return out;
+}
+
+const failureTombstone = '(extraction failed: request_too_large)';
+/** Every run rewrites its own extract receipt page; every other page must stay as it was. */
+const receipts = (snapshot: Map<string, unknown>) => ({ changed: [...snapshot.keys()].filter(slug => slug.startsWith('extracts/')) });
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`A-25 propose_takes: a page that keeps failing is tombstoned and never blocks the rest (${backend})`, () => {
+ test('A-25 item: the 5 newest pages fail every run; the 6th page gets proposals and the 5 carry a failure tombstone after 4 runs', () => withBrain(databaseUrl, async engine => {
+ const before = await snapshotItems(engine, SOURCE);
+ const calls: string[][] = [];
+ const runs = [];
+ for (let i = 0; i < 4; i++) { const c: string[] = []; calls.push(c); runs.push(await run(engine, extractor(poison, c))); }
+ const got = await proposals(engine);
+ expect(got[HEALTHY]).toEqual([`Claim from ${HEALTHY}`]);
+ for (const slug of POISON) expect({ slug, rows: got[slug] }).toEqual({ slug, rows: [failureTombstone] });
+ expect(calls[1]![0]).toBe(HEALTHY);
+ const last = runs[3]!.details.failed_pages!;
+ expect(last.map(f => [f.slug, f.attempts, f.held])).toEqual([...POISON].map(slug => [slug, 3, true]));
+ expectItemFailure(last[0], { key: 'page-01', code: 'request_too_large', fix: /gbrain takes propose --retry-failed --slug page-01 --source default/ });
+
+ const fifth = await run(engine, extractor(poison));
+ expect({ calls: fifth.details.llm_calls_succeeded as number + (fifth.details.llm_calls_failed as number), cache_hits: fifth.details.cache_hits })
+ .toEqual({ calls: 0, cache_hits: 6 });
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), receipts(before));
+ }), 120_000);
+
+ test('A-25 item: a failure tombstone stays distinct from a successful empty extraction', () => withBrain(databaseUrl, async engine => {
+ for (let i = 0; i < 4; i++) await run(engine, extractor(slug => slug === 'page-01' ? tooLong() : null));
+ const rows = await engine.executeRaw<{ page_slug: string; claim_text: string; status: string }>(
+ "SELECT page_slug, claim_text, status FROM take_proposals WHERE source_id = $1 AND page_slug = 'page-01'", [SOURCE]);
+ expect(rows).toEqual([{ page_slug: 'page-01', claim_text: failureTombstone, status: 'rejected' }]);
+ }), 120_000);
+
+ test('A-25 recovery: retry-failed releases the tombstone, and a content change bypasses it', () => withBrain(databaseUrl, async engine => {
+ for (let i = 0; i < 4; i++) await run(engine, extractor(poison));
+ const released = await retryFailedProposals(engine, SOURCE, 'page-01');
+ expect(released).toEqual({ released: ['page-01'] });
+ await engine.putPage('page-02', { type: 'note' as never, title: 'page-02', compiled_truth: 'A shorter page-02 the model can read.', timeline: '', frontmatter: {} });
+ const before = await snapshotItems(engine, SOURCE);
+ const healed = await run(engine, extractor(() => null));
+ expect(healed.details.failed_pages).toEqual([]);
+ const got = await proposals(engine);
+ expect({ p1: got['page-01'], p2: got['page-02']?.includes('Claim from page-02') }).toEqual({ p1: ['Claim from page-01'], p2: true });
+ expect(got['page-03']).toEqual([failureTombstone]);
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), receipts(before));
+ }), 120_000);
+
+ test('A-25 recovery: the fix a held page names (takes propose --retry-failed) releases it, and --failed lists what is held', () => withBrain(databaseUrl, async engine => {
+ let last: Failed[] = [];
+ for (let i = 0; i < 4; i++) last = (await run(engine, extractor(poison))).details.failed_pages!;
+ const cli = async (argv: string[]) => {
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };
+ try { await runTakes(engine, argv); } finally { console.log = log; }
+ return JSON.parse(lines.join('\n'));
+ };
+ const fix = last.find(f => f.slug === 'page-01')!.fix as { argv: string[]; verify: { argv: string[] } };
+ expect(fix.argv.slice(0, 2)).toEqual(['gbrain', 'takes']);
+ expect((await cli(fix.verify.argv.slice(2))).map((f: { slug: string; code: string }) => [f.slug, f.code]))
+ .toEqual([...POISON].map(slug => [slug, 'request_too_large']));
+ expect(await cli([...fix.argv.slice(2), '--json'])).toEqual({ source_id: SOURCE, released: ['page-01'] });
+ expect((await cli(fix.verify.argv.slice(2))).map((f: { slug: string }) => f.slug)).toEqual([...POISON].filter(slug => slug !== 'page-01'));
+ await run(engine, extractor(() => null));
+ expect((await proposals(engine))['page-01']).toEqual(['Claim from page-01']);
+ }), 120_000);
+
+ test('A-25 recovery: a prompt-version change retries a tombstoned page', () => withBrain(databaseUrl, async engine => {
+ for (let i = 0; i < 4; i++) await run(engine, extractor(poison), { promptVersion: 'v-example-1' });
+ const calls: string[] = [];
+ await run(engine, extractor(() => null, calls), { promptVersion: 'v-example-2' });
+ expect(calls.sort()).toEqual([...PAGES].sort());
+ }), 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test(`A-25 run: a run-scoped ${name} from the extractor stops the phase and records no failure`, () => withBrain(databaseUrl, async engine => {
+ const before = await snapshotItems(engine, SOURCE);
+ const calls: string[] = [];
+ const { result } = await run(engine, extractor(() => error(), calls));
+ expect(result.status).toBe('fail');
+ expect(calls).toEqual(['page-01']);
+ expect(await proposals(engine)).toEqual({});
+ const ledger = await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op = 'propose-takes-failures'");
+ expect(ledger).toEqual([]);
+ expectOthersUnchanged(before, await snapshotItems(engine, SOURCE), receipts(before));
+ }), 120_000);
+ }
+
+ test('A-25 breaker: when every page fails, no run counts a failure and no page is ever tombstoned', () => withBrain(databaseUrl, async engine => {
+ const runs = [];
+ for (let i = 0; i < 4; i++) runs.push(await run(engine, extractor(() => tooLong())));
+ expect(await proposals(engine)).toEqual({});
+ expect(runs[0]!.details.systemic).toMatchObject({ code: 'item_failures_systemic' });
+ for (const { details } of runs) {
+ expect(details.failed_pages!.length).toBeGreaterThan(0);
+ expect(details.failed_pages!.filter(f => f.attempts !== 0 || f.held)).toEqual([]);
+ }
+ }), 120_000);
+ });
+}