Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(privacy): remote reads see private pages in the caller's private-readable sources (GBRA-156)

garrytan21aa19c0a830
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 6aa1743180..e6b104cd95 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -55,6 +55,10 @@ const VETTED_BUILDERS: Record<string, string> = {
pageReadFilter: 'src/core/search/read-policy-sql.ts: binds scope values as params, splices only the caller alias',
buildRecencyComponentSql: 'src/core/search/sql-ranking.ts: inlines LIKE literals + numeric coefficients from the decay map, as master (planner behavior)',
privatePagesFilterFragment: 'src/core/search/private-visibility.ts: constant visibility predicate over a caller alias',
+ privatePagesFilterForCaller: 'src/core/search/private-visibility.ts: privatePagesFilterFragment ORed with the private-readable source ids, each checked by isValidSourceId (alphabet [a-z0-9-], no quote) before it is quoted in',
+ privateLinkOriginFilterForCaller: 'src/core/search/private-visibility.ts: constant link-origin predicate ORed with isValidSourceId-checked private-readable source ids',
+ privateTimelineEventFilterForCaller: 'src/core/search/private-visibility.ts: constant timeline-event predicate ORed with isValidSourceId-checked private-readable source ids',
+ orPrivateReadableSource: 'src/core/search/private-visibility.ts: wraps a caller predicate with isValidSourceId-checked private-readable source ids quoted as literals',
quarantineFilterFragment: 'src/core/quarantine.ts: constant quarantine predicate over a caller alias',
currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',
buildCJKKeywordSql: 'src/core/search/cjk-keyword-sql.ts: binds the query as params; shared by both engines',
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 13cc2998ea..26bf7a1d48 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -34,7 +34,7 @@ import {
EmbeddingColumnNotRegisteredError,
} from '../search/embedding-column.ts';
import { chunkDocumentOrder, chunkGenerationFilter, chunkManifestJoin, chunkVisibleFilter, chunkWriteInvalidations, currentTextProjectionFilter, movableChunkSql, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import { splitEmbeddingSignature, lockEmbeddingSources } from '../embedding-invalidation.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from '../embed-skip.ts';
import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
@@ -401,7 +401,7 @@ function chunkReadWhere(
? sqlFragment`p.source_id = ANY(${scope.sourceIds}::text[])`
: sqlFragment`p.source_id = ${scope.sourceId}`;
return sqlFragment`p.slug = ${slug} AND ${scopeSql}
- ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
+ ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``}
AND ${trustedSql(opts?.includeUnsealed ? chunkGenerationFilter('p', 'cc', opts.chunkManifest ?? true) : chunkVisibleFilter('p', 'cc'))}
${requiresSafeChunks(opts) ? trustedSql(`AND ${safeChunksFilter('p')}`) : sqlFragment``}`;
}
@@ -1122,7 +1122,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReq
const scopeSql = opts.sourceIds && opts.sourceIds.length > 0
? sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[])`
: opts.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;
- const privateSql = opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``;
+ const privateSql = opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``;
const safeSql = requiresSafeChunks(opts) ? trustedSql(`AND ${safeChunksFilter('p')}`) : sqlFragment``;
const { rows } = await exec.run(sqlFragment`
WITH req AS (
diff --git a/src/core/engine-sql/exact-identity.ts b/src/core/engine-sql/exact-identity.ts
index d373ad4444..cbb6e1341d 100644
--- a/src/core/engine-sql/exact-identity.ts
+++ b/src/core/engine-sql/exact-identity.ts
@@ -19,7 +19,7 @@
*/
import { joinFragments, renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
import { entityTypePredicateSql, type EntityTypeFilter } from '../schema-pack/entity-types.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
export interface ExactIdentityProbes {
@@ -84,7 +84,7 @@ export function exactIdentityStatement(opts: ExactIdentityStatementOpts): { text
WHERE a.source_id = ANY(${sourceIds}::text[]) AND a.alias_norm = ANY(${probes.aliasKeys}::text[])`);
}
arms.push(...emailArms(sourceIds, probes.emails));
- const privacy = opts.remote?.excludePrivate ? trustedSql(` AND ${privatePagesFilterFragment('p')}`) : sqlFragment``;
+ const privacy = opts.remote?.excludePrivate ? trustedSql(` AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``;
const remote = opts.remote ? sqlFragment` AND ${trustedSql(quarantineFilterFragment('p'))}${privacy}` : sqlFragment``;
return renderFragment(sqlFragment`
WITH cand AS (
diff --git a/src/core/engine-sql/graph-rank.ts b/src/core/engine-sql/graph-rank.ts
index 726190b289..56fa65b8b7 100644
--- a/src/core/engine-sql/graph-rank.ts
+++ b/src/core/engine-sql/graph-rank.ts
@@ -38,7 +38,7 @@
*/
import { renderFragment, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
import { entityTypePredicateSql, type EntityTypeFilter } from '../schema-pack/entity-types.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
import { rankingLinkSql } from '../link-ranking-policy.ts';
import { MAX_RETIREMENT_HOPS, retiredPageSql } from '../entities/resolve.ts';
@@ -87,7 +87,7 @@ const FOLD_REASON_SQL = "CASE WHEN btrim(COALESCE(rp.frontmatter->>'superseded_b
function readablePageSql(opts: Pick<RankEntitiesStatementOpts, 'sourceIds' | 'remote'>): SqlFragment {
const scope = opts.sourceIds ? sqlFragment` AND vp.source_id = ANY(${opts.sourceIds}::text[])` : sqlFragment``;
if (!opts.remote) return sqlFragment`vp.deleted_at IS NULL${scope}`;
- const privacy = opts.remote.excludePrivate ? trustedSql(` AND ${privatePagesFilterFragment('vp')}`) : sqlFragment``;
+ const privacy = opts.remote.excludePrivate ? trustedSql(` AND ${privatePagesFilterForCaller('vp')}`) : sqlFragment``;
return sqlFragment`vp.deleted_at IS NULL${scope} AND ${trustedSql(quarantineFilterFragment('vp'))}${privacy}
AND EXISTS (SELECT 1 FROM sources rank_source WHERE rank_source.id = vp.source_id AND NOT rank_source.archived)`;
}
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.ts
index 9bf967290a..b17b2d165f 100644
--- a/src/core/engine-sql/links.ts
+++ b/src/core/engine-sql/links.ts
@@ -15,7 +15,7 @@ import type { LinkBatchInput, TraverseGraphOpts } from '../engine.ts';
import type { Link, GraphNode, GraphPath } from '../types.ts';
import { executeRawJsonb } from '../sql-query.ts';
import { sanitizeForJsonb, buildLinkRows } from '../batch-rows.ts';
-import { privatePagesFilterFragment, privateLinkOriginFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller, privateLinkOriginFilterForCaller } from '../search/private-visibility.ts';
import { TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from '../engine-constants.ts';
import { PageMissingError } from '../engine-errors.ts';
import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
@@ -343,7 +343,7 @@ export async function removeLink(
export async function getLinks(exec: ScopedRead, slug: string, opts?: LinkReadScope): Promise<Link[]> {
- const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';
+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterForCaller('f')} AND ${privatePagesFilterForCaller('t')} AND ${privateLinkOriginFilterForCaller('l')}` : '';
const tSel = opts?.temporal ? TEMPORAL_LINK_SELECT_SQL : '';
const tJoin = opts?.temporal ? temporalLinkJoinSql('l', opts.excludePrivate) : '';
const finish = (rows: unknown[]) => finishTemporal(rows, opts);
@@ -414,7 +414,7 @@ export async function getLinks(exec: ScopedRead, slug: string, opts?: LinkReadSc
export async function getBacklinks(exec: ScopedRead, slug: string, opts?: LinkReadScope): Promise<Link[]> {
- const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterFragment('f')} AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';
+ const privacy = opts?.excludePrivate ? `AND ${privatePagesFilterForCaller('f')} AND ${privatePagesFilterForCaller('t')} AND ${privateLinkOriginFilterForCaller('l')}` : '';
const tSel = opts?.temporal ? TEMPORAL_LINK_SELECT_SQL : '';
const tJoin = opts?.temporal ? temporalLinkJoinSql('l', opts.excludePrivate) : '';
const finish = (rows: unknown[]) => finishTemporal(rows, opts);
@@ -536,7 +536,7 @@ export async function findOrphanPages(exec: LegacyUnscopedRead, opts?: {
FROM links l
JOIN pages tgt ON tgt.id = l.to_page_id
WHERE l.from_page_id = p.id
- AND tgt.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('tgt')} AND ${privateLinkOriginFilterFragment('l')}`) : sqlFragment``}
+ AND tgt.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('tgt')} AND ${privateLinkOriginFilterForCaller('l')}`) : sqlFragment``}
)`
: sqlFragment``;
const rows = (await exec.run(sqlFragment`
@@ -548,14 +548,14 @@ export async function findOrphanPages(exec: LegacyUnscopedRead, opts?: {
(NOT ${trustedSql(QUARANTINE_FILTER_FRAGMENT)}) AS quarantined,
p.source_id
FROM pages p
- WHERE p.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
+ WHERE p.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``}
${sourceFilter}
AND NOT EXISTS (
SELECT 1
FROM links l
JOIN pages src ON src.id = l.from_page_id
WHERE l.to_page_id = p.id
- AND src.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('src')} AND ${privateLinkOriginFilterFragment('l')}`) : sqlFragment``}
+ AND src.deleted_at IS NULL ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('src')} AND ${privateLinkOriginFilterForCaller('l')}`) : sqlFragment``}
)
${outboundFilter}
ORDER BY p.slug
@@ -638,7 +638,7 @@ export async function traverseGraph(
opts?: TraverseGraphOpts,
): Promise<GraphNode[]> {
const privacy = (page: string, link?: string) => opts?.excludePrivate
- ? trustedSql(`AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}`) : sqlFragment``;
+ ? trustedSql(`AND ${privatePagesFilterForCaller(page)}${link ? ` AND ${privateLinkOriginFilterForCaller(link)}` : ''}`) : sqlFragment``;
// v0.34.1 (#861 — P0 leak seal): visited pages are scoped to the caller's
// source(s) at the seed and at every step, and the per-node `links`
// aggregation only includes edges to in-scope pages.
@@ -689,7 +689,7 @@ export async function traversePathsDetailed(
opts?: LinkReadScope & { depth?: number; linkType?: string; direction?: 'in' | 'out' | 'both' },
): Promise<{ paths: GraphPath[]; truncated: boolean }> {
const privacy = (page: string, link?: string) => opts?.excludePrivate
- ? trustedSql(`AND ${privatePagesFilterFragment(page)}${link ? ` AND ${privateLinkOriginFilterFragment(link)}` : ''}`) : sqlFragment``;
+ ? trustedSql(`AND ${privatePagesFilterForCaller(page)}${link ? ` AND ${privateLinkOriginFilterForCaller(link)}` : ''}`) : sqlFragment``;
const depth = opts?.depth ?? 5;
const direction = opts?.direction ?? 'out';
const linkType = opts?.linkType ?? null;
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 2587abc644..2005593a30 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -22,7 +22,7 @@ import { moveSlugBindings, recordRenameAlias } from '../page-state/rename-alias.
import { segmentedRevertRefusal } from '../page-state/versions.ts';
import { sanitizeText } from '../batch-rows.ts';
import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';
-import { privatePagesFilterFragment, privateSnapshotFilterFragment } from '../search/private-visibility.ts';
+import { orPrivateReadableSource, privatePagesFilterFragment, privateSnapshotFilterFragment, privatePagesFilterForCaller } from '../search/private-visibility.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
import { rederiveHiddenSql } from '../eligibility/sql.ts';
import { validateSlug, contentHash, isBlankBody, rowToPage, rowToStalePage, isMissingSchemaObject, warnOncePerProcess } from '../utils.ts';
@@ -495,7 +495,7 @@ export async function listPages(exec: ScopedRead, filters?: PageFilters): Promis
: sqlFragment`AND p.deleted_at IS NULL`;
// #4352: untrusted-caller private-page filter (see PageFilters.excludePrivate).
const privateCondition = filters?.excludePrivate === true
- ? trustedSql(`AND ${privatePagesFilterFragment('p')}`)
+ ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`)
: sqlFragment``;
const effectiveAfterCondition = filters?.effective_after
? sqlFragment`AND p.effective_date >= ${filters.effective_after}::timestamptz`
@@ -723,7 +723,7 @@ export async function resolveSlugs(
// `get_page`.
const sources = opts?.sourceIds?.length ? opts.sourceIds : null;
const scalar = opts?.sourceId ?? null;
- const privacy = opts?.excludePrivate ? trustedSql(` AND ${privatePagesFilterFragment('pages')}`) : sqlFragment``;
+ const privacy = opts?.excludePrivate ? trustedSql(` AND ${privatePagesFilterForCaller('pages')}`) : sqlFragment``;
const scopeFragment = sources
? sqlFragment` AND source_id = ANY(${sources}::text[])`
: scalar
@@ -1011,7 +1011,7 @@ export async function getVersions<B extends boolean = true>(
opts?: GetVersionsOpts<B>,
): Promise<PageVersionRows<B>> {
const privacy = opts?.excludePrivate
- ? trustedSql(`AND ${privatePagesFilterFragment('p')} AND ${privateSnapshotFilterFragment('pv')}`) : sqlFragment``;
+ ? trustedSql(`AND ${orPrivateReadableSource('p.source_id', `${privatePagesFilterFragment('p')} AND ${privateSnapshotFilterFragment('pv')}`)}`) : sqlFragment``;
const scope = opts?.sourceIds && opts.sourceIds.length > 0
? sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[])`
: opts?.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;
@@ -1127,7 +1127,7 @@ export async function resolveSlugWithAliasDetailed(
): Promise<{ canonical_slug: string; source_id: string } | null> {
const sources = Array.isArray(sourceOrSources) ? sourceOrSources : [sourceOrSources];
if (sources.length === 0) return null;
- const privacy = opts?.excludePrivate ? trustedSql(`AND EXISTS (SELECT 1 FROM pages p WHERE p.slug = slug_aliases.canonical_slug AND p.source_id = slug_aliases.source_id AND p.deleted_at IS NULL AND ${privatePagesFilterFragment('p')})`) : sqlFragment``;
+ const privacy = opts?.excludePrivate ? trustedSql(`AND EXISTS (SELECT 1 FROM pages p WHERE p.slug = slug_aliases.canonical_slug AND p.source_id = slug_aliases.source_id AND p.deleted_at IS NULL AND ${privatePagesFilterForCaller('p')})`) : sqlFragment``;
try {
const { rows } = await exec.run<{ canonical_slug: string; source_id: string }>(sqlFragment`
SELECT canonical_slug, source_id
diff --git a/src/core/engine-sql/tags.ts b/src/core/engine-sql/tags.ts
index 32eba700a3..5de22f41cd 100644
--- a/src/core/engine-sql/tags.ts
+++ b/src/core/engine-sql/tags.ts
@@ -5,7 +5,7 @@
* page-state guarded implementation (`page-state/tags.ts`) and stay there.
* `getTags` was unscoped on master (EO4 inventory): `LegacyUnscopedRead`.
*/
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import type { LegacyUnscopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
@@ -23,7 +23,7 @@ export async function getTags(
opts?.sourceIds && opts.sourceIds.length > 0
? sqlFragment`source_id = ANY(${opts.sourceIds}::text[])`
: sqlFragment`source_id = ${opts?.sourceId ?? 'default'}`;
- const privacy = opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('pages')}`) : sqlFragment``;
+ const privacy = opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('pages')}`) : sqlFragment``;
const live = opts?.liveOnly ? sqlFragment`AND deleted_at IS NULL` : sqlFragment``;
const { rows } = await exec.run<{ tag: string }>(sqlFragment`
SELECT DISTINCT tag FROM tags
diff --git a/src/core/engine-sql/takes.ts b/src/core/engine-sql/takes.ts
index 3ebcd4c5de..c4f9c6fdb0 100644
--- a/src/core/engine-sql/takes.ts
+++ b/src/core/engine-sql/takes.ts
@@ -23,7 +23,7 @@ import { deriveResolutionTuple, finalizeScorecard } from '../takes-resolution.ts
import { normalizeWeightForStorage } from '../takes-fence.ts';
import { buildTakeRows } from '../batch-rows.ts';
import { staleTakeRowToRow, takeRowToTake, takeHitRowToHit, tryParseEmbedding } from '../utils.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import { jsonbParam, type SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
@@ -308,7 +308,7 @@ export async function listTakes(exec: LegacyUnscopedRead, opts: TakesListOpts =
FROM takes t
JOIN pages p ON p.id = t.page_id
WHERE 1=1
- ${opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
+ ${opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``}
AND (${opts.page_id ?? null}::int IS NULL OR t.page_id = ${opts.page_id ?? null}::int)
AND (${opts.page_slug ?? null}::text IS NULL OR p.slug = ${opts.page_slug ?? null}::text)
AND (${opts.holder ?? null}::text IS NULL OR t.holder = ${opts.holder ?? null}::text)
@@ -354,7 +354,7 @@ export async function searchTakes(exec: LegacyUnscopedRead, query: string, opts:
JOIN pages p ON p.id = t.page_id
WHERE t.active
AND ${query} <% t.claim
- ${opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
+ ${opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``}
AND (
${opts.takesHoldersAllowList ?? null}::text[] IS NULL
OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
@@ -389,7 +389,7 @@ export async function searchTakesVector(
JOIN pages p ON p.id = t.page_id
WHERE t.active
AND t.embedding IS NOT NULL
- ${opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}
+ ${opts.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}`) : sqlFragment``}
AND (
${opts.takesHoldersAllowList ?? null}::text[] IS NULL
OR t.holder = ANY(${opts.takesHoldersAllowList ?? null}::text[])
@@ -630,7 +630,7 @@ export async function getScorecard(exec: LegacyUnscopedRead, opts: TakesScorecar
)::float AS brier
FROM takes
WHERE 1=1 ${holderClause} ${domainClause} ${sinceClause} ${untilClause} ${allowed} ${sourceFilter}
- ${opts.excludePrivate ? trustedSql(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterFragment('p')})`) : sqlFragment``}
+ ${opts.excludePrivate ? trustedSql(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterForCaller('p')})`) : sqlFragment``}
`)).rows;
const r = rows[0] as { total_bets: number; resolved: number; correct: number; incorrect: number; partial: number; unresolvable_count: number; brier: number | null };
return finalizeScorecard(r);
@@ -671,7 +671,7 @@ export async function getCalibrationCurve(exec: LegacyUnscopedRead, opts: Calibr
FROM takes
WHERE resolved_quality IN ('correct','incorrect')
${holderClause} ${allowed} ${sourceFilter}
- ${opts.excludePrivate ? trustedSql(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterFragment('p')})`) : sqlFragment``}
+ ${opts.excludePrivate ? trustedSql(`AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND ${privatePagesFilterForCaller('p')})`) : sqlFragment``}
)
SELECT
(bucket_idx::numeric * ${bucketSize}::numeric)::float AS bucket_lo,
diff --git a/src/core/engine-sql/timeline.ts b/src/core/engine-sql/timeline.ts
index e074162966..8b12addcc0 100644
--- a/src/core/engine-sql/timeline.ts
+++ b/src/core/engine-sql/timeline.ts
@@ -18,7 +18,7 @@ import type {
import { executeRawJsonb } from '../sql-query.ts';
import { sanitizeForJsonb, buildTimelineRows } from '../batch-rows.ts';
import { finalizeLastSeen } from '../chronicle/last-seen.ts';
-import { privatePagesFilterFragment, privateTimelineEventFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller, privateTimelineEventFilterForCaller } from '../search/private-visibility.ts';
import { PageMissingError } from '../engine-errors.ts';
import type { SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead } from './brands.ts';
@@ -119,8 +119,8 @@ export async function getTimeline(exec: LegacyUnscopedRead, slug: string, opts?:
const rows = (await exec.run(sqlFragment`
SELECT te.* FROM ${pagesJoin}
WHERE p.slug = ${slug} ${sourceCond} ${afterCond} ${beforeCond}
- ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}
- AND ${privateTimelineEventFilterFragment('te')}`) : sqlFragment``}${opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('timeline_entries', 'te', opts.eligibility))}` : sqlFragment``}
+ ${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterForCaller('p')}
+ AND ${privateTimelineEventFilterForCaller('te')}`) : sqlFragment``}${opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('timeline_entries', 'te', opts.eligibility))}` : sqlFragment``}
ORDER BY te.date DESC, te.id DESC LIMIT ${limit}`)).rows;
return rows as unknown as TimelineEntry[];
}
@@ -134,7 +134,7 @@ export async function getTimeline(exec: LegacyUnscopedRead, slug: string, opts?:
// ep=true: the ep LEFT JOIN carries the same scope so out-of-scope event fields null out (#2200 origin-join shape).
function chronicleSourceCond(opts?: PageReadScope, ep = false) {
const privacy = opts?.excludePrivate && !ep
- ? trustedSql(`AND ${privatePagesFilterFragment('p')} AND ${privateTimelineEventFilterFragment('te')}`)
+ ? trustedSql(`AND ${privatePagesFilterForCaller('p')} AND ${privateTimelineEventFilterForCaller('te')}`)
: sqlFragment``;
if (opts?.sourceIds && opts.sourceIds.length > 0)
return ep ? sqlFragment`AND ep.source_id = ANY(${opts.sourceIds}::text[])` : sqlFragment`AND p.source_id = ANY(${opts.sourceIds}::text[]) ${privacy}`;
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index a6bb9e484f..ca97ea8375 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -30,7 +30,7 @@ import { slugifySegment } from '../sync.ts';
const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonical = async (...args) =>
(await import('../mentions/siblings.ts')).siblingCanonical(...args);
import { isMissingSchemaObject } from '../utils.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import { rankingLinkSql } from '../link-ranking-policy.ts';
/**
@@ -490,7 +490,7 @@ export async function resolveStrictEntityReference(
): Promise<StrictResolution> {
const trimmed = raw.trim();
if (!trimmed) return { slug: null, miss: 'no_page' };
- const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';
+ const privacy = opts.excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : '';
const live = async (slugs: string[]) => slugs.length === 0 ? [] : engine.executeRaw<{ slug: string; type: string | null }>(
`SELECT p.slug, p.type FROM pages p
WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug = ANY($2::text[]) ${privacy}`,
@@ -572,7 +572,7 @@ export async function entityReferenceCandidates(
const trimmed = raw.trim();
const token = slugify(trimmed);
if (!token) return [];
- const privacy = opts.excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';
+ const privacy = opts.excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : '';
const aliases = await aliasHitSlugs(engine, source_id, trimmed).catch(() => [] as string[]);
const prefixed = (await findPrefixCandidates(engine, source_id, token)).map(c => c.slug);
const named = await engine.executeRaw<{ slug: string }>(
diff --git a/src/core/entity-identity.ts b/src/core/entity-identity.ts
index 93bd2ebc3c..9720f9aab1 100644
--- a/src/core/entity-identity.ts
+++ b/src/core/entity-identity.ts
@@ -29,7 +29,7 @@
import type { BrainEngine } from './engine.ts';
import type { Link } from './types.ts';
import { isMissingSchemaObject } from './utils.ts';
-import { privatePagesFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterForCaller } from './search/private-visibility.ts';
/** Config key for the flag-gated retrieval union. Default OFF. */
export const ENTITY_IDENTITY_UNION_CONFIG_KEY = 'entity_identity.union';
@@ -176,7 +176,7 @@ export async function listEntityIdentities(
const params: unknown[] = [];
const allowedSources = opts.allowedSources?.length ? opts.allowedSources
: opts.sourceId ? [opts.sourceId] : undefined;
- if (opts.excludePrivate) where.push(privatePagesFilterFragment('p'));
+ if (opts.excludePrivate) where.push(privatePagesFilterForCaller('p'));
if (opts.entityId) {
params.push(validateEntityId(opts.entityId));
where.push(`ei.entity_id = $${params.length}`);
@@ -200,7 +200,7 @@ export async function listEntityIdentities(
});
seedScope += ` AND ei2.source_id IN (${ph.join(', ')})`;
}
- if (opts.excludePrivate) seedScope += ` AND ${privatePagesFilterFragment('p2')}`;
+ if (opts.excludePrivate) seedScope += ` AND ${privatePagesFilterForCaller('p2')}`;
where.push(`ei.entity_id IN (
SELECT ei2.entity_id FROM entity_identities ei2
JOIN pages p2 ON p2.id = ei2.page_id AND p2.source_id = ei2.source_id
diff --git a/src/core/facts/subject-infer.ts b/src/core/facts/subject-infer.ts
index 07a16b599f..5a50e1c22b 100644
--- a/src/core/facts/subject-infer.ts
+++ b/src/core/facts/subject-infer.ts
@@ -24,7 +24,7 @@
import type { BrainEngine } from '../engine.ts';
import { extractCandidates, isCommonCapitalizedWord } from '../context/entity-salience.ts';
import { isFactEntityPage, resolveStrictEntityReference, type StrictResolution } from '../entities/resolve.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
export type InferredVia = 'page' | 'mention';
export type InferMissReason = 'ambiguous' | 'unverified_match' | 'no_mention' | 'no_page';
@@ -224,7 +224,7 @@ function onlyExampleUses(fact: string, query: string): boolean {
}
async function liveFactEntityPage(engine: BrainEngine, sourceId: string, slug: string, excludePrivate?: boolean): Promise<string | null> {
- const privacy = excludePrivate ? `AND ${privatePagesFilterFragment('p')}` : '';
+ const privacy = excludePrivate ? `AND ${privatePagesFilterForCaller('p')}` : '';
const [row] = await engine.executeRaw<{ slug: string; type: string | null }>(
`SELECT p.slug, p.type FROM pages p WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL ${privacy} LIMIT 1`,
[sourceId, slug],
diff --git a/src/core/link-relationship-notes.ts b/src/core/link-relationship-notes.ts
index 1af8e7e78c..82ce231284 100644
--- a/src/core/link-relationship-notes.ts
+++ b/src/core/link-relationship-notes.ts
@@ -14,7 +14,7 @@
import {
annotateTemporalRow, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type RelationshipStatus,
} from './link-validity.ts';
-import { privateLinkOriginFilterFragment, privatePagesFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterForCaller, privateLinkOriginFilterForCaller } from './search/private-visibility.ts';
const NOTE_ENDED_CAP = 3;
@@ -58,13 +58,13 @@ export async function loadRelationshipNotes(
): Promise<Map<string, string>> {
const notes = new Map<string, string>();
if (subjects.length === 0) return notes;
- const privacy = opts.excludePrivate ? ` AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';
+ const privacy = opts.excludePrivate ? ` AND ${privatePagesFilterForCaller('t')} AND ${privateLinkOriginFilterForCaller('l')}` : '';
// The evidence the relationship projection counts for this scope (link-relationships.ts): an origin that is gone or in
// another source never counts, and a private origin does not count toward the world scope.
const endBy = (producer: string) => `EXISTS (SELECT 1 FROM link_transitions x LEFT JOIN pages xo ON xo.id = x.origin_page_id
WHERE x.from_page_id = l.from_page_id AND x.to_page_id = l.to_page_id AND x.link_type = l.link_type AND x.kind = 'end'
AND x.occurred_on = lr_t.last_end AND x.producer ${producer}
- AND (x.origin_page_id IS NULL OR xo.deleted_at IS NULL AND xo.source_id = f.source_id${opts.excludePrivate ? ` AND ${privatePagesFilterFragment('xo')}` : ''}))`;
+ AND (x.origin_page_id IS NULL OR xo.deleted_at IS NULL AND xo.source_id = f.source_id${opts.excludePrivate ? ` AND ${privatePagesFilterForCaller('xo')}` : ''}))`;
const rows = await engine.executeRaw<{ from_slug: string; source_id: string; to_slug: string; to_title: string | null; link_type: string; last_end: string | null; end_upper_bound: boolean | null }>(
`SELECT f.slug AS from_slug, f.source_id, t.slug AS to_slug, t.title AS to_title, l.link_type, lr_t.last_end::text AS last_end,
(${endBy("= 'dream'")} AND NOT ${endBy("<> 'dream'")}) AS end_upper_bound${TEMPORAL_LINK_SELECT_SQL}
diff --git a/src/core/mentions/referrers.ts b/src/core/mentions/referrers.ts
index e83c770348..15fddda95a 100644
--- a/src/core/mentions/referrers.ts
+++ b/src/core/mentions/referrers.ts
@@ -23,7 +23,7 @@
import type { BrainEngine } from '../engine.ts';
import { boundedBodyPrefixSql } from '../page-window/bounded-lead.ts';
-import { privateLinkOriginFilterFragment, privatePagesFilterFragment, privatePagesFilterFragmentFast } from '../search/private-visibility.ts';
+import { privatePagesFilterFastForCaller, privatePagesFilterForCaller, privateLinkOriginFilterForCaller } from '../search/private-visibility.ts';
import { isIdentityUnionEnabled, listEntityIdentities } from '../entity-identity.ts';
import { stripTakesFence } from '../takes-fence.ts';
import { stripFactsFence } from '../facts-fence.ts';
@@ -98,9 +98,9 @@ async function targetPages(engine: BrainEngine, scope: ReferrerScope, union?: bo
/** The caller's read filters, shared by the single-target CTE and its batched variant. */
function referrerFilters(scope: Pick<ReferrerScope, 'excludePrivate' | 'eligibility' | 'includeQuarantined'>) {
return {
- targetPriv: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('t')}` : '',
- linkPriv: scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '',
- pagePriv: scope.excludePrivate ? ` AND ${privatePagesFilterFragmentFast('f')}` : '',
+ targetPriv: scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('t')}` : '',
+ linkPriv: scope.excludePrivate ? ` AND ${privateLinkOriginFilterForCaller('l')}` : '',
+ pagePriv: scope.excludePrivate ? ` AND ${privatePagesFilterFastForCaller('f')}` : '',
pageTrust: ` AND ${pageEligibleSql('f', scope.eligibility)}${scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('f')}`}`,
};
}
@@ -358,7 +358,7 @@ export async function readPageStatusByRef(engine: BrainEngine, refs: Array<{ sou
scope: { excludePrivate: boolean; includeQuarantined?: boolean }): Promise<Map<string, string>> {
const out = new Map<string, string>();
if (!refs.length) return out;
- const priv = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '';
+ const priv = scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('p')}` : '';
const quarantine = scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('p')}`;
const rows = await engine.executeRaw<{ source_id: string; slug: string; status: unknown }>(
`SELECT p.source_id, p.slug, p.frontmatter->'status' AS status
@@ -385,8 +385,8 @@ export async function readRecordMetadata(engine: BrainEngine, pageIds: number[],
scope: Pick<ReferrerScope, 'referrerSources' | 'excludePrivate' | 'includeQuarantined'>): Promise<Map<number, RecordMetadata>> {
const out = new Map<number, RecordMetadata>();
if (!pageIds.length) return out;
- const linkPriv = scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '';
- const targetPriv = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('t')}` : '';
+ const linkPriv = scope.excludePrivate ? ` AND ${privateLinkOriginFilterForCaller('l')}` : '';
+ const targetPriv = scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('t')}` : '';
const targetQuarantine = scope.includeQuarantined ? '' : ` AND ${quarantineFilterFragment('t')}`;
const [status, links] = await Promise.all([
engine.executeRaw<{ id: number; status: unknown }>(`SELECT id, frontmatter->'status' AS status FROM pages WHERE id = ANY($1::int[])`, [pageIds]),
diff --git a/src/core/mentions/siblings.ts b/src/core/mentions/siblings.ts
index c7240f8ffa..e36a9173e6 100644
--- a/src/core/mentions/siblings.ts
+++ b/src/core/mentions/siblings.ts
@@ -72,9 +72,9 @@ export async function readIdentitySiblings(engine: BrainEngine, sourceId: string
if (!policy.siblingMerge) return { pages: [], capped: false, verdict: 'disabled' };
const pack = opts.pack !== undefined ? opts.pack : await loadSourcePack(engine, sourceId);
const types = linkableTypesFor(pack, policy);
- const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterForCaller } = await import('../search/private-visibility.ts');
const { quarantineFilterFragment } = await import('../quarantine.ts');
- const privacy = (opts.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '')
+ const privacy = (opts.excludePrivate ? ` AND ${privatePagesFilterForCaller('pages')}` : '')
+ (opts.excludeQuarantined ? ` AND ${quarantineFilterFragment('pages')}` : '');
const like = `%: ${subject.replace(/[\\%_]/g, m => `\\${m}`)}`;
const rows = await engine.executeRaw<{ slug: string; title: string | null; type: string | null; identity: unknown }>(
@@ -106,10 +106,10 @@ export async function siblingCanonical(engine: BrainEngine, sourceId: string, sl
try {
const policy = await readMentionPolicy(engine);
if (!policy.siblingMerge) return null;
- const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterForCaller } = await import('../search/private-visibility.ts');
const rows = await engine.executeRaw<{ slug: string; title: string | null; type: string | null; identity: unknown }>(
`SELECT slug, title, type, frontmatter->>'identity' AS identity FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL AND slug = ANY($2::text[])${opts.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : ''}`,
+ WHERE source_id = $1 AND deleted_at IS NULL AND slug = ANY($2::text[])${opts.excludePrivate ? ` AND ${privatePagesFilterForCaller('pages')}` : ''}`,
[sourceId, unique]);
if (rows.length !== unique.length) return null;
const pack = await loadSourcePack(engine, sourceId);
diff --git a/src/core/ops/graph-rank.ts b/src/core/ops/graph-rank.ts
index 09e3633e11..773e30f02d 100644
--- a/src/core/ops/graph-rank.ts
+++ b/src/core/ops/graph-rank.ts
@@ -149,7 +149,7 @@ async function readRemoteCoverage(ctx: OperationContext, sourceIds: string[] | u
async function attachDuplicates(ctx: OperationContext, rows: RankedEntity[], filter: EntityTypeFilter, excludePrivate: boolean): Promise<number> {
const { nameVariantsEnabled, readPossibleDuplicates } = await import('../verbs/entity-variants.ts');
if (!(await nameVariantsEnabled(ctx.engine))) return 0;
- const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterForCaller } = await import('../search/private-visibility.ts');
const deadline = Date.now() + DUPLICATE_BUDGET_MS;
let checked = 0;
for (const row of rows.slice(0, RANK_ENTITIES_DUPLICATE_ROWS)) {
@@ -159,8 +159,8 @@ async function attachDuplicates(ctx: OperationContext, rows: RankedEntity[], fil
selectColumns: 'slug, title, type, frontmatter',
entityTypes: new Set(typesFor(filter, row.source_id)),
omitQuarantined: ctx.remote !== false,
- privatePredicate: excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '',
- retirementPrivacy: excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '',
+ privatePredicate: excludePrivate ? ` AND ${privatePagesFilterForCaller('pages')}` : '',
+ retirementPrivacy: excludePrivate ? ` AND ${privatePagesFilterForCaller('p')}` : '',
});
if (duplicates.length) row.possible_duplicates = duplicates;
}
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 5217c2387b..ce5a92e7a2 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -30,7 +30,7 @@ import {
assertSourceInCallerScope,
} from './context.ts';
import { listWantedPages } from '../wanted-links-store.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import type { OperationContext } from './contract.ts';
import type { Link, PageReadPolicy } from '../types.ts';
import { ALL_SOURCES } from '../source-id.ts';
@@ -662,7 +662,7 @@ const wanted_pages: Operation = {
limitOk ? { def: wanted_pages.params.offset, example: 0 } : { def: wanted_pages.params.limit, example: WANTED_DEFAULT_LIMIT });
}
const { total, rows } = await listWantedPages(ctx.engine, { sourceId: policy.sourceId, sourceIds: policy.sourceIds,
- excludePrivate: policy.excludePrivate, privateFilter: privatePagesFilterFragment,
+ excludePrivate: policy.excludePrivate, privateFilter: privatePagesFilterForCaller,
limit: p.count_only === true ? 1 : limit, offset });
const next = offset + limit < total ? offset + limit : null;
return {
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 38b2ce653f..4771c31999 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -28,7 +28,7 @@ import { sanitizeRemoteBody } from '../remote-body.ts';
import { getContentFlag } from '../quarantine.ts';
import { fileHeldField, readHeldPages } from '../persistence/held-reads.ts';
import { bumpLastRetrievedAt } from '../last-retrieved.ts';
-import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs } from '../search/private-visibility.ts';
+import { resolveExcludePrivatePages, isPrivatePage, findPrivateOnlySlugs, isPrivatePageForCaller } from '../search/private-visibility.ts';
import { LIST_PAGES_DESCRIPTION, CAPTURE_DESCRIPTION } from '../operations-descriptions.ts';
import { listPagesPagination, listingTruncatedNotice } from './list-pages-pagination.ts';
import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';
@@ -143,7 +143,7 @@ const get_page: Operation = {
let snapshot = await ctx.engine.readPageSnapshot(slug, { includeDeleted, excludePrivate, ...sourceOpts, resolveAlias: true });
let page = snapshot?.page ?? null;
- if (page && excludePrivate && isPrivatePage(page)) page = null;
+ if (page && excludePrivate && isPrivatePageForCaller(page)) page = null;
let resolved_slug: string | undefined = page && page.slug !== slug ? page.slug : undefined;
if (!page && fuzzy) {
@@ -157,7 +157,7 @@ const get_page: Operation = {
? await tx.readPageSnapshot(candidates[0], { includeDeleted, excludePrivate, ...sourceOpts }) : null };
});
if (fallback.candidates.length > 1) return { error: 'ambiguous_slug', candidates: fallback.candidates };
- if (fallback.snapshot && !(excludePrivate && isPrivatePage(fallback.snapshot.page))) {
+ if (fallback.snapshot && !(excludePrivate && isPrivatePageForCaller(fallback.snapshot.page))) {
snapshot = fallback.snapshot;
page = snapshot.page;
resolved_slug = page.slug;
@@ -296,7 +296,7 @@ const fetch_page: Operation = {
throw error;
}
const page = snapshot?.page;
- if (!page || (excludePrivate && isPrivatePage(page))) throw missing();
+ if (!page || (excludePrivate && isPrivatePageForCaller(page))) throw missing();
const readable = await pageTrustForRead(ctx, page, p.min_trust); // #5575: below the read floor reads as missing
if (!readable) throw missing();
bumpLastRetrievedAt(ctx.engine, [page.id]);
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index d8bdbb8e55..cb48948ebc 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -22,7 +22,7 @@ import {
} from './context.ts';
import { embedQueryWithPrefix } from '../search/query-prefix.ts';
import { ALL_SOURCES } from '../source-id.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
/** Result pages whose takes D2 checks: the page a get_page read returned, or the first distinct pages of a search/query. */
const HIDDEN_TAKES_PAGE_CAP = 3;
@@ -238,7 +238,7 @@ const takes_calibration: Operation = {
async function countMcpResolved(ctx: OperationContext): Promise<number> {
const scope = await readPolicyOpts(ctx);
const where: string[] = [`t.resolved_at IS NOT NULL`, `t.resolved_by LIKE 'mcp:%'`];
- if (scope.excludePrivate) where.push(privatePagesFilterFragment('p'));
+ if (scope.excludePrivate) where.push(privatePagesFilterForCaller('p'));
const params: unknown[] = [];
if (scope.sourceIds && scope.sourceIds.length > 0) {
params.push(scope.sourceIds);
diff --git a/src/core/page-state/snapshot.ts b/src/core/page-state/snapshot.ts
index 2f6ce8aa1c..f336293ed1 100644
--- a/src/core/page-state/snapshot.ts
+++ b/src/core/page-state/snapshot.ts
@@ -1,5 +1,5 @@
import { fenceClaimHashes, overlayWithdrawalBody } from '../facts/withdrawal-overlay.ts';
-import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { privatePagesFilterForCaller } from '../search/private-visibility.ts';
import type { ReadQuery } from '../search/read-enrichment.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { rowToPage } from '../utils.ts';
@@ -82,7 +82,7 @@ async function readSnapshotStatement(query: ReadQuery, slug: string, opts?: Page
filters.push(`p.source_id=$${params.length}`);
}
if (!opts?.includeDeleted) filters.push('p.deleted_at IS NULL');
- if (opts?.excludePrivate) filters.push(privatePagesFilterFragment('p'));
+ if (opts?.excludePrivate) filters.push(privatePagesFilterForCaller('p'));
if (opts?.requireLiveSource) filters.push('EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)');
params.push(opts?.sourceIds?.[0] ?? 'default');
const and = filters.map(filter => ` AND ${filter}`).join('');
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index df9293f234..ecfed76034 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -124,7 +124,7 @@ import { finalizeLastSeen } from './chronicle/last-seen.ts';
import { resolveBoostMap, resolveHardExcludes } from './search/source-boost.ts';
import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, buildBestPerPagePoolCte, buildOrFallbackWebsearchQuery, boundWebsearchQuery, collapseWebsearchDashRuns } from './search/sql-ranking.ts';
import { RARE_TERM_CHUNK_CAP, rankOrFallbackByRarity, rareTermPagesSql, type RareTermPages } from './search/keyword-or-rarity.ts';
-import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment, privatePagesFilterForCaller } from './search/private-visibility.ts';
import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';
import {
vectorCastSuffix,
@@ -2310,7 +2310,7 @@ export class PGLiteEngine implements BrainEngine {
// v0.31.8 (D21): build WHERE clause dynamically. Without opts.sourceId,
// no source filter (preserves pre-v0.31.8 cross-source read).
const where: string[] = ['p.slug = $1'];
- if (opts?.excludePrivate) where.push(privatePagesFilterFragment('p'));
+ if (opts?.excludePrivate) where.push(privatePagesFilterForCaller('p'));
if (!opts?.includeDeleted) where.push('p.deleted_at IS NULL'); // raw_data follows the page soft-delete
const params: unknown[] = [slug];
if (source) {
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 407c2a777c..6330d3d658 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -121,7 +121,7 @@ import { buildSourceFactorCase, buildHardExcludeClause, buildVisibilityClause, b
import { narrowedOrFallbackQuery } from './search/keyword-or-narrow.ts';
import { RARE_TERM_CHUNK_CAP, rankOrFallbackByRarity, rareTermPagesSql, type RareTermPages } from './search/keyword-or-rarity.ts';
import { buildKeywordChunkMatch, KEYWORD_RANK_CANDIDATES, KEYWORD_RANKED_ROWS_CTE, KEYWORD_STATEMENT_SETTINGS } from './search/keyword-chunk-match.ts';
-import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterFragment, privateSnapshotFilterFragment, privateLinkOriginFilterFragment, privateTimelineEventFilterFragment, privateProvenanceFilterFragment, privatePagesFilterForCaller } from './search/private-visibility.ts';
import { DEFAULT_EMBEDDING_MODEL, DEFAULT_EMBEDDING_DIMENSIONS } from './ai/defaults.ts';
import { readStoredEmbeddingIdentity } from './stored-embedding-identity.ts';
import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } from './engine-constants.ts';
@@ -2093,7 +2093,7 @@ export class PostgresEngine implements BrainEngine {
opts?: PageReadScope & { includeDeleted?: boolean },
): Promise<RawData[]> {
const sql = this.sql;
- const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``;
+ const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterForCaller('p')}`) : sql``;
const alive = opts?.includeDeleted ? sql`` : sql`AND p.deleted_at IS NULL`; // raw_data follows the page soft-delete
const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;
const sourceId = sourceIds ? undefined : opts?.sourceId;
diff --git a/src/core/search/alias-fanout.ts b/src/core/search/alias-fanout.ts
index 8d06bc50cd..bbf126d682 100644
--- a/src/core/search/alias-fanout.ts
+++ b/src/core/search/alias-fanout.ts
@@ -99,7 +99,7 @@ export async function resolveQueryEntities(engine: BrainEngine, query: string, s
}
const norms = [...new Set(grams.map(g => g.norm))];
const sources = scope.sourceIds?.length ? scope.sourceIds : [scope.sourceId ?? 'default'];
- const { privatePagesFilterFragment } = await import('./private-visibility.ts');
+ const { privatePagesFilterForCaller } = await import('./private-visibility.ts');
// The alias, title and case-sensitive reads depend on nothing but the n-grams (the title read also on the
// linkable types, which the request's config snapshot answers), so they run at once: on a pooled Postgres
// one round trip of wall time instead of three in series (#6721). A policy or pack failure still throws.
@@ -109,7 +109,7 @@ export async function resolveQueryEntities(engine: BrainEngine, query: string, s
return engine.executeRaw<{ slug: string; source_id: string; t: string }>(
`SELECT slug, source_id, lower(title) AS t FROM pages
WHERE lower(title) = ANY($1::text[]) AND source_id = ANY($2::text[]) AND type = ANY($3::text[]) AND deleted_at IS NULL
- ${scope.excludePrivate ? `AND ${privatePagesFilterFragment('pages')}` : ''}`, [norms, sources, types]).catch(() => []);
+ ${scope.excludePrivate ? `AND ${privatePagesFilterForCaller('pages')}` : ''}`, [norms, sources, types]).catch(() => []);
})();
const [aliasHits, titleRows, caseRows] = await Promise.all([
engine.resolveAliases(norms, scope).catch(() => new Map<string, Array<{ slug: string; source_id: string }>>()),
diff --git a/src/core/search/alias-hop.ts b/src/core/search/alias-hop.ts
index 6555007e76..8e3c2ef51c 100644
--- a/src/core/search/alias-hop.ts
+++ b/src/core/search/alias-hop.ts
@@ -8,7 +8,7 @@ import type { SearchResult } from '../types.ts';
import { pageLeadSource, projectedLead } from '../page-window/bounded-lead.ts';
import { isIdentityEntity } from '../entities/resolve.ts';
import { normalizeAlias } from './alias-normalize.ts';
-import { isPrivatePage } from './private-visibility.ts';
+import { isPrivatePageForCaller } from './private-visibility.ts';
// T3 — free-text alias hop tuning.
const ALIAS_HOP_PRESENT_BOOST = 1.10; // bounded boost when canonical already in results
@@ -219,7 +219,7 @@ async function fetchAliasCanonical(
// #4352 — the alias inject path bypasses the engines' SQL visibility
// clause (getPage, not search); re-apply the private predicate here so
// an untrusted caller can't hop into a `visibility: private` page.
- if (opts.excludePrivate && isPrivatePage(page)) return null;
+ if (opts.excludePrivate && isPrivatePageForCaller(page)) return null;
return page;
}
diff --git a/src/core/search/collapse.ts b/src/core/search/collapse.ts
index 0366f51e6c..72cb460873 100644
--- a/src/core/search/collapse.ts
+++ b/src/core/search/collapse.ts
@@ -34,7 +34,7 @@ import type { BrainEngine } from '../engine.ts';
import type { SearchResult } from '../types.ts';
import { boundedBodyPrefixSql, pageLeadSource, projectedLead } from '../page-window/bounded-lead.ts';
import { type IdentityTierOpts, isExcludedIdentity } from './alias-hop.ts';
-import { isPrivatePage } from './private-visibility.ts';
+import { isPrivatePageForCaller } from './private-visibility.ts';
export type CollapseReason = 'twin' | 'redirect' | 'family';
export interface CollapsedRef { slug: string; source_id?: string; reason: CollapseReason }
@@ -204,7 +204,7 @@ async function readTarget(engine: BrainEngine, sourceId: string, slug: string, s
if (opts.sourceId && opts.sourceId !== sourceId) return null;
try {
const page = await engine.getPage(slug, { sourceId, excludePrivate: opts.excludePrivate });
- if (!page || (opts.excludePrivate && isPrivatePage(page))) return null;
+ if (!page || (opts.excludePrivate && isPrivatePageForCaller(page))) return null;
const lead = await projectedLead(engine, { slug: page.slug, source_id: page.source_id ?? sourceId, compiled_truth: await pageLeadSource(engine, page) });
if (!lead.trim()) return null;
return {
diff --git a/src/core/search/exact-scan.ts b/src/core/search/exact-scan.ts
index 797c09a42a..4caa1d3e13 100644
--- a/src/core/search/exact-scan.ts
+++ b/src/core/search/exact-scan.ts
@@ -33,7 +33,7 @@
import type { BrainEngine } from '../engine.ts';
import type { TrustTier } from '../trust/tier.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
-import { privatePagesFilterFragment } from './private-visibility.ts';
+import { privatePagesFilterForCaller } from './private-visibility.ts';
import { pageEligibleSql } from '../eligibility/sql.ts';
import { buildHardExcludeClause } from './sql-ranking.ts';
import { escapeLikePattern } from './sql-ranking.ts';
@@ -134,7 +134,7 @@ export function buildExactBatchStatement(opts: ExactScanOpts, after: number, bat
else if (opts.sourceId) pageFilters.push('p.source_id = ' + add(opts.sourceId));
if (opts.types?.length) pageFilters.push('p.type = ANY(' + add(opts.types) + '::text[])');
if (opts.slugPrefix) pageFilters.push('p.slug LIKE ' + add(escapeLikePattern(opts.slugPrefix) + '%') + " ESCAPE '\\'");
- if (opts.excludePrivate) pageFilters.push(privatePagesFilterFragment('p'));
+ if (opts.excludePrivate) pageFilters.push(privatePagesFilterForCaller('p'));
if (opts.minTrust) pageFilters.push(pageEligibleSql('p', { floor: opts.minTrust }));
const hardExclude = buildHardExcludeClause('p.slug', opts.excludeSlugPrefixes);
const safe = opts.remote ? ` AND ${safeChunksFilter('p')}` : '';
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 1b396c86c1..0e1e8b49e0 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -20,7 +20,9 @@
* behind SearchOpts.excludePrivate; this resolver decides whether to set it.
*/
+import { AsyncLocalStorage } from 'node:async_hooks';
import type { BrainEngine } from '../engine.ts';
+import { isValidSourceId } from '../source-id.ts';
export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';
@@ -63,6 +65,55 @@ export function privatePagesFilterFragmentFast(pageAlias: string): string {
OR ${privatePagesFilterFragment(pageAlias)})`;
}
+/**
+ * GBRA-156: the sources whose private pages the current remote read may see,
+ * from its grant's `private_pages: granted_sources` axis (the sources the
+ * grant names explicitly; never the no-grant floor, federation, an OAuth
+ * client's bound source or a request's `source_ids`). Set only by MCP
+ * dispatch around a non-mutating operation; empty everywhere else (local
+ * CLI, writes, jobs, cycles), so every other path keeps the rule above.
+ */
+const privateReadable = new AsyncLocalStorage<readonly string[]>();
+
+/** Runs `fn` with `sourceIds` as the private-readable set; an invalid id empties the whole set (fail closed). */
+export function withPrivateReadableSources<T>(sourceIds: readonly string[] | undefined, fn: () => T): T {
+ const ids = sourceIds?.length && sourceIds.every(isValidSourceId) ? Object.freeze([...new Set(sourceIds)]) : Object.freeze([]);
+ return privateReadable.run(ids, fn);
+}
+
+/** The private-readable set of the current read; empty outside a granted remote read. */
+export function privateReadableSources(): readonly string[] {
+ return privateReadable.getStore() ?? [];
+}
+
+/**
+ * `visiblePredicate`, widened to rows whose source (`sourceIdSql`, a
+ * code-provided column reference) is in the current private-readable set.
+ * The ids are embedded as literals: each passed isValidSourceId, whose
+ * alphabet has no quote or backslash.
+ */
+export function orPrivateReadableSource(sourceIdSql: string, visiblePredicate: string): string {
+ const ids = privateReadableSources();
+ if (ids.length === 0) return visiblePredicate;
+ return `(${sourceIdSql} IN (${ids.map(id => `'${id}'`).join(', ')}) OR ${visiblePredicate})`;
+}
+
+/** privatePagesFilterFragment for a remote read: a page in a private-readable source passes. Read sites only; derived-visibility decisions keep the plain fragment. */
+export function privatePagesFilterForCaller(pageAlias: string): string {
+ return orPrivateReadableSource(`${pageAlias}.source_id`, privatePagesFilterFragment(pageAlias));
+}
+
+/** privatePagesFilterFragmentFast for a remote read. */
+export function privatePagesFilterFastForCaller(pageAlias: string): string {
+ return orPrivateReadableSource(`${pageAlias}.source_id`, privatePagesFilterFragmentFast(pageAlias));
+}
+
+/** isPrivatePage for a remote read: false for a page whose `source_id` is private-readable; a row without `source_id` keeps the plain rule. */
+export function isPrivatePageForCaller(page: { type?: string | null; frontmatter?: unknown; source_id?: string | null }): boolean {
+ if (!isPrivatePage(page)) return false;
+ return !(typeof page.source_id === 'string' && privateReadableSources().includes(page.source_id));
+}
+
/**
* Declared lineage: a page whose frontmatter `derived_from` names a page (one
* slug or a list, `.md` optional) that is explicitly `visibility: private` in
@@ -232,6 +283,24 @@ export function privateTimelineEventFilterFragment(timelineAlias: string): strin
))`;
}
+/** privateLinkOriginFilterFragment for a remote read: an origin page in a private-readable source passes. */
+export function privateLinkOriginFilterForCaller(linkAlias: string): string {
+ return `(${linkAlias}.origin_page_id IS NULL OR EXISTS (
+ SELECT 1 FROM pages origin_private
+ WHERE origin_private.id = ${linkAlias}.origin_page_id
+ AND ${privatePagesFilterForCaller('origin_private')}
+ ))`;
+}
+
+/** privateTimelineEventFilterFragment for a remote read. */
+export function privateTimelineEventFilterForCaller(timelineAlias: string): string {
+ return `(${timelineAlias}.event_page_id IS NULL OR EXISTS (
+ SELECT 1 FROM pages event_private
+ WHERE event_private.id = ${timelineAlias}.event_page_id
+ AND ${privatePagesFilterForCaller('event_private')}
+ ))`;
+}
+
/**
* Fact-row twin for ontology provenance: hide an observation whose provenance
* page (`source_markdown_slug`, looked up in the fact's own source) is
@@ -294,7 +363,7 @@ export async function findPrivateOnlySlugs(
${opts.includeDeleted ? '' : 'AND p.deleted_at IS NULL'}
${scopeClause}
GROUP BY p.slug
- HAVING bool_and(NOT (${privatePagesFilterFragment('p')}))`,
+ HAVING bool_and(NOT (${privatePagesFilterForCaller('p')}))`,
params,
);
return new Set(rows.map(r => r.slug));
diff --git a/src/core/search/read-policy-sql.ts b/src/core/search/read-policy-sql.ts
index 0985972dfb..d189d016a1 100644
--- a/src/core/search/read-policy-sql.ts
+++ b/src/core/search/read-policy-sql.ts
@@ -1,5 +1,5 @@
import type { PageReadScope, PageReadPolicy } from '../types.ts';
-import { privatePagesFilterFragment } from './private-visibility.ts';
+import { privatePagesFilterForCaller } from './private-visibility.ts';
import { quarantineFilterFragment } from '../quarantine.ts';
import { pageEligibleSql } from '../eligibility/sql.ts';
@@ -24,7 +24,7 @@ export function pageReadFilter(
params.push(scope.sourceId);
clauses.push(`${alias}.source_id = $${params.length}`);
}
- if (scope?.excludePrivate) clauses.push(privatePagesFilterFragment(alias));
+ if (scope?.excludePrivate) clauses.push(privatePagesFilterForCaller(alias));
if (scope?.minTrust || scope?.suppressFlagged) clauses.push(pageEligibleSql(alias, { floor: scope.minTrust, suppressFlagged: scope.suppressFlagged }));
if (live) clauses.push(
`${alias}.deleted_at IS NULL`,
diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.ts
index b9cd6f3ffb..fafdf711c1 100644
--- a/src/core/search/sql-ranking.ts
+++ b/src/core/search/sql-ranking.ts
@@ -19,7 +19,7 @@
import { quarantineFilterFragment } from '../quarantine.ts';
import { unverifiedExtractionFragment } from '../extraction-review.ts';
-import { privatePagesFilterFragment } from './private-visibility.ts';
+import { privatePagesFilterForCaller } from './private-visibility.ts';
import { chunkVisibleFilter, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';
import { pageEligibleSql } from '../eligibility/sql.ts';
import type { TrustTier } from '../trust/tier.ts';
@@ -205,7 +205,7 @@ export function buildVisibilityClause(
// #4352 remediation: the predicate text lives ONCE in private-visibility.ts
// (shared with listPages + the relational-arm hydrate) so it cannot drift.
const privateClause = opts?.excludePrivate
- ? ` AND ${privatePagesFilterFragment(pageAlias)}`
+ ? ` AND ${privatePagesFilterForCaller(pageAlias)}`
: '';
const chunksClause = requiresSafeChunks(opts) ? ` AND ${safeChunksFilter(pageAlias)}` : '';
// C4: a pinned question's page holds only the question and owner notes; it is
diff --git a/src/core/similar-pages.ts b/src/core/similar-pages.ts
index 1f33d339f3..06bc5f374f 100644
--- a/src/core/similar-pages.ts
+++ b/src/core/similar-pages.ts
@@ -13,7 +13,7 @@
*/
import type { BrainEngine } from './engine.ts';
import { normalizeAlias } from './search/alias-normalize.ts';
-import { privatePagesFilterFragment } from './search/private-visibility.ts';
+import { privatePagesFilterForCaller } from './search/private-visibility.ts';
export type SimilarPageEvidence = 'exact_title' | 'alias' | 'same_name_other_directory' | 'similar_title';
@@ -37,7 +37,7 @@ export async function findSimilarPages(engine: Pick<BrainEngine, 'executeRaw'>,
const dir = input.slug.includes('/') ? input.slug.slice(0, input.slug.indexOf('/')) : '';
// ILIKE without wildcards is an exact case-insensitive match the title
// trigram index (idx_pages_trgm) serves; % and _ in the title are escaped.
- const privacy = input.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '';
+ const privacy = input.excludePrivate ? ` AND ${privatePagesFilterForCaller('p')}` : '';
const rows = await engine.executeRaw<{ slug: string; evidence: SimilarPageEvidence }>(`
WITH hits AS (
SELECT NULL::text AS slug, 'page_exists' AS evidence, 0 AS tier, 0::real AS sim FROM pages p
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 8de556843f..1cfa4f6509 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -306,10 +306,10 @@ export async function selectEntityCandidates(
scope: EntityLookupScope,
opts: { omitQuarantined?: boolean; suggest?: boolean; variants?: boolean } = {},
): Promise<EntityCandidates> {
- const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterForCaller } = await import('../search/private-visibility.ts');
// Predicate text lives ONCE (private-visibility.ts) — both card queries
// below select `FROM pages` unaliased, so qualify with the table name.
- const privatePredicate = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '';
+ const privatePredicate = scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('pages')}` : '';
const norm = normalizeAlias(trimmed);
const titleLc = trimmed.toLowerCase();
@@ -403,7 +403,7 @@ export async function selectEntityCandidates(
const variants = opts.variants && await nameVariantsEnabled(engine)
? await resolveNameVariant<CardPageRow>(engine, sourceId, trimmed, {
selectColumns: CARD_ROW_COLUMNS, privatePredicate, entityTypes: scope.entityTypes, omitQuarantined: opts.omitQuarantined,
- retirementPrivacy: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '' })
+ retirementPrivacy: scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('p')}` : '' })
: { matches: [] };
const variantSuggestions = (matches: typeof variants.matches): EntitySuggestion[] => matches.map(m => ({
slug: m.row.slug, title: m.row.title ?? m.row.slug, create_safety: 'exists', source_id: sourceId }));
@@ -506,11 +506,11 @@ export async function buildEntityCard(
await readCardIdentity(engine, hitSource, row, { excludePrivate: scope.excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }));
await attachCardRecords(engine, hitSource, card, opts, scope.excludePrivate);
if (await nameVariantsEnabled(engine)) {
- const { privatePagesFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterForCaller } = await import('../search/private-visibility.ts');
const duplicates = await readPossibleDuplicates<CardPageRow>(engine, hitSource, row, {
selectColumns: CARD_ROW_COLUMNS, entityTypes: scope.entityTypes, omitQuarantined: opts.omitQuarantined,
- privatePredicate: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('pages')}` : '',
- retirementPrivacy: scope.excludePrivate ? ` AND ${privatePagesFilterFragment('p')}` : '' });
+ privatePredicate: scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('pages')}` : '',
+ retirementPrivacy: scope.excludePrivate ? ` AND ${privatePagesFilterForCaller('p')}` : '' });
if (duplicates.length) card.possible_duplicates = duplicates;
}
// #7161: a thin card while mentions are behind may be a stale stub; show where the name appears in text.
@@ -583,9 +583,9 @@ async function assembleCard(
const visibility = remote ? (['world'] as ('private' | 'world')[]) : undefined;
// Facts saved about this entity may sit under a sibling page or the bare subject slug (siblings.ts).
const factSlugs = await factEntitySlugs(engine, sourceId, pageSlug, { excludePrivate }).catch(() => [pageSlug]);
- const { privatePagesFilterFragment, privateLinkOriginFilterFragment, privateProvenanceFilterFragment } = await import('../search/private-visibility.ts');
+ const { privatePagesFilterForCaller, privateLinkOriginFilterForCaller, privateProvenanceFilterFragment } = await import('../search/private-visibility.ts');
const inboundPrivacy = excludePrivate
- ? ` AND ${privatePagesFilterFragment('f')} AND ${privateLinkOriginFilterFragment('l')}`
+ ? ` AND ${privatePagesFilterForCaller('f')} AND ${privateLinkOriginFilterForCaller('l')}`
: '';
// Parallel depth-1 reads — every arm individually fail-soft so a partial
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 8007d03b52..35eb23b62f 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -14,6 +14,7 @@ import type { OperationContext, AuthInfo } from '../core/operations.ts';
import type { OperationMeta } from '../core/ops/contract.ts';
import { loadConfig } from '../core/config.ts';
import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';
+import { withPrivateReadableSources } from '../core/search/private-visibility.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';
@@ -861,6 +862,8 @@ export function buildOperationContext(
};
}
+const WORLD_ONLY_PACK_OPS = new Set(['context_pack', 'delta']);
+
/**
* Resolve operation, validate params, build context, invoke handler, format result.
*
@@ -876,9 +879,14 @@ export async function dispatchToolCall(
// #6721: a read op answers every config read from one snapshot of the table
// (config-snapshot.ts); a write reads config live, so it sees its own writes.
// GBRA-156: and reads the brain identity and each local writer's credential once for its pre-submission checks.
- const run = () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, opts));
+ // GBRA-156: a remote read sees private pages only in the sources its grant names under private_pages: granted_sources.
+ // Writes, local callers and every path outside this call keep the empty set, so they hide or see exactly what they did.
+ // context_pack and delta stay world-only for every caller unless a trusted local one passes include_private, so no grant widens them.
+ const readOnly = operations.find(o => o.name === name)?.mutating === false;
+ const privateSources = readOnly && opts.remote !== false && !WORLD_ONLY_PACK_OPS.has(name) ? opts.auth?.privatePages?.sources : undefined;
+ const run = () => withPrivateReadableSources(privateSources, () => withRequestIdentityMemo(() => dispatchResolvedCall(engine, name, params, opts)));
if (name === 'search' || name === 'query') return withSearchConnectionBudget(() => withRequestConfigSnapshot(engine, run));
- return operations.find(o => o.name === name)?.mutating === false
+ return readOnly
? withRequestConfigSnapshot(engine, run)
: withoutRequestConfigSnapshot(run);
}