Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(context): hide private pages from volunteer_context, turn context, reflex resolve and compile-context (N8-1, N8-2)
garrytanbb4e997020e7
diff --git a/src/core/context/compile-view.ts b/src/core/context/compile-view.tsindex d040c77c1d..8a5ce80789 100644--- a/src/core/context/compile-view.ts+++ b/src/core/context/compile-view.ts@@ -18,7 +18,10 @@* not frontmatter) ∪ `listPages({updated_after: anchor−30d, sourceId,* limit})` for recency. The RESOLVED sourceId is passed into EVERY* listPages call and EVERY body read (`getPage(slug, {sourceId})`) —- * unscoped reads are the cross-source-leak invariant class.+ * unscoped reads are the cross-source-leak invariant class. Every arm also+ * passes `excludePrivate: true`: the compiled file lands in AGENTS.md /+ * CLAUDE.md imports, the same world-only injected-context posture as the+ * turn hook, so `visibility: private` pages never become candidates.** Score = recency-decay(vs anchor) × longest-prefix boost from* DEFAULT_SOURCE_BOOSTS, plus a fixed pin bonus for tag-pinned pages.@@ -191,14 +194,14 @@ async function fetchCandidates(const [prefixResults, tagPages, probe] = await Promise.all([Promise.all(prefixes.map((slugPrefix) =>- engine.listPages({ slugPrefix, sourceId, sort: 'slug', limit: PREFIX_CANDIDATE_LIMIT }),+ engine.listPages({ slugPrefix, sourceId, excludePrivate: true, sort: 'slug', limit: PREFIX_CANDIDATE_LIMIT }),),),// Tag arm — explicit pins (few by construction; slug sort for stable order).- engine.listPages({ tag: COMPILE_CONTEXT_TAG, sourceId, sort: 'slug' }),+ engine.listPages({ tag: COMPILE_CONTEXT_TAG, sourceId, excludePrivate: true, sort: 'slug' }),// Recency-anchor probe: the newest updated_at in the source (ties share// the timestamp, so tie order cannot change the probed VALUE).- engine.listPages({ sourceId, sort: 'updated_desc', limit: 1 }),+ engine.listPages({ sourceId, excludePrivate: true, sort: 'updated_desc', limit: 1 }),]);for (const pages of prefixResults) add(pages, false);add(tagPages, true);@@ -216,6 +219,7 @@ async function fetchCandidates(const recent = await engine.listPages({updated_after: windowStart,sourceId,+ excludePrivate: true,sort: 'updated_desc',limit: RECENCY_CANDIDATE_LIMIT,});diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.tsindex 42e28261f2..8bc5d16dd8 100644--- a/src/core/context/retrieval-reflex.ts+++ b/src/core/context/retrieval-reflex.ts@@ -20,7 +20,10 @@* Privacy (eng-review D5): the synopsis is taken from a SAFE source —* frontmatter `summary` if present, else the page body with takes/private-fact* fences STRIPPED (same boundary get_page applies to untrusted readers). Raw- * compiled_truth is never injected.+ * compiled_truth is never injected. Page visibility: `visibility: private`+ * and derived-private pages never resolve unless the caller passes+ * `excludePrivate: false` (trusted local only) — the same page filter remote+ * search applies (search/private-visibility.ts).*/import type { BrainEngine } from '../engine.ts';@@ -30,6 +33,7 @@ import { escapeLikePattern } from '../search/sql-ranking.ts';import { slugify } from '../entities/resolve.ts';import { stripTakesFence } from '../takes-fence.ts';import { stripFactsFence } from '../facts-fence.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';import type { EntityCandidate } from './entity-salience.ts';import { reflexPointerRationale } from './reflex-rationale.ts';import { logVolunteerEventsFireAndForget, volunteerEventRowsFrom } from './volunteer-events.ts';@@ -140,6 +144,15 @@ export interface ResolvePointersOpts {* config — the resolver itself never touches config (sync hot path).*/lexicalArms?: boolean;+ /**+ * Hide `visibility: private` (and derived-private) pages from every arm,+ * using the same predicate remote search applies. Default true+ * (fail-closed): pointers are injected into agent prompts, so the IPC+ * resolve, turn-context and direct-Postgres reflex lanes stay world-only.+ * Only a trusted local caller (volunteer_context with remote === false,+ * via resolveExcludePrivatePages) passes false.+ */+ excludePrivate?: boolean;}export interface PageRow {@@ -170,6 +183,7 @@ export async function resolveEntitiesToPointers(// v0.46.15 identity wave: the two new lexical arms (weak-alias + surname)// share one kill switch. Default ON; `false` reproduces pre-wave behavior.const lexicalArms = opts.lexicalArms !== false;+ const privacySql = opts.excludePrivate === false ? '' : `AND ${privatePagesFilterFragment('p')}`;// display lookup keyed by normalized query, so resolved slugs can recover a// human surface form for the pointer label.@@ -283,8 +297,8 @@ export async function resolveEntitiesToPointers(if (hitSlugs.size) {try {const liveRows = await engine.executeRaw<{ slug: string; source_id: string }>(- `SELECT slug, source_id FROM pages- WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND slug = ANY($2::text[])`,+ `SELECT p.slug, p.source_id FROM pages p+ WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[]) ${privacySql}`,[sourceIds, [...hitSlugs]],);for (const r of liveRows) liveAliasKeys.add(keyOf(r.source_id, r.slug));@@ -343,24 +357,24 @@ export async function resolveEntitiesToPointers(// class ("Labs", "Systems" as pseudo-surnames).rows = useSurnameArm? await engine.executeRaw<PageRow>(- `SELECT slug, source_id, title, type, frontmatter, compiled_truth- FROM pages- WHERE deleted_at IS NULL- AND source_id = ANY($1::text[])- AND ( lower(title) = ANY($2::text[])- OR slug = ANY($3::text[])- OR slug LIKE ANY($4::text[])- OR (lower(title) LIKE ANY($5::text[]) AND type = 'person') )`,+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth+ FROM pages p+ WHERE p.deleted_at IS NULL ${privacySql}+ AND p.source_id = ANY($1::text[])+ AND ( lower(p.title) = ANY($2::text[])+ OR p.slug = ANY($3::text[])+ OR p.slug LIKE ANY($4::text[])+ OR (lower(p.title) LIKE ANY($5::text[]) AND p.type = 'person') )`,[sourceIds, titlesLc, exactSlugs, slugSuffixes, surnamePatterns],): await engine.executeRaw<PageRow>(- `SELECT slug, source_id, title, type, frontmatter, compiled_truth- FROM pages- WHERE deleted_at IS NULL- AND source_id = ANY($1::text[])- AND ( lower(title) = ANY($2::text[])- OR slug = ANY($3::text[])- OR slug LIKE ANY($4::text[]) )`,+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth+ FROM pages p+ WHERE p.deleted_at IS NULL ${privacySql}+ AND p.source_id = ANY($1::text[])+ AND ( lower(p.title) = ANY($2::text[])+ OR p.slug = ANY($3::text[])+ OR p.slug LIKE ANY($4::text[]) )`,[sourceIds, titlesLc, exactSlugs, slugSuffixes],);} catch {@@ -373,9 +387,9 @@ export async function resolveEntitiesToPointers(if (aliasOnly.length) {try {const extra = await engine.executeRaw<PageRow>(- `SELECT slug, source_id, title, type, frontmatter, compiled_truth- FROM pages- WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND slug = ANY($2::text[])`,+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth+ FROM pages p+ WHERE p.deleted_at IS NULL ${privacySql} AND p.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[])`,[sourceIds, aliasOnly.map((p) => p.slug)],);for (const r of extra) rowByKey.set(keyOf(r.source_id, r.slug), r);@@ -457,11 +471,11 @@ export async function resolveEntitiesToPointers(if (cjkNorms.length) {try {const cjkRows = await engine.executeRaw<PageRow>(- `SELECT slug, source_id, title, type, frontmatter, compiled_truth- FROM pages- WHERE deleted_at IS NULL- AND source_id = ANY($1::text[])- AND ( lower(title) = ANY($2::text[]) OR slug = ANY($3::text[]) )`,+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth+ FROM pages p+ WHERE p.deleted_at IS NULL ${privacySql}+ AND p.source_id = ANY($1::text[])+ AND ( lower(p.title) = ANY($2::text[]) OR p.slug = ANY($3::text[]) )`,[sourceIds, cjkNorms, cjkNorms],);const cjkHits = new Map<string, Array<{ slug: string; source_id: string }>>();diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.tsindex f972fd78b6..3cd344897b 100644--- a/src/core/context/turn-context.ts+++ b/src/core/context/turn-context.ts@@ -6,7 +6,8 @@* existing, deterministic sources —** 1. reflex pointers — extractCandidatesFromWindow → resolveEntitiesToPointers- * (slug-only suppression, the windowed contract)+ * (slug-only suppression, the windowed contract;+ * private pages excluded like remote search, N8-2)* 2. volunteered pages — volunteerContext (confidence-gated, ≤3, deduped* against section 1 via excludeSlugs)* 3. hot facts — getBrainHotMemoryMeta's cache + shape [ENG-11], with@@ -240,6 +241,7 @@ export async function assembleTurnContext(suppression: 'slug-only',maxPointers: DEFAULT_MAX_POINTERS,lexicalArms: opts.lexicalArms,+ excludePrivate: true,});pointers = block?.pointers ?? [];}@@ -261,6 +263,7 @@ export async function assembleTurnContext(// v0.46.15+ lexical-arms kill switch rides the same threading as the// pointer arm above (ResolvePointersOpts.lexicalArms).lexicalArms: opts.lexicalArms,+ excludePrivate: true,});}} catch {diff --git a/src/core/context/volunteer.ts b/src/core/context/volunteer.tsindex c4a491015e..d5c934eaaf 100644--- a/src/core/context/volunteer.ts+++ b/src/core/context/volunteer.ts@@ -71,6 +71,8 @@ export interface VolunteerOpts {minConfidence?: number;/** v0.46.15: lexical-arms kill switch — see ResolvePointersOpts.lexicalArms. */lexicalArms?: boolean;+ /** Private-page filter — see ResolvePointersOpts.excludePrivate (default true). */+ excludePrivate?: boolean;}/** Shared wire protocol for window turns — watch.ts imports this so the two@@ -287,6 +289,7 @@ export async function volunteerContext(suppression: ropts.suppression,maxPointers: ropts.maxPointers,lexicalArms: ropts.lexicalArms,+ excludePrivate: opts.excludePrivate,}),candidates,turns.length,diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex d901b07164..ced82a3837 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -79,6 +79,7 @@ const volunteer_context: Operation = {const turns = parseWindow(p.window);const { loadConfig: loadCfgForArms } = await import('../config.ts');const { lexicalArmsEnabled } = await import('../context/reflex.ts');+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');const pages = await volunteerContext(ctx.engine, turns, {sourceIds,priorContext: typeof p.prior_context === 'string' ? p.prior_context : undefined,@@ -87,6 +88,8 @@ const volunteer_context: Operation = {// v0.46.15+ kill switch for the lexical recall arms (weak-alias +// surname) — file-plane gate, threaded per ResolvePointersOpts.lexicalArms: lexicalArmsEnabled(loadCfgForArms()),+ // N8-1: the same private-page gate remote search applies.+ excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote),});// Feedback-loop logging: fire-and-forget batched INSERT through thediff --git a/test/compile-view.test.ts b/test/compile-view.test.tsindex e3a20efc96..180268ff0d 100644--- a/test/compile-view.test.ts+++ b/test/compile-view.test.ts@@ -18,6 +18,7 @@ import {type CompileViewInput,} from '../src/core/context/compile-view.ts';import { loadSensitivityConfig } from '../src/core/context/sensitivity-scan.ts';+import { isPrivatePage } from '../src/core/search/private-visibility.ts';import * as tokenBudget from '../src/core/search/token-budget.ts';import type { Page, PageFilters, GetPageOpts } from '../src/core/types.ts';@@ -60,6 +61,7 @@ function makeEngine(pages: Page[]): CompileViewEngine {async listPages(filters: PageFilters = {}) {let rows = pages.slice();if (filters.sourceId) rows = rows.filter((p) => p.source_id === filters.sourceId);+ if (filters.excludePrivate) rows = rows.filter((p) => !isPrivatePage(p));if (filters.slugPrefix) rows = rows.filter((p) => p.slug.startsWith(filters.slugPrefix!));if (filters.tag) {rows = rows.filter((p) => {@@ -271,6 +273,20 @@ describe('compileView — recency arm (adversarial review: newest-first + tie-dr});});+describe('compileView — private pages', () => {+ test('a visibility: private page never reaches the compiled file on any arm (N8 context-path audit)', async () => {+ const secret = { visibility: 'private', tags: ['compile-context'] };+ const engine = makeEngine([+ page('people/public-person', { title: 'Public Person' }),+ page('people/secret-person', { title: 'SECRETTITLE', compiled_truth: 'SECRETBODY line.', frontmatter: secret }),+ page('notes/recent-secret', { title: 'RECENTSECRET', frontmatter: { visibility: 'private' }, updated_at: new Date('2026-08-02T00:00:00.000Z') }),+ ]);+ const out = await compileView(input(engine));+ expect(out.text).toContain('people/public-person');+ for (const marker of ['SECRETTITLE', 'SECRETBODY', 'secret-person', 'RECENTSECRET']) expect(out.text).not.toContain(marker);+ });+});+describe('compileView — source isolation + read errors', () => {test('duplicate slug across sources compiles the requested source body', async () => {const pages = [diff --git a/test/reflex-private-visibility.test.ts b/test/reflex-private-visibility.test.tsnew file mode 100644index 0000000000..2db505bb23--- /dev/null+++ b/test/reflex-private-visibility.test.ts@@ -0,0 +1,119 @@+/**+ * Ambient recall must not widen what remote search returns (gbrain-evals+ * N8-1 / N8-2). volunteer_context resolved a `visibility: private` page by+ * title, alias or surname and returned its title and body synopsis to a+ * remote caller, and the per-turn hook block (assembleTurnContext, turn+ * mode) injected the same page. Remote callers on every transport, the+ * turn block and the reflex resolver's default now hide private and+ * derived-private pages; the trusted local caller still sees them.+ *+ * Synthetic data only.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { assembleTurnContext } from '../src/core/context/turn-context.ts';+import { resolveEntitiesToPointers } from '../src/core/context/retrieval-reflex.ts';+import { extractCandidatesFromWindow } from '../src/core/context/entity-salience.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';++let engine: PGLiteEngine;+const config = { engine: 'pglite' } as any;++const put = (slug: string, content: string) =>+ dispatchToolCall(engine, 'put_page', { slug, content }, { remote: false, sourceId: 'default', config });++const page = (title: string, type: string, visibility: string | null, aliases: string[], body: string) =>+ `---\ntype: ${type}\ntitle: ${JSON.stringify(title)}\n${visibility ? `visibility: ${visibility}\n` : ''}aliases: ${JSON.stringify(aliases)}\n---\n\n${body}\n`;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ __resetPrivateVisibilityCacheForTests();+ await put('people/zora-quillfeather', page('Zora Quillfeather', 'person', 'private', ['Zee'], 'Zora Quillfeather is a confidential contact, code PRIVMARK1.'));+ await put('atoms/velmora-claim', page('Velmora Claim', 'atom', null, [], 'Velmora Claim derived ATOMMARK1 statement.'));+ await put('companies/harbor-logistics', page('Harbor Logistics', 'company', 'world', ['Harbor'], 'Harbor Logistics is a shipping partner WORLDMARK1.'));+});++afterAll(async () => {+ await engine.disconnect();+});++const HIDDEN = ['people/zora-quillfeather', 'PRIVMARK1', 'Zora Quillfeather', 'atoms/velmora-claim', 'ATOMMARK1'];++const WINDOWS = [+ 'user: Lunch with Zora Quillfeather and Harbor Logistics went well.',+ 'user: Zee called about Harbor Logistics again.',+ 'user: Did Quillfeather reply? Harbor Logistics is waiting.',+ 'user: The Velmora Claim came up while reviewing Harbor Logistics.',+];++const remoteCallers = {+ stdio: { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config },+ http: {+ remote: true,+ transport: 'http' as const,+ sourceId: 'default',+ takesHoldersAllowList: ['world'],+ config,+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default'] } as any,+ },+};++async function volunteer(window: string, opts: Record<string, unknown>) {+ const r = await dispatchToolCall(engine, 'volunteer_context', { window, min_confidence: 0.5 }, opts as any);+ expect(r.isError).toBeFalsy();+ return r.content[0].text;+}++describe('volunteer_context hides private pages from remote callers', () => {+ for (const [name, opts] of Object.entries(remoteCallers)) {+ for (const window of WINDOWS) {+ test(`${name}: ${window}`, async () => {+ const text = await volunteer(window, opts);+ for (const marker of HIDDEN) expect(text).not.toContain(marker);+ expect(text).toContain('companies/harbor-logistics');+ });+ }++ test(`${name}: remote search agrees (no private hit)`, async () => {+ const r = await dispatchToolCall(engine, 'search', { query: 'Zora Quillfeather' }, opts as any);+ expect(r.content[0].text).not.toContain('PRIVMARK1');+ });+ }++ test('local trusted caller still sees the private page', async () => {+ const text = await volunteer(WINDOWS[0], { remote: false, sourceId: 'default', config });+ expect(text).toContain('people/zora-quillfeather');+ expect(text).toContain('companies/harbor-logistics');+ });+});++describe('turn-context block never injects private pages', () => {+ for (const window of WINDOWS) {+ test(window, async () => {+ const r = await assembleTurnContext(engine, {+ sourceId: 'default',+ window: [{ role: 'user', text: window.replace(/^user: /, '') }],+ });+ for (const marker of HIDDEN) expect(r.text).not.toContain(marker);+ expect(r.text).toContain('companies/harbor-logistics');+ });+ }+});++describe('resolveEntitiesToPointers is world-only unless a caller widens it', () => {+ const candidates = () =>+ extractCandidatesFromWindow([{ role: 'user', text: 'Zora Quillfeather met Harbor Logistics.' }]);++ test('default excludes private pages (the ambient reflex and IPC resolve posture)', async () => {+ const block = await resolveEntitiesToPointers(engine, 'default', candidates());+ expect(block?.pointers.map((p) => p.slug)).toEqual(['companies/harbor-logistics']);+ });++ test('excludePrivate: false (trusted local) keeps the private page', async () => {+ const block = await resolveEntitiesToPointers(engine, 'default', candidates(), { excludePrivate: false });+ expect(block?.pointers.map((p) => p.slug).sort()).toEqual(['companies/harbor-logistics', 'people/zora-quillfeather']);+ });+});