Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(memory-verbs): context_pack and delta facts carry fact_id and provenance (#6146)

time-attackbad13a855879
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index b03961df48..913f1a63bd 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -46,4 +46,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/utils.ts` — Shared SQL utilities used by both engines. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness). `isUndefinedColumnError(err)` predicate — pattern-matches Postgres SQLSTATE 42703 / "column ... does not exist" with engine-driver shape variation tolerated; used by `oauth-provider.ts` so genuine errors (lock timeout, network blip, permission denied) propagate while column-missing falls through to the legacy fallback. `validateSourceId(id)` throws on anything outside `^[a-z0-9_-]+$`, used by the per-source disk-layout fix in patterns.ts/synthesize.ts before any `join(brainDir, '.sources', source_id, slug+'.md')` so source_id can't traverse out of brainDir. `rowToSearchResult` projects email `message_id` / `thread_id` metadata and exposes `source_subject` only when a non-empty Message-ID proves the page is an email, so generated page titles never become authoritative email subjects. `rowToPage` populates the required `Page.source_id` from the SELECT projection (`scripts/check-source-id-projection.sh` enforces every projection feeding `rowToPage` includes the column). `bigintToStringReplacer(key, value)` — the JSON replacer turning `bigint` into strings (the postgres.js int8 wire shape), shared by cli.ts's local-result normalizer (which re-exports it) and the commands that stringify results themselves (`gbrain call`, `extract --explain`); commands import it from here, never from the dispatcher. Its doc comment deliberately carries no double-dash flag literals — the flag-registry generator harvests them from every module a command transitively imports, and utils.ts is imported by nearly all.
-- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.
+- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. The `context_pack` and `delta` fact items advertise optional `fact_id` and `provenance` (#6146). RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index d5b1347abc..a55ca8a306 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -76,7 +76,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); existing private-meeting filtering, source opt-in and source-qualified deduplication still apply. Dual-engine tests in `test/extract-timeline-attendance.test.ts` use an empty gazetteer so a body-mention fallback cannot conceal a broken attendance consumer.
- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.
-- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.
+- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. `context_pack` and `delta` `facts[]` carry recall's `fact_id` and `provenance` (the stored `facts.source`), read in one batched `withProvenance` lookup by the delivered ids, so hot memory and MCP `_meta` stay unchanged; remote callers get provenance through the same redaction as the fact text, and it never enters `text` (#6146, `test/context-pack-fact-traceability.test.ts`). Recall keeps source/visibility and fact filters before per-arm candidate limits. Its default/explicit `facts_first` packing preserves the frozen memory-verb contract, including the positive sub-one budget quirk. Optional `query_first` packs the ranked page prefix first only with a nonblank query and positive finite budget; floor-zero and exhausted remainders explicitly return empty arms rather than call the unbounded zero-budget packer. Neither arm skips oversized prefix items or truncates. No-query and inactive-budget paths keep legacy behavior. Only policy-supplied calls add `budget_packing` effective-policy/reason and candidate/kept/dropped/estimated-used accounting. Counter sums match the frozen fields. Do not change the global packer or fact relevance to implement this policy. Delta rejects calendar-invalid ISO dates and years outside 0001-9999 (on the parsed UTC value) before normalization across fractional-second forms, while preserving valid six-digit microsecond cursors. Delta's per-arm cursor (contributor audit wave P0): the start position resolves `cursor` > `since` (whole tuple, slug only when supplied) > the session row; each arm advances through its delivered prefix only (`src/core/context/delta-cursor.ts`), an arm that failed or never finished holds, the conservative legacy `next_cursor.since`/`slug` never passes the oldest undelivered fact, and a legacy caller at an unpageable same-timestamp boundary is refused with `delta_cursor_upgrade_required`. Incomplete wakes emit `delta_incomplete` (`fix.next: wait`, `report` on the third consecutive wake, counted atomically in `session_context_state.degraded_wakes` with an in-process fallback when the store is down); a failed state read refuses with `unavailable`/`session_state` instead of re-initializing at now. `test/recall-budget-policy.test.ts` pins recall behavior; `test/ambient-recall.test.ts` pins delta cursor validation; `test/delta-cursor-integrity.test.ts` (both engines) pins every no-advance path, the facts drain, legacy safety and the commit-visibility bound.
- `src/core/markdown-code.ts` — `stripCodeBlocks` masks fenced and inline code while preserving every CR/LF and UTF-16 code-unit offset. Citation paragraphs and later link references retain their original boundaries, including after an unclosed fence. `parseTimelineEntries` in `src/core/link-extraction.ts` groups the optional dash with its trailing whitespace so leading whitespace does not trigger overlapping repetition. Existing date and delimiter rules remain unchanged. Standalone backtick and tilde fences require valid closing markers; historical inline triple-backtick spans remain masked. Pinned through real FS/DB link and timeline consumers by `test/timeline-parser-regression.test.ts`; its adversarial whitespace workload runs in a timeout-bounded child process. #6133: inline spans pair backtick runs of equal length (CommonMark), found read-only by `fence-scan.ts` `scanMarkdownCode`/`inlineCodeEndAt` over a view where a bare CR is a space (so a span may still cross one), so a double-backtick span and a span holding a single backtick are masked whole and a backslash-escaped backtick opens nothing; the lint `placeholder-date` rule (`src/commands/lint.ts`) runs over the masked text, so placeholders in inline code no longer fire (`test/lint-3958.test.ts`, `test/timeline-parser-regression.test.ts`).
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 23518cf8ca..75a4c270b4 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -659,6 +659,16 @@ degraded_reason?, budget_tokens?, budget_used?, dropped_count?, core? }`. `text`
pre-rendered, envelope-wrapped injectable block; with `budget_tokens` it is
rendered from the packed sets and never exceeds the declared budget.
+`entities` scopes the cards and open threads, not the facts. The hot-facts arm
+is the session's recent memory (its facts, else the last 24 hours of the
+session's source), the same set every MCP response carries, so a fact about
+another entity, or about none, can appear next to the requested ones. For a
+strictly entity-scoped read use `recall` with `entity` (`gbrain recall --entity
+<slug>`). Each `facts[]` entry (here and in `delta`) carries `fact_id`, the
+opaque id `forget` accepts, and `provenance`, the stored source attribution
+(`remember --provenance`), so a packed fact traces back to its full record;
+neither enters `text`.
+
#### context_pack core memory (additive)
`core: { text, revision, chars_used, chars_limit, pages, truncated }` carries the
@@ -777,8 +787,9 @@ isolation on every read. Remote callers see `visibility = world` facts only.
Read verbs redact credential-shaped values in their responses with the
canonical secret scanner: a value becomes `<REDACTED:pattern>`. `recall`,
-`context_pack` and `delta` redact the facts' `fact`, `context` and `source`
-fields for remote callers (`ctx.remote !== false`; every MCP transport,
+`context_pack` and `delta` redact the facts' `fact`, `context` and provenance
+(`source` and `provenance` in `recall`, `provenance` in `context_pack` and
+`delta`) fields for remote callers (`ctx.remote !== false`; every MCP transport,
including stdio, and thin clients) and return them as stored to the trusted
local CLI, so a remembered credential is readable only with `gbrain recall` on
the brain host. Search results, the rendered `text` and `entity` cards are
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 52d5295fd8..632ba4c2a0 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -609,6 +609,21 @@ function parseEntityList(v: unknown): string[] {
const lineCost = (line: string) => estimateTokens(line + '\n');
const dropAll = <T>(items: T[]) => ({ items: [] as T[], meta: { budget: 0, used: 0, dropped: items.length, kept: 0 } });
+/**
+ * #6146: the stored provenance (`facts.source`, what `remember --provenance`
+ * wrote) of the facts a pack or delta delivers, in one batched read keyed by
+ * the facts' own ids, so hot memory (and every MCP `_meta`) stays unchanged.
+ * Fail-soft like the rest of the pack: a failed read leaves `provenance` null.
+ */
+async function withProvenance<T extends { id: number }>(engine: BrainEngine, sourceId: string, facts: T[]): Promise<Array<T & { provenance: string | null }>> {
+ if (facts.length === 0) return [];
+ const rows = await engine.executeRaw<{ id: number | string; source: string | null }>(
+ 'SELECT id, source FROM facts WHERE source_id = $1 AND id = ANY($2::bigint[])', [sourceId, facts.map((f) => f.id)],
+ ).catch(() => []);
+ const byId = new Map(rows.map((r) => [Number(r.id), r.source]));
+ return facts.map((f) => ({ ...f, provenance: byId.get(f.id) ?? null }));
+}
+
const context_pack: Operation = {
name: 'context_pack',
mutating: false,
@@ -672,7 +687,7 @@ const context_pack: Operation = {
// Pack, price and render the redacted presentation sets (one echo
// dictionary); local callers get the delivered facts back raw below.
- const rawFacts = res.facts ?? [];
+ const rawFacts = await withProvenance(ctx.engine, sourceId, res.facts ?? []);
const view = redactRetrievalOutput([{ cards: res.cards ?? [], facts: rawFacts }], {}).results[0];
let cards = view.cards;
let facts = view.facts;
@@ -727,6 +742,9 @@ const context_pack: Operation = {
// #4206: provenance context (parity with the recall projection).
context: f.context ?? null,
confidence: f.confidence,
+ // #6146: recall's v1 names, so a packed fact traces back to its record.
+ fact_id: String(f.id),
+ provenance: f.provenance,
})),
text,
...(core && core.enabled ? { core: { text: core.text, chars_used: core.chars_used, chars_limit: core.chars_limit, pages: core.pages,
@@ -892,7 +910,7 @@ const delta: Operation = {
// (one echo dictionary). The cursors read the raw rows at the delivered
// index and local callers get the delivered facts back raw below.
const rawPages = res.deltaPages ?? [];
- const rawFacts = res.facts ?? [];
+ const rawFacts = await withProvenance(ctx.engine, sourceId, res.facts ?? []);
const view = redactRetrievalOutput([{ pages: rawPages, facts: rawFacts, threads: res.openThreads ?? [] }], {}).results[0];
let pages = view.pages;
let facts = view.facts;
@@ -1026,6 +1044,9 @@ const delta: Operation = {
// #4206: provenance context (parity with the recall projection).
context: f.context ?? null,
confidence: f.confidence,
+ // #6146: recall's v1 names, so a packed fact traces back to its record.
+ fact_id: String(f.id),
+ provenance: f.provenance,
})),
threads,
text,
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 0bc2a5d0dc..a00681a417 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -795,6 +795,8 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
entity_slug: { type: ['string', 'null'] },
valid_from: { type: 'string' },
confidence: { type: 'number' },
+ fact_id: { type: 'string', description: 'Opaque protocol id — the value forget accepts.' },
+ provenance: { type: ['string', 'null'], description: 'The stored source attribution (remember --provenance).' },
},
},
},
@@ -847,6 +849,8 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
entity_slug: { type: ['string', 'null'] },
valid_from: { type: 'string' },
confidence: { type: 'number' },
+ fact_id: { type: 'string', description: 'Opaque protocol id — the value forget accepts.' },
+ provenance: { type: ['string', 'null'], description: 'The stored source attribution (remember --provenance).' },
},
},
},
diff --git a/test/context-pack-fact-traceability.test.ts b/test/context-pack-fact-traceability.test.ts
new file mode 100644
index 0000000000..f8a1f76081
--- /dev/null
+++ b/test/context-pack-fact-traceability.test.ts
@@ -0,0 +1,79 @@
+/**
+ * #6146: a fact delivered by `context_pack` or `delta` traces back to its
+ * record. Each `facts[]` entry carries recall's v1 names: `fact_id` (the
+ * opaque id `forget` accepts) and `provenance` (the stored source attribution,
+ * what `remember --provenance` wrote). Remote callers get the provenance
+ * through the same credential redaction as the fact text; the trusted local
+ * CLI gets it as stored. The rendered `text` is unchanged: provenance never
+ * enters it.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { randomBytes, randomUUID } from 'node:crypto';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+const rand = (n: number) => [...randomBytes(n)].map(b => ALNUM[b % ALNUM.length]).join('');
+const KEY = ['sk', rand(40)].join('-');
+
+let engine: PGLiteEngine;
+const noop = { info: () => {}, warn: () => {}, error: () => {} };
+const local = (): OperationContext => ({ engine, config: {} as GBrainConfig, logger: noop, dryRun: false, remote: false, sourceId: 'default' }) as OperationContext;
+
+type Fact = { fact: string; entity_slug: string | null; fact_id?: string; provenance?: string | null; id?: number };
+type Body = { facts: Fact[]; text: string };
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.insertFact({ fact: 'Project Boreal uses the colour green.', entity_slug: 'projects/boreal-example', source: 'POC-CORRECTION-2026-10-06', visibility: 'world', embedding: null } as never, { source_id: 'default' });
+ await engine.insertFact({ fact: 'Project Atlas uses the colour blue.', entity_slug: null, source: `test:${KEY}`, visibility: 'world', embedding: null } as never, { source_id: 'default' });
+}, 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ resetGateway();
+});
+
+async function recallIds(): Promise<Map<string, { id: number; source: string }>> {
+ const body = await operationsByName.recall!.handler(local(), { since: '2000-01-01T00:00:00Z' }) as { facts: Array<{ id: number; fact: string; source: string }> };
+ return new Map(body.facts.map(f => [f.fact, { id: f.id, source: f.source }]));
+}
+
+const ARGS = { context_pack: () => ({ entities: 'projects/boreal-example', session_id: randomUUID() }), delta: () => ({ since: '2000-01-01T00:00:00Z' }) } as const;
+
+describe('#6146 context_pack and delta facts carry fact_id and provenance', () => {
+ for (const name of ['context_pack', 'delta'] as const) {
+ test(`${name}, trusted local CLI: fact_id matches recall and provenance is the stored source`, async () => {
+ __resetHotMemoryCacheForTests();
+ const recalled = await recallIds();
+ const body = await operationsByName[name]!.handler(local(), ARGS[name]()) as Body;
+ const boreal = body.facts.find(f => f.fact.startsWith('Project Boreal'))!;
+ const atlas = body.facts.find(f => f.fact.startsWith('Project Atlas'))!;
+ expect(boreal.fact_id).toBe(String(recalled.get(boreal.fact)!.id));
+ expect(boreal.provenance).toBe('POC-CORRECTION-2026-10-06');
+ expect(atlas.fact_id).toBe(String(recalled.get(atlas.fact)!.id));
+ expect(atlas.provenance).toBe(`test:${KEY}`);
+ expect(body.text).not.toContain('POC-CORRECTION');
+ });
+
+ test(`${name}, remote MCP caller: provenance is redacted like the fact text`, async () => {
+ __resetHotMemoryCacheForTests();
+ const res = await dispatchToolCall(engine as never, name, ARGS[name](), { remote: true, transport: 'stdio', sourceId: 'default' });
+ const raw = res.content.map(c => (c as { text?: string }).text ?? '').join('\n');
+ expect(raw.includes(KEY)).toBe(false);
+ const body = JSON.parse((res.content[0] as { text: string }).text) as Body;
+ const atlas = body.facts.find(f => f.fact.startsWith('Project Atlas'))!;
+ expect(atlas.provenance).toBe('test:<REDACTED:openai>');
+ expect(atlas.fact_id).toMatch(/^\d+$/);
+ const boreal = body.facts.find(f => f.fact.startsWith('Project Boreal'))!;
+ expect(boreal.provenance).toBe('POC-CORRECTION-2026-10-06');
+ });
+ }
+});