Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(links): write cross-source automatic edges the source policy approved on every writer (#4680)

garrytan58022038e2a9
diff --git a/docs/architecture/brains-and-sources.md b/docs/architecture/brains-and-sources.md
index 5c4bbf1066..f21033bd69 100644
--- a/docs/architecture/brains-and-sources.md
+++ b/docs/architecture/brains-and-sources.md
@@ -302,11 +302,24 @@ gbrain extract links --source db # re-extract once; --stale
Without the flag, an isolated (`federated=false`) source only writes edges
whose both endpoints live in that source; a federated source may also link
-into the configured default source (`sources.default`). With the flag on, a
-target that exists only in other sources resolves to the lexicographically
-smallest source id, so repeated extracts converge on the same row. The read
-side is unchanged: a federated caller's source grant still scopes every link
-read.
+into the configured default source (`sources.default`) and follow an
+explicit `[[source:slug]]` reference. With the flag on, a target that exists
+only in other sources resolves to the lexicographically smallest source id,
+so repeated extracts converge on the same row.
+
+Every automatic writer applies that one policy: `put_page` and `capture`
+(link preparation), the managed stale pass, the source reconciliation sweep
+and `extract links --source db`. A local write resolves a cross-source
+wikilink only under `link_resolution.cross_source` or from a federated origin
+source; the drops it counts come back in the write receipt as
+`auto_links.skipped_cross_source`. An outbound edge always originates in the
+page's own source (canonical attendance, which points at the person, is the
+one edge whose far endpoint may live elsewhere), and a derived edge records
+whether its reference was authored qualified (`links.resolution_type`:
+`qualified` for `[[source:slug]]`, `unqualified` otherwise). The read side is
+unchanged: a federated caller's source grant still scopes both endpoints of
+every link read, and the entity card confines an untrusted caller's edges to
+the card's own source.
## What confines remote callers (and what does not)
diff --git a/docs/architecture/key-files/company-brain.md b/docs/architecture/key-files/company-brain.md
index c8c67e94d5..289930cf85 100644
--- a/docs/architecture/key-files/company-brain.md
+++ b/docs/architecture/key-files/company-brain.md
@@ -9,7 +9,7 @@ For the operator workflow, see the [company-brain ingestion guide](../../guides/
- `src/commands/company-brain-{inspect,connect,demo}.ts` — dedicated source subcommand parsing and versioned JSON/error output. Inspection is engine-free; connect requires explicit brain/source selection and previews through the existing resident-owner route before a probe-only local connection. Human progress is stderr-scoped for JSON output. `core/company-brain/{demo,sample,evidence,status}.ts` supplies the real-pipeline offline sample, actual source-scoped evidence, and private receipt status without fabricated answers or host-path fields.
-- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints, and resolves no foreign-source fallback. Standard DB extraction passes the same captured endpoint revision fences. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`engine.readPageSnapshotsBatch`, built on `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, page-subject purges and the '*' purge marker included, line fingerprints only for pages with withdrawals, purges or a '*' marker, a body-byte budget per call; Postgres binds the refs' sources for RLS; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.
+- `src/core/{derived-links,link-reconciliation}.ts` — source-qualified, revision-fenced atomic replacement of derived edges; manual rows survive. The source reconciliation API supports bounded cursors, refuses changed endpoints (foreign ones included) and resolves a target into another source only under the source policy it shares with `put_page`'s link preparation (`makeLinkSourceResolver`: `link_resolution.cross_source`, or a `[[source:slug]]` reference from a federated origin; #4680). Standard DB extraction passes the same captured endpoint revision fences. `replaceDerivedLinksBatch` (engine member) publishes many origins in one transaction: one relation-semantics prime, one sorted guard lock over every origin and endpoint, one extraction-generation check and one batched origin read (`engine.readPageSnapshotsBatch`, built on `src/core/page-snapshot-batch.ts`: each exact ref's `readPageSnapshot` result in one statement, page-subject purges and the '*' purge marker included, line fingerprints only for pages with withdrawals, purges or a '*' marker, a body-byte budget per call; Postgres binds the refs' sources for RLS; `test/page-snapshot-batch.test.ts`), then each origin's own checks and writes in order; any failure rolls the batch back, and `replaceDerivedLinksBatchOrReplay` then replays the origins one by one through `replaceDerivedLinks`, so each outcome (settings-changed skip, first error) is the unbatched one (`test/extract-db-batch-equivalence.test.ts` pins `extract all --source db` rows to the per-page walk). `test/derived-link-reconciliation.test.ts` and `test/extract-endpoint-revision.serial.test.ts` cover both engines and rollback/freshness behavior.
- `src/core/attendance-repair.ts` and `src/commands/extract-attendance-repair.ts` — trusted-local historical attendance preview and exact-receipt apply. Indexed source-page slug windows precede eligibility filtering; explicit Markdown evidence uses capped endpoint and adjacency lookups, while all frontmatter remains report-only and unmaterialized. A narrow `derived-links.ts` delta preserves unrelated row IDs and evidence; brain/source incarnation, page revisions, ontology/parser and affected-edge hashes fence each origin transaction. Existing `op_checkpoints` banks commit proof before the private cursor advances across committed origins and revalidated skipped pages, making interruption replay idempotent. No broad derived replacement, normal-extraction watermark updates, MCP administration or provider calls. Covered by the dual-engine `test/attendance-repair.test.ts` and real CLI `test/attendance-repair-cli.serial.test.ts`; operator contract and limits are in `docs/guides/attendance-evidence.md`.
- `src/core/schema-pack/base/company-brain.yaml` — optional company vocabulary extending `gbrain-base-v2` without normalization rules or maintenance phases. Overrides company aliases and prefixes so product stays a distinct query and path type. Bundled through `schema-pack/bundled.ts` and `bundled-assets.ts`; attribution is in `third-party/company-brain/`. The generic fictional sample in `src/core/company-brain/sample/` preserves the upstream layout and relationship metadata. `test/company-brain-schema.test.ts` pins inherited lint, type closure, folder inference, read-only bundling, and sample references.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index d1312002d7..3301da30a1 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -382,6 +382,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.157.0', text: 'The entity counters in `get_health` / `gbrain health` (`entity_page_count`, `link_coverage`, `timeline_coverage`, `most_connected`) and doctor\'s `graph_coverage` and `orphan_ratio` gates now count the page types the active schema pack declares with `primitive: entity` (`yc`, `civic` and `organization` included on gbrain-base; a custom pack\'s own entity types; `person` or `company` only while the pack does not reclassify them), resolved per source when sources carry their own pack. Brains whose entities are pack types move from 0 entities and `null` ratios to real numbers, and a doctor score can drop where coverage is low. A pack that does not load now reports `entity_types_status: pack_unavailable` with 0 entities and a `graph_coverage` warn instead of counting the old hardcoded list.' },
{ since: '0.60.157.0', text: 'Dream `synthesize_concepts` now writes one concept page for spellings of a label that differ only by hyphens, underscores or dots (`network-effects`, `network_effects`, `networkeffects`): the spelling that already has a live `concepts/` page wins, otherwise the one most atoms use (a tie goes to the hyphenated form), and the other spellings redirect to it for that run without any page write. Two spellings that both already have live pages (`re-sign` / `resign`, `co-op` / `coop`) are kept apart; merging those stays the human redirect path (`merged_into` / `aliases`). Existing duplicate pages are not merged for you: `details.folded_spellings` on the phase receipt names each fold.' },
{ since: '0.60.157.0', text: 'A `put_page` (or `gbrain put`) of a page that already exists, sent without `expected_revision` or `force`, is now refused with its own code `revision_required` instead of `revision_conflict`; the message, the refusal and the fix (read the page, resend with its revision) are unchanged. A stale `expected_revision` is still `revision_conflict`. A client that switched on `revision_conflict` to decide between "re-read and merge" and "I forgot the precondition" can now branch on the code (#5385).' },
+ { since: '0.60.157.0', text: 'A wikilink or markdown link whose target the source policy resolved into another source (`link_resolution.cross_source` on, or a `[[source:slug]]` reference from a federated source) is now written by `put_page`, `capture`, the managed stale pass and the source reconciliation sweep, the way `extract links --source db` already wrote it; before, those writers dropped the approved edge and the next pass deleted the rows the extractor had admitted. With the flag off and a non-federated source nothing changes, and the write receipt now counts the drops as `auto_links.skipped_cross_source`. A reader granted one source still never sees the other source\'s endpoint. Watch `gbrain get-links` on pages that cite another source: the edges you opted into now appear.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.ts
index df4f70665a..40e2260a8d 100644
--- a/src/core/link-reconciliation.ts
+++ b/src/core/link-reconciliation.ts
@@ -72,25 +72,33 @@ export async function reconcileSourceLinks(
return result;
}
const sourceIncarnation = sources[0].incarnation;
- const pages = await loadLinkPageMetadata(engine, sourceId);
- const index = new Map(pages.map(page => [page.slug, page]));
+ // #4680: every source's live pages, so the source policy can resolve a target into another
+ // source (names still resolve within the origin's source: makeIndexedLinkResolver filters).
+ const pages = await loadLinkPageMetadata(engine);
+ const metadata = new Map(pages.map(page => [`${page.source_id}\0${page.slug}`, page]));
+ const endpoints = indexLinkSources(pages);
+ const policy = await loadLinkSourcePolicy(engine, sourceId);
const resolver = makeIndexedLinkResolver(pages, sourceId);
const wantedEnabled = await isWantedPagesEnabled(engine);
const grammar = await readLineGrammarSettings(engine);
const lineGrammar = { enabled: grammar.enabled, allowUndeclaredTypes: grammar.allowUndeclaredTypes };
- const remaining = pages.filter(page => !opts.afterSlug || page.slug > opts.afterSlug)
+ const remaining = pages.filter(page => page.source_id === sourceId && (!opts.afterSlug || page.slug > opts.afterSlug))
.sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0);
- for (const metadata of remaining.slice(0, limit)) {
- originSlug = metadata.slug;
+ for (const own of remaining.slice(0, limit)) {
+ originSlug = own.slug;
const snapshot = await engine.readPageSnapshot(originSlug, { sourceId });
- if (!snapshot || snapshot.revision !== metadata.knowledge_revision || snapshot.sourceIncarnation !== sourceIncarnation) {
+ if (!snapshot || snapshot.revision !== own.knowledge_revision || snapshot.sourceIncarnation !== sourceIncarnation) {
result.failures.push({ originSlug, code: 'revision_conflict' });
return result;
}
const page = snapshot.page;
+ const sourcesOf = makeLinkSourceResolver(page.slug, sourceId, endpoints, policy);
const extracted = await extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,
page.type, resolver, { pack: opts.pack, globalBasename: opts.globalBasename, lineGrammar,
- targetType: (slug, source) => !source || source === sourceId ? index.get(slug)?.type : undefined });
+ targetType: (slug, source) => {
+ const resolved = sourcesOf.resolve({ targetSlug: slug, targetSourceId: source, linkType: '', context: '' });
+ return resolved.ok ? metadata.get(`${resolved.toSourceId}\0${slug}`)?.type : undefined;
+ } });
for (const ref of extracted.unresolved) {
const target = unwrapWikilink(ref.name);
const qualifier = target.split(':')[0];
@@ -104,28 +112,19 @@ export async function reconcileSourceLinks(
}
const rows: LinkBatchInput[] = [];
for (const candidate of extracted.candidates) {
- const from = candidate.fromSlug ?? page.slug;
- if (candidate.targetSourceId && candidate.targetSourceId !== sourceId) {
- result.unresolved.push({ originSlug, target: `${candidate.targetSourceId}:${candidate.targetSlug}`, reason: 'cross_source' });
- continue;
- }
- if (!index.has(from) || !index.has(candidate.targetSlug)) {
- result.unresolved.push({ originSlug, target: candidate.targetSlug, reason: 'missing_target' });
- continue;
- }
- rows.push(resolvedLinkCandidate(candidate, page.slug, sourceId,
- { fromSlug: from, fromSourceId: sourceId, toSourceId: sourceId }));
+ const admitted = sourcesOf.admit(candidate);
+ if (admitted.ok) { rows.push(admitted.row); continue; }
+ const crossSource = admitted.reason === 'cross_source';
+ result.unresolved.push({ originSlug, reason: crossSource ? 'cross_source' : 'missing_target',
+ target: crossSource && candidate.targetSourceId ? `${candidate.targetSourceId}:${candidate.targetSlug}` : candidate.targetSlug });
}
const wanted = wantedEnabled ? collectWantedLinks({ candidates: extracted.candidates, frontmatterUnresolved: extracted.unresolved,
- originSourceId: sourceId, crossSourceAllowed: false, resolve: candidate =>
- candidate.targetSourceId && candidate.targetSourceId !== sourceId ? { ok: false, reason: 'cross_source' }
- : !index.has(candidate.targetSlug) ? { ok: false, reason: 'missing_target' } : { ok: true } }) : [];
+ originSourceId: sourceId, crossSourceAllowed: sourcesOf.crossSourceAllowed, resolve: sourcesOf.resolve }) : [];
let written: { created: number; removed: number };
try {
written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,
- expectedRevision: snapshot.revision, sourceIncarnation }, rows, { lineGrammar: grammar, wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints:
- [...new Set(rows.flatMap(row => [row.from_slug, row.to_slug]))].map(slug => ({ slug, sourceId,
- revision: index.get(slug)!.knowledge_revision })) });
+ expectedRevision: snapshot.revision, sourceIncarnation }, rows, { lineGrammar: grammar,
+ wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints: capturedLinkEndpoints(rows, metadata) });
} catch (error) {
if (!(error instanceof DerivedLinkSettingsChangedError)) throw error;
result.failures.push({ originSlug, code: 'revision_conflict' });
@@ -238,13 +237,43 @@ export function indexLinkSources(pages: ReadonlyArray<{ slug: string; source_id:
return { allSlugs, slugToSources };
}
-export async function loadLinkSourcePolicy(engine: BrainEngine, sourceId: string) {
+export interface LinkSourcePolicy { allowCrossSource: boolean; crossSource: boolean; defaultSourceId: string }
+
+export async function loadLinkSourcePolicy(engine: BrainEngine, sourceId: string): Promise<LinkSourcePolicy> {
const [source, crossSource, defaultSourceId] = await Promise.all([
fetchSource(engine, sourceId), isCrossSourceLinksEnabled(engine), resolveLinkFallbackDefault(engine),
]);
return { allowCrossSource: source !== null && !source.archived && isSourceFederated(source.config), crossSource, defaultSourceId };
}
+export type LinkCandidateAdmission = { ok: true; row: LinkBatchInput } | Exclude<CandidateSourceResolution, { ok: true }>;
+
+/**
+ * #4680: the one source-policy resolver for one origin page, shared by put_page's link
+ * preparation and the source reconciliation sweep (`extract links --source db` applies the
+ * same `resolveCandidateSources` contract inline). `resolve` decides both endpoints'
+ * sources under the policy; `admit` turns an approved candidate into its link row and
+ * requires only that an outbound edge originates in the origin's own source (publication
+ * enforces that too): a target the policy resolved into another source is admitted, a
+ * candidate the policy refused is a counted drop. Canonical attendance is the one edge
+ * whose far endpoint, the person, may live in another source.
+ */
+export function makeLinkSourceResolver(pageSlug: string, pageSourceId: string,
+ endpoints: { allSlugs: Set<string>; slugToSources: Map<string, string[]> }, policy: LinkSourcePolicy) {
+ const resolve = (candidate: LinkCandidate): CandidateSourceResolution => resolveCandidateSources(candidate, pageSlug, pageSourceId,
+ endpoints.allSlugs, endpoints.slugToSources, policy.allowCrossSource, policy);
+ return {
+ resolve,
+ crossSourceAllowed: policy.allowCrossSource || policy.crossSource,
+ admit(candidate: LinkCandidate): LinkCandidateAdmission {
+ const resolved = resolve(candidate);
+ if (!resolved.ok) return resolved;
+ if (!candidate.canonicalAttendance && resolved.fromSourceId !== pageSourceId) return { ok: false, reason: 'cross_source' };
+ return { ok: true, row: resolvedLinkCandidate(candidate, pageSlug, pageSourceId, resolved) };
+ },
+ };
+}
+
export function capturedLinkEndpoints(links: LinkBatchInput[], metadata: ReadonlyMap<string, Pick<LinkPageMetadata, 'slug' | 'source_id' | 'knowledge_revision'>>) {
const keys = new Set(links.flatMap(link => [
`${link.from_source_id ?? 'default'}\0${link.from_slug}`, `${link.to_source_id ?? 'default'}\0${link.to_slug}`,
diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.ts
index 8a146a81a3..bdf6b9329b 100644
--- a/src/core/persistence/links-preparation.ts
+++ b/src/core/persistence/links-preparation.ts
@@ -1,10 +1,10 @@
import type { BrainEngine } from '../engine.ts';
import { isUndefinedTableError } from '../utils.ts';
import type { ParsedPage } from '../import-file.ts';
-import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResolver, resolvedLinkCandidate } from '../link-extraction.ts';
+import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResolver } from '../link-extraction.ts';
import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';
import { DerivedLinkEndpointChangedError } from '../derived-links.ts';
-import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, resolveCandidateSources } from '../link-reconciliation.ts';
+import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, makeLinkSourceResolver } from '../link-reconciliation.ts';
import { collectWantedLinks, isWantedPagesEnabled, possibleWantedRows } from '../wanted-links.ts';
import { readFix } from '../ops/op-fix.ts';
import { readLineGrammarSettings, type LineGrammarSettings } from '../line-grammar.ts';
@@ -106,24 +106,25 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
const metadata = new Map(endpointRows.map(row => [`${row.source_id}\0${row.slug}`, row]));
endpoints.allSlugs.add(slug);
endpoints.slugToSources.set(slug, [...new Set([sourceId, ...(endpoints.slugToSources.get(slug) ?? [])])]);
- const resolve = (candidate: Parameters<typeof resolveCandidateSources>[0]) => resolveCandidateSources(candidate, slug,
- sourceId, endpoints.allSlugs, endpoints.slugToSources, policy.allowCrossSource, policy);
+ // #4680: the source policy decides the target's source (shared with the reconciliation sweep).
+ const sources = makeLinkSourceResolver(slug, sourceId, endpoints, policy);
const { candidates, unresolved, attendanceComplete } = await extractPageLinks(slug, content, page.frontmatter, page.type, resolver,
{ ...opts, targetType: (targetSlug, targetSourceId) => {
- const resolved = resolve({ targetSlug, targetSourceId, linkType: '', context: '' });
+ const resolved = sources.resolve({ targetSlug, targetSourceId, linkType: '', context: '' });
return resolved.ok ? (targetSlug === slug && resolved.toSourceId === sourceId ? page.type
: metadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type) : undefined;
} });
// The rows the store keeps (#6228/#6225), so the receipt's wanted preview never names a target no page can have.
const wanted = { producers: ['body', 'frontmatter'] as const, rows: await isWantedPagesEnabled(engine)
? await possibleWantedRows(engine, sourceId, collectWantedLinks({ candidates: candidates.map(retarget), frontmatterUnresolved: unresolved,
- originSourceId: sourceId, crossSourceAllowed: policy.allowCrossSource || policy.crossSource, resolve }))
+ originSourceId: sourceId, crossSourceAllowed: sources.crossSourceAllowed, resolve: sources.resolve }))
: [] };
+ let skippedCrossSource = 0;
const rows = candidates.map(retarget).flatMap(candidate => {
- const resolved = resolve(candidate);
- if (!resolved.ok) return [];
- if (!candidate.canonicalAttendance && (resolved.fromSourceId !== sourceId || resolved.toSourceId !== sourceId)) return [];
- return [resolvedLinkCandidate(candidate, slug, sourceId, resolved)];
+ const admitted = sources.admit(candidate);
+ if (admitted.ok) return [admitted.row];
+ if (admitted.reason === 'cross_source') skippedCrossSource++;
+ return [];
});
return { attendanceComplete, settings, pageKeys: [{ sourceId, slug }, ...rows.flatMap(row => [
{ sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },
@@ -137,7 +138,7 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,
expectedEndpoints: capturedLinkEndpoints(rows, new Map([...metadata,
[`${sourceId}\0${slug}`, { slug, source_id: sourceId, type: page.type, knowledge_revision: snapshot.revision }]]))
.filter(endpoint => endpoint.slug !== slug || endpoint.sourceId !== sourceId) });
- return { ...result, errors: 0, unresolved_count: unresolved.length, wanted_count: wanted.rows.length,
+ return { ...result, errors: 0, unresolved_count: unresolved.length, skipped_cross_source: skippedCrossSource, wanted_count: wanted.rows.length,
...(wanted.rows.length ? { wanted: wanted.rows.slice(0, 10).map(row => ({ slug: row.target_ref, source_id: row.target_source_id })),
wanted_message: 'These link targets have no page yet; each edge is created when its page is. Create the page if it is real, or fix the link if it is a typo.',
fix: readFix(`Lists every link target in source ${sourceId} that has no page yet, with the pages that link to it, read-only.`,
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index b066566e10..91ed9b5d6a 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -373,8 +373,11 @@ async function assembleCard(
// slug; engine.getBacklinkCounts counts inbound from ALL sources. We run
// a both-sides-scoped query here (f.source_id = t.source_id = this source),
// mentions excluded (matching the backlink-count convention). Outgoing edges
- // (getLinks) are the entity's OWN declared links — from-side scoped — so they
- // stay as-is. The referrer must also be live and, for an untrusted caller,
+ // (getLinks) are the entity's OWN declared links — from-side scoped for the
+ // trusted local caller; an untrusted caller reads them through the engine's
+ // all-endpoints branch (`sourceIds`), so an edge the source policy admitted
+ // into another source (#4680) never shows that source's slug on the card.
+ // The referrer must also be live and, for an untrusted caller,
// readable: the same private-page and private-origin predicates get_backlinks
// applies, so a private or derived page never surfaces its slug, its
// links.context sentence, or a count.
@@ -386,7 +389,7 @@ async function assembleCard(
)
.then(rs => rs.map(r => r.alias_norm))
.catch(() => [] as string[]),
- engine.getLinks(pageSlug, { sourceId, excludePrivate, temporal: { status: 'all' } }).catch(() => []),
+ engine.getLinks(pageSlug, { ...(remote ? { sourceIds: [sourceId] } : { sourceId }), excludePrivate, temporal: { status: 'all' } }).catch(() => []),
engine
.executeRaw<{ from_slug: string; link_type: string; context: string | null }>(
`SELECT f.slug AS from_slug, l.link_type, l.context${TEMPORAL_LINK_SELECT_SQL}
diff --git a/test/link-cross-source.test.ts b/test/link-cross-source.test.ts
new file mode 100644
index 0000000000..7912a73e45
--- /dev/null
+++ b/test/link-cross-source.test.ts
@@ -0,0 +1,219 @@
+/**
+ * #4680 — cross-source automatic links follow the source policy on every writer.
+ *
+ * Protects: (1) an outbound edge the source policy approved (`link_resolution.cross_source`,
+ * or a `[[source:slug]]` reference from a federated origin) is written by put_page's link
+ * preparation and kept by the source reconciliation sweep and the stale re-extract, with
+ * `skipped_cross_source` reporting the drops instead of hiding them; (2) with the flag off
+ * and a non-federated origin, cross-source candidates are dropped exactly as before and
+ * counted; (3) canonical attendance keeps its foreign-person exception and the endpoint
+ * revision fence still refuses a stale foreign endpoint; (4) read side: a reader granted one source never sees the other
+ * source's endpoint through get_links, get_backlinks or the entity card, whether `remote`
+ * is true or omitted, while a reader granted both sources does.
+ * Fails when: the preparation gate or the sweep drops approved edges (the admitted rows
+ * are then deleted by the next preserving replacement), the count is missing, the
+ * attendance exception or revision fence is lost, or a
+ * link read scopes only one endpoint for an untrusted caller.
+ * Seams: none (production entry points only). PGLite always, Postgres when DATABASE_URL
+ * is set (test/postgres-unit-arms.txt lane).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operationsByName, type AuthInfo, type OperationContext } from '../src/core/operations.ts';
+import { reconcileSourceLinks } from '../src/core/link-reconciliation.ts';
+import { prepareAutomaticLinks } from '../src/core/persistence/links-preparation.ts';
+import { extractManagedStaleLinks } from '../src/core/persistence/links-maintenance.ts';
+import { loadActivePackForLocalEngine } from '../src/core/schema-pack/best-effort.ts';
+import { readLineGrammarSettings } from '../src/core/line-grammar.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const ON = { GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' };
+const OFF = { GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: undefined };
+
+async function page(engine: BrainEngine, sourceId: string, slug: string, type: string, body = 'A page.') {
+ await engine.putPage(slug, { type, title: slug.split('/').pop()!, compiled_truth: body, frontmatter: {} }, { sourceId });
+}
+
+async function setFederated(engine: BrainEngine, sourceId: string, federated: boolean) {
+ await engine.executeRaw(`UPDATE sources SET config=$2::text::jsonb WHERE id=$1`, [sourceId, JSON.stringify(federated ? { federated: true } : {})]);
+}
+
+/** Every edge touching (sourceId, slug) as `from > to type producer`. */
+async function edges(engine: BrainEngine, sourceId: string, slug: string) {
+ const rows = await engine.executeRaw<{ edge: string }>(`SELECT f.source_id||':'||f.slug||' > '||t.source_id||':'||t.slug||' '||l.link_type||' '||l.link_source AS edge
+ FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_id
+ WHERE (f.source_id=$1 AND f.slug=$2) OR (t.source_id=$1 AND t.slug=$2)`, [sourceId, slug]);
+ return rows.map(row => row.edge).sort();
+}
+
+/** put_page's automatic link pass for one page: prepare, lock, apply. */
+async function derive(engine: BrainEngine, sourceId: string, slug: string) {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ const prepared = await prepareAutomaticLinks(engine, slug, { ...snapshot.page, frontmatter: snapshot.page.frontmatter ?? {} }, sourceId);
+ return engine.transaction(async tx => { await tx.lockPageKeys(prepared.pageKeys); return prepared.apply(tx); });
+}
+
+const ORIGIN_BODY = 'Shared [[topics/shared]] and qualified [[beta:topics/shared]].\nBeta only [[topics/beta-only]].';
+const SAME = 'alpha:notes/origin > alpha:topics/shared mentions markdown';
+const QUALIFIED = 'alpha:notes/origin > beta:topics/shared mentions markdown';
+const UNQUALIFIED = 'alpha:notes/origin > beta:topics/beta-only mentions markdown';
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`${backend}: #4680 cross-source automatic links follow the source policy on every writer`, () => {
+ let engine: BrainEngine; let close: () => Promise<void>;
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl));
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES('alpha','alpha','{}'),('beta','beta','{}')`);
+ await page(engine, 'alpha', 'topics/shared', 'note');
+ await page(engine, 'beta', 'topics/shared', 'note');
+ await page(engine, 'beta', 'topics/beta-only', 'note');
+ await page(engine, 'beta', 'people/bob-example', 'person');
+ await page(engine, 'alpha', 'notes/origin', 'note', ORIGIN_BODY);
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('policy denies (flag off, origin not federated): cross-source candidates are dropped as before and counted', () => withEnv(OFF, async () => {
+ await setFederated(engine, 'alpha', false);
+ const applied = await derive(engine, 'alpha', 'notes/origin');
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME]);
+ expect(applied).toMatchObject({ errors: 0, skipped_cross_source: 2 });
+ }), 60_000);
+
+ test('a federated origin admits the qualified reference only; the unqualified foreign-only target is still counted', () => withEnv(OFF, async () => {
+ await setFederated(engine, 'alpha', true);
+ try {
+ const applied = await derive(engine, 'alpha', 'notes/origin');
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME, QUALIFIED]);
+ expect(applied).toMatchObject({ errors: 0, skipped_cross_source: 1 });
+ } finally { await setFederated(engine, 'alpha', false); }
+ }), 60_000);
+
+ test('policy approves (flag on): both cross-source edges are kept and skipped_cross_source is 0', () => withEnv(ON, async () => {
+ const applied = await derive(engine, 'alpha', 'notes/origin');
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME, UNQUALIFIED, QUALIFIED]);
+ expect(applied).toMatchObject({ errors: 0, skipped_cross_source: 0 });
+ }), 60_000);
+
+ test('the source reconciliation sweep and the stale re-extract keep the admitted edges', () => withEnv(ON, async () => {
+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: 'alpha' }))!.manifest;
+ const swept = await reconcileSourceLinks(engine, 'alpha', { pack });
+ expect(swept.ok).toBe(true);
+ expect(swept.unresolved.filter(ref => ref.originSlug === 'notes/origin')).toEqual([]);
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME, UNQUALIFIED, QUALIFIED]);
+ const stale = await extractManagedStaleLinks(engine, { sourceId: 'alpha', slugs: ['notes/origin'], maxPages: 1, mentions: false });
+ expect(stale).toMatchObject({ pages: 1, removed: 0, skipped: 0 });
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME, UNQUALIFIED, QUALIFIED]);
+ }), 60_000);
+
+ test('flag off again: the sweep reports the foreign targets as cross_source and removes them, as before', () => withEnv(OFF, async () => {
+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: 'alpha' }))!.manifest;
+ const swept = await reconcileSourceLinks(engine, 'alpha', { pack });
+ expect(swept.ok).toBe(true);
+ expect(swept.unresolved.filter(ref => ref.originSlug === 'notes/origin').map(ref => [ref.target, ref.reason]).sort())
+ .toEqual([['beta:topics/shared', 'cross_source'], ['topics/beta-only', 'cross_source']]);
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME]);
+ }), 60_000);
+
+ test('a preserving stale pass no longer deletes admitted cross-source rows absent from a reduced set (133 → 3)', () => withEnv(ON, async () => {
+ for (let i = 0; i < 5; i++) await page(engine, 'beta', `topics/foreign-${i}`, 'note');
+ await page(engine, 'alpha', 'notes/bulk', 'note', `See ${Array.from({ length: 5 }, (_, i) => `[[topics/foreign-${i}]]`).join(', ')} and [[topics/shared]].`);
+ // The rows `extract links --source db` writes for this page: every approved endpoint, foreign ones included.
+ const snapshot = (await engine.readPageSnapshot('notes/bulk', { sourceId: 'alpha' }))!;
+ const rows = [...Array.from({ length: 5 }, (_, i) => ({ to_slug: `topics/foreign-${i}`, to_source_id: 'beta' })), { to_slug: 'topics/shared', to_source_id: 'alpha' }]
+ .map(to => ({ from_slug: 'notes/bulk', from_source_id: 'alpha', link_type: 'mentions', link_source: 'markdown', origin_source_id: 'alpha', context: 'See', ...to }));
+ await engine.replaceDerivedLinks({ slug: 'notes/bulk', sourceId: 'alpha', expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation },
+ rows, { lineGrammar: await readLineGrammarSettings(engine) });
+ expect(await edges(engine, 'alpha', 'notes/bulk')).toHaveLength(6);
+ const applied = await derive(engine, 'alpha', 'notes/bulk');
+ expect(applied).toMatchObject({ errors: 0, removed: 0, skipped_cross_source: 0 });
+ expect(await edges(engine, 'alpha', 'notes/bulk')).toHaveLength(6);
+ }), 60_000);
+
+ test('canonical attendance keeps admitting a foreign person under the policy; denied, the attendance stays unresolved as before', async () => {
+ await page(engine, 'alpha', 'meetings/standup', 'meeting', 'Attendees: [[people/bob-example]]');
+ await withEnv(ON, async () => {
+ expect(await derive(engine, 'alpha', 'meetings/standup')).toMatchObject({ errors: 0, skipped_cross_source: 0 });
+ expect(await edges(engine, 'alpha', 'meetings/standup')).toEqual(['beta:people/bob-example > alpha:meetings/standup attended markdown']);
+ });
+ await withEnv(OFF, async () => {
+ expect(await derive(engine, 'alpha', 'meetings/standup')).toMatchObject({ created: 0, removed: 0, errors: 1, unresolved_count: 1 });
+ expect(await edges(engine, 'alpha', 'meetings/standup')).toEqual(['beta:people/bob-example > alpha:meetings/standup attended markdown']);
+ });
+ }, 60_000);
+
+ test('the endpoint revision fence still refuses a foreign endpoint that changed after preparation', () => withEnv(ON, async () => {
+ const snapshot = (await engine.readPageSnapshot('notes/origin', { sourceId: 'alpha' }))!;
+ const prepared = await prepareAutomaticLinks(engine, 'notes/origin', { ...snapshot.page, frontmatter: snapshot.page.frontmatter ?? {} }, 'alpha');
+ await page(engine, 'beta', 'topics/beta-only', 'note', 'Edited after the links were prepared.');
+ const applied = await engine.transaction(async tx => { await tx.lockPageKeys(prepared.pageKeys); return prepared.apply(tx); });
+ expect(applied).toMatchObject({ created: 0, removed: 0, errors: 1 });
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME]);
+ }), 60_000);
+ });
+
+ describe(`${backend}: #4680 read side — a reader granted one source never sees the other source's endpoint`, () => {
+ let engine: BrainEngine; let close: () => Promise<void>;
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedSharedSkillsEngine(databaseUrl));
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES('alpha','alpha','{}'),('beta','beta','{}')`);
+ await page(engine, 'alpha', 'topics/shared', 'note');
+ await page(engine, 'beta', 'topics/shared', 'note');
+ await page(engine, 'beta', 'topics/beta-only', 'note');
+ await page(engine, 'alpha', 'notes/origin', 'note', ORIGIN_BODY);
+ await withEnv(ON, async () => { expect(await derive(engine, 'alpha', 'notes/origin')).toMatchObject({ errors: 0, skipped_cross_source: 0 }); });
+ expect(await edges(engine, 'alpha', 'notes/origin')).toEqual([SAME, UNQUALIFIED, QUALIFIED]);
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ const auth = (allowedSources: string[]) => ({ token: '', clientId: 'client-a', scopes: ['read'], sourceId: allowedSources[0], allowedSources,
+ principal: { kind: 'oauth_client', id: 'client-a' } }) as AuthInfo;
+ const keys = (rows: unknown) => (rows as Array<Record<string, string>>).map(r => `${r.from_source_id}:${r.from_slug} > ${r.to_source_id}:${r.to_slug}`).sort();
+ const quiet = { info: () => {}, warn: () => {}, error: () => {} };
+ /** The link ops through the MCP dispatcher (`remote: true`) and through a context whose `remote` is omitted (untrusted too). */
+ const readers = (grant: string[]) => ({
+ async remote(name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(engine, name, params, { remote: true, transport: 'http', sourceId: grant[0], auth: auth(grant), config: {} as never });
+ return JSON.parse(result.content[0].text);
+ },
+ async omitted(name: string, params: Record<string, unknown>) {
+ const ctx = { engine, config: {} as never, logger: quiet, dryRun: false, sourceId: grant[0], auth: auth(grant), transport: 'http' } as unknown as OperationContext;
+ return operationsByName[name].handler(ctx, params);
+ },
+ });
+
+ for (const how of ['remote', 'omitted'] as const) {
+ test(`${how}: granted [alpha] sees no beta endpoint; granted [alpha, beta] sees the admitted edges`, async () => {
+ const alpha = readers(['alpha']);
+ expect(keys(await alpha[how]('get_links', { slug: 'notes/origin' }))).toEqual(['alpha:notes/origin > alpha:topics/shared']);
+ expect(keys(await alpha[how]('get_backlinks', { slug: 'topics/shared' }))).toEqual(['alpha:notes/origin > alpha:topics/shared']);
+ expect(await alpha[how]('get_backlinks', { slug: 'topics/beta-only' })).toEqual([]);
+ const beta = readers(['beta']);
+ expect(await beta[how]('get_backlinks', { slug: 'topics/beta-only' })).toEqual([]);
+ expect(await beta[how]('get_backlinks', { slug: 'topics/shared' })).toEqual([]);
+ const both = readers(['alpha', 'beta']);
+ expect(keys(await both[how]('get_links', { slug: 'notes/origin' }))).toEqual([
+ 'alpha:notes/origin > alpha:topics/shared', 'alpha:notes/origin > beta:topics/beta-only', 'alpha:notes/origin > beta:topics/shared']);
+ expect(keys(await both[how]('get_backlinks', { slug: 'topics/beta-only' }))).toEqual(['alpha:notes/origin > beta:topics/beta-only']);
+ }, 60_000);
+
+ test(`${how}: the entity card confines its edges to the card's own source for an untrusted caller`, async () => {
+ for (const grant of [['alpha'], ['alpha', 'beta']]) {
+ const result = await readers(grant)[how]('entity', { name: 'notes/origin' }) as { found: boolean; card: { edges: Array<{ direction: string; slug: string }> } };
+ expect(result.found).toBe(true);
+ expect(result.card.edges.map(edge => `${edge.direction} ${edge.slug}`)).toEqual(['out topics/shared']);
+ }
+ }, 60_000);
+ }
+
+ test('the trusted local caller keeps the cross-source far endpoint', async () => {
+ const ctx = { engine, config: {} as never, logger: quiet, dryRun: false, remote: false, sourceId: 'alpha' } as OperationContext;
+ expect(keys(await operationsByName.get_links.handler(ctx, { slug: 'notes/origin' }))).toEqual([
+ 'alpha:notes/origin > alpha:topics/shared', 'alpha:notes/origin > beta:topics/beta-only', 'alpha:notes/origin > beta:topics/shared']);
+ }, 60_000);
+ });
+}
diff --git a/test/link-preparation-shared-index.test.ts b/test/link-preparation-shared-index.test.ts
index 68cfbc4e93..3640a71f4b 100644
--- a/test/link-preparation-shared-index.test.ts
+++ b/test/link-preparation-shared-index.test.ts
@@ -7,7 +7,9 @@
* keep exactly the edges, drop reasons (`cross_source` vs `missing_target`),
* unresolved counts and wanted rows that the per-page slug read and the
* slug-only endpoint query produced, for frontmatter, dir-qualified and bare
- * wikilink, markdown, source-qualified and renamed-slug forms; (2) the shared
+ * wikilink, markdown, source-qualified and renamed-slug forms — an edge the
+ * policy resolved into the other source is written (#4680), one it refused
+ * is not; (2) the shared
* index sees every page written after it was built (insert, rename, delete),
* whether or not the write went through a page write path, and is reused
* without a full slug read while the source is unchanged.
@@ -79,6 +81,13 @@ const EDGES = [
'alpha:notes/origin > alpha:topics/shared related_to frontmatter',
'alpha:notes/origin > alpha:topics/shared wikilink_basename wikilink-resolved',
];
+// #4680 (contract change): the edges the source policy resolved into beta are written, not dropped
+// after approval. Under `cross_source` the bare and qualified beta-only forms collapse to one edge;
+// a federated origin admits only the qualified forms (the bare one stays a counted `cross_source`).
+const CROSS_SOURCE_EDGES = [...EDGES,
+ 'alpha:notes/origin > beta:topics/beta-only mentions markdown',
+ 'alpha:notes/origin > beta:topics/shared mentions markdown',
+];
const resolutions = (betaOnly: string, betaOnlyQualified: string, sharedQualified: string) => [
'alice-example missing_target', 'bob-example missing_target', 'ideas/unwritten missing_target', 'people/alice-example alpha>alpha',
'projects/gadget missing_target', 'projects/widget alpha>alpha', 'shared missing_target', `topics/beta-only ${betaOnly}`,
@@ -89,10 +98,10 @@ const POLICIES = [
{ name: 'cross-source links off', env: {}, federated: false, expected: { edges: EDGES, unresolved: 2,
resolutions: resolutions('cross_source', 'cross_source', 'cross_source'),
wanted: wanted('alpha:topics/beta-only', 'alpha:bob-example', 'alpha:ideas/unwritten', 'alpha:topics/beta-only') } },
- { name: 'link_resolution.cross_source on', env: { GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, federated: false, expected: { edges: EDGES, unresolved: 2,
+ { name: 'link_resolution.cross_source on', env: { GBRAIN_LINK_RESOLUTION_CROSS_SOURCE: '1' }, federated: false, expected: { edges: CROSS_SOURCE_EDGES, unresolved: 2,
resolutions: resolutions('alpha>beta', 'alpha>beta', 'alpha>beta'),
wanted: wanted('alpha:bob-example', 'alpha:ideas/unwritten', 'alpha:topics/beta-only', 'beta:topics/beta-only') } },
- { name: 'federated origin source', env: {}, federated: true, expected: { edges: EDGES, unresolved: 2,
+ { name: 'federated origin source', env: {}, federated: true, expected: { edges: CROSS_SOURCE_EDGES, unresolved: 2,
resolutions: resolutions('cross_source', 'alpha>beta', 'alpha>beta'),
wanted: wanted('alpha:topics/beta-only', 'alpha:bob-example', 'alpha:ideas/unwritten', 'alpha:topics/beta-only', 'beta:topics/beta-only') } },
];
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 7171a00b5d..709fbc5418 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -44,6 +44,7 @@ test/import-frontmatter-key-order-5158.test.ts
test/import-inline-chunk-keep.test.ts
test/import-revision-concurrency.test.ts
test/lane-apply-pipelining.test.ts
+test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts
test/links-attendance-blocked.test.ts
test/managed-cycle-pull-upstream.test.ts