Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(facts): speaker attribution storage — facts.attributed_to (migration v201), extractor field, fence 15th cell, one speaker rule in every dedup path

garrytan9edcdef72113
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 883b5c1f36..1f08ce3467 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -100,6 +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 v201) 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/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/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 44ee6e5371..58c9631cbd 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -84,6 +84,8 @@ export interface TurnContextFact {
created_at?: string;
/** #4206: provenance context (e.g. extract_facts' source_slug). */
context?: string | null;
+ /** Who asserted the claim; rendered so an assistant suggestion never reads as the user's own claim. */
+ attributed_to?: 'user' | 'assistant' | 'other' | null;
confidence: number;
}
@@ -662,6 +664,7 @@ async function assembleDelta(
// #4206: provenance context rides delta like the other projections.
context: r.context ?? null,
confidence: r.confidence,
+ ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),
})),
};
} catch {
@@ -756,7 +759,7 @@ export const renderCardLine = (c: EntityCard): string =>
export const renderThreadLine = (t: EntityOpenThread): string =>
`- [${t.kind}] ${t.text}${t.date ? ` (${t.date})` : ''}`;
export const renderFactLine = (f: TurnContextFact): string =>
- `- ${f.fact}${f.entity_slug ? ` [${f.entity_slug}]` : ''} (${f.confidence.toFixed(2)})`;
+ `- ${f.attributed_to === 'assistant' ? '(assistant said) ' : ''}${f.fact}${f.entity_slug ? ` [${f.entity_slug}]` : ''} (${f.confidence.toFixed(2)})`;
export const renderPageLine = (p: DeltaPage): string => `- **${p.title}** → \`${p.slug}\` (${p.updated_at})`;
const PACK_HEADERS = ['## Standing entities', '## Open threads', '## Hot memory (recent facts)'] as const;
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index 7546f9a357..9e5fc3e750 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -3,7 +3,8 @@
*
* Per /plan-eng-review Phase 5:
*
- * For each (source_id, entity_slug) bucket of unconsolidated active facts:
+ * For each (source_id, entity_slug) bucket of unconsolidated active facts
+ * the user asserted (or with no recorded speaker):
* 1. Skip if count < 3 OR oldest fact age < 24h.
* 2. Cluster by embedding cosine — greedy threshold 0.85.
* 3. For each cluster ≥ 2: pick the highest-confidence fact's text as
@@ -79,6 +80,7 @@ export async function runPhaseConsolidate(
AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until > now())
AND entity_slug IS NOT NULL
+ AND (attributed_to IS NULL OR attributed_to = 'user')
AND ($2::boolean=false OR visibility='world')
AND ($1::text IS NULL OR source_id=$1)
GROUP BY source_id, entity_slug
@@ -116,7 +118,9 @@ export async function runPhaseConsolidate(
visibility: managed ? ['world'] : undefined,
limit: 100,
});
- const unconsolidated = managed ? candidates.filter(f => f.visibility === 'world') : candidates;
+ // Takes here are the user's own (holder 'self'): a claim the assistant or
+ // a named third party asserted is never promoted into one.
+ const unconsolidated = candidates.filter(f => (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));
if (unconsolidated.length < minPerBucket) {
bucketsSkipped += 1;
continue;
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index 3140f33377..e242bba508 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -14,7 +14,7 @@
* `LegacyUnscopedRead`.
*/
import type {
- FactRow, FactKind, FactVisibility, FactInsertStatus,
+ FactRow, FactKind, FactVisibility, FactInsertStatus, FactAttribution,
NewFact, FactListOpts, FactsHealth,
} from '../engine.ts';
import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';
@@ -91,12 +91,12 @@ export async function insertFact(
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
embedding, embedded_at, embedding_model, embedded_text_hash,
- claim_metric, claim_value, claim_unit, claim_period
+ claim_metric, claim_value, claim_unit, claim_period, attributed_to
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
${embedLit === null ? null : trustedSql(vectorLiteralSql(embedLit, castSuffix))}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? sqlFragment`md5(${input.fact})` : null},
- ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
+ ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}, ${input.attributed_to ?? null}
) RETURNING id
`)).rows;
const id = Number(ins[0].id);
@@ -119,12 +119,12 @@ export async function insertFact(
source_id, entity_slug, fact, kind, visibility, notability, context,
valid_from, valid_until, source, source_session, confidence,
embedding, embedded_at, embedding_model, embedded_text_hash,
- claim_metric, claim_value, claim_unit, claim_period
+ claim_metric, claim_value, claim_unit, claim_period, attributed_to
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
${validFrom}, ${validUntil}, ${input.source}, ${sourceSession}, ${confidence},
${embedLit === null ? null : trustedSql(vectorLiteralSql(embedLit, castSuffix))}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? sqlFragment`md5(${input.fact})` : null},
- ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}
+ ${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod}, ${input.attributed_to ?? null}
) RETURNING id
`)).rows;
return Number(ins[0].id);
@@ -236,14 +236,14 @@ export async function insertFacts(
embedding, embedded_at, embedding_model, embedded_text_hash,
row_num, source_markdown_slug,
claim_metric, claim_value, claim_unit, claim_period,
- event_type
+ event_type, attributed_to
) VALUES (
${ctx.source_id}, ${entitySlug}, ${input.fact}, ${kind}, ${visibility}, ${notability}, ${context},
${validFrom}, ${validUntil}, ${expiredAt}, ${input.source}, ${sourceSession}, ${confidence},
${embedLit === null ? null : trustedSql(vectorLiteralSql(embedLit, castSuffix))}, ${embeddedAt}, ${embedding ? input.embedding_model ?? null : null}, ${embedding && input.embedding_model ? sqlFragment`md5(${input.fact})` : null},
${input.row_num}, ${input.source_markdown_slug},
${claimMetric}, ${claimValue}, ${claimUnit}, ${claimPeriod},
- ${eventType}
+ ${eventType}, ${input.attributed_to ?? null}
)
ON CONFLICT (source_id, source_markdown_slug, row_num)
WHERE row_num IS NOT NULL
@@ -519,9 +519,12 @@ export async function findCandidateDuplicates(
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; attributedTo?: FactAttribution | null },
): Promise<FactRow[]> {
const k = Math.min(Math.max(opts?.k ?? 5, 1), 20);
+ const speaker = opts?.attributedTo
+ ? sqlFragment`AND (attributed_to IS NULL OR attributed_to = ${opts.attributedTo})`
+ : sqlFragment``;
// Validity-lapsed rows are not dedup candidates: a re-stated fact after
// its valid_until lapses re-inserts fresh (WP5 read-time TTL honesty).
if (opts?.embedding) {
@@ -537,6 +540,7 @@ export async function findCandidateDuplicates(
AND embedding_model=${opts.embeddingModel} AND embedded_text_hash=md5(fact)
AND vector_dims(embedding)=${opts.embedding.length}
AND source != ALL(${AUDIT_ROW_SOURCES}::text[])
+ ${speaker}
ORDER BY embedding <=> ${trustedSql(vectorLiteralSql(lit, '::vector'))}
LIMIT ${k}
`)).rows;
@@ -548,6 +552,7 @@ export async function findCandidateDuplicates(
AND entity_slug = ${entitySlug}
AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until > now())
+ ${speaker}
ORDER BY created_at DESC, id DESC
LIMIT ${k}
`)).rows;
@@ -697,6 +702,7 @@ interface FactRowSqlShape {
created_at: Date;
fact_fingerprint?: string | null;
created_at_iso?: string | null;
+ attributed_to?: FactAttribution | null;
}
/**
@@ -750,6 +756,7 @@ function rowToFact(raw: FactRowSqlShape): FactRow {
created_at: row.created_at,
...(row.fact_fingerprint ? { fact_fingerprint: row.fact_fingerprint } : {}),
...(row.created_at_iso ? { created_at_iso: row.created_at_iso } : {}),
+ ...(row.attributed_to ? { attributed_to: row.attributed_to } : {}),
};
}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index cef81dc187..13dc4ce5b5 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -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 v201); 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;
@@ -585,6 +594,8 @@ export interface NewFact {
* set this — leaving it undefined preserves pre-v0.40 behavior.
*/
event_type?: string | null;
+ /** Speaker attribution (migration v201). Undefined/null → NULL (unavailable). */
+ attributed_to?: FactAttribution | null;
}
/** Options shared by list-facts methods. */
@@ -2258,13 +2269,15 @@ export interface BrainEngine {
* Find candidate duplicates for a new fact within a source+entity bucket.
* Entity-prefilter is mandatory (bounds the contradiction-classifier blast
* radius). Hard cap k=5 by default. Embedding-cosine when both sides have
- * embeddings; recency fallback otherwise.
+ * embeddings; recency fallback otherwise. `attributedTo` (the new fact's
+ * speaker) drops rows a different known speaker asserted before the k cap;
+ * NULL rows stay candidates.
*/
findCandidateDuplicates(
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; attributedTo?: FactAttribution | null },
): Promise<FactRow[]>;
/**
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index 2d4afb4340..64876a178d 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -58,6 +58,8 @@ export const FACTS_FENCE_END = '<!--- gbrain:facts:end -->';
// markdown contexts (the chunker strip, the CI invariant check) where
// importing engine.ts pulls a large DB-shaped transitive graph.
export type FactKind = 'event' | 'preference' | 'commitment' | 'belief' | 'fact' | 'idea';
+export type FactAttribution = 'user' | 'assistant' | 'other';
+const ATTRIBUTION_VALUES: ReadonlySet<string> = new Set(['user', 'assistant', 'other']);
// Mirror src/core/engine.ts FactVisibility ('private' | 'world'). Binary
// gate per the existing takes D21 contract — drives the chunker strip
@@ -118,6 +120,14 @@ export interface ParsedFact {
claimValue?: number;
claimUnit?: string;
claimPeriod?: string;
+ /**
+ * Speaker attribution (15th column): who asserted the claim. A row carrying
+ * it is written 15 cells wide with the typed-claim cells padded empty;
+ * every other row keeps its width. Parsers that predate the column read
+ * the first 14 cells and ignore the 15th; writers that predate it drop
+ * the cell on rewrite.
+ */
+ attributedTo?: FactAttribution;
}
export interface FactsFenceParseResult {
@@ -239,6 +249,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
claimValueRaw = '',
claimUnitRaw = '',
claimPeriodRaw = '',
+ attributedToRaw = '',
] = cells;
const rowNum = parseInt(rowNumStr, 10);
@@ -286,6 +297,12 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
continue;
}
+ const attributedTo = attributedToRaw.trim().toLowerCase();
+ if (attributedTo && !ATTRIBUTION_VALUES.has(attributedTo)) {
+ warnings.push(`FACTS_TABLE_MALFORMED: unknown attributed_to "${attributedToRaw.trim()}" in row ${rowNumStr} (expected user|assistant|other)`);
+ continue;
+ }
+
const { text: claimText, struck } = stripStrikethrough(claimRaw);
const context = parseStringCell(contextRaw);
const supersededBy = parseSupersededByFromContext(context);
@@ -310,6 +327,7 @@ export function parseFactsFence(body: string): FactsFenceParseResult {
claimValue,
claimUnit: parseStringCell(claimUnitRaw),
claimPeriod: parseStringCell(claimPeriodRaw),
+ ...(attributedTo ? { attributedTo: attributedTo as FactAttribution } : {}),
});
}
@@ -361,18 +379,23 @@ export function renderFactsTable(facts: ParsedFact[]): string {
f.claimUnit !== undefined ||
f.claimPeriod !== undefined,
);
- const header = anyTyped
- ? `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |`
+ // Speaker attribution widens the header to 15; only rows that carry it
+ // are written 15 cells wide (typed cells padded), others keep their width.
+ const anyAttributed = facts.some(f => f.attributedTo !== undefined);
+ const wide = anyTyped || anyAttributed;
+ const header = wide
+ ? `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context | claim_metric | claim_value | claim_unit | claim_period |${anyAttributed ? ' attributed_to |' : ''}`
: `| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |`;
- const separator = anyTyped
- ? `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|`
+ const separator = wide
+ ? `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|--------------|-------------|------------|--------------|${anyAttributed ? '---------------|' : ''}`
: `|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|`;
const rows = facts.map(f => {
const claimCell = f.active ? f.claim : `~~${f.claim}~~`;
const base = `| ${f.rowNum} | ${escapeFenceCell(claimCell)} | ${f.kind} | ${formatConfidence(f.confidence)} | ${f.visibility} | ${f.notability} | ${escapeFenceCell(f.validFrom ?? '')} | ${escapeFenceCell(f.validUntil ?? '')} | ${escapeFenceCell(f.source ?? '')} | ${escapeFenceCell(f.context ?? '')} |`;
- if (!anyTyped) return base;
+ if (!wide) return base;
const valueCell = f.claimValue === undefined ? '' : String(f.claimValue);
- return `${base} ${escapeFenceCell(f.claimMetric ?? '')} | ${escapeFenceCell(valueCell)} | ${escapeFenceCell(f.claimUnit ?? '')} | ${escapeFenceCell(f.claimPeriod ?? '')} |`;
+ const typed = `${base} ${escapeFenceCell(f.claimMetric ?? '')} | ${escapeFenceCell(valueCell)} | ${escapeFenceCell(f.claimUnit ?? '')} | ${escapeFenceCell(f.claimPeriod ?? '')} |`;
+ return f.attributedTo ? `${typed} ${f.attributedTo} |` : typed;
});
// #4615: the leading double-'' emits a BLANK LINE between the begin marker
// and the header. The marker is an HTML block; with only one newline after
@@ -536,6 +559,7 @@ export function upsertFactRow(
claimValue: newRow.claimValue,
claimUnit: newRow.claimUnit,
claimPeriod: newRow.claimPeriod,
+ ...(newRow.attributedTo ? { attributedTo: newRow.attributedTo } : {}),
},
];
diff --git a/src/core/facts/attribution.ts b/src/core/facts/attribution.ts
new file mode 100644
index 0000000000..72da49ea4f
--- /dev/null
+++ b/src/core/facts/attribution.ts
@@ -0,0 +1,17 @@
+/**
+ * Speaker attribution compatibility: the one rule every fact dedup path
+ * applies before candidate limits and similarity decisions.
+ *
+ * `attributed_to` records WHO asserted a claim (user, assistant, a named
+ * other party), never whether it is true or accepted. Two facts asserted by
+ * different known speakers are never duplicates of each other: "Assistant
+ * recommended the Lisbon hostel" must not collapse into, supersede, or be
+ * swallowed by the user's own claim. NULL (attribution unavailable: older
+ * facts, non-conversation text) is compatible with either speaker, so
+ * brains without attribution keep their existing dedup behavior.
+ */
+import type { FactAttribution } from '../engine.ts';
+
+export function attributionCompatible(a: FactAttribution | null | undefined, b: FactAttribution | null | undefined): boolean {
+ return !a || !b || a === b;
+}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 8e40441c28..bcb318712c 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -712,14 +712,14 @@ async function runPipelineBodyInner(
// Dedup against DB candidates (correct per Codex Q7: fence rows
// have no embeddings; FS lock + sync invariant means DB == fence
// at write time). cosineVerdict: 0.95 for explicit lanes; capture lanes never drop by cosine (#5888).
- const exact = resolvedSlug ? await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility }, null) : null;
+ const exact = resolvedSlug ? await decideSingleFact(ctx.engine, ctx.sourceId, { entity_slug: resolvedSlug, fact: f.fact, kind: f.kind ?? 'fact', visibility, attributed_to: f.attributed_to ?? null }, null) : null;
let matchedExistingId: number | null = exact?.candidate?.id ?? null;
if (matchedExistingId === null && resolvedSlug && f.embedding && !f.entity_inferred) {
const candidates = await ctx.engine.findCandidateDuplicates(
ctx.sourceId,
resolvedSlug,
f.fact,
- { embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT },
+ { embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT, attributedTo: f.attributed_to ?? null },
);
let top: { id: number; score: number; fact: string } | null = null;
for (const c of candidates) {
@@ -804,7 +804,7 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
- embedding_model: f.embedding_model ?? null,
+ embedding_model: f.embedding_model ?? null, attributed_to: f.attributed_to ?? null,
// #4206: caller event-time fallback + provenance context. #4819: a
// DB-only row has no fence to name the page it came from, so the page
// path's slug fills context when the caller passed no sourceSlug.
@@ -844,7 +844,7 @@ async function runPipelineBodyInner(
// (historical imports); then import time.
validFrom: f.valid_from ?? ctx.validFrom ?? new Date(),
embedding: f.embedding ?? null,
- embedding_model: f.embedding_model ?? null,
+ embedding_model: f.embedding_model ?? null, attributedTo: f.attributed_to ?? undefined,
sessionId: f.source_session ?? null,
}));
@@ -893,7 +893,7 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
- embedding_model: f.embedding_model ?? null,
+ embedding_model: f.embedding_model ?? null, attributed_to: f.attributed_to ?? null,
// #4206: caller event-time fallback + provenance context.
valid_from: f.valid_from ?? ctx.validFrom,
context: ctx.sourceSlug ?? input.pageSlug ?? null,
@@ -926,7 +926,7 @@ async function runPipelineBodyInner(
source_session: f.source_session ?? null,
confidence: f.confidence,
embedding: f.embedding ?? null,
- embedding_model: f.embedding_model ?? null,
+ embedding_model: f.embedding_model ?? null, attributed_to: f.attributed_to ?? null,
// #4206: caller event-time fallback + provenance context.
valid_from: f.valid_from ?? ctx.validFrom,
context: ctx.sourceSlug ?? input.pageSlug ?? null,
diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.ts
index 677c1117d3..b5d2833323 100644
--- a/src/core/facts/capture-dedup.ts
+++ b/src/core/facts/capture-dedup.ts
@@ -25,7 +25,7 @@
* collapse to the newest row, which carries every entity slug of its group.
*/
-import type { BrainEngine, FactRow } from '../engine.ts';
+import type { BrainEngine, FactAttribution, FactRow } from '../engine.ts';
import { corpusFileSessionId } from '../context/corpus-segments.ts';
import { writeHeartbeat } from '../context/hook-heartbeat.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
@@ -121,6 +121,8 @@ export interface CaptureCandidate {
embedding?: Float32Array | null;
embeddingModel?: string | null;
entityInferred?: unknown;
+ /** Speaker of the candidate; a fact another known speaker asserted never matches. */
+ attributedTo?: FactAttribution | null;
}
export interface CaptureScope {
engine: BrainEngine;
@@ -138,8 +140,9 @@ export async function findCaptureDuplicate(scope: CaptureScope, candidate: Captu
const rows = await scope.engine.executeRaw<{ id: number; entity_slug: string | null; source: string; source_session: string | null; created_at: Date | string }>(
`SELECT id,entity_slug,source,source_session,created_at FROM facts WHERE source_id=$1 AND visibility=ANY($2::text[])
AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3) AND expired_at IS NULL AND (valid_until IS NULL OR valid_until>now())
+ AND ($4::text IS NULL OR attributed_to IS NULL OR attributed_to=$4)
ORDER BY created_at DESC, id DESC LIMIT ${CAPTURE_DEDUP_SCAN_LIMIT}`,
- [scope.sourceId, visibilities, candidate.fact]);
+ [scope.sourceId, visibilities, candidate.fact, candidate.attributedTo ?? null]);
const conversation = canonicalConversationKey(scope.sessionId);
const recent = rows.filter(row => Math.abs(new Date(row.created_at).getTime() - scope.anchor.getTime()) <= CAPTURE_DEDUP_WINDOW_MS
|| conversation !== null && isCaptureLane(row.source) && canonicalConversationKey(row.source_session) === conversation);
@@ -156,7 +159,7 @@ export async function findCaptureDuplicate(scope: CaptureScope, candidate: Captu
export async function findNearDuplicate(scope: CaptureScope, candidate: CaptureCandidate): Promise<number | null> {
if (!candidate.entitySlug || !candidate.embedding || candidate.entityInferred) return null;
const found = await scope.engine.findCandidateDuplicates(scope.sourceId, candidate.entitySlug, candidate.fact,
- { embedding: candidate.embedding, embeddingModel: candidate.embeddingModel, k: 5 });
+ { embedding: candidate.embedding, embeddingModel: candidate.embeddingModel, k: 5, attributedTo: candidate.attributedTo ?? null });
let best: { id: number; score: number; fact: string } | null = null;
for (const row of found) {
if (!row.embedding || row.expired_at || candidate.visibility === 'world' && row.visibility !== 'world') continue;
@@ -172,7 +175,7 @@ export interface CaptureDedupResult<T> { kept: T[]; duplicateIds: number[]; near
* The shared pre-branch check. `resolve` maps an extracted entity reference
* to the slug the writers will use (null when unresolved).
*/
-export async function applyCaptureDedup<T extends { fact: string; entity_slug?: string | null; embedding?: Float32Array | null; embedding_model?: string | null; entity_inferred?: unknown }>(
+export async function applyCaptureDedup<T extends { fact: string; entity_slug?: string | null; embedding?: Float32Array | null; embedding_model?: string | null; entity_inferred?: unknown; attributed_to?: FactAttribution | null }>(
scope: CaptureScope, facts: T[], visibility: 'private' | 'world', resolve: (entity: string | null | undefined) => Promise<string | null>,
): Promise<CaptureDedupResult<T>> {
const started = Date.now();
@@ -180,7 +183,7 @@ export async function applyCaptureDedup<T extends { fact: string; entity_slug?:
let failed = false;
for (const fact of facts) {
const candidate: CaptureCandidate = { fact: fact.fact, entitySlug: await resolve(fact.entity_slug), visibility,
- embedding: fact.embedding, embeddingModel: fact.embedding_model, entityInferred: fact.entity_inferred };
+ embedding: fact.embedding, embeddingModel: fact.embedding_model, entityInferred: fact.entity_inferred, attributedTo: fact.attributed_to ?? null };
try {
const match = await findCaptureDuplicate(scope, candidate);
if (match) {
@@ -207,7 +210,7 @@ export async function applyCaptureDedup<T extends { fact: string; entity_slug?:
* The backstop's entry point: capture lanes only, slugs resolved the way both
* writers resolve them, anchored on the turn time when the lane knows it.
*/
-export async function dedupCapturedFacts<T extends { fact: string; entity_slug?: string | null; embedding?: Float32Array | null; embedding_model?: string | null; entity_inferred?: unknown }>(
+export async function dedupCapturedFacts<T extends { fact: string; entity_slug?: string | null; embedding?: Float32Array | null; embedding_model?: string | null; entity_inferred?: unknown; attributed_to?: FactAttribution | null }>(
ctx: { engine: BrainEngine; sourceId: string; source: string; sessionId: string | null; turnAt?: Date },
facts: T[], visibility: 'private' | 'world',
resolveEntity: (engine: BrainEngine, sourceId: string, raw: string) => Promise<{ slug: string; source: string } | null>,
@@ -236,6 +239,8 @@ export type CollapsedHotFact<R extends HotFactRow> = R & { entity_slugs?: string
* V2 hot-memory collapse: one representative (the newest row) per
* (fingerprint, entity) group; groups of different entities merge only when
* the claim names one of them. Input order is preserved by representative.
+ * A group holding claims from two different known speakers (user and
+ * assistant) also splits by speaker, so one never hides the other.
*/
/** `members` (optional) receives raw row id -> emitted representative id, so delta can advance its facts keyset through raw rows. */
export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine, sourceId: string, rows: R[], members?: Map<number, number>): Promise<CollapsedHotFact<R>[]> {
@@ -251,9 +256,11 @@ export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine
const clusterOf = new Map<R, R[]>();
for (const group of byFingerprint.values()) {
const named = group.some(r => r.entity_slug && claimNamesEntity(r.fact, names.get(r.entity_slug) ?? []));
+ const speakers = new Set(group.flatMap(r => r.attributed_to ? [r.attributed_to] : []));
const clusters = new Map<string, R[]>();
for (const row of group) {
- const key = named ? '*' : row.entity_slug ?? '';
+ const entityKey = named ? '*' : row.entity_slug ?? '';
+ const key = speakers.size > 1 ? `${entityKey}\u0000${row.attributed_to ?? ''}` : entityKey;
clusters.set(key, [...(clusters.get(key) ?? []), row]);
}
for (const cluster of clusters.values()) for (const row of cluster) clusterOf.set(row, cluster);
diff --git a/src/core/facts/extract-from-fence.ts b/src/core/facts/extract-from-fence.ts
index 941f122b01..831cee946b 100644
--- a/src/core/facts/extract-from-fence.ts
+++ b/src/core/facts/extract-from-fence.ts
@@ -38,6 +38,7 @@
* warning surfaced by extract-facts, not a parse failure.
*/
+import { attributionCompatible } from './attribution.ts';
import type { NewFact, FactKind, FactVisibility } from '../engine.ts';
import type { ParsedFact } from '../facts-fence.ts';
@@ -73,19 +74,21 @@ export const FENCE_SOURCE_DEFAULT = 'fence:reconcile';
/**
* #1781: duplicate ACTIVE fence rows (same claim and source) index once.
+ * Rows two different known speakers asserted are not duplicates (attribution.ts).
* Returns the row numbers of the later copies, which extract_facts leaves
* out of the index. A struck history row never collapses with an active row
* that carries the same text, so a claim that reverts to an earlier value
* stays active.
*/
export function duplicateActiveFenceRows(facts: ParsedFact[]): Set<number> {
- const seen = new Set<string>();
+ const seen = new Map<string, Array<ParsedFact['attributedTo']>>();
const duplicates = new Set<number>();
for (const f of facts) {
if (!f.active) continue;
const key = `${f.claim}\u0000${f.source ?? FENCE_SOURCE_DEFAULT}`;
- if (seen.has(key)) duplicates.add(f.rowNum);
- else seen.add(key);
+ const speakers = seen.get(key) ?? [];
+ if (speakers.some(s => attributionCompatible(s, f.attributedTo))) duplicates.add(f.rowNum);
+ else seen.set(key, [...speakers, f.attributedTo]);
}
return duplicates;
}
@@ -272,6 +275,7 @@ export function extractFactsFromFenceText(
claim_value: f.claimValue ?? null,
claim_unit: f.claimUnit ?? null,
claim_period: f.claimPeriod ?? null,
+ attributed_to: f.attributedTo ?? null,
};
return row;
});
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 7560798c04..7f9eb80cab 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -29,7 +29,7 @@ import type { ChatResult } from '../ai/gateway.ts';
import { INJECTION_PATTERNS } from '../think/sanitize.ts';
import { resolveModel } from '../model-config.ts';
import { normalizeModelId } from '../model-id.ts';
-import type { BrainEngine, NewFact, FactKind } from '../engine.ts';
+import type { BrainEngine, NewFact, FactKind, FactAttribution } from '../engine.ts';
import { normalizeMetricLabel } from './extract-from-fence.ts';
import { isNullLikeEntity } from './write-single.ts';
import { isAIInvocationPolicyError } from '../ai/invocation-guard.ts';
@@ -389,6 +389,8 @@ const ATTRIBUTION_BLOCK = [
'The user accepting it is a separate fact only when the user explicitly accepts it ("User accepted the',
'assistant\'s suggestion to …"); rejected or corrected suggestions produce no user fact. A named third',
'party\'s claim keeps the speaker\'s name in the fact text.',
+ '- Add "attributed_to" to every fact object: "user" when the user asserted it, "assistant" when the assistant',
+ ' did, "other" for a named third party, null when the speaker is unclear.',
].join('\n');
/** @internal Exported for the prompt-shape test. Both variants off → the historical prompt, byte-identical. */
@@ -442,16 +444,24 @@ const FACTS_EXTRACTION_SCHEMA: Record<string, unknown> = {
};
const FACTS_RESPONSE_SCHEMA = { name: 'facts_extraction', schema: FACTS_EXTRACTION_SCHEMA };
-/** The grounded variant's schema: every fact also carries a nullable valid_from. */
-const FACTS_GROUNDED_RESPONSE_SCHEMA = (() => {
+/**
+ * The variant's response schema: grounding adds a nullable `valid_from`,
+ * attribution a nullable `attributed_to`; both off → the historical schema.
+ */
+function factsResponseSchema(variant: ExtractorVariant): typeof FACTS_RESPONSE_SCHEMA {
+ if (!variant.dateGrounding && !variant.attribution) return FACTS_RESPONSE_SCHEMA;
const items = (FACTS_EXTRACTION_SCHEMA.properties as { facts: { items: Record<string, unknown> } }).facts.items;
- const groundedItems = {
+ const extra: Record<string, unknown> = {
+ ...(variant.dateGrounding ? { valid_from: { type: ['string', 'null'] } } : {}),
+ ...(variant.attribution ? { attributed_to: { type: ['string', 'null'], enum: ['user', 'assistant', 'other', null] } } : {}),
+ };
+ const variantItems = {
...items,
- properties: { ...(items.properties as Record<string, unknown>), valid_from: { type: ['string', 'null'] } },
- required: [...(items.required as string[]), 'valid_from'],
+ properties: { ...(items.properties as Record<string, unknown>), ...extra },
+ required: [...(items.required as string[]), ...Object.keys(extra)],
};
- return { name: 'facts_extraction', schema: { ...FACTS_EXTRACTION_SCHEMA, properties: { facts: { type: 'array', items: groundedItems } } } };
-})();
+ return { name: 'facts_extraction', schema: { ...FACTS_EXTRACTION_SCHEMA, properties: { facts: { type: 'array', items: variantItems } } } };
+}
export type ExtractFailureReason =
| 'chat_unavailable'
@@ -584,7 +594,7 @@ export async function extractFactsFromTurnWithOutcome(
const extractorSystem = promptAppendix
? `${buildExtractorSystem(admitsLow, variant)}\n\n${promptAppendix}`
: buildExtractorSystem(admitsLow, variant);
- const responseSchema = variant.dateGrounding ? FACTS_GROUNDED_RESPONSE_SCHEMA : FACTS_RESPONSE_SCHEMA;
+ const responseSchema = factsResponseSchema(variant);
const dateLine = variant.dateGrounding ? `${observationDateLine(input.observationDate ?? null)}\n` : '';
const userContent = `${dateLine}<turn>\n${cleaned}\n</turn>\n\nExtract up to ${cap} facts.${
input.entityHints && input.entityHints.length
@@ -787,6 +797,7 @@ export async function extractFactsFromTurnWithOutcome(
...(variant.dateGrounding && parseExtractedEventDate(candidate.valid_from)
? { valid_from: parseExtractedEventDate(candidate.valid_from)! }
: {}),
+ ...(variant.attribution && candidate.attributed_to ? { attributed_to: candidate.attributed_to } : {}),
});
}
@@ -839,7 +850,8 @@ interface RawExtracted {
unit?: string | null;
period?: string | null;
/** Date-grounding variant: the event date the extractor stated (raw string; validated on use). */
- valid_from?: string | null;
+ valid_from?: string | null; /** Attribution variant: who asserted the claim; anything outside the three speakers parses as null. */
+ attributed_to?: FactAttribution | null;
}
/**
@@ -925,6 +937,7 @@ function tryArrayShapeDetailed(s: string): ParsedExtractorShape | null {
unit: typeof o.unit === 'string' ? o.unit : null,
period: typeof o.period === 'string' ? o.period : null,
valid_from: typeof o.valid_from === 'string' ? o.valid_from : null,
+ attributed_to: o.attributed_to === 'user' || o.attributed_to === 'assistant' || o.attributed_to === 'other' ? o.attributed_to : null,
});
}
return { facts: out, invalidCandidates };
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index 6962ca4d79..e5498a12fe 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -38,7 +38,7 @@ import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendFileSync } from 'node:fs';
import { dirname, isAbsolute, relative } from 'node:path';
-import type { BrainEngine, NewFact, FactVisibility, FactKind } from '../engine.ts';
+import type { BrainEngine, NewFact, FactVisibility, FactKind, FactAttribution } from '../engine.ts';
import type { ResolutionSource } from '../entities/resolve.ts';
import { inferTypeFromPack, parseMarkdown } from '../markdown.ts';
import { yamlScalar } from '../frontmatter-inference.ts';
@@ -97,6 +97,8 @@ export interface FenceInputFact {
validUntil?: Date | null;
embedding: Float32Array | null;
sessionId: string | null;
+ /** Speaker attribution; written to the fence's attributed_to cell. */
+ attributedTo?: FactAttribution;
}
export interface FenceWriteResult {
@@ -473,6 +475,7 @@ export async function writeFactsToFence(
validUntil: f.validUntil ? formatFenceDate(f.validUntil) : undefined,
source: f.source,
context: f.context ?? undefined,
+ ...(f.attributedTo ? { attributedTo: f.attributedTo } : {}),
});
body = updated;
assignedRowNums.push(rowNum);
diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.ts
index daf0505e4a..903f62bd13 100644
--- a/src/core/facts/meta-hook.ts
+++ b/src/core/facts/meta-hook.ts
@@ -201,6 +201,7 @@ export async function getBrainHotMemoryMeta(
// in) rides the pack/delta projections instead of being recall-only.
context: r.context ?? null,
confidence: Number(effectiveConfidence(r, now).toFixed(3)),
+ ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),
})),
},
};
diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.ts
index d4164a08f7..4c244f4776 100644
--- a/src/core/facts/relink-publish.ts
+++ b/src/core/facts/relink-publish.ts
@@ -72,6 +72,7 @@ function fenceRow(v: Record<string, unknown>, rowNum: number, context: string) {
...(v.claim_value != null ? { claimValue: Number(v.claim_value) } : {}),
...(v.claim_unit ? { claimUnit: String(v.claim_unit) } : {}),
...(v.claim_period ? { claimPeriod: String(v.claim_period) } : {}),
+ ...(v.attributed_to === 'user' || v.attributed_to === 'assistant' || v.attributed_to === 'other' ? { attributedTo: v.attributed_to as 'user' | 'assistant' | 'other' } : {}),
};
}
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 2fd0d3a5b9..bcbc49ad7d 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -1,4 +1,4 @@
-import type { BrainEngine, FactRow } from '../engine.ts';
+import type { BrainEngine, FactAttribution, FactRow } from '../engine.ts';
import { verbError } from '../ops/contract.ts';
import { isAvailable, embedOne, getEmbeddingModel } from '../ai/gateway.ts';
import { cosineSimilarity } from './classify.ts';
@@ -9,6 +9,8 @@ export type FactCandidate = FactRow & { source_markdown_slug: string | null; row
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
export interface SingleFactIntent {
fact: string; kind: FactRow['kind']; visibility: FactRow['visibility']; entity_slug: string | null;
+ /** Speaker of the new claim; a fact another known speaker asserted is never its duplicate. */
+ attributed_to?: FactAttribution | null;
}
/** Provider work belongs to preparation, never to a page/source transaction. */
export async function prepareFactEmbedding(fact: string, signal?: AbortSignal): Promise<{ embedding: Float32Array | null; embedding_model: string | null; degraded: boolean }> {
@@ -35,10 +37,11 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
const [exact] = await engine.executeRaw<FactCandidate>(`SELECT * FROM facts WHERE source_id=$1
AND entity_slug IS NOT DISTINCT FROM $2 AND visibility=$3 AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until>now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($4)
- ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact]);
+ AND ($5::text IS NULL OR attributed_to IS NULL OR attributed_to=$5)
+ ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact, input.attributed_to ?? null]);
if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };
if (embedding && input.entity_slug) {
- const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, embeddingModel, k: 5 });
+ const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, embeddingModel, k: 5, attributedTo: input.attributed_to ?? null });
const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null }>(
'SELECT id,source_markdown_slug,row_num FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
[sourceId, candidates.map(c => c.id)]);
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index b40f480a84..282fc081dc 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -543,7 +543,7 @@ const recall: Operation = {
// pre-v1 consumers — legacy fields are frozen byte-equal). `provenance`
// is the protocol name for the stored source attribution.
fact_id: String(r.id),
- provenance: r.source,
+ provenance: r.source, ...(r.attributed_to ? { attributed_to: r.attributed_to } : {}),
})),
total: packedFacts.length,
...(ambiguousEntity ? { ambiguous_entity: { candidates: ambiguousEntity, suggestion: AMBIGUOUS_ENTITY_SUGGESTION } } : {}),
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index cef73d31d3..605ddd6a6b 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -1,4 +1,5 @@
import type { BrainEngine, NewFact } from '../engine.ts';
+import { attributionCompatible } from '../facts/attribution.ts';
import type { GBrainConfig } from '../config.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
@@ -123,13 +124,13 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);
let nextRow = Math.max(maximum?.n ?? 0, ...parsed.facts.map(fact => fact.rowNum)) + 1;
const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate }> = [];
- const seen = new Map<string, number>();
+ const seen = new Map<string, number[]>();
for (const fact of facts) {
await assertFactNotWithdrawn(engine, row.source_id, fact);
const key = JSON.stringify([fact.fact, fact.visibility, fact.entity_slug]);
- const earlier = seen.get(key);
+ const earlier = (seen.get(key) ?? []).find(i => attributionCompatible(entries[i].fact.attributed_to, fact.attributed_to));
if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }
- seen.set(key, entries.length);
+ seen.set(key, [...(seen.get(key) ?? []), entries.length]);
const decision = await decideSingleFact(engine, row.source_id, fact, dedupEmbedding(fact), fact.embedding_model, fact.source);
const supersedes = p.supersede === true && decision.status === 'superseded' ? decision.candidate! : undefined;
if (decision.candidate && !supersedes) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }
@@ -138,7 +139,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,
validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,
claimMetric: fact.claim_metric ?? undefined, claimValue: fact.claim_value ?? undefined,
- claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined }).body;
+ claimUnit: fact.claim_unit ?? undefined, claimPeriod: fact.claim_period ?? undefined,
+ ...(fact.attributed_to ? { attributedTo: fact.attributed_to } : {}) }).body;
// Strike the superseded row in this page's fence, as the remember mutation does.
if (supersedes && rowNum !== undefined && supersedes.source_markdown_slug === row.slug && supersedes.row_num != null) {
body = replaceOrInsertFactsFence(body, renderFactsTable(parseFactsFence(body).facts.map(f => f.rowNum === Number(supersedes.row_num)
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index c6c0d1b75e..04dcf9afbd 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2441,7 +2441,7 @@ export class PGLiteEngine implements BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; attributedTo?: import('./engine.ts').FactAttribution | null },
): Promise<FactRow[]> {
return factsImpl.findCandidateDuplicates(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, entitySlug, factText, opts);
}
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 55039f1eac..f7ffdcdec9 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2170,7 +2170,7 @@ export class PostgresEngine implements BrainEngine {
source_id: string,
entitySlug: string,
factText: string,
- opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null },
+ opts?: { k?: number; embedding?: Float32Array; embeddingModel?: string | null; attributedTo?: import('./engine.ts').FactAttribution | null },
): Promise<FactRow[]> {
return factsImpl.findCandidateDuplicates(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id, entitySlug, factText, opts);
}
diff --git a/src/core/schema-migrations/v201-facts-attributed-to.ts b/src/core/schema-migrations/v201-facts-attributed-to.ts
new file mode 100644
index 0000000000..83086d6caf
--- /dev/null
+++ b/src/core/schema-migrations/v201-facts-attributed-to.ts
@@ -0,0 +1,21 @@
+import type { Migration } from './types.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. 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.
+export const v201: Migration = {
+ version: 201,
+ 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'));
+ `,
+};
diff --git a/test/facts/speaker-attribution.test.ts b/test/facts/speaker-attribution.test.ts
new file mode 100644
index 0000000000..dfcfaf0efd
--- /dev/null
+++ b/test/facts/speaker-attribution.test.ts
@@ -0,0 +1,222 @@
+/**
+ * Speaker attribution on saved facts (`facts.attribution`, migration v201).
+ *
+ * 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 --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 7d807b48ac..4d99432776 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -69,6 +69,7 @@
"fact_withdrawals.fact_withdrawals_pkey": "p PRIMARY KEY (source_id, visibility, subject, fact_hash)",
"fact_withdrawals.fact_withdrawals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"fact_withdrawals.fact_withdrawals_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
+ "facts.facts_attributed_to_check": "c CHECK ((attributed_to = ANY (ARRAY['user'::text, 'assistant'::text, 'other'::text])))",
"facts.facts_confidence_check": "c CHECK (((confidence >= (0)::double precision) AND (confidence <= (1)::double precision)))",
"facts.facts_kind_check": "c CHECK ((kind = ANY (ARRAY['event'::text, 'preference'::text, 'commitment'::text, 'belief'::text, 'fact'::text, 'idea'::text])))",
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
@@ -1740,7 +1741,8 @@
"37 last_write_request_id uuid/uuid NULL",
"38 last_write_principal_kind text/text NULL",
"39 last_write_principal_id text/text NULL",
- "40 last_written_at timestamp with time zone/timestamptz NULL"
+ "40 last_written_at timestamp with time zone/timestamptz NULL",
+ "41 attributed_to text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index cdc1320166..bca1eda32c 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -69,6 +69,7 @@
"fact_withdrawals.fact_withdrawals_pkey": "p PRIMARY KEY (source_id, visibility, subject, fact_hash)",
"fact_withdrawals.fact_withdrawals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"fact_withdrawals.fact_withdrawals_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
+ "facts.facts_attributed_to_check": "c CHECK ((attributed_to = ANY (ARRAY['user'::text, 'assistant'::text, 'other'::text])))",
"facts.facts_confidence_check": "c CHECK (((confidence >= (0)::double precision) AND (confidence <= (1)::double precision)))",
"facts.facts_kind_check": "c CHECK ((kind = ANY (ARRAY['event'::text, 'preference'::text, 'commitment'::text, 'belief'::text, 'fact'::text, 'idea'::text])))",
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
@@ -1740,7 +1741,8 @@
"37 last_write_request_id uuid/uuid NULL",
"38 last_write_principal_kind text/text NULL",
"39 last_write_principal_id text/text NULL",
- "40 last_written_at timestamp with time zone/timestamptz NULL"
+ "40 last_written_at timestamp with time zone/timestamptz NULL",
+ "41 attributed_to text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 4f88afa57e..d05077e0fd 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -69,6 +69,7 @@
"fact_withdrawals.fact_withdrawals_pkey": "p PRIMARY KEY (source_id, visibility, subject, fact_hash)",
"fact_withdrawals.fact_withdrawals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"fact_withdrawals.fact_withdrawals_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
+ "facts.facts_attributed_to_check": "c CHECK ((attributed_to = ANY (ARRAY['user'::text, 'assistant'::text, 'other'::text])))",
"facts.facts_confidence_check": "c CHECK (((confidence >= (0)::double precision) AND (confidence <= (1)::double precision)))",
"facts.facts_kind_check": "c CHECK ((kind = ANY (ARRAY['event'::text, 'preference'::text, 'commitment'::text, 'belief'::text, 'fact'::text, 'idea'::text])))",
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
@@ -1736,7 +1737,8 @@
"37 last_write_request_id uuid/uuid NULL",
"38 last_write_principal_kind text/text NULL",
"39 last_write_principal_id text/text NULL",
- "40 last_written_at timestamp with time zone/timestamptz NULL"
+ "40 last_written_at timestamp with time zone/timestamptz NULL",
+ "41 attributed_to text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 82c79e14db..e169cdad29 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -69,6 +69,7 @@
"fact_withdrawals.fact_withdrawals_pkey": "p PRIMARY KEY (source_id, visibility, subject, fact_hash)",
"fact_withdrawals.fact_withdrawals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"fact_withdrawals.fact_withdrawals_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
+ "facts.facts_attributed_to_check": "c CHECK ((attributed_to = ANY (ARRAY['user'::text, 'assistant'::text, 'other'::text])))",
"facts.facts_confidence_check": "c CHECK (((confidence >= (0)::double precision) AND (confidence <= (1)::double precision)))",
"facts.facts_kind_check": "c CHECK ((kind = ANY (ARRAY['event'::text, 'preference'::text, 'commitment'::text, 'belief'::text, 'fact'::text, 'idea'::text])))",
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
@@ -1741,7 +1742,8 @@
"37 last_write_request_id uuid/uuid NULL",
"38 last_write_principal_kind text/text NULL",
"39 last_write_principal_id text/text NULL",
- "40 last_written_at timestamp with time zone/timestamptz NULL"
+ "40 last_written_at timestamp with time zone/timestamptz NULL",
+ "41 attributed_to text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index dc86dec44e..8068b36453 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -69,6 +69,7 @@
"fact_withdrawals.fact_withdrawals_pkey": "p PRIMARY KEY (source_id, visibility, subject, fact_hash)",
"fact_withdrawals.fact_withdrawals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"fact_withdrawals.fact_withdrawals_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
+ "facts.facts_attributed_to_check": "c CHECK ((attributed_to = ANY (ARRAY['user'::text, 'assistant'::text, 'other'::text])))",
"facts.facts_confidence_check": "c CHECK (((confidence >= (0)::double precision) AND (confidence <= (1)::double precision)))",
"facts.facts_kind_check": "c CHECK ((kind = ANY (ARRAY['event'::text, 'preference'::text, 'commitment'::text, 'belief'::text, 'fact'::text, 'idea'::text])))",
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
@@ -1741,7 +1742,8 @@
"37 last_write_request_id uuid/uuid NULL",
"38 last_write_principal_kind text/text NULL",
"39 last_write_principal_id text/text NULL",
- "40 last_written_at timestamp with time zone/timestamptz NULL"
+ "40 last_written_at timestamp with time zone/timestamptz NULL",
+ "41 attributed_to text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 630b3f847c..b7b07ce628 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -69,6 +69,7 @@
"fact_withdrawals.fact_withdrawals_pkey": "p PRIMARY KEY (source_id, visibility, subject, fact_hash)",
"fact_withdrawals.fact_withdrawals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"fact_withdrawals.fact_withdrawals_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
+ "facts.facts_attributed_to_check": "c CHECK ((attributed_to = ANY (ARRAY['user'::text, 'assistant'::text, 'other'::text])))",
"facts.facts_confidence_check": "c CHECK (((confidence >= (0)::double precision) AND (confidence <= (1)::double precision)))",
"facts.facts_kind_check": "c CHECK ((kind = ANY (ARRAY['event'::text, 'preference'::text, 'commitment'::text, 'belief'::text, 'fact'::text, 'idea'::text])))",
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
@@ -1737,7 +1738,8 @@
"37 last_write_request_id uuid/uuid NULL",
"38 last_write_principal_kind text/text NULL",
"39 last_write_principal_id text/text NULL",
- "40 last_written_at timestamp with time zone/timestamptz NULL"
+ "40 last_written_at timestamp with time zone/timestamptz NULL",
+ "41 attributed_to text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index dcbd5cd7e8..6145137329 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -961,6 +961,10 @@ const COLUMN_EXEMPTIONS = new Set<string>([
// brains is invisible to them). Migration is column-only, no FK,
// no index — bootstrap probe would be pure overhead.
'facts.event_type',
+ // migration v201 — 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