Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P4.6b: daily spend cap on loop extraction through the job spend-authorization envelope

garrytan4480982a4e71
diff --git a/docs/architecture/key-files/open-loops-engine.md b/docs/architecture/key-files/open-loops-engine.md
index 593a3fe630..b87089146d 100644
--- a/docs/architecture/key-files/open-loops-engine.md
+++ b/docs/architecture/key-files/open-loops-engine.md
@@ -7,6 +7,7 @@ close semantics). The Gmail sweep that feeds both lanes is in
`google-and-loops.md` (`google-source.ts`, `loop-catchup.ts`, `loops-enqueue.ts`).
- `src/core/google/loops-exclusion.ts` — the user's own label exclusion for the open-loop engine (#5445). `excludedLabelTokens` reads the source's `g_loops_exclude_labels`, else the brain-wide `loops.extraction_exclude_labels` (no merge); `resolveExcludedLabels` matches tokens against the account's label catalog (id verbatim, name case-insensitively; with no catalog only id-shaped tokens resolve) into a `LoopsExclusionPolicy { tokens, ids, unresolved }`, where a non-empty `unresolved` means FAIL CLOSED for new paid extraction. `resolveSweepExclusion` (`loops-enqueue.ts`) runs it once per Gmail sweep (one `GmailClient.getLabels` call when anything is configured), logs each unresolved name, and `storeLoopsExclusion` keeps the resolution in `op_checkpoints` (op `loops-exclusion`, keyed like the loop outcomes) so `loadLoopsExclusionPolicy` can apply the policy without a Gmail client at the two late sites: `runLoopsExtract` (skips `excluded_label`, throws retryable `excluded_label_unresolved`) and `openDueGraceHold` (`'excluded'` drops the hold, `'deferred'` keeps it). A stored resolution is reused only for the same token list; changed tokens fall back to id-only until the next sweep. The policy gates `loopExtractionEligibility` right after SPAM/TRASH and before the owner override (reasons `excluded_label` / `excluded_label_unresolved` in the sweep's counters), `withLabelExclusion` strips the opens from a `detectThreadLoop` verdict (closes untouched), `recordGraceVerdict` records no hold for an excluded thread, `runLoopsCatchup` skips with `excluded_label_unresolved`, and `enqueueLoopsExtraction` reports the same `skipped_reason` ahead of `no_candidates`. The leaf is `excluded` from connector identity. Tests: `test/loops-exclusion.test.ts`, `test/google-source-reconcile.test.ts` ("label exclusion (#5445)"), `test/loops-extract-run.serial.test.ts` ("#5445 execution-time").
+- `src/core/google/loops-spend.ts` — the daily spend cap on loop extraction (wave 14 P4.6b): `loops.extraction_max_usd_per_day` (default $2.00, validated at `config set` by `validateLoopsSpendConfigValue`; a stored value is `user`-sourced). `loopsSpendGate` is what both enqueue sites call: it reads the cap and the day's group spend (`readGroupSpend` on `group:<day group>`) and returns the `SpendAuthorization` to stamp (`loopsExtractSpendAuthorization`: kind `authorized`, command `loops_extract`, via `preapproval`, one deterministic UUID per UTC day from `loopsSpendGroupId`) or the reason to queue nothing (`daily_spend_cap` at the cap, `spend_cap_zero` at 0). The sweep's `enqueueLoopsExtraction` and the catch-up's enqueue pass that record through `MinionQueue.add`'s trusted `spendAuthorization` option, so the worker runs each job under `runWithJobSpend` (spend-authorization.ts): every provider attempt reserves against the group and settles its usage; refusal before the call is `cost_cap_exceeded`, recorded on the row. An unreadable meter admits the enqueue (the worker still enforces). Tests: `test/loops-extract-spend-cap.test.ts`.
- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions.
- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code; a failed facts write is logged with slug, source and a bounded error, never the commitment text, and the loop row still lands), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, `Auto-Submitted`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.
- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. `openedAt` sets `opened_at` (default now()); an open row keeps the earlier of its stored and incoming value, a reopened row takes the incoming one. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `listOpenLoops` takes an optional `id` that composes with the status/type/counterparty filters and never replaces the source scope. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.
diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.md
index 526c43a505..b6eb47dc7e 100644
--- a/docs/guides/google-connect.md
+++ b/docs/guides/google-connect.md
@@ -377,7 +377,9 @@ upstream failures rather than triggering a full re-list.
bundle (a loud per-credential warning when a Testing-mode consent screen
would travel with it — those tokens die within 7 days on the target).
- LLM spend: commitment extraction sends recent email text (last 30 days,
- capped per sweep) to your configured chat provider. Kill switch:
+ capped per sweep) to your configured chat provider, under a daily cap of
+ $2.00 (`loops.extraction_max_usd_per_day`; see
+ [open loops](open-loops.md#which-threads-reach-the-extractor)). Kill switch:
`gbrain config set loops.extraction_enabled false`. The deterministic
unanswered-thread detector is free and always on.
- Atom extraction from email and calendar pages is on by default: page text
diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.md
index c20d992e9c..a1662ca2be 100644
--- a/docs/guides/open-loops.md
+++ b/docs/guides/open-loops.md
@@ -160,6 +160,23 @@ sweep picks up where it left off; nothing was spent in between. An id-shaped
token (`Label_12`, `CATEGORY_FORUMS`) still applies when the list cannot be
read.
+**What it may spend.** Extraction runs under a daily cap,
+`loops.extraction_max_usd_per_day` (default $2.00, per UTC day, across every
+source of the brain). Every `loops_extract` job a sweep or the managed
+catch-up queues carries the day's spend group, so the worker meters each
+model attempt against it: an attempt the cap cannot admit is refused before
+the provider is called (`cost_cap_exceeded` on the job, nothing spent), the
+job dies, and the thread is queued again on a later day when the sweep next
+touches it (the managed catch-up re-queues it once by itself). A sweep that
+finds the day already at its cap queues nothing and reports
+`loops_enqueue.skipped_reason: daily_spend_cap` with the amounts and the key
+to raise. `gbrain config set loops.extraction_max_usd_per_day 5` raises it;
+`0` queues no paid extraction at all (`spend_cap_zero`); a stored value makes
+the cap yours, so a model with no known price is refused instead of running
+unmetered. `gbrain jobs list --group <id>` shows a day's jobs and amounts
+(the group id is printed in the refusal). The deterministic detector is free
+and unaffected.
+
**Every eligible thread is queued** (newest first — ordering only, nothing is
dropped for being older). The MinionQueue is the backlog and the worker's
concurrency is the rate limit (a thread only re-candidates when it changes,
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 5aabb5158f..65e782cd15 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 1926 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
src/core/chunkers/code.ts 1598 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)
-src/core/config.ts 1935 ratchet +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); +3 W14 P4.6a #5445: loops.extraction_exclude_labels key row (resolver in google/loops-exclusion.ts)
+src/core/config.ts 1939 ratchet +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); +3 W14 P4.6a #5445: loops.extraction_exclude_labels key row (resolver in google/loops-exclusion.ts); +4 W14 P4.6b: loops.extraction_max_usd_per_day key row (validated in google/loops-spend.ts)
src/core/bootstrap/harness.ts 2610 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)
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 683 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; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept)
diff --git a/src/commands/config.ts b/src/commands/config.ts
index ca8ce2fbb5..64e48f2017 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -396,6 +396,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:
const err = validateFenceConfigValue(key, value);
if (err) { console.error(`[config] ${err}`); process.exit(1); }
}
+ if (key.startsWith('loops.')) (await import('./config/loops-values.ts')).refuseInvalidLoopsConfigValue(key, value);
if (key === 'persistence.max_claim_ms') {
const { validateMaxClaimConfigValue } = await import('../core/persistence/claim-phase.ts');
const err = validateMaxClaimConfigValue(key, value);
diff --git a/src/commands/config/loops-values.ts b/src/commands/config/loops-values.ts
new file mode 100644
index 0000000000..4782726de5
--- /dev/null
+++ b/src/commands/config/loops-values.ts
@@ -0,0 +1,15 @@
+/**
+ * `config set` value checks for `loops.*` keys: nothing is written when a
+ * value is one the reader would not accept.
+ */
+import { exitCliError, usageError } from '../../cli/cli-error.ts';
+import { LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, validateLoopsSpendConfigValue } from '../../core/google/loops-spend.ts';
+
+export function refuseInvalidLoopsConfigValue(key: string, value: string): void {
+ const err = validateLoopsSpendConfigValue(key, value);
+ if (!err) return;
+ exitCliError(usageError(err, `Re-run with a non-negative USD amount, e.g. gbrain config set ${LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY} 2.00 (0 queues no paid loop extraction).`, {
+ why: 'The daily loop-extraction cap is read as USD; any other value would leave the cap at its default.',
+ fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false },
+ }), 'config');
+}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 6e24d89d86..52d5e780cd 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -373,6 +373,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.147.0', text: 'In a brain folder with the Git durability hook, a write that arrives while the effect worker commits a backlog of Git effects now publishes after the group in flight, inside its 5 s wait, instead of returning pending after the whole backlog; Git effects still commit in order. A write waiting on a busy worktree is reported as `writer_busy` without a stale preparing phase.' },
// `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.151.0', text: '`delta` and `context_pack` called without `include_private`, and the per-turn context block that harness hooks inject, now apply to their facts the same page-visibility rule they already apply to their pages. With `include_private` from the local CLI, `delta` and `context_pack` output is unchanged.' },
+ { since: '0.60.157.0', text: 'Open-loop extraction from Gmail threads (`loops_extract` jobs) now runs under a $2.00 per UTC day cap, brain-wide: every job a sweep or the managed catch-up queues shares the day\'s spend group, an attempt the cap cannot admit is refused before the provider call and the thread is queued again on a later day, and a sweep that finds the day at its cap queues nothing (`daily_spend_cap`). `gbrain config set loops.extraction_max_usd_per_day <usd>` changes the cap (0 queues no paid extraction).' },
{ since: '0.60.157.0', text: 'A page whose database frontmatter carries the v0.13.1 grandfather `validate: false` while its canonical file does not is no longer refused `source_changed` on write; the next coordinated write publishes the stamp to the file. `remember` and other caller writes that were refused that way are counted by doctor (`lost_caller_writes`) and replayed by `gbrain repair failed-writes --source <id>` on the brain host, after the user agrees to the previewed set.' },
];
diff --git a/src/core/config.ts b/src/core/config.ts
index 090595a80c..3eb34517b9 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1456,6 +1456,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #5445: brain-wide Gmail labels (names or ids, comma/JSON list) whose threads
// never enter paid loop extraction; a source's g_loops_exclude_labels wins.
'loops.extraction_exclude_labels',
+ // W14 P4.6b: USD per UTC day that loops_extract jobs may spend, brain-wide
+ // (default 2.00; 0 = no paid loop extraction). Validated in google/loops-spend.ts.
+ 'loops.extraction_max_usd_per_day',
// #2113: output-token cap for the per-turn facts extractor (default 4000).
'facts.extraction_max_tokens',
// Automatic facts drain caps (src/core/facts/drain.ts FACTS_DRAIN_KEYS).
diff --git a/src/core/google/loop-catchup.ts b/src/core/google/loop-catchup.ts
index c8d1005871..5629081738 100644
--- a/src/core/google/loop-catchup.ts
+++ b/src/core/google/loop-catchup.ts
@@ -36,6 +36,7 @@ import { connectorStateKey } from '../persistence/connector-state.ts';
import { LOOPS_EXTRACT_ENQUEUE_CEILING, LOOPS_EXTRACT_JOB, LOOPS_EXTRACT_WINDOW_DAYS, isLoopsExtractionEnabled, loopExtractionEligibility } from './loops-extract.ts';
import { openDueGraceHold, type ThreadLoopVerdict } from './loop-detect.ts';
import { NO_EXCLUSION, type LoopsExclusionPolicy } from './loops-exclusion.ts';
+import { loopsSpendGate } from './loops-spend.ts';
import type { GmailThreadData, GoogleSourceState, LoopGraceHold } from './types.ts';
export const GRACE_HOLDS_CAP = 2_000;
@@ -241,6 +242,8 @@ export async function runLoopsCatchup(ctx: {
}
const { isAvailable } = await import('../ai/gateway.ts');
if (!isAvailable('chat')) return skip('chat_unavailable', 'no configured chat model / API key');
+ const spend = await loopsSpendGate(ctx.engine, now);
+ if (!spend.ok) return skip(spend.reason, spend.message);
const cu = ctx.state.loops_catchup ??= { version: 1, floor_ms: now - LOOPS_EXTRACT_WINDOW_DAYS * DAY_MS, retried: [], done: false };
const pages = await ctx.engine.executeRaw<{ slug: string; thread_id: string; date: string }>(
@@ -262,7 +265,7 @@ export async function runLoopsCatchup(ctx: {
const settle = (slug: string, rev: number, outcome: string) => recordLoopsExtractOutcome(ctx.engine, ctx.sourceId, slug, { rev, outcome, catchup: true });
const enqueue = async (c: { slug: string; thread_id: string; rev: number }, key: string) => {
await queue.add(LOOPS_EXTRACT_JOB, { slug: c.slug, sourceId: ctx.sourceId, threadId: c.thread_id, newestMs: c.rev, catchup: true },
- { priority: 6, idempotency_key: key });
+ { priority: 6, idempotency_key: key }, { spendAuthorization: spend.record });
budget--;
report.enqueued++;
};
diff --git a/src/core/google/loops-enqueue.ts b/src/core/google/loops-enqueue.ts
index b924e4e364..70395081f9 100644
--- a/src/core/google/loops-enqueue.ts
+++ b/src/core/google/loops-enqueue.ts
@@ -9,6 +9,7 @@ import { pendingLoopsExtractDepth, type LoopsEnqueueReport } from './loop-catchu
import { myAddressSet, type GoogleSyncDeps } from './sweep-shared.ts';
import type { GmailClient } from './google-clients.ts';
import { excludedLabelTokens, NO_EXCLUSION, resolveExcludedLabels, storeLoopsExclusion, type LoopsExclusionPolicy } from './loops-exclusion.ts';
+import { loopsSpendGate } from './loops-spend.ts';
/**
* #5445: resolves the source's loop exclusion labels once per sweep (one
@@ -76,6 +77,12 @@ export async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<Loop
);
return { ...report, skipped_reason: 'chat_unavailable' };
}
+ // P4.6b: the day's spend authorization; a day already at its cap queues nothing.
+ const spend = await loopsSpendGate(deps.engine);
+ if (!spend.ok) {
+ deps.log(`[google] loops_extract: ${spend.message} — skipped enqueue of ${deps.extractCandidates.length} eligible thread(s) (${spend.reason})`);
+ return { ...report, skipped_reason: spend.reason };
+ }
const { MinionQueue } = await import('../minions/queue.ts');
const queue = new MinionQueue(deps.engine);
// EVERY eligible candidate is enqueued (up to a generous safety ceiling).
@@ -132,6 +139,7 @@ export async function enqueueLoopsExtraction(deps: GoogleSyncDeps): Promise<Loop
// its cap-hit coalesce loses brand-new keys, see above).
idempotency_key: `loops:${deps.sourceId}:${c.slug}:${c.newestMs}`,
},
+ { spendAuthorization: spend.record },
);
}
deps.log(`[google] loops_extract: enqueued ${picked.length} eligible thread(s)`);
diff --git a/src/core/google/loops-spend.ts b/src/core/google/loops-spend.ts
new file mode 100644
index 0000000000..41c0e9677e
--- /dev/null
+++ b/src/core/google/loops-spend.ts
@@ -0,0 +1,118 @@
+/**
+ * The daily spend cap on open-loop extraction (#5445 follow-up, wave 14 P4.6b).
+ *
+ * `loops.extraction_max_usd_per_day` (default $2.00; 0 means no paid loop
+ * extraction) bounds what `loops_extract` jobs may spend per UTC day, brain
+ * wide. Both enqueue sites (the sweep's `enqueueLoopsExtraction` and the
+ * managed catch-up) stamp every job with the day's spend authorization, a
+ * group record keyed on the day (`loops_extract:<YYYY-MM-DD>`), so the worker
+ * runs each job under `runWithJobSpend`: every provider attempt reserves its
+ * maximum against `group:<day group>` in the durable meter and settles its
+ * measured usage; an attempt the cap cannot admit is refused BEFORE the
+ * provider call (`cost_cap_exceeded`), the job dies without spending, and the
+ * next sweep that touches the thread queues it under a later day. A sweep
+ * that finds the day's group already at its cap queues nothing and reports
+ * `daily_spend_cap` as its skip reason.
+ *
+ * A stored value makes the cap `user`-sourced: a model with no known price is
+ * then refused rather than run unmetered (the same rule every user cap has).
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../engine.ts';
+import { readGroupSpend } from '../minions/budget-meter.ts';
+import type { SpendAuthorization } from '../minions/spend-record.ts';
+
+export const LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY = 'loops.extraction_max_usd_per_day';
+export const LOOPS_EXTRACT_DEFAULT_MAX_USD_PER_DAY = 2;
+/** The `command` every day group records; the resume guidance names it. */
+export const LOOPS_EXTRACT_SPEND_COMMAND = 'loops_extract';
+
+/** Null when the value is valid for `loops.extraction_max_usd_per_day`; otherwise the refusal text (nothing is written). */
+export function validateLoopsSpendConfigValue(key: string, value: string): string | null {
+ if (key !== LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY) return null;
+ return parseUsd(value) === null
+ ? `${key} must be a non-negative USD amount such as 2.00 (0 means no paid loop extraction; got "${value}"). Nothing was written.`
+ : null;
+}
+
+function parseUsd(value: string): number | null {
+ const text = value.trim();
+ if (!/^\d+(\.\d+)?$/.test(text)) return null;
+ const usd = Number(text);
+ return Number.isFinite(usd) ? usd : null;
+}
+
+export interface LoopsExtractDailyCap {
+ capUsd: number;
+ /** `user` when the key is stored, `default` otherwise. */
+ source: 'user' | 'default';
+}
+
+/** The cap in force; an unset or unreadable value keeps the default. */
+export async function readLoopsExtractDailyCap(engine: Pick<BrainEngine, 'getConfig'>): Promise<LoopsExtractDailyCap> {
+ try {
+ const value = await engine.getConfig(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY);
+ const usd = typeof value === 'string' ? parseUsd(value) : null;
+ if (usd !== null) return { capUsd: usd, source: 'user' };
+ } catch {
+ // unreadable config keeps the default
+ }
+ return { capUsd: LOOPS_EXTRACT_DEFAULT_MAX_USD_PER_DAY, source: 'default' };
+}
+
+/** The UTC day a job is charged to, `YYYY-MM-DD`. */
+export const loopsSpendDay = (nowMs: number): string => new Date(nowMs).toISOString().slice(0, 10);
+
+/**
+ * The day's group id: a UUID derived from the day, so every enqueue site of
+ * every process lands the day's jobs in one group without coordination.
+ */
+export function loopsSpendGroupId(day: string): string {
+ const h = createHash('sha256').update(`${LOOPS_EXTRACT_SPEND_COMMAND}:${day}`).digest('hex');
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${((parseInt(h[16]!, 16) & 0x3) | 0x8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+export const loopsSpendBudgetKey = (day: string): string => `group:${loopsSpendGroupId(day)}`;
+
+/** The record both enqueue sites stamp on the day's jobs; null when the cap is 0 (nothing may be queued). */
+export function loopsExtractSpendAuthorization(cap: LoopsExtractDailyCap, nowMs: number): SpendAuthorization | null {
+ if (cap.capUsd <= 0) return null;
+ const day = loopsSpendDay(nowMs);
+ return {
+ version: 1, kind: 'authorized', group_id: loopsSpendGroupId(day),
+ consented_effects: ['paid'], cap_usd: cap.capUsd, cap_source: cap.source, via: 'preapproval',
+ command: LOOPS_EXTRACT_SPEND_COMMAND, authorized_at: new Date(nowMs).toISOString(),
+ };
+}
+
+export type LoopsSpendGate =
+ | { ok: true; record: SpendAuthorization; day: string; spentUsd: number; capUsd: number }
+ | { ok: false; reason: 'spend_cap_zero' | 'daily_spend_cap'; day: string; spentUsd: number; capUsd: number; message: string };
+
+/**
+ * What an enqueue site may do today: the record to stamp, or the reason to
+ * queue nothing. Settled spend plus overdue holds at or over the cap closes
+ * the day; live holds of jobs still running do not (the worker's own
+ * reservation refuses them if they would overrun).
+ */
+export async function loopsSpendGate(engine: BrainEngine, nowMs = Date.now()): Promise<LoopsSpendGate> {
+ const cap = await readLoopsExtractDailyCap(engine);
+ const day = loopsSpendDay(nowMs);
+ const raise = `raise it with \`gbrain config set ${LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY} <usd>\``;
+ if (cap.capUsd <= 0) {
+ return { ok: false, reason: 'spend_cap_zero', day, spentUsd: 0, capUsd: 0,
+ message: `${LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY} is 0, so no paid loop extraction is queued; ${raise}` };
+ }
+ let spentUsd = 0;
+ try {
+ const spend = await readGroupSpend(engine, loopsSpendBudgetKey(day));
+ spentUsd = (spend.committedCents + spend.overdueCents) / 100;
+ } catch {
+ // an unreadable meter admits the enqueue; the worker's reservation still enforces the cap
+ }
+ if (spentUsd >= cap.capUsd) {
+ return { ok: false, reason: 'daily_spend_cap', day, spentUsd, capUsd: cap.capUsd,
+ message: `loop extraction spent $${spentUsd.toFixed(2)} of its $${cap.capUsd.toFixed(2)} ${cap.source} cap for ${day} (UTC); nothing more is queued today, the threads are queued on their next touch tomorrow; ${raise}` };
+ }
+ return { ok: true, record: loopsExtractSpendAuthorization(cap, nowMs)!, day, spentUsd, capUsd: cap.capUsd };
+}
diff --git a/test/loops-extract-spend-cap.test.ts b/test/loops-extract-spend-cap.test.ts
new file mode 100644
index 0000000000..3f250cd184
--- /dev/null
+++ b/test/loops-extract-spend-cap.test.ts
@@ -0,0 +1,192 @@
+/**
+ * Wave 14 P4.6b — the daily spend cap on open-loop extraction
+ * (src/core/google/loops-spend.ts, both enqueue sites, the worker guard).
+ *
+ * - `loops.extraction_max_usd_per_day` validates at config set, defaults to
+ * $2.00 and is `user`-sourced when stored;
+ * - every loops_extract job the sweep or the managed catch-up queues carries
+ * the day's group authorization (one deterministic group per UTC day);
+ * - a day already at its cap queues nothing (`daily_spend_cap`), a cap of 0
+ * queues nothing (`spend_cap_zero`);
+ * - under the worker guard, an attempt the day's group cannot admit is refused
+ * before the provider call (cost_cap_exceeded) and an attempt that fits is
+ * metered against the group.
+ *
+ * PGLite in memory; the chat transport is a stub that throws, so no model is
+ * ever called and nothing is spent. Synthetic data only.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __setChatTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { invokeAI } from '../src/core/ai/invocation-guard.ts';
+import { reserveGroup, settle } from '../src/core/minions/budget-meter.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { parseSpendAuthorization, runWithJobSpend, SpendGroupRefusedError } from '../src/core/minions/spend-authorization.ts';
+import type { MinionJob, MinionJobContext } from '../src/core/minions/types.ts';
+import { enqueueLoopsExtraction } from '../src/core/google/loops-enqueue.ts';
+import { runLoopsCatchup } from '../src/core/google/loop-catchup.ts';
+import { NO_EXCLUSION } from '../src/core/google/loops-exclusion.ts';
+import {
+ LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY,
+ loopsExtractSpendAuthorization,
+ loopsSpendBudgetKey,
+ loopsSpendDay,
+ loopsSpendGate,
+ loopsSpendGroupId,
+ readLoopsExtractDailyCap,
+ validateLoopsSpendConfigValue,
+} from '../src/core/google/loops-spend.ts';
+import { parseGoogleSourceConfig } from '../src/core/google/source-config.ts';
+import type { GoogleSyncDeps } from '../src/core/google/sweep-shared.ts';
+import type { GoogleSourceState } from '../src/core/google/types.ts';
+
+const SRC = 'gsrc';
+const NOW = Date.parse('2026-08-25T12:00:00Z');
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ __setChatTransportForTests(async () => { throw new Error('the chat transport must never be called by these tests'); });
+});
+afterAll(async () => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });
+ await engine.disconnect();
+});
+beforeEach(async () => {
+ for (const sql of ['DELETE FROM mcp_spend_reservations', 'DELETE FROM mcp_spend_log', 'DELETE FROM minion_jobs', 'DELETE FROM op_checkpoints',
+ "DELETE FROM pages WHERE source_id = 'gsrc'", "DELETE FROM config WHERE key LIKE 'loops.%'"]) await engine.executeRaw(sql);
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{"kind":"google"}'::jsonb) ON CONFLICT (id) DO NOTHING`, [SRC]);
+});
+
+/** Charges `cents` of settled spend to the day's group (a priced claude-sonnet-5 attempt). */
+async function chargeDay(cents: number, nowMs = Date.now()): Promise<void> {
+ const hold = await reserveGroup(engine, { budgetKey: loopsSpendBudgetKey(loopsSpendDay(nowMs)), capCents: null, estimatedCents: cents,
+ model: 'anthropic:claude-sonnet-5', provider: 'anthropic' });
+ await settle(engine, hold.reservationId, cents, 'test');
+}
+
+const loopsJobs = () => engine.executeRaw<{ id: number; spend_authorization: unknown; idempotency_key: string }>(
+ `SELECT id, spend_authorization, idempotency_key FROM minion_jobs WHERE name = 'loops_extract' ORDER BY id`);
+
+describe('P4.6b config and record', () => {
+ test('the key validates as a non-negative USD amount', () => {
+ for (const ok of ['2', '0', '0.50', '12.5']) expect(validateLoopsSpendConfigValue(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, ok)).toBeNull();
+ for (const bad of ['-1', 'abc', '$2', '']) expect(validateLoopsSpendConfigValue(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, bad)).toContain('Nothing was written');
+ expect(validateLoopsSpendConfigValue('loops.extraction_enabled', 'false')).toBeNull();
+ });
+
+ test('the cap defaults to $2.00 and is user-sourced once stored', async () => {
+ expect(await readLoopsExtractDailyCap(engine)).toEqual({ capUsd: 2, source: 'default' });
+ await engine.setConfig(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, '0.75');
+ expect(await readLoopsExtractDailyCap(engine)).toEqual({ capUsd: 0.75, source: 'user' });
+ await engine.setConfig(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, 'garbage');
+ expect(await readLoopsExtractDailyCap(engine)).toEqual({ capUsd: 2, source: 'default' });
+ });
+
+ test('one group per UTC day, the same from every process, and the record parses strictly', () => {
+ expect(loopsSpendGroupId('2026-08-25')).toBe(loopsSpendGroupId('2026-08-25'));
+ expect(loopsSpendGroupId('2026-08-25')).not.toBe(loopsSpendGroupId('2026-08-26'));
+ expect(loopsSpendDay(Date.parse('2026-08-25T23:59:59Z'))).toBe('2026-08-25');
+ expect(loopsSpendDay(Date.parse('2026-08-26T00:00:00Z'))).toBe('2026-08-26');
+ const record = loopsExtractSpendAuthorization({ capUsd: 2, source: 'default' }, NOW)!;
+ expect(parseSpendAuthorization(record)).toEqual(record);
+ expect(record).toMatchObject({ kind: 'authorized', cap_usd: 2, cap_source: 'default', command: 'loops_extract', group_id: loopsSpendGroupId('2026-08-25') });
+ expect(loopsExtractSpendAuthorization({ capUsd: 0, source: 'user' }, NOW)).toBeNull();
+ });
+
+ test('the gate admits under the cap, closes the day at the cap and refuses a cap of 0', async () => {
+ const open = await loopsSpendGate(engine, NOW);
+ expect(open).toMatchObject({ ok: true, day: '2026-08-25', spentUsd: 0, capUsd: 2 });
+ await chargeDay(150, NOW);
+ expect(await loopsSpendGate(engine, NOW)).toMatchObject({ ok: true, spentUsd: 1.5 });
+ await chargeDay(50, NOW);
+ const closed = await loopsSpendGate(engine, NOW);
+ expect(closed).toMatchObject({ ok: false, reason: 'daily_spend_cap', spentUsd: 2, capUsd: 2 });
+ expect((closed as { message: string }).message).toContain(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY);
+ expect(await loopsSpendGate(engine, NOW + 86_400_000)).toMatchObject({ ok: true, day: '2026-08-26', spentUsd: 0 });
+ await engine.setConfig(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, '0');
+ expect(await loopsSpendGate(engine, NOW)).toMatchObject({ ok: false, reason: 'spend_cap_zero' });
+ });
+});
+
+describe('P4.6b enqueue sites', () => {
+ const deps = (): GoogleSyncDeps => ({
+ engine, sourceId: SRC, opts: { sourceId: SRC, noEmbed: true, noExtract: true },
+ cfg: parseGoogleSourceConfig({ kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_history_days: 90, g_dir: '/tmp/gsrc' }, '/tmp/gsrc'),
+ entry: { id: 'google:[email protected]', provider: 'google', kind: 'oauth2', client_ref: 'byo', secret: {}, meta: { account: '[email protected]' } } as unknown as GoogleSyncDeps['entry'],
+ log: () => {}, tick: () => {}, exclusion: NO_EXCLUSION, managed: null, processedThreads: new Set(),
+ extractCandidates: [
+ { slug: 'emails/2026/08/2026-08-25-a-1111aaaa', threadId: '1111aaaa', newestMs: Date.now() - 3_600_000 },
+ { slug: 'emails/2026/08/2026-08-25-b-2222bbbb', threadId: '2222bbbb', newestMs: Date.now() - 7_200_000 },
+ ],
+ } as unknown as GoogleSyncDeps);
+
+ test('the sweep stamps the day group on every job it queues', async () => {
+ const r = await enqueueLoopsExtraction(deps());
+ expect(r).toMatchObject({ enqueued: 2, skipped_reason: null });
+ const jobs = await loopsJobs();
+ expect(jobs).toHaveLength(2);
+ const today = loopsSpendGroupId(loopsSpendDay(Date.now()));
+ for (const j of jobs) expect(parseSpendAuthorization(j.spend_authorization)).toMatchObject({ group_id: today, cap_usd: 2, command: 'loops_extract' });
+ });
+
+ test('a day at its cap queues nothing and the report says why', async () => {
+ await chargeDay(200);
+ const logs: string[] = [];
+ const d = deps(); d.log = (l) => logs.push(l);
+ expect(await enqueueLoopsExtraction(d)).toMatchObject({ enqueued: 0, skipped_reason: 'daily_spend_cap' });
+ expect(await loopsJobs()).toHaveLength(0);
+ expect(logs.join('\n')).toContain('$2.00 of its $2.00 default cap');
+ await engine.setConfig(LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, '0');
+ expect(await enqueueLoopsExtraction(deps())).toMatchObject({ enqueued: 0, skipped_reason: 'spend_cap_zero' });
+ });
+
+ test('the managed catch-up stamps the same day group and skips at the cap', async () => {
+ await engine.setConfig('loops.extraction_enabled', 'true');
+ await engine.putPage('emails/2026/08/2026-08-25-c-3333cccc', { type: 'email', title: 'Plan', compiled_truth: 'Peer: Can you review the plan?',
+ frontmatter: { thread_id: '3333cccc', date: new Date(Date.now() - 86_400_000).toISOString() } }, { sourceId: SRC });
+ const state = {} as GoogleSourceState;
+ const ctx = () => ({ engine, sourceId: SRC, state, log: () => {}, myAddresses: new Set(['[email protected]']), inFlight: new Set<string>(),
+ fetchThread: async (threadId: string) => ({ threadId, account: '[email protected]', messages: [{
+ id: 'm1', threadId, from: 'Peer <[email protected]>', fromAddress: '[email protected]', to: ['[email protected]'], cc: [], subject: 'Plan',
+ dateIso: new Date(Date.now() - 86_400_000).toISOString(), internalDateMs: Date.now() - 86_400_000, labelIds: ['INBOX'], listUnsubscribe: false,
+ calendarMethod: null, bodyText: 'Can you review the plan?' }] }) });
+ const r = await runLoopsCatchup(ctx());
+ expect(r).toMatchObject({ enqueued: 1, skipped_reason: null });
+ const [job] = await loopsJobs();
+ expect(job.idempotency_key.startsWith('loops-catchup:')).toBe(true);
+ expect(parseSpendAuthorization(job.spend_authorization)).toMatchObject({ group_id: loopsSpendGroupId(loopsSpendDay(Date.now())), command: 'loops_extract' });
+ await chargeDay(200);
+ expect(await runLoopsCatchup({ ...ctx(), state: {} as GoogleSourceState })).toMatchObject({ enqueued: 0, skipped_reason: 'daily_spend_cap' });
+ });
+});
+
+describe('P4.6b worker guard', () => {
+ const attempt = (maxCents: number, actualCents: number) => invokeAI(
+ { operation: 'loops_extract', kind: 'chat', model: 'anthropic:claude-sonnet-5', maxInputTokens: maxCents * 2500, maxOutputTokens: 0 },
+ async () => 'ok', () => ({ inputTokens: actualCents * 5000, outputTokens: 0 }));
+ const ctxFor = (job: MinionJob) => ({ id: job.id, name: job.name, data: job.data, attempts_made: 0 }) as unknown as MinionJobContext;
+
+ test('an attempt the day group cannot admit is refused before the provider call; one that fits is metered', async () => {
+ const queue = new MinionQueue(engine);
+ const record = loopsExtractSpendAuthorization({ capUsd: 2, source: 'default' }, Date.now())!;
+ await queue.add('loops_extract', { slug: 'emails/x', sourceId: SRC }, { idempotency_key: 'loops:gsrc:x:1' }, { spendAuthorization: record });
+ const job = (await queue.claim('tok', 60_000, 'default', ['loops_extract']))!;
+ expect(job.spend_authorization?.group_id).toBe(record.group_id);
+ let providerCalls = 0;
+ const metered = await runWithJobSpend(engine, job, ctxFor(job), async () => { providerCalls++; return attempt(40, 30); });
+ expect(metered).toBe('ok');
+ expect(await loopsSpendGate(engine)).toMatchObject({ ok: true, spentUsd: 0.3 });
+ await chargeDay(170);
+ const refused = await runWithJobSpend(engine, job, ctxFor(job), async () => { providerCalls++; return attempt(40, 30); }).then(() => null, (e: unknown) => e);
+ expect(refused).toBeInstanceOf(SpendGroupRefusedError);
+ expect((refused as SpendGroupRefusedError).envelope.code).toBe('cost_cap_exceeded');
+ expect((await loopsSpendGate(engine))).toMatchObject({ ok: false, reason: 'daily_spend_cap', spentUsd: 2 });
+ expect(providerCalls).toBe(2);
+ });
+});