Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): hot memory and delta inject one line per duplicate group (#5888)

garrytan7feb83879307
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 7a8df14bb3..584e1254e9 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,7 +16,7 @@ src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3192 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set
src/core/cycle/synthesize.ts 3293 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option)
src/core/cycle/extract-atoms.ts 1834 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize
-src/core/engine.ts 2674 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option
+src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
src/core/operations.ts 331 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 3cd344897b..8dfef2b9a9 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -35,6 +35,7 @@ import {
} from './retrieval-reflex.ts';
import { volunteerContext, type VolunteeredPage } from './volunteer.ts';
import { getBrainHotMemoryMeta } from '../facts/meta-hook.ts';
+import { collapseHotFacts } from '../facts/capture-dedup.ts';
import { buildEntityCard, type EntityCard, type EntityOpenThread } from '../verbs/entity-card.ts';
import { estimateTokens } from '../search/token-budget.ts';
import type { DecideSlotMeta } from '../search/decide-stage.ts';
@@ -74,6 +75,8 @@ export interface TurnContextFact {
kind: string;
notability?: string | null;
entity_slug: string | null;
+ /** #5888: every entity of a collapsed duplicate group (representative first). */
+ entity_slugs?: string[];
valid_from?: string;
/** Recording time (v0.45.7) — delta's "new since" filter prefers this over valid_from. */
created_at?: string;
@@ -606,8 +609,10 @@ async function assembleDelta(
activeOnly: true,
limit: 50,
visibility,
+ fingerprint: true,
});
- acc.facts = rows
+ // #5888: duplicates collapse to their newest representative, as in hot memory.
+ acc.facts = (await collapseHotFacts(engine, opts.sourceId, rows))
.filter((r) => !since || isAfter(r.created_at.toISOString(), since))
.map((r) => ({
id: r.id,
@@ -615,6 +620,7 @@ async function assembleDelta(
kind: r.kind,
notability: r.notability,
entity_slug: r.entity_slug,
+ ...(r.entity_slugs ? { entity_slugs: r.entity_slugs } : {}),
valid_from: r.valid_from.toISOString(),
created_at: r.created_at.toISOString(),
// #4206: provenance context rides delta like the other projections.
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index c8ce78c9f7..c875788f84 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -383,7 +383,7 @@ export async function listFactsSince(
const excludeAuditRows = opts?.excludeAuditRows === true;
const grepPat = grepPattern(opts);
const rows = (await exec.run<FactRowSqlShape>(sqlFragment`
- SELECT * FROM facts
+ SELECT *${opts?.fingerprint ? sqlFragment`, gbrain_fact_fingerprint(fact) AS fact_fingerprint` : sqlFragment``} FROM facts
WHERE source_id = ${source_id}
AND ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} >= ${since}
${entitySlug ? sqlFragment`AND entity_slug = ${entitySlug}` : sqlFragment``}
@@ -415,7 +415,7 @@ export async function listFactsBySession(
const excludeAuditRows = opts?.excludeAuditRows === true;
const grepPat = grepPattern(opts);
const rows = (await exec.run<FactRowSqlShape>(sqlFragment`
- SELECT * FROM facts
+ SELECT *${opts?.fingerprint ? sqlFragment`, gbrain_fact_fingerprint(fact) AS fact_fingerprint` : sqlFragment``} FROM facts
WHERE source_id = ${source_id}
AND source_session = ${sessionId}
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
@@ -654,6 +654,7 @@ interface FactRowSqlShape {
embedded_text_hash?: string | null;
embedded_at: Date | null;
created_at: Date;
+ fact_fingerprint?: string | null;
}
/**
@@ -705,6 +706,7 @@ function rowToFact(raw: FactRowSqlShape): FactRow {
embedded_text_hash: row.embedded_text_hash ?? null,
embedded_at: row.embedded_at,
created_at: row.created_at,
+ ...(row.fact_fingerprint ? { fact_fingerprint: row.fact_fingerprint } : {}),
};
}
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 0a2378553c..174ea6587b 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -534,6 +534,8 @@ export interface FactRow {
embedding: Float32Array | null;
embedded_at: Date | null;
created_at: Date;
+ /** Set only when the list call asked for `fingerprint` (#5888 hot-memory collapse). */
+ fact_fingerprint?: string;
}
/** Input for insertFact. source_id supplied via the ctx arg. */
@@ -633,6 +635,8 @@ export interface FactListOpts {
* unaffected.
*/
excludeAuditRows?: boolean;
+ /** #5888: listFactsSince/listFactsBySession also select `gbrain_fact_fingerprint(fact)` as `fact_fingerprint`. */
+ fingerprint?: boolean;
}
/** Per-source operational health snapshot consumed by `gbrain doctor`. */
diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.ts
index bb7fdc3c46..daf0505e4a 100644
--- a/src/core/facts/meta-hook.ts
+++ b/src/core/facts/meta-hook.ts
@@ -21,6 +21,7 @@
import type { OperationContext } from './../operations.ts';
import type { FactRow } from './../engine.ts';
import { effectiveConfidence } from './decay.ts';
+import { collapseHotFacts } from './capture-dedup.ts';
const DEFAULT_TTL_MS = 30_000;
const DEFAULT_TOP_K = 10;
@@ -153,24 +154,27 @@ export async function getBrainHotMemoryMeta(
// local → all rows.
const visibility = ctx.remote === false ? undefined : ['world'] as ('world' | 'private')[];
- let rows: FactRow[] = [];
+ // #5888 V2: over-fetch so collapsing duplicates still fills topK.
+ let fetched: FactRow[] = [];
if (sessionId) {
- rows = await ctx.engine.listFactsBySession(sourceId, sessionId, {
- activeOnly: true, limit: topK, visibility,
+ fetched = await ctx.engine.listFactsBySession(sourceId, sessionId, {
+ activeOnly: true, limit: topK * 3, visibility, fingerprint: true,
});
}
// If no session-scoped rows, fall back to recent across the source.
- if (rows.length === 0) {
- rows = await ctx.engine.listFactsSince(sourceId, new Date(Date.now() - 24 * 60 * 60 * 1000), {
- activeOnly: true, limit: topK, visibility,
+ if (fetched.length === 0) {
+ fetched = await ctx.engine.listFactsSince(sourceId, new Date(Date.now() - 24 * 60 * 60 * 1000), {
+ activeOnly: true, limit: topK * 3, visibility, fingerprint: true,
});
}
- if (rows.length === 0) {
+ if (fetched.length === 0) {
store({ expiresAt: Date.now() + ttl, payload: undefined });
return undefined;
}
- // Sort by effective confidence (decayed) before truncating.
+ // One representative per (fingerprint, entity) group, then sort by
+ // effective confidence (decayed) before truncating.
+ let rows = await collapseHotFacts(ctx.engine, sourceId, fetched);
const now = new Date();
rows.sort((a, b) => effectiveConfidence(b, now) - effectiveConfidence(a, now));
rows = rows.slice(0, topK);
@@ -187,6 +191,7 @@ export async function getBrainHotMemoryMeta(
// weight HIGH-tier facts in their context budget.
notability: r.notability,
entity_slug: r.entity_slug,
+ ...(r.entity_slugs ? { entity_slugs: r.entity_slugs } : {}),
valid_from: r.valid_from.toISOString(),
// v0.45.7 ambient recall: recording time, so delta's "new facts since my
// last wake" filters on WHEN the fact was learned, not its semantic