Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge remote-tracking branch 'origin/master' into capy/p2-hub-dampening-explain-date-grounding

garrytan37fed20d64b7
diff --cc docs/architecture/key-files/graph-and-facts.md
index f3e6831d65,883b5c1f36..5a67bf202c
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@@ -100,7 -100,6 +100,7 @@@ rejection of serve-only flags before a
- `src/core/extraction-review.ts` — Extraction quarantine lane markers, sibling of `src/core/quarantine.ts` / `embed-skip.ts` (frontmatter-key pattern, no schema migration). Auto-extracted stubs from untrusted input carry the PAIR `provenance: 'auto-extracted'` + `status: 'unverified'` (both required — user pages with their own `status`/`provenance` never match). Exports `quarantineMarkers()`, `isUnverifiedExtraction()` (JS predicate) and `unverifiedExtractionFragment(alias)` — the single SQL source of truth consumed by `buildSourceFactorCase` (namespace source-boost guard), both engines' `getUnverifiedExtractionPageIds`, the `extraction_pending` op, and the `unverified_extractions` doctor check, so filter and marker keys can never drift. Consequences: unverified stubs are excluded from the compiled-truth fusion boost + the `people/`/`companies/` source-boost (rank as ordinary content), stamped `unverified: true` in search results (`stampUnverifiedExtractions`, hybrid.ts), listed by `extraction_pending`, promoted (status → `verified`, provenance kept for audit) or rejected (soft-delete) by the owner-only `extraction_review` op. Pinned by `test/extraction-review.test.ts` (PGLite) + `test/e2e/extraction-review-postgres.test.ts` (live Postgres parity).
- `src/core/facts-fence.ts` — the `## Facts` fence primitives: parse (`parseFactsFence`; a confidence cell outside 0..1 or not a plain number is `FACTS_TABLE_MALFORMED`, a `claim_value` cell parses strictly (plain/scientific numbers, `1,234,567` separators, a leading currency symbol, a k/M/B suffix that scales; anything else such as `1,5` or `0.9abc` is `FACTS_TABLE_MALFORMED`), `formatFenceDate` writes UTC-midnight dates as `YYYY-MM-DD` and any other instant as a UTC timestamp so TTLs and write-time `valid_from` round-trip, so the page is non-authoritative instead of failing the DB CHECK), render (`renderFactsTable`), and strip (`stripFactsFence({keepVisibility})` — the remote-read privacy boundary `get_page`/`fetch_page`/the chunker apply), plus the remote write-back merge, plus the ONE fence-placement rule: `replaceOrInsertFactsFence(body, fenceBlock)` replaces an existing fence in place or inserts a fresh `## Facts` section ABOVE the timeline sentinel (`timelineSentinelOffset`, #4756 — below it splitBody() files the fence into page.timeline where extract_facts refuses to reconcile it), EOF only when the page has no sentinel; every writer that materializes a fence (`upsertFactRow`, the phantom-redirect canonical append, the importer's hidden-row merge) routes through it, so no writer can re-grow its own EOF append. `restoreHiddenFactRows(incoming, existing)` is the row-level, visibility-aware merge `import-file.ts` applies per fence-bearing column (compiled_truth AND timeline) when a remote caller writes back a page it read with hidden rows stripped — without it, a remote get→edit→put round-trip would silently drop every non-`world` fact row. Rules: only non-`world` rows of the existing fence are restoration candidates (a caller's deletion of a VISIBLE row stays honored — world rows are never restored); a hidden row whose rowNum is absent from the incoming fence is restored at its stable rowNum (cross-page `#F<N>` refs survive); a rowNum collision (a caller-authored addition landing on a hidden number the caller never saw) keeps the hidden row's number and renumbers the CALLER's row onto fresh appended numbers (upsertFactRow's append-only contract); same rowNum + same claim keeps the incoming version (idempotent full-content write-throughs); either side parsing with warnings returns null — re-rendering a fence that didn't fully parse would drop the caller's unparsed rows — and `factsGapWarning` surfaces exactly that residual loss. Pure and side-effect-free. Pinned by `test/facts-fence.test.ts` + the remote write-back describes in `test/privacy-strip-and-forget.test.ts` (row-level merge, world-only deletion honored, timeline-embedded fence round-trip).
- - `src/core/facts/attribution.ts` — speaker attribution's one dedup rule: `attributionCompatible(a, b)` is false only for two different known speakers (`user`, `assistant`, `other`); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: `findCandidateDuplicates` (`attributedTo` option, SQL pre-limit), `decideSingleFact` exact and cosine matches, capture exact/near matches, hot-memory collapse (`collapseHotFacts` splits a fingerprint group by speaker when it holds two), fence reindex (`duplicateActiveFenceRows`) and the managed batch key (`facts-prepare.ts`). `facts.attributed_to` (migration v213) is written by the extractor (`facts.attribution`, default on per `docs/eval/decisions/p2-e3-heldout/`; `false` opts out), carried in the fence's 15th cell (only on rows that have it), returned by `recall` and hot memory, rendered `(assistant said)` in context packs, and kept out of `consolidate` (takes are the user's own). Pinned by `test/facts/speaker-attribution.test.ts`.
++- `src/core/facts/attribution.ts` — speaker attribution's one dedup rule: `attributionCompatible(a, b)` is false only for two different known speakers (`user`, `assistant`, `other`); NULL (no recorded speaker) is compatible with either. Every dedup path applies it before candidate limits: `findCandidateDuplicates` (`attributedTo` option, SQL pre-limit), `decideSingleFact` exact and cosine matches, capture exact/near matches, hot-memory collapse (`collapseHotFacts` splits a fingerprint group by speaker when it holds two), fence reindex (`duplicateActiveFenceRows`) and the managed batch key (`facts-prepare.ts`). `facts.attributed_to` (migration v214) is written by the extractor (`facts.attribution`, default on per `docs/eval/decisions/p2-e3-heldout/`; `false` opts out), carried in the fence's 15th cell (only on rows that have it), returned by `recall` and hot memory, rendered `(assistant said)` in context packs, and kept out of `consolidate` (takes are the user's own). Pinned by `test/facts/speaker-attribution.test.ts`.
- `src/core/fence-shared.ts` — shared pipe-table primitives for the `## Takes` (`takes-fence.ts`) and `## Facts` (`facts-fence.ts`) fences: `parseRowCells`, `isSeparatorRow`, `stripStrikethrough`, `parseStringCell`, `escapeFenceCell`. `parseRowCells` is escape-aware: `\|` stays inside its cell and decodes back to a literal `|` (exact inverse of `escapeFenceCell`), while any other backslash passes through verbatim so existing fence text (e.g. Windows paths) is byte-stable across a render → parse cycle. This matters because the fence is canonical and reconcile is wipe-and-reinsert — a pipe inside a cell shifting the column layout would corrupt every row behind it on the next reconcile. Pinned by the escape cases in `test/facts-fence.test.ts` + the full render → parse → reconcile round-trip in `test/e2e/facts-fence-reconcile-postgres.test.ts`.
diff --cc scripts/module-size-limits.tsv
index 96b418d1e9,fe8af68231..8f94f7c86d
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@@ -34,9 -34,9 +34,9 @@@ src/commands/sources.ts 2042 ratchet +
src/core/link-extraction.ts 2158 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note
src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verify
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
- src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
+ src/commands/hook.ts 1915 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; +12 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
- src/core/config.ts 1874 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +2 P2 extraction.date_grounding / facts.attribution / search.hub_dampening keys
-src/core/config.ts 1875 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +3 core memory: memory.core.* and memory.pressure.* known keys
++src/core/config.ts 1877 ratchet +8 #5988: sync.holds/hold_cap/hold_escalate_count/hold_escalate_pct/parser_regression key registration (read by persistence/sync-holds.ts); +3 agent operator wave A4: GBrainConfig.consent file-plane slot + 2 consent.preapprove.* key rows (logic in core/consent.ts); +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +3 cat40 cost wave C1 (garrytan/gbrain-evals#57 follow-ups): mcp.result_rows GBrainConfig slot + key row (resolver in mcp/result-rows.ts); v0.60.46.0 merge: both waves' +3 compose (1824 + 3 = 1827 measured); +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (1838 measured); +3 retrieval feedback: the feedback keys in KNOWN_CONFIG_KEYS; 2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x engine graduation composition: both deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); P3 x aow-followup composition: deltas re-summed at the merge; 2 Lane D: facts.drain_budget_usd, facts.drain_daily_budget_usd, facts.drain_max_jobs key registration (validated in core/facts/drain.ts); +2 engine graduation (GBRA-50 G3): GBrainConfig.migrate.graduation file-plane opt-out slot + key row (read by commands/migrate-graduation.ts); +1 GBRA-49: graph.* key prefix (graph.edge_validity, read by link-validity.ts); +3 P7 search.relational_planner / search.relational_orient_onehop key registration; +2 P7 search.relational_chain_slots key registration; +3 agent operator follow-up Item 2: mcp.allow_session_widen (GBrainConfig.mcp slot + known key); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts); cat40 entity wave merge with v0.60.61.0 (1853 measured); P3 x cat40-entity-wave composition: deltas re-summed at the merge; +6 fix wave lane B3: chat_fallback_on_refusal (GBrainConfig slot, GBRAIN_CHAT_FALLBACK_ON_REFUSAL env fold, known key); +2 W-B4: shared_skills.inventory.* known keys (logic in shared-skills/inventory-limits.ts); +2 fix wave 9 lane B #4921: ai.chat.per_turn_timeout_ms known key; +1 wave 9 lane W #5363: cycle.consolidate.cluster_threshold key row; +1 #5984 lanes: sync.lanes key registration; +2 P8: dream.quote_verify and think.quote_verify known keys; +2 P8: GBrainConfig.mcp.advertised_surface interface slot (resolver in mcp/surface.ts); +3 core memory: memory.core.* and memory.pressure.* known keys; +2 P2 extraction.date_grounding / facts.attribution / search.hub_dampening keys
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 663 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts)
diff --cc src/core/engine.ts
index bae8036b16,9a4f63a76e..5cdf61355d
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@@ -539,17 -539,8 +539,17 @@@ export interface FactRow
fact_fingerprint?: string;
/** Set by `listFactsKeyset`: created_at at the column's microsecond precision (ISO UTC). */
created_at_iso?: string;
- /** Who asserted the claim (migration v213); null when attribution is unavailable. */
++ /** Who asserted the claim (migration v214); null when attribution is unavailable. */
+ attributed_to?: FactAttribution | null;
}
+/**
+ * Who asserted a saved fact: the user, the assistant (a recommendation, answer
+ * or plan it gave), or a named third party. Never whether the claim is true or
+ * was accepted. NULL means attribution is unavailable.
+ */
+export type FactAttribution = 'user' | 'assistant' | 'other';
+
/** Input for insertFact. source_id supplied via the ctx arg. */
export interface NewFact {
embedding_model?: string | null;
@@@ -594,8 -585,6 +594,8 @@@
* set this — leaving it undefined preserves pre-v0.40 behavior.
*/
event_type?: string | null;
- /** Speaker attribution (migration v213). Undefined/null → NULL (unavailable). */
++ /** Speaker attribution (migration v214). Undefined/null → NULL (unavailable). */
+ attributed_to?: FactAttribution | null;
}
/** Options shared by list-facts methods. */
diff --cc src/core/schema-migrations/registry.generated.ts
index f0ac20be08,0d6bbcb732..f6d3241dfd
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -213,7 -213,7 +213,8 @@@ import { v209 } from './v209-page-facts
import { v210 } from './v210-clamp-oauth-token-ttl.ts';
import { v211 } from './v211-function-search-path.ts';
import { v212 } from './v212-decide-review-proposals.ts';
- import { v213 } from './v213-facts-attributed-to.ts';
+ import { v213 } from './v213-core-edit-notices.ts';
++import { v214 } from './v214-facts-attributed-to.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -426,4 -426,4 +427,5 @@@ export const MIGRATIONS: Migration[] =
v211,
v212,
v213,
++ v214,
];
diff --cc src/core/schema-migrations/v214-facts-attributed-to.ts
index fb5aab97bf,0000000000..2577c6229d
mode 100644,000000..100644
--- a/src/core/schema-migrations/v214-facts-attributed-to.ts
+++ b/src/core/schema-migrations/v214-facts-attributed-to.ts
@@@ -1,24 -1,0 +1,24 @@@
+import type { Migration } from './types.ts';
+import { WRITE_ATTRIBUTION_SCHEMA_SQL } from '../persistence/attribution-schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Speaker attribution: who asserted a saved fact ('user', 'assistant' or a
+// named 'other' party), written by the conversation-facts extractor when
+// `facts.attribution` is on (the default). NULL means attribution is unavailable (older
+// facts, non-conversation text) and is compatible with either speaker in
+// every dedup path. Nullable with no default: metadata-only on Postgres 11+
+// and PGLite, no backfill. The facts table is created by migrations only
+// (v045), so there is no schema.sql mirror. The column is canonical content
+// (attribution-schema.ts), so the write-attribution trigger function is
+// re-created here to include it in the content-change comparison.
- export const v213: Migration = {
- version: 213,
++export const v214: Migration = {
++ version: 214,
+ name: 'facts_attributed_to',
+ idempotent: true,
+ sql: `
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS attributed_to TEXT
+ CHECK (attributed_to IN ('user', 'assistant', 'other'));
+ ${WRITE_ATTRIBUTION_SCHEMA_SQL}`,
+};
diff --cc test/facts/speaker-attribution.test.ts
index dbe2c6e341,0000000000..c3714cb087
mode 100644,000000..100644
--- a/test/facts/speaker-attribution.test.ts
+++ b/test/facts/speaker-attribution.test.ts
@@@ -1,222 -1,0 +1,222 @@@
+/**
- * Speaker attribution on saved facts (`facts.attribution`, migration v213).
++ * Speaker attribution on saved facts (`facts.attribution`, migration v214).
+ *
+ * Protects: the attribution variant asks for and parses `attributed_to`
+ * (anything outside user|assistant|other parses as null) and the default
+ * variant never emits it; the column round-trips through insertFact /
+ * insertFacts / list reads and rejects unknown speakers; the fence writes a
+ * 15th cell only on rows that carry a speaker, older 10- and 14-cell rows
+ * keep their width, an unknown value is a malformed row; every dedup path
+ * treats two different known speakers as distinct claims while NULL stays
+ * compatible with either (candidate lookup, exact single-fact match, fence
+ * reindex, managed batch key via the shared rule, capture exact match,
+ * hot-memory collapse); consolidate never promotes an assistant claim into
+ * the user's takes; recall and the context-pack line carry the speaker.
+ * Seams: gateway chat transport stub; in-memory PGLite.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { configureGateway, resetGateway, __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';
+import { extractFactsFromTurnWithOutcome, parseExtractorJson } from '../../src/core/facts/extract.ts';
+import { attributionCompatible } from '../../src/core/facts/attribution.ts';
+import { parseFactsFence, renderFactsTable, upsertFactRow, type ParsedFact } from '../../src/core/facts-fence.ts';
+import { duplicateActiveFenceRows, extractFactsFromFenceText } from '../../src/core/facts/extract-from-fence.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { decideSingleFact } from '../../src/core/facts/single-prepare.ts';
+import { collapseHotFacts, findCaptureDuplicate } from '../../src/core/facts/capture-dedup.ts';
+import { renderFactLine } from '../../src/core/context/turn-context.ts';
+import { runPhaseConsolidate } from '../../src/core/cycle/phases/consolidate.ts';
+import { operationsByName } from '../../src/core/operations.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+
+function chatResult(text: string): ChatResult {
+ return {
+ text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
+ } as ChatResult;
+}
+
+describe('extractor field', () => {
+ beforeEach(() => {
+ resetGateway();
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ });
+ afterAll(() => {
+ __setChatTransportForTests(null);
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { ...process.env } });
+ });
+
+ const reply = { facts: [
+ { fact: 'Assistant recommended the Harbor Hostel in Amsterdam', kind: 'fact', notability: 'high', entity: null, attributed_to: 'assistant' },
+ { fact: 'User is planning a trip to Amsterdam', kind: 'event', notability: 'high', entity: null, attributed_to: 'user' },
+ { fact: 'User likes canals', kind: 'preference', notability: 'high', entity: null, attributed_to: 'narrator' },
+ ] };
+ async function run(variant: { attribution?: boolean }) {
+ const seen: ChatOpts[] = [];
+ __setChatTransportForTests(async (opts) => { seen.push(opts); return chatResult(JSON.stringify(reply)); });
+ const outcome = await extractFactsFromTurnWithOutcome({ turnText: 'User: any hostel near the center?\nAssistant: Try the Harbor Hostel.', source: 'test:attribution', variant, embedding: null });
+ return { seen, facts: outcome.ok ? outcome.facts : [] };
+ }
+
+ test('attribution on: the schema asks for the speaker and each fact keeps it; an unknown speaker parses as null', async () => {
+ const { seen, facts } = await run({ attribution: true });
+ expect(JSON.stringify(seen[0].responseSchema)).toContain('attributed_to');
+ expect(seen[0].system).toContain('"attributed_to"');
+ expect(facts.map(f => f.attributed_to ?? null)).toEqual(['assistant', 'user', null]);
+ });
+
+ test('attribution off: no speaker in the schema and none on the facts', async () => {
+ const { seen, facts } = await run({});
+ expect(JSON.stringify(seen[0].responseSchema)).not.toContain('attributed_to');
+ expect(facts.every(f => f.attributed_to === undefined)).toBe(true);
+ });
+
+ test('parser accepts exactly the three speakers', () => {
+ const parsed = parseExtractorJson(JSON.stringify({ facts: ['user', 'assistant', 'other', 'Assistant', 7].map(a => ({ fact: 'x', kind: 'fact', attributed_to: a })) }))!;
+ expect(parsed.map(p => p.attributed_to)).toEqual(['user', 'assistant', 'other', null, null]);
+ });
+});
+
+describe('the compatibility rule', () => {
+ test('different known speakers are incompatible; null is compatible with either', () => {
+ expect(attributionCompatible('user', 'assistant')).toBe(false);
+ expect(attributionCompatible('assistant', 'other')).toBe(false);
+ expect(attributionCompatible('user', 'user')).toBe(true);
+ expect(attributionCompatible(null, 'assistant')).toBe(true);
+ expect(attributionCompatible(undefined, null)).toBe(true);
+ });
+});
+
+describe('fence column', () => {
+ const row = (rowNum: number, over: Partial<ParsedFact> = {}): ParsedFact => ({
+ rowNum, claim: `claim ${rowNum}`, kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium',
+ validFrom: '2026-03-10', source: 'test', active: true, ...over,
+ });
+ const dataRows = (table: string) => table.split('\n').filter(l => /^\| \d/.test(l));
+ const cells = (line: string) => line.split('|').length - 2;
+
+ test('no attributed row → the 10-cell table, unchanged', () => {
+ const table = renderFactsTable([row(1), row(2)]);
+ expect(table).not.toContain('attributed_to');
+ expect(dataRows(table).map(cells)).toEqual([10, 10]);
+ });
+
+ test('mixed rows: only the attributed row is 15 cells wide, typed cells padded; parse round-trips', () => {
+ const table = renderFactsTable([row(1), row(2, { attributedTo: 'assistant' }), row(3, { claimMetric: 'mrr', claimValue: 5 })]);
+ expect(table).toContain('| claim_period | attributed_to |');
+ expect(dataRows(table).map(cells)).toEqual([14, 15, 14]);
+ const parsed = parseFactsFence(table);
+ expect(parsed.warnings).toEqual([]);
+ expect(parsed.facts.map(f => f.attributedTo)).toEqual([undefined, 'assistant', undefined]);
+ expect(parsed.facts[2].claimValue).toBe(5);
+ expect(renderFactsTable(parsed.facts)).toBe(table);
+ });
+
+ test('an unrelated row upsert keeps the speaker cell; an unknown speaker is a malformed row', () => {
+ const body = upsertFactRow(upsertFactRow('', { claim: 'Assistant recommended X', kind: 'fact', confidence: 1, visibility: 'private', notability: 'high', attributedTo: 'assistant' }).body,
+ { claim: 'User likes Y', kind: 'preference', confidence: 1, visibility: 'private', notability: 'high' }).body;
+ expect(parseFactsFence(body).facts.map(f => f.attributedTo)).toEqual(['assistant', undefined]);
+ const bad = body.replace('| assistant |', '| narrator |');
+ const parsed = parseFactsFence(bad);
+ expect(parsed.facts).toHaveLength(1);
+ expect(parsed.warnings.join(' ')).toContain('unknown attributed_to "narrator"');
+ });
+
+ test('reindex: the speaker reaches the row; same text from two speakers is not a duplicate, a null copy is', () => {
+ const facts = [row(1, { claim: 'Lisbon in May', attributedTo: 'user' }), row(2, { claim: 'Lisbon in May', attributedTo: 'assistant' }), row(3, { claim: 'Lisbon in May' })];
+ expect([...duplicateActiveFenceRows(facts)]).toEqual([3]);
+ expect(extractFactsFromFenceText([facts[1]], 'people/alice-example', 'default')[0].attributed_to).toBe('assistant');
+ });
+});
+
+describe('storage and dedup (PGLite)', () => {
+ let engine: PGLiteEngine;
+ const emb = (x: number) => { const v = new Float32Array(1536); v[0] = x; v[1] = 1 - x; v[2] = 0.1; return v; };
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Alice.' });
+ }, 120_000);
+ afterAll(async () => { if (engine) await engine.disconnect(); });
+
+ test('insertFact and insertFacts store the speaker; reads return it only when set; the column rejects unknown speakers', async () => {
+ const a = await engine.insertFact({ fact: 'Assistant recommended the Harbor Hostel', source: 'test', entity_slug: 'people/alice-example', attributed_to: 'assistant' }, { source_id: 'default' });
+ await engine.insertFacts([{ fact: 'Alice prefers trains', source: 'test', entity_slug: 'people/alice-example', attributed_to: 'user', row_num: 1, source_markdown_slug: 'people/alice-example' }], { source_id: 'default' });
+ const plain = await engine.insertFact({ fact: 'Alice lives in Porto', source: 'test', entity_slug: 'people/alice-example' }, { source_id: 'default' });
+ const rows = await engine.listFactsByEntity('default', 'people/alice-example', { activeOnly: true });
+ const by = new Map(rows.map(r => [r.fact, r]));
+ expect(by.get('Assistant recommended the Harbor Hostel')!.attributed_to).toBe('assistant');
+ expect(by.get('Alice prefers trains')!.attributed_to).toBe('user');
+ expect('attributed_to' in by.get('Alice lives in Porto')!).toBe(false);
+ expect(rows.find(r => r.id === a.id)).toBeDefined();
+ expect(plain.status).toBe('inserted');
+ await expect(engine.executeRaw(`UPDATE facts SET attributed_to='narrator' WHERE id=$1`, [plain.id])).rejects.toThrow();
+ });
+
+ test('candidate lookup drops other speakers before the k cap and keeps NULL rows', async () => {
+ await engine.executeRaw(`DELETE FROM facts`);
+ const ids: Record<string, number> = {};
+ for (const [fact, speaker, x] of [['Hostel pick: Harbor', 'assistant', 0.9], ['Hostel pick: Harbor!', 'user', 0.91], ['Hostel pick Harbor', null, 0.92]] as const) {
+ ids[fact] = (await engine.insertFact({ fact, source: 'test', entity_slug: 'people/alice-example', attributed_to: speaker, embedding: emb(x), embedding_model: 'test:emb' }, { source_id: 'default' })).id;
+ }
+ const facts = (rows: Array<{ fact: string }>) => rows.map(r => r.fact).sort();
+ expect(facts(await engine.findCandidateDuplicates('default', 'people/alice-example', 'q', { embedding: emb(0.9), embeddingModel: 'test:emb', k: 5, attributedTo: 'user' })))
+ .toEqual(['Hostel pick Harbor', 'Hostel pick: Harbor!']);
+ expect(facts(await engine.findCandidateDuplicates('default', 'people/alice-example', 'q', { k: 5, attributedTo: 'assistant' })))
+ .toEqual(['Hostel pick Harbor', 'Hostel pick: Harbor']);
+ expect(await engine.findCandidateDuplicates('default', 'people/alice-example', 'q', { k: 5 })).toHaveLength(3);
+ });
+
+ test('exact single-fact match and capture exact match ignore the same text from another speaker', async () => {
+ await engine.executeRaw(`DELETE FROM facts`);
+ const assistant = await engine.insertFact({ fact: 'Book the Harbor Hostel', source: 'test', entity_slug: 'people/alice-example', visibility: 'private', attributed_to: 'assistant' }, { source_id: 'default' });
+ const intent = { fact: 'Book the Harbor Hostel', kind: 'fact' as const, visibility: 'private' as const, entity_slug: 'people/alice-example' };
+ expect((await decideSingleFact(engine, 'default', { ...intent, attributed_to: 'user' }, null)).status).toBe('inserted');
+ expect((await decideSingleFact(engine, 'default', { ...intent, attributed_to: 'assistant' }, null)).candidate?.id).toBe(assistant.id);
+ expect((await decideSingleFact(engine, 'default', intent, null)).candidate?.id).toBe(assistant.id);
+ const scope = { engine, sourceId: 'default', lane: 'test', sessionId: null, anchor: new Date() };
+ const candidate = { fact: 'Book the Harbor Hostel', entitySlug: 'people/alice-example', visibility: 'private' as const };
+ expect(await findCaptureDuplicate(scope, { ...candidate, attributedTo: 'user' })).toBeNull();
+ expect((await findCaptureDuplicate(scope, { ...candidate, attributedTo: 'assistant' }))?.id).toBe(assistant.id);
+ });
+
+ test('hot-memory collapse keeps the user and the assistant version of one claim apart', async () => {
+ await engine.executeRaw(`DELETE FROM facts`);
+ for (const speaker of ['user', 'assistant', 'assistant'] as const) {
+ await engine.insertFact({ fact: 'Harbor Hostel in May', source: 'test', entity_slug: 'people/alice-example', attributed_to: speaker }, { source_id: 'default' });
+ }
+ const rows = await engine.listFactsSince('default', new Date(0), { activeOnly: true, fingerprint: true });
+ const collapsed = await collapseHotFacts(engine, 'default', rows);
+ expect(collapsed.map(r => r.attributed_to).sort()).toEqual(['assistant', 'user']);
+ });
+
+ test('consolidate never promotes assistant claims into the user\'s takes', async () => {
+ await engine.executeRaw(`DELETE FROM facts`);
+ const old = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
+ for (let i = 0; i < 3; i++) {
+ await engine.insertFact({ fact: `Assistant recommended the Harbor Hostel (${i})`, source: 'test', entity_slug: 'people/alice-example', attributed_to: 'assistant', valid_from: old, embedding: emb(0.5), embedding_model: 'test:emb' }, { source_id: 'default' });
+ }
+ const result = await runPhaseConsolidate(engine, { sourceId: 'default' });
+ expect(result.status).not.toBe('fail');
+ const [{ n }] = await engine.executeRaw<{ n: number }>(`SELECT COUNT(*)::int AS n FROM facts WHERE consolidated_at IS NOT NULL`);
+ expect(n).toBe(0);
+ });
+
+ test('recall returns the speaker; the context-pack line marks assistant claims', async () => {
+ await engine.executeRaw(`DELETE FROM facts`);
+ await engine.insertFact({ fact: 'Assistant recommended the Harbor Hostel', source: 'test', entity_slug: 'people/alice-example', attributed_to: 'assistant' }, { source_id: 'default' });
+ await engine.insertFact({ fact: 'Alice lives in Porto', source: 'test', entity_slug: 'people/alice-example' }, { source_id: 'default' });
+ const ctx = { engine, remote: false, sourceId: 'default', config: { engine: 'pglite' }, dryRun: false,
+ logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;
+ const out = await operationsByName.recall.handler(ctx, { entity: 'people/alice-example' }) as { facts: Array<Record<string, unknown>> };
+ const by = new Map(out.facts.map(f => [f.fact, f]));
+ expect(by.get('Assistant recommended the Harbor Hostel')!.attributed_to).toBe('assistant');
+ expect('attributed_to' in by.get('Alice lives in Porto')!).toBe(false);
+ const line = (attributed_to?: 'assistant' | 'user') => renderFactLine({ id: 1, fact: 'Harbor Hostel', kind: 'fact', entity_slug: null, confidence: 1, ...(attributed_to ? { attributed_to } : {}) });
+ expect(line('assistant')).toBe('- (assistant said) Harbor Hostel (1.00)');
+ expect(line('user')).toBe('- Harbor Hostel (1.00)');
+ expect(line()).toBe('- Harbor Hostel (1.00)');
+ });
+});
diff --cc test/schema-bootstrap-coverage.test.ts
index 98b043beb3,dcbd5cd7e8..e183e376af
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@@ -961,10 -961,6 +961,10 @@@ const COLUMN_EXEMPTIONS = new Set<strin
// brains is invisible to them). Migration is column-only, no FK,
// no index — bootstrap probe would be pure overhead.
'facts.event_type',
- // migration v213 — speaker attribution. The facts table is migration-created
++ // migration v214 — speaker attribution. The facts table is migration-created
+ // (absent from PGLITE_SCHEMA_SQL), so no schema-blob forward reference can
+ // exist; nullable column only, no index or FK.
+ 'facts.attributed_to',
// v0.42.56.0 (migration v122, #2390) — Life Chronicle ontology columns.
// Same precedent as facts.claim_metric et al: the `facts` table itself is
// migration-created (absent from PGLITE_SCHEMA_SQL), so no schema-blob