Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): keep the guarded 0.95 same-entity drop in capture lanes (#5888)
garrytan00ad7183d2b1
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex d6cea2fee8..61b282bc66 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -85,7 +85,7 @@ rejection of serve-only flags before a brain opens.- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).-- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes keep the 0.95 drop; capture lanes never drop by cosine and return `near_duplicate` only at 0.92+ when `claimsDiverge` (negation, number, date or amount tokens) is false. `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).+- `src/core/facts/capture-dedup.ts` — the capture-lane (`hook:writeback`, `sweep:corpus`, `hook:compact`) duplicate policy (#5888). `cosineVerdict(source, score, claim, existing)` is the one cosine rule at every fact-write decision point (`backstop.ts` unmanaged loop, `single-prepare.ts` `decideSingleFact` and so `persistence/facts-prepare.ts` under its publication guard): explicit lanes keep the unguarded 0.95 drop; capture lanes drop at 0.95 only when `claimsDiverge` (negation, number, date or amount tokens) is false, and the 0.92–0.95 band returns `near_duplicate` (shadow count, never a drop). The unmanaged backstop's capture-lane cosine candidates also honor the visibility rule (a world candidate ignores private facts). `dedupCapturedFacts` runs before the backstop's managed/unmanaged branch: one indexed read (`(source_id, visibility, gbrain_fact_fingerprint(fact))`, `LIMIT 50`) drops a candidate whose fingerprint matches an active fact on the same entity (or both none) or on an entity whose title/`page_aliases` the claim names (`claimNamesEntity`, whole words), visible where the candidate is (private sees world+private, world sees world), within 15 minutes of `ctx.turnAt` (else now) or written by a capture lane in the same `canonicalConversationKey` conversation (`sweep:corpus:<file>` and `.txt` stripped via `corpusFileSessionId`). Read failure keeps the candidate and warns with the lane; each drop logs lane, matched id and rule on stderr; drops and shadow near-duplicate counts append one `writeback_dedup` heartbeat event. Explicit `remember` never passes through it. `collapseHotFacts` groups hot-memory/delta rows by the SQL `fact_fingerprint` column (`FactListOpts.fingerprint`), merges different entities only when the claim names one, and keeps the newest row with `entity_slugs[]`. The check is best-effort outside the publication transaction (two concurrent capture writers can both insert). Tests: `test/facts/capture-dedup-policy.test.ts`, `test/capture-dedup.test.ts` (unmanaged + coordinator-managed bound source; Postgres via `test/e2e/capture-dedup-postgres.test.ts`).- `src/core/facts/relink.ts` + `relink-publish.ts` + `relink-model.ts` + `relink-reasons.ts` + `relink-schema.ts` — `gbrain facts relink` (`src/commands/facts.ts`, CLI-only, host-only). Candidates are active database-only rows with `entity_slug IS NULL` (fence-owned subjectless rows are only counted), walked by id from `--after-id` over `idx_facts_unlinked_active`. Free tiers via `inferFactSubject`, then the model tier (`facts.extraction_model`, batches of 25, `--max-usd` BudgetTracker cap, private facts only with `--include-private`; an answer must quote the fact and pass the strict resolver). Publication is one coordinator request per entity page (`relink_facts`, dispatched from `persistence/service.ts`, managed or not): each fact's whole row is pinned by hash; prepare and the locked validation must classify identically; linked rows take fresh fence positions (row id, embedding and provenance kept, context gains `entity relinked from <tier>`) ahead of the page projection; exact duplicates retire expired and detached; nothing is superseded; withdrawn claims are skipped; attempt rows and the `decide_sweep_deferred` handoff (`enqueueRelinked`, when the conflict slot is not off) commit in the same transaction. Write target follows `persistence/fact-write-target.ts` (the remember rule): bound write-through publishes the file, write-through off or connector-database publishes the page body only, an unbound write-through source is refused as `unfenceable` (relink never claims an owner). `fact_relink_attempts` (migration v187) holds `linked`/`deduped` records and model verdict memos (`no_subject`, `ambiguous`, `unverified_match`) that stop reruns from paying again unless `--retry-model`. `RELINK_REASONS` is the one reason list (code, memoized flag, fix text) used by output, memo and the guide. Pinned by `test/facts-relink.test.ts` and `test/facts-relink-routing.test.ts` (+ `test/e2e/facts-relink-routing.test.ts`).diff --git a/docs/guides/ambient-writeback.md b/docs/guides/ambient-writeback.mdindex 5d66dd4f1d..b3724a3b79 100644--- a/docs/guides/ambient-writeback.md+++ b/docs/guides/ambient-writeback.md@@ -175,11 +175,12 @@ source already has the same normalized text, andsame conversation (no time limit there, so a sweep hours later stillrecognizes the writeback's copy).-Similar but differently worded facts are always kept. Capture counts them as-near duplicates (cosine 0.92 or higher on the same entity, with no difference-in a negation, number or date) so the threshold can be measured before it-ever removes anything. A correction such as "is not moving" or a changed-amount is never treated as a duplicate. If the duplicate check cannot read+A reworded copy on the same entity is also skipped when the two are very close+(cosine 0.95 or higher) and do not differ in a negation, number or date. A+correction such as "is not moving" or a changed amount is never treated as a+duplicate, however close the wording. Facts between cosine 0.92 and 0.95 are+always kept; capture only counts them as near duplicates so a lower threshold+can be measured before it ever removes anything. If the duplicate check cannot readthe database, the fact is kept and a warning names the lane. Explicit`remember` is never skipped, so use it for anything that must persist.diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 787e83acba..2aaa39b4af 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -47,7 +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 { cosineVerdict, dedupCapturedFacts, isCaptureLane, withCaptureDrops } from './capture-dedup.ts';import { appendContextNote, type InferredVia } from './subject-infer.ts';import { inferenceNote, inferMissingSubjects } from './subject-infer-write.ts';@@ -693,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). cosineVerdict: 0.95 for explicit lanes; capture lanes never drop by cosine (#5888).+ // at write time). cosineVerdict: 0.95 for explicit lanes; guarded 0.95 for capture lanes (#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,7 +705,7 @@ async function runPipelineBodyInner();let top: { id: number; score: number; fact: string } | null = null;for (const c of candidates) {- if (!c.embedding) continue;+ if (!c.embedding || isCaptureLane(ctx.source) && visibility === 'world' && c.visibility !== 'world') continue;const s = cosineSimilarity(f.embedding, c.embedding);if (!top || s > top.score) top = { id: c.id, score: s, fact: c.fact };}diff --git a/src/core/facts/capture-dedup.ts b/src/core/facts/capture-dedup.tsindex 116a36f5a3..749ca4596b 100644--- a/src/core/facts/capture-dedup.ts+++ b/src/core/facts/capture-dedup.ts@@ -13,10 +13,11 @@* `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+ * The writers' same-entity cosine check keeps its 0.95 drop for capture+ * lanes, but only when the two claims do not differ in a negation, number or+ * date token (a correction is never a duplicate). The 0.92-0.95 band is+ * shadow-only: counted (`near_duplicate` on the `writeback_dedup` heartbeat+ * event) so a lower threshold can be measured, never dropped. A failed* dedup read inserts the candidate (fail open) and warns with the lane.* Explicit lanes (`remember`, extract_facts, sync) never pass through here.*@@ -35,8 +36,8 @@ export const CAPTURE_LANES = ['hook:writeback', 'sweep:corpus', 'hook:compact']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;+/** Same-entity cosine drop; capture lanes apply it only through the claimsDiverge guard. */+export const DUPLICATE_THRESHOLD = 0.95;const CAPTURE_DEDUP_SCAN_LIMIT = 50;export function isCaptureLane(source: string | null | undefined): boolean {@@ -74,12 +75,14 @@ export function claimsDiverge(a: string, b: string): boolean {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.+ * The one cosine policy for every fact-write decision point. Explicit lanes+ * keep the unguarded 0.95 rule; capture lanes drop at 0.95 only when the+ * claims do not diverge, and only count the 0.92-0.95 band.*/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';+ if (!isCaptureLane(source)) return score >= DUPLICATE_THRESHOLD ? 'duplicate' : 'distinct';+ if (score < NEAR_DUPLICATE_THRESHOLD || claimsDiverge(claim, existing)) return 'distinct';+ return score >= DUPLICATE_THRESHOLD ? 'duplicate' : 'near_duplicate';}function nameKey(text: string): string {diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 2fd0d3a5b9..248275d7a7 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -29,7 +29,7 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri}/*** 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).+ * `lane` is the writer's `facts.source`: capture lanes drop at 0.95 only through the claimsDiverge guard (#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=$1diff --git a/test/capture-dedup.test.ts b/test/capture-dedup.test.tsindex 112561de48..37f7b480ef 100644--- a/test/capture-dedup.test.ts+++ b/test/capture-dedup.test.ts@@ -7,11 +7,13 @@* managed coordinator, PGLite): the reproduced `remember` + writeback pair on* two entities ends with one active row; a lagging corpus sweep of the same* conversation dedups across lanes; negation and changed-number pairs at an- * injected cosine of 0.97 both survive; a 0.93 paraphrase is kept and counted- * in shadow mode only; subject-relative claims for two people stay two- * facts; the 15-minute window, the visibility rule and fail-open hold.- * Fails when: dedup stays per entity (2d8801b4), a capture lane drops by- * cosine, or the dedup read error aborts the write.+ * injected cosine of 0.97 both survive (guard); a 0.96 paraphrase is dropped+ * and a 0.93 one is kept and counted in shadow mode only; subject-relative+ * claims for two people stay two facts; the 15-minute window, the visibility+ * rule and fail-open hold.+ * Fails when: dedup stays per entity (2d8801b4), the guard or the shadow+ * band lets a capture lane drop a correction or a 0.92-0.95 fact, or the+ * dedup read error aborts the write.* Existing coverage: none at this boundary (dedup tests were per entity).* Seams: chat + embedding transports only. Synthetic names only.* Backends: PGLite here; with a safe DATABASE_URL also Postgres@@ -192,14 +194,17 @@ for (const mode of ['unmanaged', 'managed'] as const) {expect((await readHeartbeatTail(50)).filter(e => e.event === 'writeback_dedup')).toEqual([]);}), 60_000);- test('a same-entity paraphrase at cosine 0.93 is kept and counted in shadow mode only', () => run(async () => {+ test('a same-entity paraphrase at cosine 0.96 is dropped; one at 0.93 is kept and counted in shadow mode only', () => run(async () => {vectors.set('Alice Example prefers async updates', at(1));+ vectors.set('Alice Example wants async updates', at(0.96));vectors.set('Alice Example likes asynchronous updates', at(0.93));extracts([{ fact: 'Alice Example prefers async updates', entity: 'people/alice-example' }]);await capture('hook:compact', 'sess-4');+ extracts([{ fact: 'Alice Example wants async updates', entity: 'people/alice-example' }]);+ expect(await capture('hook:compact', 'sess-4')).toMatchObject({ inserted: 0, duplicate: 1 });extracts([{ fact: 'Alice Example likes asynchronous updates', entity: 'people/alice-example' }]);expect(await capture('hook:compact', 'sess-4')).toMatchObject({ inserted: 1, duplicate: 0 });- expect((await active()).length).toBe(2);+ expect((await active()).map(f => f.fact)).toEqual(['Alice Example prefers async updates', 'Alice Example likes asynchronous updates']);expect((await readHeartbeatTail(50)).filter(e => e.event === 'writeback_dedup').map(e => [e.reason, e.duplicate, e.near_duplicate])).toEqual([['hook:compact', 0, 1]]);expect((await buildMemoryWritebackCheck(engine)).details).toMatchObject({ cross_lane_duplicates_7d: 0, near_duplicates_shadow_7d: 1 });@@ -219,12 +224,19 @@ for (const mode of ['unmanaged', 'managed'] as const) {extracts([{ fact: claim, entity: 'people/bob-example' }]);expect(await capture('hook:writeback', 'sess-6')).toMatchObject({ inserted: 1 });expect(await capture('hook:writeback', 'sess-7', { visibility: 'world' })).toMatchObject({ inserted: 1, duplicate: 0 });+ // Cross-entity copies (the cosine check is entity-scoped) isolate the 15-minute bound.const later = 'Bob Example owns the Acme Example budget';await remember(later, 'people/bob-example');await age(later, 16);- extracts([{ fact: later, entity: 'people/bob-example' }]);+ extracts([{ fact: later, entity: 'companies/acme-example' }]);expect(await capture('hook:writeback', 'sess-8')).toMatchObject({ inserted: 1, duplicate: 0 });- expect((await active()).map(f => [f.fact === claim, f.visibility])).toEqual([[true, 'private'], [true, 'world'], [false, 'world'], [false, 'private']]);+ const recent = 'Bob Example approves the Acme Example budget';+ await remember(recent, 'people/bob-example');+ await age(recent, 14);+ extracts([{ fact: recent, entity: 'companies/acme-example' }]);+ expect(await capture('hook:writeback', 'sess-8')).toMatchObject({ inserted: 0, duplicate: 1 });+ expect((await active()).map(f => [f.fact === claim, f.entity_slug, f.visibility])).toEqual([[true, 'people/bob-example', 'private'],+ [true, 'people/bob-example', 'world'], [false, 'people/bob-example', 'world'], [false, 'companies/acme-example', 'private'], [false, 'people/bob-example', 'world']]);}), 60_000);test('a dedup read failure inserts the candidate and warns with the lane', () => run(async () => {diff --git a/test/facts/capture-dedup-policy.test.ts b/test/facts/capture-dedup-policy.test.tsindex 4d04ef4769..027d074ca7 100644--- a/test/facts/capture-dedup-policy.test.ts+++ b/test/facts/capture-dedup-policy.test.ts@@ -2,10 +2,11 @@* #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+ * capture lanes drop at 0.95 only through the guard and only count the+ * 0.92-0.95 band, explicit lanes keep their unguarded 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, the shadow band starts dropping, or* the corpus sweep's `sweep:corpus:<file>` key no longer matches the writeback* session id. Pure functions, no engine.*/@@ -20,8 +21,11 @@ describe('cosineVerdict', () => {['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'],+ ['writeback paraphrase at 0.99 is a duplicate', 'hook:writeback', 0.99, same, 'Alice Example relocates to NYC', 'duplicate'],+ ['compact harvest paraphrase at 0.95 is a duplicate', 'hook:compact', 0.95, same, 'Alice Example relocates to NYC', 'duplicate'],+ ['corpus sweep at 0.949 is only a near duplicate', 'sweep:corpus', 0.949, same, 'Alice Example relocates to NYC', 'near_duplicate'],+ ['corpus sweep at 0.93 is only a near duplicate', 'sweep:corpus', 0.93, same, 'Alice Example relocates to NYC', 'near_duplicate'],+ ['a correction at 0.99 is kept by the guard', 'hook:writeback', 0.99, same, 'Alice Example is not moving to NYC', 'distinct'],['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'],