Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(entity): entity and context_pack resolve across the caller's sources (#6723)
garrytanf61ee03cb668
diff --git a/docs/.wave18-fragments/lane4.md b/docs/.wave18-fragments/lane4.mdnew file mode 100644index 0000000000..3d41b7f3c8--- /dev/null+++ b/docs/.wave18-fragments/lane4.md@@ -0,0 +1,18 @@+# Wave 18 lane 4 fragments (integrator: apply, then delete this file)++Branch `capy/wave18-lane4`. Every `since` below is a placeholder: stamp the wave's version at the merge slot.++## BEHAVIOR_CHANGES rows (`src/core/behavior-change-notice.ts`, append at the end of `BEHAVIOR_CHANGES`)++```ts+ // Wave 18 lane 4 (#6725, PR #6745 by @javieraldape). `since` is a placeholder until the merge-slot stamp.+ { 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.' },+```++## 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).+- `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/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.mdindex 12b7248ba8..a219fdb5ec 100644--- a/docs/architecture/key-files/agent-bootstrap-continued.md+++ b/docs/architecture/key-files/agent-bootstrap-continued.md@@ -5,7 +5,7 @@- `src/core/wsl-paths.ts` — WSL Windows-drive path translation shared by the doctor asset checks (`src/commands/doctor-asset-paths.ts`) and hook-transcript confinement (`confineTranscriptPath` above). Exports `WINDOWS_DRIVE_PATH_RE`, `translateWindowsPath(p, mountRoot)` (`C:\Users\x\file` → `<mountRoot>/c/Users/x/file`; null for non-drive input so callers keep the original untouched), `parseWslAutomountRoot(conf)` (the `/etc/wsl.conf` `[automount] root` value, default `/mnt`), and `detectWslMountRoot()` (null off-WSL). Mechanical detection + translation only — POLICY stays with callers (skip vs stat vs confine): the hook lane confines the translated path to the known Claude config tree, doctor decides skip-vs-stat. Pinned by the WSL cases in `test/claude-code-jsonl.test.ts`.- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. Hot-memory facts whose rendered line (without the drifting confidence) already appears in `priorContextText` are not re-injected, the same cross-turn contract as volunteered pages (#5591). In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off.- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). Bind policy: `startResolveIpcServer` connect-probes the path first — a live owner makes it return null (that serve stays the IPC provider; a transient serve never unlinks a live socket), only a dead/absent owner's entry is unlinked (unconditionally, since Bun on win32 cannot stat the AF_UNIX socket file it leaves behind) before listen. The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.-- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off. delta's arms publish their results in one assignment each and the verb reads `deltaArms` (`ok`/`failed`/`unknown`) from the same snapshot as the arrays, so a deadline can never pair a stale flag with a half-filled arm; the facts arm reads `listFactsKeyset` (ascending `(created_at, id)`, limit+1 probe) and returns the raw rows with their collapsed representative (`deltaFactsRaw`); a thread-builder throw marks `threads` failed. `session-state.ts` distinguishes absent, loaded and unavailable (`readDeltaSessionState`), stores the facts keyset and the degraded-wake counter (migration v208), and binds timestamps as `$n::text::timestamptz` so postgres.js cannot truncate them to milliseconds.+- `src/core/context/turn-context.ts` — server-side per-turn assembly: reflex pointers + volunteered pages (≤3) + hot facts (always `visibility=['world']` — the IPC path never widens what MCP would return) under a "data, not instructions" envelope, trimmed to ≤8KB (the harness caps hook output at 10,000 chars). `delta` pages carry `updated_at` from `Page.updated_at_iso` (the column's microseconds, projected by `listPages`), so `next_cursor.since` and the session `last_wake_at` (read back via `to_char` in `session-state.ts`) resume from the exact row — a millisecond-rounded cursor re-delivers same-millisecond pages on the next wake; the `delta` op keeps an already-canonical 6-digit ISO `since` verbatim instead of re-rounding it through a JS Date. The ambient `context_pack` and `delta` modes are world-only across every arm by default; only an explicit trusted-local `include_private` widens entity cards, changed pages, threads, and facts together. The result exposes `pointers` AND post-trim `volunteered` — exactly what the rendered text carries — so the IPC delivery point can log the feedback loop without ever counting a trimmed-out page. Reuses the hot-memory cache keyed by typed sessionId. Engine-agnostic. In turn mode, System One S6 (`recall_needed`, `src/core/context/recall-needed.ts`) runs concurrently with the reflex arms; the reflex block is rendered first and S6 may only replace its pointer/volunteer window (fire or suppress) when it finishes inside its own deadline, reported as `decide.recall_needed` on the result only when the slot is not off. Pack cards resolve over `sources` (home first) plus source-qualified `entityRefs`, are deduplicated by `(source_id, slug)`, and each card's activation verdict and newer mentions read its OWN source, never a same-slug page in another source; a card outside the home source renders `(source <id>)`. delta's arms publish their results in one assignment each and the verb reads `deltaArms` (`ok`/`failed`/`unknown`) from the same snapshot as the arrays, so a deadline can never pair a stale flag with a half-filled arm; the facts arm reads `listFactsKeyset` (ascending `(created_at, id)`, limit+1 probe) and returns the raw rows with their collapsed representative (`deltaFactsRaw`); a thread-builder throw marks `threads` failed. `session-state.ts` distinguishes absent, loaded and unavailable (`readDeltaSessionState`), stores the facts keyset and the degraded-wake counter (migration v208), and binds timestamps as `$n::text::timestamptz` so postgres.js cannot truncate them to milliseconds.- `src/core/context/resolve-ipc.ts` (IPC v2) — discriminated-union requests (absent `kind` = legacy resolve; `turn_context` carries `protocol: 2` + a shared secret from a 0600 file in the data dir, plus an additive `channel` for feedback-loop attribution — wire channel claims are validated to the harness channels at the logging site, anything else logs as the default hook channel), handler map, named response types, per-kind timeouts/size caps, socket + parent dir permissions set before exposure, server-side source binding (cross-source requests rejected), protocol echo (a response without it = stale serve → loud degradation). The connection handler processes exactly ONE request per connection (trailing bytes mid-await never double-process a line or double-log a delivery); the client clamps a too-big request below the message cap by dropping the advisory `priorContextText` BEFORE any conversation turn. Delivery seams: `onDelivered` (resolve kind) and `onTurnContextDelivered` (turn_context kind) both fire ONLY after the response write succeeds — a block abandoned before the serve responded is never counted (serve's callback logs the delivered block's volunteered pages + pointers to `context_volunteer_events` under the request channel); write-accept still isn't proof of injection (the client can trim/drop after receipt), which is why the `volunteer_channels` doctor check reconciles counts against the hook heartbeat. v1 clients and servers interoperate untouched. Serve-delegated sync rides the same socket as three additive secret-gated kinds (`sync_start`/`sync_status`/`sync_abort`, wire shapes + fail-closed option validation in `src/core/context/sync-ipc.ts`): start+poll, one line per connection, O(1) handlers with no server budget race; a pre-delegation serve answers `unknown_kind:*` without the protocol echo and the client degrades to the typed stale-serve refusal.- `src/core/facts/visibility.ts` — `resolveDefaultVisibility(engine)` / `resolveVisibilityParam`: the ONE resolver behind all four facts-visibility default sites (`facts.default_visibility` config key; explicit caller value always wins; invalid values fail closed to private). Bootstrap sets the workspace brain's default to `world` so the principal's own sessions can recall their facts — a documented, security-relevant knob. NOTE the deliberate asymmetry with the ambient-writeback TEMPLATE resolver (writeback-config.ts below): this READ/extract default fail-closes UNSET to private; write GUIDANCE treats unset as world (the `remember` verb's own default) because telling agents to write private-by-default on a default install makes their facts invisible to their own later remote sessions.- **Ambient memory writeback cluster** (opt-in, `memory.auto_writeback = off|salient|all`, default off; guide `docs/guides/ambient-writeback.md`):diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex 954e7ccac2..88101bd5ec 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -18,7 +18,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.- `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-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. 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-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/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/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 4e0271d62b..650d6701f7 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -537,6 +537,29 @@ verbatim name-like lines from the remote-sanitized body, 600 characters perpage and 1,200 per card, `identity_excerpt_omitted[]`); `alias_guidance`(`{ text, requires_surface? }`). `recent_facts[]` (`{ id, fact, kind, valid_from, entity_slug? }`, the 5 newest active saved facts, also those saved under an identity sibling or the bare subject slug, which carry that `entity_slug`); `active_fact_count` and `recall {entity}` cover the same slugs.+#### entity source resolution and `source_id` (additive)++Without `source_id`, `name` and each of `names` resolve across every source+the caller can read: the home source first (the connection's source, or the+ambient GBRAIN_SOURCE / .gbrain-source binding), then the other readable+sources sorted by id, so one brain always resolves a name the same way. The+first source with a hit owns the card, and every read behind it (aliases,+facts, edges, references, identity) uses that source; sources outside the+caller's grant are never read and look like a miss. A remote `__all__` names+no source and still resolves nothing.++`source_id` (one readable source) pins the lookup. A pin outside the grant,+for a removed source or with a malformed id is refused with recall's selector+errors: `scope_denied`, `not_found`, `invalid_params`. `prefer_source_id`+reorders the walk without narrowing it (thin clients send their+.gbrain-source there). When the ambient binding's source has no match, a+`source_binding_narrowed` notice names where each name resolved.++Every card carries `card.entity.source_id`, every `names` row `source_id`,+and each suggestion its `source_id`: `(source_id, slug)` is the entity's+identity, and two pages sharing a slug in two sources are two entities. A+row's `next` names `source_id` when the page is outside the home source.+#### entity open_threads loop backing (additive)On brains running the open-loop engine, `open_threads` entries may@@ -885,6 +908,20 @@ memory), so other facts can appear; `recall` with `entity` reads one entitystrictly. `facts[]` here and in `delta` carry `fact_id` (what `forget` takes)and `provenance` (the stored source), never rendered into `text`.+#### context_pack sources: `source_id`, `entity_refs` (additive)++`entities` resolve like `entity` names: across the caller's readable sources,+home first then by id, unless `source_id` pins one (same selector errors;+`prefer_source_id` reorders only). `entity_refs`+(`[{"source_id": "wiki", "slug": "people/alice-example"}]`, inside the same cap+of 8 after `entities`) packs source-qualified entities, each read only in its+own source and checked like a pin. Every card carries `source_id`; a card+from outside the home source renders as `slug` (source <id>) in `text`, and+its newer-mention continuation names the source. Each card's activation+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 records (additive)When `entity.record_types` names page types, each card of the `context_pack`diff --git a/src/cli/main.ts b/src/cli/main.tsindex ca0958f278..0093637b44 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -1217,8 +1217,8 @@ export async function readStdinBounded(): Promise<string | null> {const NON_SCOPE_SOURCE_ID_OPS = new Set(['get_skill']);/**- * Returns the ambient binding (GBRAIN_SOURCE / .gbrain-source) that was mapped- * onto `source_id`, so an empty result can say what narrowed it; null when the+ * Returns the ambient binding (GBRAIN_SOURCE / .gbrain-source) mapped onto `source_id`+ * (`prefer_source_id` on ops that declare it: it orders a lookup, never narrows it); null when the* scope came from a flag or nothing was mapped.*/export function applyThinClientSourceScope(@@ -1247,7 +1247,7 @@ export function applyThinClientSourceScope(}return null; // ambient env/dotfile scope with nowhere to send it}- params.source_id = resolved;+ params[!explicit && 'prefer_source_id' in op.params ? 'prefer_source_id' : 'source_id'] = resolved;if (explicit) return null;const env = process.env.GBRAIN_SOURCE;return { sourceId: resolved, via: env && env.length > 0 ? 'GBRAIN_SOURCE' : '.gbrain-source' };diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex b5e4126481..92d356eda4 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -239,6 +239,13 @@ export interface AssembleTurnContextOpts {includePrivate?: boolean;/** pack — cap on entity-card fan-out (default 8; push path passes smaller). */maxEntities?: number;+ /**+ * #6723 pack — the sources an unqualified entity name resolves in, home+ * first (verbs/entity-source.ts). Absent: `sourceId` alone.+ */+ sources?: readonly string[];+ /** #6723 pack — source-qualified entities, each resolved in its own source only (after `entities`, inside the same cap). */+ entityRefs?: ReadonlyArray<{ name: string; sourceId: string }>;/*** Wall-clock budget (ms). When set, arms race the deadline and whatever has* resolved is returned as a PARTIAL pack (degradedReason 'deadline'); the@@ -571,11 +578,15 @@ async function assemblePack(): Promise<TurnContextResult> {const remote = opts.includePrivate !== true; // fail-closed: only explicit true widensconst maxEntities = clampPositive(opts.maxEntities, PACK_DEFAULT_MAX_ENTITIES);- const entities = (opts.entities ?? [])- .filter((e) => typeof e === 'string' && e.trim())- .slice(0, maxEntities);+ const sources = opts.sources?.length ? opts.sources : [opts.sourceId];+ const entities = [+ ...(opts.entities ?? []).filter((e) => typeof e === 'string' && e.trim()).map((name) => ({ name, sources })),+ ...(opts.entityRefs ?? []).map((ref) => ({ name: ref.name, sources: [ref.sourceId] })),+ ].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 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 }));// Cooperative deadline (perf review): raceDeadline abandons but cannot stop@@ -585,13 +596,14 @@ async function assemblePack(const deadlineAt =typeof opts.deadlineMs === 'number' && opts.deadlineMs > 0 ? Date.now() + opts.deadlineMs : null;const build = (async () => {- for (const name of entities) {+ for (const { name, sources: nameSources } of entities) {if (deadlineAt !== null && Date.now() >= deadlineAt) return;try {- const res = await buildEntityCard(engine, opts.sourceId, name, { remote, eligibility: policy, omitQuarantined: opts.includeQuarantined !== true });- if (res.found && res.card) {- const verdict = (await pageActivationVerdicts(engine, [{ source_id: opts.sourceId, slug: res.card.entity.slug }], policy))- .get(pageKey({ source_id: opts.sourceId, slug: res.card.entity.slug }));+ const res = await buildEntityCard(engine, nameSources[0]!, name, { remote, eligibility: policy, omitQuarantined: opts.includeQuarantined !== true, sources: nameSources });+ if (res.found && res.card && !acc.cards.some((c) => keyOf(c) === keyOf(res.card!))) {+ // The card's OWN source decides activation: a same-slug page in another source never gates or admits it.+ const ref = { source_id: res.card.entity.source_id, slug: res.card.entity.slug };+ 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);@@ -611,11 +623,11 @@ async function assemblePack(let left = NEWER_MENTIONS_PACK_CHARS;for (const card of acc.cards) {if (left <= 0 || (deadlineAt !== null && Date.now() >= deadlineAt)) return;- const m = await readNewerMentions(engine, opts.sourceId, card.entity.slug,+ const m = await readNewerMentions(engine, card.entity.source_id, card.entity.slug,{ excludePrivate, keepVisibility: remote ? ['world'] : ['private', 'world'], charBudget: left, eligibility: policy, includeQuarantined: opts.includeQuarantined === true });if (!m) continue;- acc.mentions.set(card.entity.slug, m);- left -= renderNewerMentionLines({ ...card, newer_mentions: m }).join('\n').length + 1;+ acc.mentions.set(keyOf(card), m);+ left -= renderNewerMentionLines({ ...card, newer_mentions: m }, sources[0]).join('\n').length + 1;}})();@@ -625,7 +637,7 @@ async function assemblePack(// response could diverge from the rendered text after the first await// downstream. Copies freeze the delivered view.const mentions = new Map(acc.mentions);- const cards = acc.cards.map((c) => (mentions.has(c.entity.slug) ? { ...c, newer_mentions: mentions.get(c.entity.slug) } : c));+ const cards = acc.cards.map((c) => (mentions.has(keyOf(c)) ? { ...c, newer_mentions: mentions.get(keyOf(c)) } : c));const facts = [...acc.facts];// `since` filter (adversarial review: was documented but dead) — open-thread// events are cut to those after the cursor, matching the verb contract.@@ -633,7 +645,7 @@ async function assemblePack(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);+ const text = renderPack(cards, openThreads, facts, opts.checkpointLinks, sources[0]);return {text,pointers: [],@@ -867,8 +879,11 @@ const labeled = (item: { trust_tier?: TrustTier; origin?: string }, text: stringitem.trust_tier ? renderTrustedInline(text, labelOf(item)) : text;const cardSummary = (c: EntityCard, text: string): string =>c.quarantined ? renderTrustedInline(text, { trust_tier: 'external_untrusted', origin: 'quarantined' }) : labeled(c, text);-export const renderCardLine = (c: EntityCard): string =>- `- **${c.entity.title}** → \`${c.entity.slug}\`${c.summary ? ` — ${cardSummary(c, c.summary)}` : c.trust_tier ? ` — ${cardSummary(c, '')}` : ''}${c.relationship_note ? ` [${c.relationship_note}]` : ''} (use get_page/entity before relying on details)`;+/** #6723: a card from outside the pack's home source names its source, so a follow-up reads the right page. */+const sourceNote = (c: EntityCard, home?: string): string =>+ home !== undefined && c.entity.source_id !== undefined && c.entity.source_id !== home ? ` (source ${c.entity.source_id})` : '';+export const renderCardLine = (c: EntityCard, home?: string): string =>+ `- **${c.entity.title}** → \`${c.entity.slug}\`${sourceNote(c, home)}${c.summary ? ` — ${cardSummary(c, c.summary)}` : c.trust_tier ? ` — ${cardSummary(c, '')}` : ''}${c.relationship_note ? ` [${c.relationship_note}]` : ''} (use get_page/entity before relying on details)`;export const renderThreadLine = (t: EntityOpenThread): string =>`- [${t.kind}] ${labeled(t, t.text)}${t.date ? ` (${t.date})` : ''}`;export const renderFactLine = (f: TurnContextFact): string =>@@ -876,13 +891,13 @@ export const renderFactLine = (f: TurnContextFact): string =>export const renderPageLine = (p: DeltaPage): string => `- **${labeled(p, p.title)}** → \`${p.slug}\` (${p.updated_at})`;/** One card's newer-mentions block: a line naming the entity and its page date, then one line per page. [] when there are none. */-export const renderNewerMentionLines = (c: EntityCard): string[] => {+export const renderNewerMentionLines = (c: EntityCard, home?: string): string[] => {const m = c.newer_mentions;if (!m?.rows.length) return [];return [- `- **${c.entity.title}** (\`${c.entity.slug}\`, page dated ${m.since.slice(0, 10)}):`,+ `- **${c.entity.title}** (\`${c.entity.slug}\`${sourceNote(c, home)}, page dated ${m.since.slice(0, 10)}):`,...m.rows.map(renderNewerMentionRow),- ...(m.more ? [` - more pages dated after ${m.since.slice(0, 10)} mention it: entity("${c.entity.slug}") lists them all`] : []),+ ...(m.more ? [` - more pages dated after ${m.since.slice(0, 10)} mention it: entity("${c.entity.slug}"${sourceNote(c, home) ? `, source_id "${c.entity.source_id}"` : ''}) lists them all`] : []),];};@@ -905,6 +920,7 @@ export function renderPack(openThreads: EntityOpenThread[],facts: TurnContextFact[],checkpointLinks?: TurnContextResult['checkpointLinks'],+ home?: string,): string {const links = checkpointLinks ?? [];if (!cards.length && !openThreads.length && !facts.length && !links.length) return '';@@ -919,10 +935,10 @@ export function renderPack('re-pull with get_page. Trust these links over the compaction summary.',);}- if (cards.length) lines.push('', PACK_HEADERS[0], ...cards.map(renderCardLine));+ 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));- const mentionLines = cards.flatMap(renderNewerMentionLines);+ 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/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex 5ddca0c5d1..8d4859a726 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -130,6 +130,15 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["type": "string"},"description": "Or up to 50 names/codes at once: compact rows."+ },+ "source_id": {+ "type": "string",+ "description": "Read only this source. Default: your source first, then every source you can read."+ },+ "prefer_source_id": {+ "type": "string",+ "description": "Source to try first (thin clients send .gbrain-source here); never narrows.",+ "fullSurfaceOnly": true}},"scope": "read",@@ -5177,6 +5186,30 @@ export const OPERATION_MANIFEST: OperationMeta[] = [],"description": "With counterparty: the task the brief is for.","fullSurfaceOnly": true+ },+ "source_id": {+ "type": "string",+ "description": "Resolve entities in this source only. Default: your source first, then every source you can read."+ },+ "entity_refs": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "source_id": {+ "type": "string"+ },+ "slug": {+ "type": "string"+ }+ }+ },+ "description": "Source-qualified entities: [{\"source_id\":\"wiki\",\"slug\":\"people/alice-example\"}]."+ },+ "prefer_source_id": {+ "type": "string",+ "description": "Source to try first (thin clients send .gbrain-source here); never narrows.",+ "fullSurfaceOnly": true}},"scope": "read",diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 24e32f7ccc..efef652762 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -704,6 +704,10 @@ const context_pack: Operation = {include_quarantined: { type: 'boolean', description: 'Admin or memory_confirm: quarantined cards.', fullSurfaceOnly: true },counterparty: { type: 'string', description: 'Person or company (name or slug): adds a pulled brief of dated items about them.', fullSurfaceOnly: true },intent: { type: 'string', enum: [...BRIEF_INTENTS], description: 'With counterparty: the task the brief is for.', fullSurfaceOnly: true },+ source_id: { type: 'string', description: 'Resolve entities in this source only. Default: your source first, then every source you can read.' },+ entity_refs: { type: 'array', items: { type: 'object', properties: { source_id: { type: 'string' }, slug: { type: 'string' } } },+ description: 'Source-qualified entities: [{"source_id":"wiki","slug":"people/alice-example"}].' },+ prefer_source_id: { type: 'string', description: 'Source to try first (thin clients send .gbrain-source here); never narrows.', fullSurfaceOnly: true },},scope: 'read',verb: true,@@ -727,7 +731,12 @@ const context_pack: Operation = {// Echo the CAPPED list (pre-landing review): the assembler bundles at most// PACK_DEFAULT_MAX_ENTITIES, so echoing more would claim entities were// bundled that produced no cards.- const entities = parseEntityList(p.entities).slice(0, PACK_DEFAULT_MAX_ENTITIES);+ const names = parseEntityList(p.entities).slice(0, PACK_DEFAULT_MAX_ENTITIES);+ // #6723: names resolve across the readable sources (home first) unless source_id pins one; entity_refs name their source.+ const { ambientMissNotice, entityRefs, entitySources } = await import('../verbs/entity-source.ts');+ const walk = await entitySources(ctx, p, 'context_pack');+ const refs = (await entityRefs(ctx, p.entity_refs, PACK_DEFAULT_MAX_ENTITIES)).slice(0, PACK_DEFAULT_MAX_ENTITIES - names.length);+ const entities = [...names, ...refs.map((r) => r.name)];// Fail-closed: private only when EXPLICITLY requested AND the caller is// trusted-local (ctx.remote === false). A remote caller never widens.const includePrivate = p.include_private === true && ctx.remote === false;@@ -747,8 +756,10 @@ const context_pack: Operation = {? { cards: [], facts: [], text: '', pointers: [], factsCount: 0 } as unknown as Awaited<ReturnType<typeof assembleContextPack>>: await assembleContextPack(ctx.engine, {sourceId,- entities,since,+ entities: names,+ sources: walk.sources,+ entityRefs: refs,sessionId: typeof p.session_id === 'string' ? p.session_id : undefined,includePrivate,maxEntities: PACK_DEFAULT_MAX_ENTITIES,@@ -778,19 +789,23 @@ const context_pack: Operation = {emitNotice: (n) => ctx.emitNotice?.(n) }).catch((): PackRefs => ({ bySlug: new Map(), notice: null }));if (packRefs.notice) ctx.emitNotice?.(packRefs.notice);+ const ambientNotice = ambientMissNotice('context_pack', walk, (res.cards ?? []).filter((c) => c.entity.source_id !== walk.ambient?.sourceId && !refs.some((r) => r.sourceId === c.entity.source_id && r.name === c.entity.slug))+ .map((c) => ({ name: c.entity.title, foundIn: c.entity.source_id })));+ if (ambientNotice) ctx.emitNotice?.(ambientNotice);// F3 (`entity.row_page_status`, default on): each card and newer-mentions row carries its page's frontmatter `status` (pull verb only).const { readRowPageStatus } = await import('../entity-references-config.ts');const { readPageStatusByRef } = await import('../mentions/referrers.ts');- const statusRefs = (res.cards ?? []).flatMap((c) => [c.entity.slug, ...(c.newer_mentions?.rows ?? []).map((r) => r.slug)]).map((slug) => ({ source_id: sourceId, slug }));+ // #6723: every card, and its newer-mention rows, reads its own source.+ const statusRefs = (res.cards ?? []).flatMap((c) => [c.entity.slug, ...(c.newer_mentions?.rows ?? []).map((r) => r.slug)].map((slug) => ({ source_id: c.entity.source_id, slug })));const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');const pageStatus = statusRefs.length && await readRowPageStatus(ctx.engine)? await readPageStatusByRef(ctx.engine, statusRefs, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, includePrivate ? false : undefined), includeQuarantined }).catch(() => new Map<string, string>()): new Map<string, string>();- const statusOf = (slug: string) => { const value = pageStatus.get(`${sourceId}:${slug}`); return value ? { page_status: value } : {}; };+ const statusOf = (src: string, slug: string) => { const value = pageStatus.get(`${src}:${slug}`); return value ? { page_status: value } : {}; };const withRefs = (res.cards ?? []).map((c) => ({- ...c, ...packRefs.bySlug.get(c.entity.slug), ...statusOf(c.entity.slug),- ...(c.newer_mentions ? { newer_mentions: { ...c.newer_mentions, rows: c.newer_mentions.rows.map((r) => ({ ...r, ...statusOf(r.slug) })) } } : {}),+ ...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];let cards = view.cards;@@ -807,7 +822,7 @@ const context_pack: Operation = {// rendered line plus its rendered (since-filtered) thread lines.const itemBudget = budgetTokens - packHeaderCost() - coreTokens - (pullBrief?.text ? estimateTokens(pullBrief.text) : 0);const cardCost = (c: (typeof cards)[number]) =>- lineCost(renderCardLine(c)) + threadsOf(c).reduce((n, t) => n + lineCost(renderThreadLine(t)), 0);+ 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;@@ -817,7 +832,7 @@ const context_pack: Operation = {const mentionBudget = remaining - factPack.meta.used - lineCost('') - lineCost(NEWER_MENTIONS_HEADER);const withMentions = cards.filter((c) => c.newer_mentions);const mentionPack = mentionBudget > 0- ? packToBudget(withMentions, (c) => renderNewerMentionLines(c).reduce((n, l) => n + lineCost(l), 0), mentionBudget)+ ? packToBudget(withMentions, (c) => renderNewerMentionLines(c, walk.home).reduce((n, l) => n + lineCost(l), 0), mentionBudget): dropAll(withMentions);const keptMentions = new Set(mentionPack.items);cards = cards.map((c) => (c.newer_mentions && !keptMentions.has(c) ? { ...c, newer_mentions: undefined } : c));@@ -837,7 +852,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) : res.text;+ const basePack = entities.length === 0 ? '' : budgetTokens !== null ? renderPack(cards, open_threads, facts, undefined, walk.home) : 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;@@ -847,6 +862,7 @@ const context_pack: Operation = {entities,cards: cards.map((c) => ({slug: c.entity.slug,+ source_id: c.entity.source_id,title: c.entity.title,type: c.entity.type,...(c.page_status ? { page_status: c.page_status } : {}),diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex a9524aecd5..f4d509bdb1 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -221,12 +221,21 @@ const entity: Operation = {params: {name: { type: 'string', description: 'Name, alias or slug.' },names: { type: 'array', items: { type: 'string' }, description: 'Or up to 50 names/codes at once: compact rows.' },+ source_id: { type: 'string', description: 'Read only this source. Default: your source first, then every source you can read.' },+ prefer_source_id: { type: 'string', description: 'Source to try first (thin clients send .gbrain-source here); never narrows.', fullSurfaceOnly: true },},scope: 'read',verb: true,annotations: { title: 'entity (card lookup, zero LLM)', readOnlyHint: true },handler: async (ctx, p) => {const { verbError } = await import('./operations.ts');+ // #6723: resolve across the caller's readable sources (home first) unless source_id pins one.+ const { ambientMissNotice, entitySources } = await import('./verbs/entity-source.ts');+ const walk = await entitySources(ctx, p, 'entity');+ const ambientMiss = (misses: Array<{ name: string; foundIn?: string }>) => {+ const notice = ambientMissNotice('entity', walk, misses.filter(m => m.foundIn !== walk.ambient?.sourceId));+ if (notice) ctx.emitNotice?.(notice);+ };if (p.names !== undefined) {const { ENTITY_NAMES_MAX, lookupEntityNames } = await import('./verbs/entity-names.ts');const names = Array.isArray(p.names) ? p.names.filter((n): n is string => typeof n === 'string' && n.trim() !== '') : [];@@ -235,8 +244,9 @@ const entity: Operation = {`Pass either name: "Alice Example" for one full card, or names: ["Alice Example", "WGCO"] (up to ${ENTITY_NAMES_MAX}) for compact rows.`);}const t0 = Date.now();- const out = await lookupEntityNames(ctx.engine, ctx.sourceId ?? 'default', names, { remote: ctx.remote !== false, surfaceCeiling: ctx.surfaceCeiling,+ const out = await lookupEntityNames(ctx.engine, walk.home, names, { remote: ctx.remote !== false, sources: walk.sources, surfaceCeiling: ctx.surfaceCeiling,emitNotice: n => ctx.emitNotice?.(n) });+ ambientMiss(out.results.map(r => ({ name: r.name, ...(r.found ? { foundIn: r.source_id } : {}) })));return { protocol_version: 1, latency_ms: Date.now() - t0, ...out };}const name = typeof p.name === 'string' ? p.name.trim() : '';@@ -249,8 +259,8 @@ const entity: Operation = {}const t0 = Date.now();const { buildEntityCard } = await import('./verbs/entity-card.ts');- const result = await buildEntityCard(ctx.engine, ctx.sourceId ?? 'default', name, {- remote: ctx.remote !== false, includeReferences: true, surfaceCeiling: ctx.surfaceCeiling,+ const result = await buildEntityCard(ctx.engine, walk.home, name, {+ remote: ctx.remote !== false, includeReferences: true, surfaceCeiling: ctx.surfaceCeiling, sources: walk.sources,omitQuarantined: ctx.remote !== false, // #5575: like get_page, a remote reader never gets a quarantined page's cardemitNotice: n => ctx.emitNotice?.(n),});@@ -260,6 +270,7 @@ const entity: Operation = {const notice = mentionCoverageNotice(coverage, result.card?.entity.type);if (notice) ctx.emitNotice?.(notice);}+ ambientMiss([{ name, ...(result.source_id ? { foundIn: result.source_id } : {}) }]);if (result.card?.identity_siblings?.capped) {const { siblingsCappedNotice } = await import('./verbs/entity-card-identity.ts');ctx.emitNotice?.(siblingsCappedNotice(result.card.entity.slug));@@ -659,7 +670,11 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {entity: {type: 'object',required: ['slug', 'title', 'type'],- properties: { slug: { type: 'string' }, title: { type: 'string' }, type: { type: ['string', 'null'] } },+ properties: {+ slug: { type: 'string' }, title: { type: 'string' }, type: { type: ['string', 'null'] },+ // #6723 — ADDITIVE OPTIONAL: (source_id, slug) is the entity's identity.+ source_id: { type: 'string' },+ },},aka: { type: 'array', items: { type: 'string' } },summary: { type: 'string' },@@ -744,6 +759,7 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {slug: { type: 'string' },title: { type: 'string' },create_safety: { type: 'string', enum: CREATE_SAFETY_ENUM },+ source_id: { type: 'string' },},},},@@ -831,6 +847,8 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {required: ['slug', 'title', 'summary', 'open_threads'],properties: {slug: { type: 'string' },+ // #6723 — ADDITIVE OPTIONAL: the card page's source; (source_id, slug) is the entity's identity.+ source_id: { type: 'string' },title: { type: 'string' },type: { type: ['string', 'null'] },summary: { type: 'string' },diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.tsindex f808b70b05..0ef18636ee 100644--- a/src/core/verbs/entity-card.ts+++ b/src/core/verbs/entity-card.ts@@ -83,7 +83,8 @@ export interface EntityOpenThread {}export interface EntityCard {- entity: { slug: string; title: string; type: string | null };+ /** #6723: `source_id` is the source the page lives in; (source_id, slug) is the entity's identity. */+ entity: { slug: string; title: string; type: string | null; source_id: string };/** page_aliases reverse lookup (normalized forms). Empty on pre-migration brains. */aka: string[];/** Privacy-safe synopsis — same fence boundary as get_page. */@@ -159,6 +160,8 @@ export interface EntitySuggestion {slug: string;title: string;create_safety: string;+ /** #6723: the source the suggested page lives in. */+ source_id?: string;}export interface EntityCardResult {@@ -167,10 +170,18 @@ export interface EntityCardResult {suggestions?: EntitySuggestion[];/** On a miss with `includeReferences`: the source's mention coverage (a miss may be a not-yet-indexed name). */coverage?: MentionCoverage;+ /** #6723: the source of the resolved page (absent on a miss). */+ source_id?: string;}export interface EntityCardOpts {remote: boolean;+ /**+ * #6723: the sources to resolve the name in, probed in this order (home+ * first); the first source with a hit owns the card and every read behind+ * it. Absent: the positional source alone.+ */+ sources?: readonly string[];/*** Compute `referenced_by`, `referenced_by_count` and `coverage` (the `entity`* verb). Ambient callers (context_pack, delta) leave it off.@@ -255,7 +266,7 @@ export async function selectEntityCandidates(sourceId: string,trimmed: string,scope: EntityLookupScope,- opts: { omitQuarantined?: boolean } = {},+ opts: { omitQuarantined?: boolean; suggest?: boolean } = {},): Promise<EntityCandidates> {const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');// Predicate text lives ONCE (private-visibility.ts) — both card queries@@ -351,7 +362,9 @@ export async function selectEntityCandidates(if (live.length === 0) return { kind: 'withheld' };candidates.splice(0, candidates.length, ...live);}- if (candidates.length === 0) return { kind: 'miss', suggestions: await nearMissSuggestions(engine, sourceId, trimmed, scope.excludePrivate) };+ if (candidates.length === 0) {+ return { kind: 'miss', suggestions: opts.suggest === false ? [] : await nearMissSuggestions(engine, sourceId, trimmed, scope.excludePrivate) };+ }// Large pages: the hit carries a bounded, withdrawal-overlaid body prefix (its summary and lead read only that).const [row] = await overlaidBoundedRows(engine, [candidates[0].row]);@@ -363,10 +376,36 @@ export async function selectEntityCandidates(title: c.row.title ?? c.slug,// A page that resolved through the precision arms exists by definition.create_safety: 'exists',+ source_id: sourceId,})),};}+/**+ * #6723: resolve a name across sources in the given order (home first, then+ * the rest of the caller's grant). The first source with a hit owns the+ * result; a source is read with its own lookup scope (pack, linkable types).+ * Without a hit anywhere, the first source's miss (its near-miss suggestions)+ * or withheld result is returned. Sources outside the list are never read.+ */+export async function selectAcrossSources(+ engine: BrainEngine,+ sources: readonly string[],+ trimmed: string,+ remote: boolean,+ opts: { omitQuarantined?: boolean; scopes?: Map<string, Promise<EntityLookupScope>> } = {},+): Promise<{ sourceId: string; scope: EntityLookupScope; selected: EntityCandidates }> {+ let first: { sourceId: string; scope: EntityLookupScope; selected: EntityCandidates } | undefined;+ for (const sourceId of sources) {+ if (opts.scopes && !opts.scopes.has(sourceId)) opts.scopes.set(sourceId, entityLookupScope(engine, sourceId, remote));+ const scope = await (opts.scopes?.get(sourceId) ?? entityLookupScope(engine, sourceId, remote));+ const selected = await selectEntityCandidates(engine, sourceId, trimmed, scope, { omitQuarantined: opts.omitQuarantined, suggest: first === undefined });+ if (selected.kind === 'hit') return { sourceId, scope, selected };+ first ??= { sourceId, scope, selected };+ }+ return first!;+}+export async function buildEntityCard(engine: BrainEngine,sourceId: string,@@ -377,26 +416,28 @@ export async function buildEntityCard(if (!trimmed) return { found: false, suggestions: [] };// Covers entity, context_pack, and delta (all route through buildEntityCard).- const scope = await entityLookupScope(engine, sourceId, opts.remote);- const selected = await selectEntityCandidates(engine, sourceId, trimmed, scope, { omitQuarantined: opts.omitQuarantined });+ // #6723: the source with the hit owns the card; every read below uses it.+ const sources = opts.sources?.length ? opts.sources : [sourceId];+ const { sourceId: hitSource, scope, selected } = await selectAcrossSources(engine, sources, trimmed, opts.remote, { omitQuarantined: opts.omitQuarantined });if (selected.kind === 'withheld') return { found: false, suggestions: [] };if (selected.kind === 'miss') {return {found: false, suggestions: selected.suggestions,- ...(opts.includeReferences ? { coverage: await readMentionCoverage(engine, [sourceId]).catch(() => undefined) } : {}),+ ...(opts.includeReferences ? { coverage: await readMentionCoverage(engine, [...sources]).catch(() => undefined) } : {}),};}const { row, runnersUp } = selected;- const card = await assembleCard(engine, sourceId, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});+ const card = await assembleCard(engine, hitSource, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});if (opts.includeReferences) {- Object.assign(card, await cardReferences(engine, sourceId, row, opts, scope.excludePrivate, scope.entityTypes),- await readCardIdentity(engine, sourceId, row, { excludePrivate: scope.excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));- await attachCardRecords(engine, sourceId, card, opts, scope.excludePrivate);+ 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 }));+ await attachCardRecords(engine, hitSource, card, opts, scope.excludePrivate);}return {found: true,card,+ source_id: hitSource,...(runnersUp.length ? { suggestions: runnersUp } : {}),};}@@ -634,7 +675,7 @@ async function assembleCard(const pageTrust = (await loadPageTrust(engine, [{ source_id: sourceId, slug: pageSlug }]).catch(() => null))?.byKey.get(`${sourceId}\u0000${pageSlug}`);return {- entity: { slug: pageSlug, title: row.title ?? pageSlug, type: row.type ?? null },+ 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 } : {}),aka,@@ -694,6 +735,7 @@ async function nearMissSuggestions(slug: r.slug,title: r.title ?? r.slug,create_safety: r.create_safety ?? 'unknown',+ source_id: r.source_id ?? sourceId,}));} catch {return [];diff --git a/src/core/verbs/entity-names.ts b/src/core/verbs/entity-names.tsindex 6ef286bb26..5335cf4f91 100644--- a/src/core/verbs/entity-names.ts+++ b/src/core/verbs/entity-names.ts@@ -19,7 +19,7 @@* RECORD_ROWS_PER_CALL per call, allotted in input order.*/import type { BrainEngine } from '../engine.ts';-import { entityLookupScope, readAka, selectEntityCandidates, type EntityLookupScope } from './entity-card.ts';+import { readAka, selectAcrossSources, type EntityLookupScope } from './entity-card.ts';import { readSiblingIdentity } from './entity-card-identity.ts';import { boundedProjectedPrefix } from '../page-window/document.ts';import { boundedBodyPrefixSql, overlaidBoundedRows } from '../page-window/bounded-lead.ts';@@ -34,7 +34,7 @@ const CONCURRENCY = 8;export interface EntityNamePage extends RowReferences { slug: string; title: string; type: string | null; aka: string[]; lead: string }export type EntityNameRow =- | ({ name: string; found: true } & EntityNamePage & { siblings?: EntityNamePage[] })+ | ({ name: string; found: true; source_id: string } & EntityNamePage & { siblings?: EntityNamePage[] })| { name: string; found: false; suggestions?: Array<{ slug: string; title: string }> };/** The opening prose of a page body: fences and secrets removed, headings, markers and table rows dropped, up to `max` characters. */@@ -47,28 +47,39 @@ export function pageLead(body: string | null, max = ENTITY_LEAD_CHARS): string {}export async function lookupEntityNames(engine: BrainEngine, sourceId: string, names: string[],- opts: { remote: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<{ results: EntityNameRow[]; found: number; missing: number }> {+ opts: { remote: boolean; sources?: readonly string[]; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<{ results: EntityNameRow[]; found: number; missing: number }> {const unique = [...new Set(names.map(n => n.trim()).filter(Boolean))];- const scope = await entityLookupScope(engine, sourceId, opts.remote);+ // #6723: each name resolves in the first source (home first) with a hit; a source's lookup scope is read once per batch.+ const sources = opts.sources?.length ? opts.sources : [sourceId];+ const scopes = new Map<string, Promise<EntityLookupScope>>();+ const excludePrivate = new Map<string, boolean>();const rows = new Map<string, EntityNameRow>();for (let i = 0; i < unique.length; i += CONCURRENCY) {- await Promise.all(unique.slice(i, i + CONCURRENCY).map(async name => rows.set(name, await lookupOne(engine, sourceId, name, scope, opts))));+ await Promise.all(unique.slice(i, i + CONCURRENCY).map(async name => {+ const { sourceId: hitSource, scope, selected } = await selectAcrossSources(engine, sources, name, opts.remote, { omitQuarantined: opts.remote, scopes });+ excludePrivate.set(hitSource, scope.excludePrivate);+ rows.set(name, await lookupOne(engine, hitSource, name, scope, selected, opts));+ }));}const results = unique.map(n => rows.get(n)!);- await attachReferences(engine, sourceId, results, scope.excludePrivate, opts);+ for (const [src, exclude] of excludePrivate) {+ await attachReferences(engine, src, results.filter(r => r.found && r.source_id === src), exclude, { ...opts, home: sources[0]! });+ }const found = results.filter(r => r.found).length;return { results, found, missing: results.length - found };}-/** One batched reference read for every found page and sibling, in input order (page first, then its siblings). */+/** One batched reference read per source for every found page and sibling, in input order (page first, then its siblings). */async function attachReferences(engine: BrainEngine, sourceId: string, results: EntityNameRow[], excludePrivate: boolean,- opts: { remote: boolean; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<void> {+ opts: { remote: boolean; home: string; surfaceCeiling?: 'verbs' | 'starter' | 'full'; emitNotice?: (n: Notice) => void }): Promise<void> {const pages: EntityNamePage[] = [];for (const r of results) if (r.found) pages.push(r, ...(r.siblings ?? []));if (!pages.length) return;const refs = await readRowReferences(engine, sourceId, pages.map(p => ({ slug: p.slug, sourceId })),{ remote: opts.remote, excludePrivate, surfaceCeiling: opts.surfaceCeiling, surface: 'names', emitNotice: opts.emitNotice });- pages.forEach((p, i) => Object.assign(p, refs.rows[i]));+ // A follow-up for a page outside the caller's home source names its source.+ pages.forEach((p, i) => Object.assign(p, refs.rows[i], sourceId !== opts.home && refs.rows[i]?.next+ ? { next: { ...refs.rows[i]!.next, arguments: { ...refs.rows[i]!.next!.arguments, source_id: sourceId } } } : {}));if (refs.notice) opts.emitNotice?.(refs.notice);if (!refs.rows.some(r => r.referenced_by_count !== undefined || r.records)) return;const coverage = await readMentionCoverage(engine, [sourceId]).catch(() => null);@@ -77,8 +88,7 @@ async function attachReferences(engine: BrainEngine, sourceId: string, results:}async function lookupOne(engine: BrainEngine, sourceId: string, name: string, scope: EntityLookupScope,- opts: { remote: boolean }): Promise<EntityNameRow> {- const selected = await selectEntityCandidates(engine, sourceId, name, scope, { omitQuarantined: opts.remote });+ selected: Awaited<ReturnType<typeof selectAcrossSources>>['selected'], opts: { remote: boolean }): Promise<EntityNameRow> {if (selected.kind !== 'hit') {const suggestions = (selected.kind === 'miss' ? selected.suggestions : []).slice(0, 3).map(s => ({ slug: s.slug, title: s.title }));return { name, found: false, ...(suggestions.length ? { suggestions } : {}) };@@ -96,7 +106,7 @@ async function lookupOne(engine: BrainEngine, sourceId: string, name: string, scfor (const s of await overlaidBoundedRows(engine, sib)) bodies.set(s.slug, s.compiled_truth);}return {- name, found: true, slug: row.slug, title: row.title ?? row.slug, type: row.type ?? null, aka, lead: pageLead(bodies.get(row.slug) ?? null),+ name, found: true, source_id: sourceId, slug: row.slug, title: row.title ?? row.slug, type: row.type ?? null, aka, lead: pageLead(bodies.get(row.slug) ?? null),...(siblingPages.length ? { siblings: siblingPages.map(p => ({ slug: p.slug, title: p.title, type: p.type, aka: p.aka, lead: pageLead(bodies.get(p.slug) ?? null) })) } : {}),};}diff --git a/src/core/verbs/entity-references.ts b/src/core/verbs/entity-references.tsindex 95df8cb038..6ae6a27e49 100644--- a/src/core/verbs/entity-references.ts+++ b/src/core/verbs/entity-references.ts@@ -53,7 +53,7 @@ export interface RecordGroupView {/** What a row gains: absent fields are switched off by config. */export interface RowReferences {referenced_by_count?: number;- next?: { tool: 'entity'; arguments: { name: string } };+ next?: { tool: 'entity'; arguments: { name: string; source_id?: string } };records?: RecordGroupView[];/** The count and records could not be read in time (or failed); not "no references". */references_unavailable?: ReferencesUnavailable;@@ -161,13 +161,29 @@ export interface PackCardReferences extends RowReferences {* records of each card's page and its identity siblings, side by side, in one* batched read. Nothing is read unless record types are enrolled.*/-export async function readPackReferences(engine: BrainEngine, sourceId: string, cards: Array<{ entity: { slug: string; title: string } }>,+export async function readPackReferences(engine: BrainEngine, sourceId: string, cards: Array<{ entity: { slug: string; title: string; source_id?: string } }>,req: Omit<ReferencesRequest, 'surface' | 'excludePrivate'>): Promise<{ bySlug: Map<string, PackCardReferences>; notice: Notice | null }> {const bySlug = new Map<string, PackCardReferences>();const config = req.config ?? await readEntityReferencesConfig(engine);if (!cards.length || !referencesWanted(config, 'pack')) return { bySlug, notice: null };const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');const excludePrivate = await resolveExcludePrivatePages(engine, req.remote ? undefined : false);+ // #6723: each card reads its own source (one batch per source); the map is keyed `<source_id>:<slug>`.+ const bySource = new Map<string, typeof cards>();+ for (const c of cards) bySource.set(c.entity.source_id ?? sourceId, [...(bySource.get(c.entity.source_id ?? sourceId) ?? []), c]);+ let notice: Notice | null = null;+ for (const [src, group] of bySource) {+ const part = await readSourcePackReferences(engine, src, group, { ...req, excludePrivate, config });+ for (const [slug, refs] of part.bySlug) bySlug.set(`${src}:${slug}`, refs);+ notice ??= part.notice;+ }+ return { bySlug, notice };+}++async function readSourcePackReferences(engine: BrainEngine, sourceId: string, cards: Array<{ entity: { slug: string; title: string } }>,+ req: Omit<ReferencesRequest, 'surface'> & { config: EntityReferencesConfig }): Promise<{ bySlug: Map<string, PackCardReferences>; notice: Notice | null }> {+ const bySlug = new Map<string, PackCardReferences>();+ const { excludePrivate, config } = req;const { readIdentitySiblings } = await import('../mentions/siblings.ts');const siblings = await Promise.all(cards.map(c => readIdentitySiblings(engine, sourceId, c.entity, { excludePrivate, excludeQuarantined: true })));const targets: RecordTarget[] = [];diff --git a/src/core/verbs/entity-source.ts b/src/core/verbs/entity-source.tsnew file mode 100644index 0000000000..1787a9d569--- /dev/null+++ b/src/core/verbs/entity-source.ts@@ -0,0 +1,125 @@+/**+ * #6723: which sources an `entity` or `context_pack` lookup reads, in order.+ *+ * - An explicit `source_id` pins the lookup to that one source. The grant+ * check and liveness check are the same ones `recall` runs+ * (federatedSearchScope + assertExplicitSourceLive), and their refusals+ * come back as recall's selector errors: `scope_denied`, `not_found`,+ * `invalid_params`.+ * - Without a pin the lookup walks the caller's read scope: the home source+ * first (the ambient binding when one is in force, else the connection's+ * source), then every other readable source sorted by id, so the same+ * brain always resolves a name the same way. A stdio connection bound by+ * GBRAIN_SOURCE or .gbrain-source walks the sources it may name+ * explicitly; a thin client sends its ambient source as `prefer_source_id`,+ * which only reorders the walk and never adds a source to it.+ * - Sources outside the scope are never read, so they look exactly like a+ * miss. A remote `__all__` stays fail-closed (it names no real source); a+ * trusted local `__all__` walks every live source.+ */+import type { Notice } from '../agent-output.ts';+import type { OperationContext } from '../ops/contract.ts';+import { OperationError, verbError } from '../ops/contract.ts';+import { assertExplicitSourceLive, federatedSearchScope, parseSourceIdParam } from '../ops/context.ts';+import { ALL_SOURCES } from '../source-id.ts';++export interface EntitySources {+ /** Sources probed per name: home first, then the rest sorted by id. */+ sources: string[];+ /** The first probe; follow-ups for a hit here need no source_id. */+ home: string;+ /** The ambient binding that chose `home` (stdio binding or a thin client's prefer_source_id). */+ ambient?: { sourceId: string; via: string };+}++/** Recall's selector errors for a refused explicit source (scope_denied / not_found / invalid_params). */+function selectorError(error: unknown): unknown {+ if (!(error instanceof OperationError)) return error;+ const code = error.code === 'permission_denied' ? 'scope_denied'+ : error.code === 'unknown_source' ? 'not_found'+ : error.code === 'invalid_params' ? 'invalid_params' : null;+ if (code === null) return error;+ return Object.assign(verbError(code, error.message,+ error.suggestion ?? 'Choose a permitted active source, or omit source_id to use your existing scope.',+ error.detail ?? error.code), error.fix ? { fix: error.fix } : {});+}++/** One explicit source the caller may read (a pin, or one source-qualified entity). */+export async function explicitEntitySource(ctx: OperationContext, raw: unknown, opName: string): Promise<string> {+ try {+ const sourceId = parseSourceIdParam(raw, opName);+ if (sourceId === undefined) throw verbError('invalid_params', `${opName}: source_id is required.`, 'Pass a source id from sources_list.');+ federatedSearchScope(ctx, sourceId);+ await assertExplicitSourceLive(ctx, sourceId);+ return sourceId;+ } catch (error) {+ throw selectorError(error);+ }+}++export async function entitySources(ctx: OperationContext, p: { source_id?: unknown; prefer_source_id?: unknown }, opName: string): Promise<EntitySources> {+ if (p.source_id !== undefined && p.source_id !== null) {+ const sourceId = await explicitEntitySource(ctx, p.source_id, opName);+ return { sources: [sourceId], home: sourceId };+ }+ let prefer: string | undefined;+ try {+ prefer = parseSourceIdParam(p.prefer_source_id, opName);+ } catch (error) {+ throw selectorError(error);+ }+ const scope = federatedSearchScope(ctx, undefined);+ let readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : [ctx.sourceId ?? 'default']);+ if (ctx.remote === false && readable.length === 1 && readable[0] === ALL_SOURCES) {+ readable = (await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(r => r.id);+ }+ const binding = ctx.auth?.allowedSources === undefined ? ctx.explicitReadBinding : undefined;+ if (binding && readable.length === 1 && readable[0] === binding.sourceId) readable = binding.sourceIds;+ const ambient = prefer !== undefined ? { sourceId: prefer, via: 'the client\'s GBRAIN_SOURCE or .gbrain-source' }+ : binding ? { sourceId: binding.sourceId, via: binding.via } : undefined;+ const wanted = ambient?.sourceId ?? ctx.sourceId;+ const home = wanted !== undefined && readable.includes(wanted) ? wanted : readable[0] ?? 'default';+ const rest = [...new Set(readable)].filter(s => s !== home).sort();+ return { sources: [home, ...rest], home, ...(ambient ? { ambient } : {}) };+}++/**+ * context_pack's `entity_refs`: source-qualified entities+ * (`[{source_id, slug}]`), each checked like a pin. Anything else is+ * invalid_params naming the expected shape.+ */+export async function entityRefs(ctx: OperationContext, raw: unknown, max: number): Promise<Array<{ name: string; sourceId: string }>> {+ if (raw === undefined || raw === null) return [];+ const items = Array.isArray(raw) ? raw : null;+ const valid = items?.every(r => r && typeof r === 'object' && typeof (r as { slug?: unknown }).slug === 'string' && (r as { slug: string }).slug.trim());+ if (!items || !valid || items.length > max) {+ throw verbError('invalid_params', `context_pack: entity_refs must be 1 to ${max} objects with source_id and slug.`,+ 'Pass entity_refs: [{"source_id": "wiki", "slug": "people/alice-example"}], the source_id and slug a card or pointer returned.');+ }+ const out: Array<{ name: string; sourceId: string }> = [];+ for (const r of items as Array<{ source_id?: unknown; slug: string }>) {+ out.push({ name: r.slug.trim(), sourceId: await explicitEntitySource(ctx, r.source_id, 'context_pack') });+ }+ return out;+}++/**+ * `source_binding_narrowed` for a lookup whose ambient source had no hit for+ * some names: says which binding chose the first source and where the names+ * were found instead (or that they were found nowhere this connection reads).+ * Null when no ambient binding was in force or it had every hit.+ */+export function ambientMissNotice(op: string, walk: EntitySources, misses: Array<{ name: string; foundIn?: string }>): Notice | null {+ if (!walk.ambient || misses.length === 0) return null;+ const { sourceId, via } = walk.ambient;+ const readable = walk.sources.includes(sourceId);+ const parts = misses.slice(0, 5).map(m => m.foundIn ? `'${m.name}' resolved in source '${m.foundIn}'` : `'${m.name}' was not found in any source this connection reads`);+ return {+ code: 'source_binding_narrowed',+ kind: 'info',+ why: `This ${op} lookup prefers source '${sourceId}' (set by ${via}), `+ + (readable ? `which has no match for ${misses.length === 1 ? 'one name' : `${misses.length} names`}` : 'which this connection cannot read')+ + `; the lookup read the other sources this connection can read: ${parts.join('; ')}${misses.length > 5 ? '; …' : ''}.`+ + ' Each result names its source_id; pass source_id to read one source only.',+ };+}diff --git a/test/entity-source-federation.test.ts b/test/entity-source-federation.test.tsnew file mode 100644index 0000000000..39389a3653--- /dev/null+++ b/test/entity-source-federation.test.ts@@ -0,0 +1,192 @@+/**+ * #6723: `entity` and `context_pack` resolve names across the caller's+ * readable sources, like `volunteer_context` already does.+ *+ * Protects: a pointer volunteered from a federated source opens with `entity`+ * and packs with `context_pack`; the home source wins a name both sources+ * hold; the rest of the walk is sorted by id (grant order never changes the+ * answer); `source_id` pins one source and a refused pin returns recall's+ * selector errors; sources outside the grant are never read; a remote+ * `__all__` stays fail-closed; two different entities sharing a slug in two+ * sources pack side by side, each named by its source; a stdio binding or a+ * thin client's .gbrain-source orders the walk without narrowing it and says+ * so when its source missed; remote cards never carry loop-backed threads.+ * Privacy invariant: each pack card's activation verdict, newer mentions and+ * enrichment come from its OWN source, never a same-slug page at home.+ * Regression: both verbs read `ctx.sourceId ?? 'default'` only, so a+ * federated pointer could not be opened and a same-named home page won.+ * Synthetic data only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName, type OperationContext } from '../src/core/operations.ts';+import type { Notice } from '../src/core/agent-output.ts';+import { applyThinClientSourceScope } from '../src/cli/main.ts';+import { upsertOpenLoop } from '../src/core/loops/loops-store.ts';+import { withTrustPromotion } from '../src/core/persistence/context.ts';+import { enableTrustProtections } from './helpers/trust-protections.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const noop = { info() {}, warn() {}, error() {} };+type Ctx = Partial<OperationContext> & { notices?: Notice[] };+function ctx(o: { remote?: boolean; sourceId?: string; grant?: string[]; binding?: OperationContext['explicitReadBinding']; notices?: Notice[] } = {}): OperationContext {+ return {+ engine, config: { engine: 'pglite' }, logger: noop, dryRun: false, remote: o.remote ?? true, sourceId: o.sourceId ?? 'default',+ takesHoldersAllowList: ['world'],+ ...(o.grant ? { auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: o.grant } } : {}),+ ...(o.binding ? { explicitReadBinding: o.binding, transport: 'stdio' } : {}),+ ...(o.notices ? { emitNotice: (n: Notice) => o.notices!.push(n) } : {}),+ } as unknown as OperationContext;+}+const federated = (notices?: Notice[]) => ctx({ grant: ['default', 'wiki'], notices });+const call = async (op: string, c: OperationContext, p: Record<string, unknown>) => await operationsByName[op]!.handler(c, p) as any;+async function refusal(op: string, c: OperationContext, p: Record<string, unknown>): Promise<{ error?: string; code?: string }> {+ try { await call(op, c, p); } catch (e) { return { error: (e as any).envelope?.error ?? (e as any).verbCode ?? (e as any).code, code: (e as any).code }; }+ throw new Error('expected a refusal');+}++async function person(source: string, slug: string, title: string, body: string): Promise<number> {+ const [row] = await engine.executeRaw<{ id: number }>(+ `INSERT INTO pages (slug, source_id, type, title, compiled_truth, timeline) VALUES ($1, $2, 'person', $3, $4, '') RETURNING id`,+ [slug, source, title, body]);+ return Number(row!.id);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ for (const id of ['wiki', 'alpha', 'secret']) await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ($1, $1, '{}') ON CONFLICT (id) DO NOTHING`, [id]);+ await person('wiki', 'people/zoe-example', 'Zoe Example', 'Zoe Example runs the wiki team.');+ await person('default', 'people/sam-example', 'Sam Example', 'The default-source Sam.');+ await person('wiki', 'people/sam-example', 'Sam Example', 'The wiki-source Sam.');+ await person('alpha', 'people/ivy-example', 'Ivy Example', 'The alpha-source Ivy.');+ await person('wiki', 'people/ivy-example', 'Ivy Example', 'The wiki-source Ivy.');+ await person('secret', 'people/hidden-example', 'Hidden Example', 'Never readable by the federated token.');+ await upsertOpenLoop(engine, {+ sourceId: 'wiki', dedupKey: 'commit:zoe0001', loopType: 'commitment_owed_by_me', counterpartySlug: 'people/zoe-example',+ summary: 'LOOP-SENTINEL send Zoe the draft', evidence: [{ message_id: 'm-1', quote: 'quote' }], detector: 'llm_extract',+ });+}, 120_000);++afterAll(async () => { await engine.disconnect(); });++describe('#6723 federated entity resolution', () => {+ test('volunteer -> entity -> context_pack round trip on a slug that lives in a federated source', async () => {+ const volunteered = await call('volunteer_context', federated(), { window: 'user: what is Zoe Example working on?' });+ expect(volunteered.pages.map((p: any) => [p.source_id, p.slug])).toEqual([['wiki', 'people/zoe-example']]);++ const card = await call('entity', federated(), { name: 'Zoe Example' });+ expect(card.found).toBe(true);+ expect(card.card.entity).toMatchObject({ slug: 'people/zoe-example', source_id: 'wiki' });+ expect(card.card.open_threads.some((t: any) => t.loop_id !== undefined || /LOOP-SENTINEL/.test(t.text))).toBe(false);++ const rows = await call('entity', federated(), { names: ['people/zoe-example'] });+ expect(rows.results[0]).toMatchObject({ found: true, slug: 'people/zoe-example', source_id: 'wiki', next: { tool: 'entity', arguments: { name: 'people/zoe-example', source_id: 'wiki' } } });++ const pack = await call('context_pack', federated(), { entities: 'Zoe Example' });+ expect(pack.cards.map((c: any) => [c.source_id, c.slug])).toEqual([['wiki', 'people/zoe-example']]);+ expect(pack.text).toContain('`people/zoe-example` (source wiki)');+ expect(JSON.stringify(pack)).not.toContain('LOOP-SENTINEL');+ });++ test('the home source wins a name both sources hold; source_id pins the other one', async () => {+ const home = await call('entity', federated(), { name: 'Sam Example' });+ expect(home.card.entity.source_id).toBe('default');+ expect(home.card.summary).toContain('default-source Sam');+ const pinned = await call('entity', federated(), { name: 'Sam Example', source_id: 'wiki' });+ expect(pinned.card.entity.source_id).toBe('wiki');+ expect(pinned.card.summary).toContain('wiki-source Sam');+ });++ test('outside home, the walk is sorted by source id whatever the grant order', async () => {+ for (const grant of [['default', 'wiki', 'alpha'], ['wiki', 'alpha', 'default'], ['alpha', 'default', 'wiki']]) {+ const card = await call('entity', ctx({ grant }), { name: 'Ivy Example' });+ expect(card.card.entity.source_id).toBe('alpha');+ }+ });++ test('two entities sharing one slug in two sources pack side by side, each with its own source', async () => {+ const pack = await call('context_pack', federated(), { entity_refs: [{ source_id: 'default', slug: 'people/sam-example' }, { source_id: 'wiki', slug: 'people/sam-example' }] });+ expect(pack.cards.map((c: any) => [c.source_id, c.slug, c.summary])).toEqual([+ ['default', 'people/sam-example', expect.stringContaining('default-source Sam')],+ ['wiki', 'people/sam-example', expect.stringContaining('wiki-source Sam')],+ ]);+ });++ test('a source outside the grant is never read: unpinned it is a miss, pinned it is scope_denied', async () => {+ expect((await call('entity', federated(), { name: 'Hidden Example' })).found).toBe(false);+ expect((await call('context_pack', federated(), { entities: 'Hidden Example' })).cards).toEqual([]);+ expect((await refusal('entity', federated(), { name: 'Hidden Example', source_id: 'secret' })).code).toBe('scope_denied');+ expect((await refusal('context_pack', federated(), { entity_refs: [{ source_id: 'secret', slug: 'people/hidden-example' }] })).code).toBe('scope_denied');+ expect((await refusal('entity', ctx({ remote: false }), { name: 'Zoe Example', source_id: 'ghost' })).code).toBe('not_found');+ expect((await refusal('entity', federated(), { name: 'Zoe Example', source_id: 'Bad Id!' })).code).toBe('invalid_params');+ });++ test('a remote __all__ stays fail-closed; a trusted local __all__ reads every source', async () => {+ expect((await call('entity', ctx({ sourceId: '__all__' }), { name: 'Zoe Example' })).found).toBe(false);+ expect((await refusal('entity', federated(), { name: 'Zoe Example', source_id: '__all__' })).code).toBe('invalid_params');+ expect((await call('entity', ctx({ remote: false, sourceId: '__all__' }), { name: 'Zoe Example' })).card.entity.source_id).toBe('wiki');+ });++ test('a stdio .gbrain-source binding orders the walk without narrowing it, and says when its source missed', async () => {+ const notices: Notice[] = [];+ const bound = ctx({ binding: { sourceId: 'default', via: '.gbrain-source', sourceIds: ['default', 'wiki'], optedOut: [] }, notices });+ expect((await call('entity', bound, { name: 'Zoe Example' })).card.entity.source_id).toBe('wiki');+ const narrowed = notices.filter(n => n.code === 'source_binding_narrowed');+ expect(narrowed).toHaveLength(1);+ expect(narrowed[0]!.why).toContain("'Zoe Example' resolved in source 'wiki'");+ notices.length = 0;+ expect((await call('entity', bound, { name: 'Sam Example' })).card.entity.source_id).toBe('default');+ expect(notices.filter(n => n.code === 'source_binding_narrowed')).toEqual([]);+ });++ test("a thin client's .gbrain-source becomes a preference, never a pin", async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-entity-ambient-'));+ try {+ writeFileSync(join(dir, '.gbrain-source'), 'default\n');+ for (const op of ['entity', 'context_pack']) {+ const params: Record<string, unknown> = op === 'entity' ? { name: 'Zoe Example' } : { entities: 'Zoe Example' };+ await withEnv({ GBRAIN_SOURCE: undefined }, () => { applyThinClientSourceScope(operationsByName[op]!, params, dir); });+ expect(params).toMatchObject({ prefer_source_id: 'default' });+ expect(params.source_id).toBeUndefined();+ const notices: Notice[] = [];+ const res = await call(op, federated(notices), params);+ expect(op === 'entity' ? res.card.entity.source_id : res.cards[0].source_id).toBe('wiki');+ expect(notices.map(n => n.code)).toContain('source_binding_narrowed');+ }+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe('#6723 privacy invariant: a pack card is gated and enriched by its own source', () => {+ test('a same-slug home page with the opposite activation verdict neither drops nor admits the federated card', async () => {+ await enableTrustProtections(engine);+ try {+ const [row] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id = 'default' AND slug = 'people/sam-example'");+ const homeId = Number(row!.id);+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw("UPDATE pages SET trust_tier = 'agent_written' WHERE id = $1", [homeId])));+ await engine.executeRaw(`INSERT INTO write_gate_receipts (target_table, target_id, source_id, content_hash, tier, detector_version, verdict, reason_families)+ VALUES ('pages', $1, 'default', md5($1), 'agent_written', 1, 'flag', ARRAY['standing_instruction']::text[]) ON CONFLICT DO NOTHING`, [String(homeId)]);++ const wikiPack = await call('context_pack', federated(), { entity_refs: [{ source_id: 'wiki', slug: 'people/sam-example' }] });+ expect(wikiPack.cards.map((c: any) => c.source_id)).toEqual(['wiki']);+ expect(wikiPack.suppressed).toBeUndefined();++ const homePack = await call('context_pack', federated(), { entity_refs: [{ source_id: 'default', slug: 'people/sam-example' }] });+ expect(homePack.cards).toEqual([]);+ expect(homePack.suppressed?.withheld).toBe(1);+ expect(homePack.text).not.toContain('default-source Sam');+ } finally {+ await engine.unsetConfig('write_gate.external_mode');+ await engine.unsetConfig('trust.agent_activation');+ await engine.executeRaw("DELETE FROM write_gate_receipts");+ }+ });+});diff --git a/test/helpers/entity-names-parity.ts b/test/helpers/entity-names-parity.tsindex fb7201c19b..c72b44b6b4 100644--- a/test/helpers/entity-names-parity.ts+++ b/test/helpers/entity-names-parity.ts@@ -108,7 +108,7 @@ async function referenceOne(engine: BrainEngine, sourceId: string, name: string,for (const s of sib) bodies.set(s.slug, s.compiled_truth);}return {- name, found: true, slug: entity.slug, title: entity.title, type: entity.type, aka, lead: pageLead(bodies.get(entity.slug) ?? null),+ name, found: true, source_id: entity.source_id, slug: entity.slug, title: entity.title, type: entity.type, aka, lead: pageLead(bodies.get(entity.slug) ?? null),...(siblingPages.length ? { siblings: siblingPages.map(p => ({ slug: p.slug, title: p.title, type: p.type, aka: p.aka, lead: pageLead(bodies.get(p.slug) ?? null) })) } : {}),};}