Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
recall: opt-in confidence weighting (trust floor + decay) and no-entity grouping for question recall
garrytan90c72a63d6d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76800a8a01..4c4b17c254 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,24 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased]++**`recall` can weigh how much a fact deserves to be believed, and can group a no-entity question's facts by entity. Both are opt-in.**++### What changed++| Situation | Before | With the switch on |+|---|---|---|+| `recall {question}`: a year-old fact you confirmed and a fresh agent-written or external fact match equally | the newest fact ranked first | the confirmed fact ranks first (`recall.confidence_weighting on`) |+| The same, between two agent-written facts | newest first | newest first (age still decays) |+| A dated historical fact ("founded in 2015") | ranked by match | ranked by match; it does not decay |+| `recall {question}` with no `entity` answered by two clients' facts | one flat list, the clients' figures interleaved | each entity's facts together, `facts_groups`, and an `entity_unspecified` notice offering the recall per entity (`recall.group_by_entity on`) |+| `gbrain config set recall.question_admission <typo>` | stored and silently ignored | refused; the new switches take only `on` or `off` |++Weighting is `relevance × (0.5 + 0.5 × weight)`: facts you confirmed and your own notes keep full weight at any age, other tiers decay from `valid_from` and carry a tier weight (tool 0.9, agent 0.8, external 0.6). It only reorders facts that already matched; `relevance` stays the plain score and `rank_score` and `confidence_factor` show the weighting. Grouping runs after the limit and budget cuts, so no entity is cut off by it. Both read database rows only, so they work the same on brains with no git repository.++On a keyless 60-question fixture (old confirmed truth against fresh agent and external text, an agent knowledge update, dated history), weighting moved the confirmed truth to first in 20 of 20 questions, from 0 of 20, and left the update and history cases at 20 of 20. Grouping removed entity interleaving in 10 of 10 two-client questions with the same number of entities delivered.+## [0.60.474.0] - 2026-10-27**A database role that can't read the writer state is now refused instead of let through.**diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex 69a1ff129d..92d88fce80 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -69,8 +69,8 @@ link it here rather than raising the cap.| [Evaluation](key-files/evaluation.md) | `evals/brainbench/` through `src/eval/shared/judge-runner.ts` || [Files And Sync (1/2)](key-files/files-and-sync-1.md) | `src/core/audit-week-file.ts` through `src/core/sync-embed-backfill.ts` || [Files And Sync (2/2)](key-files/files-and-sync-2.md) | `src/core/sync-failure-ledger.ts` through `src/core/write-through.ts` |-| [Graph And Facts](key-files/graph-and-facts.md) | `src/core/check-resolvable.ts` through `src/core/trajectory-format.ts` |-| [Entity recall](key-files/entity-recall.md) | `src/core/mentions/*`, `src/core/ops/backlinks-paged.ts`, `extract mentions --explain`, migration v206 |+| [Graph And Facts](key-files/graph-and-facts.md) | `check-resolvable.ts` to `trajectory-format.ts`; [recall](key-files/recall.md) |+| [Entity recall](key-files/entity-recall.md) | `mentions/*`, `ops/backlinks-paged.ts`, `extract mentions --explain`, migration v206 || [Mcp](key-files/mcp.md) | `src/mcp/dispatch.ts` through `src/mcp/validate-params.ts` || [Providers](key-files/providers.md) | `src/core/anthropic-pricing.ts` through `src/core/transcription.ts` || [Runtime](key-files/runtime.md) | `src/core/abort-check.ts` through `src/core/zombie-reap.ts` |diff --git a/docs/architecture/key-files/recall.md b/docs/architecture/key-files/recall.mdnew file mode 100644index 0000000000..210f4cfaab--- /dev/null+++ b/docs/architecture/key-files/recall.md@@ -0,0 +1,38 @@+# Key files: Recall ranking++[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.++recall's `question` ranking itself (pool, score, admission) is the+`src/core/facts/question-recall.ts` entry in [Graph And Facts](graph-and-facts.md).+This page covers the two switches layered on it (#2941, #2953).++## Confidence weighting and entity grouping++With `recall.confidence_weighting` on, `rankFactsByQuestion` multiplies each+admitted fact's relevance by `confidenceFactor(recallConfidence(...))` after+admission (admission still reads raw relevance, so the admitted set never+changes), orders by that rank score, newest `valid_from`, id, and only then+collapses copies (#7043) and cuts to `limit`; `weightedRepresentative`+delivers a collapsed group's best-ranked copy, not its newest. The response+keeps `relevance` raw and adds `rank_score` and `confidence_factor` per fact+(`src/core/ops/facts.ts`).++With `recall.group_by_entity` on and no `entity`, `groupFactsByEntity` runs+in the recall op after the limit and budget cuts, so it only reorders the+delivered facts: groups keyed by (source_id, entity_slug), ordered by their+best fact, a null-entity group for unscoped facts, `facts_groups`+[{source_id, entity_slug, fact_ids, top_relevance}], and, when two or more+entities answer, `entity_unspecified` {candidates, suggestion} plus the+`entity_unspecified` info notice whose decision offers one recall per entity+(at most 5). Grouping reads delivered rows only, so a remote caller never+learns of a hidden entity. Both switches work the same on repo-less brains:+they read database rows only.++Tests: `test/recall-confidence-grouping.test.ts` (both engines; Postgres+through `test/e2e/recall-confidence-grouping-postgres.test.ts`).++## Files++- `src/core/facts/recall-config.ts` — recall's config keys: `recall.confidence_weighting` and `recall.group_by_entity` (`on` | `off`, default off; unset, unreadable or unknown stored values read as off) and `recall.question_admission` (`reserve` | `facts_arm`). `recallConfigValueRefusal` is what `gbrain config set` (commands/config.ts) calls for every `recall.*` key, so a typo is refused instead of stored.+- `src/core/facts/decay.ts` — `effectiveConfidence` (confidence × exp(-age/half-life) from `valid_from`; the hot-memory injector and recall's CLI JSON `effective_confidence`) and `recallConfidence(fact, dated, now)`, the weighting's belief weight: trust is a floor (`TRUST_RECALL_FLOOR`: `user_confirmed` and `operator_curated` weigh 1 at any age), every other tier decays by `effectiveConfidence` times `TRUST_RECALL_WEIGHT` (tool 0.9, agent and unknown 0.8, external 0.6). A writer-dated `fact` row does not decay; expired or lapsed rows weigh 0. `confidenceFactor(w) = 0.5 + 0.5w`, so weighting at most halves a score.diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.mdindex 4e7296b2e4..a581a62542 100644--- a/docs/guides/entity-recall.md+++ b/docs/guides/entity-recall.md@@ -183,6 +183,22 @@ is fixed by running `gbrain extract --stale`. Given a slugthe page derives with its origin and declaring line, each rejected candidatewith its reason, and the identity-sibling decision.+## Questions that name no entity++`recall` with a `question` and no `entity` ranks facts across every entity, so+two clients' figures can come back side by side. To have them grouped:++```bash+gbrain config set recall.group_by_entity on+```++Each entity's facts then sit together, facts saved with no entity form their+own group, and `facts_groups` lists the groups. When facts from two or more+entities answer, `entity_unspecified` names them and the `entity_unspecified`+notice offers the same recall with `entity` set for each, so the agent can+ask which one was meant. A call that passes `entity` is never grouped. Off by+default.+## Settings| Key | Default | Effect |diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.mdindex 35e985e318..d66b348faf 100644--- a/docs/guides/memory-trust.md+++ b/docs/guides/memory-trust.md@@ -79,6 +79,30 @@ and `get_page`, labeled, but hook context, the context engine,outright. `gbrain trust disable --all` turns every protection off; labelsstay.+## How recall weighs old and low-trust facts (opt-in)++`recall` with a `question` ranks saved facts by how well they match. Turn on+confidence weighting and the match is also weighed by how much each fact+deserves to be believed now:++```bash+gbrain config set recall.confidence_weighting on+```++- Facts you confirmed, and facts from your own notes, keep full weight at any+ age.+- Other facts lose weight as they age (an event after about a week, a+ preference or commitment after about three months, other facts after about+ a year) and by tier: tool data a little, agent-written and unverified facts+ more, external text the most.+- A fact the writer dated ("founded in 2010") is history and keeps its weight.+- Weighting at most halves a fact's score. It reorders the facts that match+ and never hides one; `relevance` stays the plain match score, and+ `rank_score` and `confidence_factor` show the weighting.++It works the same on a brain with no git repository. `gbrain config set+recall.confidence_weighting off` turns it off.+## Older memoryContent saved before this release is flagged only after you claim yourdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex bfa01bceb3..fadf4a70ba 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 2012 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured)+src/core/config.ts 2013 ratchet +2 W5: search.page_rank_cut / page_rank_cut_factor KNOWN_CONFIG_KEYS rows (read in search/page-rank-cut.ts); +3 W3 confidence-gated reranking: search.reranker.gate / gate_min_gap KNOWN_CONFIG_KEYS rows (values parsed in search/crag.ts); re-summed at the W3 merge onto master v0.60.169.0 (1951 measured); +1 budgeted delivery PR 1: the search.auto_packing KNOWN_CONFIG_KEYS row (values validated in search/evidence-packing.ts); +1 #6278: persistence.sync_preparation_ms/maintenance_preparation_ms/preparation_ceiling_ms/max_preparation_attempts/preparation_deadlines key row (logic in persistence/preparation-budget.ts, switches.ts); +22 fix wave 11 W6.2/W6.3 (#5989, #6132): search.cjk_keyword_deadline_ms and search.hnsw_iterative_scan type fields, KNOWN_CONFIG_KEYS rows and the mergeSearchScanKnobs helper that keeps loadConfigWithEngine under its function-size baseline (logic in search/cjk-keyword-deadline.ts, search/hnsw-iterative-scan.ts); +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 fix wave 10 lane L1 #4907: cycle.synthesize_concepts.budget_usd registered (validation in cycle/phase-config-values.ts); +2 #5958: dream.propose_takes.call_timeout_ms registered; 3 core memory: memory.core.* and memory.pressure.* known keys; +15 P5: wanted_pages.enabled/remote, line_grammar.enabled/allow_undeclared_types/effective_ranges and put_page.similar_pages key rows (logic in wanted-links.ts, line-grammar.ts, similar-pages.ts); +1 P2 extraction.date_grounding / facts.attribution keys; +1 #6188: fences.normalize registered in KNOWN_CONFIG_KEYS; +2 #6188: fences.repair.max_usd_per_page/per_day key rows; +1 fix wave 12 W2.3 #6231: facts.page_write_notability_filter key row (resolver in facts/notability-filter.ts); +1 #6317: persistence.single_consumer key row (logic in persistence/switches.ts, consumer-election.ts); +2 newer mentions on context_pack cards: mentions.newer_on_cards key row (logic in mentions/newer-mentions.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +1 #5329 (W14 PR3): chronicle.max_events_per_page registered in KNOWN_CONFIG_KEYS (validation in chronicle/config.ts); +2 C1/C2 memory proof wave: search.evidence_date_header + facts.candidate_fusion registry rows; +1 facts.supersession_thresholds registry row (per-model supersession calibration); +1 C4: models.standing_questions key row; +1 search.entity_anchoring key registration (default off; search/entity-anchor.ts); +1 search.query_facts_arm key registration (default off; search/facts-arm.ts); re-summed at the master 6ccf30c3e merge (1871 integration + 1868 master - 1865 base); +1 search.temporal_fact_reserve key registration (default off; search/facts-arm.ts); +1 fix wave 13 PR2: persistence.publication_ceiling_ms (P2.1/P2.3); v0.60.165.0 merge: W14 PR4 +7 and master +2 compose (1947 measured); +1 memory proof wave 2 W1: the recall.question_admission KNOWN_CONFIG_KEYS row (values validated in facts/question-recall.ts); +2 Cat 40 Hard fix wave (#6271) on top: mentions.alias_deny/multiword_aliases/sibling_merge and search.alias_fanout_max/demote_generated KNOWN_CONFIG_KEYS rows (1950 measured); +1 wave 15 P7.1 #5213: cycle.propose_takes.types KNOWN_CONFIG_KEYS row (parse + filter live in cycle/propose-takes.ts); +1 wave 15 P7.2 #6451: autopilot.git_pull KNOWN_CONFIG_KEYS row (read in persistence/automatic-sync-policy.ts); +1 wave 15 P7.3 #6369: cycle.lint.enabled KNOWN_CONFIG_KEYS row (read in cycle/lint-fix-setting.ts); +2 wave 15 P7.4 #5461: think.pages_budget_chars / think.excerpt_ceiling_chars KNOWN_CONFIG_KEYS rows (validation in think/pages-budget.ts); +6 wave 16 G5.1 (#6495): search.keyword_statement_timeout_ms type field, DB merge and KNOWN_CONFIG_KEYS row, toEngineConfig carries it (range + resolver live in postgres-engine/keyword-statement-timeout.ts); +1 GBRA-81 item 1: search.mode_source registered; +1 GBRA-60 S1: search.diverse_pool_depth in the known search keys; +3 #6643: sync.knock_on_refreeze_limit / sync.knock_on_run_limit KNOWN_CONFIG_KEYS rows (read by persistence/sync-run.ts knockOnLimits); +3 #6696: KNOWN_CONFIG_KEYS rows for persistence.maintenance.compaction_stale_hours and refusal_breaker_threshold; +1 wave 5 D5: context.proactive_brief KNOWN_CONFIG_KEYS row (read in context/proactive-brief.ts); +3 Cat 40 next wave part 1: KNOWN_CONFIG_KEYS rows for entity.names_references + entity.record_types + entity.row_page_status (one line), mcp.instructions_governing_rule and search.long_page_unit (re-summed at the 0.60.242.0 merge: master 1975 + 3); +1 wave 17 (#6667): cycle.consolidate.enabled KNOWN_CONFIG_KEYS row (read in cycle/phases/consolidate.ts); +2 Wave B PR 1: pages.segmented_storage and the segmented ceiling/retention keys (page-body/limits.ts); merge v0.60.249.0: Wave B PR 1 and master growth compose at 1981; +1 #6297: dream.patterns.min_interval_hours / child_read_budget_kb known keys; +1 #5012: loops.updates_require_reciprocity known key; +1 wave 18b lane 2 (#6495): search.keyword_timeout_negative_cache_seconds KNOWN_CONFIG_KEYS row; integrated at wave 18b: master 1981 + 4 (lanes 2, 3, 5 known keys); +1 #6948: sync.origin_twins.auto_resolve KNOWN_CONFIG_KEYS row (read in repair/origin-twins-heal.ts); +1 #6948 sweep C-9: facts.absorb_retry.max_resubmits KNOWN_CONFIG_KEYS row (read in facts/dead-absorb-retry.ts); +1 #6907: backup.remote_timeout_ms KNOWN_CONFIG_KEYS row (resolver in backup/repository.ts); +1 at the #6712 PR 4b merge onto master v0.60.310.0 (both sides added a key); +3 #7130: sync.max_deletes / sync.max_delete_ratio / purge.retention_hours KNOWN_CONFIG_KEYS rows and the two per-source cap prefixes (parsers live in core/sync-reconcile.ts); +2 GBRA-154: search.collapse / search.rank_priors KNOWN_CONFIG_KEYS rows (read in search/mode.ts); +1 GBRA-150: sync.metafile_pages KNOWN_CONFIG_KEYS row (read in core/sync.ts); +1 GBRA-159: visibility.honor_aliases KNOWN_CONFIG_KEYS row (read in search/private-visibility.ts); +4 GBRA-156 warm CLI socket: GBrainConfig.serve_cli_socket slot and the published-config.ts import/re-export (snapshot-only merge and MERGED_CONFIG_BY_ENGINE live in core/published-config.ts); re-summed at the GBRA-159 hotfix merge (2000 measured); +2 #7242 GBrainConfig.minions.terminal_hook (interface field); #7252 merge of master v0.60.343.0: both sides grew the file, re-summed (2002 measured); +1 GBRA-155: entity.name_variants KNOWN_CONFIG_KEYS row (read in verbs/entity-variants.ts); +2 GBRA-161: the generations.* KNOWN_CONFIG_KEYS rows and their comment (bounds and reader in generations/config.ts); +1 GBRA-156: search.evidence_tail_trim KNOWN_CONFIG_KEYS row (read in search/evidence-tail-trim.ts); +2 GBRA-175: self_upgrade.channel (the GBrainConfig field and its KNOWN_CONFIG_KEYS row; resolved in core/self-upgrade.ts); re-summed at the master 440eeef6 merge (2009 measured); +2 GBRA-156 vector prewarm: GBrainConfig.serve_vector_prewarm slot (snapshot merge lives in core/published-config.ts); +1 GBRA-95 G7a: storage.git_lfs KNOWN_CONFIG_KEYS row (read in persistence/git-declared.ts); re-summed at the v0.60.449.0 merge (2012 measured); +1 GBRA-216 (#2941/#2953): recall.confidence_weighting / recall.group_by_entity KNOWN_CONFIG_KEYS row (values validated in facts/recall-config.ts)src/core/persistence/sync-run.ts 1686 ratchet new row: crossed the 1500 unlisted cap in #6643 (knock-on re-freeze, checkpoint revival, root cause and the truthful --retry-failed wait all drive the private cursor/gate machinery: holdUnderGate, freezeEntry, saveCursor); classification lives in sync-knock-on.ts, the checkpoint clause in checkpoint-validation.ts; peel the settle path (settleFailedRequest and its recoveries) into a sibling module next; +3 #6722: committed pages' size_state tallied into the cursor and the sync receipt size_states (logic in page-embedding-budget.ts addSizeState); merge v0.60.240.0: large pages and master growth compose at 1687; +2 #6694: the slug-mode checkpoint revival import and its doc line (predicate lives in persistence/sync-slug-mode.ts); +11 #6712 PR 3 (L7): a plain sync retries the recorded failure --retry-failed used to (retryRecordedFailure; the unchanged-refusal replay lives in persistence/sync-stop-class.ts replaysUnchangedRefusal), the moved-checkpoint and company content-refusal exceptions; #6712 PR 3 integration: lanes L7 (retryRecordedFailure, +19) and L8 (#6727 legacy-slug refusal line, #6735 timeout revival, +6) compose at 1762; +2 wave 18a integration: #6729 (lane 2, written against the 1745 ceiling) records identity downgrades in performManagedPass through noteIdentityDowngrades (logic in core/sync-identity-downgrades.ts), composed with master 1762; +14 Wave B PR 2: freezeEntry freezes a Markdown file over the read bound by reference (body_ref) and holdFailedFenceRequest holds a streamed refusal; both set freezeEntry/holdFailedFenceRequest locals (blob, oversize, rawHash) so they stay here, the hashing and preparation live in persistence/sync-streamed.ts and the hold in sync-screen.ts streamedRefusalHold; integrated at the master 4e29d0904 merge: master 1764 + Wave B PR 2 14 = 1778 measured; +4 #6948: freezeEntry holds an entry several live pages claim (hold in sync-screen.ts originConflictHold, verdict in persistence/origin-twins.ts); +1 #7167: managedDryRun reports the writer state (the import of persistence/sync-dry-run-writer.ts, where the read lives); +4 G3 git-canonical: freezeEntry reads a strict source's entry from its commit (pinnedBlob) and carries committedOnly to publication; both use freezeEntry locals (rule in persistence/sync-classify.ts)src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env; -119 #6082: plugin-lane detectors moved to plugin-lanes.ts (re-exported); +18 #6092/#6171: hook ownership identity on write/remove/converge, permission ownership carry, --remove --dry-run and the --status hook census (logic in hooks.ts + harness-hooks.ts); +5 D8 Codex slice: the Codex SessionEnd capture hook obeys the recorded consent (wireCodexCapture: hooks on, capture accepted, never registrar mode) and is disclosed in the consent block; -31 #6743: cleanup gate moved to harness-cleanup.ts; +8 #6798: supersededEnrollments dep (interface field + default) and the --status epoch hint printed only for a superseded enrollment (the brain read lives in harness-skills.ts brainSupersededEnrollments)src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option@@ -45,6 +45,6 @@ src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: rerankersrc/commands/eval-longmemeval.ts 1545 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); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +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.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1733 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); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)-src/commands/config.ts 1524 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); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)+src/commands/config.ts 1525 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); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal); +1 GBRA-216: recall.* config set value refusal (facts/recall-config.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)src/core/behavior-change-notice.ts 1518 ratchet the BEHAVIOR_CHANGES table grows by one row per disclosed change: +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2); the behavior-change table split (#7607) retires this rowdiff --git a/src/commands/config.ts b/src/commands/config.tsindex ee213866a0..1e06341a8d 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -406,6 +406,7 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:if (err) { console.error(`[config] ${err}`); process.exit(1); }}if (key.startsWith('loops.')) (await import('./config/loops-values.ts')).refuseInvalidLoopsConfigValue(key, value);+ if (key.startsWith('recall.')) { const err = (await import('../core/facts/recall-config.ts')).recallConfigValueRefusal(key, value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }if (key === 'sync.slug_conflicts.auto_remove') { const err = (await import('../core/repair/slug-autoheal.ts')).slugAutoRemoveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }if (key === 'sync.origin_twins.auto_resolve') { const err = (await import('../core/repair/origin-twins-heal.ts')).originAutoResolveValueRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }if (key === 'sync.repo_path') { const err = (await import('../core/sync-config-keys.ts')).syncRepoPathRefusal(value); if (err) { console.error(`[config] ${err}`); process.exit(1); } }diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 60bab0385a..bd34cba1b4 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -442,8 +442,10 @@ export async function recallVerbForCaller(engine: BrainEngine, args: string[], r}export type RecallVerbResult = {- facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string; relevance?: number }>;+ facts: Array<{ fact_id: string; fact: string; kind: string; entity_slug: string | null; provenance: string; relevance?: number; rank_score?: number }>;facts_order?: 'relevance' | 'newest';+ facts_groups?: Array<{ source_id: string; entity_slug: string | null; fact_ids: string[] }>;+ entity_unspecified?: { candidates: Array<{ source_id: string; entity_slug: string }>; suggestion: string };facts_degraded?: { reason?: string; unembedded?: number };results?: Array<{ slug: string; title: string | null; evidence: string; chunk: string | null }>;search_degraded?: string;@@ -510,9 +512,18 @@ export async function renderRecallVerbResult(flags: ParsedFlags, result: RecallVconst lines: string[] = [];if (result.facts.length) {lines.push(result.facts_order === 'relevance' ? 'Facts (ranked by relevance to the question):' : 'Facts:');- for (const f of result.facts) {- lines.push(` #${f.fact_id} [${f.kind}]${f.entity_slug ? ` (${f.entity_slug})` : ''} ${f.fact} — ${f.provenance}${typeof f.relevance === 'number' ? ` (relevance ${f.relevance.toFixed(2)})` : ''}`);+ const factLine = (f: RecallVerbResult['facts'][number], indent: string) =>+ `${indent}#${f.fact_id} [${f.kind}]${f.entity_slug ? ` (${f.entity_slug})` : ''} ${f.fact} — ${f.provenance}${typeof f.relevance === 'number' ? ` (relevance ${f.relevance.toFixed(2)})` : ''}`;+ const byId = new Map(result.facts.map(f => [f.fact_id, f]));+ if (result.facts_groups?.length) {+ for (const g of result.facts_groups) {+ lines.push(` ${g.entity_slug ?? 'No entity'}:`);+ for (const id of g.fact_ids) { const f = byId.get(id); if (f) lines.push(factLine(f, ' ')); }+ }+ } else {+ for (const f of result.facts) lines.push(factLine(f, ' '));}+ if (result.entity_unspecified) lines.push(`note: ${result.entity_unspecified.candidates.length} entities answer this question; rerun with an entity to read one (${result.entity_unspecified.candidates.map(c => c.entity_slug).join(', ')}).`);}if (result.results?.length) {lines.push('Pages:');diff --git a/src/core/config.ts b/src/core/config.tsindex 0a95052dce..6f609ddc0b 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1480,6 +1480,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['models.eval.longmemeval', 'models.eval.cross_modal.slot_a', 'models.eval.cross_modal.slot_b', 'models.eval.cross_modal.slot_c', // #5872 D12 probe judge slots'facts.extraction_model','recall.question_admission', // recall `question` admission rule: reserve (default) | facts_arm (facts/question-recall.ts)+ 'recall.confidence_weighting', 'recall.group_by_entity', // #2941/#2953 switches, on | off, default off (facts/recall-config.ts)// Brain-wide kill switch for fact extraction, read by// src/core/facts/extract.ts:isFactsExtractionEnabled and honored by// sweep.ts, operations.ts and transcripts/ingest-facts.ts. That function'sdiff --git a/src/core/facts/decay.ts b/src/core/facts/decay.tsindex f239595b0b..6875ba321b 100644--- a/src/core/facts/decay.ts+++ b/src/core/facts/decay.ts@@ -1,9 +1,10 @@/*** v0.31 Hot Memory — confidence decay helper.*- * Single source of truth for the per-kind halflife table. Recall, supersession- * audit, facts_health, and the MCP `_meta.brain_hot_memory` injector all call- * `effectiveConfidence(fact, now)`. Tests pin the table values.+ * Single source of truth for the per-kind halflife table. The MCP+ * `_meta.brain_hot_memory` injector and recall's CLI JSON call+ * `effectiveConfidence(fact, now)`; recall's `question` ranking calls+ * `recallConfidence` (decay with a trust floor). Tests pin the table values.** Half-lives chosen empirically (per /plan-eng-review halflife-defaults call):* event 7 days — lunch on Tuesday is meaningless after Tuesday@@ -18,6 +19,7 @@*/import type { FactRow, FactKind } from '../engine.ts';+import type { TrustTier } from '../trust/tier.ts';/*** Halflife in days per fact kind. Exported as a const so tests can pin@@ -57,6 +59,38 @@ export function effectiveConfidence(fact: FactRow, now: Date = new Date()): numbreturn clamp01(decayed);}+/**+ * #2941: recall `question` ranking weights each admitted fact by how much it+ * deserves to be believed now (`recall.confidence_weighting`, default off).+ * Trust is a floor, not a multiplier: rows the owner stands behind+ * (confirmed, or the owner's own notes) never lose weight to age, so fresh+ * agent-written or external text cannot outrank an older confirmed fact.+ * Every other tier decays from `valid_from` (git-durable on repo brains, a+ * database column on repo-less ones) and carries its tier weight. A+ * writer-dated `fact` row ("founded in 2010") is historical and still true,+ * so it does not decay. Expired or lapsed rows (`include_expired`) weigh 0.+ */+export const TRUST_RECALL_FLOOR: Readonly<Record<TrustTier, number>> = Object.freeze({+ user_confirmed: 1, operator_curated: 1, tool_observed: 0, agent_written: 0, unknown: 0, external_untrusted: 0,+});+export const TRUST_RECALL_WEIGHT: Readonly<Record<TrustTier, number>> = Object.freeze({+ user_confirmed: 1, operator_curated: 1, tool_observed: 0.9, agent_written: 0.8, unknown: 0.8, external_untrusted: 0.6,+});++export type RecallConfidenceFact = Pick<FactRow, 'kind' | 'confidence' | 'valid_from' | 'valid_until' | 'expired_at' | 'trust_tier'>;++/** The [0, 1] belief weight of a fact for recall ranking at `now`; `dated` means the writer supplied `valid_from`. */+export function recallConfidence(fact: RecallConfidenceFact, dated: boolean, now: Date = new Date()): number {+ if (fact.expired_at && fact.expired_at.getTime() <= now.getTime()) return 0;+ if (fact.valid_until && fact.valid_until.getTime() <= now.getTime()) return 0;+ const tier = fact.trust_tier ?? 'unknown';+ const decayed = dated && fact.kind === 'fact' ? clamp01(fact.confidence) : effectiveConfidence(fact as FactRow, now);+ return Math.max(TRUST_RECALL_FLOOR[tier], decayed * TRUST_RECALL_WEIGHT[tier]);+}++/** The ranking multiplier: at most halves a fact's score, so weighting reorders facts and never hides one. */+export const confidenceFactor = (weight: number): number => 0.5 + 0.5 * clamp01(weight);+function clamp01(x: number): number {if (!Number.isFinite(x)) return 0;if (x <= 0) return 0;diff --git a/src/core/facts/question-recall.ts b/src/core/facts/question-recall.tsindex c0aba1a4fc..5aad142751 100644--- a/src/core/facts/question-recall.ts+++ b/src/core/facts/question-recall.ts@@ -23,9 +23,11 @@ import { loadEmbeddingQueryPrefix } from '../search/query-prefix.ts';import { embedQueryBounded, makeQueryEmbedDeadline } from '../search/hybrid.ts';import { resolveHnswIterativeScan } from '../search/hnsw-iterative-scan.ts';import {- FACT_ADMISSION_FLOOR_EVIDENCE, QUESTION_ADMISSION_RULES, admitted, collectFactCandidates, countUncomparableFacts, poolEntityPairs, queryTerms, scoreFactCandidates,+ FACT_ADMISSION_FLOOR_EVIDENCE, QUESTION_ADMISSION_RULES, admitted, collectFactCandidates, countUncomparableFacts, isDatedFact, poolEntityPairs, queryTerms, scoreFactCandidates,type FactPoolFilters, type FactPoolScope, type QuestionAdmissionRule,} from '../search/fact-relevance.ts';+import { confidenceFactor, recallConfidence } from './decay.ts';+import { CONFIDENCE_WEIGHTING_KEY, GROUP_BY_ENTITY_KEY, recallSwitchOn } from './recall-config.ts';export const QUESTION_MAX_CHARS = 2000;/** Candidates per arm, separate from the output `limit`. */@@ -177,6 +179,10 @@ export interface QuestionRecall {rows: CollapsedFactRead<FactRow>[];/** fact id → relevance (cosine + term share + 0.1 when dated). */relevance: Map<number, number>;+ /** #2941 (`recall.confidence_weighting` on): fact id → rank score (relevance × confidence factor) and → confidence factor. */+ weighting?: { rank: Map<number, number>; factor: Map<number, number> };+ /** #2953: `recall.group_by_entity` is on and the call named no entity, so the delivered facts are grouped (groupFactsByEntity). */+ groupByEntity?: boolean;degraded?: FactsDegraded;/** Present when the cosine arm ran on a model with no measured admission floor. */calibration?: FactsCalibration;@@ -208,27 +214,35 @@ export async function rankFactsByQuestion(ctx: OperationContext, input: Questionconst { embedding, reason } = await questionEmbedding(ctx, question);if (!embedding && queryTerms(question).length === 0) return empty({ reason: 'no_query_terms' });try {- const [pool, uncomparable, rule] = await Promise.all([+ const [pool, uncomparable, rule, weighted, grouped] = await Promise.all([collectFactCandidates(ctx.engine, question, scope, embedding, {depth: { keyword: QUESTION_POOL_DEPTH, cosine: QUESTION_POOL_DEPTH, entity: QUESTION_POOL_DEPTH }, filters, cosineForAll: true,hnswIterativeScan: resolveHnswIterativeScan(ctx.config),}),embedding ? countUncomparableFacts(ctx.engine, scope, filters, embedding.length) : [],admissionRule(ctx.engine),+ recallSwitchOn(ctx.engine, CONFIDENCE_WEIGHTING_KEY),+ input.entity ? false : recallSwitchOn(ctx.engine, GROUP_BY_ENTITY_KEY),]);const ranked = scoreFactCandidates(question, pool.candidates).filter(s => admitted(s, rule));const unembedded = uncomparable.reduce((n, r) => n + r.n, 0);const why = reason ?? (embedding && !pool.column ? 'facts_embedding_column_missing' : undefined);const degraded: FactsDegraded | undefined = why || unembedded ? { ...(why ? { reason: why } : {}), ...(unembedded ? { unembedded } : {}) } : undefined;- const ids = ranked.map(s => s.candidate.id);+ let ids = ranked.map(s => s.candidate.id);const raw = ids.length? await ctx.engine.executeRaw<FactRowSqlShape>('SELECT * FROM facts WHERE source_id = ANY($1::text[]) AND id = ANY($2::bigint[])', [input.factSources, ids]): [];const byId = new Map(raw.map(r => { const row = rowToFact(r); return [row.id, { ...row, embedding: null }] as const; }));const modelKey = embedding && pool.column ? calibrationKey(getEmbeddingModel(), getEmbeddingDimensions()) : null;+ const weighting = weighted ? weighByConfidence(ranked.map(s => ({ id: s.candidate.id, score: s.score })), byId) : undefined;+ if (weighting) ids = weighting.order;+ let rows: CollapsedFactRead<FactRow>[] = await collapseFactReads(ctx.engine, ids.flatMap(id => byId.get(id) ?? []));+ if (weighting) rows = rows.map(r => weightedRepresentative(r, byId, weighting.rank));return {- rows: (await collapseFactReads(ctx.engine, ids.flatMap(id => byId.get(id) ?? []))).slice(0, input.limit),+ rows: rows.slice(0, input.limit),relevance: new Map(ranked.map(s => [s.candidate.id, Math.round(s.score * 1e4) / 1e4])),+ ...(weighting ? { weighting: { rank: weighting.rank, factor: weighting.factor } } : {}),+ ...(grouped ? { groupByEntity: true } : {}),ambiguousEntity: null,...(degraded ? { degraded } : {}),...(modelKey && FACT_ADMISSION_FLOOR_EVIDENCE[modelKey] === undefined ? { calibration: { status: 'unmeasured' as const, model_key: modelKey } } : {}),@@ -239,6 +253,78 @@ export async function rankFactsByQuestion(ctx: OperationContext, input: Question}}+const round4 = (n: number) => Math.round(n * 1e4) / 1e4;++/**+ * #2941: rank admitted facts by relevance × confidenceFactor(recallConfidence),+ * then newest valid_from, then id. Admission already ran on raw relevance, so+ * weighting reorders the admitted set and never drops a fact.+ */+function weighByConfidence(scored: Array<{ id: number; score: number }>, byId: Map<number, FactRow>, now = new Date()) {+ const rank = new Map<number, number>();+ const factor = new Map<number, number>();+ for (const { id, score } of scored) {+ const row = byId.get(id);+ const f = row ? confidenceFactor(recallConfidence(row, isDatedFact(row), now)) : 1;+ factor.set(id, round4(f));+ rank.set(id, score * f);+ }+ const order = scored.map(s => s.id).sort((a, b) => rank.get(b)! - rank.get(a)!+ || (byId.get(b)?.valid_from.getTime() ?? 0) - (byId.get(a)?.valid_from.getTime() ?? 0) || b - a);+ for (const [id, s] of rank) rank.set(id, round4(s));+ return { order, rank, factor };+}++/** #7043 keeps a group's newest copy; under weighting the delivered copy is the group's best-ranked one, so its position, provenance and trust agree. */+function weightedRepresentative(row: CollapsedFactRead<FactRow>, byId: Map<number, FactRow>, rank: Map<number, number>): CollapsedFactRead<FactRow> {+ if (!row.collapsed_ids?.length) return row;+ const best = row.collapsed_ids.filter(id => rank.has(id) && byId.has(id)).sort((a, b) => rank.get(b)! - rank.get(a)! || b - a)[0];+ if (best === undefined || best === row.id) return row;+ const { entity_slugs, collapsed_count, collapsed_ids } = row;+ return { ...byId.get(best)!, ...(entity_slugs ? { entity_slugs } : {}), ...(collapsed_count ? { collapsed_count } : {}), collapsed_ids };+}++export interface FactEntityGroup { source_id: string; entity_slug: string | null; fact_ids: string[]; top_relevance: number | null }++export const ENTITY_UNSPECIFIED_SUGGESTION = 'These facts belong to different entities. Ask which one the question is about, then recall again with entity set.';+const ENTITY_UNSPECIFIED_MAX_OPTIONS = 5;++/**+ * #2953: the delivered facts grouped by (source_id, entity_slug), the+ * identity key, so two entities' figures never interleave. Runs after the+ * limit and budget cuts, so it only reorders what is delivered: each group+ * keeps its internal order and groups are ordered by their best fact. Facts+ * with no entity form their own group. When two or more entities answer,+ * `entity_unspecified` lists them and the emitted notice offers the same+ * recall per entity.+ */+export function groupFactsByEntity<R extends { id: number; source_id: string; entity_slug: string | null }>(rows: R[], ranking: QuestionRecall, params: Record<string, unknown>,+ emitNotice?: (n: Notice) => void): { rows: R[]; fields: { facts_groups: FactEntityGroup[]; entity_unspecified?: { candidates: EntityCandidate[]; suggestion: string } } } {+ const buckets = new Map<string, R[]>();+ for (const r of rows) {+ const key = `${r.source_id}\u0000${r.entity_slug ?? ''}`;+ buckets.set(key, [...(buckets.get(key) ?? []), r]);+ }+ const groups = [...buckets.values()].map(members => ({+ source_id: members[0]!.source_id, entity_slug: members[0]!.entity_slug, fact_ids: members.map(m => String(m.id)),+ top_relevance: ranking.relevance.get(members[0]!.id) ?? null,+ }));+ const named = groups.filter(g => g.entity_slug !== null).map(g => ({ source_id: g.source_id, entity_slug: g.entity_slug as string }));+ if (named.length < 2) return { rows: [...buckets.values()].flat(), fields: { facts_groups: groups } };+ const args = callArgs(params);+ const options = named.slice(0, ENTITY_UNSPECIFIED_MAX_OPTIONS).map((c, i) => ({+ id: `e${i + 1}`, label: `${c.entity_slug} (source ${c.source_id})`, argv: recallArgv({ ...args, entity: c.entity_slug, source_id: c.source_id }),+ }));+ const notice: Notice = {+ code: 'entity_unspecified',+ kind: 'info',+ why: `The question named no entity, and saved facts from ${named.length} entities answer it (${named.map(c => c.entity_slug).join(', ')}). They are grouped by entity in facts_groups; a figure for one entity does not apply to another.`,+ decisions: [{ id: 'entity', question: 'Which entity is the question about?', options, default: 'e1', default_reason: 'The entity with the best-matching fact.' }],+ };+ emitNotice?.(notice);+ return { rows: [...buckets.values()].flat(), fields: { facts_groups: groups, entity_unspecified: { candidates: named, suggestion: ENTITY_UNSPECIFIED_SUGGESTION } } };+}+/*** TC7: a recall that passed `query` but no `question` and no fact filter got* its facts newest first; the hint names `question` and carries the same calldiff --git a/src/core/facts/recall-config.ts b/src/core/facts/recall-config.tsnew file mode 100644index 0000000000..a68bd2039e--- /dev/null+++ b/src/core/facts/recall-config.ts@@ -0,0 +1,35 @@+/**+ * recall's config keys and their values (#2941, #2953). `config set` refuses+ * any other value (commands/config.ts), so a typo never reads as "on".+ *+ * recall.confidence_weighting on | off (default off): question ranking weighs facts by recallConfidence (facts/decay.ts)+ * recall.group_by_entity on | off (default off): a question with no entity returns its facts grouped by entity+ * recall.question_admission reserve (default) | facts_arm+ */+import type { BrainEngine } from '../engine.ts';+import { QUESTION_ADMISSION_RULES } from '../search/fact-relevance.ts';++export const CONFIDENCE_WEIGHTING_KEY = 'recall.confidence_weighting';+export const GROUP_BY_ENTITY_KEY = 'recall.group_by_entity';+const SWITCH_KEYS: readonly string[] = [CONFIDENCE_WEIGHTING_KEY, GROUP_BY_ENTITY_KEY];+const ON = ['on', 'true', '1', 'yes'];+const OFF = ['off', 'false', '0', 'no'];++/** Whether a stored switch value is on; unset, unreadable and unknown values are off. */+export async function recallSwitchOn(engine: BrainEngine, key: string): Promise<boolean> {+ const raw = (await engine.getConfig(key).catch(() => null))?.trim().toLowerCase();+ return ON.includes(raw ?? '');+}++/** Why `value` is not a valid value for a recall key, or null when it is (or the key is not one of these). */+export function recallConfigValueRefusal(key: string, value: string): string | null {+ const v = value.trim().toLowerCase();+ if (SWITCH_KEYS.includes(key)) {+ return ON.includes(v) || OFF.includes(v) ? null : `${key} must be on or off; got ${JSON.stringify(value)}. Nothing was written.`;+ }+ if (key === 'recall.question_admission') {+ return (QUESTION_ADMISSION_RULES as readonly string[]).includes(v) ? null+ : `recall.question_admission must be one of ${QUESTION_ADMISSION_RULES.join(', ')}; got ${JSON.stringify(value)}. Nothing was written.`;+ }+ return null;+}diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex dcceb507c1..e693cf58ba 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -52,7 +52,7 @@ import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';import type { TrustTier } from '../trust/tier.ts';import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';import { parseSinceParam } from '../facts/since-parse.ts';-import { parseQuestionParam, questionRecallNotices, rankFactsByQuestion, recallHintNotice, unlinkedNamesakes, type EntityCandidate, type QuestionRecall } from '../facts/question-recall.ts';+import { groupFactsByEntity, parseQuestionParam, questionRecallNotices, rankFactsByQuestion, recallHintNotice, unlinkedNamesakes, type EntityCandidate, type QuestionRecall } from '../facts/question-recall.ts';// ============================================================// v0.31 — Hot memory ops: extract_facts / recall / forget_fact@@ -471,9 +471,7 @@ const recall: Operation = {// Engines apply grep in SQL (pre-limit). This client-side pass stays only// as the filter for the supersessions branch, which bypasses FactListOpts.- if (grep && p.supersessions === true) {- rows = rows.filter(r => r.fact.toLowerCase().includes(grep));- }+ if (grep && p.supersessions === true) rows = rows.filter(r => r.fact.toLowerCase().includes(grep));// #7043: copies of one claim (the fact arms read MAX_SEARCH_LIMIT rows) collapse after the visibility filters, before the limit cut.if (!ranking) rows = (await collapseFactReads(ctx.engine, rows)).slice(0, limit);@@ -579,6 +577,7 @@ const recall: Operation = {droppedCount = factsPack.meta.dropped + resultsPack.meta.dropped;}+ const grouped = ranking?.groupByEntity ? groupFactsByEntity(packedFacts, ranking, p, ctx.emitNotice) : null; if (grouped) packedFacts = grouped.rows; // #2953: reorders delivered facts onlyconst budgetPacking = recallBudgetPacking(p.budget_policy, queryText, budgetTokens, { rows, packedFacts, searchResults, packedResults }, recallResultCost(delivery));const out = {@@ -613,13 +612,13 @@ const recall: Operation = {fact_id: String(r.id),provenance: r.source, ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),...(r.entity_slugs ? { entity_slugs: r.entity_slugs } : {}), ...(r.collapsed_count ? { collapsed_count: r.collapsed_count } : {}),- ...(ranking ? { relevance: ranking.relevance.get(r.id) } : {}),+ ...(ranking ? { relevance: ranking.relevance.get(r.id), ...(ranking.weighting ? { rank_score: ranking.weighting.rank.get(r.id), confidence_factor: ranking.weighting.factor.get(r.id) } : {}) } : {}),})), f => f.id)),total: packedFacts.length,facts_order: ranking ? 'relevance' : 'newest',...(ranking?.degraded ? { facts_degraded: ranking.degraded } : {}),...(ranking?.calibration ? { facts_calibration: ranking.calibration } : {}),- ...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),+ ...grouped?.fields, ...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),...(pending_consolidation_count !== undefined ? { pending_consolidation_count } : {}),// MEMORY_VERBS v1 envelope (G1B superset — additive on every response).protocol_version: MEMORY_VERBS_VERSION,diff --git a/test/e2e/recall-confidence-grouping-postgres.test.ts b/test/e2e/recall-confidence-grouping-postgres.test.tsnew file mode 100644index 0000000000..0474d4e3f6--- /dev/null+++ b/test/e2e/recall-confidence-grouping-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../recall-confidence-grouping.test.ts'));diff --git a/test/recall-confidence-grouping.test.ts b/test/recall-confidence-grouping.test.tsnew file mode 100644index 0000000000..f9b70c952d--- /dev/null+++ b/test/recall-confidence-grouping.test.ts@@ -0,0 +1,210 @@+/**+ * recall `question` confidence weighting (#2941, recall.confidence_weighting)+ * and entity grouping (#2953, recall.group_by_entity). Both default off; off+ * must leave the response exactly as before. Keyless (term share only) so the+ * ranking is deterministic; facts are written straight to the database, the+ * repo-less shape (no git, no fence file).+ *+ * Both engines: PGLite always, Postgres through+ * test/e2e/recall-confidence-grouping-postgres.test.ts.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { CONFIDENCE_WEIGHTING_KEY, GROUP_BY_ENTITY_KEY, recallConfigValueRefusal } from '../src/core/facts/recall-config.ts';+import { HALFLIFE_DAYS, confidenceFactor, recallConfidence, type RecallConfidenceFact } from '../src/core/facts/decay.ts';+import { withTrustPromotion } from '../src/core/persistence/context.ts';+import type { TrustTier } from '../src/core/trust/tier.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++// eslint-disable-next-line @typescript-eslint/no-explicit-any+type R = Record<string, any>;+const DAY = 24 * 60 * 60 * 1000;+const NOW = new Date('2026-10-01T00:00:00Z');+const noopLogger = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} };+const markers = (facts: R[]) => facts.map(f => String(f.fact).split(' ')[0]);+const row = (o: Partial<RecallConfidenceFact> & { daysAgo: number }): RecallConfidenceFact => ({+ kind: 'fact', confidence: 1, valid_until: null, expired_at: null, ...o, valid_from: new Date(NOW.getTime() - o.daysAgo * DAY),+});++describe('recallConfidence (pure)', () => {+ test('trust is a floor: confirmed and owner notes never decay; other tiers decay and carry their weight', () => {+ expect(recallConfidence(row({ daysAgo: 1000, trust_tier: 'user_confirmed' }), false, NOW)).toBe(1);+ expect(recallConfidence(row({ daysAgo: 1000, trust_tier: 'operator_curated' }), false, NOW)).toBe(1);+ expect(recallConfidence(row({ daysAgo: 0, trust_tier: 'agent_written' }), false, NOW)).toBeCloseTo(0.8, 6);+ expect(recallConfidence(row({ daysAgo: 0, trust_tier: 'external_untrusted' }), false, NOW)).toBeCloseTo(0.6, 6);+ expect(recallConfidence(row({ daysAgo: 0, trust_tier: 'tool_observed' }), false, NOW)).toBeCloseTo(0.9, 6);+ expect(recallConfidence(row({ daysAgo: 0 }), false, NOW)).toBeCloseTo(0.8, 6);+ expect(recallConfidence(row({ daysAgo: HALFLIFE_DAYS.fact, trust_tier: 'agent_written' }), false, NOW)).toBeCloseTo(0.8 * Math.exp(-1), 6);+ });++ test('an older confirmed fact outweighs fresh agent-written and external facts', () => {+ const old = recallConfidence(row({ daysAgo: 365, trust_tier: 'user_confirmed' }), false, NOW);+ for (const tier of ['agent_written', 'external_untrusted', 'tool_observed', 'unknown'] as TrustTier[]) {+ expect(old).toBeGreaterThan(recallConfidence(row({ daysAgo: 0, trust_tier: tier }), false, NOW));+ }+ });++ test('a writer-dated fact row does not decay; a writer-dated event does', () => {+ expect(recallConfidence(row({ daysAgo: 4000, trust_tier: 'agent_written' }), true, NOW)).toBeCloseTo(0.8, 6);+ expect(recallConfidence(row({ daysAgo: 70, kind: 'event', trust_tier: 'agent_written' }), true, NOW)).toBeLessThan(0.001);+ });++ test('expired or lapsed facts weigh 0 whatever their tier, and the factor stays in [0.5, 1]', () => {+ expect(recallConfidence(row({ daysAgo: 1, trust_tier: 'user_confirmed', expired_at: new Date(NOW.getTime() - DAY) }), false, NOW)).toBe(0);+ expect(recallConfidence(row({ daysAgo: 1, trust_tier: 'user_confirmed', valid_until: new Date(NOW.getTime() - DAY) }), false, NOW)).toBe(0);+ expect(confidenceFactor(0)).toBe(0.5);+ expect(confidenceFactor(1)).toBe(1);+ expect(confidenceFactor(7)).toBe(1);+ });+});++describe('recall config values', () => {+ test('switches take on/off; question_admission takes its rules; anything else is refused', () => {+ for (const key of [CONFIDENCE_WEIGHTING_KEY, GROUP_BY_ENTITY_KEY]) {+ for (const v of ['on', 'off', 'true', 'false', 'ON']) expect(recallConfigValueRefusal(key, v)).toBeNull();+ expect(recallConfigValueRefusal(key, 'bogus')).toContain('must be on or off');+ }+ expect(recallConfigValueRefusal('recall.question_admission', 'facts_arm')).toBeNull();+ expect(recallConfigValueRefusal('recall.question_admission', 'bogus')).toContain('reserve, facts_arm');+ expect(recallConfigValueRefusal('recall.unrelated', 'anything')).toBeNull();+ });+});++for (const kind of testBackends()) {+ describe(`recall confidence weighting and entity grouping (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const ids: Record<string, number> = {};+ let notices: Notice[] = [];+ const ctxOf = (remote: boolean): OperationContext => ({+ engine, config: {} as GBrainConfig, logger: noopLogger, dryRun: false, remote, transport: 'stdio', sourceId: 'default',+ emitNotice: (n: Notice) => notices.push(n),+ } as OperationContext);+ const recall = async (p: R, remote = false) => (await operationsByName.recall.handler(ctxOf(remote), p)) as R;+ const setFlag = (key: string, value: string | null) => value === null+ ? engine.executeRaw('DELETE FROM config WHERE key = $1', [key]) : engine.setConfig(key, value);++ async function fact(name: string, f: { text: string; entity: string | null; daysAgo: number; tier?: TrustTier; visibility?: 'world' | 'private' }) {+ const [r] = await engine.executeRaw<{ id: string | number }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, valid_from, created_at, source)+ VALUES ('default', $1, $2, 'fact', $3, now() - ($4 || ' days')::interval, now() - ($4 || ' days')::interval, 'test') RETURNING id`,+ [f.entity, f.text, f.visibility ?? 'world', String(f.daysAgo)]);+ ids[name] = Number(r!.id);+ const tier = f.tier ?? 'agent_written';+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw('UPDATE facts SET trust_tier = $1 WHERE id = $2', [tier, ids[name]])));+ }++ beforeAll(async () => {+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ __setEmbedTransportForTests(null);+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ // Weighting: identical term match, so only trust and age can separate them.+ await fact('confirmed', { text: 'OLDCONFIRMED widget-example warranty period lasts twelve months', entity: null, daysAgo: 400, tier: 'user_confirmed' });+ await fact('fresh', { text: 'FRESHAGENT widget-example warranty period lasts three months', entity: null, daysAgo: 1, tier: 'agent_written' });+ await fact('external', { text: 'FRESHEXTERNAL widget-example warranty period lasts six months', entity: null, daysAgo: 2, tier: 'external_untrusted' });+ // Duplicate claim: older confirmed copy, newer agent copy.+ await fact('dupOld', { text: 'gadget-example ships with a carbon fiber frame', entity: null, daysAgo: 300, tier: 'user_confirmed' });+ await fact('dupNew', { text: 'gadget-example ships with a carbon fiber frame', entity: null, daysAgo: 3, tier: 'agent_written' });+ // Grouping: two clients and a default, plus a private figure for a third client.+ await fact('priceA', { text: 'PRICEA annual subscription price quoted 5000 dollars', entity: 'companies/client-a-example', daysAgo: 5 });+ await fact('termsA', { text: 'TERMSA annual subscription price includes onboarding', entity: 'companies/client-a-example', daysAgo: 6 });+ await fact('priceB', { text: 'PRICEB annual subscription price quoted 10000 dollars', entity: 'companies/client-b-example', daysAgo: 4 });+ await fact('priceDefault', { text: 'PRICEDEFAULT standard annual subscription price list 10000 dollars', entity: null, daysAgo: 7 });+ await fact('priceC', { text: 'PRICEC annual subscription price quoted 7000 dollars', entity: 'companies/client-c-example', daysAgo: 3, visibility: 'private' });+ }, 180_000);+ afterAll(async () => { resetGateway(); await close?.(); });+ beforeEach(async () => {+ notices = [];+ __resetPrivateVisibilityCacheForTests();+ await setFlag(CONFIDENCE_WEIGHTING_KEY, null);+ await setFlag(GROUP_BY_ENTITY_KEY, null);+ });++ const WARRANTY = 'How long does the widget-example warranty period last?';+ const PRICE = 'What annual subscription price did we quote?';++ test('flags off (unset or off): the response carries no new fields and keeps relevance-then-newest order', async () => {+ const unset = await recall({ question: WARRANTY });+ await setFlag(CONFIDENCE_WEIGHTING_KEY, 'off');+ await setFlag(GROUP_BY_ENTITY_KEY, 'off');+ const off = await recall({ question: WARRANTY });+ expect(off).toEqual(unset);+ expect(markers(unset.facts)).toEqual(['FRESHAGENT', 'FRESHEXTERNAL', 'OLDCONFIRMED']);+ for (const f of unset.facts) { expect(f).not.toHaveProperty('rank_score'); expect(f).not.toHaveProperty('confidence_factor'); }+ expect(unset).not.toHaveProperty('facts_groups');+ });++ test('weighting on: the older confirmed fact outranks fresh agent and external facts; relevance stays raw; the admitted set is unchanged', async () => {+ const before = await recall({ question: WARRANTY });+ await setFlag(CONFIDENCE_WEIGHTING_KEY, 'on');+ const r = await recall({ question: WARRANTY });+ expect(markers(r.facts)).toEqual(['OLDCONFIRMED', 'FRESHAGENT', 'FRESHEXTERNAL']);+ expect(new Set(r.facts.map((f: R) => f.id))).toEqual(new Set(before.facts.map((f: R) => f.id)));+ const byMarker = Object.fromEntries(r.facts.map((f: R) => [markers([f])[0], f]));+ expect(byMarker.OLDCONFIRMED.confidence_factor).toBe(1);+ expect(byMarker.FRESHEXTERNAL.confidence_factor).toBeLessThan(byMarker.FRESHAGENT.confidence_factor);+ for (const f of r.facts) {+ expect(f.relevance).toBe(before.facts.find((b: R) => b.id === f.id).relevance);+ expect(f.rank_score).toBeCloseTo(f.relevance * f.confidence_factor, 3);+ }+ });++ test('weighting on: copies of one claim deliver the best-ranked copy (the confirmed one), not the newest', async () => {+ const off = await recall({ question: 'What frame does gadget-example ship with?' });+ expect(off.facts[0].id).toBe(ids.dupNew);+ await setFlag(CONFIDENCE_WEIGHTING_KEY, 'on');+ const on = await recall({ question: 'What frame does gadget-example ship with?' });+ expect(on.facts[0].id).toBe(ids.dupOld);+ expect(on.facts[0].collapsed_count).toBe(2);+ expect(on.facts[0].trust_tier).toBe('user_confirmed');+ });++ test('grouping on, no entity: each entity\'s facts sit together, no-entity facts form a group, and the notice offers one recall per entity', async () => {+ await setFlag(GROUP_BY_ENTITY_KEY, 'on');+ const r = await recall({ question: PRICE, limit: 10 });+ const groups = r.facts_groups as R[];+ expect(groups.map(g => g.entity_slug).sort()).toEqual([null, 'companies/client-a-example', 'companies/client-b-example', 'companies/client-c-example'].sort((a, b) => String(a).localeCompare(String(b))));+ expect(r.facts.map((f: R) => String(f.id))).toEqual(groups.flatMap(g => g.fact_ids));+ const a = groups.find(g => g.entity_slug === 'companies/client-a-example')!;+ expect(a.fact_ids.map(Number).sort()).toEqual([ids.priceA, ids.termsA].sort());+ expect(r.entity_unspecified.candidates.map((c: R) => c.entity_slug).sort()).toEqual(['companies/client-a-example', 'companies/client-b-example', 'companies/client-c-example']);+ const notice = notices.find(n => n.code === 'entity_unspecified')!;+ expect(notice.kind).toBe('info');+ const argvs = notice.decisions![0]!.options.map(o => o.argv!.join(' '));+ expect(argvs.some(a2 => a2.includes('companies/client-b-example'))).toBe(true);+ });++ test('grouping inherits the read policy: a remote caller never sees a group or candidate for a private fact', async () => {+ await setFlag(GROUP_BY_ENTITY_KEY, 'on');+ const r = await recall({ question: PRICE, limit: 10 }, true);+ expect((r.facts_groups as R[]).map(g => g.entity_slug)).not.toContain('companies/client-c-example');+ expect(r.entity_unspecified.candidates.map((c: R) => c.entity_slug)).not.toContain('companies/client-c-example');+ expect(markers(r.facts)).not.toContain('PRICEC');+ });++ test('grouping runs after the limit cut, and a call that names an entity is never grouped', async () => {+ await setFlag(GROUP_BY_ENTITY_KEY, 'on');+ const flat = await recall({ question: PRICE, limit: 1 });+ expect(flat.facts).toHaveLength(1);+ expect(flat.facts_groups).toHaveLength(1);+ expect(flat).not.toHaveProperty('entity_unspecified');+ const scoped = await recall({ question: PRICE, entity: 'companies/client-a-example' });+ expect(scoped).not.toHaveProperty('facts_groups');+ expect(markers(scoped.facts).every(m => m === 'PRICEA' || m === 'TERMSA')).toBe(true);+ });+ });+}