Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): C-9 re-submit dead put_page facts-absorb jobs once the cause clears

garrytan2bf2df57f59c
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 07f8b9a094..8934ce12bd 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1587 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)
src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout
-src/core/config.ts 1985 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys)
+src/core/config.ts 1986 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts)
src/core/persistence/sync-run.ts 1778 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured
src/core/bootstrap/harness.ts 2584 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
diff --git a/src/cli/commands/facts.ts b/src/cli/commands/facts.ts
index 054ed747da..cd5d31d01d 100644
--- a/src/cli/commands/facts.ts
+++ b/src/cli/commands/facts.ts
@@ -18,7 +18,7 @@ export async function run(args: string[], ctx: CliDispatchContext): Promise<void
const { resolveSourceId, ALL_SOURCES } = await import('../../core/source-resolver.ts');
const flag = args.indexOf('--source');
const sourceId = await resolveSourceId(eng, flag >= 0 ? args[flag + 1] : null);
- if (sourceId === ALL_SOURCES) {
+ if (sourceId === ALL_SOURCES && args[0] !== 'retry-dead') {
console.error('gbrain facts relink repairs one source at a time; pass --source <id>.');
setCliExitVerdict(1);
return;
diff --git a/src/commands/doctor/checks/knowledge-health.ts b/src/commands/doctor/checks/knowledge-health.ts
index c162b25e3e..c9cb0ee01d 100644
--- a/src/commands/doctor/checks/knowledge-health.ts
+++ b/src/commands/doctor/checks/knowledge-health.ts
@@ -320,6 +320,20 @@ async function runFactsExtraction(ctx: DoctorContext): Promise<Check[]> {
user_message: `Facts extraction for ${newestDead.slug ?? 'a page'} failed and its job is dead. Retrying job ${newestDead.id} makes one paid model call. Should I retry it?` });
}
}
+ // C-9: the dead page-write facts-absorb retry set, whatever the 24 h window holds.
+ const { readDeadFactsAbsorbRetry, factsRetryDeadCommand } = await import('../../../core/facts/dead-absorb-retry.ts');
+ const retry = await readDeadFactsAbsorbRetry(engine).catch(() => null);
+ if (check && retry && (retry.pending || retry.exhausted.length || retry.not_retryable.length)) {
+ check.message = `${check.message} Dead facts-absorb retry set: ${retry.pending} pending (the next maintenance pass re-submits them once extraction is servable), ` +
+ `${retry.exhausted.length} exhausted after ${retry.max_resubmits} re-submit(s), ${retry.not_retryable.length} not retryable (a deterministic failure; fix its cause, then gbrain jobs retry <id>). ` +
+ `See ${factsRetryDeadCommand('--list')}${retry.exhausted[0] ? `; re-enable one with ${factsRetryDeadCommand('--reset', retry.exhausted[0].key)}` : ''}.`;
+ check.details = { ...(check.details ?? {}), facts_absorb_retry: retry };
+ if (retry.exhausted.length) {
+ check.status = 'warn';
+ check.fix ??= agentFix(['gbrain', 'facts', 'retry-dead', '--list', '--json'],
+ 'Read-only: lists the dead facts-absorb jobs the maintenance pass stopped re-submitting, each with its reset command.', 'facts_extraction_health');
+ }
+ }
const note = await conversationPipelineNote(engine);
if (note && check) {
check.message = `${check.message} ${note.message}`;
diff --git a/src/commands/facts.ts b/src/commands/facts.ts
index 4bb9eb63bb..53bd90cd6a 100644
--- a/src/commands/facts.ts
+++ b/src/commands/facts.ts
@@ -8,13 +8,15 @@ import type { GBrainConfig } from '../core/config.ts';
import { RELINK_DEFAULT_LIMIT, RELINK_DEFAULT_MAX_USD, runFactsRelink, type RelinkOptions, type RelinkReport } from '../core/facts/relink.ts';
import { RELINK_REASONS, type RelinkReason } from '../core/facts/relink-reasons.ts';
import { CONVERSATION_RELINK_PAGES, runConversationRelink, type ConversationRelinkReport } from '../core/facts/conversation-relink.ts';
+import { DEFAULT_MAX_RESUBMITS, FACTS_ABSORB_RETRY_MAX_KEY, factsRetryDeadCommand, readDeadFactsAbsorbRetry, updateDeadFactsAbsorbKeys } from '../core/facts/dead-absorb-retry.ts';
export function factsHelpText(): string {
return `Usage: gbrain facts <subcommand>
Subcommands:
- relink Link facts saved without an entity to the person, company or
- project they are about, onto that entity page's ## Facts fence.
+ relink Link facts saved without an entity to the person, company or
+ project they are about, onto that entity page's ## Facts fence.
+ retry-dead Show or reset the retry set of dead page-write facts-absorb jobs.
gbrain facts relink [flags]
--source <id> Source to repair (default: the resolved source)
@@ -41,7 +43,21 @@ gbrain facts relink --conversation [--source <id>] [--slugs <a,b>] [--dry-run] [
Relink never creates pages and never supersedes a fact. Exact duplicates are
retired (expired, kept in history). Linked facts are queued for the System One
conflict sweep when that slot is on. Free tiers cost nothing; the model tier
-uses facts.extraction_model and stops at --max-usd.`;
+uses facts.extraction_model and stops at --max-usd.
+
+gbrain facts retry-dead [--list] [--json]
+gbrain facts retry-dead --reset <key>|--all [--json]
+gbrain facts retry-dead --clear <key>|--all [--json]
+ A put_page's facts-absorb job that died on a provider or configuration
+ failure is re-submitted by the next maintenance pass (the facts_drain
+ phase) once extraction is servable again, at most
+ ${FACTS_ABSORB_RETRY_MAX_KEY} times per job (default ${DEFAULT_MAX_RESUBMITS}; 0 disables) and at most
+ once an hour. --list shows the set: pending, exhausted (at the limit),
+ cleared and not retryable (a deterministic failure). --reset lets the next
+ pass re-submit a key again (naming a not-retryable job's key, after its
+ cause is fixed, adds it); --clear stops re-submitting a key. Keys are the
+ jobs' idempotency keys (facts-absorb:write:<request id>). Each re-submitted
+ job is one paid extraction call when it runs.`;
}
interface ParsedArgs { opts: Omit<RelinkOptions, 'config'>; json: boolean; error?: string }
@@ -168,6 +184,34 @@ async function runConversation(engine: BrainEngine, args: string[], config: GBra
return 0;
}
+/** C-9: the dead facts-absorb retry set (src/core/facts/dead-absorb-retry.ts). Exit 1 on a usage error. */
+async function runRetryDead(engine: BrainEngine, args: string[]): Promise<number> {
+ if (args.includes('--help') || args.includes('-h')) { console.log(factsHelpText()); return 0; }
+ const json = args.includes('--json');
+ const action = args.includes('--reset') ? 'reset' : args.includes('--clear') ? 'clear' : null;
+ if (args.includes('--reset') && args.includes('--clear')) { console.error('gbrain facts retry-dead: pass one of --reset or --clear.'); return 1; }
+ if (!action) {
+ const status = await readDeadFactsAbsorbRetry(engine);
+ if (json) { console.log(JSON.stringify(status, null, 2)); return 0; }
+ console.log(`Dead facts-absorb retry set (limit ${status.max_resubmits} re-submit(s) per job${status.max_resubmits === 0 ? ', disabled' : ''}):`);
+ console.log(` pending ${status.pending}, exhausted ${status.exhausted.length}, cleared ${status.cleared}, not retryable ${status.not_retryable.length}${status.waiting_on ? ` (waiting on ${status.waiting_on})` : ''}`);
+ for (const e of status.exhausted) console.log(` exhausted job ${e.job_id} ${e.slug ?? ''} after ${e.resubmits} re-submit(s); reset: ${factsRetryDeadCommand('--reset', e.key)}`);
+ for (const e of status.not_retryable.slice(0, 20)) console.log(` not retryable job ${e.job_id} ${e.slug ?? ''}: fix the cause in its error (gbrain jobs get ${e.job_id}), then gbrain jobs retry ${e.job_id}`);
+ return 0;
+ }
+ const flag = args.indexOf(`--${action}`);
+ const target = args[flag + 1];
+ const all = args.includes('--all');
+ if (!all && (!target || target.startsWith('--'))) { console.error(`gbrain facts retry-dead --${action} needs a key (facts-absorb:write:<request id>) or --all; gbrain facts retry-dead --list shows them.`); return 1; }
+ const changed = await updateDeadFactsAbsorbKeys(engine, action, all ? 'all' : [target!]);
+ if (json) console.log(JSON.stringify({ status: action, keys: changed }, null, 2));
+ else if (changed.length === 0) console.log(`No dead facts-absorb job matches ${all ? '--all' : target}; gbrain facts retry-dead --list shows the set.`);
+ else console.log(action === 'reset'
+ ? `Reset ${changed.length} key(s); the next maintenance pass may re-submit them (one paid extraction call each).`
+ : `Cleared ${changed.length} key(s); they stay dead and are not re-submitted again.`);
+ return 0;
+}
+
/** Exit code: 0 for complete and partial runs (limit or budget), 1 for usage errors. */
export async function runFactsCommand(engine: BrainEngine, args: string[], config: GBrainConfig, sourceId: string): Promise<number> {
const sub = args[0];
@@ -175,6 +219,7 @@ export async function runFactsCommand(engine: BrainEngine, args: string[], confi
console.log(factsHelpText());
return 0;
}
+ if (sub === 'retry-dead') return runRetryDead(engine, args.slice(1));
if (sub !== 'relink') {
console.error(`gbrain facts: unknown subcommand ${sub}\n\n${factsHelpText()}`);
return 1;
diff --git a/src/core/config.ts b/src/core/config.ts
index 8e95073510..908ac15b0e 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1490,6 +1490,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'facts.extraction_max_tokens',
// Automatic facts drain caps (src/core/facts/drain.ts FACTS_DRAIN_KEYS).
'facts.drain_budget_usd', 'facts.drain_daily_budget_usd', 'facts.drain_max_jobs',
+ 'facts.absorb_retry.max_resubmits', // C-9: re-submits per dead page-write facts-absorb job (default 3; 0 disables; facts/dead-absorb-retry.ts)
// #3852: operator-set system-prompt appendix for the facts extractor (e.g.
// a durable-vs-ephemeral rubric for agent work-session transcripts).
// Composes with BOTH honest-notability prompt variants.
diff --git a/src/core/cycle/facts-drain.ts b/src/core/cycle/facts-drain.ts
index c14a93f5f1..8a6dfc784d 100644
--- a/src/core/cycle/facts-drain.ts
+++ b/src/core/cycle/facts-drain.ts
@@ -5,19 +5,29 @@
* `gbrain jobs work`. Postgres brains have a job worker and skip the phase.
* The phase never fails the cycle: deferrals (no key, budget) report `warn`
* with the fix; an internal error reports `warn` with the doctor command.
+ *
+ * C-9: on every engine the phase first re-submits dead page-write facts-absorb jobs whose provider or config cause
+ * has cleared (src/core/facts/dead-absorb-retry.ts), so on PGLite the drain below runs them in the same pass.
*/
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
import { FACTS_DRAIN_DEFERRALS, FACTS_DRAIN_WALL_MS, runFactsDrain } from '../facts/drain.ts';
import { CYCLE_DEADLINE_RESERVE_MS } from './base-phase.ts';
+import { retryDeadFactsAbsorb, type DeadAbsorbRetryResult } from '../facts/dead-absorb-retry.ts';
export async function runPhaseFactsDrain(engine: BrainEngine | null, opts: { dryRun: boolean; signal?: AbortSignal; deadlineAtMs?: number | null }): Promise<PhaseResult> {
const base = { phase: 'facts_drain' as const, duration_ms: 0 };
if (!engine) return { ...base, status: 'skipped', summary: 'no database connected', details: { reason: 'no_database' } };
+ const deadRetry = await retryDeadFactsAbsorb(engine, { dryRun: opts.dryRun }).catch((e: unknown): DeadAbsorbRetryResult & { error: string } => ({
+ max_resubmits: 0, pending: 0, resubmitted: 0, exhausted: [], cleared: 0, not_retryable: [], error: e instanceof Error ? e.message : String(e) }));
+ const retryNote = deadRetrySummary(deadRetry);
+ const dead_retry = { resubmitted: deadRetry.resubmitted, pending: deadRetry.pending, exhausted: deadRetry.exhausted.length, not_retryable: deadRetry.not_retryable.length,
+ ...(deadRetry.waiting_on ? { waiting_on: deadRetry.waiting_on } : {}), ...('error' in deadRetry ? { error: deadRetry.error } : {}) };
+ const retryWarn = deadRetry.exhausted.length > 0 || 'error' in deadRetry;
if (engine.kind !== 'pglite') {
- return { ...base, status: 'skipped', summary: 'Postgres brains run facts-absorb jobs on the job worker', details: { reason: 'not_applicable' } };
+ return { ...base, status: retryWarn ? 'warn' : 'skipped', summary: `Postgres brains run facts-absorb jobs on the job worker${retryNote}`, details: { reason: 'not_applicable', dead_retry } };
}
- if (opts.dryRun) return { ...base, status: 'skipped', summary: 'dry run: no facts extracted', details: { reason: 'dry_run' } };
+ if (opts.dryRun) return { ...base, status: 'skipped', summary: `dry run: no facts extracted${retryNote}`, details: { reason: 'dry_run', dead_retry } };
const remaining = opts.deadlineAtMs != null ? opts.deadlineAtMs - CYCLE_DEADLINE_RESERVE_MS - Date.now() : FACTS_DRAIN_WALL_MS;
if (remaining <= 0) return { ...base, status: 'skipped', summary: 'no cycle time left for the facts drain', details: { reason: 'deadline' } };
const r = await runFactsDrain(engine, { owner: 'cycle', signal: opts.signal, wallClockMs: Math.min(FACTS_DRAIN_WALL_MS, remaining) });
@@ -25,10 +35,20 @@ export async function runPhaseFactsDrain(engine: BrainEngine | null, opts: { dry
outcome: r.outcome, completed: r.completed, failed: r.failed, deferred: r.deferred, facts_inserted: r.facts_inserted,
spent_usd: r.spent_usd, unpriced_calls: r.unpriced_calls, backlog_before: r.backlog_before, backlog_after: r.backlog_after, model: r.model,
...(r.error ? { code: r.error.code, reason: r.error.reason, fix: r.error.fix } : {}),
+ dead_retry,
};
if (r.outcome === 'disabled') return { ...base, status: 'skipped', summary: 'facts extraction is off (facts.extraction_enabled false)', details };
- if (r.outcome === 'idle' || r.outcome === 'not_applicable') return { ...base, status: 'ok', summary: 'no queued facts-absorb jobs', details };
+ if (r.outcome === 'idle' || r.outcome === 'not_applicable') return { ...base, status: retryWarn ? 'warn' : 'ok', summary: `no queued facts-absorb jobs${retryNote}`, details };
const summary = `${r.completed} page(s) extracted (${r.facts_inserted} facts, $${r.spent_usd.toFixed(3)}), ${r.backlog_after ?? '?'} still queued` +
- (r.error ? `: ${r.error.message}` : '');
- return { ...base, status: FACTS_DRAIN_DEFERRALS.has(r.outcome) || r.failed > 0 ? 'warn' : 'ok', summary, details };
+ (r.error ? `: ${r.error.message}` : '') + retryNote;
+ return { ...base, status: FACTS_DRAIN_DEFERRALS.has(r.outcome) || r.failed > 0 || retryWarn ? 'warn' : 'ok', summary, details };
+}
+
+function deadRetrySummary(r: DeadAbsorbRetryResult & { error?: string }): string {
+ const parts = [
+ r.resubmitted ? `re-submitted ${r.resubmitted} dead facts-absorb job(s)` : '',
+ r.exhausted.length ? `${r.exhausted.length} dead facts-absorb job(s) reached the re-submit limit (${r.max_resubmits}); see gbrain facts retry-dead --list` : '',
+ r.error ? `dead facts-absorb retry failed: ${r.error}` : '',
+ ].filter(Boolean);
+ return parts.length ? `; ${parts.join('; ')}` : '';
}
diff --git a/src/core/facts/dead-absorb-retry.ts b/src/core/facts/dead-absorb-retry.ts
new file mode 100644
index 0000000000..fb898a4549
--- /dev/null
+++ b/src/core/facts/dead-absorb-retry.ts
@@ -0,0 +1,193 @@
+/**
+ * C-9 (#6948 sweep, #6761): the retry set for dead page-write facts-absorb jobs.
+ *
+ * A put_page's facts-backstop effect submits one facts-absorb job (idempotency key facts-absorb:write:<request id>,
+ * 5 attempts) and completes as 'queued' in the same transaction, so nothing dispatches it again. When the job dies
+ * on a provider or configuration failure (an outage, a revoked key, #6113), that revision's facts would never land.
+ *
+ * Each maintenance pass (the facts_drain cycle phase, any engine) reads the dead page-write jobs. A job whose error
+ * is a provider or configuration failure is recorded in a durable set keyed by its idempotency key (config row
+ * facts.absorb_retry.state). Once the cause has cleared (extraction enabled and its model servable), the pass
+ * re-submits it in place (gbrain jobs retry semantics: same row, same key, fresh attempts), at most
+ * facts.absorb_retry.max_resubmits times per key (default 3; 0 disables) and at most once an hour per key, and at
+ * most MAX_RESUBMITS_PER_PASS keys per pass. A key at its limit is exhausted: it stays dead and visible until an
+ * operator resets it (gbrain facts retry-dead --reset <key>) or clears it (--clear <key>: never re-submitted again).
+ * A job that died on anything else (a deterministic write refusal, an unclassified error) is not retryable: it stays
+ * dead and is counted. Entries settle when their job completes or its row is gone.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { classifyJobError } from '../minions/error-classify.ts';
+
+export const FACTS_ABSORB_RETRY_STATE_KEY = 'facts.absorb_retry.state';
+export const FACTS_ABSORB_RETRY_MAX_KEY = 'facts.absorb_retry.max_resubmits';
+export const DEFAULT_MAX_RESUBMITS = 3;
+export const MAX_RESUBMITS_PER_PASS = 20;
+export const RESUBMIT_SPACING_MS = 60 * 60_000;
+const WRITE_KEY_PREFIX = 'facts-absorb:write:';
+
+export type DeadAbsorbClass = 'provider' | 'config' | 'not_retryable';
+
+/**
+ * Provider and configuration failures clear on their own or with an operator fix; everything else stays dead.
+ * Extraction failures carry `[facts-extract] <reason> (model=..) (cause=<class> <global llm class>)` (extract.ts):
+ * provider_error and chat_unavailable are retryable; refusal, content filter, malformed or truncated output fail the
+ * same way on the same page text.
+ */
+export function classifyDeadFactsAbsorb(errorText: string | null | undefined): DeadAbsorbClass {
+ const text = errorText ?? '';
+ if (/facts_absorb_write_refused/.test(text)) return 'not_retryable';
+ const extract = /^\[facts-extract\] ([a-z_]+)/.exec(text);
+ if (extract) {
+ if (extract[1] === 'chat_unavailable') return 'config';
+ if (extract[1] !== 'provider_error') return 'not_retryable';
+ return /\(cause=[^)]*\b(auth|billing|model_not_found)\b/.test(text) ? 'config' : 'provider';
+ }
+ if (/chat_unavailable|no usable provider key|not servable|model[_ ]not[_ ]found|billing|insufficient[_ ]quota|credit/i.test(text)) return 'config';
+ if (/ECONNREFUSED|ECONNRESET|ENOTFOUND|ETIMEDOUT|EAI_AGAIN|EPIPE|fetch failed|socket hang up|network error/i.test(text)) return 'provider';
+ const cluster = classifyJobError(text);
+ if (cluster === 'auth') return 'config';
+ if (cluster === 'rate_limit' || cluster === 'rate_lease_full' || cluster === 'http_5xx' || cluster === 'timeout') return 'provider';
+ return 'not_retryable';
+}
+
+export interface RetryEntry {
+ /** not_retryable only when an operator reset that key by name. */
+ job_id: number; slug: string | null; source_id: string; class: DeadAbsorbClass;
+ first_dead_at: string; resubmits: number; last_resubmit_at: string | null; cleared_at: string | null;
+}
+interface RetryState { version: 1; keys: Record<string, RetryEntry> }
+
+export interface DeadAbsorbRetryResult {
+ max_resubmits: number;
+ /** Retryable dead jobs in the set that the next pass may re-submit (under the limit, not cleared). */
+ pending: number;
+ resubmitted: number;
+ /** Keys at the limit: dead until reset. */
+ exhausted: Array<{ key: string; job_id: number; slug: string | null; resubmits: number }>;
+ cleared: number;
+ not_retryable: Array<{ job_id: number; slug: string | null }>;
+ /** Why nothing was re-submitted this pass although keys were pending. */
+ waiting_on?: 'extraction_disabled' | 'extraction_unavailable' | 'spacing' | 'disabled' | 'dry_run';
+}
+
+export function factsRetryDeadCommand(flag: '--list' | '--reset' | '--clear', key?: string): string {
+ return ['gbrain facts retry-dead', flag, ...(key ? [`'${key.replaceAll("'", "'\\''")}'`] : [])].join(' ');
+}
+
+export async function loadMaxResubmits(engine: BrainEngine): Promise<number> {
+ const raw = await engine.getConfig(FACTS_ABSORB_RETRY_MAX_KEY).catch(() => null);
+ if (raw === null || raw === undefined || raw.trim() === '') return DEFAULT_MAX_RESUBMITS;
+ const n = Number(raw);
+ return Number.isSafeInteger(n) && n >= 0 ? n : DEFAULT_MAX_RESUBMITS;
+}
+
+async function readState(engine: BrainEngine): Promise<RetryState> {
+ try {
+ const raw = await engine.getConfig(FACTS_ABSORB_RETRY_STATE_KEY);
+ const parsed = raw ? JSON.parse(raw) as Partial<RetryState> : null;
+ if (parsed && parsed.keys && typeof parsed.keys === 'object' && !Array.isArray(parsed.keys)) return { version: 1, keys: parsed.keys };
+ } catch { /* an unreadable set is rebuilt from the dead rows */ }
+ return { version: 1, keys: {} };
+}
+
+const writeState = (engine: BrainEngine, state: RetryState) => engine.setConfig(FACTS_ABSORB_RETRY_STATE_KEY, JSON.stringify(state));
+
+const JOB_COLUMNS = "id, idempotency_key, status, error_text, data->>'slug' AS slug, COALESCE(data->>'sourceId', 'default') AS source_id, finished_at";
+const newEntry = (row: JobRow, cls: DeadAbsorbClass, now: number): RetryEntry => ({ job_id: Number(row.id), slug: row.slug, source_id: row.source_id, class: cls,
+ first_dead_at: new Date(row.finished_at ?? now).toISOString(), resubmits: 0, last_resubmit_at: null, cleared_at: null });
+
+interface JobRow { id: number | string; idempotency_key: string; status: string; error_text: string | null; slug: string | null; source_id: string; finished_at: string | Date | null }
+
+/** Reconcile the set with the dead rows; with apply, re-submit the eligible keys and persist. */
+async function reconcile(engine: BrainEngine, opts: { apply: boolean; record?: boolean; now: number }): Promise<DeadAbsorbRetryResult> {
+ const state = await readState(engine);
+ const max = await loadMaxResubmits(engine);
+ const rows = await engine.executeRaw<JobRow>(
+ `SELECT ${JOB_COLUMNS} FROM minion_jobs
+ WHERE name = 'facts-absorb' AND idempotency_key LIKE $1 AND (status = 'dead' OR idempotency_key = ANY($2::text[]))`,
+ [`${WRITE_KEY_PREFIX}%`, Object.keys(state.keys)]);
+ const byKey = new Map(rows.map(r => [r.idempotency_key, r]));
+ for (const key of Object.keys(state.keys)) {
+ const row = byKey.get(key);
+ if (!row || row.status === 'completed' || row.status === 'cancelled') delete state.keys[key];
+ }
+ const result: DeadAbsorbRetryResult = { max_resubmits: max, pending: 0, resubmitted: 0, exhausted: [], cleared: 0, not_retryable: [] };
+ for (const row of rows) {
+ if (row.status !== 'dead') continue;
+ const cls = classifyDeadFactsAbsorb(row.error_text);
+ const known = state.keys[row.idempotency_key];
+ if (cls === 'not_retryable' && !known) { result.not_retryable.push({ job_id: Number(row.id), slug: row.slug }); continue; }
+ state.keys[row.idempotency_key] = known ?? newEntry(row, cls, opts.now);
+ }
+ const due: string[] = [];
+ let spaced = false;
+ for (const [key, entry] of Object.entries(state.keys)) {
+ if (byKey.get(key)?.status !== 'dead') continue;
+ if (entry.cleared_at) { result.cleared++; continue; }
+ if (entry.resubmits >= max) { result.exhausted.push({ key, job_id: entry.job_id, slug: entry.slug, resubmits: entry.resubmits }); continue; }
+ result.pending++;
+ if (entry.last_resubmit_at && opts.now - Date.parse(entry.last_resubmit_at) < RESUBMIT_SPACING_MS) { spaced = true; continue; }
+ due.push(key);
+ }
+ if (max === 0 && Object.keys(state.keys).length) result.waiting_on = 'disabled';
+ else if (due.length === 0 && result.pending > 0 && spaced) result.waiting_on = 'spacing';
+ if (due.length && !opts.apply) result.waiting_on = 'dry_run';
+ if (due.length && opts.apply) {
+ const { isFactsExtractionEnabled } = await import('./extract.ts');
+ const { resolveExtractionAvailability } = await import('./extraction-availability.ts');
+ // As the drain does: a key or model fixed since the process started counts as the cause clearing.
+ const { refreshGatewayEnvFromFilePlane, reconfigureGatewayWithEngine } = await import('../ai/gateway.ts');
+ refreshGatewayEnvFromFilePlane();
+ await reconfigureGatewayWithEngine(engine).catch(() => undefined);
+ if (!await isFactsExtractionEnabled(engine)) result.waiting_on = 'extraction_disabled';
+ else if (!(await resolveExtractionAvailability(engine)).available) result.waiting_on = 'extraction_unavailable';
+ else {
+ const { MinionQueue } = await import('../minions/queue.ts');
+ const queue = new MinionQueue(engine);
+ for (const key of due.slice(0, MAX_RESUBMITS_PER_PASS)) {
+ const entry = state.keys[key]!;
+ if (!await queue.retryJob(entry.job_id)) continue;
+ entry.resubmits++;
+ entry.last_resubmit_at = new Date(opts.now).toISOString();
+ result.resubmitted++;
+ result.pending--;
+ }
+ }
+ }
+ if (opts.apply || opts.record) await writeState(engine, state);
+ return result;
+}
+
+/** One maintenance pass: record, settle and re-submit. dryRun reports what would happen and writes nothing. */
+export function retryDeadFactsAbsorb(engine: BrainEngine, opts: { dryRun?: boolean; now?: number } = {}): Promise<DeadAbsorbRetryResult> {
+ return reconcile(engine, { apply: !opts.dryRun, now: opts.now ?? Date.now() });
+}
+
+/** Read-only status for doctor and gbrain facts retry-dead --list (nothing is written or re-submitted). */
+export async function readDeadFactsAbsorbRetry(engine: BrainEngine, now = Date.now()): Promise<DeadAbsorbRetryResult> {
+ const r = await reconcile(engine, { apply: false, now });
+ if (r.waiting_on === 'dry_run') delete r.waiting_on;
+ return r;
+}
+
+/**
+ * Operator controls. reset: the key's resubmits count from zero and it is no longer cleared, so the next pass may
+ * re-submit it; naming a dead page-write job the set does not hold (one that died not retryable, after its cause was
+ * fixed) adds it. clear: the key is never re-submitted again and stays listed as cleared. Returns the keys changed.
+ */
+export async function updateDeadFactsAbsorbKeys(engine: BrainEngine, action: 'reset' | 'clear', keys: string[] | 'all', now = Date.now()): Promise<string[]> {
+ await reconcile(engine, { apply: false, record: true, now });
+ const state = await readState(engine);
+ if (keys !== 'all') {
+ const rows = await engine.executeRaw<JobRow>(`SELECT ${JOB_COLUMNS} FROM minion_jobs WHERE name = 'facts-absorb' AND status = 'dead' AND idempotency_key = ANY($1::text[])`, [keys]);
+ for (const row of rows) state.keys[row.idempotency_key] ??= newEntry(row, classifyDeadFactsAbsorb(row.error_text), now);
+ }
+ const targets = (keys === 'all' ? Object.keys(state.keys) : keys).filter(k => state.keys[k]);
+ for (const key of targets) {
+ const entry = state.keys[key]!;
+ if (action === 'reset') { entry.resubmits = 0; entry.last_resubmit_at = null; entry.cleared_at = null; }
+ else entry.cleared_at = new Date(now).toISOString();
+ }
+ await writeState(engine, state);
+ return targets;
+}
diff --git a/test/helpers/config-reader-registry.ts b/test/helpers/config-reader-registry.ts
index 62daee8c3e..b659ef673a 100644
--- a/test/helpers/config-reader-registry.ts
+++ b/test/helpers/config-reader-registry.ts
@@ -30,6 +30,7 @@ export const INTERNAL_CONFIG_STATE: readonly InternalConfigState[] = [
{ key: 'embedding_migration.state', reason: 'gbrain migrate-embeddings resume state' },
{ key: 'embedding_migration.completed', reason: 'gbrain migrate-embeddings completion marker' },
{ key: 'facts.drain_state', reason: 'facts drain scheduler state (facts/drain.ts)' },
+ { key: 'facts.absorb_retry.state', reason: 'dead facts-absorb re-submit set (facts/dead-absorb-retry.ts); gbrain facts retry-dead edits it' },
{ key: 'google.file_modes_notice', reason: 'one-time upgrade notice marker (v0.60.31 migration)' },
{ key: 'notices.behavior_changes.http', reason: 'behavior-change notice shown-marker for serve --http' },
{ key: 'ocr_attempted', reason: 'image-OCR run counter (import-file.ts), read by doctor queue_assets' },
diff --git a/test/pathological/c-9-facts-absorb-dead.test.ts b/test/pathological/c-9-facts-absorb-dead.test.ts
index 649e81b53b..26358282bd 100644
--- a/test/pathological/c-9-facts-absorb-dead.test.ts
+++ b/test/pathological/c-9-facts-absorb-dead.test.ts
@@ -27,7 +27,15 @@ import { configureGateway, resetGateway, __setChatTransportForTests, type ChatRe
import { __resetFactsDrainNoticesForTests, runFactsDrain } from '../../src/core/facts/drain.ts';
import { _resetLlmHaltCooldownsForTests } from '../../src/core/minions/llm-halt-cooldown.ts';
import { runPhaseFactsDrain } from '../../src/core/cycle/facts-drain.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { RESUBMIT_SPACING_MS, classifyDeadFactsAbsorb, readDeadFactsAbsorbRetry, retryDeadFactsAbsorb, updateDeadFactsAbsorbKeys } from '../../src/core/facts/dead-absorb-retry.ts';
+import { factsExtractionEntry } from '../../src/commands/doctor/checks/knowledge-health.ts';
+import type { DoctorContext } from '../../src/commands/doctor/context.ts';
+import type { Check } from '../../src/commands/doctor.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { testBackends, requirePostgresTestDatabase } from '../helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
import { withEnv } from '../helpers/with-env.ts';
import { LATEST_SCHEMA_VERSION } from '../../src/core/schema-migrations/latest.generated.ts';
@@ -111,4 +119,111 @@ describe('C-9: a dead put_page facts-absorb job is re-submitted once its cause c
expect(await factCount()).toBe(1);
expect((await job(id)).status).toBe('completed');
}), 120_000);
+ test('the cause has not cleared: nothing is re-submitted while extraction is not servable, then the job runs once it is', () => isolated(async () => {
+ const id = await putPageJob();
+ __setChatTransportForTests(async () => { throw new Error('fetch failed: connect ECONNREFUSED 127.0.0.1:443'); });
+ await drainUntilDead(id);
+ // The provider key is gone (the outage was a revoked key): nothing is re-submitted.
+ await withEnv({ ANTHROPIC_API_KEY: undefined, OPENAI_API_KEY: undefined }, async () => {
+ configureGateway({ embedding_disabled: true, env: {} } as never);
+ __setChatTransportForTests(null);
+ const waiting = await retryDeadFactsAbsorb(engine);
+ expect(waiting).toMatchObject({ resubmitted: 0, pending: 1, waiting_on: 'extraction_unavailable' });
+ });
+ expect((await job(id)).status).toBe('dead');
+ configureGateway({ embedding_disabled: true, env: KEYS } as never);
+ expect(await retryDeadFactsAbsorb(engine)).toMatchObject({ resubmitted: 1, pending: 0 });
+ expect((await job(id)).status).toBe('waiting');
+ }), 120_000);
+
+ test('bounded: at most one re-submit an hour and max_resubmits per key; then exhausted until reset; clear stops it for good', () => isolated(async () => {
+ const id = await putPageJob();
+ __setChatTransportForTests(async () => { throw new Error('fetch failed: connect ECONNREFUSED 127.0.0.1:443'); });
+ await drainUntilDead(id);
+ await engine.setConfig('facts.absorb_retry.max_resubmits', '2');
+ let now = Date.now();
+ for (let round = 1; round <= 2; round++) {
+ expect(await retryDeadFactsAbsorb(engine, { now })).toMatchObject({ resubmitted: 1 });
+ await drainUntilDead(id);
+ expect(await retryDeadFactsAbsorb(engine, { now: now + 1_000 })).toMatchObject({ resubmitted: 0, ...(round < 2 ? { waiting_on: 'spacing' } : {}) });
+ now += RESUBMIT_SPACING_MS + 1;
+ }
+ const exhausted = await retryDeadFactsAbsorb(engine, { now });
+ expect(exhausted).toMatchObject({ resubmitted: 0, pending: 0 });
+ expect(exhausted.exhausted).toEqual([expect.objectContaining({ job_id: id, resubmits: 2 })]);
+ const key = exhausted.exhausted[0]!.key;
+
+ // Doctor names the count and the one command.
+ const [check] = await factsExtractionEntry.run({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext) as Check[];
+ expect(check!.status).toBe('warn');
+ expect(check!.message).toContain('1 exhausted after 2 re-submit(s)');
+ expect(check!.message).toContain(`gbrain facts retry-dead --reset '${key}'`);
+ expect(check!.details).toMatchObject({ facts_absorb_retry: { pending: 0, exhausted: [expect.objectContaining({ key })] } });
+
+ expect(await updateDeadFactsAbsorbKeys(engine, 'reset', [key], now)).toEqual([key]);
+ expect(await retryDeadFactsAbsorb(engine, { now })).toMatchObject({ resubmitted: 1 });
+ await drainUntilDead(id);
+ expect(await updateDeadFactsAbsorbKeys(engine, 'clear', 'all', now)).toEqual([key]);
+ expect(await retryDeadFactsAbsorb(engine, { now: now + 10 * RESUBMIT_SPACING_MS })).toMatchObject({ resubmitted: 0, pending: 0, cleared: 1 });
+ expect((await job(id)).status).toBe('dead');
+ }), 120_000);
+
+ test('a deterministic failure stays dead and is reported not retryable; naming its key in a reset re-enables it', () => isolated(async () => {
+ const queue = new MinionQueue(engine);
+ await engine.putPage('notes/c9-refused', { type: 'note', title: 'Refused', compiled_truth: 'Acme Example shipped the beta in 2026.', timeline: '', frontmatter: {} } as never);
+ const key = `facts-absorb:write:${randomUUID()}`;
+ const added = await queue.add('facts-absorb', { slug: 'notes/c9-refused', sourceId: 'default', source: 'mcp:put_page' }, { queue: 'default', idempotency_key: key, max_attempts: 5 });
+ await engine.executeRaw("UPDATE minion_jobs SET status='dead', finished_at=now(), error_text=$2 WHERE id=$1",
+ [added.id, '[facts-extract] malformed_output (model=anthropic:claude-sonnet-4-6)']);
+ const pass = await retryDeadFactsAbsorb(engine);
+ expect(pass).toMatchObject({ resubmitted: 0, pending: 0 });
+ expect(pass.not_retryable).toEqual([{ job_id: added.id, slug: 'notes/c9-refused' }]);
+ expect((await job(added.id)).status).toBe('dead');
+ expect((await readDeadFactsAbsorbRetry(engine)).not_retryable).toHaveLength(1);
+ expect(await updateDeadFactsAbsorbKeys(engine, 'reset', [key])).toEqual([key]);
+ expect(await retryDeadFactsAbsorb(engine)).toMatchObject({ resubmitted: 1 });
+ }), 120_000);
});
+
+describe('C-9: dead facts-absorb failure classes', () => {
+ test('provider and config failures are retryable; write refusals and content-deterministic extraction failures are not', () => {
+ expect(classifyDeadFactsAbsorb('[facts-extract] provider_error (model=anthropic:claude-sonnet-4-6) (cause=Error)')).toBe('provider');
+ expect(classifyDeadFactsAbsorb('[facts-extract] provider_error (model=openai:gpt-6.1-sol) (cause=APIError auth)')).toBe('config');
+ expect(classifyDeadFactsAbsorb('[facts-extract] chat_unavailable (model=openai:gpt-6.1-sol)')).toBe('config');
+ expect(classifyDeadFactsAbsorb('503 Service Unavailable')).toBe('provider');
+ expect(classifyDeadFactsAbsorb('Job timed out after 600000ms')).toBe('provider');
+ for (const deterministic of ['[facts-extract] malformed_output (model=x)', '[facts-extract] refusal (model=x)', '[facts-extract] truncated_output (model=x)',
+ 'facts_absorb_write_refused (permission_denied): refused. Not retried.', 'TypeError: cannot read properties of undefined', null]) {
+ expect(classifyDeadFactsAbsorb(deterministic)).toBe('not_retryable');
+ }
+ });
+});
+
+// Postgres: the job worker runs facts-absorb jobs and the facts_drain phase does not drain, but the phase still
+// re-submits a dead page-write job there, and the set and its SQL behave the same.
+for (const backend of testBackends().filter(b => b === 'postgres')) {
+ describe(`C-9 on ${backend}: the maintenance pass re-submits a dead page-write job for the worker`, () => {
+ test('a dead provider_error job is re-queued by the facts_drain phase; a write refusal stays dead', () => isolated(async () => {
+ const { engine: pg, close } = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ try {
+ const db: BrainEngine = pg;
+ await db.setConfig('facts.extraction_model', MODEL);
+ const queue = new MinionQueue(db);
+ const add = async (slug: string, errorText: string) => {
+ const j = await queue.add('facts-absorb', { slug, sourceId: 'default', source: 'mcp:put_page' }, { queue: 'default', idempotency_key: `facts-absorb:write:${randomUUID()}`, max_attempts: 5 });
+ await db.executeRaw("UPDATE minion_jobs SET status='dead', finished_at=now(), attempts_started=5, attempts_made=5, error_text=$2 WHERE id=$1", [j.id, errorText]);
+ return j.id;
+ };
+ const outage = await add('notes/c9-pg-outage', '[facts-extract] provider_error (model=anthropic:claude-sonnet-4-6) (cause=Error)');
+ const refused = await add('notes/c9-pg-refused', 'facts_absorb_write_refused (permission_denied): refused. Not retried.');
+ const pass = await runPhaseFactsDrain(db, { dryRun: false });
+ expect(pass.details).toMatchObject({ reason: 'not_applicable', dead_retry: { resubmitted: 1, not_retryable: 1 } });
+ const status = async (id: number) => (await db.executeRaw<{ status: string; attempts_made: number }>('SELECT status, attempts_made FROM minion_jobs WHERE id=$1', [id]))[0]!;
+ expect(await status(outage)).toEqual({ status: 'waiting', attempts_made: 0 });
+ expect((await status(refused)).status).toBe('dead');
+ await db.executeRaw("UPDATE minion_jobs SET status='completed', finished_at=now() WHERE id=$1", [outage]);
+ expect(await readDeadFactsAbsorbRetry(db)).toMatchObject({ pending: 0, exhausted: [], not_retryable: [{ job_id: refused }] });
+ } finally { await close(); }
+ }), 120_000);
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 12e8291655..e84ff6ff31 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -327,3 +327,4 @@ test/vector-manifest-probe-bound.test.ts
test/withdrawal-overlay-concurrency.test.ts
test/withdrawal-publication-file.test.ts
test/writer-status-owner-backends.test.ts
+test/pathological/c-9-facts-absorb-dead.test.ts