Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(facts): facts.attribution defaults on (held-out verdict p2-e3-heldout: PASS)

garrytane1bc38067e90
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 67b0d0fafc..4f5c2eb1f7 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -100,7 +100,7 @@ rejection of serve-only flags before a brain opens.
- `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 v208) is written by the extractor when `facts.attribution` is on, 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 v208) 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 --git a/docs/eval/decisions/p2-e3-heldout/README.md b/docs/eval/decisions/p2-e3-heldout/README.md
new file mode 100644
index 0000000000..70229f411e
--- /dev/null
+++ b/docs/eval/decisions/p2-e3-heldout/README.md
@@ -0,0 +1,43 @@
+# Speaker attribution: held-out verdict (PASS)
+
+This is the sealed E3 run under preregistration amendment 2 (gbrain-evals `docs/benchmarks/2026-10-04-p2-ranking-extraction-preregistration.md`).
+The evaluation custodian ran it on build 6fa1a77b3, using 60 sealed synthetic user–assistant conversations across five
+case families: rejection, quotation, correction, repeated suggestion and acceptance.
+
+The candidate was `facts.attribution=true`. The baseline was the same build with the setting absent. Both arms ran
+gbrain's conversation-facts extractor through the decision kit's facts lane, with two extractions per arm, and a fixed
+reader that answers from the saved facts of the top five sessions with 5 replicates.
+
+| Gate | Baseline → candidate | 95% CI | Result |
+|---|---|---|---|
+| Primary: assistant-said QA from saved facts | 44.1% → 95.8% (+51.7 pts; 73 wins, 0 losses) | [+42.9, +60.3] | pass |
+| Guard 1: user-said QA from saved facts (lower bound ≥ −2 pts) | 97.2% → 98.6% | [−0.4, +3.4] | pass |
+| Guard 2: rejected suggestions saved as the user's plan | 0 confirmed | — | pass |
+| Guard 3: stored speaker correct (≥ 90% of 200 sampled facts) | 194 / 200 (97%) | — | pass |
+
+**Guard 2 adjudication.** The pinned judge flagged 32 of 1,208 candidate facts in the rejection family. The custodian read
+all 32 and confirmed none. Each one was one of these:
+- an assistant recommendation that matched the user's own plan;
+- a neutral note;
+- a choice the user made themselves.
+
+**Reported only.**
+- **Facts per conversation: +41%** with attribution on. The extractor now saves what the assistant said (answers,
+ recommendations, plans) as its own facts, where the baseline dropped it. Storage, extraction output tokens and
+ hot-memory volume grow by about that much on assistant-heavy conversations.
+- **Guard 3 method:** the judge located each fact's source turn itself, because `facts.ndjson` records the session but
+ not the turn.
+
+## Default
+
+`facts.attribution` defaults on. `false`, `off` or `0` opts out. With it on:
+- the extractor phrases assistant claims as their own facts ("Assistant recommended …") and stores
+ `facts.attributed_to`;
+- dedup never merges claims from different known speakers;
+- recall and hot memory return the speaker, and context packs render "(assistant said)";
+- `consolidate` never promotes an assistant claim into the user's takes.
+
+Facts saved earlier keep `attributed_to` NULL (unknown) and stay compatible with either speaker.
+
+Development records: `../p2-attribution-gate-dev/` (the facts lane trailed pages by 73 pts on assistant-said questions)
+and `../p2-attribution-dev/`.
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 659d6b71d6..eff0570e43 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -111,9 +111,10 @@ export async function getFactsExtractionPromptAppendix(
/**
* Extraction prompt variants. `extraction.date_grounding` defaults ON for fact
* extraction (held-out verdict p2-e2-heldout-2026-10-04: unresolved relative
- * dates in saved facts 8.95% -> 2.05%, QA non-inferior); `false` / `off` / `0`
- * opt out. `facts.attribution` stays off until its own verdict: `true` / `on`
- * / `1` enable it.
+ * dates in saved facts 8.95% -> 2.05%, QA non-inferior). `facts.attribution`
+ * defaults ON (held-out verdict p2-e3-heldout: assistant-said QA from saved
+ * facts 44.1% -> 95.8%, user-said non-inferior). For both, `false` / `off` /
+ * `0` opt out.
*/
export interface ExtractorVariant {
/** Resolve relative dates against the observation date; emit valid_from. */
@@ -130,7 +131,7 @@ const readFlag = (engine: BrainEngine, key: string) => Promise.resolve().then(()
export async function getExtractorVariant(engine?: BrainEngine): Promise<ExtractorVariant> {
if (!engine) return {};
const [grounding, attribution] = await Promise.all([readFlag(engine, 'extraction.date_grounding'), readFlag(engine, 'facts.attribution')]);
- return { dateGrounding: !flagIs(grounding, FLAG_OFF), attribution: flagIs(attribution, FLAG_ON) };
+ return { dateGrounding: !flagIs(grounding, FLAG_OFF), attribution: !flagIs(attribution, FLAG_OFF) };
}
/**
diff --git a/src/core/schema-migrations/v208-facts-attributed-to.ts b/src/core/schema-migrations/v208-facts-attributed-to.ts
index 45ce576113..74eab1afaa 100644
--- a/src/core/schema-migrations/v208-facts-attributed-to.ts
+++ b/src/core/schema-migrations/v208-facts-attributed-to.ts
@@ -6,7 +6,7 @@ import { WRITE_ATTRIBUTION_SCHEMA_SQL } from '../persistence/attribution-schema.
//
// 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. NULL means attribution is unavailable (older
+// `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
diff --git a/test/facts-extract-junk-filter.test.ts b/test/facts-extract-junk-filter.test.ts
index abb904eb7c..bc6dfe7f36 100644
--- a/test/facts-extract-junk-filter.test.ts
+++ b/test/facts-extract-junk-filter.test.ts
@@ -223,8 +223,8 @@ afterAll(() => {
describe('extraction_prompt_appendix — composes with BOTH prompt variants (#3852)', () => {
const APPENDIX = 'Durable-vs-ephemeral rubric: work-session narration is never a fact.';
- // extraction.date_grounding defaults on, so an unconfigured brain gets the grounded variant.
- const GROUNDED = { dateGrounding: true } as const;
+ // extraction.date_grounding and facts.attribution default on, so an unconfigured brain gets both variants.
+ const GROUNDED = { dateGrounding: true, attribution: true } as const;
async function systemSentFor(
engine: BrainEngine,
diff --git a/test/facts/extract-date-grounding.test.ts b/test/facts/extract-date-grounding.test.ts
index cd7fdb71ba..018694b7e1 100644
--- a/test/facts/extract-date-grounding.test.ts
+++ b/test/facts/extract-date-grounding.test.ts
@@ -113,6 +113,11 @@ describe('defaults from the verdicts', () => {
for (const c of ['synthesis', 'atoms', 'takes'] as const) expect(await isConsumerDateGroundingOn(engineWith(null), c)).toBe(true);
expect(await isConsumerDateGroundingOn(engineWith(null), 'chronicle')).toBe(false);
});
+ test('facts.attribution defaults on; false/off/0 opt out', async () => {
+ const attr = (v: string | null) => ({ getConfig: async (k: string) => (k === 'facts.attribution' ? v : null) }) as never;
+ expect((await getExtractorVariant(attr(null))).attribution).toBe(true);
+ for (const v of ['false', 'off', '0']) expect((await getExtractorVariant(attr(v))).attribution).toBe(false);
+ });
test('true turns every prompt on; false turns every prompt off', async () => {
for (const c of ['chronicle', 'synthesis', 'atoms', 'takes'] as const) {
expect(await isConsumerDateGroundingOn(engineWith('true'), c)).toBe(true);