Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Link context and the core memory block no longer show private or held fact rows to remote callers (GST-2957) (#9637)

Garry Tan280b5a87cac6
diff --git a/changelog.d/capy-link-context-world-rows-2957.md b/changelog.d/capy-link-context-world-rows-2957.md
new file mode 100644
index 0000000000..9dcabe6561
--- /dev/null
+++ b/changelog.d/capy-link-context-world-rows-2957.md
@@ -0,0 +1,11 @@
+---
+important: security
+---
+**Link context no longer shows remote callers private or held fact rows: get_backlinks, get_links, traverse_graph (walks and hops), the relationship-chain evidence on search, query and recall results, the entity card, context_pack and delta's belief changes leave that text out for callers who may read only world facts, and context_pack's always-loaded core block leaves held rows out for them too.**
+
+### Fixed
+- A link's stored context is a short excerpt of the page around the reference. When the reference sat in or next to a page's `## Facts` table, the excerpt carried rows of that table, including rows saved private and world rows held until the operator accepts a widening. Remote callers who may read only world facts (another member, an unbound token) read that text through get_backlinks, get_links, traverse_graph walks and hops, the chain evidence on search, query and recall results, the entity card's edges and context_pack's cards. An attendance edge, stored on the attendee's page but cut from the meeting page, carried the meeting's rows the same way. For those callers, a context cut from a page is now returned only when it reads, word for word, inside that page as it is now and as the caller may see it; otherwise it comes back empty. That also covers a page whose table was removed by an edit that left its links unchanged. The page bodies for one read are loaded together, for at most 200 pages; contexts cut from pages beyond that come back empty for those callers. A context written by add_link or derived from frontmatter is unchanged unless it holds a facts or takes table marker.
+- unify-types' `preserve_notes` stored the first 240 characters of a converted page as the new link's context, facts and takes tables included. It now leaves those tables out, so links written from now on store a shorter excerpt for every reader, the owner included. Contexts it stored before are emptied for callers who may read only world facts when they hold a table marker.
+- `delta` with `beliefs: true` returned each changed link's stored context in its before and after values. Those callers now get the link change without the context.
+- With `memory.core.enabled` on, context_pack's core memory block showed those callers a core page's held rows. It now leaves them out, as get_page does.
+- The owner's remote callers and the local CLI read stored links exactly as before. Stored links are not rewritten and no migration runs.
diff --git a/docs/architecture/key-files/core-utilities-2-continued.md b/docs/architecture/key-files/core-utilities-2-continued.md
index e0c3bca99e..73c4d9175f 100644
--- a/docs/architecture/key-files/core-utilities-2-continued.md
+++ b/docs/architecture/key-files/core-utilities-2-continued.md
@@ -18,7 +18,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation; a page with no `[Source:` returns none before any paragraph is built. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis and keep inline code (#8893), and `supersededInlineCitationEntries` returns older readings' entries the current one drops; `timeline-extract.ts:supersededTimelineReadings` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.
- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.
-- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `fenceLowTierRows` / `renderFenceLowTier` give the demoted rows of one text for the segment reader's low-tier block. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).
+- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `fenceLowTierRows` / `renderFenceLowTier` give the demoted rows of one text for the segment reader's low-tier block. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`). GST-2957: `worldLinkContexts(engine, remote, rows, edge)` matches each returned context to its stored link rows (`storedEdge`: from, to, type) and, for a caller whose fact reads are world-only, empties it unless one row was writer-supplied (add_link, frontmatter) and holds no facts or takes fence marker (unify-types' `preserve_notes` stored page openings as manual contexts; `page-to-link.ts` now strips both fences first), or reads inside its origin page (else its from page) as it is now and as the caller sees it (sanitizeRemoteBody less `heldRowsForCaller`). Origin bodies are read in one query for at most `LINK_CONTEXT_PAGE_BOUND` (200) pages in result order; owner and local callers run no query. No match, a page past the bound, a segmented or missing page, or a failed lookup fails closed. get_links, get_backlinks, traverse_graph walks and hops (`chainStoredEdge`), the relational arm's chain evidence (`hydrateChain`, so search, query and recall) and the entity card's edges call it, and delta's link beliefs carry no context for such a caller; tests in `test/link-context-world-rows-2957.test.ts` and `test/delta-beliefs-link-context-2957.test.ts`.
- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.
- `src/core/url-redact.ts` — Postgres-URL + free-text credential redaction, sibling of `redact-connection-info.ts`. `redactPgUrl(url)` strips userinfo from a single postgres/postgresql URL, preserving scheme/host/port/db/query (non-URL input collapses to `<redacted-url>`). `redactUrlsInText(text)` sweeps free text (error messages, log lines) for credential shapes of any word-character scheme (the pattern is `\w+://`, so scheme names containing `+`/`-`/`.` are not matched — postgres shapes are the target): the userinfo match is greedy up to the LAST `@` in the token so a raw `@` inside a password can't leak its tail (over-redacts toward safety), and libpq keyword/value forms (`password=` / `sslpassword=`, including quoted values with spaces) are masked too; text without a credential shape passes through untouched. `redactDeep(value)` recursively redacts postgres URLs inside structured payloads about to be stringified. Consumers: the upgrade-errors + connection-events audit JSONL sites, and cli.ts's doctor DB-fallback stderr note (layered with `redactConnectionInfo`). CI guard: `scripts/check-pg-url-redaction.sh` fails the build when a new code path emits an unredacted postgres URL. Pinned by `test/url-redact.test.ts`.
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 5c74ab92e3..bf6c6ec16d 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -180,6 +180,8 @@ src/core/cycle/synthesize.ts writeSummaryPage field INLINE
src/core/cycle/transcript-discovery.ts discoverConversationPages field STREAM
src/core/cycle/transcript-discovery.ts discoverConversationPages sql STREAM
src/core/eligibility/fence-overlay.ts loadFenceChunkOverlay field STREAM
+src/core/eligibility/fence-overlay.ts worldLinkContexts field INLINE segmented from page: body never read, its link contexts are emptied for world-only callers (fail closed)
+src/core/eligibility/fence-overlay.ts worldLinkContexts sql INLINE segmented from page: body never read, its link contexts are emptied for world-only callers (fail closed)
src/core/eligibility/scan.ts SELECT sql STREAM
src/core/eligibility/scan.ts assess field STREAM
src/core/embed-consent.ts estimateEmbedBackfillUsd sql META
diff --git a/src/core/belief/changes.ts b/src/core/belief/changes.ts
index 8a66f07dc4..c30cdcb833 100644
--- a/src/core/belief/changes.ts
+++ b/src/core/belief/changes.ts
@@ -60,6 +60,8 @@ export interface BeliefChangesQuery {
sourceId: string; since: string; until: string; remote: boolean; entities?: readonly string[]; limit?: number;
/** Remote callers: the take holders they may read (`readHolders`); `['world']` when absent. */
takesHolders?: readonly string[];
+ /** GST-2957: the reader's fact reads are world-only (worldOnlyFacts); `deltaBeliefs` empties link contexts (withoutLinkContexts). */
+ worldOnly?: boolean;
}
const SUBJECT_EVENTS = new Set(['fact.asserted', 'fact.revised', 'fact.retracted', 'fact.withdrawn', 'fact.superseded', 'fact.transferred', 'fact.purged',
@@ -346,6 +348,7 @@ const lineCost = (line: string) => estimateTokens(line + '\n');
*/
export async function deltaBeliefs(engine: BrainEngine, q: BeliefChangesQuery, budget: number | null, text: string, envelope: string): Promise<{ beliefs: BeliefChanges; text: string }> {
let beliefs = await beliefChanges(engine, q);
+ if (q.worldOnly) beliefs = withoutLinkContexts(beliefs);
const header = `## Belief changes since ${q.since}`;
if (budget !== null) {
const room = budget - lineCost('') - lineCost(header);
@@ -355,6 +358,15 @@ export async function deltaBeliefs(engine: BrainEngine, q: BeliefChangesQuery, b
return { beliefs, text: beliefs.changes.length ? [text || envelope, '', header, ...beliefs.changes.map(renderBeliefChange)].join('\n') : text };
}
+/**
+ * GST-2957: the changes with every link value's carried context emptied, for a delta reader whose fact reads are
+ * world-only (worldOnlyFacts): the context is an excerpt of a page body, past or present, that can hold private rows.
+ */
+export function withoutLinkContexts(b: BeliefChanges): BeliefChanges {
+ const bare = (v: Record<string, unknown> | null) => (v && typeof v.context === 'string' && v.context ? { ...v, context: '' } : v);
+ return { ...b, changes: b.changes.map(c => (c.kind === 'link' ? { ...c, before: bare(c.before), after: bare(c.after) } : c)) };
+}
+
/** The CLI's text for a whole window: a header, the coverage note, one line per change. */
export function renderBeliefChanges(b: BeliefChanges): string {
if (b.not_recorded) return `The belief ledger is not recording ${b.source_id}; enable it with gbrain beliefs enable --source ${b.source_id}.`;
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index 350ec5d57b..59c4e3910c 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -636,7 +636,7 @@ async function assemblePack(
for (const { name, sources: nameSources } of entities) {
if (deadlineAt !== null && Date.now() >= deadlineAt) return;
try {
- const res = await buildEntityCard(engine, nameSources[0]!, name, { remote, eligibility: policy, omitQuarantined: opts.includeQuarantined !== true, sources: nameSources });
+ const res = await buildEntityCard(engine, nameSources[0]!, name, { remote, readerRemote: opts.untrusted === true, eligibility: policy, omitQuarantined: opts.includeQuarantined !== true, sources: nameSources });
if (res.found && res.card && !acc.cards.some((c) => keyOf(c) === keyOf(res.card!))) {
// The card's OWN source decides activation: a same-slug page in another source never gates or admits it.
const ref = { source_id: res.card.entity.source_id, slug: res.card.entity.slug };
@@ -852,7 +852,7 @@ async function assembleDelta(
for (const name of entities) {
if (pastDeadline()) return;
try {
- const res = await buildEntityCard(engine, opts.sourceId, name, { remote, eligibility: { floor: policy.floor }, omitQuarantined: true });
+ const res = await buildEntityCard(engine, opts.sourceId, name, { remote, readerRemote: opts.untrusted === true, eligibility: { floor: policy.floor }, omitQuarantined: true });
if (res.found && res.card) {
for (const t of res.card.open_threads ?? []) {
if (!since || (t.date && isAfter(t.date, since))) items.push(t);
diff --git a/src/core/core-memory.ts b/src/core/core-memory.ts
index 88213ebd53..dc70ee683c 100644
--- a/src/core/core-memory.ts
+++ b/src/core/core-memory.ts
@@ -25,6 +25,7 @@ import { proactiveEligibility } from './eligibility/registry.ts';
import { activationSuppressedSql, pageEligibleSql } from './eligibility/sql.ts';
import { compactTrustLabel, needsDataEnvelope, renderTrustedText, trustFields } from './eligibility/labels.ts';
import { PAGE_MAX_BYTES } from './page-size-policy.ts';
+import { heldRowsForCaller } from './eligibility/fence-overlay.ts';
export const CORE_DEFAULT_MAX_CHARS = 4000;
export const CORE_MIN_MAX_CHARS = 500;
@@ -115,13 +116,15 @@ export interface CorePageInput {
/** #5575 A6: the page's trust tier and short write origin; below `operator_curated` the header carries its label. */
trust_tier?: TrustTier;
origin?: string;
+ /** GST-2957: fence rows held from the reader (heldRowsForCaller), left out of the rendered text. */
+ omitRows?: ReadonlySet<number>;
}
export interface CorePage extends CorePageInput { priority: number; rendered: string; chars: number }
/** The rendered unit: title header plus the remote-safe compiled truth. */
export function renderCorePage(page: CorePageInput): string {
- const body = sanitizeRemoteBody(page.compiled_truth ?? '').trim();
+ const body = sanitizeRemoteBody(page.compiled_truth ?? '', { omitRows: page.omitRows }).trim();
const title = (page.title || page.slug).replace(/\s+/g, ' ').trim();
const label = page.trust_tier && compareTrust(page.trust_tier, OWNER_TIER_FLOOR) < 0
? ` ${compactTrustLabel({ trust_tier: page.trust_tier, origin: page.origin ?? 'legacy' })}` : '';
@@ -233,6 +236,8 @@ export interface ListCorePagesOpts {
* Accounting reads (coreUsage) leave it unset.
*/
eligibility?: ReadEligibility;
+ /** GST-2957: the reader's OperationContext.remote; a reader whose fact reads are world-only (worldOnlyFacts) gets no held rows. */
+ remote?: boolean;
}
interface CoreRow { id: number | string; source_id: string; slug: string; title: string | null; compiled_truth: string | null; frontmatter: unknown; withdrawn: boolean;
@@ -282,8 +287,9 @@ export async function listCorePages(exec: RawExec, opts: ListCorePagesOpts = {})
} else if (segmented) {
compiled = (await (await import('./page-body/ingest.ts')).materializeSegmentedBody(exec, Number(r.id), r.source_id)).compiled_truth;
}
+ const omitRows = opts.remote === undefined ? undefined : await heldRowsForCaller(exec, opts.remote, { sourceId: r.source_id, slug: r.slug, compiled_truth: compiled });
pages.push(toCorePage({
- source_id: r.source_id, slug: r.slug, title: r.title ?? r.slug, compiled_truth: compiled,
+ source_id: r.source_id, slug: r.slug, title: r.title ?? r.slug, compiled_truth: compiled, ...(omitRows?.size ? { omitRows } : {}),
frontmatter: typeof r.frontmatter === 'string' ? JSON.parse(r.frontmatter) : r.frontmatter,
...(policy ? trustFields(r.trust_tier, r.write_origin) : {}),
}));
@@ -307,6 +313,8 @@ export interface LoadCoreBlockOpts {
settings?: CoreSettings;
/** #5575: the caller's proactive eligibility (token floor); absent, the `core_delivery` surface policy applies. */
eligibility?: ReadEligibility;
+ /** GST-2957: the reader's OperationContext.remote; a reader whose fact reads are world-only (worldOnlyFacts) gets no held rows. */
+ remote?: boolean;
}
/** Credential-like PII withholds the page; contact details and private paths are redacted in place. */
@@ -367,7 +375,7 @@ export async function loadCoreBlock(engine: BrainEngine, opts: LoadCoreBlockOpts
}
const sourceIds = sessionCoreSources(opts.sessionSourceId, opts.allowedSources ?? null);
const eligibility = opts.eligibility ?? await proactiveEligibility({ engine }, 'core_delivery');
- const all = await listCorePages(engine, { sourceIds, excludePrivate: opts.excludePrivate ?? true, forCaller: opts.forCaller, eligibility });
+ const all = await listCorePages(engine, { sourceIds, excludePrivate: opts.excludePrivate ?? true, forCaller: opts.forCaller, eligibility, remote: opts.remote });
const listed = all.filter(p => !p.suppressed);
const suppressed = all.filter(p => p.suppressed).map(p => ({ source_id: p.source_id, slug: p.slug, family: 'unconfirmed agent-written instruction (gbrain trust review)' }));
const { pages, withheld } = await applyCoreSensitivity(listed);
diff --git a/src/core/eligibility/fence-overlay.ts b/src/core/eligibility/fence-overlay.ts
index 9b2ad53eae..88c76afec1 100644
--- a/src/core/eligibility/fence-overlay.ts
+++ b/src/core/eligibility/fence-overlay.ts
@@ -35,6 +35,9 @@ import { activationSuppressedSql } from './sql.ts';
import { holdFingerprint } from '../write-gate-store.ts';
import { memberFactAdmitSql } from '../access/member-facts.ts';
import { worldOnlyFacts } from '../search/private-visibility.ts';
+import { sanitizeRemoteBody } from '../remote-body.ts';
+import { MANAGED_LINK_SOURCES, maskLinksFence } from '../links-fence.ts';
+import { ensureWellFormed } from '../text-safe.ts';
/** The origin slot of a fence trust marker: the chunk holds facts-fence rows, not page prose. */
export const FENCE_TRUST_ORIGIN = 'facts-fence';
@@ -297,3 +300,73 @@ export async function heldRowsForCaller(engine: Pick<BrainEngine, 'executeRaw'>,
page: { sourceId: string; slug: string; compiled_truth: string; timeline?: string | null }): Promise<ReadonlySet<number> | undefined> {
return worldOnlyFacts(remote) ? (await loadFenceChunkOverlay(engine, page, { hideHeld: true }))?.held : undefined;
}
+
+/** Link producers whose context is an excerpt of a page body (link-extraction.ts); a null source is a legacy row. */
+const BODY_EXCERPT_LINK_SOURCES: readonly string[] = MANAGED_LINK_SOURCES.filter(s => s !== 'frontmatter');
+
+/** The most origin pages whose bodies one worldLinkContexts call reads; contexts from pages past it come back empty. */
+export const LINK_CONTEXT_PAGE_BOUND = 200;
+
+/** Text holding a facts or takes fence marker, whole or near-miss: every fence row follows its opening marker. */
+const holdsFenceMarker = (text: string): boolean => text.includes('gbrain:facts') || text.includes('gbrain:takes');
+
+/** A returned edge's stored identity: its two pages and its type. */
+export interface StoredEdgeRef { from: { sourceId: string; slug: string }; to: { sourceId: string; slug: string }; linkType: string }
+
+/** The stored identity of a returned link or graph edge. */
+export function storedEdge(e: { from_source_id: string; from_slug: string; to_source_id: string; to_slug: string; link_type: string }): StoredEdgeRef {
+ return { from: { sourceId: e.from_source_id, slug: e.from_slug }, to: { sourceId: e.to_source_id, slug: e.to_slug }, linkType: e.link_type };
+}
+
+/**
+ * GST-2957: stored link contexts as a caller whose fact reads are world-only (worldOnlyFacts) may read them. A context
+ * written by a body producer is an excerpt of the body of the link's origin page (its from page when it has none), so a
+ * reference in or near a facts or takes fence carries fence row text, private and held rows included, and a body edit
+ * can drop the fence while the link keeps the old excerpt. Each returned context is matched to its stored link rows
+ * (`edge(row)`, the same text or a read's truncation of it); the caller keeps it when one of them was supplied by a writer
+ * (add_link provenances, frontmatter fields) and holds no fence marker (unify-types' preserve_notes stores a page's
+ * opening as a manual context), or reads, whitespace-collapsed as the extractor collapses it, inside its origin page as
+ * it is now and as get_page shows it to the caller (sanitizeRemoteBody less heldRowsForCaller). The origin bodies are
+ * read in one query, for at most LINK_CONTEXT_PAGE_BOUND pages in result order. Otherwise it is emptied, as it is when
+ * no stored row matches, the page is past the bound, stored in segments or gone, or a lookup fails (fail closed).
+ * Every other caller reads contexts as stored and costs no query.
+ */
+export async function worldLinkContexts<T extends { context?: string | null }>(
+ engine: Pick<BrainEngine, 'executeRaw'>, remote: boolean | undefined, rows: T[], edge: (row: T) => StoredEdgeRef,
+): Promise<T[]> {
+ if (!worldOnlyFacts(remote)) return rows;
+ const asked = rows.flatMap((row, i) => (row.context ? [{ i, ref: edge(row), context: row.context }] : []));
+ if (asked.length === 0) return rows;
+ const kept = new Set<number>();
+ try {
+ const matches = await engine.executeRaw<{ i: number; link_source: string | null; context: string; page_id: number | null }>(
+ `SELECT u.i, l.link_source, l.context, e.id AS page_id
+ FROM unnest($1::int[], $2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[]) AS u(i, fs, fslug, ts, tslug, lt, ctx)
+ JOIN pages f ON f.source_id = u.fs AND f.slug = u.fslug
+ JOIN pages t ON t.source_id = u.ts AND t.slug = u.tslug
+ JOIN links l ON l.from_page_id = f.id AND l.to_page_id = t.id AND l.link_type = u.lt
+ AND (l.context = u.ctx OR (right(u.ctx, 1) = '…' AND left(l.context, char_length(u.ctx) - 1) = left(u.ctx, char_length(u.ctx) - 1)))
+ LEFT JOIN pages e ON e.id = COALESCE(l.origin_page_id, l.from_page_id) AND e.deleted_at IS NULL`,
+ [asked.map(a => a.i), asked.map(a => a.ref.from.sourceId), asked.map(a => a.ref.from.slug), asked.map(a => a.ref.to.sourceId),
+ asked.map(a => a.ref.to.slug), asked.map(a => a.ref.linkType), asked.map(a => a.context)]);
+ const excerpted = matches.filter(m => m.link_source == null || BODY_EXCERPT_LINK_SOURCES.includes(m.link_source)).sort((a, b) => Number(a.i) - Number(b.i));
+ for (const m of matches) if (!excerpted.includes(m) && !holdsFenceMarker(m.context)) kept.add(Number(m.i));
+ const pageIds = [...new Set(excerpted.flatMap(m => (m.page_id == null ? [] : [Number(m.page_id)])))].slice(0, LINK_CONTEXT_PAGE_BOUND);
+ const pages = pageIds.length ? await engine.executeRaw<{ id: number; source_id: string; slug: string; compiled_truth: string | null; timeline: string | null }>(
+ `SELECT id, source_id, slug, compiled_truth, timeline FROM pages
+ WHERE id = ANY($1::bigint[]) AND body_storage IS DISTINCT FROM 'segmented'`, [pageIds]) : [];
+ const views = new Map<number, string>();
+ for (const p of pages) {
+ const compiled = p.compiled_truth ?? '';
+ const omitRows = holdsFenceMarker(compiled + (p.timeline ?? ''))
+ ? await heldRowsForCaller(engine, remote, { sourceId: p.source_id, slug: p.slug, compiled_truth: compiled, timeline: p.timeline })
+ : undefined;
+ const shown = sanitizeRemoteBody(compiled, { omitRows }) + '\n' + sanitizeRemoteBody(p.timeline ?? '', { omitRows });
+ views.set(Number(p.id), ensureWellFormed(maskLinksFence(shown)).replace(/\s+/g, ' '));
+ }
+ for (const m of excerpted) if (m.page_id != null && views.get(Number(m.page_id))?.includes(m.context)) kept.add(Number(m.i));
+ } catch {
+ kept.clear();
+ }
+ return rows.map((row, i) => (!row.context || kept.has(i) ? row : { ...row, context: '' }));
+}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 62bf3e6002..3be423d7d1 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -797,7 +797,7 @@ const context_pack: Operation = {
// `default` plus this source, inside the caller's grant; it packs first.
const { loadCoreBlock } = await import('../core-memory.ts');
const allowed = named ? [sourceId] : ctx.auth?.allowedSources?.length ? ctx.auth.allowedSources : null;
- const core = await loadCoreBlock(ctx.engine, { sessionSourceId: sourceId, allowedSources: allowed, excludePrivate: !includePrivate, forCaller: true, eligibility })
+ const core = await loadCoreBlock(ctx.engine, { sessionSourceId: sourceId, allowedSources: allowed, excludePrivate: !includePrivate, forCaller: true, eligibility, remote: ctx.remote })
.catch(() => null);
const coreText = core?.text ?? '';
const coreTokens = estimateTokens(coreText);
@@ -1233,7 +1233,7 @@ const delta: Operation = {
// structured arrays reflect — the assembler's render predates both.
let text = renderDelta(pages, facts, threads, effectiveSince);
const diff = p.beliefs === true ? await (await import('../belief/changes.ts')).deltaBeliefs(ctx.engine, { sourceId, since: effectiveSince, until: horizon,
- remote: !includePrivate, takesHolders: readHolders(ctx), entities: parseEntityList(p.entities) }, budgetTokens !== null ? beliefBudget : null, text, TURN_CONTEXT_ENVELOPE) : null;
+ remote: !includePrivate, worldOnly: (await import('../search/private-visibility.ts')).worldOnlyFacts(ctx.remote), takesHolders: readHolders(ctx), entities: parseEntityList(p.entities) }, budgetTokens !== null ? beliefBudget : null, text, TURN_CONTEXT_ENVELOPE) : null;
if (diff) text = diff.text;
const budgetUsed = budgetTokens !== null ? estimateTokens(text) : undefined;
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index ec24106d9a..44a00b3f29 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -17,7 +17,8 @@ import { cutLinkPage, finishLinkPage, linkId, parseLinkListing, reportLinkPage }
import { opError, type Operation } from './contract.ts';
import type { Action } from '../agent-output.ts';
-import { presentEdgeContext, resolveChainAnchors, runRelationalChain, validateChainHops, type ChainEvidenceEdge, type ChainPlan } from '../search/relational-chain.ts';
+import { chainStoredEdge, presentEdgeContext, resolveChainAnchors, runRelationalChain, validateChainHops, type ChainEvidenceEdge, type ChainPlan } from '../search/relational-chain.ts';
+import { storedEdge, worldLinkContexts } from '../eligibility/fence-overlay.ts';
import { invalidParam, paramUse, readFix } from './op-fix.ts';
import {
assertExplicitSourceLive,
@@ -370,7 +371,8 @@ async function readLinkEdges(
} while ((listing.all || kept.length === 0) && nextId !== undefined);
reportTemporal(ctx, opName, p, temporal, hidden);
if (kept.length === 0 && hidden === 0 && listing.afterId === undefined && !fromType) await hintScopedLinkMiss(ctx, p, requested, policy, direction);
- return { links: kept, nextCursor: reportLinkPage(ctx, opName, p, listing, { returned: kept.length, nextId }) };
+ const links = await worldLinkContexts(ctx.engine, ctx.remote, kept, storedEdge);
+ return { links, nextCursor: reportLinkPage(ctx, opName, p, listing, { returned: kept.length, nextId }) };
}
/**
@@ -530,6 +532,9 @@ async function traverseChain(ctx: OperationContext, p: Record<string, unknown>,
const remote = ctx.remote !== false;
const edge = (e: ChainEvidenceEdge) => ({ ...e, context: presentEdgeContext(e.context, remote) });
const answers = rows.filter(r => r.role === 'answer');
+ const contexts = (await worldLinkContexts(ctx.engine, ctx.remote,
+ answers.flatMap(r => r.best_path.edges.map(e => ({ ...e, source_id: r.source_id }))), chainStoredEdge)).map(e => e.context);
+ let next = 0;
const rawHops = p.hops as Array<Record<string, unknown>>;
const status = diagnostics.status;
const fix = chainFix(slug, status, rawHops, readScopeArgs(p), diagnostics.empty_hop);
@@ -538,7 +543,7 @@ async function traverseChain(ctx: OperationContext, p: Record<string, unknown>,
return {
anchor: slug,
answers: answers.map(r => ({ slug: r.slug, source_id: r.source_id, path_count: r.path_count, score: r.score })),
- paths: answers.map(r => ({ nodes: r.best_path.nodes, edges: r.best_path.edges.map(edge) })),
+ paths: answers.map(r => ({ nodes: r.best_path.nodes, edges: r.best_path.edges.map(e => edge({ ...e, context: contexts[next++] ?? null })) })),
diagnostics,
...(ignored.length ? { set_aside: { ignored, note: `Walked the hops chain; ignored ${ignored.length > 1 ? `${ignored.slice(0, -1).join(', ')} and ${ignored[ignored.length - 1]}` : ignored[0]}: each hop names its link type and direction (toward), and the chain length is the number of hops.` } } : {}),
};
@@ -645,7 +650,7 @@ const traverse_graph: Operation = {
}) : undefined;
ctx.emitNotice?.({ code: 'graph_walk_truncated', kind: 'degraded', why, ...(fix ? { fix } : {}) });
}
- return paths;
+ return worldLinkContexts(ctx.engine, ctx.remote, paths, storedEdge);
},
scope: 'read',
cliHints: { name: 'graph', positional: ['slug'] },
diff --git a/src/core/schema-pack/page-to-link.ts b/src/core/schema-pack/page-to-link.ts
index 5adb9c4944..bd8611ccc1 100644
--- a/src/core/schema-pack/page-to-link.ts
+++ b/src/core/schema-pack/page-to-link.ts
@@ -25,6 +25,8 @@
import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import type { OperationContext } from '../operations.ts';
import { parseMarkdown } from '../markdown.ts';
+import { stripFactsFence } from '../facts-fence.ts';
+import { stripTakesFence } from '../takes-fence.ts';
import { loadActivePackBestEffort } from './best-effort.ts';
import type { PackResolverSpec } from './manifest-v1.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
@@ -197,7 +199,7 @@ export async function runPageToLinkCore(
from_slug: sourceSlug,
to_slug: targetSlug,
link_type: rule.link_type,
- context: rule.preserve_notes ? r.compiled_truth.slice(0, 240) : undefined,
+ context: rule.preserve_notes ? stripTakesFence(stripFactsFence(r.compiled_truth)).slice(0, 240) : undefined,
link_source: 'manual',
from_source_id: sourceId ?? 'default',
to_source_id: sourceId ?? 'default',
diff --git a/src/core/search/relational-chain.ts b/src/core/search/relational-chain.ts
index fbc7fd464a..326c8144f5 100644
--- a/src/core/search/relational-chain.ts
+++ b/src/core/search/relational-chain.ts
@@ -27,6 +27,7 @@ import type { EdgeStatusFilter, EdgeTemporalOpts } from '../link-validity.ts';
import { hubWeight } from './hub-dampening.ts';
import { pageReadFilter } from './read-policy-sql.ts';
import { sanitizeRemoteBody } from '../remote-body.ts';
+import type { StoredEdgeRef } from '../eligibility/fence-overlay.ts';
/** Page-type signature of each chain relation: subject types → object types. */
export const LINK_SIGNATURES: Readonly<Record<string, { subject: readonly string[]; object: readonly string[] }>> = {
@@ -329,6 +330,11 @@ export async function resolveChainAnchors(
return rows.map(r => ({ page_id: Number(r.id), slug, source_id: r.source_id }));
}
+/** The stored link (from, to, type) behind a chain evidence edge; a chain stays in the source its path walked. */
+export function chainStoredEdge(e: ChainEvidenceEdge & { source_id: string }): StoredEdgeRef {
+ return { from: { sourceId: e.source_id, slug: e.stored_from }, to: { sourceId: e.source_id, slug: e.stored_to }, linkType: e.link_type };
+}
+
/** Longest edge context shown to an untrusted caller. */
export const REMOTE_EDGE_CONTEXT_CHARS = 160;
diff --git a/src/core/search/relational-recall.ts b/src/core/search/relational-recall.ts
index 7dbc8b08d1..236976879c 100644
--- a/src/core/search/relational-recall.ts
+++ b/src/core/search/relational-recall.ts
@@ -38,7 +38,8 @@ import { parseRelationalQuery, type RelationalQuery, type RelationVocab } from '
import { edgeValidityEnabled, type EdgeTemporalOpts } from '../link-validity.ts';
import { stampEvidence, type EvidenceOpts } from './evidence.ts';
import { parseRelationalPlan } from './relational-plan.ts';
-import { LINK_SIGNATURES, presentEdgeContext, resolveChainAnchors, runRelationalChain, type ChainAnchor, type ChainDiagnostics, type ChainStatus, type RelationalChainRow } from './relational-chain.ts';
+import { chainStoredEdge, LINK_SIGNATURES, presentEdgeContext, resolveChainAnchors, runRelationalChain, type ChainAnchor, type ChainDiagnostics, type ChainStatus, type RelationalChainRow } from './relational-chain.ts';
+import { worldLinkContexts } from '../eligibility/fence-overlay.ts';
import { requiresSafeChunks } from './safe-chunks.ts';
export interface RelationalArmOpts extends PageReadPolicy {
@@ -533,13 +534,17 @@ async function hydrateChain(
const hydrated = await hydrate(engine, fanoutShaped, seed, opts);
const remote = requiresSafeChunks(opts);
const byKey = new Map(picked.map(r => [`${r.source_id}:${r.slug}`, r] as const));
- return hydrated.map(h => {
- const r = byKey.get(`${h.source_id}:${h.slug}`)!;
+ const shown = hydrated.map(h => byKey.get(`${h.source_id}:${h.slug}`)!);
+ const contexts = (await worldLinkContexts(engine, remote,
+ shown.flatMap(r => r.best_path.edges.slice(-3).map(e => ({ ...e, source_id: r.source_id }))), chainStoredEdge)).map(e => e.context);
+ let next = 0;
+ return hydrated.map((h, i) => {
+ const r = shown[i]!;
return {
...h,
relational: {
role: r.role, seed, hop: r.hop, path_count: r.path_count,
- edges: r.best_path.edges.slice(-3).map(e => ({ ...e, context: presentEdgeContext(e.context, remote) })),
+ edges: r.best_path.edges.slice(-3).map(e => ({ ...e, context: presentEdgeContext(contexts[next++] ?? null, remote) })),
},
};
});
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 034c5a914e..fded6de37c 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -27,6 +27,7 @@ import type { ReadEligibility } from '../eligibility/policy.ts';
import { trustFields } from '../eligibility/labels.ts';
import { isQuarantined } from '../quarantine.ts';
import { loadPageTrust } from '../eligibility/stamp.ts';
+import { storedEdge, worldLinkContexts } from '../eligibility/fence-overlay.ts';
import { projectionEligibleSql } from '../eligibility/sql.ts';
import { loadRelationshipNotes, relationshipNoteKey } from '../link-relationship-notes.ts';
import { normalizeAlias } from '../search/alias-normalize.ts';
@@ -205,6 +206,11 @@ export interface EntityCardResult {
export interface EntityCardOpts {
remote: boolean;
+ /**
+ * GST-2957: the reader's OperationContext.remote, for the edges' stored link contexts (worldLinkContexts). context_pack
+ * builds cards with `remote` set for any caller without include_private; absent, `remote` stands for it.
+ */
+ readerRemote?: boolean;
/**
* #6723: the sources to resolve the name in, probed in this order (home
* first); the first source with a hit owns the card and every read behind
@@ -500,7 +506,7 @@ export async function buildEntityCard(
}
const { row, runnersUp, match } = selected;
- const { card, facts: factRows } = await assembleCard(engine, hitSource, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {});
+ const { card, facts: factRows } = await assembleCard(engine, hitSource, row, opts.remote, scope.excludePrivate, opts.eligibility ?? {}, opts.readerRemote ?? opts.remote);
if (match) card.match = match;
if (opts.includeReferences) {
Object.assign(card, await cardReferences(engine, hitSource, row, opts, scope.excludePrivate, scope.entityTypes),
@@ -579,6 +585,7 @@ async function assembleCard(
remote: boolean,
excludePrivate: boolean,
eligibility: ReadEligibility,
+ readerRemote: boolean,
): Promise<{ card: EntityCard; facts: FactRow[] }> {
const pageSlug = row.slug;
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
@@ -675,10 +682,11 @@ async function assembleCard(
...(last ? { since: last.from, until: last.until } : {}),
};
};
- const outCandidates = (outLinks as Array<Link & Partial<TemporalAnnotation>>)
- .filter(l => l.link_source !== 'mentions')
+ const outCandidates = (await worldLinkContexts(engine, readerRemote, (outLinks as Array<Link & Partial<TemporalAnnotation>>)
+ .filter(l => l.link_source !== 'mentions'), storedEdge))
.map(l => edgeOf(l, 'out', l.to_slug));
- const inCandidates = inEdges.map(l => edgeOf(l as typeof l & Partial<TemporalAnnotation>, 'in', l.from_slug));
+ const inCandidates = (await worldLinkContexts(engine, readerRemote, inEdges, l => ({ from: { sourceId, slug: l.from_slug }, to: { sourceId, slug: pageSlug }, linkType: l.link_type })))
+ .map(l => edgeOf(l as typeof l & Partial<TemporalAnnotation>, 'in', l.from_slug));
const edges: EntityCardEdge[] = [
...[...outCandidates].sort((a, b) => rank(a) - rank(b)),
...[...inCandidates].sort((a, b) => rank(a) - rank(b)),
diff --git a/test/delta-beliefs-link-context-2957.test.ts b/test/delta-beliefs-link-context-2957.test.ts
new file mode 100644
index 0000000000..5203fe11de
--- /dev/null
+++ b/test/delta-beliefs-link-context-2957.test.ts
@@ -0,0 +1,36 @@
+/**
+ * GST-2957: delta {beliefs: true} carries each changed link's stored context, an excerpt of a page body that can hold
+ * private facts-fence rows. A remote caller whose fact reads are world-only gets the link change without that text; the
+ * local CLI still reads it. PGLite, and Postgres when DATABASE_URL is set. Synthetic data only.
+ */
+import { describe, expect, test } from 'bun:test';
+import { operationsByName } from '../src/core/operations.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { beliefBrain, beliefEngineCase, beliefPage, type BeliefBrain } from './helpers/belief-ledger.ts';
+
+const CANARY = 'falconbeliefprivcanary';
+const slug = 'companies/acme-example';
+const pause = () => new Promise(resolve => setTimeout(resolve, 25));
+const at = async (b: BeliefBrain) => { await pause(); const t = new Date((await b.engine.executeRaw<{ t: string }>('SELECT clock_timestamp() AS t'))[0]!.t).toISOString(); await pause(); return t; };
+
+for (const engineCase of testBackends().map(beliefEngineCase)) {
+ describe('GST-2957 delta beliefs link context (' + engineCase.name + ')', () => {
+ test('a world-only remote caller gets the link change without its stored context; the local CLI keeps it', () => beliefBrain(async b => {
+ await b.put('companies/widget-co', beliefPage({ title: 'Widget' }));
+ await b.put(slug, beliefPage({ facts: ['Acme sells widgets'] }));
+ const t0 = await at(b);
+ await b.put(slug, beliefPage({ facts: [{ claim: 'Acme owes [[companies/widget-co]] money ' + CANARY, visibility: 'private' }, 'Acme sells widgets'] }));
+ await pause(); await pause();
+ await new Promise(r => setTimeout(r, 2_500));
+ const delta = (remote: boolean) => operationsByName.delta!.handler({ ...b.ctx, remote, ...(remote ? { auth: { clientId: 'gst2957-remote', scopes: ['read'] } } : {}) } as never,
+ { since: t0, beliefs: true }) as Promise<Record<string, any>>;
+ const local = await delta(false);
+ const links = (r: Record<string, any>) => r.beliefs.changes.filter((c: { kind: string }) => c.kind === 'link');
+ expect(links(local).length).toBeGreaterThan(0);
+ expect(JSON.stringify(links(local))).toContain(CANARY);
+ const remote = await delta(true);
+ expect(links(remote).map((c: { subject: unknown }) => c.subject)).toEqual(links(local).map((c: { subject: unknown }) => c.subject));
+ expect(JSON.stringify(remote)).not.toContain(CANARY);
+ }, { managed: true, databaseUrl: engineCase.databaseUrl }), 120_000);
+ });
+}
diff --git a/test/link-context-world-rows-2957.test.ts b/test/link-context-world-rows-2957.test.ts
new file mode 100644
index 0000000000..5497cdf67d
--- /dev/null
+++ b/test/link-context-world-rows-2957.test.ts
@@ -0,0 +1,277 @@
+/**
+ * GST-2957: a stored link context is an excerpt of the from page's body, so a reference in or next to a facts fence
+ * carries fence row text, private rows and held rows (a world cell whose fact is stored narrower) included. Every
+ * reader that hands a context to a remote caller whose fact reads are world-only (worldOnlyFacts) must leave that text
+ * out: get_backlinks, get_links, traverse_graph (walk and hops), entity and context_pack's cards. context_pack's core
+ * block must leave held rows out for the same caller. The owner's remote callers and the local CLI keep what they read
+ * before. Each read runs through MCP dispatch as the caller, on PGLite, and on Postgres when DATABASE_URL is set.
+ * Synthetic data only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { bindCredential } from '../src/core/access/members.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { renderTakesFence } from '../src/core/takes-fence.ts';
+import { LINK_CONTEXT_PAGE_BOUND } from '../src/core/eligibility/fence-overlay.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+
+const row = (n: number, claim: string, visibility = 'world') => ({ rowNum: n, claim, kind: 'fact', confidence: 1, visibility, notability: 'medium', active: true });
+const page = (type: string, title: string, rows: ReturnType<typeof row>[], fm = '') =>
+ '---\ntype: ' + type + '\ntitle: ' + title + '\n' + fm + '---\n# ' + title + '\n\nProfile.\n\n## Facts\n\n' + renderFactsTable(rows as never) + '\n';
+
+const TARGET = 'people/target-example';
+const THIRD = 'people/third-example';
+const ACME = 'companies/acme-example';
+const LIA = 'people/lia-example';
+const PLAIN = 'notes/plain-example';
+const KIM = 'people/kim-example';
+const MEET = 'meetings/standup-example';
+const CORE = 'notes/core-example';
+/** Fence rows on LIA: a private row and a held row, each naming another page. */
+const PRIV = 'pelicanprivcanary';
+const HELD = 'wombatheldcanary';
+/** Fence rows on a core page with no links: they reach a reader only through the core block. */
+const CORE_PRIV = 'heronprivcorecanary';
+const CORE_HELD = 'badgerheldcorecanary';
+/** A private row on a meeting page naming an attendee: the attendance edge is stored from the attendee, its context cut from the meeting. */
+const MEET_PRIV = 'lynxmeetprivcanary';
+/** A context a writer gave add_link on a page with a fence. */
+const MANUAL = 'quailmanualnote';
+/** A context outside any fence, which every caller keeps. */
+const PROSE = 'otterplainprose';
+const HOPS = [{ link_type: 'works_at', toward: 'object' }];
+/** A private row on a page whose fence a body-only edit later dropped without extracting its links again. */
+const STALE = 'people/stale-example';
+const STALE_PRIV = 'ospreystaleprivcanary';
+/** A takes row inside the first 240 characters of a page, stored as a manual context the way preserve_notes stored it. */
+const NOTE_PRIV = 'grebenoteprivcanary';
+const NOTE_CONTEXT = ('Partner note.\n\n' + renderTakesFence([{ rowNum: 1, claim: 'Deal is risky ' + NOTE_PRIV, kind: 'take', holder: 'brain', weight: 0.5, active: true }] as never)).slice(0, 240);
+/** A page with more backlinks, each from its own page, than one read of origin bodies carries. */
+const HUB = 'notes/hub-example';
+const SPOKES = LINK_CONTEXT_PAGE_BOUND + 5;
+const SPOKE_PROSE = 'spokeprosecontext';
+/** A typed chain whose first edge keeps an excerpt the anchor page no longer holds (its fence was dropped since extraction). */
+const CH_ANCHOR = 'people/chainanchor-example';
+const CH_CO = 'companies/chainco-example';
+const CH_FOUNDER = 'people/chainfounder-example';
+const CHAIN_PRIV = 'kitestalechaincanary';
+const CHAIN_Q = 'Who founded the companies that Chainanchor Example invested in?';
+const CHAIN_HOPS = [{ link_type: 'invested_in', toward: 'object' }];
+const LINK_MATCH_SQL = 'AS u(i, fs, fslug, ts, tslug, lt, ctx)';
+const ORIGIN_BODY_SQL = 'SELECT id, source_id, slug, compiled_truth, timeline FROM pages';
+
+for (const kind of testBackends()) {
+ describe('GST-2957 stored link context and the core block for world-only callers (' + kind + ')', () => {
+ let engine: BrainEngine; let close: () => Promise<void>;
+ const tokens: Record<string, string> = {};
+ const provider = () => new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ async function call(who: string, op: string, params: Record<string, unknown>): Promise<string> {
+ __resetPrivateVisibilityCacheForTests();
+ let out;
+ if (who === 'local') out = await dispatchToolCall(engine, op, { ...params }, { remote: false, sourceId: 'default' });
+ else {
+ const auth = await provider().verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ out = await dispatchToolCall(engine, op, { ...params }, { remote: true, transport: 'http', auth, sourceId: auth.sourceId ?? 'default', takesHoldersAllowList: ['world'] });
+ }
+ const text = out.content.map(c => c.text).join('\n');
+ expect(out.isError, who + ' ' + op + ': ' + text.slice(0, 300)).toBeFalsy();
+ return text;
+ }
+ const put = (slug: string, content: string) => call('local', 'put_page', { slug, content, request_id: randomUUID() });
+ const holdRow = (canary: string) => engine.transaction(tx => withCoordinatedWrite(tx, ['default'],
+ () => tx.executeRaw("UPDATE facts SET visibility = 'private' WHERE fact LIKE '%' || $1 || '%'", [canary]), TEST_WRITE_ATTRIBUTION));
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({ engine: 'pglite' } as never); await engine.initSchema(); close = () => engine.disconnect(); }
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await registerLocalWriter(engine, 'cli');
+ for (const [slug, title] of [[TARGET, 'Target Example'], [THIRD, 'Third Example']]) await put(slug, page('person', title, [row(1, title + ' likes tea')]));
+ await put(ACME, page('company', 'Acme Example', [row(1, 'Acme makes widgets')]));
+ await put(LIA, page('person', 'Lia Example', [
+ row(1, 'Lia owes [[' + TARGET + ']] money ' + PRIV, 'private'),
+ row(2, 'Lia works at [[' + ACME + ']] as an engineer'),
+ row(3, 'Lia dated [[' + THIRD + ']] ' + HELD),
+ ]));
+ await put(KIM, '---\ntype: person\ntitle: Kim Example\n---\n# Kim Example\n\nProfile.\n');
+ await put(MEET, '---\ntype: meeting\ntitle: Standup Example\ndate: 2026-01-01\n---\n# Standup Example\n\n## Facts\n\n'
+ + renderFactsTable([row(1, 'The standup ran long'), row(2, 'Budget raised ' + MEET_PRIV, 'private')] as never) + '\n\n## Attendees\n\n- [[' + KIM + ']]\n');
+ await call('local', 'add_link', { from: LIA, to: THIRD, link_type: 'related_to', context: 'Met through a ' + MANUAL, request_id: randomUUID() });
+ await put(PLAIN, '---\ntype: note\ntitle: Plain\n---\n# Plain\n\nThe ' + PROSE + ' memo mentions [[' + TARGET + ']] in passing.\n');
+ await put(STALE, page('person', 'Stale Example', [row(1, 'Stale owes [[' + TARGET + ']] rent ' + STALE_PRIV, 'private')]));
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(
+ "UPDATE pages SET compiled_truth = '# Stale Example\n\nProfile rewritten.\n' WHERE slug = $1", [STALE]), TEST_WRITE_ATTRIBUTION));
+ await call('local', 'add_link', { from: THIRD, to: ACME, link_type: 'related_to', context: NOTE_CONTEXT, request_id: randomUUID() });
+ await put(CH_ANCHOR, '---\ntype: person\ntitle: Chainanchor Example\n---\n# Chainanchor Example\n\nA seed investor.\n');
+ await put(CH_CO, '---\ntype: company\ntitle: Chainco Example\n---\n# Chainco Example\n\nA payments company founded by Chainfounder.\n');
+ await put(CH_FOUNDER, '---\ntype: person\ntitle: Chainfounder Example\n---\n# Chainfounder Example\n\nBuilds payment rails.\n');
+ await engine.addLink(CH_ANCHOR, CH_CO, 'Chainanchor invested in [[' + CH_CO + ']] ' + CHAIN_PRIV + ' at the seed round', 'invested_in', 'markdown');
+ await engine.addLink(CH_CO, CH_FOUNDER, 'founded by Chainfounder', 'founded', 'markdown');
+ await engine.setConfig('search.relational_planner', 'true');
+ await put(HUB, '---\ntype: note\ntitle: Hub\n---\n# Hub\n');
+ const spokes = Array.from({ length: SPOKES }, (_, n) => ({ slug: 'notes/spoke-' + String(n).padStart(3, '0'), text: 'Spoke ' + n + ' cites the hub ' + SPOKE_PROSE + '.' }));
+ for (const s of spokes) await engine.putPage(s.slug, { title: s.slug, type: 'note' as never, compiled_truth: s.text, timeline: '', frontmatter: {}, source_path: s.slug + '.md' });
+ await engine.addLinksBatch(spokes.map(s => ({ from_slug: s.slug, to_slug: HUB, link_type: 'mentions', context: s.text,
+ link_source: 'markdown', from_source_id: 'default', to_source_id: 'default' })) as never);
+ await put(CORE, page('note', 'Core Example', [row(1, 'Core detail ' + CORE_PRIV, 'private'), row(2, 'Core detail ' + CORE_HELD), row(3, 'Core detail public')], 'always_load: true\n'));
+ // Held: a world cell whose stored fact is narrower, the state an unaccepted widening leaves (GST-2891).
+ await holdRow(HELD);
+ await holdRow(CORE_HELD);
+ await engine.setConfig('memory.core.enabled', 'true');
+ for (const id of ['owner-example', 'bob-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1)', [id]);
+ const mint = async (name: string, member?: string) => {
+ const m = await mintLegacyToken(engine, { name, scopes: ['read'], takesHolders: ['world'] });
+ tokens[name] = m.token;
+ if (member) await bindCredential(engine, { kind: 'token', id: m.id }, { member }); else await readsUnscopedOnPurpose(engine, m.id);
+ };
+ await mint('owner', 'owner-example'); await mint('bob', 'bob-example'); await mint('unbound');
+ await setOwner(engine, 'owner-example');
+ }, 300_000);
+ afterAll(async () => { await disposePersistenceConsumer(engine); await close?.(); }, 60_000);
+
+ const linkReads: Array<[string, string, Record<string, unknown>]> = [
+ ['get_backlinks', 'get_backlinks', { slug: TARGET }],
+ ['get_backlinks third', 'get_backlinks', { slug: THIRD }],
+ ['get_backlinks acme', 'get_backlinks', { slug: ACME }],
+ ['get_links', 'get_links', { slug: LIA }],
+ ['traverse_graph', 'traverse_graph', { slug: LIA, depth: 1 }],
+ ['traverse_graph in', 'traverse_graph', { slug: TARGET, depth: 1, direction: 'in' }],
+ ['traverse_graph hops', 'traverse_graph', { slug: LIA, hops: HOPS }],
+ ['entity', 'entity', { name: LIA }],
+ ['entity target', 'entity', { name: TARGET }],
+ ['context_pack', 'context_pack', { entities: LIA }],
+ ['get_links attendee', 'get_links', { slug: KIM }],
+ ['get_backlinks meeting', 'get_backlinks', { slug: MEET }],
+ ['traverse_graph attendee', 'traverse_graph', { slug: KIM, depth: 1 }],
+ ['entity attendee', 'entity', { name: KIM }],
+ ['entity meeting', 'entity', { name: MEET }],
+ ['traverse_graph stale hop', 'traverse_graph', { slug: CH_ANCHOR, hops: CHAIN_HOPS }],
+ ['search relational chain', 'search', { query: CHAIN_Q }],
+ ];
+
+ test('the fixture stores the private and held rows inside link contexts', async () => {
+ const contexts = (await engine.executeRaw<{ context: string }>('SELECT context FROM links')).map(r => r.context).join('\n');
+ expect(contexts).toContain(PRIV);
+ expect(contexts).toContain(HELD);
+ for (const canary of [STALE_PRIV, NOTE_PRIV]) expect(contexts).toContain(canary);
+ // The extractor stores a body link with no origin page: each reader's leak case is such a row, read against its from page.
+ const noOrigin = (await engine.executeRaw<{ context: string }>("SELECT context FROM links WHERE origin_page_id IS NULL AND link_source = 'markdown'")).map(r => r.context).join('\n');
+ for (const canary of [PRIV, HELD, STALE_PRIV, CHAIN_PRIV]) expect(noOrigin).toContain(canary);
+ expect(NOTE_CONTEXT).toContain('<!--- gbrain:takes:begin -->');
+ const stale = await engine.executeRaw<{ compiled_truth: string }>('SELECT compiled_truth FROM pages WHERE slug = $1', [STALE]);
+ expect(stale[0]!.compiled_truth).not.toContain('gbrain:facts');
+ const attendance = await engine.executeRaw<{ context: string }>(
+ 'SELECT l.context FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages o ON o.id = l.origin_page_id WHERE f.slug = $1 AND o.slug = $2', [KIM, MEET]);
+ expect(attendance.map(r => r.context).join('\n')).toContain(MEET_PRIV);
+ const hop = JSON.parse(await call('local', 'traverse_graph', { slug: LIA, hops: HOPS }));
+ expect(hop.answers.map((a: { slug: string }) => a.slug)).toEqual([ACME]);
+ }, 60_000);
+
+ test('a world-only remote caller reads no private or held row text through a stored link context', async () => {
+ const leaks: string[] = [];
+ for (const who of ['bob', 'unbound']) for (const [label, op, params] of linkReads) {
+ const text = await call(who, op, params);
+ for (const canary of [PRIV, HELD, MEET_PRIV, STALE_PRIV, NOTE_PRIV, CHAIN_PRIV]) if (text.includes(canary)) leaks.push(who + ' ' + label + ' ' + canary);
+ }
+ expect(leaks).toEqual([]);
+ }, 120_000);
+
+ test("context_pack's core block leaves held rows out for a world-only remote caller", async () => {
+ for (const who of ['bob', 'unbound']) {
+ const text = await call(who, 'context_pack', { entities: TARGET });
+ expect(text).toContain('Core detail public');
+ expect(text).not.toContain(CORE_PRIV);
+ expect(text).not.toContain(CORE_HELD);
+ }
+ }, 60_000);
+
+ test('a context outside any fence, or one a writer gave add_link, still reaches a world-only remote caller', async () => {
+ for (const who of ['bob', 'unbound']) {
+ expect(await call(who, 'get_links', { slug: LIA })).toContain(MANUAL);
+ expect(await call(who, 'traverse_graph', { slug: LIA, depth: 1 })).toContain(MANUAL);
+ expect(await call(who, 'get_backlinks', { slug: TARGET })).toContain(PROSE);
+ expect(await call(who, 'entity', { name: TARGET })).toContain(PROSE);
+ }
+ }, 60_000);
+
+ test("the owner's remote caller and the local CLI still read the private and held rows' context", async () => {
+ for (const who of ['owner', 'local']) {
+ expect(await call(who, 'get_backlinks', { slug: TARGET })).toContain(PRIV);
+ expect(await call(who, 'get_backlinks', { slug: THIRD })).toContain(HELD);
+ const links = await call(who, 'get_links', { slug: LIA });
+ for (const canary of [PRIV, HELD]) expect(links).toContain(canary);
+ expect(await call(who, 'entity', { name: LIA })).toContain(PRIV);
+ expect(await call(who, 'get_links', { slug: KIM })).toContain(MEET_PRIV);
+ expect(await call(who, 'get_backlinks', { slug: TARGET })).toContain(STALE_PRIV);
+ expect(await call(who, 'get_links', { slug: THIRD })).toContain(NOTE_PRIV);
+ expect(await call(who, 'traverse_graph', { slug: CH_ANCHOR, hops: CHAIN_HOPS })).toContain(CHAIN_PRIV);
+ expect(await call(who, 'search', { query: CHAIN_Q })).toContain(CHAIN_PRIV);
+ const pack = await call(who, 'context_pack', { entities: LIA });
+ for (const canary of [PRIV, HELD, CORE_HELD]) expect(pack).toContain(canary);
+ }
+ for (const who of ['bob', 'unbound']) {
+ expect(await call(who, 'traverse_graph', { slug: CH_ANCHOR, hops: CHAIN_HOPS })).toContain(CH_CO);
+ expect(await call(who, 'search', { query: CHAIN_Q })).toContain('founded by Chainfounder');
+ }
+ const walk = await call('owner', 'traverse_graph', { slug: LIA, depth: 1 });
+ for (const canary of [PRIV, HELD]) expect(walk).toContain(canary);
+ }, 120_000);
+
+ test('origin bodies are read once for at most LINK_CONTEXT_PAGE_BOUND pages; owner and local reads run no extra query and return contexts as stored', async () => {
+ const sql: string[] = [];
+ const executeRaw = engine.executeRaw;
+ engine.executeRaw = function (this: BrainEngine, q: string, p?: unknown[]) { sql.push(q); return executeRaw.call(this, q, p as never); } as typeof engine.executeRaw;
+ const read = async (who: string, slug: string) => {
+ sql.length = 0;
+ const rows = JSON.parse(await call(who, 'get_backlinks', { slug })) as Array<{ from_slug: string; context: string }>;
+ return { rows, match: sql.filter(q => q.includes(LINK_MATCH_SQL)).length, bodies: sql.filter(q => q.includes(ORIGIN_BODY_SQL)).length };
+ };
+ try {
+ const stored = await executeRaw.call(engine,
+ 'SELECT f.slug AS from_slug, l.context FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id WHERE t.slug = $1', [TARGET]) as Array<{ from_slug: string; context: string }>;
+ const pairs = (rows: Array<{ from_slug: string; context: string }>) => rows.map(r => r.from_slug + ' ' + r.context).sort();
+ for (const who of ['owner', 'local']) {
+ const hub = await read(who, HUB);
+ expect({ match: hub.match, bodies: hub.bodies }).toEqual({ match: 0, bodies: 0 });
+ expect(hub.rows.filter(r => r.context.includes(SPOKE_PROSE)).length).toBe(SPOKES);
+ const target = await read(who, TARGET);
+ expect({ match: target.match, bodies: target.bodies }).toEqual({ match: 0, bodies: 0 });
+ expect(pairs(target.rows)).toEqual(pairs(stored));
+ }
+ for (const who of ['bob', 'unbound']) {
+ const hub = await read(who, HUB);
+ expect(hub.rows.length).toBe(SPOKES);
+ expect({ match: hub.match, bodies: hub.bodies }).toEqual({ match: 1, bodies: 1 });
+ expect(hub.rows.filter(r => r.context.includes(SPOKE_PROSE)).length).toBe(LINK_CONTEXT_PAGE_BOUND);
+ }
+ for (const [op, params] of [['traverse_graph', { slug: CH_ANCHOR, hops: CHAIN_HOPS }], ['search', { query: CHAIN_Q }]] as const) {
+ for (const who of ['owner', 'local', 'bob', 'unbound']) {
+ sql.length = 0;
+ await call(who, op, params);
+ const world = who === 'bob' || who === 'unbound';
+ expect({ who, op, match: sql.filter(q => q.includes(LINK_MATCH_SQL)).length, bodies: sql.filter(q => q.includes(ORIGIN_BODY_SQL)).length })
+ .toEqual({ who, op, match: world ? 1 : 0, bodies: world ? 1 : 0 });
+ }
+ }
+ } finally {
+ engine.executeRaw = executeRaw;
+ }
+ }, 300_000);
+ });
+}
diff --git a/test/link-origin-scope.test.ts b/test/link-origin-scope.test.ts
index e2bdfd01a7..de05ce6bc6 100644
--- a/test/link-origin-scope.test.ts
+++ b/test/link-origin-scope.test.ts
@@ -25,6 +25,12 @@ import { dispatchToolCall } from '../src/mcp/dispatch.ts';
import type { GraphNode, GraphPath, Link } from '../src/core/types.ts';
import { testBackends } from './helpers/test-backends.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { bindCredential } from '../src/core/access/members.ts';
const A = 'source-a';
const B = 'source-b';
@@ -58,7 +64,9 @@ for (const kind of testBackends()) {
[B, 'notes/bob-example', 'note'], [B, 'companies/beta-example', 'company'],
];
for (const [sourceId, slug, type] of pages) {
- await engine.putPage(slug, { type: type as never, title: slug, compiled_truth: `${slug} body.`, timeline: '', frontmatter: {} }, { sourceId });
+ // GST-2957: a body-excerpt context reaches a world-only caller only while its page holds it.
+ const body = slug === ALICE ? `${slug} body. CTX-NO-ORIGIN` : `${slug} body.`;
+ await engine.putPage(slug, { type: type as never, title: slug, compiled_truth: body, timeline: '', frontmatter: {} }, { sourceId });
}
const edges: Array<[string, string, string, string, string, string, string, [string, string] | null, string | null]> = [
[A, ALICE, A, ACME, 'references', 'foreign-origin', 'CTX-FOREIGN-ORIGIN', [B, 'notes/bob-example'], 'key_people'],
@@ -139,6 +147,8 @@ for (const kind of testBackends()) {
expect(result.card.backlink_count).toBe(2);
const pack = await remoteDispatch('context_pack', { entities: `${ACME},${ALICE}` });
expect(pack).toContain('CTX-NO-ORIGIN');
+ const packCard = (JSON.parse(pack) as { cards: Array<{ slug: string; edges: Array<{ direction: string; context: string | null }> }> }).cards.find(c => c.slug === ACME)!;
+ expect(packCard.edges.filter(e => e.direction === 'in').map(e => e.context).sort()).toEqual(['CTX-LIVE-ORIGIN', 'CTX-NO-ORIGIN']);
for (const marker of HIDDEN) expect(pack).not.toContain(marker);
}, 60_000);
@@ -162,5 +172,43 @@ for (const kind of testBackends()) {
expect((await engine.findOrphanPages({ sourceId: A })).map(r => r.slug)).not.toContain(ISLAND);
expect((await engine.findOrphanPages({ sourceId: A, mode: 'inbound' })).map(r => r.slug)).not.toContain(FOREIGN_AUTHORED);
}, 60_000);
+
+ test('GST-2957: a markdown link with no origin whose context is not in its from page is empty for a world-only caller, stored for the owner and local', async () => {
+ const FROM = 'notes/stale-excerpt-from-example';
+ const TO = 'companies/stale-excerpt-to-example';
+ const STALE = 'CTX-STALE-EXCERPT';
+ for (const slug of [FROM, TO]) await engine.putPage(slug, { type: 'note' as never, title: slug, compiled_truth: `${slug} body.`, timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source)
+ SELECT f.id, t.id, 'related', $3, 'markdown' FROM pages f JOIN pages t ON t.source_id = 'default' AND t.slug = $2
+ WHERE f.source_id = 'default' AND f.slug = $1`, [FROM, TO, STALE]);
+ for (const id of ['owner-example', 'other-example']) await engine.executeRaw('INSERT INTO access_members (id) VALUES ($1) ON CONFLICT DO NOTHING', [id]);
+ const tokens: Record<string, string> = {};
+ for (const [name, member] of [['owner', 'owner-example'], ['other', 'other-example']]) {
+ const m = await mintLegacyToken(engine, { name: `stale-${name}`, scopes: ['read'], takesHolders: ['world'] });
+ tokens[name] = m.token;
+ await bindCredential(engine, { kind: 'token', id: m.id }, { member });
+ }
+ await setOwner(engine, 'owner-example');
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const read = async (who: string, op: string, params: Record<string, unknown>) => {
+ __resetPrivateVisibilityCacheForTests();
+ const tokenAuth = who === 'local' ? null : await provider.verifyAccessToken(tokens[who]!) as unknown as AuthInfo;
+ const result = tokenAuth
+ ? await dispatchToolCall(engine, op, params, { remote: true, transport: 'http', auth: tokenAuth, sourceId: 'default' })
+ : await dispatchToolCall(engine, op, params, { remote: false, sourceId: 'default' });
+ expect(result.isError, result.content[0].text.slice(0, 300)).toBeFalsy();
+ return result.content[0].text;
+ };
+ const reads: Array<[string, Record<string, unknown>]> = [['get_links', { slug: FROM }], ['get_backlinks', { slug: TO }], ['traverse_graph', { slug: FROM, depth: 1, direction: 'out' }], ['entity', { name: TO }]];
+ for (const [op, params] of reads) {
+ const shown = await read('other', op, params);
+ expect(shown, `other ${op}`).toContain(FROM);
+ expect(shown, `other ${op}`).not.toContain(STALE);
+ for (const who of ['owner', 'local']) expect(await read(who, op, params), `${who} ${op}`).toContain(STALE);
+ }
+ const stored = await engine.getLinks(FROM, { sourceId: 'default' });
+ expect(stored.map(l => l.context)).toEqual([STALE]);
+ }, 60_000);
});
}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index cbd81aee38..53e35c55bc 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -93,6 +93,7 @@ test/db-wins-unimported-gst2579.test.ts
test/decide/conflict-proposals-managed.test.ts
test/declared-lineage-visibility.test.ts
test/degraded-engine-recovered-surface-9224.test.ts
+test/delta-beliefs-link-context-2957.test.ts
test/derived-link-reconciliation.test.ts
test/derived-origin-carry-managed.test.ts
test/derived-origin-carry-private.test.ts
@@ -329,6 +330,7 @@ test/large-pages/upload-over-ceiling.test.ts
test/large-pages/upload-provenance-7873.test.ts
test/large-pages/upload-review.test.ts
test/large-pages/v252-master-reader-compat.test.ts
+test/link-context-world-rows-2957.test.ts
test/link-cross-source.test.ts
test/link-dates-per-row-gst2228.test.ts
test/link-origin-scope.test.ts
diff --git a/test/retrieval-op-redaction.test.ts b/test/retrieval-op-redaction.test.ts
index 21ece5a745..7647c748de 100644
--- a/test/retrieval-op-redaction.test.ts
+++ b/test/retrieval-op-redaction.test.ts
@@ -70,7 +70,7 @@ beforeAll(async () => {
timeline: `- ${TODAY}: ${planted('timeline')}`, frontmatter: { summary: planted('summary') },
}, { sourceId: SRC });
await engine.putPage('notes/n1', {
- type: 'note', title: planted('note'), compiled_truth: `${planted('note body')}\nGITHUB_TOKEN=${rand(31)}7`,
+ type: 'note', title: planted('note'), compiled_truth: `${planted('note body')}\n${planted('link')}\nGITHUB_TOKEN=${rand(31)}7`,
timeline: `- ${TODAY}: ${planted('note timeline')}`, frontmatter: {},
}, { sourceId: SRC });
await engine.putPage('misc/orphan', { type: 'note', title: planted('orphan'), compiled_truth: planted('orphan body'), frontmatter: {} }, { sourceId: SRC });
diff --git a/test/schema-pack-page-to-link.test.ts b/test/schema-pack-page-to-link.test.ts
index ce7a211323..3b69091309 100644
--- a/test/schema-pack-page-to-link.test.ts
+++ b/test/schema-pack-page-to-link.test.ts
@@ -10,6 +10,8 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { runPageToLinkCore } from '../src/core/schema-pack/page-to-link.ts';
import type { OperationContext } from '../src/core/operations.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { renderTakesFence } from '../src/core/takes-fence.ts';
let engine: PGLiteEngine;
@@ -107,6 +109,30 @@ describe('runPageToLinkCore', () => {
expect(linkRows[0].link_type).toBe('partner_of');
});
+ it('preserve_notes keeps the page opening without its facts or takes fence (GST-2957)', async () => {
+ await seed('people/alice', 'person');
+ await seed('companies/acme', 'company');
+ const facts = renderFactsTable([{ rowNum: 1, claim: 'Deal terms kestrelfactcanary', kind: 'fact', confidence: 1, visibility: 'private', notability: 'medium', active: true }] as never);
+ const takes = renderTakesFence([{ rowNum: 1, claim: 'Deal is risky ternetakecanary', kind: 'take', holder: 'brain', weight: 0.5, active: true }] as never);
+ await seed('atoms/partner-1', 'atom-partner-link', { source: 'people/alice', target: 'companies/acme' },
+ 'Partner note.\n\n' + facts + '\n\n' + takes + '\n\nSigned in spring.');
+ await runPageToLinkCore(ctxOf(), {
+ rules: [{
+ from_type: 'atom-partner-link',
+ link_type: 'partner_of',
+ source_slug_from: { frontmatter_field: 'source' },
+ target_slug_from: { frontmatter_field: 'target' },
+ preserve_notes: true,
+ }],
+ apply: true,
+ });
+ const [link] = await engine.executeRaw<{ context: string }>(
+ `SELECT l.context FROM links l JOIN pages p ON p.id = l.from_page_id WHERE p.slug = 'people/alice'`);
+ expect(link!.context).toContain('Partner note.');
+ expect(link!.context).toContain('Signed in spring.');
+ for (const text of ['kestrelfactcanary', 'ternetakecanary', 'gbrain:facts', 'gbrain:takes']) expect(link!.context).not.toContain(text);
+ });
+
it('records unresolved when source frontmatter field is missing', async () => {
await seed('atoms/bad-1', 'atom-partner-link', { target: 'companies/acme' }); // no source
const result = await runPageToLinkCore(ctxOf(), {
diff --git a/test/traverse-graph-hops.test.ts b/test/traverse-graph-hops.test.ts
index 4eb8ba83e7..664859674c 100644
--- a/test/traverse-graph-hops.test.ts
+++ b/test/traverse-graph-hops.test.ts
@@ -28,12 +28,13 @@ beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({});
await engine.initSchema();
- const page = (slug: string, type: string, frontmatter?: Record<string, unknown>) =>
- engine.putPage(slug, { type: type as 'person', title: slug.split('/')[1], compiled_truth: `${slug} body`, timeline: '', ...(frontmatter ? { frontmatter } : {}) });
+ const page = (slug: string, type: string, frontmatter?: Record<string, unknown>, body = `${slug} body`) =>
+ engine.putPage(slug, { type: type as 'person', title: slug.split('/')[1], compiled_truth: body, timeline: '', ...(frontmatter ? { frontmatter } : {}) });
await page('people/alice-example', 'person');
await page('people/bob-example', 'person');
await page('people/priv-example', 'person', { visibility: 'private' });
- await page('companies/acme-example', 'company');
+ // GST-2957: a world-only remote caller sees a body-excerpt context only when the page still holds it.
+ await page('companies/acme-example', 'company', undefined, `companies/acme-example body. founded by bob ${'x'.repeat(400)}`);
await page('companies/lonely-example', 'company');
await engine.addLink('people/alice-example', 'companies/acme-example', 'alice backed acme', 'invested_in', 'markdown');
await engine.addLink('companies/acme-example', 'people/bob-example', `founded by bob ${'x'.repeat(400)}`, 'founded', 'markdown');