Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(synthesize-concepts): read cycle.synthesize_concepts.budget_usd and say when the cap is hit (#4907)

time-attack9258fc3d8101
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 401ecc279d..3e6d80bad3 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -37,7 +37,7 @@ src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/patterns.ts runPhasePatterns 303 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/propose-takes.ts ProposeTakesPhase.process 427 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
-src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 467 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock
+src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 473 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 #5490 review: a narrative a chat_fallback_chain model wrote is hashed under that model so the next cycle re-synthesizes it; +13 fix wave 9 lane P (D-N3): fence-stripped member hash with legacy-hash grandfathering, and the classic write moved to publishClassicConcept (concept-publication.ts); +3 (#5041): opt-in concept write-through hook and the import callback publishClassicConcept runs under the page lock; +6 #4907 (issue #4906): configured budget read, budget-capped counter, summary clause and details.warnings (message text in budgetWarnings)
src/core/cycle/synthesize.ts runPhaseSynthesizeInner 1046 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase
src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/import-file.ts importFromContent 808 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 08c28eab80..6b2f5c2725 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1586 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 1903 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
src/core/chunkers/code.ts 1588 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)
-src/core/config.ts 1872 ratchet +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)
+src/core/config.ts 1874 ratchet +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)
src/core/bootstrap/harness.ts 2711 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
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
src/core/ops/pages.ts 671 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose
diff --git a/src/commands/config.ts b/src/commands/config.ts
index a81d37fbae..40bb9640ba 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1183,6 +1183,13 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }
}
+ // #4907: a phase knob the phase would ignore is refused before the write.
+ const { PHASE_CONFIG_KEYS, parsePhaseConfigValue } = await import('../core/cycle/phase-config-values.ts');
+ if (PHASE_CONFIG_KEYS.includes(key)) {
+ try { parsePhaseConfigValue(key, value); }
+ catch (error) { (await import('../cli/cli-error.ts')).exitCliError(error, 'config'); }
+ }
+
// #5254: an unknown value would silently keep refusing unbound writes.
const { UNBOUND_WRITE_KEY, parseUnboundWriteValue } = await import('../core/persistence/unbound-source.ts');
if (key === UNBOUND_WRITE_KEY) {
diff --git a/src/core/config.ts b/src/core/config.ts
index 77fc8e7fc4..b4f5c8b501 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1394,6 +1394,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'models.dream.synthesize',
'models.dream.extract_atoms',
'cycle.extract_atoms.budget_usd',
+ // #4907: synthesize_concepts phase budget (finite USD > 0, default 1.5); cycle/phase-config-values.ts.
+ 'cycle.synthesize_concepts.budget_usd',
'cycle.extract_atoms.max_source_chars',
'cycle.extract_atoms.page_discovery_budget',
// #4540: per-item extractor caps (defaults 50000 chars / 4096 tokens) plus
diff --git a/src/core/cycle/phase-config-values.ts b/src/core/cycle/phase-config-values.ts
new file mode 100644
index 0000000000..90f73faded
--- /dev/null
+++ b/src/core/cycle/phase-config-values.ts
@@ -0,0 +1,99 @@
+/**
+ * Registered numeric knobs for dream-cycle phases that a phase reads through
+ * `engine.getConfig` at run time. One spec per key carries the accepted
+ * range, so `gbrain config set` refuses a value the phase would not apply, and
+ * the phase names the key when a stored value is invalid or out of range
+ * instead of falling back silently. Neither the refusal nor the warning
+ * echoes the stored or rejected value.
+ */
+import { opError, type OperationError } from '../ops/contract.ts';
+
+export const SYNTHESIZE_CONCEPTS_BUDGET_KEY = 'cycle.synthesize_concepts.budget_usd';
+export const SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD = 1.5;
+
+interface PhaseConfigSpec {
+ /** Human range, used in the refusal and the stored-value warnings. */
+ expected: string;
+ /** What applies when the key is unset or its stored value is invalid. */
+ defaultText: string;
+ /** The value `config set` accepts, or null. */
+ parse(raw: string): number | null;
+ /** A stored value the phase holds to the range instead of ignoring; null = invalid. */
+ clamp?(raw: string): number | null;
+}
+
+const finitePositive = (raw: string): number | null => {
+ const text = raw.trim();
+ const n = Number(text);
+ return text !== '' && Number.isFinite(n) && n > 0 ? n : null;
+};
+
+const SPECS: Record<string, PhaseConfigSpec> = {
+ [SYNTHESIZE_CONCEPTS_BUDGET_KEY]: {
+ expected: 'a finite number of US dollars above 0',
+ defaultText: String(SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD),
+ parse: finitePositive,
+ },
+};
+
+export const PHASE_CONFIG_KEYS: readonly string[] = Object.keys(SPECS);
+
+function specFor(key: string): PhaseConfigSpec {
+ const spec = SPECS[key];
+ if (!spec) throw new Error(`not a phase config key: ${key}`);
+ return spec;
+}
+
+/** `config set` validation: the parsed value, or an `invalid_params` refusal naming the key and range. */
+export function parsePhaseConfigValue(key: string, value: string): number {
+ const spec = specFor(key);
+ const parsed = spec.parse(value);
+ if (parsed !== null) return parsed;
+ throw invalidPhaseConfig(key, spec);
+}
+
+function invalidPhaseConfig(key: string, spec: PhaseConfigSpec): OperationError {
+ return opError('invalid_params', `Invalid ${key}: expected ${spec.expected}.`,
+ `Set ${key} to ${spec.expected} (default: ${spec.defaultText}), or unset it to use the default.`,
+ {
+ why: `The phase reads ${key} on every run and would not apply this value. Nothing was written.`,
+ fix: {
+ argv: ['gbrain', 'config', 'set', key, '<VALUE>'],
+ inputs: [{ name: 'VALUE', how: `${spec.expected[0]!.toUpperCase()}${spec.expected.slice(1)}; ask the user when the intended value is unclear.` }],
+ consent: [], actor: 'agent', requires_exclusive: false,
+ why: `A value in range is applied on the next run; unset the key to use the default (${spec.defaultText}).`,
+ verify: { argv: ['gbrain', 'config', 'get', key] },
+ },
+ });
+}
+
+function storedValueWarning(key: string, spec: PhaseConfigSpec, using: string): string {
+ return `${key} is set to an invalid value (expected ${spec.expected}); using ${using}. ` +
+ `Fix: gbrain config set ${key} <value>, or gbrain config unset ${key}. Verify: gbrain config get ${key}`;
+}
+
+/**
+ * Read one phase knob. Unset or unreadable keeps the default with no warning
+ * (a config lookup never stops a maintenance phase). An accepted value is used
+ * as-is; a value the spec clamps is held to the range with a warning; anything
+ * else keeps the default with a warning. `value` is undefined for the default.
+ */
+export async function readPhaseConfigNumber(
+ engine: { getConfig?(key: string): Promise<string | null> },
+ key: string,
+): Promise<{ value?: number; warning?: string }> {
+ const spec = specFor(key);
+ let raw: string | null | undefined;
+ try {
+ raw = await engine.getConfig?.(key);
+ } catch {
+ return {};
+ }
+ if (raw === null || raw === undefined || String(raw).trim() === '') return {};
+ const text = String(raw);
+ const parsed = spec.parse(text);
+ if (parsed !== null) return { value: parsed };
+ const clamped = spec.clamp?.(text) ?? null;
+ if (clamped !== null) return { value: clamped, warning: storedValueWarning(key, spec, String(clamped)) };
+ return { warning: storedValueWarning(key, spec, `the default (${spec.defaultText})`) };
+}
diff --git a/src/core/cycle/synthesize-concepts.ts b/src/core/cycle/synthesize-concepts.ts
index b46e02428d..76c623ed86 100644
--- a/src/core/cycle/synthesize-concepts.ts
+++ b/src/core/cycle/synthesize-concepts.ts
@@ -46,8 +46,8 @@ import { derivedWriteThrough } from './derived-write-through.ts';
import {
addManagedProvenanceLinks, CONCEPT_DEFERRAL_CODES, CONCEPT_HOLD_CODES, publishClassicConcept, publishManagedConcept, stripFenceSections,
} from './concept-publication.ts';
+import { readPhaseConfigNumber, SYNTHESIZE_CONCEPTS_BUDGET_KEY, SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD } from './phase-config-values.ts';
-const DEFAULT_BUDGET_USD = 1.5;
// Miss policy for the shared resolver (`priceFor`: operator overrides, the
// claude-cli → Anthropic sibling, canonical rows): assume Sonnet-tier
// pricing for a model nothing prices, and name it in the phase details
@@ -71,6 +71,17 @@ function narrativePricing(model: string, overrides: PricingOverrides | undefined
return FALLBACK_PRICING;
}
+/** #4907: the run's named-key budget warnings (invalid stored budget, groups refused at the cap), each echoed once to stderr. */
+function budgetWarnings(configWarning: string | undefined, capped: number, budgetUsd: number): string[] {
+ const warnings = configWarning ? [configWarning] : [];
+ if (capped > 0) {
+ warnings.push(`${capped} LLM-eligible concept(s) got no model narrative because the $${budgetUsd.toFixed(2)} phase budget was reached; they retry next run. ` +
+ `Raise the cap: gbrain config set ${SYNTHESIZE_CONCEPTS_BUDGET_KEY} <usd>. Verify: gbrain config get ${SYNTHESIZE_CONCEPTS_BUDGET_KEY}`);
+ }
+ for (const warning of warnings) console.error(`[synthesize_concepts] ${warning}`);
+ return warnings;
+}
+
const TIER_T1_MIN = 10;
const TIER_T2_MIN = 5;
const TIER_T3_MIN = 2;
@@ -257,7 +268,9 @@ export async function runPhaseSynthesizeConcepts(
// 4. Per group: synthesize narrative (LLM for T1/T2, deterministic for T3+)
let conceptsWritten = 0;
let estimatedSpendUsd = 0;
- const budgetCap = DEFAULT_BUDGET_USD;
+ const budget = await readPhaseConfigNumber(engine, SYNTHESIZE_CONCEPTS_BUDGET_KEY);
+ const budgetCap = budget.value ?? SYNTHESIZE_CONCEPTS_DEFAULT_BUDGET_USD;
+ let budgetCapped = 0;
const failures: Array<{ concept: string; error: string }> = [];
// #4589 provenance-link problems. Kept OUT of `failures`: that list means
// "the LLM call failed → template fallback" downstream (summary wording,
@@ -365,6 +378,7 @@ export async function runPhaseSynthesizeConcepts(
if (estimatedSpendUsd >= budgetCap) {
narrative = deterministicNarrative(group);
synthesisMode = 'budget_fallback';
+ budgetCapped++;
} else {
try {
const result = await chat({
@@ -547,6 +561,7 @@ export async function runPhaseSynthesizeConcepts(
// survives only as the fallback for legacy unscoped callers. Receipt only
// fires when concepts were actually written; rollup always fires so doctor
// sees the phase ran.
+ const warnings = budgetWarnings(budget.warning, budgetCapped, budgetCap);
// Managed brains skip the receipt page (a legacy putPage), like extract_atoms;
// the rollup row below still records the run for doctor.
if (!opts.dryRun && !maintenance && conceptsWritten > 0) {
@@ -589,6 +604,7 @@ export async function runPhaseSynthesizeConcepts(
`synthesize_concepts: ${conceptsWritten} concepts ` +
`(T1=${tierCounts.T1} T2=${tierCounts.T2} T3=${tierCounts.T3})` +
(failures.length > 0 ? ` (${failures.length} LLM-failed → template fallback)` : '') +
+ (budgetCapped > 0 ? ` (${budgetCapped} over the $${budgetCap.toFixed(2)} budget → template fallback)` : '') +
(linkWarnings.length > 0 ? ` (${linkWarnings.length} provenance-link warning(s))` : '') +
(skippedHumanOwned.length > 0 ? ` (${skippedHumanOwned.length} human-owned page(s) left untouched)` : '') +
(skippedUnchanged.length > 0 ? ` (${skippedUnchanged.length} unchanged)` : '') +
@@ -604,6 +620,7 @@ export async function runPhaseSynthesizeConcepts(
atoms_seen: atoms.length,
failures,
link_warnings: linkWarnings,
+ warnings,
skipped_human_owned: skippedHumanOwned,
skipped_unchanged: skippedUnchanged,
rehashed,
diff --git a/test/cycle-synthesize-concepts-budget-config.test.ts b/test/cycle-synthesize-concepts-budget-config.test.ts
new file mode 100644
index 0000000000..e469141741
--- /dev/null
+++ b/test/cycle-synthesize-concepts-budget-config.test.ts
@@ -0,0 +1,199 @@
+// #4907 / #4906: synthesize_concepts reads `cycle.synthesize_concepts.budget_usd`.
+//
+// Protects: an operator's concept budget is the cap the phase enforces (the
+// pre-call refusal at `estimatedSpendUsd >= budgetCap`, the pricing-fallback
+// message and `details.budget_usd`), an invalid stored value is named instead
+// of silently ignored, a budget-capped run says so, and `config set` refuses a
+// value the phase would ignore.
+// Fails when: the phase keeps the hardcoded $1.50 cap, drops the named-key
+// warning, or `config set` writes a non-positive budget.
+// Why new: the phase had no config read; the stub engine implements
+// `readPageSnapshot` (the phase reads each concept page before any spend), so
+// the phase runs to the cap under test rather than throwing first.
+//
+// The real phase runs through its `_chat` / `_atoms` seams under `dryRun`:
+// nothing is written and no provider is called.
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';
+import { parsePhaseConfigValue, SYNTHESIZE_CONCEPTS_BUDGET_KEY } from '../src/core/cycle/phase-config-values.ts';
+import { renderCliError } from '../src/core/agent-output.ts';
+import { KNOWN_CONFIG_KEYS } from '../src/core/config.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const KEY = SYNTHESIZE_CONCEPTS_BUDGET_KEY;
+
+/** Three T1 groups (>= 10 atoms each), so every one is LLM-eligible. */
+function atoms(groups = 3, per = 10) {
+ const out: Array<{ slug: string; concept_refs: string[]; body: string; title: string }> = [];
+ for (let g = 0; g < groups; g++) {
+ for (let i = 0; i < per; i++) {
+ out.push({ slug: `atoms/2026-09-05/g${g}-a${i}`, concept_refs: [`concept-${g}`], title: `atom ${g}.${i}`, body: `body of atom ${g}.${i}` });
+ }
+ }
+ return out;
+}
+
+/** Each answer costs $0.90 at the Sonnet fallback rate (300k input tokens at $3/M). */
+function countingChat() {
+ const calls = { n: 0 };
+ const chat = (async () => {
+ calls.n++;
+ return { model: 'test:unpriced-model', text: 'a synthesized narrative.', usage: { input_tokens: 300_000, output_tokens: 0 } };
+ }) as never;
+ return { calls, chat };
+}
+
+function engineWith(configured: string | null | (() => never)) {
+ return {
+ getConfig: async (k: string) => {
+ if (k !== KEY) return null;
+ return typeof configured === 'function' ? configured() : configured;
+ },
+ readPageSnapshot: async () => null,
+ } as never;
+}
+
+async function captureStderr<T>(fn: () => Promise<T>): Promise<{ value: T; stderr: string }> {
+ const original = console.error;
+ const lines: string[] = [];
+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try {
+ return { value: await fn(), stderr: lines.join('\n') };
+ } finally {
+ console.error = original;
+ }
+}
+
+async function run(configured: string | null | (() => never)) {
+ const { calls, chat } = countingChat();
+ const { value: r, stderr } = await captureStderr(() =>
+ runPhaseSynthesizeConcepts(engineWith(configured), { dryRun: true, _atoms: atoms(), _chat: chat } as never));
+ const details = r.details as Record<string, unknown>;
+ return {
+ r, stderr, calls: calls.n, details,
+ modes: details.synthesis_mode_counts as Record<string, number>,
+ warnings: details.warnings as string[],
+ };
+}
+
+describe('synthesize_concepts budget comes from cycle.synthesize_concepts.budget_usd', () => {
+ test('unset keeps the $1.50 default: the call that crosses it runs, the next group is refused before any call', async () => {
+ const out = await run(null);
+ expect(out.calls).toBe(2);
+ expect(out.modes.llm).toBe(2);
+ expect(out.modes.budget_fallback).toBe(1);
+ expect(out.details.budget_usd).toBe(1.5);
+ });
+
+ test('a larger configured budget is the cap the phase enforces and meters against', async () => {
+ const out = await run('20');
+ expect(out.calls).toBe(3);
+ expect(out.modes.llm).toBe(3);
+ expect(out.modes.budget_fallback).toBe(0);
+ expect(out.details.budget_usd).toBe(20);
+ expect(out.stderr).toContain('against the $20.00 phase budget');
+ expect(out.warnings).toEqual([]);
+ });
+
+ test('a smaller configured budget stops spend earlier: no provider call past the cap', async () => {
+ const out = await run('0.5');
+ expect(out.calls).toBe(1);
+ expect(out.modes.llm).toBe(1);
+ expect(out.modes.budget_fallback).toBe(2);
+ expect(out.details.budget_usd).toBe(0.5);
+ expect(out.stderr).toContain('against the $0.50 phase budget');
+ });
+
+ for (const bad of ['not-a-number', '0', '-7.25', 'Infinity']) {
+ test(`a stored ${JSON.stringify(bad)} keeps the default and names the key without echoing the value`, async () => {
+ const out = await run(bad);
+ expect(out.calls).toBe(2);
+ expect(out.details.budget_usd).toBe(1.5);
+ const warning = out.warnings.find((w) => w.includes('invalid value'));
+ expect(warning).toContain(KEY);
+ expect(warning).toContain(`gbrain config set ${KEY}`);
+ expect(warning).toContain(`gbrain config get ${KEY}`);
+ if (bad !== '0') expect(warning).not.toContain(bad);
+ expect(out.stderr).toContain(`${KEY} is set to an invalid value`);
+ });
+ }
+
+ test('a budget-capped run is loud: the summary and warnings name the cap and the key', async () => {
+ const out = await run(null);
+ expect(out.r.summary).toContain('1 over the $1.50 budget → template fallback');
+ const capped = out.warnings.find((w) => w.includes('phase budget was reached'));
+ expect(capped).toContain('1 LLM-eligible concept(s)');
+ expect(capped).toContain(`gbrain config set ${KEY} <usd>`);
+ expect(out.stderr).toContain('phase budget was reached');
+ });
+
+ test('a getConfig that throws keeps the default and does not stop the phase', async () => {
+ const out = await run(() => { throw new Error('config plane down'); });
+ expect(out.r.status).not.toBe('error');
+ expect(out.details.budget_usd).toBe(1.5);
+ });
+});
+
+describe('config set validation for cycle.synthesize_concepts.budget_usd', () => {
+ test('the key is registered', () => {
+ expect(KNOWN_CONFIG_KEYS).toContain(KEY);
+ });
+
+ test('a finite positive value is accepted', () => {
+ expect(parsePhaseConfigValue(KEY, '20')).toBe(20);
+ expect(parsePhaseConfigValue(KEY, '0.25')).toBe(0.25);
+ });
+
+ for (const bad of ['0', '-7.25', 'NaN', 'Infinity', 'twenty', ' ']) {
+ test(`${JSON.stringify(bad)} is refused with the rendered contract and never echoed`, () => {
+ let err: unknown;
+ try { parsePhaseConfigValue(KEY, bad); } catch (e) { err = e; }
+ const rendered = renderCliError(err, { json: true, command: 'config', tty: false });
+ expect(rendered.exitCode).toBe(2);
+ const env = JSON.parse(rendered.stdout!);
+ expect(env).toMatchObject({
+ code: 'invalid_params',
+ fix: { argv: ['gbrain', 'config', 'set', KEY, '<VALUE>'], verify: { argv: ['gbrain', 'config', 'get', KEY] } },
+ });
+ expect(env.message).toContain(KEY);
+ expect(env.why).toContain('Nothing was written');
+ expect(env.fix.next).toBeTruthy();
+ if (bad.trim().length > 1) expect(rendered.stdout).not.toContain(bad);
+ });
+ }
+});
+
+describe('gbrain config set refuses a non-positive budget before writing', () => {
+ let home: string;
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-concepts-budget-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const dbPath = join(home, '.gbrain', 'brain.pglite');
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: dbPath }) + '\n');
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: dbPath });
+ await engine.initSchema();
+ await engine.disconnect();
+ }, 240_000);
+
+ afterAll(() => {
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('exit 2 with the rendered invalid_params refusal, and the key stays unset', async () => {
+ const set = await runCli(['config', 'set', KEY, '0'], { home, timeoutMs: 120_000 });
+ expect(set.exitCode).toBe(2);
+ expect(set.stderr).toContain(`Error [invalid_params]: Invalid ${KEY}`);
+ expect(set.stderr).toContain(`Fix: gbrain config set ${KEY}`);
+ expect(set.stderr).toContain('Why: ');
+ expect(set.stdout).not.toContain('Set ');
+ const get = await runCli(['config', 'get', KEY], { home, timeoutMs: 120_000 });
+ expect(get.exitCode).not.toBe(0);
+ expect(get.stdout.trim()).toBe('');
+ }, 300_000);
+});