Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): capture lanes drop only exact duplicates across entities and lanes (#5888)

garrytancfe90ca31de7
diff --git a/src/commands/doctor/checks/memory-writeback.ts b/src/commands/doctor/checks/memory-writeback.ts
index 3b49e3d623..6c0b21361f 100644
--- a/src/commands/doctor/checks/memory-writeback.ts
+++ b/src/commands/doctor/checks/memory-writeback.ts
@@ -132,6 +132,16 @@ export async function buildMemoryWritebackCheck(engine: BrainEngine | null): Pro
counters_note: `local, append-only, loss-tolerant observability over the last ${COUNTER_WINDOW_DAYS}d — never a source of truth`,
};
+ // #5888: capture-lane exact duplicates dropped (every capture lane runs
+ // whether or not writeback is on) and near duplicates counted in shadow
+ // mode only (kept, never dropped).
+ try {
+ const cutoff = Date.now() - COUNTER_WINDOW_DAYS * 24 * 60 * 60 * 1000;
+ const dedup = (await readHeartbeatTail(2000)).filter((e) => e.event === 'writeback_dedup' && Date.parse(e.ts) >= cutoff);
+ details.cross_lane_duplicates_7d = dedup.reduce((n, e) => n + (e.duplicate ?? 0), 0);
+ details.near_duplicates_shadow_7d = dedup.reduce((n, e) => n + (e.near_duplicate ?? 0), 0);
+ } catch { /* heartbeat unreadable — counters stay absent */ }
+
// Plane comparison (the dual-write design's promised surfacing): the DB
// row is authoritative at runtime; a disagreeing file mirror means a
// failed dual-write, a foreign writer, or another machine's `config set`
diff --git a/src/core/context/hook-heartbeat.ts b/src/core/context/hook-heartbeat.ts
index cc2d02c54c..ec04efbbe7 100644
--- a/src/core/context/hook-heartbeat.ts
+++ b/src/core/context/hook-heartbeat.ts
@@ -46,6 +46,8 @@ export interface HookHeartbeatEntry {
inserted?: number;
duplicate?: number;
superseded?: number;
+ /** #5888 — `writeback_dedup` shadow count: near duplicates kept, never dropped (counts only). */
+ near_duplicate?: number;
/**
* Cathedral 5 — the compact hook's harvest-schedule ACK code
* (`scheduled` / `skip_queue_full` / `skip_not_found` / `skip_bad_basename`
@@ -67,7 +69,7 @@ export interface HookHeartbeatEntry {
/** The FULL key allowlist — CI greps the fixture against this [S3#7]. */
export const HEARTBEAT_ALLOWED_KEYS = [
'ts', 'event', 'outcome', 'reason', 'duration_ms', 'turns', 'bytes', 'redactions',
- 'segment', 'inserted', 'duplicate', 'superseded', 'links', 'flush',
+ 'segment', 'inserted', 'duplicate', 'superseded', 'near_duplicate', 'links', 'flush',
'pattern', 'fingerprint', 'hint',
] as const;
@@ -158,6 +160,7 @@ export async function writeHeartbeat(
...(entry.segment !== undefined ? { segment: entry.segment } : {}),
...(entry.inserted !== undefined ? { inserted: entry.inserted } : {}),
...(entry.duplicate !== undefined ? { duplicate: entry.duplicate } : {}),
+ ...(entry.near_duplicate !== undefined ? { near_duplicate: entry.near_duplicate } : {}),
...(entry.links !== undefined ? { links: entry.links } : {}),
...(entry.flush !== undefined ? { flush: entry.flush } : {}),
...(entry.pattern !== undefined ? { pattern: entry.pattern } : {}),
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index 514a39d40f..787e83acba 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -47,6 +47,7 @@ import type { GBrainConfig } from '../config.ts';
import { isAvailable } from '../ai/gateway.ts';
import { withAIInvocationPreflight } from '../ai/invocation-guard.ts';
import { decideSingleFact } from './single-prepare.ts';
+import { cosineVerdict, dedupCapturedFacts, withCaptureDrops } from './capture-dedup.ts';
import { appendContextNote, type InferredVia } from './subject-infer.ts';
import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';
@@ -101,8 +102,10 @@ export interface FactsBackstopCtx {
* - 'code_import' — code import path
* - 'hook:compact' — compaction-boundary checkpoint harvest (cathedral 5)
* - 'hook:writeback' — ambient-writeback Stop-hook backstop (WP4)
+ * - 'sweep:corpus' — the sweep's session-corpus pass
+ * The last three are capture lanes (capture-dedup.ts, #5888).
*/
- source: 'sync:import' | 'mcp:put_page' | 'mcp:extract_facts' | 'file_upload' | 'code_import' | 'hook:compact' | 'hook:writeback';
+ source: 'sync:import' | 'mcp:put_page' | 'mcp:extract_facts' | 'file_upload' | 'code_import' | 'hook:compact' | 'hook:writeback' | 'sweep:corpus';
/** Execution mode — D8. Default 'queue' (fire-and-forget). */
mode?: 'queue' | 'inline';
/** Notability filter — D4. Default 'all'; sync uses 'high-only'; the
@@ -130,6 +133,8 @@ export interface FactsBackstopCtx {
* context_pack / delta projections surface the provenance.
*/
sourceSlug?: string;
+ /** #5888: when the source turn happened, for the capture-lane dedup window (default: now). */
+ turnAt?: Date;
}
/** Discriminated return shape based on FactsBackstopCtx.mode. */
@@ -159,14 +164,6 @@ interface ParsedPageInput {
frontmatter: Record<string, unknown>;
}
-/**
- * Cosine similarity threshold for the dedup fast-path. Matches the existing
- * extract_facts op behavior at operations.ts:2460. Higher = stricter
- * dedup (more rows kept distinct); lower = looser (more rows treated as
- * duplicates of older ones).
- */
-const DEDUP_THRESHOLD = 0.95;
-
/** k for findCandidateDuplicates — ceiling on candidates considered. */
const DEDUP_CANDIDATE_LIMIT = 5;
@@ -657,13 +654,14 @@ async function runPipelineBodyInner(
// facts.default_visibility (fail-closed to 'private').
const { resolveDefaultVisibility } = await import('./visibility.ts');
const visibility = ctx.visibility ?? (await resolveDefaultVisibility(ctx.engine));
- const facts = await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed);
- if (managed) return publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug);
+ // #5888: one exact-duplicate check for the capture lanes, before either writer.
+ const { facts, dropped } = await dedupCapturedFacts(ctx, await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed), visibility, resolveEntitySlugWithSource);
+ if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);
let inserted = 0;
- let duplicate = 0;
+ let duplicate = dropped.length;
let superseded = 0;
- const fact_ids: number[] = [];
+ const fact_ids: number[] = [...dropped];
// Cathedral 5: slugs whose fence-write actually inserted a fact this run.
const fencedSlugs = new Set<string>();
@@ -695,7 +693,7 @@ 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). Threshold 0.95 unchanged.
+ // 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;
let matchedExistingId: number | null = exact?.candidate?.id ?? null;
if (matchedExistingId === null && resolvedSlug && f.embedding && !f.entity_inferred) {
@@ -705,15 +703,14 @@ async function runPipelineBodyInner(
f.fact,
{ embedding: f.embedding, embeddingModel: f.embedding_model, k: DEDUP_CANDIDATE_LIMIT },
);
- let topId: number | null = null;
- let topScore = -1;
+ let top: { id: number; score: number; fact: string } | null = null;
for (const c of candidates) {
if (!c.embedding) continue;
const s = cosineSimilarity(f.embedding, c.embedding);
- if (s > topScore) { topScore = s; topId = c.id; }
+ if (!top || s > top.score) top = { id: c.id, score: s, fact: c.fact };
}
- if (topId !== null && topScore >= DEDUP_THRESHOLD) {
- matchedExistingId = topId;
+ if (top && cosineVerdict(ctx.source, top.score, f.fact, top.fact) === 'duplicate') {
+ matchedExistingId = top.id;
}
}
diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.ts
new file mode 100644
index 0000000000..116a36f5a3
--- /dev/null
+++ b/src/core/facts/capture-dedup.ts
@@ -0,0 +1,271 @@
+/**
+ * #5888 — capture-lane duplicate policy, shared by every write path that
+ * stores automatically captured facts (`hook:writeback`, `sweep:corpus`,
+ * `hook:compact`) and by the hot-memory read that injects them.
+ *
+ * Write side (`applyCaptureDedup`, called by the backstop before its
+ * managed/unmanaged branch): an extracted candidate is DROPPED only when an
+ * active fact in the same source has the same `gbrain_fact_fingerprint` and
+ * - sits on the same entity (or both have none), or on a different entity
+ * whose page title or alias the claim names (subject-relative claims such
+ * as "Prefers email" captured for two people are never merged);
+ * - is visible where the candidate is (a `private` candidate compares with
+ * `world` and `private` facts, a `world` candidate only with `world`);
+ * - was written within 15 minutes of the source turn, or by a capture lane
+ * in the same conversation (no time bound inside one conversation).
+ * Near duplicates (cosine >= 0.92 on the same entity, claims not differing
+ * in a negation, number or date token) are never dropped: they are counted
+ * in shadow mode (`near_duplicate` on the `writeback_dedup` heartbeat event)
+ * so a threshold can be measured before it ever deletes anything. A failed
+ * dedup read inserts the candidate (fail open) and warns with the lane.
+ * Explicit lanes (`remember`, extract_facts, sync) never pass through here.
+ *
+ * Read side (`collapseHotFacts`): rows with the same fingerprint on the same
+ * entity, or on different entities when the claim names one of them,
+ * collapse to the newest row, which carries every entity slug of its group.
+ */
+
+import type { BrainEngine, 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';
+import { cosineSimilarity } from './classify.ts';
+
+export const CAPTURE_LANES = ['hook:writeback', 'sweep:corpus', 'hook:compact'] as const;
+export const CAPTURE_DEDUP_WINDOW_MS = 15 * 60 * 1000;
+/** Shadow-mode near-duplicate threshold (measured, never a drop). */
+export const NEAR_DUPLICATE_THRESHOLD = 0.92;
+/** Explicit lanes keep their pre-#5888 cosine rule. */
+export const EXPLICIT_DUPLICATE_THRESHOLD = 0.95;
+const CAPTURE_DEDUP_SCAN_LIMIT = 50;
+
+export function isCaptureLane(source: string | null | undefined): boolean {
+ return (CAPTURE_LANES as readonly string[]).includes(source ?? '');
+}
+
+/**
+ * One key per harness conversation across the capture lanes: the corpus sweep
+ * tags rows `sweep:corpus:<file>`, where the file is `<session>.txt`, a
+ * checkpoint segment or a writeback turn file of that session.
+ */
+export function canonicalConversationKey(sessionId: string | null | undefined): string | null {
+ if (!sessionId) return null;
+ const bare = sessionId.startsWith('sweep:corpus:') ? sessionId.slice('sweep:corpus:'.length) : sessionId;
+ const key = bare.endsWith('.txt') ? corpusFileSessionId(bare) : bare;
+ return key || null;
+}
+
+const NEGATION_TOKENS = /\b(?:no longer|not|no|never|stopped|isn't|doesn't|won't|isnt|doesnt|wont)\b/g;
+const DATE_WORDS = /\b(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?|(?:mon|tues|wednes|thurs|fri|satur|sun)days?|today|tomorrow|yesterday)\b/g;
+const NUMBER_TOKENS = /[$€£¥]?\d[\d,.:/-]*\s?(?:k|m|bn|b|%|percent)?\b/g;
+const NUMBER_WORDS = /\b(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|twenty|thirty|forty|fifty|hundred|thousand|million|billion|dozen|half|twice|first|second|third|last)\b/g;
+
+function guardTokens(text: string): string {
+ const t = text.normalize('NFKC').toLowerCase().replace(/[’‘]/g, "'");
+ const pick = (re: RegExp) => (t.match(re) ?? []).map(s => s.replace(/\s+/g, '').replace(/[.,]+$/, ''));
+ return JSON.stringify([pick(NEGATION_TOKENS).sort(), [...pick(NUMBER_TOKENS), ...pick(NUMBER_WORDS), ...pick(DATE_WORDS).map(d => d.replace(/days$/, 'day'))].sort()]);
+}
+
+/** V1 guard: true when two claims differ in a negation, number, date or amount token. */
+export function claimsDiverge(a: string, b: string): boolean {
+ return guardTokens(a) !== guardTokens(b);
+}
+
+export type CosineVerdict = 'duplicate' | 'near_duplicate' | 'distinct';
+
+/**
+ * The one cosine policy for every fact-write decision point. Capture lanes
+ * never return `duplicate`; explicit lanes keep the 0.95 rule unchanged.
+ */
+export function cosineVerdict(source: string | null | undefined, score: number, claim: string, existing: string): CosineVerdict {
+ if (!isCaptureLane(source)) return score >= EXPLICIT_DUPLICATE_THRESHOLD ? 'duplicate' : 'distinct';
+ return score >= NEAR_DUPLICATE_THRESHOLD && !claimsDiverge(claim, existing) ? 'near_duplicate' : 'distinct';
+}
+
+function nameKey(text: string): string {
+ return ` ${normalizeAlias(text).replace(/[^\p{L}\p{N}]+/gu, ' ').trim()} `;
+}
+
+/** True when the claim contains one of the entity's names as whole words. */
+export function claimNamesEntity(claim: string, names: readonly string[]): boolean {
+ const haystack = nameKey(claim);
+ return names.some(name => {
+ const needle = nameKey(name);
+ return needle.trim().length > 0 && haystack.includes(needle);
+ });
+}
+
+/** Title + aliases of each live entity page, keyed by slug. */
+export async function entityNames(engine: BrainEngine, sourceId: string, slugs: string[]): Promise<Map<string, string[]>> {
+ const names = new Map<string, string[]>();
+ const wanted = [...new Set(slugs)];
+ if (!wanted.length) return names;
+ const add = (slug: string, name: string | null) => {
+ if (name) names.set(slug, [...(names.get(slug) ?? []), name]);
+ };
+ const pages = await engine.executeRaw<{ slug: string; title: string | null }>(
+ 'SELECT slug,title FROM pages WHERE source_id=$1 AND slug=ANY($2::text[]) AND deleted_at IS NULL', [sourceId, wanted]);
+ for (const page of pages) add(page.slug, page.title);
+ try {
+ const aliases = await engine.executeRaw<{ slug: string; alias_norm: string }>(
+ 'SELECT slug,alias_norm FROM page_aliases WHERE source_id=$1 AND slug=ANY($2::text[])', [sourceId, pages.map(p => p.slug)]);
+ for (const alias of aliases) add(alias.slug, alias.alias_norm);
+ } catch { /* pre-v110 brain: titles only */ }
+ return names;
+}
+
+export interface CaptureCandidate {
+ fact: string;
+ entitySlug: string | null;
+ visibility: 'private' | 'world';
+ embedding?: Float32Array | null;
+ embeddingModel?: string | null;
+ entityInferred?: unknown;
+}
+export interface CaptureScope {
+ engine: BrainEngine;
+ sourceId: string;
+ lane: string;
+ sessionId: string | null;
+ /** The source turn's own time when the lane knows it, else check time. */
+ anchor: Date;
+}
+export interface CaptureMatch { id: number; rule: 'same_entity' | 'named_entity'; }
+
+/** The exact-fingerprint drop rule (one bounded indexed read). */
+export async function findCaptureDuplicate(scope: CaptureScope, candidate: CaptureCandidate): Promise<CaptureMatch | null> {
+ const visibilities = candidate.visibility === 'world' ? ['world'] : ['world', 'private'];
+ 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())
+ ORDER BY created_at DESC, id DESC LIMIT ${CAPTURE_DEDUP_SCAN_LIMIT}`,
+ [scope.sourceId, visibilities, candidate.fact]);
+ 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);
+ const same = recent.find(row => (row.entity_slug ?? null) === candidate.entitySlug);
+ if (same) return { id: Number(same.id), rule: 'same_entity' };
+ const others = recent.filter(row => row.entity_slug);
+ if (!others.length) return null;
+ const names = await entityNames(scope.engine, scope.sourceId, others.map(row => row.entity_slug!));
+ const named = others.find(row => claimNamesEntity(candidate.fact, names.get(row.entity_slug!) ?? []));
+ return named ? { id: Number(named.id), rule: 'named_entity' } : null;
+}
+
+/** Shadow mode: the id of a same-entity near duplicate, never a drop. */
+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 });
+ 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;
+ const score = cosineSimilarity(candidate.embedding, row.embedding);
+ if (!best || score > best.score) best = { id: row.id, score, fact: row.fact };
+ }
+ return best && cosineVerdict(scope.lane, best.score, candidate.fact, best.fact) === 'near_duplicate' ? best.id : null;
+}
+
+export interface CaptureDedupResult<T> { kept: T[]; duplicateIds: number[]; nearDuplicates: number; }
+
+/**
+ * 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 }>(
+ scope: CaptureScope, facts: T[], visibility: 'private' | 'world', resolve: (entity: string | null | undefined) => Promise<string | null>,
+): Promise<CaptureDedupResult<T>> {
+ const started = Date.now();
+ const result: CaptureDedupResult<T> = { kept: [], duplicateIds: [], nearDuplicates: 0 };
+ 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 };
+ try {
+ const match = await findCaptureDuplicate(scope, candidate);
+ if (match) {
+ result.duplicateIds.push(match.id);
+ console.warn(`[facts] capture dedup: lane=${scope.lane} dropped a duplicate of fact #${match.id} (rule=${match.rule})`);
+ continue;
+ }
+ if (await findNearDuplicate(scope, candidate) !== null) result.nearDuplicates++;
+ } catch (err) {
+ failed = true;
+ console.warn(`[facts] capture dedup read failed: lane=${scope.lane} inserting the candidate (${err instanceof Error ? err.message : String(err)})`);
+ }
+ result.kept.push(fact);
+ }
+ if (result.duplicateIds.length || result.nearDuplicates || failed) {
+ await writeHeartbeat({ ts: new Date().toISOString(), event: 'writeback_dedup', outcome: failed ? 'degraded' : 'ok',
+ reason: failed ? `${scope.lane}:read_failed` : scope.lane, duration_ms: Date.now() - started,
+ duplicate: result.duplicateIds.length, near_duplicate: result.nearDuplicates }, { trim: false });
+ }
+ return result;
+}
+
+/**
+ * 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 }>(
+ 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>,
+): Promise<{ facts: T[]; dropped: number[] }> {
+ if (!isCaptureLane(ctx.source)) return { facts, dropped: [] };
+ const result = await applyCaptureDedup({ engine: ctx.engine, sourceId: ctx.sourceId, lane: ctx.source, sessionId: ctx.sessionId,
+ anchor: ctx.turnAt ?? new Date() }, facts, visibility, async entity => {
+ const resolved = entity ? await resolveEntity(ctx.engine, ctx.sourceId, entity) : null;
+ return resolved && resolved.source !== 'fallback_slugify' ? resolved.slug : null;
+ });
+ return { facts: result.kept, dropped: result.duplicateIds };
+}
+
+/** Folds the pre-branch drops into a writer's counts (null: every candidate was dropped). */
+export function withCaptureDrops<R extends { inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[] }>(
+ dropped: number[], published: R | null,
+): R | { inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[] } {
+ if (!published) return { inserted: 0, duplicate: dropped.length, superseded: 0, fact_ids: dropped, entity_slugs: [] };
+ return { ...published, duplicate: published.duplicate + dropped.length, fact_ids: [...dropped, ...published.fact_ids] };
+}
+
+export type HotFactRow = FactRow & { fact_fingerprint?: string | null };
+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.
+ */
+export async function collapseHotFacts<R extends HotFactRow>(engine: BrainEngine, sourceId: string, rows: R[]): Promise<CollapsedHotFact<R>[]> {
+ const byFingerprint = new Map<string, R[]>();
+ for (const row of rows) {
+ const key = row.fact_fingerprint ?? `id:${row.id}`;
+ byFingerprint.set(key, [...(byFingerprint.get(key) ?? []), row]);
+ }
+ const multiEntity = [...byFingerprint.values()].filter(group => new Set(group.map(r => r.entity_slug)).size > 1);
+ const names = multiEntity.length
+ ? await entityNames(engine, sourceId, multiEntity.flatMap(group => group.flatMap(r => r.entity_slug ? [r.entity_slug] : []))).catch(() => new Map<string, string[]>())
+ : new Map<string, string[]>();
+ 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 clusters = new Map<string, R[]>();
+ for (const row of group) {
+ const key = named ? '*' : row.entity_slug ?? '';
+ clusters.set(key, [...(clusters.get(key) ?? []), row]);
+ }
+ for (const cluster of clusters.values()) for (const row of cluster) clusterOf.set(row, cluster);
+ }
+ const out: CollapsedHotFact<R>[] = [];
+ const emitted = new Set<R[]>();
+ for (const row of rows) {
+ const cluster = clusterOf.get(row)!;
+ if (emitted.has(cluster)) continue;
+ emitted.add(cluster);
+ const newest = cluster.reduce((a, b) => b.created_at.getTime() > a.created_at.getTime() || b.created_at.getTime() === a.created_at.getTime() && b.id > a.id ? b : a);
+ const slugs = [...new Set([newest.entity_slug, ...cluster.map(r => r.entity_slug)].filter((s): s is string => !!s))];
+ out.push(slugs.length > 1 ? { ...newest, entity_slugs: slugs } : newest);
+ }
+ return out;
+}
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index f2e14047ce..2fd0d3a5b9 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -3,6 +3,7 @@ import { verbError } from '../ops/contract.ts';
import { isAvailable, embedOne, getEmbeddingModel } from '../ai/gateway.ts';
import { cosineSimilarity } from './classify.ts';
import { isFactWithdrawn } from './withdrawal.ts';
+import { cosineVerdict } from './capture-dedup.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -26,8 +27,11 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri
'Remember a corrected claim. Repeating the old claim does not restore withdrawn memory.');
}
}
-/** SQL-only, so publication can verify the semantic decision under its guard. */
-export async function decideSingleFact(engine: BrainEngine, sourceId: string, input: SingleFactIntent, embedding: Float32Array | null, embeddingModel?: string | null): Promise<FactDecision> {
+/**
+ * SQL-only, so publication can verify the semantic decision under its guard.
+ * `lane` is the writer's `facts.source`: capture lanes never drop by cosine (#5888).
+ */
+export async function decideSingleFact(engine: BrainEngine, sourceId: string, input: SingleFactIntent, embedding: Float32Array | null, embeddingModel?: string | null, lane?: string | null): Promise<FactDecision> {
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)
@@ -52,7 +56,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
const next = cosineSimilarity(embedding, c.embedding);
if (next > score) { score = next; candidate = c; }
}
- if (candidate && score >= 0.95) return {
+ if (candidate && cosineVerdict(lane, score, input.fact, candidate.fact) === 'duplicate') return {
status: candidate.kind === input.kind ? 'superseded' : 'duplicate', candidate,
};
}
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index c8d59c206c..22e1c69876 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -98,7 +98,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const earlier = seen.get(key);
if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }
seen.set(key, entries.length);
- const decision = await decideSingleFact(engine, row.source_id, fact, dedupEmbedding(fact), fact.embedding_model);
+ 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; }
const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;
@@ -136,7 +136,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
for (const entry of entries) {
await assertFactNotWithdrawn(tx, row.source_id, entry.fact);
if (entry.duplicateOf !== undefined) continue;
- const current = await decideSingleFact(tx, row.source_id, entry.fact, dedupEmbedding(entry.fact), entry.fact.embedding_model);
+ const current = await decideSingleFact(tx, row.source_id, entry.fact, dedupEmbedding(entry.fact), entry.fact.embedding_model, entry.fact.source);
if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw new OperationError('revision_conflict', 'The fact deduplication state changed before publication.');
}
}, apply: async tx => {
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 7393ab1011..8ec12ecb6d 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -716,6 +716,8 @@ async function runCorpusIngestPass(
mode: 'inline',
remote: false,
abortSignal: signal,
+ // #5888: the file's write time anchors the capture dedup window, not the (possibly late) sweep.
+ turnAt: await stat(full).then(st => st.mtime, () => undefined),
...(wbMeta && wbCfg.mode === 'salient' ? { notabilityFilter: 'medium-and-up' as const } : {}),
// visibility deliberately unset → resolveDefaultVisibility [ENG-8]
});
diff --git a/test/facts/capture-dedup-policy.test.ts b/test/facts/capture-dedup-policy.test.ts
new file mode 100644
index 0000000000..4d04ef4769
--- /dev/null
+++ b/test/facts/capture-dedup-policy.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #5888 — the capture-lane dedup policy, branch by branch.
+ *
+ * Protects: corrections and changed numbers are never treated as duplicates,
+ * capture lanes never drop by cosine (shadow count only), explicit lanes keep
+ * their 0.95 rule, every capture lane maps one conversation to one key, and
+ * the cross-entity naming rule matches whole names only.
+ * Fails when: the guard is dropped, a capture lane regains a cosine drop, or
+ * the corpus sweep's `sweep:corpus:<file>` key no longer matches the writeback
+ * session id. Pure functions, no engine.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ canonicalConversationKey, claimNamesEntity, claimsDiverge, cosineVerdict, isCaptureLane,
+} from '../../src/core/facts/capture-dedup.ts';
+
+describe('cosineVerdict', () => {
+ const same = 'Alice Example is moving to NYC';
+ test.each([
+ ['explicit lane at 0.95 is a duplicate', 'mcp:extract_facts', 0.95, same, same, 'duplicate'],
+ ['explicit lane at 0.949 is distinct', 'mcp:extract_facts', 0.949, same, same, 'distinct'],
+ ['explicit lane keeps its rule for a negation pair', 'sync:import', 0.97, same, 'Alice Example is not moving to NYC', 'duplicate'],
+ ['writeback at 0.99 is only a near duplicate', 'hook:writeback', 0.99, same, 'Alice Example relocates to NYC', 'near_duplicate'],
+ ['corpus sweep at 0.93 is a near duplicate', 'sweep:corpus', 0.93, same, 'Alice Example relocates to NYC', 'near_duplicate'],
+ ['compact harvest at 0.919 is distinct', 'hook:compact', 0.919, same, 'Alice Example relocates to NYC', 'distinct'],
+ ['negation pair at 0.97 is distinct', 'hook:writeback', 0.97, same, 'Alice Example is not moving to NYC', 'distinct'],
+ ['"no longer" pair is distinct', 'hook:writeback', 0.97, 'Bob Example works at Acme Example', 'Bob Example no longer works at Acme Example', 'distinct'],
+ ['changed amount at 0.97 is distinct', 'hook:writeback', 0.97, 'MRR is $50k', 'MRR is $60k', 'distinct'],
+ ['changed month is distinct', 'sweep:corpus', 0.97, 'The renewal closes in November', 'The renewal closes in December', 'distinct'],
+ ['changed date is distinct', 'hook:compact', 0.97, 'Launch is on 2026-10-02', 'Launch is on 2026-10-09', 'distinct'],
+ ] as const)('%s', (_label, lane, score, a, b, verdict) => {
+ expect(cosineVerdict(lane, score, a, b)).toBe(verdict);
+ });
+});
+
+describe('claimsDiverge', () => {
+ test('identical guard tokens with different wording do not diverge', () => {
+ expect(claimsDiverge('MRR is $50k as of March', 'Monthly revenue reached $50k as of March')).toBe(false);
+ });
+ test('a curly-apostrophe contraction counts as a negation', () => {
+ expect(claimsDiverge('Dana Example drinks coffee', 'Dana Example doesn’t drink coffee')).toBe(true);
+ });
+ test('a changed number word diverges', () => {
+ expect(claimsDiverge('Bob Example has two kids', 'Bob Example has three kids')).toBe(true);
+ });
+ test('a plural weekday matches its singular', () => {
+ expect(claimsDiverge('Widget Co ships releases on Tuesdays', 'Widget Co releases ship every Tuesday')).toBe(false);
+ });
+ test('a word containing "no" is not a negation', () => {
+ expect(claimsDiverge('Dana Example knows Rust', 'Dana Example knows Rust well')).toBe(false);
+ });
+});
+
+describe('canonicalConversationKey', () => {
+ test.each([
+ ['sess-1', 'sess-1'],
+ ['sweep:corpus:sess-1.txt', 'sess-1'],
+ ['sweep:corpus:sess-1.seg-0123456789ab.txt', 'sess-1'],
+ ['sweep:corpus:sess-1.wb-0123456789ab.src-default.txt', 'sess-1'],
+ [null, null],
+ ['', null],
+ ] as const)('%p → %p', (input, key) => {
+ expect(canonicalConversationKey(input)).toBe(key);
+ });
+});
+
+test('capture lanes are exactly writeback, corpus sweep and compact harvest', () => {
+ expect(['hook:writeback', 'sweep:corpus', 'hook:compact', 'mcp:extract_facts', 'user told me', null].map(isCaptureLane))
+ .toEqual([true, true, true, false, false, false]);
+});
+
+describe('claimNamesEntity', () => {
+ test('a title inside the claim names the entity', () => {
+ expect(claimNamesEntity('Alice Example will lead the renewal', ['Alice Example'])).toBe(true);
+ });
+ test('a name embedded in a longer word does not', () => {
+ expect(claimNamesEntity('Acmeexample shipped', ['Acme Example', 'acme'])).toBe(false);
+ });
+ test('a subject-relative claim names nobody', () => {
+ expect(claimNamesEntity('Prefers email', ['Alice Example', 'Bob Example'])).toBe(false);
+ });
+ test('an alias names the entity', () => {
+ expect(claimNamesEntity('The ACME team signed', ['acme'])).toBe(true);
+ });
+});