Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(context): context_pack returns the packed entities' own facts (#6724)

garrytand3247dc44182
diff --git a/docs/.wave18-fragments/lane4.md b/docs/.wave18-fragments/lane4.md
index 3d41b7f3c8..6ea63bc589 100644
--- a/docs/.wave18-fragments/lane4.md
+++ b/docs/.wave18-fragments/lane4.md
@@ -9,10 +9,12 @@ Branch `capy/wave18-lane4`. Every `since` below is a placeholder: stamp the wave
{ since: '0.60.267.0', text: '`volunteer_context` and the retrieval reflex now point at one page per name per source: when a meeting, transcript or note page shares an entity page\'s exact title, the pointer goes to the explicit exact slug, then the linkable entity type, then anything else, as `entity` already chose (#6725). The choice runs after the privacy and activation gate, so a private or withheld entity page falls back to the readable page, and same-title pages in different sources are still both volunteered.' },
// Wave 18 lane 4 (#6723). `since` is a placeholder until the merge-slot stamp.
{ since: '0.60.267.0', text: '`entity` and `context_pack` now resolve names across every source the caller can read, like `volunteer_context` (#6723): the home source first (the connection\'s source, or its GBRAIN_SOURCE / .gbrain-source binding), then the other readable sources sorted by id. A name only another readable source holds now returns a card instead of `found: false`; a name the home source holds still resolves there. `source_id` pins one source (refusals match `recall`: `scope_denied`, `not_found`, `invalid_params`), `context_pack` takes source-qualified `entity_refs`, and every card, `names` row and suggestion carries `source_id`. A bound connection\'s lookups that its own source misses get a `source_binding_narrowed` notice naming where each name resolved. Sources outside the grant are never read; a remote `__all__` still resolves nothing. Each pack card\'s activation verdict, newer mentions, records and page status now come from its own source.' },
+ // Wave 18 lane 4 (#6724). `since` is a placeholder until the merge-slot stamp.
+ { since: '0.60.267.0', text: '`context_pack` now returns `entity_facts[]`, the packed entities\' own facts (up to 5 per card, newest first, read in the card\'s own source and visibility), each tagged with its card\'s `source_id` and `slug` and carrying `fact_id`, confidence, `attributed_to`, provenance and trust (#6724). `facts[]` is unchanged hot memory. `text` gains a `## Entity facts` section before hot memory, and a fact in both renders once. Under `budget_tokens` entity facts pack after cards and before hot facts; a remote caller still never sees a private fact.' },
```
## Regeneration steps (integrator-owned generated files)
-- `bun run build:llms`: `docs/protocol/MEMORY_VERBS_v1.md` gained the "entity source resolution and `source_id`" and "context_pack sources" sections, so `llms-full.txt` is stale (`test/build-llms.test.ts` fails until regenerated).
+- `bun run build:llms`: `docs/protocol/MEMORY_VERBS_v1.md` gained the "entity source resolution and `source_id`", "context_pack sources" and "context_pack entity_facts" sections, so `llms-full.txt` is stale (`test/build-llms.test.ts` fails until regenerated).
- `src/core/operation-manifest.generated.ts` was regenerated in-branch (`bun run build:operation-manifest`) for the new `entity` / `context_pack` params; rerun it after the merge.
- Plugin trees / MCP tool goldens: rerun their generators after the merge (new `source_id`, `prefer_source_id` and `entity_refs` params).
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index 88101bd5ec..0fbed797cd 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -19,7 +19,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/entity-references-config.ts` — the one reader for `entity.names_references` (default on: found `names` rows and siblings carry `referenced_by_count` and a row-level `next` to the card) and `entity.record_types` (comma-separated canonical page types, default empty: no `records`), plus `readRowPageStatus` for `entity.row_page_status` (F3, default on: `page_status` on `context_pack` cards and newer-mention rows and on `get_backlinks` rows; record rows keep it when off). `readEntityReferencesConfig(engine)` fails closed to `{namesRow: true, recordTypes: []}`; the names verb and the MCP instruction builder (`readInstructionContent`) both read it. Test: `test/mcp-instructions-references.test.ts`.
- `src/core/verbs/entity-source.ts` — which sources `entity` and `context_pack` read: `entitySources` returns the walk (home first: the ambient GBRAIN_SOURCE / .gbrain-source binding or a thin client's `prefer_source_id`, else the connection's source; then every other source in `federatedSearchScope` sorted by id; a bound stdio connection walks its binding's explicit-read set; a trusted local `__all__` walks every live source, a remote one stays fail-closed). An explicit `source_id` (or an `entity_refs` item, `entityRefs`) is a pin checked by `federatedSearchScope` + `assertExplicitSourceLive`, refused with recall's selector errors (`scope_denied`, `not_found`, `invalid_params`). `ambientMissNotice` is the `source_binding_narrowed` info notice when the ambient source had no match. Test: `test/entity-source-federation.test.ts`.
-- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote, sources?})`: the zero-LLM sub-100ms card behind the `entity` verb. With `sources` (`selectAcrossSources`), the first source with a hit owns the card and every read behind it, and `card.entity.source_id` names it; suggestions carry `source_id`. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Candidate selection is the exported `selectEntityCandidates(engine, sourceId, name, scope, {omitQuarantined})` (typed result: `hit` with the best page row, its `compiled_truth` a bounded withdrawal-overlaid prefix from `page-window/bounded-lead.ts`, and runners-up, `miss` with keyword near-misses, `withheld` when every match is quarantined and omitted); `entityLookupScope` reads its per-call invariants once (private-page setting, mention policy, source pack, linkable types), and `readAka` is the card's `aka` read. `entity names[]` calls the same three directly. The exact-title / slug-suffix arm and the alias resolver's title check are index scans since v240 (`idx_pages_source_title_lower`, `idx_pages_slug_trgm`). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, live first, then events, references and liveness-exempt `amends`, then ended, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. `context_pack` cards add `newer_mentions` (next entry). With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)).
+- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote, sources?})`: the zero-LLM sub-100ms card behind the `entity` verb. With `sources` (`selectAcrossSources`), the first source with a hit owns the card and every read behind it, and `card.entity.source_id` names it; suggestions carry `source_id`. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Candidate selection is the exported `selectEntityCandidates(engine, sourceId, name, scope, {omitQuarantined})` (typed result: `hit` with the best page row, its `compiled_truth` a bounded withdrawal-overlaid prefix from `page-window/bounded-lead.ts`, and runners-up, `miss` with keyword near-misses, `withheld` when every match is quarantined and omitted); `entityLookupScope` reads its per-call invariants once (private-page setting, mention policy, source pack, linkable types), and `readAka` is the card's `aka` read. `entity names[]` calls the same three directly. The exact-title / slug-suffix arm and the alias resolver's title check are index scans since v240 (`idx_pages_source_title_lower`, `idx_pages_slug_trgm`). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, live first, then events, references and liveness-exempt `amends`, then ended, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. `context_pack` cards add `newer_mentions` (next entry). With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)). `buildEntityCard` also returns `factRows`, the full fact rows the card read (its visibility, eligibility and source already applied), outside the card. `assemblePack` (`src/core/context/turn-context.ts`) turns up to `RECENT_FACTS_CAP` per packed card into `entityFacts`, attributed to the card's `(source_id, slug)` and deduplicated by fact id; `renderPack` puts them under `## Entity facts` before hot memory and renders a fact in both once. The `context_pack` op returns them as `entity_facts[]` beside unchanged `facts[]`, packs them after cards under `budget_tokens`, drops them with their card, and prices a hot fact already shown there at zero. Test: `test/context-pack-entity-facts.test.ts`.
+- `src/core/context/pack-brief.ts` — `contextPackBrief(ctx, p, {sourceId, includePrivate, eligibility})`: the `context_pack` pull brief for a named `counterparty` (`intent` meeting/reply), built on `proactive-brief.ts`; null when no counterparty is passed. Loaded by dynamic import so the op module stays light.
- `src/core/mentions/newer-mentions.ts` — `readNewerMentions(engine, sourceId, slug, {excludePrivate, keepVisibility, charBudget, eligibility, includeQuarantined})`: the entity page's `COALESCE(effective_date, updated_at)`, then `readReferrerPage` (limit `NEWER_MENTIONS_CAP` 8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, within `NEWER_MENTIONS_CARD_CHARS` (2,000) of rendered rows; `more` when further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorized `include_quarantined`; `renderNewerMentionRow` labels each preview with its page's trust fields (`renderTrustedInline`; a quarantined one as external data). `isNewerMentionsEnabled` reads `mentions.newer_on_cards` (unset = on). `assemblePack` (`src/core/context/turn-context.ts`) reads them after cards and hot facts under the pack deadline and `NEWER_MENTIONS_PACK_CHARS` (6,000), `renderPack` puts them in a section after hot memory, and the `context_pack` op packs them last under `budget_tokens`. Test: `test/context-pack-newer-mentions.test.ts`.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index d569079556..a896c179ff 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -77,7 +77,7 @@ rejection of serve-only flags before a brain opens.
- `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/facts/question-recall.ts` — recall's `question`: `parseQuestionParam` refuses `supersessions`, `include_expired` and more than 2,000 characters with the corrected call as `fix.mcp`; `rankFactsByQuestion` resolves `entity` per source to pairs and runs `unlinkedNamesakes` on the whole filtered pool before ranking, embeds the question once through `embedQueryBounded` (the gateway's query-embedding cache, so a `query` of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set `facts_degraded.reason`), ranks with `search/fact-relevance.ts` under the `recall.question_admission` rule (`reserve` default, or `facts_arm`; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through `rowToFact`, counts uncomparable facts (`facts_degraded.unembedded`, the `facts_unembedded` notice with the `embed --stale --facts` preview), sets `calibration` (recall's informational `facts_calibration: {status: 'unmeasured', model_key}`, #6590) when the cosine arm ran on a model with no row in `FACT_ADMISSION_FLOOR_EVIDENCE` (`search/fact-relevance.ts`, shared with doctor `fact_admission_floors`), with the `facts_calibration_unmeasured` info notice deduped per brain per session by its `dedupe_key` (test `test/recall-facts-calibration-6590.test.ts`), and turns a DB error into `unavailable` (`fix.next: wait`). `recallHintNotice` builds `recall_hint`. Tests: `test/recall-question.test.ts` (both engines), `test/recall-question-cli.test.ts`.
-- `src/core/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Every recall response carries `facts_order` (`newest`, or `relevance` when `question` ranked the facts arm through `facts/question-recall.ts`); a `query` call without `question` or a fact filter emits `recall_hint`. `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/ops/facts.ts` — shared fact/memory operations, including `recall` and the `delta` cursor. Every recall response carries `facts_order` (`newest`, or `relevance` when `question` ranked the facts arm through `facts/question-recall.ts`); a `query` call without `question` or a fact filter emits `recall_hint`. `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`). `context_pack` `entity_facts[]` carry the packed cards' own facts (#6724, entry in core-services-3.md). 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 b14e27f480..4f47f765ea 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -902,11 +902,11 @@ synced to a cloud model). `include_private` widens ALL arms in
lockstep, and is honored ONLY for trusted-local callers (`remote === false`); a
remote caller never widens (fail-closed).
-Response: `{ protocol_version, entities, cards[], open_threads[], facts[], text,
+Response: `{ protocol_version, entities, cards[], open_threads[], facts[], entity_facts[], text,
degraded_reason?, budget_tokens?, budget_used?, dropped_count?, core?, pinned_questions?, withheld?, brief? }`. `text` is the
envelope-wrapped injectable block, rendered from the packed sets within `budget_tokens`.
-`entities` scopes cards and threads, not the hot facts (the session's recent
+`entities` scopes cards, threads and `entity_facts`, not the hot facts (the session's recent
memory), so other facts can appear; `recall` with `entity` reads one entity
strictly. `facts[]` here and in `delta` carry `fact_id` (what `forget` takes)
and `provenance` (the stored source), never rendered into `text`.
@@ -925,6 +925,20 @@ verdict, newer mentions, records and `page_status` come from its own source,
never from a same-slug page in another source, and cards are deduplicated by
`(source_id, slug)`.
+#### context_pack entity_facts (additive)
+
+`entity_facts[]` holds the packed entities' own facts: up to 5 per card, newest
+first, read in the card's own source with the card's visibility (world-only
+unless a trusted-local caller passed `include_private`) and eligibility. Each
+row is `{ source_id, slug, fact_id, fact, kind, entity_slug, valid_from?,
+context, confidence, attributed_to, provenance, trust_tier?, origin? }`, where
+`(source_id, slug)` names the card. `facts[]` is unchanged hot memory, so a
+fact can appear in both arrays. `text` renders entity facts under `## Entity
+facts (about the standing entities)` before hot memory, and a fact in both
+renders once, there. Under `budget_tokens` entity facts pack after cards and
+before hot facts, leave with a dropped card (counted in `dropped_count`), and
+a hot fact already shown as an entity fact costs nothing.
+
#### context_pack records (additive)
When `entity.record_types` names page types, each card of the `context_pack`
diff --git a/src/core/context/pack-brief.ts b/src/core/context/pack-brief.ts
new file mode 100644
index 0000000000..a152665f9f
--- /dev/null
+++ b/src/core/context/pack-brief.ts
@@ -0,0 +1,56 @@
+/**
+ * context_pack's pull brief (wave 5 D5), peeled from ops/facts.ts so the
+ * context_pack handler stays under the unlisted module-size cap. Behavior is
+ * unchanged; `BRIEF_INTENTS` here is proactive-brief.ts's list, pinned equal to
+ * ops/facts.ts's literal copy by test/proactive-brief.test.ts.
+ */
+import type { OperationContext } from '../ops/contract.ts';
+import { verbError } from '../ops/contract.ts';
+import { paramUse } from '../ops/op-fix.ts';
+import type { ReadEligibility } from '../eligibility/policy.ts';
+import { assembleBrief, briefView, BRIEF_INTENTS, resolvePullCounterparty } from './proactive-brief.ts';
+
+/**
+ * context_pack's pull brief (wave 5 D5): null unless `counterparty` is given.
+ * An unresolved counterparty is a labelled empty brief, not an error; an
+ * invalid `intent` is invalid_params.
+ */
+export async function contextPackBrief(
+ ctx: OperationContext,
+ p: Record<string, unknown>,
+ opts: { sourceId: string; includePrivate: boolean; eligibility: ReadEligibility },
+): Promise<{ text: string; view: Record<string, unknown> } | null> {
+ if (typeof p.counterparty !== 'string' || !p.counterparty.trim()) return null;
+ if (p.intent !== undefined && !(BRIEF_INTENTS as readonly unknown[]).includes(p.intent)) {
+ throw verbError(
+ 'invalid_params',
+ `context_pack: intent must be one of ${BRIEF_INTENTS.join(', ')}`,
+ `Pass ${paramUse(ctx, 'intent', 'meeting')} or omit it.`,
+ );
+ }
+ const local = ctx.remote === false;
+ const label = {
+ delivery: 'pull' as const,
+ intent: (p.intent as string | undefined) ?? null,
+ ...(local ? {} : { withheld_arms: ['loops'] }),
+ };
+ const cp = await resolvePullCounterparty(ctx.engine, opts.sourceId, p.counterparty.slice(0, 200), {
+ excludePrivate: !opts.includePrivate, eligibility: opts.eligibility,
+ });
+ if (!cp) return { text: '', view: { ...label, counterparty: null, items: [], reason: 'counterparty_unresolved' } };
+ const now = Date.now();
+ const brief = await assembleBrief(ctx.engine, {
+ trigger: 'pull',
+ counterparties: [cp],
+ local,
+ includePrivate: opts.includePrivate,
+ eligibility: opts.eligibility,
+ clock: { now, stopAt: now + CONTEXT_PACK_BRIEF_BUDGET_MS },
+ });
+ const counterparty = { slug: cp.slug, display: cp.display };
+ if (!brief) return { text: '', view: { ...label, counterparty, items: [], reason: 'no_items' } };
+ return { text: brief.text, view: { ...label, counterparty, items: briefView(brief).items } };
+}
+
+/** Wall-clock cap on the pull brief's queries. */
+const CONTEXT_PACK_BRIEF_BUDGET_MS = 1000;
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 92d356eda4..37060a3eeb 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -39,7 +39,8 @@ import { volunteerContext, type VolunteeredPage } from './volunteer.ts';
import { getBrainHotMemoryMeta } from '../facts/meta-hook.ts';
import { collapseHotFacts } from '../facts/capture-dedup.ts';
import type { ArmStatus, RawFactRef } from './delta-cursor.ts';
-import { buildEntityCard, type EntityCard, type EntityOpenThread } from '../verbs/entity-card.ts';
+import { buildEntityCard, RECENT_FACTS_CAP, type EntityCard, type EntityOpenThread } from '../verbs/entity-card.ts';
+import type { FactRow } from '../engine.ts';
import { isNewerMentionsEnabled, readNewerMentions, renderNewerMentionRow, NEWER_MENTIONS_HEADER, NEWER_MENTIONS_PACK_CHARS, type NewerMentions } from '../mentions/newer-mentions.ts';
import { estimateTokens } from '../search/token-budget.ts';
import type { DecideSlotMeta } from '../search/decide-stage.ts';
@@ -99,6 +100,28 @@ export interface TurnContextFact {
origin?: string;
}
+/**
+ * #6724: one fact about a packed entity, from the rows its card already read,
+ * attributed to the card's (source_id, slug). `provenance` is the stored
+ * `facts.source`.
+ */
+export interface EntityFact extends TurnContextFact {
+ source_id: string;
+ slug: string;
+ provenance: string | null;
+}
+
+/** Up to RECENT_FACTS_CAP of a card's fact rows (newest first) as entity facts. */
+function entityFactsOf(card: EntityCard, rows: FactRow[]): EntityFact[] {
+ const iso = (v: Date | string | null | undefined) => (v == null ? undefined : v instanceof Date ? v.toISOString() : String(v));
+ return rows.slice(0, RECENT_FACTS_CAP).map((f) => ({
+ id: Number(f.id), fact: f.fact, kind: f.kind, notability: f.notability ?? null, entity_slug: f.entity_slug,
+ valid_from: iso(f.valid_from), created_at: iso(f.created_at), context: f.context ?? null, attributed_to: f.attributed_to ?? null,
+ confidence: Number(f.confidence), ...trustFields(f.trust_tier, f.write_origin),
+ source_id: card.entity.source_id, slug: card.entity.slug, provenance: f.source ?? null,
+ }));
+}
+
/** One page in a `delta` result (updated after the cursor). */
export interface DeltaPage {
slug: string;
@@ -154,6 +177,8 @@ export interface TurnContextResult {
deltaOverflow?: boolean;
/** pack/delta mode — the hot facts included (structured, for the verb JSON). */
facts?: TurnContextFact[];
+ /** #6724 pack mode — the packed entities' own facts (each card's newest, eligibility applied), deduplicated by id. */
+ entityFacts?: EntityFact[];
/**
* delta mode — per-arm completion captured in the SAME snapshot as the
* arrays: `ok` (read completed), `failed` (read threw), `unknown` (the
@@ -585,7 +610,7 @@ async function assemblePack(
].slice(0, maxEntities);
// Cards and their newer mentions are keyed by (source_id, slug): two pages sharing a slug in two sources are two entities.
- const acc: { cards: EntityCard[]; facts: TurnContextFact[]; withheld: number; mentions: Map<string, NewerMentions> } = { cards: [], facts: [], withheld: 0, mentions: new Map() };
+ const acc: { cards: EntityCard[]; facts: TurnContextFact[]; entityFacts: EntityFact[]; withheld: number; mentions: Map<string, NewerMentions> } = { cards: [], facts: [], entityFacts: [], withheld: 0, mentions: new Map() };
const keyOf = (c: EntityCard) => pageKey({ source_id: c.entity.source_id, slug: c.entity.slug });
// #5575 (CEO-20): context_pack is a proactive surface.
const policy: ReadEligibility = opts.eligibility ?? await proactiveEligibility({ engine }, 'context_pack').catch(() => ({ suppressFlagged: true }));
@@ -606,7 +631,10 @@ async function assemblePack(
const verdict = (await pageActivationVerdicts(engine, [ref], policy)).get(pageKey(ref));
if (verdict?.suppressed) acc.withheld++;
// Under trust.agent_activation=allow (the default) a flagged entity page stays, labeled unconfirmed.
- else if (verdict && !verdict.belowFloor) acc.cards.push(verdict.unconfirmed ? { ...res.card, unconfirmed: true as const } : res.card);
+ else if (verdict && !verdict.belowFloor) {
+ acc.cards.push(verdict.unconfirmed ? { ...res.card, unconfirmed: true as const } : res.card);
+ acc.entityFacts.push(...entityFactsOf(res.card, res.factRows ?? []).filter((f) => !acc.entityFacts.some((e) => e.id === f.id)));
+ }
}
} catch {
/* fail-soft: skip this entity */
@@ -639,13 +667,14 @@ async function assemblePack(
const mentions = new Map(acc.mentions);
const cards = acc.cards.map((c) => (mentions.has(keyOf(c)) ? { ...c, newer_mentions: mentions.get(keyOf(c)) } : c));
const facts = [...acc.facts];
+ const entityFacts = [...acc.entityFacts];
// `since` filter (adversarial review: was documented but dead) — open-thread
// events are cut to those after the cursor, matching the verb contract.
const since = typeof opts.since === 'string' && opts.since.trim() ? opts.since : undefined;
const openThreads = cards
.flatMap((c) => c.open_threads ?? [])
.filter((t) => !since || (t.date !== null && isAfter(t.date, since)));
- const text = renderPack(cards, openThreads, facts, opts.checkpointLinks, sources[0]);
+ const text = renderPack(cards, openThreads, facts, opts.checkpointLinks, sources[0], entityFacts);
return {
text,
pointers: [],
@@ -653,6 +682,7 @@ async function assemblePack(
cards,
openThreads,
facts,
+ ...(entityFacts.length ? { entityFacts } : {}),
mode: 'pack',
...(opts.checkpointLinks?.length ? { checkpointLinks: opts.checkpointLinks } : {}),
...(degradedReason ? { degradedReason } : {}),
@@ -902,6 +932,8 @@ export const renderNewerMentionLines = (c: EntityCard, home?: string): string[]
};
const PACK_HEADERS = ['## Standing entities', '## Open threads', '## Hot memory (recent facts)'] as const;
+/** #6724: the packed entities' own facts render under their own header, before hot memory; a fact in both renders once, here. */
+export const ENTITY_FACTS_HEADER = '## Entity facts (about the standing entities)';
const deltaHeaders = (since?: string): readonly [string, string, string] => {
const s = since ? ` since ${since}` : '';
return [`## Pages changed${s}`, `## New facts${s}`, `## Thread updates${s}`];
@@ -921,9 +953,12 @@ export function renderPack(
facts: TurnContextFact[],
checkpointLinks?: TurnContextResult['checkpointLinks'],
home?: string,
+ entityFacts: TurnContextFact[] = [],
): string {
const links = checkpointLinks ?? [];
- if (!cards.length && !openThreads.length && !facts.length && !links.length) return '';
+ const shown = new Set(entityFacts.map((f) => f.id));
+ const hot = facts.filter((f) => !shown.has(f.id));
+ if (!cards.length && !openThreads.length && !hot.length && !entityFacts.length && !links.length) return '';
const lines: string[] = [TURN_CONTEXT_ENVELOPE];
if (links.length) {
lines.push('', '## Compaction checkpoints');
@@ -937,7 +972,8 @@ export function renderPack(
}
if (cards.length) lines.push('', PACK_HEADERS[0], ...cards.map((c) => renderCardLine(c, home)));
if (openThreads.length) lines.push('', PACK_HEADERS[1], ...openThreads.map(renderThreadLine));
- if (facts.length) lines.push('', PACK_HEADERS[2], ...facts.map(renderFactLine));
+ if (entityFacts.length) lines.push('', ENTITY_FACTS_HEADER, ...entityFacts.map(renderFactLine));
+ if (hot.length) lines.push('', PACK_HEADERS[2], ...hot.map(renderFactLine));
const mentionLines = cards.flatMap((c) => renderNewerMentionLines(c, home));
if (mentionLines.length) lines.push('', NEWER_MENTIONS_HEADER, ...mentionLines);
return lines.join('\n');
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 5bf936fc2a..e7b0a3ccb7 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -715,7 +715,7 @@ const context_pack: Operation = {
annotations: { title: 'context_pack (boundary bundle)', readOnlyHint: true },
handler: async (ctx, p) => {
const { assembleContextPack, renderPack, isAfter, PACK_DEFAULT_MAX_ENTITIES, renderCardLine, renderThreadLine, renderFactLine, packHeaderCost,
- renderNewerMentionLines } = await import('../context/turn-context.ts');
+ renderNewerMentionLines, ENTITY_FACTS_HEADER } = await import('../context/turn-context.ts');
const { NEWER_MENTIONS_HEADER } = await import('../mentions/newer-mentions.ts');
const sourceId = ctx.sourceId ?? 'default';
const rawSince = typeof p.since === 'string' && p.since.trim() ? p.since : undefined;
@@ -751,7 +751,7 @@ const context_pack: Operation = {
// push switch is not read; nothing changes for a caller that does not
// pass it). Open loops are trusted-local only; the change arm is
// world-only unless a trusted caller widened with include_private.
- const pullBrief = await contextPackBrief(ctx, p, { sourceId, includePrivate, eligibility });
+ const pullBrief = await (await import('../context/pack-brief.ts')).contextPackBrief(ctx, p, { sourceId, includePrivate, eligibility });
const res = entities.length === 0
? { cards: [], facts: [], text: '', pointers: [], factsCount: 0 } as unknown as Awaited<ReturnType<typeof assembleContextPack>>
: await assembleContextPack(ctx.engine, {
@@ -807,9 +807,12 @@ const context_pack: Operation = {
...c, ...packRefs.bySlug.get(`${c.entity.source_id}:${c.entity.slug}`), ...statusOf(c.entity.source_id, c.entity.slug),
...(c.newer_mentions ? { newer_mentions: { ...c.newer_mentions, rows: c.newer_mentions.rows.map((r) => ({ ...r, ...statusOf(c.entity.source_id, r.slug) })) } } : {}),
}));
- const view = redactRetrievalOutput([{ cards: withRefs, facts: rawFacts }], {}).results[0];
+ // #6724: the packed cards' own facts (each read in its card's source, world-only for a remote caller).
+ const rawEntityFacts = res.entityFacts ?? [];
+ const view = redactRetrievalOutput([{ cards: withRefs, facts: rawFacts, entity_facts: rawEntityFacts }], {}).results[0];
let cards = view.cards;
let facts = view.facts;
+ let entityFacts = view.entity_facts;
// The SAME since filter the assembler applied (pre-landing review: the raw
// flatMap silently dropped the documented `since` contract from the
// structured array whenever budget packing ran) — shared with the card
@@ -825,8 +828,15 @@ const context_pack: Operation = {
lineCost(renderCardLine(c, walk.home)) + threadsOf(c).reduce((n, t) => n + lineCost(renderThreadLine(t)), 0);
const cardPack = itemBudget > 0 ? packToBudget(cards, cardCost, itemBudget) : dropAll(cards);
cards = cardPack.items;
- const remaining = itemBudget - cardPack.meta.used;
- const factPack = remaining > 0 ? packToBudget(facts, (f) => lineCost(renderFactLine(f)), remaining) : dropAll(facts);
+ // #6724: a dropped card's facts go with it; entity facts pack before hot memory, and a fact in both is priced once.
+ const packed = new Set(cards.map((c) => `${c.entity.source_id}:${c.entity.slug}`));
+ const ofPacked = entityFacts.filter((e) => packed.has(`${e.source_id}:${e.slug}`));
+ const entityBudget = itemBudget - cardPack.meta.used - (ofPacked.length ? lineCost('') + lineCost(ENTITY_FACTS_HEADER) : 0);
+ const entityPack = entityBudget > 0 ? packToBudget(ofPacked, (e) => lineCost(renderFactLine(e)), entityBudget) : dropAll(ofPacked);
+ entityFacts = entityPack.items;
+ const shown = new Set(entityFacts.map((e) => e.id));
+ const remaining = entityBudget - entityPack.meta.used;
+ const factPack = remaining > 0 ? packToBudget(facts, (f) => (shown.has(f.id) ? 0 : lineCost(renderFactLine(f))), remaining) : dropAll(facts);
facts = factPack.items;
// Newer mentions pack last, into what cards and facts left; a card whose block does not fit keeps its card line.
const mentionBudget = remaining - factPack.meta.used - lineCost('') - lineCost(NEWER_MENTIONS_HEADER);
@@ -844,7 +854,7 @@ const context_pack: Operation = {
: dropAll(withRecords);
const keptRecords = new Set(recordPack.items);
cards = cards.map((c) => (renderRecordLines(c).length && !keptRecords.has(c) ? { ...c, records: undefined, sibling_records: undefined } : c));
- droppedCount = cardPack.meta.dropped + factPack.meta.dropped;
+ droppedCount = cardPack.meta.dropped + (view.entity_facts.length - entityFacts.length) + factPack.meta.dropped;
}
const open_threads = cards.flatMap(threadsOf);
// Re-render the injectable block from the FINAL sets (adversarial review):
@@ -852,7 +862,7 @@ const context_pack: Operation = {
// structured arrays report — the assembler's pre-budget rendering would
// overrun the declared budget_tokens. budget_used reports that text.
const recordLines = cards.flatMap(renderRecordLines);
- const basePack = entities.length === 0 ? '' : budgetTokens !== null ? renderPack(cards, open_threads, facts, undefined, walk.home) : res.text;
+ const basePack = entities.length === 0 ? '' : budgetTokens !== null ? renderPack(cards, open_threads, facts, undefined, walk.home, entityFacts) : res.text;
const packText = recordLines.length ? [basePack, ['', RECORDS_HEADER, ...recordLines].join('\n')].filter(Boolean).join('\n') : basePack;
const text = [coreText, pullBrief?.text ?? '', packText].filter(Boolean).join('\n\n');
const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;
@@ -894,6 +904,11 @@ const context_pack: Operation = {
provenance: f.provenance,
...(f.trust_tier ? { trust_tier: f.trust_tier, origin: f.origin } : {}),
})),
+ entity_facts: entityFacts.map((f) => ({
+ source_id: f.source_id, slug: f.slug, fact_id: String(f.id), fact: f.fact, kind: f.kind, entity_slug: f.entity_slug, valid_from: f.valid_from,
+ context: f.context ?? null, confidence: f.confidence, attributed_to: f.attributed_to ?? null, provenance: f.provenance,
+ ...(f.trust_tier ? { trust_tier: f.trust_tier, origin: f.origin } : {}),
+ })),
text,
...(pullBrief ? { brief: pullBrief.view } : {}),
...(withheld ? { suppressed: suppressionSummary(withheld) } : {}),
@@ -910,52 +925,6 @@ const context_pack: Operation = {
},
};
-/**
- * context_pack's pull brief (wave 5 D5): null unless `counterparty` is given.
- * An unresolved counterparty is a labelled empty brief, not an error; an
- * invalid `intent` is invalid_params.
- */
-async function contextPackBrief(
- ctx: OperationContext,
- p: Record<string, unknown>,
- opts: { sourceId: string; includePrivate: boolean; eligibility: import('../eligibility/policy.ts').ReadEligibility },
-): Promise<{ text: string; view: Record<string, unknown> } | null> {
- if (typeof p.counterparty !== 'string' || !p.counterparty.trim()) return null;
- if (p.intent !== undefined && !(BRIEF_INTENTS as readonly unknown[]).includes(p.intent)) {
- throw verbError(
- 'invalid_params',
- `context_pack: intent must be one of ${BRIEF_INTENTS.join(', ')}`,
- `Pass ${paramUse(ctx, 'intent', 'meeting')} or omit it.`,
- );
- }
- const { resolvePullCounterparty, assembleBrief, briefView } = await import('../context/proactive-brief.ts');
- const local = ctx.remote === false;
- const label = {
- delivery: 'pull' as const,
- intent: (p.intent as string | undefined) ?? null,
- ...(local ? {} : { withheld_arms: ['loops'] }),
- };
- const cp = await resolvePullCounterparty(ctx.engine, opts.sourceId, p.counterparty.slice(0, 200), {
- excludePrivate: !opts.includePrivate, eligibility: opts.eligibility,
- });
- if (!cp) return { text: '', view: { ...label, counterparty: null, items: [], reason: 'counterparty_unresolved' } };
- const now = Date.now();
- const brief = await assembleBrief(ctx.engine, {
- trigger: 'pull',
- counterparties: [cp],
- local,
- includePrivate: opts.includePrivate,
- eligibility: opts.eligibility,
- clock: { now, stopAt: now + CONTEXT_PACK_BRIEF_BUDGET_MS },
- });
- const counterparty = { slug: cp.slug, display: cp.display };
- if (!brief) return { text: '', view: { ...label, counterparty, items: [], reason: 'no_items' } };
- return { text: brief.text, view: { ...label, counterparty, items: briefView(brief).items } };
-}
-
-/** Wall-clock cap on the pull brief's queries. */
-const CONTEXT_PACK_BRIEF_BUDGET_MS = 1000;
-
const delta: Operation = {
name: 'delta',
mutating: false,
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 6d8ec6af1c..514f46b93f 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -934,6 +934,29 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
},
},
},
+ // #6724 — ADDITIVE OPTIONAL: the packed entities' own facts, keyed to their card's (source_id, slug); `facts` stays hot memory.
+ entity_facts: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['source_id', 'slug', 'fact_id', 'fact', 'kind'],
+ properties: {
+ source_id: { type: 'string' },
+ slug: { type: 'string', description: 'The card this fact is about.' },
+ fact_id: { type: 'string', description: 'Opaque protocol id — the value forget accepts.' },
+ fact: { type: 'string' },
+ kind: { type: 'string' },
+ entity_slug: { type: ['string', 'null'] },
+ valid_from: { type: 'string' },
+ context: { type: ['string', 'null'] },
+ confidence: { type: 'number' },
+ attributed_to: { type: ['string', 'null'] },
+ provenance: { type: ['string', 'null'], description: 'The stored source attribution (remember --provenance).' },
+ trust_tier: { type: 'string' },
+ origin: { type: 'string' },
+ },
+ },
+ },
text: { type: 'string', description: 'Pre-rendered injectable block (envelope-wrapped).' },
degraded_reason: { type: 'string', description: 'Present when a wall-clock deadline returned a partial pack.' },
budget_tokens: { type: 'integer', description: 'Present when budget_tokens was passed.' },
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 0ef18636ee..59cc8f2184 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -49,7 +49,7 @@ const OPEN_THREADS_CAP = 3;
const OPEN_THREAD_TIMELINE_WINDOW_DAYS = 90;
const SUGGESTION_CAP = 3;
const FACT_FETCH_CAP = 100;
-const RECENT_FACTS_CAP = 5;
+export const RECENT_FACTS_CAP = 5;
export interface EntityCardEdge {
type: string;
@@ -172,6 +172,12 @@ export interface EntityCardResult {
coverage?: MentionCoverage;
/** #6723: the source of the resolved page (absent on a miss). */
source_id?: string;
+ /**
+ * #6724: the full fact rows the card read (newest first, visibility and
+ * eligibility already applied), for context_pack's `entity_facts`. Never part
+ * of the card: the `entity` verb does not return it.
+ */
+ factRows?: FactRow[];
}
export interface EntityCardOpts {
@@ -428,7 +434,7 @@ export async function buildEntityCard(
}
const { row, runnersUp } = selected;
- const card = await assembleCard(engine, hitSource, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});
+ const { card, facts: factRows } = await assembleCard(engine, hitSource, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});
if (opts.includeReferences) {
Object.assign(card, await cardReferences(engine, hitSource, row, opts, scope.excludePrivate, scope.entityTypes),
await readCardIdentity(engine, hitSource, row, { excludePrivate: scope.excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));
@@ -438,6 +444,7 @@ export async function buildEntityCard(
found: true,
card,
source_id: hitSource,
+ factRows,
...(runnersUp.length ? { suggestions: runnersUp } : {}),
};
}
@@ -491,7 +498,7 @@ async function assembleCard(
remote: boolean,
excludePrivate: boolean,
eligibility: ReadEligibility,
-): Promise<EntityCard> {
+): Promise<{ card: EntityCard; facts: FactRow[] }> {
const pageSlug = row.slug;
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
// Facts saved about this entity may sit under a sibling page or the bare subject slug (siblings.ts).
@@ -674,7 +681,7 @@ async function assembleCard(
}
const pageTrust = (await loadPageTrust(engine, [{ source_id: sourceId, slug: pageSlug }]).catch(() => null))?.byKey.get(`${sourceId}\u0000${pageSlug}`);
- return {
+ return { facts, card: {
entity: { slug: pageSlug, title: row.title ?? pageSlug, type: row.type ?? null, source_id: sourceId },
...(pageTrust ?? { trust_tier: 'unknown' as const, origin: 'unrecorded' }),
...(isQuarantined(row.frontmatter) ? { quarantined: true as const } : {}),
@@ -696,7 +703,7 @@ async function assembleCard(
id: String(f.id), fact: f.fact, kind: f.kind, valid_from: f.valid_from ? toIso(f.valid_from as Date | string) : null,
...(f.entity_slug && f.entity_slug !== pageSlug ? { entity_slug: f.entity_slug } : {}),
})) } : {}),
- };
+ } };
}
/** The card's `aka`: the page's normalized aliases (page_aliases reverse lookup); empty on a pre-migration brain. */
diff --git a/test/context-pack-entity-facts.test.ts b/test/context-pack-entity-facts.test.ts
new file mode 100644
index 0000000000..5f79b9290f
--- /dev/null
+++ b/test/context-pack-entity-facts.test.ts
@@ -0,0 +1,106 @@
+/**
+ * #6724: `context_pack` adds `entity_facts[]`, the packed entities' own
+ * facts, beside `facts[]` (the session's hot memory, unchanged).
+ *
+ * Protects: a pack for X on a brain whose newest facts are about Y carries X's
+ * facts, attributed to the card's (source_id, slug), with confidence,
+ * attribution, provenance and trust kept; `facts[]` stays exactly the hot
+ * memory a v1 consumer read before; a fact in both arrays is rendered once in
+ * `text` and priced once under `budget_tokens`; a tiny budget still fits;
+ * remote callers never get a private fact; a federated card's facts come from
+ * its own source. Regression: the pack's only fact arm was source-wide hot
+ * memory, so the packed entities' facts were often absent (#6724).
+ * Synthetic data only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { estimateTokens } from '../src/core/search/token-budget.ts';
+import { __resetHotMemoryCacheForTests } from '../src/core/facts/meta-hook.ts';
+
+let engine: PGLiteEngine;
+const noop = { info() {}, warn() {}, error() {} };
+const ctx = (remote: boolean, grant?: string[]) => ({ engine, config: { engine: 'pglite' }, logger: noop, dryRun: false, remote, sourceId: 'default',
+ takesHoldersAllowList: ['world'], ...(grant ? { auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: grant } } : {}) }) as unknown as OperationContext;
+const pack = async (c: OperationContext, p: Record<string, unknown>) => { __resetHotMemoryCacheForTests(); return await operationsByName.context_pack!.handler(c, p) as any; };
+
+async function person(source: string, slug: string, title: string) {
+ await engine.executeRaw(`INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) VALUES ($1, $2, 'person', $3, $4, '')`, [slug, source, title, `${title} page.`]);
+}
+async function fact(source: string, entity: string, text: string, o: { visibility?: 'world' | 'private'; daysAgo?: number; attributed?: 'assistant' } = {}): Promise<number> {
+ const { id } = await engine.insertFact({ fact: text, kind: 'fact', entity_slug: entity, visibility: o.visibility ?? 'world', source: `provenance:${text.slice(0, 12)}`, confidence: 0.9 } as never, { source_id: source });
+ const at = new Date(Date.now() - (o.daysAgo ?? 0) * 86_400_000).toISOString();
+ await engine.executeRaw('UPDATE facts SET created_at = $1::timestamptz, valid_from = $1::timestamptz WHERE id = $2', [at, id]);
+ if (o.attributed) await engine.executeRaw('UPDATE facts SET attributed_to = $1 WHERE id = $2', [o.attributed, id]);
+ return id;
+}
+
+let aliceOld: number, aliceRecent: number, alicePrivate: number;
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('wiki', 'wiki', '{}') ON CONFLICT (id) DO NOTHING`);
+ await person('default', 'people/alice-example', 'Alice Example');
+ await person('default', 'people/bob-example', 'Bob Example');
+ await person('wiki', 'people/zoe-example', 'Zoe Example');
+ aliceOld = await fact('default', 'people/alice-example', 'Alice Example chairs the ALICE-OLD-SENTINEL review board.', { daysAgo: 40, attributed: 'assistant' });
+ alicePrivate = await fact('default', 'people/alice-example', 'Alice Example ALICE-PRIVATE-SENTINEL salary detail.', { visibility: 'private', daysAgo: 30 });
+ for (let i = 0; i < 30; i++) await fact('default', 'people/bob-example', `Bob Example BOB-HOT-${i} update.`, { daysAgo: 0 });
+ aliceRecent = await fact('default', 'people/alice-example', 'Alice Example ALICE-RECENT-SENTINEL moved to Lisbon.', { daysAgo: 0 });
+ await fact('wiki', 'people/zoe-example', 'Zoe Example ZOE-WIKI-SENTINEL leads the wiki.', { daysAgo: 5 });
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+describe('#6724 context_pack entity_facts', () => {
+ test("a pack for Alice carries Alice's own facts, attributed and labeled, beside unchanged hot memory", async () => {
+ const res = await pack(ctx(true), { entities: 'Alice Example' });
+ const old = res.entity_facts?.find((f: any) => f.fact_id === String(aliceOld));
+ expect(old).toMatchObject({ source_id: 'default', slug: 'people/alice-example', entity_slug: 'people/alice-example', confidence: 0.9,
+ attributed_to: 'assistant', provenance: expect.stringContaining('provenance:') });
+ expect(res.facts.some((f: any) => f.fact_id === String(aliceOld))).toBe(false);
+ const legacy = await pack(ctx(true), { entities: 'Bob Example' });
+ expect(res.facts.map((f: any) => f.fact_id)).toEqual(legacy.facts.map((f: any) => f.fact_id));
+ expect(res.text).toContain('## Entity facts');
+ expect(res.text).toMatch(/\(assistant said\) .*Alice Example chairs the ALICE-OLD-SENTINEL/);
+ expect(res.text.indexOf('ALICE-OLD-SENTINEL')).toBeLessThan(res.text.indexOf('## Hot memory'));
+ });
+
+ test('a fact in both arrays appears in both structured arrays and once in text', async () => {
+ const res = await pack(ctx(true), { entities: 'Alice Example' });
+ expect(res.entity_facts.some((f: any) => f.fact_id === String(aliceRecent))).toBe(true);
+ expect(res.facts.some((f: any) => f.fact_id === String(aliceRecent))).toBe(true);
+ expect(res.text.split('ALICE-RECENT-SENTINEL').length - 1).toBe(1);
+ });
+
+ test('remote callers never get a private entity fact; a trusted include_private pack does', async () => {
+ expect(JSON.stringify(await pack(ctx(true), { entities: 'Alice Example' }))).not.toContain('ALICE-PRIVATE-SENTINEL');
+ const local = await pack(ctx(false), { entities: 'Alice Example', include_private: true });
+ expect(local.entity_facts.some((f: any) => f.fact_id === String(alicePrivate))).toBe(true);
+ });
+
+ test('budgets: a tiny budget fits, and a mid budget prices a shared fact once', async () => {
+ const tiny = await pack(ctx(true), { entities: 'Alice Example', budget_tokens: 5 });
+ expect(tiny.entity_facts ?? []).toEqual([]);
+ for (const budget of [120, 200, 400]) {
+ const res = await pack(ctx(true), { entities: 'Alice Example', budget_tokens: budget });
+ expect(estimateTokens(res.text)).toBeLessThanOrEqual(budget);
+ expect(res.text.split('ALICE-RECENT-SENTINEL').length - 1).toBeLessThanOrEqual(1);
+ }
+ for (let budget = 100; budget <= 260; budget += 8) {
+ const res = await pack(ctx(true), { entities: 'Alice Example', budget_tokens: budget });
+ const ids = (a: any[]) => a.map((f: any) => f.fact_id);
+ if (ids(res.entity_facts).includes(String(aliceRecent)) && res.facts.length) expect(ids(res.facts)).toContain(String(aliceRecent));
+ if (ids(res.entity_facts).length === 2) expect(ids(res.facts)).toContain(String(aliceRecent));
+ }
+ const mid = await pack(ctx(true), { entities: 'Alice Example', budget_tokens: 400 });
+ expect(mid.entity_facts.map((f: any) => f.fact_id)).toContain(String(aliceRecent));
+ expect(mid.text).toContain('ALICE-RECENT-SENTINEL');
+ });
+
+ test("a federated card's facts come from its own source", async () => {
+ const res = await pack(ctx(true, ['default', 'wiki']), { entities: 'Zoe Example' });
+ expect(res.entity_facts.map((f: any) => [f.source_id, f.slug])).toEqual([['wiki', 'people/zoe-example']]);
+ expect(res.entity_facts[0].fact).toContain('ZOE-WIKI-SENTINEL');
+ });
+});