Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
loops: automated mail opens no reply-owed loop; mute closes, unmute re-checks (#5012 item 8)
garrytanfa75371e4e5b
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 03787a67cf..c31030f8e5 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.0src/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 refreshsrc/commands/hook.ts 1932 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +1 #5371: the stop-hook dirty probe ignores physical-root ownership metadata (root-metadata.ts, engine-free); 2 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts); +3 fix wave 11 W2.1 #6091: PreCompact/SessionEnd capture-time consent record calls (logic in core/context/capture-consent.ts); +5 fix wave 11 W2.9 #6083: the three detached-push call sites skip a managed canonical worktree (push_managed_coordinator) + import; +2 fix wave 11 integration: W1 router help guard import beside the W2 managed-root import; +2 fix wave 13 P4.9 #6399: a header-only Codex rollout ends empty_session, not parser_drift; +3 W14 P4.16 (#5799): banner and SessionStart note read livePushStatuses (predicate in core/workspace-push.ts); +1 W15 P5.7 (#4992): gitChildEnv import for the hook git probes (launches moved onto core/spawn.ts)src/core/chunkers/code.ts 1602 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts); +10 Lua grammar swap: GRAMMAR_REVISIONS + chunkerStamp() (per-language re-chunk gate); +4: CodeChunkOptions.timeoutMs (per-call parse cap; markdown fences parse under a short cap) and the "Parsing failed" → ChunkerTimeoutError mapping in parseWithTimeout-src/core/config.ts 1979 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts)+src/core/config.ts 1981 ratchet +2 wave 18b lane 5 (#5012): loops.updates_require_reciprocity KNOWN_CONFIG_KEYS row (validator in google/loops-reciprocity.ts); +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts)src/core/persistence/sync-run.ts 1690 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts)src/core/bootstrap/harness.ts 2615 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent blocksrc/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@@ -45,5 +45,5 @@ src/core/search/mode.ts 1669 ratchet +53 W3 confidence-gated reranking: rerankersrc/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)src/commands/doctor/checks/extraction-sync.ts 1523 ratchet +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.tssrc/core/search/evidence-delivery.ts 1673 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136)-src/commands/config.ts 1508 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts)+src/commands/config.ts 1509 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts)src/commands/mcp-expose.ts 1512 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts)diff --git a/src/commands/config/loops-values.ts b/src/commands/config/loops-values.tsindex 4782726de5..927ec037dc 100644--- a/src/commands/config/loops-values.ts+++ b/src/commands/config/loops-values.ts@@ -4,8 +4,16 @@*/import { exitCliError, usageError } from '../../cli/cli-error.ts';import { LOOPS_EXTRACT_MAX_USD_PER_DAY_KEY, validateLoopsSpendConfigValue } from '../../core/google/loops-spend.ts';+import { LOOPS_UPDATES_RECIPROCITY_KEY, validateLoopsReciprocityConfigValue } from '../../core/google/loops-reciprocity.ts';export function refuseInvalidLoopsConfigValue(key: string, value: string): void {+ const reciprocity = validateLoopsReciprocityConfigValue(key, value);+ if (reciprocity) {+ exitCliError(usageError(reciprocity, `Re-run with true or false, e.g. gbrain config set ${LOOPS_UPDATES_RECIPROCITY_KEY} true (false, the default, turns the rule off).`, {+ why: 'The detector reads this key as a boolean; any other value would leave the rule off.',+ fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false },+ }), 'config');+ }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).`, {diff --git a/src/commands/loops.ts b/src/commands/loops.tsindex 5a6a317149..35bac0217e 100644--- a/src/commands/loops.ts+++ b/src/commands/loops.ts@@ -11,8 +11,9 @@* gbrain loops list [--status s] [--type t] [--json]* gbrain loops show <id> [--json]* gbrain loops done <id> / drop <id>- * gbrain loops mute <sender|thread> <value> [--source <id>]- * gbrain loops unmute <sender|thread> <value> [--source <id>]+ * gbrain loops drop sender <email> [--source <id>] [--note <text>] [--dry-run]+ * gbrain loops mute <sender|thread> <value> [--source <id>] [--dry-run]+ * gbrain loops unmute <sender|thread> <value> [--source <id>] [--dry-run]** All paths dispatch through the trusted-local op layer (handleToolCall,* remote:false) so CLI and MCP share one behavior. Reads default to the@@ -39,8 +40,12 @@ export function printUsage(): void {' show <id> [--json]',' done <id> [--note <text>] mark handled',' drop <id> [--note <text>] not going to do it',- ' mute sender <email> | thread <thread-id> [--source <id>]',- ' unmute sender <email> | thread <thread-id> [--source <id>] undo a mute',+ ' drop sender <email> [--source <id>] [--note <text>] [--dry-run]',+ ' close every open reply-owed loop from one sender (preview with --dry-run; cannot be undone)',+ ' mute sender <email> | thread <thread-id> [--source <id>] [--dry-run]',+ ' stop new loops and close its open reply-owed loops',+ ' unmute sender <email> | thread <thread-id> [--source <id>] [--dry-run]',+ ' undo a mute; loops it closed are re-checked on the next sync','','The ranked digest lives at: gbrain waiting',].join('\n') + '\n',@@ -87,6 +92,8 @@ interface WaitingResult {}>;/** #5871: loops that name no counterparty, listed apart from the people; null when none. */no_counterparty?: { loop_count: number } | null;+ /** #5012: open reply-owed loops the automated-mail rule would not have opened; null when none. */+ withheld_noise?: { loop_count: number; sender_count: number; senders: Array<{ email: string; open_loops: number; preview_command: string }> } | null;count: number;stale: boolean;sources: Array<{ id: string; last_sync_at: string | null; stale: boolean }>;@@ -154,6 +161,13 @@ export async function runWaiting(engine: BrainEngine, args: string[]): Promise<vreturn;}process.stdout.write((result.text ?? 'No open loops.') + '\n');+ const noise = result.withheld_noise;+ if (noise) {+ process.stdout.write(`\n${noise.loop_count} open reply-owed loop(s) come from ${noise.sender_count} sender(s) whose mail is automated; `+ + `the detector would not open them now. Preview closing them, sender by sender:\n`+ + noise.senders.map((x) => ` ${x.preview_command} (${x.open_loops})`).join('\n') + '\n'+ + (noise.sender_count > noise.senders.length ? ` … and ${noise.sender_count - noise.senders.length} more sender(s)\n` : ''));+ }if (result.groups.length > 0 || result.no_counterparty) {process.stdout.write(`\n(close: gbrain loops done <id> · mute a sender: gbrain loops mute sender <email> · details: gbrain loops list)\n`,@@ -207,6 +221,66 @@ async function showLoop(if (link) process.stdout.write(`${link}\n`);}+function idList(ids: number[]): string {+ if (ids.length === 0) return '';+ return `: ${ids.slice(0, 20).join(', ')}${ids.length > 20 ? `, +${ids.length - 20} more` : ''}`;+}++/**+ * #5012: `gbrain loops drop sender <email>` closes every open reply-owed+ * (unanswered_inbound) loop from one sender as `dropped`, one `loops_close`+ * per loop, so each id reports its own outcome. `--dry-run` is the consent+ * step: it lists the ids and count and changes nothing. A drop is final: no+ * command reopens a dropped loop (`mute` is the reversible path).+ */+async function dropSender(engine: BrainEngine, rest: string[], json: boolean): Promise<void> {+ const email = rest[1]?.trim().toLowerCase();+ if (!email || email.startsWith('-') || !email.includes('@')) {+ exitCliError(usageError('gbrain loops drop sender needs an email address.',+ 'Usage: gbrain loops drop sender <email> [--source <id>] [--note <text>] [--dry-run]. Preview first with --dry-run.'), 'loops', { json });+ }+ const source = sourceFlag(rest);+ const noteIdx = rest.indexOf('--note');+ const note = noteIdx !== -1 ? rest[noteIdx + 1] : undefined;+ const { listSenderInboundLoops } = await import('../core/loops/loops-store.ts');+ const loops = await listSenderInboundLoops(engine, email!, source ? [source] : null);+ const ids = loops.map((l) => l.id);+ const apply = `gbrain loops drop sender ${email}${source ? ` --source ${source}` : ''}${note !== undefined ? ` --note ${JSON.stringify(note)}` : ''}`;+ if (rest.includes('--dry-run')) {+ if (json) {+ process.stdout.write(JSON.stringify({ ok: true, status: 'dry_run', sender: email, source_id: source ?? null, would_close: ids, count: ids.length,+ ...(ids.length > 0 ? { apply_command: apply } : {}) }, null, 2) + '\n');+ } else if (ids.length === 0) {+ process.stdout.write(`No open reply-owed loops from ${email}. Nothing to drop.\n`);+ } else {+ process.stdout.write(`Dry run: ${ids.length} open reply-owed loop(s) from ${email} would be dropped${idList(ids)}. Nothing changed.\n`+ + `To drop them (cannot be undone): ${apply}\n`);+ }+ return;+ }+ const closed: number[] = [];+ const failed: Array<{ id: number; reason: string }> = [];+ for (const loop of loops) {+ try {+ const result = (await handleToolCall(engine, 'loops_close', { id: loop.id, status: 'dropped', source_id: loop.source_id,+ note: note ?? `drop sender ${email}` })) as { closed: boolean; reason?: string };+ if (result.closed) closed.push(loop.id);+ else failed.push({ id: loop.id, reason: result.reason ?? 'not_closed' });+ } catch (e) {+ failed.push({ id: loop.id, reason: e instanceof Error ? e.message : String(e) });+ }+ }+ if (json) {+ process.stdout.write(JSON.stringify({ ok: failed.length === 0, status: failed.length === 0 ? 'dropped' : 'partial', sender: email,+ source_id: source ?? null, closed, failed, count: closed.length }, null, 2) + '\n');+ } else {+ process.stdout.write(`Dropped ${closed.length} open reply-owed loop(s) from ${email}${idList(closed)}.\n`+ + (failed.length > 0 ? `${failed.length} could not be dropped: ${failed.slice(0, 10).map((f) => `${f.id} (${f.reason})`).join(', ')}\n` : '')+ + (closed.length > 0 ? `To stop new loops from this sender too: gbrain loops mute sender ${email}${source ? ` --source ${source}` : ''}\n` : ''));+ }+ if (failed.length > 0) setCliExitVerdict(1);+}+export async function runLoops(engine: BrainEngine, args: string[]): Promise<void> {const [first, ...rest] = args;const sub = first as (typeof LOOPS_SUBCOMMANDS)[number] | undefined;@@ -251,6 +325,11 @@ export async function runLoops(engine: BrainEngine, args: string[]): Promise<voireturn;}+ if (sub === 'drop' && rest[0] === 'sender') {+ await dropSender(engine, rest, json);+ return;+ }+if (sub === 'done' || sub === 'drop') {const id = Number(rest.find((a) => /^\d+$/.test(a)));if (!Number.isFinite(id) || id <= 0) {@@ -316,16 +395,28 @@ export async function runLoops(engine: BrainEngine, args: string[]): Promise<voiprocess.exit(2);}}+ const dryRun = rest.includes('--dry-run');if (sub === 'mute') {const result = (await handleToolCall(engine, 'loops_mute', {kind,value,source_id: sourceId,- })) as { muted: boolean; reason?: string };+ ...(dryRun ? { dry_run: true } : {}),+ })) as { muted?: boolean; reason?: string; closed?: number[]; would_close?: number[]; undo_command: string };+ if (dryRun) {+ const ids = result.would_close ?? [];+ if (json) process.stdout.write(JSON.stringify({ ok: true, status: 'dry_run', ...result }, null, 2) + '\n');+ else process.stdout.write(`Dry run: muting ${kind} ${value} would close ${ids.length} open reply-owed loop(s)${idList(ids)}. Nothing changed.\n`);+ return;+ }if (json) {process.stdout.write(JSON.stringify({ ok: result.muted, status: result.muted ? 'muted' : 'not_muted', ...result }, null, 2) + '\n');+ } else if (result.muted) {+ const closed = result.closed ?? [];+ process.stdout.write(`Muted ${kind} ${value}. New loops won't open for it; closed ${closed.length} open reply-owed loop(s)${idList(closed)}.\n`+ + `Undo: ${result.undo_command} (re-checks the closed loops on the next sync)\n`);} else {- process.stdout.write(result.muted ? `Muted ${kind} ${value}. New loops won't open for it (existing loops keep their state).\n` : `Not muted: ${result.reason}\n`);+ process.stdout.write(`Not muted: ${result.reason}\n`);}if (!result.muted) setCliExitVerdict(1);return;@@ -334,16 +425,29 @@ export async function runLoops(engine: BrainEngine, args: string[]): Promise<voikind,value,source_id: sourceId,- })) as { removed: boolean; reason?: string };+ ...(dryRun ? { dry_run: true } : {}),+ })) as { removed?: boolean; reason?: string; requeued?: number[]; would_requeue?: number[]; unverifiable: number[];+ stale_source?: boolean; recheck_command?: string; undo_command: string };+ if (dryRun) {+ const ids = result.would_requeue ?? [];+ if (json) process.stdout.write(JSON.stringify({ ok: true, status: 'dry_run', ...result }, null, 2) + '\n');+ else process.stdout.write(`Dry run: unmuting ${kind} ${value} would queue ${ids.length} closed loop(s) for re-check${idList(ids)}. Nothing changed.\n`);+ return;+ }// A repeated unmute is a no-op, NOT a failure: removed:false exits 0 so// scripts can call it unconditionally without special-casing.if (json) {process.stdout.write(JSON.stringify({ ok: true, status: result.removed ? 'unmuted' : 'not_muted', ...result }, null, 2) + '\n');} else {+ const requeued = result.requeued ?? [];process.stdout.write(- result.removed- ? `Unmuted ${kind} ${value}. New loops can open for it again (loops closed meanwhile stay closed).\n`- : `Not muted: ${kind} ${value} had no suppression in ${sourceId}.\n`,+ (result.removed+ ? `Unmuted ${kind} ${value}. New loops can open for it again.\n`+ : `Not muted: ${kind} ${value} had no suppression in ${sourceId}.\n`)+ + (requeued.length > 0 ? `Queued ${requeued.length} loop(s) the mute closed for re-check on the next sync${idList(requeued)}; each reopens only if nothing answered its thread since.\n` : '')+ + (result.unverifiable.length > 0 ? `${result.unverifiable.length} closed loop(s) have no thread to re-check and stay closed${idList(result.unverifiable)}.\n` : '')+ + (result.stale_source ? `This source has not synced in 24h; the re-check runs on its next sync: ${result.recheck_command}\n` : '')+ + (result.removed ? `Undo: ${result.undo_command}\n` : ''),);}return;diff --git a/src/core/config.ts b/src/core/config.tsindex 5640cb2abc..a7b6f5493c 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1481,6 +1481,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// 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',+ // #5012: boolean, default false (off). On, Gmail Updates mail opens a reply-owed loop only for a sender the owner wrote to.+ 'loops.updates_require_reciprocity',// #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/google-clients.ts b/src/core/google/google-clients.tsindex 400884e34b..542c6361c9 100644--- a/src/core/google/google-clients.ts+++ b/src/core/google/google-clients.ts@@ -133,7 +133,7 @@ export class GoogleApiClient {if (reason === 'rateLimitExceeded' || reason === 'userRateLimitExceeded' || /rate/i.test(msg)) {// fall through to the retry-after sleep below} else if (!/quota/i.test(`${reason} ${msg}`)) {- throw new CredentialError('upstream', `: HTTP 403 ${reason || msg} on ${apiHint}`);+ throw new GoogleForbiddenError(`: HTTP 403 ${reason || msg} on ${apiHint}`);}}if (res.status === 403 || res.status === 429) {@@ -208,6 +208,26 @@ export class GoogleCursorExpiredError extends Error {}}+/**+ * #5012 item 9: a 403 that is neither a disabled API, a rate limit nor a+ * quota: the token cannot read this resource. Still an upstream+ * `CredentialError` for every caller that does not classify it; the calendar+ * sweep and `google status` read it as an unreadable calendar.+ */+export class GoogleForbiddenError extends CredentialError {+ constructor(detail: string) {+ super('upstream', detail);+ this.name = 'GoogleForbiddenError';+ }+}++/** #5012 item 9: the HTTP status when `e` says the calendar cannot be read by this account (403 or 404), else null. */+export function calendarUnreadableStatus(e: unknown): 403 | 404 | null {+ if (e instanceof GoogleForbiddenError) return 403;+ if (e instanceof GoogleCursorExpiredError && e.status === 404) return 404;+ return null;+}+/*** #6324: People answered a syncToken request with a 400 that is NOT the typed* expiry. The People API requires every other parameter of an incremental@@ -475,6 +495,9 @@ export class GmailClient extends GoogleApiClient {labelIds: m.labelIds ?? [],listUnsubscribe: header(m, 'List-Unsubscribe') !== '',autoSubmitted: isAutoSubmittedHeader(header(m, 'Auto-Submitted')),+ precedence: header(m, 'Precedence').trim().toLowerCase(),+ listId: header(m, 'List-Id') !== '',+ replyTo: splitAddressList(header(m, 'Reply-To')),calendarMethod: extractCalendarMethod(m.payload),bodyText,attachmentInspection,@@ -573,6 +596,23 @@ export class CalendarClient extends GoogleApiClient {* only — the sweep still reads ONE calendar per source, so this exists to* find the id you pass to `sources add --calendar-id`.*/+ /**+ * #5012 item 9: one cheap read of the calendar's events (`maxResults=1`).+ * `readable: false` carries the 403/404 that says the account cannot read+ * it; any other failure throws.+ */+ async probeCalendar(calendarId: string, opts: { signal?: AbortSignal } = {}): Promise<{ readable: true } | { readable: false; httpStatus: 403 | 404 }> {+ try {+ await this.fetchJSON(`${CALENDAR_BASE}/calendars/${encodeURIComponent(calendarId.trim() || DEFAULT_CALENDAR_ID)}/events?maxResults=1&fields=kind`,+ 'calendar-json', { ...opts, retries: 1, rateLimitRetries: 1 });+ return { readable: true };+ } catch (e) {+ const httpStatus = calendarUnreadableStatus(e);+ if (httpStatus === null) throw e;+ return { readable: false, httpStatus };+ }+ }+async listCalendars(opts: { signal?: AbortSignal } = {}): Promise<Array<{ id: string; summary: string; primary: boolean; accessRole: string }>> {diff --git a/src/core/google/google-render.ts b/src/core/google/google-render.tsindex 3715db2e41..8a8352a1f5 100644--- a/src/core/google/google-render.ts+++ b/src/core/google/google-render.ts@@ -14,7 +14,7 @@ import { createHash } from 'node:crypto';import { renderAttachmentInspection, threadAttachmentReceipts } from './attachment-receipts.ts';import { emailCitation } from '../output/scaffold.ts';-import { DEFAULT_CONTACTS_DIR, type CalendarEventData, type ContactData, type GmailThreadData } from './types.ts';+import { DEFAULT_CONTACTS_DIR, type CalendarEventData, type ContactData, type GmailMessageMeta, type GmailThreadData } from './types.ts';// ── Noise + signature rules (recipes/email-to-brain.md, now code) ───────────@@ -42,6 +42,19 @@ export function isNoiseSender(fromAddress: string): boolean {return GOOGLE_SYSTEM_SENDERS.has(f) || NOISE_SENDER_SUBSTRINGS.some((p) => f.includes(p));}+const BULK_PRECEDENCE = new Set(['bulk', 'list', 'junk']);++/**+ * #5012: mail that positively declares itself automated: `Precedence:+ * bulk|list|junk`, a `List-Id` header, or a no-reply `From` or `Reply-To`.+ * Category labels and sender guesses are deliberately not signals, so a cold+ * introduction from a real person still owes a reply.+ */+export function isPositivelyAutomated(m: GmailMessageMeta): boolean {+ return BULK_PRECEDENCE.has(m.precedence ?? '') || m.listId === true || isNoiseSender(m.fromAddress)+ || (m.replyTo ?? []).some((a) => isNoiseSender(a));+}+/*** Google Calendar system mail — the invitation/response/cancellation notices* Calendar sends ON BEHALF OF a human organiser or attendee.diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex 710c715cc2..240cdf5cce 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -62,7 +62,7 @@ import {type GoogleSourceState,} from './types.ts';import { LOOPS_EXTRACT_WINDOW_DAYS, loopExtractionEligibility } from './loops-extract.ts';-import { recordGraceVerdict, runLoopsCatchup, seedGraceBackfill, settleDueGraceHolds, type LoopsEnqueueReport } from './loop-catchup.ts';+import { recordGraceVerdict, recordWithheldVerdict, runLoopsCatchup, seedGraceBackfill, seedLoopRechecks, settleDueGraceHolds, type LoopsEnqueueReport } from './loop-catchup.ts';export type { GoogleSourceConfig } from './types.ts';export { runGoogleAttachmentBackfill } from './attachment-backfill.ts';@@ -152,7 +152,8 @@ async function saveGoogleState(deps: GoogleSyncDeps, state: GoogleSourceState):/** #5867/#5868 state a partial managed run still publishes (E20): never the Gmail cursor. */function loopRecoveryState(state: GoogleSourceState): Record<string, unknown> {- const fields = { loop_grace_holds: state.loop_grace_holds, loop_grace_backfill_done: state.loop_grace_backfill_done, loops_catchup: state.loops_catchup };+ const fields = { loop_grace_holds: state.loop_grace_holds, loop_grace_backfill_done: state.loop_grace_backfill_done, loops_catchup: state.loops_catchup,+ loop_withheld_senders: state.loop_withheld_senders, loop_automated_backfill_done: state.loop_automated_backfill_done, calendar_unreadable: state.calendar_unreadable };return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));}@@ -187,6 +188,8 @@ async function processThread(deps.processedThreads.add(thread.threadId);const verdict = await applyLoopDetection(deps, thread, slug);if (verdict && deps.loopState) recordGraceVerdict(deps.loopState, thread, verdict, slug, myAddressSet(deps.entry), deps.log, deps.exclusion);+ if (verdict && deps.loopState) recordWithheldVerdict(deps.loopState, verdict);+ if (verdict?.withheld) summary.loopsWithheld[verdict.withheld.reason] = (summary.loopsWithheld[verdict.withheld.reason] ?? 0) + 1;// LLM extraction candidates: trickle + the bounded recent window only —// the deep historical backfill is never extracted (spend honesty, F9).const newestMs = thread.messages[thread.messages.length - 1]?.internalDateMs ?? 0;@@ -450,6 +453,11 @@ async function settleGraceHolds(g: GmailSweep): Promise<'aborted' | void> {} catch (e) {deps.log(`[google] loop grace backfill failed (retried next sweep): ${e instanceof Error ? e.message : String(e)}`);}+ try {+ await seedLoopRechecks(deps.engine, deps.sourceId, state, deps.log);+ } catch (e) {+ deps.log(`[google] loop re-check seeding failed (retried next sweep): ${e instanceof Error ? e.message : String(e)}`);+ }const settled = await settleDueGraceHolds({ engine: deps.engine, sourceId: deps.sourceId, state, log: deps.log, signal: deps.opts.signal,exclusion: deps.exclusion, processed: deps.processedThreads, refetch: async (tid) => {try {@@ -743,6 +751,7 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: GothreadsSeen: 0,attachmentInspection: {},extractEligibility: {},+ loopsWithheld: {},failedFiles: 0,};const countedSlugs = new Set<string>();@@ -900,6 +909,9 @@ async function runGoogleSyncInner(engine: BrainEngine, sourceId: string, cfg: Go.join(' ')}`,);}+ if (Object.keys(summary.loopsWithheld).length > 0) {+ log(`[google] reply-owed loops withheld: ${Object.entries(summary.loopsWithheld).map(([k, v]) => `${k}=${v}`).join(' ')}`);+ }}// Commitment-loop staleness pass (v1 close semantics): overdue >14d ordiff --git a/src/core/google/loop-catchup.ts b/src/core/google/loop-catchup.tsindex 5629081738..4d4310ce7d 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 { muteRecheckThreads } from '../loops/loops-store.ts';import { loopsSpendGate } from './loops-spend.ts';import type { GmailThreadData, GoogleSourceState, LoopGraceHold } from './types.ts';@@ -100,6 +101,56 @@ export async function seedGraceBackfill(engine: BrainEngine, sourceId: string, sreturn seeded;}+/**+ * #5012: queues threads for a re-fetch through the grace-hold path (a due hold+ * with no spec). Every sweep: threads with loops an unmute queued for+ * re-check. Once: the newest thread of each of the WITHHELD_BACKFILL_SENDERS+ * senders with the most open reply-owed loops, so the withheld-senders record+ * covers loops opened before the automated-mail rule existed.+ */+export async function seedLoopRechecks(engine: BrainEngine, sourceId: string, state: GoogleSourceState, log: Log, now = Date.now()): Promise<number> {+ const holds = state.loop_grace_holds ??= {};+ const seed = (rows: Array<{ thread_id: string; page_slug: string | null }>) => rows.reduce((n, r) => {+ if (holds[r.thread_id]) return n;+ holds[r.thread_id] = { due_ms: now, slug: r.page_slug, rev: null, spec: null };+ return n + 1;+ }, 0);+ const rechecks = seed(await muteRecheckThreads(engine, sourceId));+ let backfill = 0;+ if (!state.loop_automated_backfill_done) {+ backfill = seed(await engine.executeRaw<{ thread_id: string; page_slug: string | null }>(+ `SELECT DISTINCT ON (counterparty_email) thread_id, page_slug, n FROM (+ SELECT counterparty_email, thread_id, page_slug, last_activity_at,+ count(*) OVER (PARTITION BY counterparty_email) AS n+ FROM open_loops+ WHERE source_id = $1 AND status = 'open' AND loop_type = 'unanswered_inbound'+ AND counterparty_email IS NOT NULL AND thread_id IS NOT NULL) l+ ORDER BY counterparty_email, last_activity_at DESC`, [sourceId])+ .then((rows) => (rows as Array<{ thread_id: string; page_slug: string | null; n: number }>)+ .sort((a, b) => Number(b.n) - Number(a.n)).slice(0, WITHHELD_BACKFILL_SENDERS)));+ state.loop_automated_backfill_done = true;+ }+ pruneGraceHolds(holds, log);+ if (rechecks + backfill > 0) log(`[google] loop re-checks queued: ${rechecks} unmuted thread(s), ${backfill} sender backfill thread(s)`);+ return rechecks + backfill;+}++export const WITHHELD_BACKFILL_SENDERS = 500;+export const WITHHELD_SENDERS_CAP = 2_000;++/** #5012: keeps the per-sender record of withheld reply-owed loops current with one fresh verdict. */+export function recordWithheldVerdict(state: GoogleSourceState, verdict: ThreadLoopVerdict, now = Date.now()): void {+ const record = state.loop_withheld_senders ??= {};+ for (const spec of verdict.open) if (spec.loopType === 'unanswered_inbound') delete record[spec.counterpartyEmail];+ if (!verdict.withheld) return;+ const key = sanitizeForJsonb(verdict.withheld.counterpartyEmail);+ const prior = record[key];+ record[key] = { reason: verdict.withheld.reason, count: (prior?.count ?? 0) + 1, last_ms: now };+ const keys = Object.keys(record);+ if (keys.length <= WITHHELD_SENDERS_CAP) return;+ for (const k of keys.sort((a, b) => record[a].last_ms - record[b].last_ms).slice(0, keys.length - WITHHELD_SENDERS_CAP)) delete record[k];+}+export type GraceRefetch = (threadId: string) => Promise<'ok' | 'gone' | 'failed'>;/**diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.tsindex f7820f3975..57e5a45963 100644--- a/src/core/google/loop-detect.ts+++ b/src/core/google/loop-detect.ts@@ -17,6 +17,11 @@* - list mail (List-Unsubscribe) never opens loops* - auto-submitted mail (RFC 3834 Auto-Submitted other than "no": tracker* notices, auto-replies) neither opens nor closes loops+ * - positively automated mail (#5012: `Precedence: bulk|list|junk`, a+ * `List-Id`, or a no-reply `Reply-To`) owes no reply; the verdict records+ * `withheld: 'automated_mail'`. A Gmail category alone never withholds a+ * reply-owed loop; with `loops.updates_require_reciprocity` on, Updates+ * mail opens one only when the owner has written to the sender* - self-threads (all participants are my addresses) never open loops* - CC-only inbound does not owe a reply (must be in To:)* - outbound without a question mark is FYI, not an ask; a question mark@@ -38,14 +43,17 @@ import type { BrainEngine } from '../engine.ts';import {closeThreadLoops,loadSuppressions,+ settleMuteRecheck,upsertOpenLoop,type LoopEvidence,type SuppressionSet,} from '../loops/loops-store.ts';import { resolveCounterparty, type ResolvedCounterparty } from './counterparty.ts';-import { isCalendarSystemMail, isNoiseSender } from './google-render.ts';+import { isCalendarSystemMail, isNoiseSender, isPositivelyAutomated } from './google-render.ts';+export { isPositivelyAutomated } from './google-render.ts';import { hasBulkCategory } from './gmail-categories.ts';import { isExcludedByLabels, NO_EXCLUSION, pageLabelIds, type LoopsExclusionPolicy } from './loops-exclusion.ts';+import { ownerWroteToFor } from './loops-reciprocity.ts';import type { GmailMessageMeta, GmailThreadData } from './types.ts';export const INBOUND_GRACE_HOURS = 24;@@ -80,8 +88,22 @@ export interface ThreadLoopVerdict {* hold because Gmail history never re-lists a quiet thread.*/held?: { untilMs: number; spec: ThreadLoopSpec };+ /**+ * #5012: a reply-owed loop every other gate would have opened (or held)+ * was withheld because the mail is positively automated, or because it is+ * Updates mail from a sender the owner never wrote to (opt-in rule).+ */+ withheld?: { reason: LoopWithheldReason; counterpartyEmail: string };+}++export type LoopWithheldReason = 'automated_mail' | 'updates_without_reciprocity';++/** #5012: opt-in detection policy. `ownerWroteTo` is set only when `loops.updates_require_reciprocity` is on. */+export interface LoopDetectPolicy {+ ownerWroteTo?: ReadonlySet<string> | null;}+function isMine(m: GmailMessageMeta, myAddresses: Set<string>): boolean {return m.labelIds.includes('SENT') || myAddresses.has(m.fromAddress);}@@ -122,6 +144,7 @@ export function detectThreadLoop(myAddresses: Set<string>,now: Date,suppressions?: SuppressionSet,+ policy: LoopDetectPolicy = {},): ThreadLoopVerdict {const messages = thread.messages.filter((m) => m.internalDateMs > 0);if (messages.length === 0) return { open: [], close: [] };@@ -206,6 +229,11 @@ export function detectThreadLoop(const inTo = last.to.some((a) => myAddresses.has(a));if (!inTo) return { open: [], close };if (threadSuppressed || suppressions?.senders.has(last.fromAddress)) return { open: [], close };+ if (isPositivelyAutomated(last)) return { open: [], close, withheld: { reason: 'automated_mail', counterpartyEmail: last.fromAddress } };+ if (policy.ownerWroteTo && last.labelIds.includes('CATEGORY_UPDATES') && !substantive.some((m) => isMine(m, myAddresses))+ && !policy.ownerWroteTo.has(last.fromAddress)) {+ return { open: [], close, withheld: { reason: 'updates_without_reciprocity', counterpartyEmail: last.fromAddress } };+ }const owedSince = run.find((m) => m.to.some((a) => myAddresses.has(a))) ?? last;const spec: ThreadLoopSpec = {loopType: 'unanswered_inbound',@@ -279,6 +307,11 @@ export function __clearSuppressionCacheForTests(engine?: BrainEngine): void {else suppressionCacheEpoch++;}+/** #5012: a mute or unmute in this process takes effect on the next detection, not after the 60s TTL. */+export function invalidateSuppressionCache(engine: BrainEngine): void {+ suppressionCache.delete(engine);+}+/*** Apply the verdict: close thread loops that no longer hold, upsert the ones* that do (dedup key 'thread:<threadId>:<loop_type>' — reopen on conflict).@@ -295,11 +328,12 @@ export async function applyThreadLoopVerdict(exclusion: LoopsExclusionPolicy = NO_EXCLUSION,): Promise<ThreadLoopVerdict> {const suppressions = await suppressionsFor(engine, sourceId);+ const policy: LoopDetectPolicy = { ownerWroteTo: await ownerWroteToFor(engine, sourceId, myAddresses) };// One verdict, two lanes: `close` is the turn-flip set (suppression- and// grace-independent — only a genuine reply closes, and only the answered// type); `open` is suppression-filtered. A held loop (grace window,// CC-only nudge, muted sender) is neither opened nor closed.- const verdict = withLabelExclusion(detectThreadLoop(thread, myAddresses, now, suppressions), exclusion,+ const verdict = withLabelExclusion(detectThreadLoop(thread, myAddresses, now, suppressions, policy), exclusion,thread.messages.flatMap((m) => m.labelIds));const desired = new Set(verdict.open.map((s) => s.loopType));@@ -309,6 +343,12 @@ export async function applyThreadLoopVerdict(}for (const spec of verdict.open) await upsertThreadLoop(engine, sourceId, thread.threadId, spec, pageSlug);+ // #5012: an unmute's re-check that neither reopened nor answered the queued loop leaves it closed;+ // a grace hold keeps it queued until the hold settles.+ if (!verdict.held && suppressions.recheckThreads?.has(thread.threadId)) {+ await settleMuteRecheck(engine, sourceId, thread.threadId);+ suppressions.recheckThreads.delete(thread.threadId);+ }return verdict;}diff --git a/src/core/google/loops-reciprocity.ts b/src/core/google/loops-reciprocity.tsnew file mode 100644index 0000000000..857d81f7ab--- /dev/null+++ b/src/core/google/loops-reciprocity.ts@@ -0,0 +1,63 @@+/**+ * #5012: the opt-in Updates reciprocity rule for the deterministic loop+ * detector. With `loops.updates_require_reciprocity` on (default off), a+ * reply-owed loop on Gmail Updates mail opens only when the owner has written+ * to the sender: the sender appears in a stored thread the owner wrote in, or+ * the owner wrote a substantive message in this thread. Off, the set is null+ * and the detector ignores the category, so a cold introduction that Gmail+ * files under Updates still opens a loop.+ *+ * The owner-wrote-to set is built from stored email pages (one query over the+ * source's thread pages whose `senders` include an owner address), at most+ * once per sweep: it is cached per engine and source for REBUILD_MS.+ */+import type { BrainEngine } from '../engine.ts';++export const LOOPS_UPDATES_RECIPROCITY_KEY = 'loops.updates_require_reciprocity';+const REBUILD_MS = 10 * 60_000;+const ON = new Set(['true', '1', 'on', 'yes']);+const OFF = new Set(['false', '0', 'off', 'no']);++/** Null when `value` is a boolean `config set` accepts for the key; otherwise the refusal text (nothing is written). */+export function validateLoopsReciprocityConfigValue(key: string, value: string): string | null {+ if (key !== LOOPS_UPDATES_RECIPROCITY_KEY) return null;+ const v = value.trim().toLowerCase();+ return ON.has(v) || OFF.has(v) ? null+ : `${key} must be true or false (default false: Gmail Updates mail opens reply-owed loops like any other mail; got "${value}"). Nothing was written.`;+}++const cache = new WeakMap<BrainEngine, Map<string, { set: ReadonlySet<string> | null; loadedAt: number }>>();++/** The addresses the owner has written to in this source, or null when the rule is off (the default). */+export async function ownerWroteToFor(engine: BrainEngine, sourceId: string, myAddresses: ReadonlySet<string>): Promise<ReadonlySet<string> | null> {+ let perEngine = cache.get(engine);+ if (!perEngine) cache.set(engine, perEngine = new Map());+ const hit = perEngine.get(sourceId);+ if (hit && Date.now() - hit.loadedAt < REBUILD_MS) return hit.set;+ let enabled = false;+ try {+ enabled = ON.has(String(await engine.getConfig(LOOPS_UPDATES_RECIPROCITY_KEY) ?? '').trim().toLowerCase());+ } catch { /* unreadable config keeps the default (off) */ }+ let set: ReadonlySet<string> | null = null;+ if (enabled) {+ const rows = await engine.executeRaw<{ addr: string }>(+ `SELECT DISTINCT lower(a.addr) AS addr+ FROM pages p,+ jsonb_array_elements_text(CASE WHEN jsonb_typeof(p.frontmatter->'participants') = 'array'+ THEN p.frontmatter->'participants' ELSE '[]'::jsonb END) AS a(addr)+ WHERE p.source_id = $1 AND p.type = 'email' AND p.deleted_at IS NULL+ AND jsonb_typeof(p.frontmatter->'senders') = 'array'+ AND EXISTS (SELECT 1 FROM jsonb_array_elements_text(p.frontmatter->'senders') AS s(addr)+ WHERE lower(s.addr) = ANY(string_to_array($2, E'\\n')))`,+ [sourceId, [...myAddresses].join('\n')],+ );+ set = new Set(rows.map((r) => r.addr).filter((a) => !myAddresses.has(a)));+ }+ perEngine.set(sourceId, { set, loadedAt: Date.now() });+ return set;+}++/** Test seam: forget the cached setting and set (per engine when given). */+export function __clearReciprocityCacheForTests(engine: BrainEngine): void {+ cache.delete(engine);+}diff --git a/src/core/google/sweep-shared.ts b/src/core/google/sweep-shared.tsindex 050cc98fb3..f6561fcb1f 100644--- a/src/core/google/sweep-shared.ts+++ b/src/core/google/sweep-shared.ts@@ -42,6 +42,8 @@ export interface GoogleSyncSummary {* over-filtering without leaking mail content into logs.*/extractEligibility: Record<string, number>;+ /** #5012: reply-owed loops the detector withheld this sweep, by reason (counts only). */+ loopsWithheld: Record<string, number>;failedFiles: number;}diff --git a/src/core/google/types.ts b/src/core/google/types.tsindex d8c04f0de9..8456f7d4ae 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -115,6 +115,21 @@ export interface GoogleSourceState {loop_grace_backfill_done?: boolean;/** #5867: managed-source 30-day loops_extract catch-up progress. */loops_catchup?: LoopsCatchupState;+ /**+ * #5012: the record of reply-owed loops the detector withheld, per sender+ * (src/core/google/loop-catchup.ts, capped). A sender leaves it when a later+ * thread of theirs opens a loop. `gbrain waiting` counts the open loops+ * from these senders that the rule would not have opened.+ */+ loop_withheld_senders?: Record<string, LoopWithheldSender>;+ /** #5012: one-shot re-check of the senders behind open reply-owed loops (set when seeded). */+ loop_automated_backfill_done?: boolean;+ /**+ * #5012 item 9: set when `events.list` on the configured calendar returned+ * 403 or 404 (the account cannot read it), cleared by the next successful+ * list. `gbrain doctor` and `gbrain google status --no-probe` read it.+ */+ calendar_unreadable?: CalendarUnreadable | null;calendar_sync_token: string | null;/*** Calendar id `calendar_sync_token` was minted for. A token is only valid@@ -196,6 +211,21 @@ export interface LoopGraceHold {} | null;}+/** #5012: one sender whose reply-owed loops the detector withheld. */+export interface LoopWithheldSender {+ reason: 'automated_mail' | 'updates_without_reciprocity';+ count: number;+ last_ms: number;+}++/** #5012 item 9: the configured calendar could not be read. */+export interface CalendarUnreadable {+ code: 'calendar_unreadable';+ calendar_id: string;+ http_status: 403 | 404;+ at: string;+}+/** #5867: the managed catch-up's window floor, its one-retry set and its done marker. */export interface LoopsCatchupState {version: 1;@@ -219,6 +249,12 @@ export interface GmailMessageMeta {listUnsubscribe: boolean;/** RFC 3834 `Auto-Submitted` other than `no` (tracker notices, auto-replies); absent means human mail. */autoSubmitted?: boolean;+ /** #5012: the `Precedence` header, trimmed and lowercased (`bulk`, `list`, `junk`); absent or '' when not sent. */+ precedence?: string;+ /** #5012: an RFC 2919 `List-Id` header was present (mailing-list or list-manager mail). */+ listId?: boolean;+ /** #5012: bare lowercased `Reply-To` addresses; absent or empty when not sent. */+ replyTo?: string[];/*** iCalendar method when the message carries a `text/calendar` part or an* `.ics` attachment — 'REQUEST' | 'REPLY' | 'CANCEL' | 'COUNTER' | '' when adiff --git a/src/core/loops/loops-store.ts b/src/core/loops/loops-store.tsindex eff3003837..d1b110608b 100644--- a/src/core/loops/loops-store.ts+++ b/src/core/loops/loops-store.ts@@ -152,8 +152,11 @@ export async function upsertOpenLoop(closed_at = NULL,closed_by = NULL,updated_at = now()- WHERE open_loops.status = 'open'- OR EXCLUDED.last_activity_at > open_loops.last_activity_at+ WHERE (open_loops.status = 'open'+ OR EXCLUDED.last_activity_at > open_loops.last_activity_at+ OR open_loops.closed_by = '${MUTE_RECHECK}')+ AND (open_loops.closed_by IS DISTINCT FROM '${MUTED}'+ OR open_loops.counterparty_email IS DISTINCT FROM EXCLUDED.counterparty_email)RETURNING id, (xmax = 0) AS created`,[loop.sourceId,@@ -177,7 +180,9 @@ export async function upsertOpenLoop(// The DO UPDATE's WHERE is the manual-close guard: a closed (done/dropped/// stale) row only reopens on GENUINELY newer activity. Without it, any// re-render of an unchanged thread (label-only history touch, re-extraction- // of the same content) would silently revert `gbrain loops done`.+ // of the same content) would silently revert `gbrain loops done`. #5012: a+ // loop a mute closed never reopens for the same counterparty while muted,+ // and one an unmute queued for re-check reopens on the re-check's verdict.if (rows.length > 0) {return { id: Number(rows[0].id), created: Boolean(rows[0].created), applied: true };}@@ -206,7 +211,11 @@ export async function closeOpenLoop(return rows.length > 0 ? normalizeRow(rows[0]) : null;}-/** Close every open thread-detector loop for a thread (reply auto-close). */+/**+ * Close every open thread-detector loop for a thread (reply auto-close). A+ * loop an unmute queued for re-check closes the same way: the thread's turn+ * flipped, so the owner answered it.+ */export async function closeThreadLoops(engine: BrainEngine,sourceId: string,@@ -217,7 +226,7 @@ export async function closeThreadLoops(const rows = await engine.executeRaw<{ id: number }>(`UPDATE open_loopsSET status = 'done', closed_at = now(), closed_by = $1, updated_at = now()- WHERE source_id = $2 AND thread_id = $3 AND status = 'open'+ WHERE source_id = $2 AND thread_id = $3 AND (status = 'open' OR closed_by = '${MUTE_RECHECK}')AND detector = 'deterministic_thread'AND ($4::text IS NULL OR loop_type = ANY(string_to_array($4, ',')))RETURNING id`,@@ -298,6 +307,106 @@ export async function markStaleLoops(engine: BrainEngine, sourceId: string): Pro// ── Suppressions (`gbrain loops mute`) ───────────────────────────────────────+/** #5012: `closed_by` of a reply-owed loop a mute closed (status `dropped`). */+export const MUTED = 'muted';+/** #5012: `closed_by` of a muted loop an unmute queued for re-check on the next Gmail sweep. */+export const MUTE_RECHECK = 'mute_recheck';+/** #5012: `closed_by` of a muted loop whose re-check found nothing owed, or that has no thread to re-check. */+export const UNMUTED = 'unmuted';++function suppressionMatch(kind: 'sender' | 'thread', param: string, alias = ''): string {+ return kind === 'sender' ? `${alias}counterparty_email = ${param}` : `lower(${alias}thread_id) = ${param}`;+}++/**+ * #5012: the reply-owed loops a sender or thread mute covers: open+ * `unanswered_inbound` loops (and ones still queued from an earlier unmute).+ * `apply` closes them as `dropped` / `muted`; otherwise they are only listed.+ */+export async function closeMutedLoops(+ engine: BrainEngine,+ sourceId: string,+ kind: 'sender' | 'thread',+ value: string,+ apply: boolean,+): Promise<number[]> {+ const where = `source_id = $1 AND loop_type = 'unanswered_inbound' AND ${suppressionMatch(kind, '$2')}+ AND (status = 'open' OR closed_by = '${MUTE_RECHECK}')`;+ const rows = apply+ ? await engine.executeRaw<{ id: number }>(+ `UPDATE open_loops SET status = 'dropped', closed_at = now(), closed_by = '${MUTED}', updated_at = now()+ WHERE ${where} RETURNING id`, [sourceId, value.toLowerCase()])+ : await engine.executeRaw<{ id: number }>(`SELECT id FROM open_loops WHERE ${where} ORDER BY id`, [sourceId, value.toLowerCase()]);+ return rows.map((r) => Number(r.id)).sort((a, b) => a - b);+}++/**+ * #5012: the loops an unmute hands back to detection: those this mute closed+ * that no remaining suppression still covers. Loops on a thread are queued+ * for re-check (`mute_recheck`): the next Gmail sweep re-fetches the thread+ * and reopens a loop only when nothing answered it since. A loop without a+ * thread cannot be re-checked and stays closed (`unmuted`). Manual closes are+ * never touched. Without `apply` the loops are only listed.+ */+export async function requeueMutedLoops(+ engine: BrainEngine,+ sourceId: string,+ kind: 'sender' | 'thread',+ value: string,+ apply: boolean,+): Promise<{ requeued: number[]; unverifiable: number[] }> {+ const rows = await engine.executeRaw<{ id: number; thread_id: string | null }>(+ `${apply ? `UPDATE open_loops l SET closed_by = CASE WHEN l.thread_id IS NULL THEN '${UNMUTED}' ELSE '${MUTE_RECHECK}' END, updated_at = now()`+ : 'SELECT l.id, l.thread_id FROM open_loops l'}+ WHERE l.source_id = $1 AND l.closed_by = '${MUTED}' AND ${suppressionMatch(kind, '$3', 'l.')}+ AND NOT EXISTS (SELECT 1 FROM loop_suppressions s+ WHERE s.source_id = l.source_id AND NOT (s.kind = $2 AND s.value = $3)+ AND ((s.kind = 'thread' AND s.value = lower(l.thread_id))+ OR (s.kind = 'sender' AND s.value = l.counterparty_email)))+ ${apply ? 'RETURNING l.id, l.thread_id' : ''}`,+ [sourceId, kind, value.toLowerCase()],+ );+ const ids = (pick: (r: { thread_id: string | null }) => boolean) =>+ rows.filter(pick).map((r) => Number(r.id)).sort((a, b) => a - b);+ return { requeued: ids((r) => r.thread_id !== null), unverifiable: ids((r) => r.thread_id === null) };+}++/** #5012: every open reply-owed loop from one sender (`gbrain loops drop sender`), oldest id first. */+export async function listSenderInboundLoops(+ engine: BrainEngine,+ email: string,+ sourceIds: string[] | null,+): Promise<Array<{ id: number; source_id: string }>> {+ const rows = await engine.executeRaw<{ id: number; source_id: string }>(+ `SELECT id, source_id FROM open_loops+ WHERE status = 'open' AND loop_type = 'unanswered_inbound' AND counterparty_email = $1+ AND ($2::text IS NULL OR source_id = ANY(string_to_array($2, ',')))+ ORDER BY id`,+ [email.toLowerCase(), sourceIds && sourceIds.length > 0 ? sourceIds.join(',') : null],+ );+ return rows.map((r) => ({ id: Number(r.id), source_id: r.source_id }));+}++/** #5012: a re-checked thread whose verdict neither reopened nor answered its queued loops: they stay closed. */+export async function settleMuteRecheck(engine: BrainEngine, sourceId: string, threadId: string): Promise<number> {+ const rows = await engine.executeRaw<{ id: number }>(+ `UPDATE open_loops SET closed_by = '${UNMUTED}', updated_at = now()+ WHERE source_id = $1 AND thread_id = $2 AND closed_by = '${MUTE_RECHECK}' RETURNING id`,+ [sourceId, threadId],+ );+ return rows.length;+}++/** #5012: threads with loops an unmute queued for re-check (the sweep re-fetches each). */+export async function muteRecheckThreads(engine: BrainEngine, sourceId: string): Promise<Array<{ thread_id: string; page_slug: string | null }>> {+ return engine.executeRaw<{ thread_id: string; page_slug: string | null }>(+ `SELECT thread_id, max(page_slug) AS page_slug FROM open_loops+ WHERE source_id = $1 AND closed_by = '${MUTE_RECHECK}' AND thread_id IS NOT NULL+ GROUP BY thread_id ORDER BY thread_id`,+ [sourceId],+ );+}+export async function addSuppression(engine: BrainEngine,sourceId: string,@@ -343,6 +452,8 @@ export async function removeSuppression(export interface SuppressionSet {senders: Set<string>;threads: Set<string>;+ /** #5012: threads with loops an unmute queued for re-check. */+ recheckThreads?: Set<string>;}export async function loadSuppressions(@@ -359,5 +470,6 @@ export async function loadSuppressions(if (r.kind === 'sender') senders.add(r.value);else threads.add(r.value);}- return { senders, threads };+ const recheckThreads = new Set((await muteRecheckThreads(engine, sourceId)).map((r) => r.thread_id));+ return { senders, threads, recheckThreads };}diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex cce35425f8..ad8965c6e2 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -6038,7 +6038,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["mutating": false,"idempotent": true,"outputRedaction": "retrieval",- "description": "The open-loop engine's killer output: who is waiting on you, what you promised, and the context needed to respond. Grouped by counterparty (default, ranked; each group shows at most 5 loops, the rest counted in loops_omitted) or flat. Loops that name no counterparty are never ranked as a person: they come back in no_counterparty (null when none). Loops come from the deterministic Gmail thread-state detector and the LLM commitment extractor. Remote callers get redacted evidence (no verbatim quotes); trusted local callers also get quotes, Gmail deep links, entity-card context, and a pre-rendered text digest. Carries google-source freshness (stale flag) and completeness: when it is \"partial\", some mail in the window is held after repeated import failures; present the answer as partial and name the held items and their retry command.",+ "description": "The open-loop engine's killer output: who is waiting on you, what you promised, and the context needed to respond. Grouped by counterparty (default, ranked; each group shows at most 5 loops, the rest counted in loops_omitted) or flat. Loops that name no counterparty are never ranked as a person: they come back in no_counterparty (null when none). Loops come from the deterministic Gmail thread-state detector and the LLM commitment extractor. Remote callers get redacted evidence (no verbatim quotes); trusted local callers also get quotes, Gmail deep links, entity-card context, and a pre-rendered text digest. Carries google-source freshness (stale flag) and completeness: when it is \"partial\", some mail in the window is held after repeated import failures; present the answer as partial and name the held items and their retry command. The grouped view also returns withheld_noise (null when none): open reply-owed loops from senders whose mail the detector now treats as automated, with a per-sender preview_command for closing them.","params": {"group_by": {"type": "string",@@ -6141,7 +6141,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["name": "loops_mute","idempotent": true,"outputRedaction": "no_stored_text",- "description": "Suppress a sender (email address) or thread id from opening NEW loops — the detector feedback primitive behind \"never track this sender\". Existing loops keep their state.",+ "description": "Suppress a sender (email address) or thread id from opening NEW loops — the detector feedback primitive behind \"never track this sender\". It also closes that sender's (or thread's) open reply-owed (unanswered_inbound) loops as dropped with closed_by \"muted\" and lists their ids in `closed`; other loop types keep their state. dry_run lists `would_close` and changes nothing. loops_unmute re-checks the closed loops.","params": {"kind": {"type": "string",@@ -6170,7 +6170,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["name": "loops_unmute","idempotent": true,"outputRedaction": "no_stored_text",- "description": "Remove a sender/thread suppression added by loops_mute, so the detector can open NEW loops for it again. Exact-match only. Does not reopen loops closed while the mute was in place.",+ "description": "Remove a sender/thread suppression added by loops_mute, so the detector can open NEW loops for it again. Exact-match only. The reply-owed loops the mute closed (unless another mute still covers them) are queued for re-check on the next Gmail sync and listed in `requeued`: a loop reopens only when nothing answered its thread since the mute. `unverifiable` lists closed loops with no thread to re-check (they stay closed); `stale_source` means the re-check waits on a sync that has not run in 24h. Manually closed loops are never touched. dry_run lists `would_requeue` and changes nothing.","params": {"kind": {"type": "string",diff --git a/src/core/ops/loops.ts b/src/core/ops/loops.tsindex f055f66508..1cd9c63c4c 100644--- a/src/core/ops/loops.ts+++ b/src/core/ops/loops.ts@@ -27,9 +27,11 @@ import { validateSourceId } from '../utils.ts';import { closedLoopWithActiveFact, retireLoopFact } from '../persistence/loop-fact-retirement.ts';import {addSuppression,+ closeMutedLoops,closeOpenLoop,listOpenLoops,removeSuppression,+ requeueMutedLoops,type LoopStatus,type LoopType,type OpenLoopRow,@@ -136,6 +138,45 @@ async function heldCoverage(ctx: OperationContext, sources: GoogleSourceFreshnes}}+interface WithheldNoiseSender { source_id: string; email: string; open_loops: number; reason: string; preview_command: string }++/**+ * #5012: open reply-owed loops from senders the detector now withholds (the+ * `loop_withheld_senders` record in each google source's connector state):+ * loops the automated-mail rule would not have opened. Null when there are+ * none or the record cannot be read (advisory; never blocks the answer).+ */+async function withheldNoise(ctx: OperationContext, sources: GoogleSourceFreshness[]): Promise<{ loop_count: number; sender_count: number; senders: WithheldNoiseSender[] } | null> {+ if (!sources.length) return null;+ try {+ const { managedBrain, readConnectorCursorState } = await import('../connectors/item-holds-store.ts');+ const rows = await ctx.engine.executeRaw<{ id: string; incarnation: string; local_path: string | null; config: Record<string, unknown> }>(+ `SELECT id, incarnation::text AS incarnation, local_path, config FROM sources WHERE id = ANY(string_to_array($1, E'\n'))`,+ [sources.map((x) => x.id).join('\n')]);+ const managed = await managedBrain(ctx.engine);+ const senders: WithheldNoiseSender[] = [];+ for (const row of rows) {+ const record = ((await readConnectorCursorState(ctx.engine, row, managed))?.loop_withheld_senders ?? {}) as Record<string, { reason?: string }>;+ const emails = Object.keys(record);+ if (!emails.length) continue;+ const counts = await ctx.engine.executeRaw<{ email: string; n: number }>(+ `SELECT counterparty_email AS email, count(*)::int AS n FROM open_loops+ WHERE source_id = $1 AND status = 'open' AND loop_type = 'unanswered_inbound'+ AND counterparty_email = ANY(string_to_array($2, E'\n'))+ GROUP BY counterparty_email`, [row.id, emails.join('\n')]);+ for (const c of counts) {+ senders.push({ source_id: row.id, email: c.email, open_loops: Number(c.n), reason: record[c.email]?.reason ?? 'automated_mail',+ preview_command: `gbrain loops drop sender ${c.email} --source ${row.id} --dry-run` });+ }+ }+ if (!senders.length) return null;+ senders.sort((a, b) => b.open_loops - a.open_loops || a.email.localeCompare(b.email));+ return { loop_count: senders.reduce((n, x) => n + x.open_loops, 0), sender_count: senders.length, senders: senders.slice(0, 10) };+ } catch {+ return null;+ }+}+function partialLines(held: HeldItemView[]): string[] {const lines = held.slice(0, 10).map((h) => ` - ${h.key}${h.sender ? ` from ${h.sender}` : ''}${h.subject ? `: ${h.subject}` : ''}`);if (held.length > 10) lines.push(` +${held.length - 10} more`);@@ -361,7 +402,9 @@ const open_loops: Operation = {'redacted evidence (no verbatim quotes); trusted local callers also get quotes, Gmail deep links, ' +'entity-card context, and a pre-rendered text digest. Carries google-source freshness (stale flag) and ' +'completeness: when it is "partial", some mail in the window is held after repeated import failures; present the ' +- 'answer as partial and name the held items and their retry command.',+ 'answer as partial and name the held items and their retry command. The grouped view also returns withheld_noise ' ++ '(null when none): open reply-owed loops from senders whose mail the detector now treats as automated, with a ' ++ 'per-sender preview_command for closing them.',params: {group_by: { type: 'string', enum: ['counterparty', 'none'], description: "Default 'counterparty' (ranked groups)." },status: { type: 'string', enum: ['open', 'done', 'dropped', 'stale'], description: "Default 'open', except with `id`, where any status matches." },@@ -548,6 +591,7 @@ const open_loops: Operation = {return {groups,no_counterparty: noCounterparty,+ ...(loopId === undefined ? { withheld_noise: await withheldNoise(ctx, freshness.sources) } : {}),count: loops.length,truncated,stale: freshness.stale,@@ -693,13 +737,20 @@ const loops_close: Operation = {},};+/** #5012: the CLI command that reverses a mute or unmute. */+function undoCommand(verb: 'mute' | 'unmute', kind: unknown, value: string, sourceId: string): string {+ return `gbrain loops ${verb} ${String(kind)} ${value} --source ${sourceId}`;+}+const loops_mute: Operation = {name: 'loops_mute',idempotent: true,outputRedaction: 'no_stored_text',description:'Suppress a sender (email address) or thread id from opening NEW loops — the detector feedback ' +- 'primitive behind "never track this sender". Existing loops keep their state.',+ 'primitive behind "never track this sender". It also closes that sender\'s (or thread\'s) open reply-owed ' ++ '(unanswered_inbound) loops as dropped with closed_by "muted" and lists their ids in `closed`; other loop types ' ++ 'keep their state. dry_run lists `would_close` and changes nothing. loops_unmute re-checks the closed loops.',params: {kind: { type: 'string', required: true, enum: ['sender', 'thread'], description: 'What to mute.' },value: { type: 'string', required: true, description: 'The sender email or Gmail thread id.' },@@ -728,9 +779,17 @@ const loops_mute: Operation = {if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {throw noGoogleContent(ctx, `loops_mute: source "${sourceId}" holds no Google content — a suppression there can never match; pass source_id naming the google source`);}- if (ctx.dryRun) return { dry_run: true, action: 'loops_mute', kind: p.kind, value: p.value };- await addSuppression(ctx.engine, sourceId, p.kind as 'sender' | 'thread', p.value as string);- return { muted: true, kind: p.kind, value: (p.value as string).toLowerCase(), source_id: sourceId };+ const kind = p.kind as 'sender' | 'thread';+ const value = (p.value as string).toLowerCase();+ const undo = undoCommand('unmute', kind, value, sourceId);+ if (ctx.dryRun) {+ const wouldClose = await closeMutedLoops(ctx.engine, sourceId, kind, value, false);+ return { dry_run: true, action: 'loops_mute', kind, value, source_id: sourceId, would_close: wouldClose, count: wouldClose.length, undo_command: undo };+ }+ await addSuppression(ctx.engine, sourceId, kind, value);+ const closed = await closeMutedLoops(ctx.engine, sourceId, kind, value, true);+ (await import('../google/loop-detect.ts')).invalidateSuppressionCache(ctx.engine);+ return { muted: true, kind, value, source_id: sourceId, closed, count: closed.length, undo_command: undo };},};@@ -740,7 +799,11 @@ const loops_unmute: Operation = {outputRedaction: 'no_stored_text',description:'Remove a sender/thread suppression added by loops_mute, so the detector can open NEW loops for ' +- 'it again. Exact-match only. Does not reopen loops closed while the mute was in place.',+ 'it again. Exact-match only. The reply-owed loops the mute closed (unless another mute still covers them) are queued ' ++ 'for re-check on the next Gmail sync and listed in `requeued`: a loop reopens only when nothing answered its thread ' ++ 'since the mute. `unverifiable` lists closed loops with no thread to re-check (they stay closed); `stale_source` ' ++ 'means the re-check waits on a sync that has not run in 24h. Manually closed loops are never touched. dry_run lists ' ++ '`would_requeue` and changes nothing.',params: {kind: { type: 'string', required: true, enum: ['sender', 'thread'], description: 'What to unmute.' },value: { type: 'string', required: true, description: 'The sender email or Gmail thread id.' },@@ -767,20 +830,31 @@ const loops_unmute: Operation = {if (p.source_id === undefined && !(await sourceHasGoogleContent(ctx, sourceId))) {throw noGoogleContent(ctx, `loops_unmute: source "${sourceId}" holds no Google content — pass source_id naming the google source`);}- if (ctx.dryRun) return { dry_run: true, action: 'loops_unmute', kind: p.kind, value: p.value };- const removed = await removeSuppression(- ctx.engine,- sourceId,- p.kind as 'sender' | 'thread',- p.value as string,- );+ const kind = p.kind as 'sender' | 'thread';+ const value = (p.value as string).toLowerCase();+ const undo = undoCommand('mute', kind, value, sourceId);+ if (ctx.dryRun) {+ const preview = await requeueMutedLoops(ctx.engine, sourceId, kind, value, false);+ return { dry_run: true, action: 'loops_unmute', kind, value, source_id: sourceId, would_requeue: preview.requeued,+ unverifiable: preview.unverifiable, count: preview.requeued.length, undo_command: undo };+ }+ const removed = await removeSuppression(ctx.engine, sourceId, kind, value);+ const { requeued, unverifiable } = await requeueMutedLoops(ctx.engine, sourceId, kind, value, true);+ (await import('../google/loop-detect.ts')).invalidateSuppressionCache(ctx.engine);+ const fresh = (await googleSourceFreshness(ctx, { sourceId })).sources[0];+ const stale = requeued.length > 0 && (fresh?.stale ?? true);// removed:false is the ordinary "was not muted" answer, never an error —// a retried unmute must be safe.return {removed: removed > 0,- kind: p.kind,- value: (p.value as string).toLowerCase(),+ kind,+ value,source_id: sourceId,+ requeued,+ unverifiable,+ count: requeued.length,+ ...(stale ? { stale_source: true, recheck_command: `gbrain sync --source ${sourceId}` } : {}),+ undo_command: undo,...(removed > 0 ? {} : { reason: 'no matching suppression' }),};},diff --git a/test/contacts-phone-only-groups-6324.test.ts b/test/contacts-phone-only-groups-6324.test.tsindex 25ddf7f04e..6ce3687759 100644--- a/test/contacts-phone-only-groups-6324.test.ts+++ b/test/contacts-phone-only-groups-6324.test.ts@@ -184,7 +184,7 @@ function harness(state: Partial<GoogleSourceState> = {}, opts: { idLookup?: boolconst full: GoogleSourceState = { gmail_history_id: null, gmail_backfill_floor_ms: null, gmail_backfill_done: false, gmail_newest_ms: null,calendar_sync_token: null, contacts_sync_token: null, last_full_at: null, ...state };const summary: GoogleSyncSummary = { status: 'synced', added: 0, modified: 0, deleted: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], threadsSeen: 0,- attachmentInspection: {}, extractEligibility: {}, failedFiles: 0 };+ attachmentInspection: {}, extractEligibility: {}, loopsWithheld: {}, failedFiles: 0 };const run = (people: PeopleClient, syncOpts: { full?: boolean } = {}) => {const deps = { managed, engine, sourceId: 'g', cfg: { dir: '/nonexistent/google', contactsDir: 'people', account: '[email protected]' },opts: { ...syncOpts, signal: controller.signal }, entry: { meta: {} }, log: (m: string) => log.push(m), tick: () => {}, exclusion: {}, extractCandidates: [], processedThreads: new Set() };diff --git a/test/e2e/loops-noise-5012-postgres.test.ts b/test/e2e/loops-noise-5012-postgres.test.tsnew file mode 100644index 0000000000..b28e7bf1d6--- /dev/null+++ b/test/e2e/loops-noise-5012-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../loops-noise-5012-store.test.ts'));diff --git a/test/google-clients.test.ts b/test/google-clients.test.tsindex 6a0527bdc5..0e9771287a 100644--- a/test/google-clients.test.ts+++ b/test/google-clients.test.ts@@ -699,6 +699,41 @@ describe('GmailClient', () => {expect(thread.messages.map((m) => m.autoSubmitted)).toEqual(cases.map(([, expected]) => expected));});+ test('#5012: getThread captures Precedence, List-Id and Reply-To; absent headers read as human mail', async () => {+ const headerSets: Array<Array<{ name: string; value: string }>> = [+ [{ name: 'Precedence', value: ' Bulk ' }],+ [{ name: 'list-id', value: 'Team updates <updates.example.com>' }],+ [{ name: 'Reply-To', value: 'Alerts <[email protected]>, [email protected]' }],+ [],+ ];+ const rawThread = {+ id: '17aa5555dddd0000',+ messages: headerSets.map((extra, i) => ({+ id: `18c2f4a9b3d21a${String(i).padStart(2, '0')}`,+ threadId: '17aa5555dddd0000',+ labelIds: [],+ internalDate: String(Date.parse('2026-08-10T09:00:00Z') + i * 60_000),+ payload: {+ mimeType: 'text/plain',+ headers: [+ { name: 'From', value: 'Sender <[email protected]>' },+ { name: 'To', value: '[email protected]' },+ { name: 'Subject', value: `Notice ${i}` },+ ...extra,+ ],+ body: { data: b64url('Your statement is ready.') },+ },+ })),+ };+ const h = makeHarness(() => json(rawThread));+ const thread = await new GmailClient(h.tokens, h.fetchImpl, () => {}, CLIENT_ID).getThread('17aa5555dddd0000', '[email protected]');+ const [bulk, list, replyTo, human] = thread.messages as unknown as Array<Record<string, unknown>>;+ expect(bulk.precedence).toBe('bulk');+ expect(list.listId).toBe(true);+ expect(replyTo.replyTo).toEqual(['[email protected]', '[email protected]']);+ expect([human.precedence, human.listId, human.replyTo]).toEqual(['', false, []]);+ });+test('getThread stamps calendarMethod from a real-shape text/calendar part; plain messages get null', async () => {const rawThread = {id: '17aa7777eeee8888',diff --git a/test/google-loop-detect.test.ts b/test/google-loop-detect.test.tsindex 2eb4968dcd..737cf4a7db 100644--- a/test/google-loop-detect.test.ts+++ b/test/google-loop-detect.test.ts@@ -52,6 +52,8 @@ interface MsgSpec {dateMs?: number;/** Extra Gmail label ids (categories) beside SENT/INBOX. */labels?: string[];+ /** #5012 automated-mail headers (fields a master mapper did not capture). */+ headers?: { precedence?: string; listId?: boolean; replyTo?: string[] };}function msg(spec: MsgSpec): GmailMessageMeta {@@ -73,6 +75,7 @@ function msg(spec: MsgSpec): GmailMessageMeta {labelIds: [spec.sent ? 'SENT' : 'INBOX', ...(spec.labels ?? [])],listUnsubscribe: spec.listUnsub ?? false,bodyText: spec.body ?? 'Can you review the plan?',+ ...(spec.headers ?? {}),};}@@ -925,3 +928,65 @@ describe('#5103: Google system senders and bulk categories in the deterministicexpect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);});});++describe('#5012 positively automated mail and the opt-in Updates reciprocity rule', () => {+ const alert = (headers: MsgSpec['headers'], labels: string[] = []) =>+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels, headers,+ subject: 'Your balance alert', body: 'Your available balance is below the threshold you set. Review it?' });++ const automatedHeaders: Array<[string, NonNullable<MsgSpec['headers']>]> = [+ ['Precedence: bulk', { precedence: 'bulk' }],+ ['Precedence: list', { precedence: 'list' }],+ ['Precedence: junk', { precedence: 'junk' }],+ ['a List-Id header', { listId: true }],+ ['a no-reply Reply-To', { replyTo: ['[email protected]'] }],+ ];+ for (const [name, headers] of automatedHeaders) {+ test(`a bank alert with ${name} opens no reply-owed loop and records why`, () => {+ const v = detectThreadLoop(thread([alert(headers)]), MY, NOW, sup());+ expect(v.open).toEqual([]);+ expect(v.held).toBeUndefined();+ expect(v.withheld).toEqual({ reason: 'automated_mail', counterpartyEmail: '[email protected]' });+ });+ }++ test('withholding never fabricates a close: my earlier outbound ask is still closed by their reply', () => {+ const v = detectThreadLoop(thread([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Can you raise my limit?' }),+ alert({ precedence: 'bulk' }),+ ]), MY, NOW, sup());+ expect(v.close).toEqual(['unanswered_outbound']);+ expect(v.open).toEqual([]);+ });++ test('a cold founder intro in Primary still opens a loop', () => {+ const v = detectThreadLoop(thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48,+ labels: ['CATEGORY_PERSONAL'], subject: 'Intro: seed round', body: 'Would you have 20 minutes next week to hear about what we are building?' })]), MY, NOW, sup());+ expect(v.open.map((o) => [o.loopType, o.counterpartyEmail])).toEqual([['unanswered_inbound', '[email protected]']]);+ expect(v.withheld).toBeUndefined();+ });++ const updatesIntro = () => thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48,+ labels: ['CATEGORY_UPDATES'], subject: 'Intro: seed round', body: 'Would you have 20 minutes next week?' })]);++ test('a cold founder intro in Updates opens a loop by default (the category alone never withholds)', () => {+ const v = detectThreadLoop(updatesIntro(), MY, NOW, sup());+ expect(v.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);+ });++ test('with the reciprocity rule on, Updates mail opens only for a sender the owner wrote to', () => {+ const off = detectThreadLoop(updatesIntro(), MY, NOW, sup(), { ownerWroteTo: new Set() });+ expect(off.open).toEqual([]);+ expect(off.withheld).toEqual({ reason: 'updates_without_reciprocity', counterpartyEmail: '[email protected]' });+ const known = detectThreadLoop(updatesIntro(), MY, NOW, sup(), { ownerWroteTo: new Set(['[email protected]']) });+ expect(known.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);+ });++ test('with the reciprocity rule on, an Updates thread the owner already wrote in still opens', () => {+ const v = detectThreadLoop(thread([+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, labels: ['CATEGORY_UPDATES'], body: 'Please resend the invoice.' }),+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, labels: ['CATEGORY_UPDATES'], body: 'Attached. Can you approve it?' }),+ ]), MY, NOW, sup(), { ownerWroteTo: new Set() });+ expect(v.open.map((o) => o.counterpartyEmail)).toEqual(['[email protected]']);+ });+});diff --git a/test/loops-cli.test.ts b/test/loops-cli.test.tsindex b0cdb1c0d5..88e5ba7776 100644--- a/test/loops-cli.test.ts+++ b/test/loops-cli.test.ts@@ -407,7 +407,9 @@ describe('runLoops', () => {test('mute sender writes the suppression row (lowercased) and prints the semantics', async () => {const r = await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]']));expect(r.out).toContain('Muted sender [email protected]');- expect(r.out).toContain("existing loops keep their state");+ // #5012: a mute now closes the sender's open reply-owed loops and prints the count and the undo.+ expect(r.out).toContain('closed 0 open reply-owed loop(s)');+ expect(r.out).toContain('Undo: gbrain loops unmute sender [email protected] --source default');expect(r.verdict).toBe(0);const set = await loadSuppressions(engine, 'default');expect(set.senders.has('[email protected]')).toBe(true);diff --git a/test/loops-noise-5012-store.test.ts b/test/loops-noise-5012-store.test.tsnew file mode 100644index 0000000000..a85a7eb858--- /dev/null+++ b/test/loops-noise-5012-store.test.ts@@ -0,0 +1,162 @@+/**+ * #5012 item 8: the store SQL behind mute/unmute, `loops drop sender`, the+ * one-shot withheld-sender backfill and the opt-in Updates reciprocity set,+ * on every test backend (PGLite always; Postgres when DATABASE_URL is set,+ * run by test/e2e/loops-noise-5012-postgres.test.ts).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ addSuppression,+ closeMutedLoops,+ listSenderInboundLoops,+ loadSuppressions,+ muteRecheckThreads,+ removeSuppression,+ requeueMutedLoops,+ settleMuteRecheck,+ upsertOpenLoop,+ type OpenLoopUpsert,+} from '../src/core/loops/loops-store.ts';+import { seedLoopRechecks } from '../src/core/google/loop-catchup.ts';+import { ownerWroteToFor, __clearReciprocityCacheForTests } from '../src/core/google/loops-reciprocity.ts';+import type { GoogleSourceState } from '../src/core/google/types.ts';+import { testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const engines: Array<{ backend: string; engine: BrainEngine; close: () => Promise<void> }> = [];+const ALERTS = '[email protected]';+const CAROL = '[email protected]';+const OLD = '2026-08-01T00:00:00Z';+const NEWER = '2026-08-20T00:00:00Z';++beforeAll(async () => {+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({ database_url: '' });+ await engine.initSchema();+ engines.push({ backend, engine, close: () => engine.disconnect() });+ } else {+ engines.push({ backend, ...(await isolatedPersistencePostgres(process.env.DATABASE_URL!)) });+ }+ }+}, 120_000);++afterAll(async () => {+ for (const e of engines) await e.close();+});++async function source(engine: BrainEngine, id: string): Promise<void> {+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{"kind":"google"}'::jsonb) ON CONFLICT (id) DO NOTHING`, [id]);+}++function loop(sourceId: string, threadId: string | null, over: Partial<OpenLoopUpsert> = {}): OpenLoopUpsert {+ return {+ sourceId,+ dedupKey: `thread:${threadId ?? 'none'}:${over.counterpartyEmail ?? ALERTS}:unanswered_inbound`,+ loopType: 'unanswered_inbound',+ counterpartyEmail: ALERTS,+ summary: 'Reply owed: "Balance alert"',+ evidence: [{ message_id: 'm1', quote: 'Your balance is low.' }],+ threadId,+ detector: 'deterministic_thread',+ lastActivityAt: OLD,+ ...over,+ };+}++async function row(engine: BrainEngine, id: number): Promise<{ status: string; closed_by: string | null }> {+ const rows = await engine.executeRaw<{ status: string; closed_by: string | null }>(`SELECT status, closed_by FROM open_loops WHERE id = $1`, [id]);+ return rows[0];+}++describe('#5012 loop noise store SQL on every backend', () => {+ test('mute closes, a sweep never reopens a muted loop, unmute re-queues, a re-check settles', async () => {+ for (const { backend, engine } of engines) {+ const src = 'g-mute';+ await source(engine, src);+ const a = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f01'));+ const noThread = await upsertOpenLoop(engine, loop(src, null));+ const other = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f02', { counterpartyEmail: CAROL }));++ await addSuppression(engine, src, 'sender', ALERTS);+ expect(await closeMutedLoops(engine, src, 'sender', ALERTS, false), backend).toEqual([a.id, noThread.id].sort((x, y) => x - y));+ expect((await row(engine, a.id)).status, backend).toBe('open');+ expect(await closeMutedLoops(engine, src, 'sender', ALERTS, true), backend).toEqual([a.id, noThread.id].sort((x, y) => x - y));+ expect(await row(engine, a.id), backend).toEqual({ status: 'dropped', closed_by: 'muted' });+ expect((await row(engine, other.id)).status, backend).toBe('open');++ const again = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f01', { lastActivityAt: NEWER }));+ expect(again.applied, backend).toBe(false);+ expect(await row(engine, a.id), backend).toEqual({ status: 'dropped', closed_by: 'muted' });++ expect(await removeSuppression(engine, src, 'sender', ALERTS), backend).toBe(1);+ expect(await requeueMutedLoops(engine, src, 'sender', ALERTS, false), backend).toEqual({ requeued: [a.id], unverifiable: [noThread.id] });+ expect(await requeueMutedLoops(engine, src, 'sender', ALERTS, true), backend).toEqual({ requeued: [a.id], unverifiable: [noThread.id] });+ expect(await row(engine, a.id), backend).toEqual({ status: 'dropped', closed_by: 'mute_recheck' });+ expect(await row(engine, noThread.id), backend).toEqual({ status: 'dropped', closed_by: 'unmuted' });+ expect(await muteRecheckThreads(engine, src), backend).toEqual([{ thread_id: '18c2f4a9b3d21f01', page_slug: null }]);+ expect([...((await loadSuppressions(engine, src)).recheckThreads ?? [])], backend).toEqual(['18c2f4a9b3d21f01']);++ const reopened = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f01'));+ expect(reopened.applied, backend).toBe(true);+ expect(await row(engine, a.id), backend).toEqual({ status: 'open', closed_by: null });++ await addSuppression(engine, src, 'sender', ALERTS);+ await closeMutedLoops(engine, src, 'sender', ALERTS, true);+ await removeSuppression(engine, src, 'sender', ALERTS);+ await requeueMutedLoops(engine, src, 'sender', ALERTS, true);+ expect(await settleMuteRecheck(engine, src, '18c2f4a9b3d21f01'), backend).toBe(1);+ expect(await row(engine, a.id), backend).toEqual({ status: 'dropped', closed_by: 'unmuted' });+ expect(await muteRecheckThreads(engine, src), backend).toEqual([]);+ }+ });++ test('unmute leaves a loop another suppression still covers', async () => {+ for (const { backend, engine } of engines) {+ const src = 'g-cover';+ await source(engine, src);+ const a = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f03'));+ await addSuppression(engine, src, 'sender', ALERTS);+ await addSuppression(engine, src, 'thread', '18c2f4a9b3d21f03');+ await closeMutedLoops(engine, src, 'sender', ALERTS, true);+ await removeSuppression(engine, src, 'sender', ALERTS);+ expect(await requeueMutedLoops(engine, src, 'sender', ALERTS, true), backend).toEqual({ requeued: [], unverifiable: [] });+ expect(await row(engine, a.id), backend).toEqual({ status: 'dropped', closed_by: 'muted' });+ }+ });++ test('drop sender lists only that sender, and the backfill picks each sender\'s newest thread', async () => {+ for (const { backend, engine } of engines) {+ const src = 'g-drop';+ await source(engine, src);+ const a = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f04'));+ const b = await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f05', { lastActivityAt: NEWER }));+ await upsertOpenLoop(engine, loop(src, '18c2f4a9b3d21f06', { counterpartyEmail: CAROL }));+ expect(await listSenderInboundLoops(engine, '[email protected]', [src]), backend)+ .toEqual([{ id: a.id, source_id: src }, { id: b.id, source_id: src }]);+ const state = {} as GoogleSourceState;+ expect(await seedLoopRechecks(engine, src, state, () => {}, Date.parse(NEWER)), backend).toBe(2);+ expect(Object.keys(state.loop_grace_holds ?? {}).sort(), backend).toEqual(['18c2f4a9b3d21f05', '18c2f4a9b3d21f06']);+ }+ });++ test('the Updates reciprocity set reads email page frontmatter', async () => {+ for (const { backend, engine } of engines) {+ const src = 'g-recip';+ await source(engine, src);+ await engine.putPage('email/2026/08/plan', { type: 'email', title: 'Plan', compiled_truth: 'x', timeline: '',+ frontmatter: { senders: ['[email protected]'], participants: ['[email protected]', '[email protected]'] } }, { sourceId: src });+ await engine.putPage('email/2026/08/news', { type: 'email', title: 'News', compiled_truth: 'x', timeline: '',+ frontmatter: { senders: ['[email protected]'], participants: ['[email protected]', '[email protected]'] } }, { sourceId: src });+ await engine.setConfig('loops.updates_require_reciprocity', 'true');+ __clearReciprocityCacheForTests(engine);+ expect([...(await ownerWroteToFor(engine, src, new Set(['[email protected]'])))!], backend).toEqual(['[email protected]']);+ await engine.setConfig('loops.updates_require_reciprocity', 'false');+ __clearReciprocityCacheForTests(engine);+ expect(await ownerWroteToFor(engine, src, new Set(['[email protected]'])), backend).toBeNull();+ }+ });+});diff --git a/test/loops-noise-5012.test.ts b/test/loops-noise-5012.test.tsnew file mode 100644index 0000000000..764e885c1c--- /dev/null+++ b/test/loops-noise-5012.test.ts@@ -0,0 +1,338 @@+/**+ * #5012 item 8: loop noise without hiding real people, on a real PGLite+ * engine (the store SQL is identical on Postgres; see+ * test/loops-noise-5012-store.test.ts and its Postgres run in+ * test/e2e/loops-noise-5012-postgres.test.ts).+ *+ * - positively automated mail (Precedence / List-Id / no-reply Reply-To)+ * opens no reply-owed loop through the apply step, and leaves a record;+ * - `loops mute` closes the sender's (or thread's) open reply-owed loops,+ * `unmute` queues them for re-check, and the re-check reopens only a+ * thread nothing answered since the mute;+ * - `loops drop sender` previews, then closes only that sender's loops;+ * - `gbrain waiting` reports the loops the rule would not have opened;+ * - the opt-in Updates reciprocity rule's owner-wrote-to set.+ *+ * Synthetic data only.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { applyThreadLoopVerdict, __clearSuppressionCacheForTests } from '../src/core/google/loop-detect.ts';+import * as loopsStore from '../src/core/loops/loops-store.ts';+import { listOpenLoops, upsertOpenLoop, type OpenLoopUpsert } from '../src/core/loops/loops-store.ts';+import * as catchup from '../src/core/google/loop-catchup.ts';+import { runLoops, runWaiting } from '../src/commands/loops.ts';+import { handleToolCall } from '../src/mcp/server.ts';+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';+import type { GmailMessageMeta, GmailThreadData, GoogleSourceState } from '../src/core/google/types.ts';++let engine: PGLiteEngine;+let stateDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ stateDir = mkdtempSync(join(tmpdir(), 'gbrain-5012-'));+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(stateDir, { recursive: true, force: true });+});++beforeEach(async () => {+ await resetPgliteState(engine);+ __clearSuppressionCacheForTests();+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config, last_sync_at) VALUES ('g1', 'g1', $1::text::jsonb, now())+ ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config, last_sync_at = now()`,+ [JSON.stringify({ kind: 'google', g_account: '[email protected]', g_dir: stateDir })],+ );+ writeFileSync(join(stateDir, '.google-source.json'), '{}');+ _resetCliExitVerdictForTests();+});++const NOW = new Date('2026-08-25T12:00:00Z');+const MY = new Set(['[email protected]']);+let seq = 0;++function msg(spec: { from: string; to?: string[]; ageHours: number; sent?: boolean; body?: string; threadId?: string;+ headers?: { precedence?: string; listId?: boolean; replyTo?: string[] } }): GmailMessageMeta {+ const internalDateMs = NOW.getTime() - spec.ageHours * 3_600_000;+ seq += 1;+ return {+ id: `18c2f4a9b3d3${(0x3000 + seq).toString(16)}`,+ threadId: spec.threadId ?? '18c2f4a9b3d21e07',+ from: spec.from,+ fromAddress: spec.from.toLowerCase(),+ to: (spec.to ?? []).map((a) => a.toLowerCase()),+ cc: [],+ subject: 'Balance alert',+ dateIso: new Date(internalDateMs).toISOString(),+ internalDateMs,+ labelIds: spec.sent ? ['SENT'] : ['INBOX'],+ listUnsubscribe: false,+ bodyText: spec.body ?? 'Can you review this?',+ ...(spec.headers ?? {}),+ } as GmailMessageMeta;+}++function thread(messages: GmailMessageMeta[], threadId = '18c2f4a9b3d21e07'): GmailThreadData {+ return { threadId, account: '[email protected]', messages };+}++function loop(over: Partial<OpenLoopUpsert> = {}): OpenLoopUpsert {+ const threadId = over.threadId ?? '18c2f4a9b3d21e07';+ return {+ sourceId: 'g1',+ dedupKey: `thread:${threadId}:${over.loopType ?? 'unanswered_inbound'}`,+ loopType: 'unanswered_inbound',+ counterpartyEmail: '[email protected]',+ summary: 'Reply owed to [email protected]: "Balance alert"',+ evidence: [{ message_id: 'm1', quote: 'Your balance is low.' }],+ threadId,+ detector: 'deterministic_thread',+ lastActivityAt: new Date(NOW.getTime() - 48 * 3_600_000).toISOString(),+ ...over,+ };+}++async function captured(fn: () => Promise<void>): Promise<{ out: string; err: string; verdict: number; exitCalled?: number }> {+ const outOrig = process.stdout.write.bind(process.stdout);+ const errOrig = process.stderr.write.bind(process.stderr);+ const cerrOrig = console.error;+ const exitOrig = process.exit;+ const out: string[] = [];+ const err: string[] = [];+ let exitCalled: number | undefined;+ _resetCliExitVerdictForTests();+ process.stdout.write = ((c: string | Uint8Array) => { out.push(String(c)); return true; }) as typeof process.stdout.write;+ process.stderr.write = ((c: string | Uint8Array) => { err.push(String(c)); return true; }) as typeof process.stderr.write;+ console.error = (...a: unknown[]) => { err.push(a.map(String).join(' ') + '\n'); };+ process.exit = ((code?: number) => { exitCalled = code ?? 0; throw new Error('__exit__'); }) as typeof process.exit;+ try {+ await fn();+ } catch (e) {+ if ((e as Error).message !== '__exit__') throw e;+ } finally {+ process.exit = exitOrig;+ console.error = cerrOrig;+ process.stdout.write = outOrig;+ process.stderr.write = errOrig;+ }+ const verdict = currentExitCode();+ _resetCliExitVerdictForTests();+ process.exitCode = 0;+ return { out: out.join(''), err: err.join(''), verdict, ...(exitCalled !== undefined ? { exitCalled } : {}) };+}++async function row(id: number): Promise<{ status: string; closed_by: string | null }> {+ const [r] = await engine.executeRaw<{ status: string; closed_by: string | null }>('SELECT status, closed_by FROM open_loops WHERE id = $1', [id]);+ return r!;+}++describe('automated mail opens no reply-owed loop (forced probe)', () => {+ test('a Precedence: bulk bank alert to me opens nothing; the same alert without the header opens a loop', async () => {+ const alert = (headers?: { precedence?: string }) =>+ thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48, headers })]);+ const v = await applyThreadLoopVerdict(engine, 'g1', alert({ precedence: 'bulk' }), MY, null, NOW);+ expect(await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' })).toHaveLength(0);+ expect((v as { withheld?: unknown }).withheld).toEqual({ reason: 'automated_mail', counterpartyEmail: '[email protected]' });+ await applyThreadLoopVerdict(engine, 'g1', alert(), MY, null, NOW);+ expect(await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' })).toHaveLength(1);+ });++ test('a List-Id or a no-reply Reply-To withholds the loop too', async () => {+ await applyThreadLoopVerdict(engine, 'g1', thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48,+ headers: { listId: true } })], '18c2f4a9b3d21e08'), MY, null, NOW);+ await applyThreadLoopVerdict(engine, 'g1', thread([msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 48,+ headers: { replyTo: ['[email protected]'] } })], '18c2f4a9b3d21e09'), MY, null, NOW);+ expect(await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' })).toHaveLength(0);+ });++ test('the sweep record keeps the withheld sender until a later thread of theirs opens a loop', () => {+ const state = {} as GoogleSourceState;+ const record = (catchup as unknown as { recordWithheldVerdict: (s: GoogleSourceState, v: unknown, n: number) => void }).recordWithheldVerdict;+ record(state, { open: [], close: [], withheld: { reason: 'automated_mail', counterpartyEmail: '[email protected]' } }, 1);+ record(state, { open: [], close: [], withheld: { reason: 'automated_mail', counterpartyEmail: '[email protected]' } }, 2);+ expect(state.loop_withheld_senders).toEqual({ '[email protected]': { reason: 'automated_mail', count: 2, last_ms: 2 } });+ record(state, { open: [{ loopType: 'unanswered_inbound', counterpartyEmail: '[email protected]' }], close: [] }, 3);+ expect(state.loop_withheld_senders).toEqual({});+ });+});++describe('mute closes, unmute re-checks', () => {+ test('mute sender closes that sender\'s open reply-owed loops (muted) and prints the count and the undo', async () => {+ const a = await upsertOpenLoop(engine, loop());+ const b = await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e0a' }));+ const other = await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e0b', counterpartyEmail: '[email protected]' }));+ const commitment = await upsertOpenLoop(engine, loop({ dedupKey: 'commit:aaaa1111', loopType: 'commitment_owed_by_me', detector: 'llm_extract' }));+ const preview = await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]', '--dry-run', '--json']));+ expect(JSON.parse(preview.out)).toMatchObject({ status: 'dry_run', would_close: [a.id, b.id], count: 2 });+ expect((await row(a.id)).status).toBe('open');++ const r = await captured(() => runLoops(engine, ['mute', 'sender', '[email protected]']));+ expect(r.out).toContain(`closed 2 open reply-owed loop(s): ${a.id}, ${b.id}`);+ expect(r.out).toContain('Undo: gbrain loops unmute sender [email protected] --source g1');+ expect(await row(a.id)).toEqual({ status: 'dropped', closed_by: 'muted' });+ expect(await row(b.id)).toEqual({ status: 'dropped', closed_by: 'muted' });+ expect((await row(other.id)).status).toBe('open');+ expect((await row(commitment.id)).status).toBe('open');+ });++ test('mute thread closes that thread\'s reply-owed loop; the MCP result lists it', async () => {+ const a = await upsertOpenLoop(engine, loop());+ const res = await handleToolCall(engine, 'loops_mute', { kind: 'thread', value: '18C2F4A9B3D21E07', source_id: 'g1' }) as Record<string, unknown>;+ expect(res).toMatchObject({ muted: true, closed: [a.id], count: 1, undo_command: 'gbrain loops unmute thread 18c2f4a9b3d21e07 --source g1' });+ });++ test('a sweep never reopens a muted loop for the same counterparty, even on newer activity', async () => {+ const a = await upsertOpenLoop(engine, loop());+ await handleToolCall(engine, 'loops_mute', { kind: 'sender', value: '[email protected]', source_id: 'g1' });+ const again = await upsertOpenLoop(engine, loop({ lastActivityAt: NOW.toISOString() }));+ expect(again.applied).toBe(false);+ expect(await row(a.id)).toEqual({ status: 'dropped', closed_by: 'muted' });+ // A different person writing later in the thread is not hidden by this sender's mute.+ const other = await upsertOpenLoop(engine, loop({ counterpartyEmail: '[email protected]', lastActivityAt: NOW.toISOString() }));+ expect(other.applied).toBe(true);+ });++ test('unmute queues the closed loops; the re-check reopens an unanswered thread and never one answered during the mute', async () => {+ const quiet = '18c2f4a9b3d21e0c';+ const answered = '18c2f4a9b3d21e0d';+ const owed = (tid: string) => msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 72, threadId: tid,+ body: 'Could we find 20 minutes next week?' });+ const q0 = owed(quiet);+ const a0 = owed(answered);+ await applyThreadLoopVerdict(engine, 'g1', thread([q0], quiet), MY, null, NOW);+ await applyThreadLoopVerdict(engine, 'g1', thread([a0], answered), MY, null, NOW);+ const [qLoop, aLoop] = await Promise.all([quiet, answered].map(async (tid) =>+ (await listOpenLoops(engine, { sourceIds: ['g1'], status: 'open' })).find((l) => l.thread_id === tid)!));+ await handleToolCall(engine, 'loops_mute', { kind: 'sender', value: '[email protected]', source_id: 'g1' });++ const dry = await handleToolCall(engine, 'loops_unmute', { kind: 'sender', value: '[email protected]', source_id: 'g1', dry_run: true }) as Record<string, unknown>;+ expect(dry).toMatchObject({ dry_run: true, would_requeue: [qLoop.id, aLoop.id].sort((x, y) => x - y) });+ expect((await row(qLoop.id)).closed_by).toBe('muted');++ const r = await captured(() => runLoops(engine, ['unmute', 'sender', '[email protected]']));+ expect(r.out).toContain('Queued 2 loop(s) the mute closed for re-check on the next sync');+ expect(r.out).toContain('Undo: gbrain loops mute sender [email protected] --source g1');+ expect((await row(qLoop.id)).closed_by).toBe('mute_recheck');++ // The next sweep queues both threads through the grace-hold re-fetch.+ const state = {} as GoogleSourceState;+ await catchup.seedLoopRechecks(engine, 'g1', state, () => {}, NOW.getTime());+ expect(Object.keys(state.loop_grace_holds ?? {}).sort()).toEqual([quiet, answered].sort());++ // Re-fetched: the quiet thread is unchanged, the other was answered while muted.+ __clearSuppressionCacheForTests();+ await applyThreadLoopVerdict(engine, 'g1', thread([q0], quiet), MY, null, NOW);+ await applyThreadLoopVerdict(engine, 'g1', thread([a0, msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10,+ sent: true, threadId: answered, body: 'Tuesday works, invite sent.' })], answered), MY, null, NOW);+ expect(await row(qLoop.id)).toEqual({ status: 'open', closed_by: null });+ expect(await row(aLoop.id)).toEqual({ status: 'done', closed_by: 'reply_detected' });+ });++ test('unmute never touches a manual disposition, and leaves a loop another mute still covers', async () => {+ const manual = await upsertOpenLoop(engine, loop());+ const covered = await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e0e' }));+ await loopsStore.closeOpenLoop(engine, 'g1', manual.id, 'dropped', 'manual');+ await handleToolCall(engine, 'loops_mute', { kind: 'sender', value: '[email protected]', source_id: 'g1' });+ await handleToolCall(engine, 'loops_mute', { kind: 'thread', value: '18c2f4a9b3d21e0e', source_id: 'g1' });+ const res = await handleToolCall(engine, 'loops_unmute', { kind: 'sender', value: '[email protected]', source_id: 'g1' }) as Record<string, unknown>;+ expect(res).toMatchObject({ removed: true, requeued: [], unverifiable: [] });+ expect(await row(manual.id)).toEqual({ status: 'dropped', closed_by: 'manual' });+ expect(await row(covered.id)).toEqual({ status: 'dropped', closed_by: 'muted' });+ });++ test('unmute reports a stale source with the sync that runs the re-check', async () => {+ await upsertOpenLoop(engine, loop());+ await handleToolCall(engine, 'loops_mute', { kind: 'sender', value: '[email protected]', source_id: 'g1' });+ await engine.executeRaw(`UPDATE sources SET last_sync_at = now() - interval '3 days' WHERE id = 'g1'`);+ const res = await handleToolCall(engine, 'loops_unmute', { kind: 'sender', value: '[email protected]', source_id: 'g1' }) as Record<string, unknown>;+ expect(res).toMatchObject({ stale_source: true, recheck_command: 'gbrain sync --source g1' });+ });+});++describe('loops drop sender', () => {+ test('--dry-run lists ids and count and changes nothing; the apply closes only that sender\'s reply-owed loops', async () => {+ const a = await upsertOpenLoop(engine, loop());+ const b = await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e0f' }));+ const other = await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e10', counterpartyEmail: '[email protected]' }));+ const outbound = await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e11', loopType: 'unanswered_outbound' }));++ const dry = await captured(() => runLoops(engine, ['drop', 'sender', '[email protected]', '--dry-run', '--json']));+ expect(JSON.parse(dry.out)).toMatchObject({ ok: true, status: 'dry_run', would_close: [a.id, b.id], count: 2,+ apply_command: 'gbrain loops drop sender [email protected]' });+ expect((await row(a.id)).status).toBe('open');+ const human = await captured(() => runLoops(engine, ['drop', 'sender', '[email protected]', '--dry-run']));+ expect(human.out).toContain('would be dropped');+ expect(human.out).toContain('cannot be undone');++ const r = await captured(() => runLoops(engine, ['drop', 'sender', '[email protected]', '--source', 'g1', '--json']));+ expect(JSON.parse(r.out)).toMatchObject({ ok: true, status: 'dropped', closed: [a.id, b.id], failed: [], count: 2 });+ expect(await row(a.id)).toEqual({ status: 'dropped', closed_by: 'drop sender [email protected]' });+ expect((await row(other.id)).status).toBe('open');+ expect((await row(outbound.id)).status).toBe('open');+ expect(r.verdict).toBe(0);+ });++ test('drop sender without an email is a usage error', async () => {+ const r = await captured(() => runLoops(engine, ['drop', 'sender']));+ expect(r.exitCalled).toBe(2);+ });+});++describe('gbrain waiting reports the loops the rule would not have opened', () => {+ test('counts open reply-owed loops from recorded senders and prints the exact dry-run command', async () => {+ await upsertOpenLoop(engine, loop());+ await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e12' }));+ await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e13', counterpartyEmail: '[email protected]' }));+ writeFileSync(join(stateDir, '.google-source.json'), JSON.stringify({+ loop_withheld_senders: { '[email protected]': { reason: 'automated_mail', count: 1, last_ms: 1 } } }));+ const r = await captured(() => runWaiting(engine, []));+ expect(r.out).toContain('2 open reply-owed loop(s) come from 1 sender(s) whose mail is automated');+ expect(r.out).toContain('gbrain loops drop sender [email protected] --source g1 --dry-run');+ const j = await captured(() => runWaiting(engine, ['--json']));+ expect(JSON.parse(j.out).withheld_noise).toMatchObject({ loop_count: 2, sender_count: 1,+ senders: [{ email: '[email protected]', source_id: 'g1', open_loops: 2 }] });+ });++ test('the one-shot sender backfill queues the newest thread of each sender with open reply-owed loops', async () => {+ await upsertOpenLoop(engine, loop({ lastActivityAt: '2026-08-01T00:00:00Z' }));+ await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e14', lastActivityAt: '2026-08-02T00:00:00Z' }));+ await upsertOpenLoop(engine, loop({ threadId: '18c2f4a9b3d21e15', counterpartyEmail: '[email protected]' }));+ const state = {} as GoogleSourceState;+ expect(await catchup.seedLoopRechecks(engine, 'g1', state, () => {}, NOW.getTime())).toBe(2);+ expect(Object.keys(state.loop_grace_holds ?? {}).sort()).toEqual(['18c2f4a9b3d21e14', '18c2f4a9b3d21e15']);+ expect(state.loop_automated_backfill_done).toBe(true);+ expect(await catchup.seedLoopRechecks(engine, 'g1', { loop_automated_backfill_done: true } as GoogleSourceState, () => {}, NOW.getTime())).toBe(0);+ });+});++describe('opt-in Updates reciprocity', () => {+ test('off by default (null); on, the set holds the people the owner wrote to', async () => {+ const r = (await import('../src/core/google/loops-reciprocity.ts')) as unknown as {+ ownerWroteToFor: (e: PGLiteEngine, s: string, my: Set<string>) => Promise<Set<string> | null>;+ validateLoopsReciprocityConfigValue: (k: string, v: string) => string | null;+ __clearReciprocityCacheForTests: (e: PGLiteEngine) => void;+ };+ r.__clearReciprocityCacheForTests(engine);+ expect(await r.ownerWroteToFor(engine, 'g1', MY)).toBeNull();+ await engine.putPage('email/2026/08/plan', { type: 'email', title: 'Plan', compiled_truth: 'x', timeline: '',+ frontmatter: { senders: ['[email protected]', '[email protected]'], participants: ['[email protected]', '[email protected]', '[email protected]'] } }, { sourceId: 'g1' });+ await engine.putPage('email/2026/08/news', { type: 'email', title: 'News', compiled_truth: 'x', timeline: '',+ frontmatter: { senders: ['[email protected]'], participants: ['[email protected]', '[email protected]'] } }, { sourceId: 'g1' });+ await engine.setConfig('loops.updates_require_reciprocity', 'true');+ r.__clearReciprocityCacheForTests(engine);+ expect([...(await r.ownerWroteToFor(engine, 'g1', MY))!].sort()).toEqual(['[email protected]', '[email protected]']);+ expect(r.validateLoopsReciprocityConfigValue('loops.updates_require_reciprocity', 'maybe')).toContain('must be true or false');+ expect(r.validateLoopsReciprocityConfigValue('loops.updates_require_reciprocity', 'false')).toBeNull();+ });+});