Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(context): match pinned questions on the card's source and slug (#6723)

garrytan6dfaca04acaf
diff --git a/docs/.wave18-fragments/lane4.md b/docs/.wave18-fragments/lane4.md
index 147e536459..9c45610c7d 100644
--- a/docs/.wave18-fragments/lane4.md
+++ b/docs/.wave18-fragments/lane4.md
@@ -8,7 +8,7 @@ Branch `capy/wave18-lane4`. Every `since` below is a placeholder: stamp the wave
// 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.' },
+ { 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, page status and pinned questions now come from its own source: a pinned question joins the pack only when its source and `scope_entity` match a packed card, and a requested name that packs no card no longer pulls in a pin by slug.' },
// 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.' },
```
diff --git a/docs/architecture/key-files/core-questions.md b/docs/architecture/key-files/core-questions.md
index 0929e4a4d5..60b6edb11b 100644
--- a/docs/architecture/key-files/core-questions.md
+++ b/docs/architecture/key-files/core-questions.md
@@ -18,7 +18,7 @@ User guide: [docs/guides/pinned-questions.md](../../guides/pinned-questions.md).
- `src/core/questions/receipt.ts` — `buildReceipt`: freshness (`fresh|stale|awaiting_refresh|refreshing|archived`), sentence counts, evidence watermark, last refresh, blocked reason (`awaiting_consent`, `no_model_key`, `budget_exhausted`, `refresh_failed`, `no_worker`), `fix` (an agent-operator `Action` with a read-only `verify`) and the answer for owner-capable readers. `scheduledRefreshAvailable` (a `standing_questions` run in the last two days, or installed unpaused autopilot) decides `no_worker`.
-- `src/core/questions/service.ts` — The operations' behavior. `requireOwnerCapable` admits the trusted local CLI and remote grants that read private pages and are neither slug-fenced nor delegated; everyone else gets `question_owner_only` with the CLI equivalent. Consent: CLI pins are active; MCP pins are inactive (`awaiting_consent`) unless a paid preapproval exists; `pin --id` on the host activates. First answer is a bounded wait (`wait_ms`, abort releases the lease). `pinnedAnswersForPack` feeds context_pack's optional `pinned_questions` / `withheld` fields (published, active, entity-scoped pins; fresh sentences only). Emits the `pinned_answer_stale` notice.
+- `src/core/questions/service.ts` — The operations' behavior. `requireOwnerCapable` admits the trusted local CLI and remote grants that read private pages and are neither slug-fenced nor delegated; everyone else gets `question_owner_only` with the CLI equivalent. Consent: CLI pins are active; MCP pins are inactive (`awaiting_consent`) unless a paid preapproval exists; `pin --id` on the host activates. First answer is a bounded wait (`wait_ms`, abort releases the lease). `pinnedAnswersForPack` feeds context_pack's optional `pinned_questions` / `withheld` fields (published, active, entity-scoped pins whose `(source_id, scope_entity)` is one of the pack's accepted cards; fresh sentences only). Emits the `pinned_answer_stale` notice.
- `src/core/questions/phase.ts` — Cycle phase `standing_questions` (global, writes): syncs question pages, refreshes due active pins (never answered, then stale, then new evidence since the watermark; cooldown per pin or `cycle.standing_questions.cooldown_days`) under one `BudgetMeter` (`cycle.standing_questions.budget_usd`) and `max_per_cycle`, stops on `budget_exhausted` or `no_model_key`, and stamps `cycle.standing_questions.last_run_at`. Kill switch `cycle.standing_questions.enabled=false`.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 4f47f765ea..9dc63f6e9d 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -923,7 +923,8 @@ 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)`.
+`(source_id, slug)`. `pinned_questions` carries a published pin only when its
+source and `scope_entity` match an accepted card's `(source_id, slug)`.
#### context_pack entity_facts (additive)
diff --git a/evals/pinned-questions/appended-gate.ts b/evals/pinned-questions/appended-gate.ts
index 2fd9d873c5..308e5fa4b8 100644
--- a/evals/pinned-questions/appended-gate.ts
+++ b/evals/pinned-questions/appended-gate.ts
@@ -234,7 +234,7 @@ export async function runAppended(opts: AppendedOpts): Promise<{ arms: ArmRun[];
const r = await readerAnswer(opts.arms.reader, opts.readerModel, q, context);
arm.reads.push({ entity: e.slug, batch: b, gold, correct: correctFor(r.text, gold), stale: staleFor(r.text, gold, past), usd: priced(r.model, r.input_tokens, r.output_tokens) });
};
- const pack = await pinnedAnswersForPack(ctx, [e.slug]);
+ const pack = await pinnedAnswersForPack(ctx, [{ source_id: ctx.sourceId, slug: e.slug }]);
const pinnedText = (pack?.pinned_questions ?? []).flatMap(p => p.answer).join(' ');
answerTexts.push(...(pack?.pinned_questions ?? []).flatMap(p => p.answer));
await read(pinned, pinnedText);
diff --git a/evals/pinned-questions/benefit-gate.ts b/evals/pinned-questions/benefit-gate.ts
index 9e97a9a63d..a197568e90 100644
--- a/evals/pinned-questions/benefit-gate.ts
+++ b/evals/pinned-questions/benefit-gate.ts
@@ -144,7 +144,7 @@ export async function runGate(opts: GateOpts): Promise<GateReport> {
const g = gold.get(e.slug)!;
const q = question(e.name);
for (let r = 0; r < opts.readsPerWrite; r++) {
- const pack = await pinnedAnswersForPack(ctx, [e.slug]);
+ const pack = await pinnedAnswersForPack(ctx, [{ source_id: sourceId, slug: e.slug }]);
const pinnedText = (pack?.pinned_questions ?? []).flatMap(p => p.answer).join(' ');
const pinnedRead = await readerAnswer(opts.reader, opts.readerModel, q, pinnedText);
const usdP = priced(pinnedRead.model, pinnedRead.input_tokens, pinnedRead.output_tokens);
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index e7b0a3ccb7..15d7634994 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -919,7 +919,7 @@ const context_pack: Operation = {
? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }
: {}),
// C4: optional pinned answers (fresh sentences) and the withheld count (src/core/questions/service.ts).
- ...(await (await import('../questions/service.ts')).pinnedAnswersForPack(ctx, [...new Set([...(res.cards ?? []).map((c) => c.entity.slug), ...entities])])
+ ...(await (await import('../questions/service.ts')).pinnedAnswersForPack(ctx, (res.cards ?? []).map((c) => ({ source_id: c.entity.source_id, slug: c.entity.slug })))
.catch(() => null)),
};
},
diff --git a/src/core/questions/service.ts b/src/core/questions/service.ts
index 24639d61f0..b3a1cba0ce 100644
--- a/src/core/questions/service.ts
+++ b/src/core/questions/service.ts
@@ -256,13 +256,15 @@ export interface PinnedForPack {
* sentences are withheld and counted. Owner-capable callers only; anyone else
* gets nothing (and no hint that pins exist).
*/
-export async function pinnedAnswersForPack(ctx: OperationContext, entitySlugs: string[]): Promise<PinnedForPack | null> {
- if (entitySlugs.length === 0) return null;
+/** Published pins scoped to the pack's accepted entities, matched on the pin's source and `scope_entity` (#6723). */
+export async function pinnedAnswersForPack(ctx: OperationContext, entities: Array<{ source_id: string; slug: string }>): Promise<PinnedForPack | null> {
+ if (entities.length === 0) return null;
let access: CallerAccess;
try { access = await requireOwnerCapable(ctx, 'context_pack', ['gbrain', 'questions', 'list']); } catch { return null; }
const sources = access.readableSources ?? [defaultSource(ctx)];
const pins = (await listPins(ctx.engine, { sourceIds: sources, states: ['active'] }))
- .filter(pin => pin.publish_mode === 'publish' && pin.answer_revision > 0 && pin.scope_entity && entitySlugs.includes(pin.scope_entity));
+ .filter(pin => pin.publish_mode === 'publish' && pin.answer_revision > 0 && pin.scope_entity
+ && entities.some(e => e.source_id === pin.source_id && e.slug === pin.scope_entity));
if (pins.length === 0) return null;
const pinned: NonNullable<PinnedForPack['pinned_questions']> = [];
let withheld = 0;
diff --git a/test/context-pack-pinned-federation.test.ts b/test/context-pack-pinned-federation.test.ts
new file mode 100644
index 0000000000..2973d8c871
--- /dev/null
+++ b/test/context-pack-pinned-federation.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #6723: context_pack's pinned-question enrichment matches each accepted card
+ * on (source_id, scope_entity), never on the slug alone.
+ *
+ * Protects: two granted sources each hold companies/acme-example and each has
+ * its own published pin scoped to it; a pack for one source's entity carries
+ * only that source's pin, a pack for both carries both, and an unqualified
+ * name packs the home card with the home pin. Regression: the enrichment
+ * compared pin.scope_entity with bare card slugs, so a federated pack showed
+ * the other source's same-slug pin as if it were about this entity.
+ * Synthetic data only; the model is a stub.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { pinQuestion } from '../src/core/questions/service.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { ENTITY, MODEL, QUESTION, localCtx, logger, seedBrain, stubAnswer, type Seeded } from './helpers/pinned-questions-fixture.ts';
+import type { QuestionChatFn } from '../src/core/questions/refresh.ts';
+
+let engine: PGLiteEngine;
+let a: Seeded, b: Seeded;
+const pins: Record<string, string> = {};
+
+const chat = (prefix: string): QuestionChatFn => async (req) =>
+ ({ text: stubAnswer(req.user, { prefix }), usage: { input_tokens: 1000, output_tokens: 200 }, model: MODEL });
+
+async function pack(params: Record<string, unknown>): Promise<{ pinned_questions?: Array<{ id: string; answer: string[] }> }> {
+ const result = await dispatchToolCall(engine, 'context_pack', params, {
+ remote: true, transport: 'stdio', sourceId: a.sourceId, config: { engine: engine.kind, embedding_disabled: true } as never, logger,
+ auth: { token: 't', clientId: 'pq-agent', scopes: ['read', 'write'], sourceId: a.sourceId, allowedSources: [a.sourceId, b.sourceId] },
+ });
+ expect(result.isError ?? false).toBe(false);
+ return JSON.parse((result.content[0] as { text: string }).text);
+}
+const ids = (p: Awaited<ReturnType<typeof pack>>) => (p.pinned_questions ?? []).map((q) => q.id).sort();
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ a = await seedBrain(engine);
+ b = await seedBrain(engine);
+ for (const [s, prefix] of [[a, ' A-SIDE'], [b, ' B-SIDE']] as const) {
+ const out = await pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { entity: ENTITY } }, { chat: chat(prefix) });
+ pins[s.sourceId] = out.receipt.id;
+ }
+ await engine.setConfig('search.remote_private_pages', 'visible');
+ __resetPrivateVisibilityCacheForTests();
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+describe('#6723 context_pack pinned questions are matched per source', () => {
+ test('each source-qualified card carries only its own source\'s pin', async () => {
+ const onlyA = await pack({ entity_refs: [{ source_id: a.sourceId, slug: ENTITY }] });
+ expect(ids(onlyA)).toEqual([pins[a.sourceId]]);
+ expect(JSON.stringify(onlyA.pinned_questions)).toContain('A-SIDE');
+ expect(JSON.stringify(onlyA.pinned_questions)).not.toContain('B-SIDE');
+
+ const onlyB = await pack({ entity_refs: [{ source_id: b.sourceId, slug: ENTITY }] });
+ expect(ids(onlyB)).toEqual([pins[b.sourceId]]);
+ expect(JSON.stringify(onlyB.pinned_questions)).toContain('B-SIDE');
+ expect(JSON.stringify(onlyB.pinned_questions)).not.toContain('A-SIDE');
+ });
+
+ test('both same-slug cards carry both pins; an unqualified name packs the home card with the home pin', async () => {
+ const both = await pack({ entity_refs: [{ source_id: a.sourceId, slug: ENTITY }, { source_id: b.sourceId, slug: ENTITY }] });
+ expect(ids(both)).toEqual([pins[a.sourceId], pins[b.sourceId]].sort());
+ const home = await pack({ entities: ENTITY });
+ expect(ids(home)).toEqual([pins[a.sourceId]]);
+ });
+});
diff --git a/test/helpers/pinned-questions-scenarios.ts b/test/helpers/pinned-questions-scenarios.ts
index ddf5d6626a..6bda313985 100644
--- a/test/helpers/pinned-questions-scenarios.ts
+++ b/test/helpers/pinned-questions-scenarios.ts
@@ -262,7 +262,7 @@ export function registerPinnedQuestionSuite(label: string, getEngine: () => Brai
expect(notices).toMatchObject([{ code: 'pinned_answer_stale', kind: 'degraded' }]);
expect(sentence(after, c.needle)).toMatchObject({ stale: true, reasons: [c.reason] });
expect(after.fix?.mcp?.tool).toBe('questions_refresh');
- const pack = await (await import('../../src/core/questions/service.ts')).pinnedAnswersForPack(localCtx(engine, s.sourceId), [ENTITY]);
+ const pack = await (await import('../../src/core/questions/service.ts')).pinnedAnswersForPack(localCtx(engine, s.sourceId), [{ source_id: s.sourceId, slug: ENTITY }]);
expect(pack?.withheld?.stale_sentences).toBe(after.sentences.stale);
expect(JSON.stringify(pack?.pinned_questions ?? [])).not.toContain(before!.text);
}, 30_000);