Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(links): link reads follow the caller's federated source scope (#5827)
garrytande4fc6dcd691
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex f853f42803..1ebad6ec4f 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -311,7 +311,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/cycle/concept-publication.ts": ["test/e2e/managed-writers-w3.test.ts"],"src/core/chronicle/extract-events.ts": ["test/e2e/managed-writers-w3.test.ts"],"src/commands/enrich.ts": ["test/e2e/managed-writers-w3.test.ts"],- "src/core/ops/links.ts": ["test/e2e/managed-writers-w3.test.ts"],+ // #5827: link-op source scope (remote federated, local per-source merge).+ "src/core/ops/links.ts": ["test/e2e/managed-writers-w3.test.ts", "test/e2e/federated-link-reads-postgres.test.ts"],"src/core/cycle/extract-atoms-page-state.ts": ["test/e2e/extract-atoms-page-state.test.ts", "test/e2e/reconcile-crash.test.ts", "test/e2e/reconcile-crash-unactivated.test.ts", "test/e2e/reconcile-pgbouncer.test.ts"],"src/commands/migrations/v0_13_1.ts": ["test/e2e/grandfather-projection-postgres.test.ts", "test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],"src/commands/migrations/v0_32_2.ts": ["test/e2e/migrations-v0_32_2-managed.test.ts"],@@ -612,4 +613,4 @@ E2E_TEST_MAP["src/core/engine-sql/dialect-*.ts"] = ENGINE_SQL_EXECUTOR_E2E;E2E_TEST_MAP["src/core/engine-sql/normalize.ts"] = ["test/e2e/engine-sql-normalize-parity.test.ts"];E2E_TEST_MAP["src/core/engine-sql/brands.ts"] = ["test/e2e/engine-sql-rls-scope.test.ts"];E2E_TEST_MAP["src/core/engine-sql/chunks.ts"] = ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts"];-E2E_TEST_MAP["src/core/engine-sql/links.ts"] = ["test/e2e/links-read-order.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts"];+E2E_TEST_MAP["src/core/engine-sql/links.ts"] = ["test/e2e/links-read-order.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/federated-link-reads-postgres.test.ts"];diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex b3088939b5..6852bb3060 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -576,10 +576,14 @@ export function thinkSourceScopeOpts(ctx: OperationContext): {* and have a foreign far/origin slug disclosed. So for remote callers we promote a* scalar scope to a single-element `sourceIds:[id]`, routing them through the* all-endpoint branch. Trusted local CLI (`ctx.remote === false`) keeps the scalar- * cross-source view, and a federated array passes through unchanged.+ * cross-source view, and a federated array passes through unchanged. `scope`+ * defaults to the ambient ladder; the link ops pass their resolved per-call+ * scope (`federatedSearchScope`) so the same promotion applies to it.*/-export function linkReadScopeOpts(ctx: OperationContext): { sourceId?: string; sourceIds?: string[] } {- const scope = sourceScopeOpts(ctx);+export function linkReadScopeOpts(+ ctx: OperationContext,+ scope: { sourceId?: string; sourceIds?: string[] } = sourceScopeOpts(ctx),+): { sourceId?: string; sourceIds?: string[] } {if (ctx.remote !== false && scope.sourceId && !scope.sourceIds) {return { sourceIds: [scope.sourceId] };}diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 9d09529b3f..eb34a74806 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -10,13 +10,19 @@ import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';import { OperationError, type Operation } from './contract.ts';import {+ assertExplicitSourceLive,enforceClientSlugFence,+ federatedSearchScope,linkReadScopeOpts,+ parseSourceIdParam,readPolicyOpts,reclassifyMutationTimePageMiss,requireWritablePage,sourceScopeOpts,} from './context.ts';+import type { OperationContext } from './contract.ts';+import type { Link, PageReadPolicy } from '../types.ts';+import { ALL_SOURCES } from '../source-id.ts';import { PageMissingError } from '../engine-errors.ts';import { TRAVERSE_PATH_ROW_CAP } from '../engine-constants.ts';// #4224: flag-gated cross-source identity union for the link read ops.@@ -154,32 +160,157 @@ const remove_link: Operation = {cliHints: { name: 'unlink', aliases: ['link-rm'], positional: ['from', 'to'] },};-const get_links: Operation = {- name: 'get_links',- description: 'List outgoing links from a page',- params: {- slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },- },- handler: async (ctx, p) => {- // #2200: linkReadScopeOpts so a federated grant — and an untrusted remote- // scalar scope (promoted to sourceIds[]) — reaches the engine's all-endpoint- // branch. Trusted local/internal callers keep the scalar cross-source view.- const sourceOpts = await readPolicyOpts(ctx, linkReadScopeOpts(ctx));- const links = await ctx.engine.getLinks(p.slug as string, sourceOpts);+const LINK_SOURCE_ID_PARAM = {+ type: 'string',+ description: "Scope the read to one source (a multi-source brain can hold the same slug in several sources). Omitted: your granted sources remotely (a connection with no grant reads every federated source); locally, the resolved source, or every federated source when no --source / GBRAIN_SOURCE / .gbrain-source pinned it. '__all__' spans every source for trusted local callers and only your readable sources for remote callers.",+} as const;+const LINK_ALL_SOURCES_PARAM = {+ type: 'boolean',+ description: 'Span sources (equivalent to source_id=__all__): every source locally, only your readable sources remotely.',+} as const;++/**+ * #5827: the per-call source scope of a link read (get_links, get_backlinks,+ * traverse_graph). `federatedSearchScope` is the single trust + grant+ * resolver (#5081 explicit-read admission; an unqualified no-grant read widens+ * to the transport-computed federated set; a grant never widens), the+ * liveness check runs strictly after it (an archived source the caller was+ * never granted answers permission_denied, not unknown_source), and+ * `linkReadScopeOpts` promotes a remote scalar to `sourceIds[]` so the+ * engine's #2200 all-endpoints branch applies. Trusted local callers get the+ * scope as resolved: an explicit source stays scalar, `__all__` is brain-wide,+ * and an unqualified read may come back as the federated `sourceIds[]`.+ */+async function resolveLinkReadScope(+ ctx: OperationContext,+ p: Record<string, unknown>,+ opName: string,+): Promise<{ requested: string | undefined; policy: PageReadPolicy }> {+ const sourceIdParam = parseSourceIdParam(p.source_id, opName, { allowAll: true });+ if (p.all_sources === true && sourceIdParam !== undefined && sourceIdParam !== ALL_SOURCES) {+ throw new OperationError(+ 'invalid_params',+ `${opName}: pass either source_id or all_sources, not both.`,+ 'Drop all_sources to read one source, or drop source_id to span sources.',+ );+ }+ const requested = p.all_sources === true ? ALL_SOURCES : sourceIdParam;+ const scope = federatedSearchScope(ctx, requested);+ await assertExplicitSourceLive(ctx, requested);+ return { requested, policy: await readPolicyOpts(ctx, linkReadScopeOpts(ctx, scope)) };+}++const linkIdentity = (l: Link) => JSON.stringify([+ l.from_source_id, l.from_slug, l.to_source_id, l.to_slug, l.link_type,+ l.link_source ?? null, l.origin_source_id ?? null, l.origin_slug ?? null, l.origin_field ?? null,+]);++/**+ * get_links / get_backlinks body. A trusted local unqualified read whose scope+ * widened to the federated set runs the scalar read once per federated source+ * (resolved source first, the set's own order) and merges, de-duplicated on+ * link identity: the scalar branch keeps the cross-source far-endpoint view+ * local callers rely on, which the all-endpoints branch would drop for far+ * pages in non-federated sources. Every other caller runs one read.+ */+async function readLinkEdges(+ ctx: OperationContext,+ p: Record<string, unknown>,+ opName: 'get_links' | 'get_backlinks',+ direction: 'out' | 'in',+): Promise<Link[]> {+ const slug = p.slug as string;+ const { requested, policy } = await resolveLinkReadScope(ctx, p, opName);+ const scopes: PageReadPolicy[] = ctx.remote === false && policy.sourceIds+ ? policy.sourceIds.map((sourceId) => ({ ...policy, sourceIds: undefined, sourceId }))+ : [policy];+ const perScope: Link[][] = [];+ for (const sourceOpts of scopes) {+ const links = direction === 'out'+ ? await ctx.engine.getLinks(slug, sourceOpts)+ : await ctx.engine.getBacklinks(slug, sourceOpts);// #4224: flag-gated identity union — merge edges from the page's identity// co-members (entity_identity.union config, default off; pure no-op then).// Member visibility never widens past the caller's grant. The scalar base// scope (when present) pins group resolution to the page actually read.- const unioned = await unionLinksAcrossIdentity(ctx.engine, p.slug as string, links, 'out', {+ // The engine authorizes the base and every member read before merging;+ // each union contributor must preserve this policy because no final filter runs.+ perScope.push(await unionLinksAcrossIdentity(ctx.engine, slug, links, direction, {sourceId: sourceOpts.sourceId,allowedSources: sourceOpts.sourceIds,excludePrivate: sourceOpts.excludePrivate,- });- // The engine authorizes the base and every member read before merging;- // each union contributor must preserve this policy because no final filter runs.- return unioned;+ }));+ }+ if (perScope.length === 1) {+ if (perScope[0].length === 0) await hintScopedLinkMiss(ctx, p, requested, policy, direction);+ return perScope[0];+ }+ const seen = new Set<string>();+ const merged = perScope.flat().filter((l) => {+ const key = linkIdentity(l);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+ if (merged.length === 0) await hintScopedLinkMiss(ctx, p, requested, policy, direction);+ return merged;+}++/**+ * #5827: local scoped-miss hint. A trusted local unqualified link read that+ * found nothing, for a slug that has links in a source outside the read scope+ * (a non-federated source, or any other source when the read was pinned),+ * names the scope it read, the per-source link counts and the exact rerun+ * command on stderr. stdout keeps the empty result; quiet under --json; never+ * for remote callers (no cross-source existence oracle).+ */+async function hintScopedLinkMiss(+ ctx: OperationContext,+ p: Record<string, unknown>,+ requested: string | undefined,+ policy: PageReadPolicy,+ direction: 'out' | 'in',+): Promise<void> {+ if (ctx.remote !== false || requested !== undefined || p.json === true) return;+ const readSources = policy.sourceIds ?? (policy.sourceId !== undefined ? [policy.sourceId] : undefined);+ if (readSources === undefined) return;+ const slug = p.slug as string;+ try {+ const rows = await ctx.engine.executeRaw<{ source_id: string }>(+ `SELECT DISTINCT p.source_id FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE p.slug = $1 AND p.deleted_at IS NULL AND s.archived IS NOT TRUE+ ORDER BY p.source_id`,+ [slug],+ );+ const counts: Array<{ sourceId: string; count: number }> = [];+ for (const { source_id: sourceId } of rows) {+ if (readSources.includes(sourceId)) continue;+ const opts = { sourceId, excludePrivate: policy.excludePrivate };+ const links = direction === 'out' ? await ctx.engine.getLinks(slug, opts) : await ctx.engine.getBacklinks(slug, opts);+ if (links.length > 0) counts.push({ sourceId, count: links.length });+ }+ if (counts.length === 0) return;+ const command = direction === 'out' ? 'links' : 'backlinks';+ const label = readSources.length === 1 ? `source ${readSources[0]}` : `sources ${readSources.join(', ')}`;+ ctx.logger.warn(+ `[gbrain] ${command}: no ${direction === 'out' ? 'outgoing' : 'incoming'} links for ${slug} in ${label}; ` ++ `found ${counts.map((c) => `${c.count} in source ${c.sourceId}`).join(', ')}. Rerun with:\n` ++ counts.map((c) => ` gbrain ${command} ${slug} --source ${c.sourceId}`).join('\n'),+ );+ } catch { /* the hint is best-effort; the empty result stands */ }+}++const get_links: Operation = {+ name: 'get_links',+ description: 'List outgoing links from a page',+ params: {+ slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },+ source_id: LINK_SOURCE_ID_PARAM,+ all_sources: LINK_ALL_SOURCES_PARAM,},+ handler: async (ctx, p) => readLinkEdges(ctx, p, 'get_links', 'out'),scope: 'read',+ cliHints: { name: 'links', aliases: ['get_links'], positional: ['slug'] },};const get_backlinks: Operation = {@@ -187,21 +318,10 @@ const get_backlinks: Operation = {description: 'List incoming links to a page',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose incoming links to list.' },+ source_id: LINK_SOURCE_ID_PARAM,+ all_sources: LINK_ALL_SOURCES_PARAM,},- handler: async (ctx, p) => {- // #2200: linkReadScopeOpts — federated grant + untrusted remote scalar- // (promoted to sourceIds[]) reach the engine's all-endpoint branch.- const sourceOpts = await readPolicyOpts(ctx, linkReadScopeOpts(ctx));- const links = await ctx.engine.getBacklinks(p.slug as string, sourceOpts);- // #4224: flag-gated identity union (see get_links).- const unioned = await unionLinksAcrossIdentity(ctx.engine, p.slug as string, links, 'in', {- sourceId: sourceOpts.sourceId,- allowedSources: sourceOpts.sourceIds,- excludePrivate: sourceOpts.excludePrivate,- });- // Base and member reads enforce the policy before merging (see get_links).- return unioned;- },+ handler: async (ctx, p) => readLinkEdges(ctx, p, 'get_backlinks', 'in'),scope: 'read',cliHints: { name: 'backlinks', positional: ['slug'] },};@@ -252,6 +372,8 @@ const traverse_graph: Operation = {depth: { type: 'number', description: `Max traversal depth (capped at ${TRAVERSE_DEPTH_CAP}). Default ${DEFAULT_TRAVERSE_DEPTH}, except a remote call that lets direction default to 'both' uses ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} (bidirectional path enumeration is combinatorial on hubs); an explicit depth is always honored up to the cap.` },link_type: { type: 'string', description: 'Filter to one link type (per-edge filter, traversal only follows matching edges)' },direction: { type: 'string', enum: ['in', 'out', 'both'], description: "Traversal direction ('in', 'out', or 'both'). Remote callers default to 'both'; trusted local no-filter callers keep the legacy outgoing-node output." },+ source_id: LINK_SOURCE_ID_PARAM,+ all_sources: LINK_ALL_SOURCES_PARAM,},handler: async (ctx, p) => {const slug = p.slug as string;@@ -278,7 +400,10 @@ const traverse_graph: Operation = {// walks stay within the auth'd client's accessible sources. Pre-fix,// traverseGraph / traversePaths happily followed edges into pages from// foreign sources, leaking topology + page metadata via the graph op.- const scope = await readPolicyOpts(ctx);+ // #5827: the walk scopes every visited page, so a federated `sourceIds[]`+ // (no-grant remote, or a trusted local unqualified read) walks the+ // federated set in one query; nodes and edges carry their source ids.+ const { policy: scope } = await resolveLinkReadScope(ctx, p, 'traverse_graph');// Backward compat: trusted local no-filter callers keep the legacy// GraphNode[] shape used by `gbrain graph`. Remote MCP callers need the// natural no-filter invocation to surface inbound-only typed edges too,diff --git a/test/e2e/federated-link-reads-postgres.test.ts b/test/e2e/federated-link-reads-postgres.test.tsnew file mode 100644index 0000000000..0eff44cf34--- /dev/null+++ b/test/e2e/federated-link-reads-postgres.test.ts@@ -0,0 +1,94 @@+/**+ * #5827 — Postgres twin of test/federated-link-reads-5827.test.ts.+ *+ * The link ops' remote no-grant path binds the federated set as a `text[]`+ * through the engine's #2200 all-endpoints branch, and traverse_graph now+ * projects page ids and source ids; postgres.js array binding and the+ * DISTINCT/ORDER BY shape only fail on real Postgres, so the federated matrix+ * runs here too: a no-grant caller reads business links (not the empty+ * `default`), a non-federated referrer, an archived source and a private page+ * stay out, a granted token never widens, same-slug pages in two federated+ * sources stay distinct edges/nodes, and a trusted local unqualified read+ * merges one scalar read per federated source.+ *+ * DATABASE_URL-gated: self-skips without a real Postgres.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';+import { operationsByName, type AuthInfo, type OperationContext } from '../../src/core/operations.ts';+import { noGrantFederatedScope } from '../../src/core/source-resolver.ts';+import { dispatchToolCall, type DispatchOpts } from '../../src/mcp/dispatch.ts';+import { FEDERATED_SET, edgeKeys, seedFederatedLinkFixture } from '../helpers/federated-link-fixture.ts';++const describePg = hasDatabase() ? describe : describe.skip;++describePg('#5827 federated link reads — Postgres', () => {+ beforeAll(async () => {+ await setupDB();+ await seedFederatedLinkFixture(getEngine());+ }, 90_000);++ afterAll(async () => {+ await teardownDB();+ }, 30_000);++ async function noGrantOpts(): Promise<DispatchOpts> {+ const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'default', hasSourceGrant: false } as AuthInfo;+ return {+ remote: true, transport: 'http', sourceId: 'default', auth,+ localFederatedSourceIds: await noGrantFederatedScope(getEngine(), false, 'default'),+ };+ }++ async function call(opts: DispatchOpts, name: string, params: Record<string, unknown>) {+ const result = await dispatchToolCall(getEngine(), name, params, opts);+ return { isError: result.isError === true, body: JSON.parse(result.content[0].text) };+ }++ test('no-grant get_backlinks and get_links read the federated set only', async () => {+ const opts = await noGrantOpts();+ expect(opts.localFederatedSourceIds).toEqual([...FEDERATED_SET]);+ expect(edgeKeys((await call(opts, 'get_backlinks', { slug: 'companies/acme-example' })).body)).toEqual([+ 'people/alice-example(business)->companies/acme-example(business)',+ ]);+ expect(edgeKeys((await call(opts, 'get_links', { slug: 'people/alice-example' })).body)).toEqual([+ 'people/alice-example(business)->companies/acme-example(business)',+ 'people/alice-example(wiki)->topics/widget-co(wiki)',+ ]);+ });++ test('no-grant traverse_graph keeps same-slug edges from two sources distinct', async () => {+ const { body } = await call(await noGrantOpts(), 'traverse_graph', { slug: 'people/alice-example', depth: 1 });+ expect(edgeKeys(body)).toEqual([+ 'people/alice-example(business)->companies/acme-example(business)',+ 'people/alice-example(wiki)->topics/widget-co(wiki)',+ ]);+ });++ test('explicit non-federated or archived source_id is refused for a no-grant caller', async () => {+ const opts = await noGrantOpts();+ expect((await call(opts, 'get_backlinks', { slug: 'companies/priv-only-co', source_id: 'priv' })).body.error).toBe('permission_denied');+ expect((await call(opts, 'get_backlinks', { slug: 'companies/acme-example', source_id: 'arch' })).body.error).toBe('permission_denied');+ });++ test('a granted token reads only its grant', async () => {+ const auth = { token: '', clientId: 'client-a', scopes: ['read'], sourceId: 'wiki', allowedSources: ['wiki'] } as AuthInfo;+ const opts: DispatchOpts = { remote: true, transport: 'http', sourceId: 'wiki', auth, localFederatedSourceIds: [...FEDERATED_SET] };+ expect((await call(opts, 'get_backlinks', { slug: 'companies/acme-example' })).body).toEqual([]);+ });++ test('trusted local unqualified backlinks merge one scalar read per federated source; graph nodes carry source ids', async () => {+ const engine = getEngine();+ const ctx: OperationContext = {+ engine, config: {} as never, logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false, remote: false, sourceId: 'default', localFederatedSourceIds: [...FEDERATED_SET],+ };+ const rows = await operationsByName.get_backlinks.handler(ctx, { slug: 'companies/acme-example' });+ const perSource: unknown[] = [];+ for (const sourceId of FEDERATED_SET) perSource.push(...await engine.getBacklinks('companies/acme-example', { sourceId }));+ expect(rows).toEqual(perSource);+ expect(edgeKeys(rows as unknown[])).toContain('notes/priv-note(priv)->companies/acme-example(business)');+ const nodes = await operationsByName.traverse_graph.handler(ctx, { slug: 'people/alice-example', depth: 1 }) as Array<Record<string, unknown>>;+ expect(nodes.filter((n) => n.depth === 0).map((n) => n.source_id).sort()).toEqual(['business', 'wiki']);+ });+});diff --git a/test/federated-link-reads-5827.test.ts b/test/federated-link-reads-5827.test.tsnew file mode 100644index 0000000000..60eeb27dd1--- /dev/null+++ b/test/federated-link-reads-5827.test.ts@@ -0,0 +1,241 @@+/**+ * #5827 — link reads on multi-source federated brains.+ *+ * Contract protected: get_links / get_backlinks / traverse_graph read the same+ * source set as `search` for the same caller. A no-grant remote caller (whose+ * scalar scope collapses to an empty `default`) reads across the transport's+ * federated set through the #2200 all-endpoints branch; a granted token never+ * widens; non-federated and archived sources stay out; private pages stay+ * hidden from remote callers. Trusted local unqualified reads merge one scalar+ * read per federated source; explicit `source_id` is honored or refused.+ *+ * Regression that fails it: the link ops reading `sourceScopeOpts` (scalar+ * `default`) again — on the wave-5 base every new-behavior case below returned+ * [] or ignored `source_id`. Existing coverage (get-page-federated-scope,+ * operations-source-isolation-matrix) only exercises granted tokens.+ * Remote calls go through `dispatchToolCall` with the HTTP no-grant context+ * `serve-http-mcp.ts` builds; no production seam is added.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName, type AuthInfo, type OperationContext } from '../src/core/operations.ts';+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';+import { makeContext } from '../src/cli.ts';+import { withEnv } from './helpers/with-env.ts';+import { FEDERATED_SET, edgeKeys, seedAliceIdentity, seedFederatedLinkFixture } from './helpers/federated-link-fixture.ts';+import { ENTITY_IDENTITY_UNION_CONFIG_KEY } from '../src/core/entity-identity.ts';+import type { GraphNode } from '../src/core/types.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await seedFederatedLinkFixture(engine);+}, 60_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+}, 60_000);++async function noGrantOpts(): Promise<DispatchOpts> {+ const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'default', hasSourceGrant: false } as AuthInfo;+ return {+ remote: true, transport: 'http', sourceId: 'default', auth,+ localFederatedSourceIds: await noGrantFederatedScope(engine, false, 'default'),+ };+}++function grantedOpts(allowedSources: string[]): DispatchOpts {+ const auth = {+ token: '', clientId: 'client-a', scopes: ['read'], sourceId: allowedSources[0], allowedSources,+ principal: { kind: 'oauth_client', id: 'client-a' },+ } as AuthInfo;+ return { remote: true, transport: 'http', sourceId: allowedSources[0], auth, localFederatedSourceIds: [...FEDERATED_SET] };+}++async function call(opts: DispatchOpts, name: string, params: Record<string, unknown>) {+ const result = await dispatchToolCall(engine, name, params, opts);+ return { isError: result.isError === true, body: JSON.parse(result.content[0].text) };+}++function localCtx(overrides: Partial<OperationContext> = {}, warnings: string[] = []): OperationContext {+ return {+ engine: engine as never,+ config: {} as never,+ logger: { info: () => {}, warn: (m: string) => { warnings.push(m); }, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ localFederatedSourceIds: [...FEDERATED_SET],+ ...overrides,+ };+}++const runOp = (name: string, ctx: OperationContext, params: Record<string, unknown>) =>+ operationsByName[name].handler(ctx, params) as Promise<unknown[]>;++describe('#5827 remote no-grant caller reads the federated set', () => {+ test('the transport computed a federated set without priv (never federated) or arch (archived)', async () => {+ expect((await noGrantOpts()).localFederatedSourceIds).toEqual([...FEDERATED_SET]);+ });++ test('get_backlinks returns the business backlink; non-federated, archived and private referrers stay out', async () => {+ const { isError, body } = await call(await noGrantOpts(), 'get_backlinks', { slug: 'companies/acme-example' });+ expect(isError).toBe(false);+ expect(edgeKeys(body)).toEqual(['people/alice-example(business)->companies/acme-example(business)']);+ });++ test('get_links spans both federated same-slug pages', async () => {+ const { body } = await call(await noGrantOpts(), 'get_links', { slug: 'people/alice-example' });+ expect(edgeKeys(body)).toEqual([+ 'people/alice-example(business)->companies/acme-example(business)',+ 'people/alice-example(wiki)->topics/widget-co(wiki)',+ ]);+ });++ test('traverse_graph returns two distinguishable edges for the same slug in two federated sources', async () => {+ const { body } = await call(await noGrantOpts(), 'traverse_graph', { slug: 'people/alice-example', depth: 1 });+ expect(edgeKeys(body)).toEqual([+ 'people/alice-example(business)->companies/acme-example(business)',+ 'people/alice-example(wiki)->topics/widget-co(wiki)',+ ]);+ });++ test('all_sources and source_id=__all__ read the same federated set as an unqualified call', async () => {+ const opts = await noGrantOpts();+ const unqualified = edgeKeys((await call(opts, 'get_links', { slug: 'people/alice-example' })).body);+ expect(unqualified).toHaveLength(2);+ expect(edgeKeys((await call(opts, 'get_links', { slug: 'people/alice-example', all_sources: true })).body)).toEqual(unqualified);+ expect(edgeKeys((await call(opts, 'get_links', { slug: 'people/alice-example', source_id: '__all__' })).body)).toEqual(unqualified);+ });++ test('an explicit federated source_id narrows to that source', async () => {+ const { body } = await call(await noGrantOpts(), 'get_links', { slug: 'people/alice-example', source_id: 'wiki' });+ expect(edgeKeys(body)).toEqual(['people/alice-example(wiki)->topics/widget-co(wiki)']);+ });++ test('an explicit non-federated source_id is refused with the #5081 hint', async () => {+ for (const name of ['get_links', 'get_backlinks', 'traverse_graph']) {+ const { isError, body } = await call(await noGrantOpts(), name, { slug: 'notes/priv-note', source_id: 'priv' });+ expect(isError).toBe(true);+ expect(body.error).toBe('permission_denied');+ expect(body.suggestion).toContain('priv is not federated');+ }+ });++ test('an archived source the caller was never granted answers permission_denied, not unknown_source', async () => {+ for (const name of ['get_links', 'get_backlinks', 'traverse_graph']) {+ const { body } = await call(await noGrantOpts(), name, { slug: 'notes/arch-note', source_id: 'arch' });+ expect(body.error).toBe('permission_denied');+ }+ });++ test('source_id together with all_sources is invalid_params', async () => {+ const { body } = await call(await noGrantOpts(), 'get_links', { slug: 'people/alice-example', source_id: 'wiki', all_sources: true });+ expect(body.error).toBe('invalid_params');+ });++ test('identity union under the federated scope adds federated co-members only', async () => {+ await seedAliceIdentity(engine);+ try {+ const { body } = await call(await noGrantOpts(), 'get_links', { slug: 'people/alice-example' });+ expect(edgeKeys(body)).toEqual([+ 'people/al-example(wiki)->topics/gadget-co(wiki)',+ 'people/alice-example(business)->companies/acme-example(business)',+ 'people/alice-example(wiki)->topics/widget-co(wiki)',+ ]);+ } finally {+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'false');+ }+ });+});++describe('#5827 granted tokens never widen', () => {+ test('a business grant reads exactly what the engine returns for that grant', async () => {+ const expected = await engine.getBacklinks('companies/acme-example', { sourceIds: ['business'], excludePrivate: true });+ const { body } = await call(grantedOpts(['business']), 'get_backlinks', { slug: 'companies/acme-example' });+ expect(body).toEqual(JSON.parse(JSON.stringify(expected)));+ expect(edgeKeys(body)).toEqual(['people/alice-example(business)->companies/acme-example(business)']);+ });++ test('a wiki grant sees no business links and cannot name business', async () => {+ const opts = grantedOpts(['wiki']);+ expect((await call(opts, 'get_backlinks', { slug: 'companies/acme-example' })).body).toEqual([]);+ expect(edgeKeys((await call(opts, 'get_links', { slug: 'people/alice-example' })).body)).toEqual([+ 'people/alice-example(wiki)->topics/widget-co(wiki)',+ ]);+ const denied = await call(opts, 'get_links', { slug: 'people/alice-example', source_id: 'business' });+ expect(denied.body.error).toBe('permission_denied');+ });++ test('a token granted an archived source gets unknown_source for it', async () => {+ const { body } = await call(grantedOpts(['business', 'arch']), 'get_backlinks', {+ slug: 'companies/acme-example', source_id: 'arch',+ });+ expect(body.error).toBe('unknown_source');+ });+});++describe('#5827 trusted local link reads', () => {+ test('an unqualified read merges one scalar read per federated source, keeping cross-source referrers', async () => {+ const rows = await runOp('get_backlinks', localCtx(), { slug: 'companies/acme-example' });+ const perSource: unknown[] = [];+ for (const sourceId of FEDERATED_SET) perSource.push(...await engine.getBacklinks('companies/acme-example', { sourceId }));+ expect(rows).toEqual(perSource);+ expect(edgeKeys(rows)).toEqual([+ 'notes/arch-note(arch)->companies/acme-example(business)',+ 'notes/priv-note(priv)->companies/acme-example(business)',+ 'people/alice-example(business)->companies/acme-example(business)',+ 'people/secret-example(business)->companies/acme-example(business)',+ ]);+ });++ test('a pinned scalar read (no federated set) is unchanged', async () => {+ const ctx = localCtx({ sourceId: 'business', localFederatedSourceIds: undefined });+ const rows = await runOp('get_backlinks', ctx, { slug: 'companies/acme-example' });+ expect(rows).toEqual(await engine.getBacklinks('companies/acme-example', { sourceId: 'business' }));+ });++ test('`gbrain backlinks <slug> --source business` reads business through makeContext', async () => {+ const ctx = await withEnv({ GBRAIN_SOURCE: undefined }, () => makeContext(engine as never, { source: 'business' }));+ expect(ctx.sourceId).toBe('business');+ const rows = await runOp('get_backlinks', ctx, { slug: 'companies/acme-example' });+ expect(rows).toEqual(await engine.getBacklinks('companies/acme-example', { sourceId: 'business' }));+ });++ test('explicit source_id and all_sources are honored', async () => {+ const wiki = await runOp('get_links', localCtx(), { slug: 'people/alice-example', source_id: 'wiki' });+ expect(edgeKeys(wiki)).toEqual(['people/alice-example(wiki)->topics/widget-co(wiki)']);+ const all = await runOp('get_backlinks', localCtx(), { slug: 'companies/acme-example', all_sources: true });+ expect(all).toEqual(await engine.getBacklinks('companies/acme-example'));+ });++ test('an archived source_id answers unknown_source locally', async () => {+ await expect(runOp('get_backlinks', localCtx(), { slug: 'companies/acme-example', source_id: 'arch' }))+ .rejects.toMatchObject({ code: 'unknown_source' });+ });++ test('a miss for a slug linked only in a non-federated source prints the rerun hint; --json keeps quiet', async () => {+ const warnings: string[] = [];+ const rows = await runOp('get_backlinks', localCtx({}, warnings), { slug: 'companies/priv-only-co' });+ expect(rows).toEqual([]);+ expect(warnings).toEqual([+ '[gbrain] backlinks: no incoming links for companies/priv-only-co in sources default, business, wiki; '+ + 'found 1 in source priv. Rerun with:\n gbrain backlinks companies/priv-only-co --source priv',+ ]);+ const quiet: string[] = [];+ expect(await runOp('get_backlinks', localCtx({}, quiet), { slug: 'companies/priv-only-co', json: true })).toEqual([]);+ expect(quiet).toEqual([]);+ });++ test('`gbrain graph` keeps same-slug roots from two federated sources as two nodes', async () => {+ const nodes = await runOp('traverse_graph', localCtx(), { slug: 'people/alice-example', depth: 1 }) as GraphNode[];+ expect(nodes.filter((n) => n.depth === 0).map((n) => `${n.slug}(${n.source_id})`).sort()).toEqual([+ 'people/alice-example(business)',+ 'people/alice-example(wiki)',+ ]);+ });+});diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex ef539d5501..f0f8fb76d2 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 200378,- "stdoutSha256": "c23df35de49ce6ca01006bf4db2ce92fb57d2f37f089f82fef292c047982b00e",+ "stdoutBytes": 202679,+ "stdoutSha256": "cc0d36a47564e1ead83e5c073fb21615e5027572de1ed56373c534845f8e1bd8","toolNames": ["remember","entity",@@ -1322,13 +1322,23 @@"description": "List outgoing links from a page","name": "get_links","parameters": {- "slug": "string"+ "all_sources": "boolean?",+ "slug": "string",+ "source_id": "string?"},"schema": {"properties": {+ "all_sources": {+ "description": "Span sources (equivalent to source_id=__all__): every source locally, only your readable sources remotely.",+ "type": "boolean"+ },"slug": {"description": "Slug of the page whose outgoing links to list.","type": "string"+ },+ "source_id": {+ "description": "Scope the read to one source (a multi-source brain can hold the same slug in several sources). Omitted: your granted sources remotely (a connection with no grant reads every federated source); locally, the resolved source, or every federated source when no --source / GBRAIN_SOURCE / .gbrain-source pinned it. '__all__' spans every source for trusted local callers and only your readable sources for remote callers.",+ "type": "string"}},"required": [@@ -1341,13 +1351,23 @@"description": "List incoming links to a page","name": "get_backlinks","parameters": {- "slug": "string"+ "all_sources": "boolean?",+ "slug": "string",+ "source_id": "string?"},"schema": {"properties": {+ "all_sources": {+ "description": "Span sources (equivalent to source_id=__all__): every source locally, only your readable sources remotely.",+ "type": "boolean"+ },"slug": {"description": "Slug of the page whose incoming links to list.","type": "string"+ },+ "source_id": {+ "description": "Scope the read to one source (a multi-source brain can hold the same slug in several sources). Omitted: your granted sources remotely (a connection with no grant reads every federated source); locally, the resolved source, or every federated source when no --source / GBRAIN_SOURCE / .gbrain-source pinned it. '__all__' spans every source for trusted local callers and only your readable sources for remote callers.",+ "type": "string"}},"required": [@@ -1370,13 +1390,19 @@"description": "Traverse link graph from a page. Remote callers default to bidirectional edges (GraphPath[]) at depth 2 (pass depth explicitly for deeper walks); trusted local no-filter callers keep the legacy node shape at depth 5.","name": "traverse_graph","parameters": {+ "all_sources": "boolean?","depth": "number?","direction": "string?","link_type": "string?",- "slug": "string"+ "slug": "string",+ "source_id": "string?"},"schema": {"properties": {+ "all_sources": {+ "description": "Span sources (equivalent to source_id=__all__): every source locally, only your readable sources remotely.",+ "type": "boolean"+ },"depth": {"description": "Max traversal depth (capped at 10). Default 5, except a remote call that lets direction default to 'both' uses 2 (bidirectional path enumeration is combinatorial on hubs); an explicit depth is always honored up to the cap.","type": "number"@@ -1397,6 +1423,10 @@"slug": {"description": "Slug of the page to start the traversal from, e.g. 'people/alice-example'. This is the start-node param — there is no `start` or `root` param.","type": "string"+ },+ "source_id": {+ "description": "Scope the read to one source (a multi-source brain can hold the same slug in several sources). Omitted: your granted sources remotely (a connection with no grant reads every federated source); locally, the resolved source, or every federated source when no --source / GBRAIN_SOURCE / .gbrain-source pinned it. '__all__' spans every source for trusted local callers and only your readable sources for remote callers.",+ "type": "string"}},"required": [diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 5944223737..57de21a79c 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -633,6 +633,7 @@"depth: number","links: { to_slug: string; link_type: string; }[]","slug: string",+ "source_id: string","title: string","type: string"],@@ -644,8 +645,10 @@"context: string","depth: number","from_slug: string",+ "from_source_id: string","link_type: string",- "to_slug: string"+ "to_slug: string",+ "to_source_id: string"],"name": "GraphPath"},@@ -5450,7 +5453,7 @@"kind": "function","name": "linkReadScopeOpts","signature": [- "(ctx: OperationContext) => { sourceId?: string; sourceIds?: string[]; }"+ "(ctx: OperationContext, scope?: { sourceId?: string; sourceIds?: string[]; }) => { sourceId?: string; sourceIds?: string[]; }"]},{@@ -7451,6 +7454,7 @@"depth: number","links: { to_slug: string; link_type: string; }[]","slug: string",+ "source_id: string","title: string","type: string"],@@ -7462,8 +7466,10 @@"context: string","depth: number","from_slug: string",+ "from_source_id: string","link_type: string",- "to_slug: string"+ "to_slug: string",+ "to_source_id: string"],"name": "GraphPath"},diff --git a/test/helpers/federated-link-fixture.ts b/test/helpers/federated-link-fixture.tsnew file mode 100644index 0000000000..98bb61c2bb--- /dev/null+++ b/test/helpers/federated-link-fixture.ts@@ -0,0 +1,90 @@+/**+ * #5827 — shared multi-source federated link fixture (PGLite unit test and the+ * Postgres E2E twin). `default` is federated but EMPTY, so a no-grant caller+ * whose scalar scope collapses to `default` reads nothing unless the link ops+ * widen to the federated set.+ *+ * default federated (seeded) no pages+ * business federated companies/acme-example, people/alice-example,+ * people/secret-example (visibility: private)+ * wiki federated people/alice-example (same slug as business),+ * topics/widget-co, people/al-example, topics/gadget-co+ * priv never federated notes/priv-note, companies/priv-only-co, people/alice-priv+ * arch federated, ARCHIVED notes/arch-note+ *+ * Edges: alice(business)→acme, secret→acme, alice(wiki)→widget-co,+ * al-example→gadget-co, priv-note→acme (cross-source priv→business),+ * priv-note→priv-only-co, alice-priv→priv-note, arch-note→acme.+ */+import type { BrainEngine } from '../../src/core/engine.ts';+import { linkEntityIdentity, ENTITY_IDENTITY_UNION_CONFIG_KEY } from '../../src/core/entity-identity.ts';++export const FEDERATED_SET = ['default', 'business', 'wiki'] as const;++const SOURCES: Array<{ id: string; config: string; archived: boolean }> = [+ { id: 'business', config: '{"federated": true}', archived: false },+ { id: 'wiki', config: '{"federated": true}', archived: false },+ { id: 'priv', config: '{}', archived: false },+ { id: 'arch', config: '{"federated": true}', archived: true },+];++const PAGES: Array<{ sourceId: string; slug: string; type: string; private?: boolean }> = [+ { sourceId: 'business', slug: 'companies/acme-example', type: 'company' },+ { sourceId: 'business', slug: 'people/alice-example', type: 'person' },+ { sourceId: 'business', slug: 'people/secret-example', type: 'person', private: true },+ { sourceId: 'wiki', slug: 'people/alice-example', type: 'person' },+ { sourceId: 'wiki', slug: 'topics/widget-co', type: 'note' },+ { sourceId: 'wiki', slug: 'people/al-example', type: 'person' },+ { sourceId: 'wiki', slug: 'topics/gadget-co', type: 'note' },+ { sourceId: 'priv', slug: 'notes/priv-note', type: 'note' },+ { sourceId: 'priv', slug: 'companies/priv-only-co', type: 'company' },+ { sourceId: 'priv', slug: 'people/alice-priv', type: 'person' },+ { sourceId: 'arch', slug: 'notes/arch-note', type: 'note' },+];++const LINKS: Array<[fromSource: string, from: string, toSource: string, to: string, type: string]> = [+ ['business', 'people/alice-example', 'business', 'companies/acme-example', 'works_at'],+ ['business', 'people/secret-example', 'business', 'companies/acme-example', 'advises'],+ ['wiki', 'people/alice-example', 'wiki', 'topics/widget-co', 'mentions'],+ ['wiki', 'people/al-example', 'wiki', 'topics/gadget-co', 'mentions'],+ ['priv', 'notes/priv-note', 'business', 'companies/acme-example', 'cites'],+ ['priv', 'notes/priv-note', 'priv', 'companies/priv-only-co', 'cites'],+ ['priv', 'people/alice-priv', 'priv', 'notes/priv-note', 'authored'],+ ['arch', 'notes/arch-note', 'business', 'companies/acme-example', 'cites'],+];++export async function seedFederatedLinkFixture(engine: BrainEngine): Promise<void> {+ for (const s of SOURCES) {+ await engine.executeRaw(+ `INSERT INTO sources (id, name, local_path, config, archived)+ VALUES ($1, $1, $2, $3::text::jsonb, $4)+ ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config, archived = EXCLUDED.archived`,+ [s.id, `/tmp/gbrain-5827-${s.id}`, s.config, s.archived],+ );+ }+ await engine.executeRaw(`UPDATE sources SET config = '{"federated": true}'::jsonb WHERE id = 'default'`);+ for (const page of PAGES) {+ await engine.putPage(page.slug, {+ type: page.type as never,+ title: `${page.slug} (${page.sourceId})`,+ compiled_truth: `${page.slug} in ${page.sourceId}`,+ frontmatter: page.private ? { visibility: 'private' } : {},+ }, { sourceId: page.sourceId });+ }+ for (const [fromSourceId, from, toSourceId, to, type] of LINKS) {+ await engine.addLink(from, to, `${type} ctx`, type, 'manual', undefined, undefined, { fromSourceId, toSourceId });+ }+}++/** One identity across business, wiki and the never-federated priv source. */+export async function seedAliceIdentity(engine: BrainEngine): Promise<void> {+ await engine.setConfig(ENTITY_IDENTITY_UNION_CONFIG_KEY, 'true');+ await linkEntityIdentity(engine, { entityId: 'person/alice', slug: 'people/alice-example', sourceId: 'business' });+ await linkEntityIdentity(engine, { entityId: 'person/alice', slug: 'people/al-example', sourceId: 'wiki' });+ await linkEntityIdentity(engine, { entityId: 'person/alice', slug: 'people/alice-priv', sourceId: 'priv' });+}++/** `from(source)->to(source)` keys, sorted, for set-style assertions. */+export function edgeKeys(rows: readonly unknown[]): string[] {+ return (rows as Array<Record<string, unknown>>).map((r) => `${r.from_slug}(${r.from_source_id})->${r.to_slug}(${r.to_source_id})`).sort();+}