Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(visibility): remote page reads honor the privacy aliases by default (visibility.honor_aliases false opts out)
garrytan3051950b2284
diff --git a/src/commands/doctor/checks/derived-visibility.ts b/src/commands/doctor/checks/derived-visibility.tsindex 1083ab62bc..be994f114b 100644--- a/src/commands/doctor/checks/derived-visibility.ts+++ b/src/commands/doctor/checks/derived-visibility.ts@@ -14,7 +14,7 @@*/import type { BrainEngine } from '../../../core/engine.ts';import type { Check } from '../../doctor.ts';-import { derivationPrivateSql, privateSnapshotFilterFragment } from '../../../core/search/private-visibility.ts';+import { derivationPrivateSql, privateSnapshotFilterFragment, readHonorAliases } from '../../../core/search/private-visibility.ts';import { aliasOnlyPagesSql, worldFactsFromPrivateSources } from '../../../core/repair/visibility.ts';const FACT_SAMPLE = 50;@@ -22,6 +22,7 @@ const FACT_SAMPLE = 50;export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: string): Promise<Check> {const name = 'derived_visibility';try {+ const aliasesHonored = await readHonorAliases(engine);const [row] = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number; looser_events: number; alias_pages_without_visibility: number }>(`WITH derived AS (SELECT p.* FROM pages p WHERE p.deleted_at IS NULL ${sourceId ? 'AND p.source_id=$1' : ''}@@ -56,7 +57,8 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: strconst parts: string[] = [];if (unstamped + looser) parts.push(`${unstamped} derived page(s) have no explicit visibility (${row.unstamped_atoms} atoms, ${row.unstamped_concepts} concepts) `+ `and ${looser} are stored looser than their origin (${row.looser_events} chronicle events); remote reads treat the unstamped ones as private.`);- if (row.alias_pages_without_visibility) parts.push(`${row.alias_pages_without_visibility} page(s) mark themselves private with a privacy alias (access, confidentiality) but carry no visibility, so remote page reads treat them as world.`);+ if (row.alias_pages_without_visibility) parts.push(`${row.alias_pages_without_visibility} page(s) mark themselves private with a privacy alias (access, confidentiality) but carry no visibility. `+ + (aliasesHonored ? 'Remote page reads hide them (to show them: gbrain config set visibility.honor_aliases false).' : 'visibility.honor_aliases is false, so remote page reads show them.'));if (facts.length) parts.push(`${facts.length} active world fact(s) are held in or were extracted from a private page; ${readable.length} of them are readable by remote callers (ids in details.remotely_readable_fact_ids).`);parts.push('Preview: gbrain repair visibility — apply after the user agrees: gbrain repair visibility --apply');return { name, status: 'warn', details, message: parts.join(' ') };diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex b018e70b55..d8beeb3180 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1057,6 +1057,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GBRA-159 visibility hotfix.{ since: '0.60.341.0', text: 'Nothing derived from a private page is stored wider than the page. Facts extracted from a `visibility: private` page are private even when `facts.default_visibility` is world (before, a fact with no fence page was then returned to remote callers by recall and the entity card), and a page marked private only by `access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted` counts as private for its facts, chronicle events, timeline rows and remember saves. `remember` without a `visibility` now saves private when its target page is private or `facts.default_visibility` is explicitly private; otherwise the default stays world. Google Calendar events marked private or confidential sync as `visibility: private` pages, and a connector re-render keeps a page\'s private label. Remote page reads honor the privacy aliases only after `gbrain config set visibility.honor_aliases true`.' },{ since: '0.60.341.0', text: 'Doctor `derived_visibility` also reports pages that carry a privacy alias but no `visibility`, chronicle events of a private origin, and world facts held in or extracted from a private page (fact ids a remote caller can read today are listed). `gbrain repair visibility` previews all of them and, with `--apply` only, makes them private; nothing runs on upgrade.' },+ { since: 'TBD', text: 'Remote (MCP and HTTP) page reads now hide a page marked private only by a privacy alias (`access: private|restricted|confidential` or `confidentiality: confidential|secret|private|restricted`, with no `visibility`), as they hide `visibility: private` pages; local CLI reads are unchanged. To keep showing such pages to remote callers: `gbrain config set visibility.honor_aliases false`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/config.ts b/src/core/config.tsindex f646f91746..a365675a56 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1509,7 +1509,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// didn't specify one: 'private' (default) | 'world'. Resolved by// src/core/facts/visibility.ts; explicit caller values always win.'facts.default_visibility',- 'visibility.honor_aliases', // remote page reads honor `access`/`confidentiality` aliases on pages without `visibility`; default off (search/private-visibility.ts)+ 'visibility.honor_aliases', // remote page reads honor `access`/`confidentiality` aliases on pages without `visibility`; default on, false opts out (search/private-visibility.ts)'facts.entity_inference', // #5836: write-time subject inference kill switch (subject-infer.ts)'facts.candidate_fusion', // C2: 'rrf_free' (default, cosine arm) | 'interleave' (cosine + keyword; facts/single-prepare.ts)'facts.supersession_thresholds', // JSON {"provider:model@dims": number | "off"} (facts/supersession-threshold.ts)diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 1ebe448f6a..1b396c86c1 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -51,13 +51,13 @@ export function privatePagesFilterFragment(pageAlias: string): string {/*** `privatePagesFilterFragment` with a cheap first test: a page with no- * `visibility` or `derived_from` key (nor, while `visibility.honor_aliases` is on, a- * privacy-alias key) whose type is not atom, concept or event is visible by every rule+ * `visibility` or `derived_from` key (nor, unless the operator turned+ * `visibility.honor_aliases` off, a privacy-alias key) whose type is not atom, concept or event is visible by every rule* above, so only the remaining pages run the full check. For scans over thousands of* candidate pages (an entity's referrers).*/export function privatePagesFilterFragmentFast(pageAlias: string): string {- return `((${pageAlias}.frontmatter->'visibility' IS NULL AND ${pageAlias}.frontmatter->'derived_from' IS NULL${honorAliasEngines.size > 0+ return `((${pageAlias}.frontmatter->'visibility' IS NULL AND ${pageAlias}.frontmatter->'derived_from' IS NULL${honorAliases()? `\n AND ${pageAlias}.frontmatter->'access' IS NULL AND ${pageAlias}.frontmatter->'confidentiality' IS NULL` : ''}AND ${pageAlias}.type NOT IN ('atom', 'concept', 'event'))OR ${privatePagesFilterFragment(pageAlias)})`;@@ -88,13 +88,12 @@ function declaredLineagePrivateSql(p: string): string {* pair it with privatePagesFilterFragment on the live page. A page carrying the* `pinned_question` marker is private whatever its `visibility` says (pinned* questions are owner-private, src/core/questions/pages.ts). A page with no- * `visibility` but a privacy alias is private here only while the operator has- * set `visibility.honor_aliases`; the row-side isPrivatePage re-check that some- * readers run after this SQL filter does not consult the flag.+ * `visibility` but a privacy alias is private too, unless the operator turned+ * `visibility.honor_aliases` off; the row-side isPrivatePage applies the same rule.*/export function privateSnapshotFilterFragment(alias: string): string {return `(COALESCE(${alias}.frontmatter->>'visibility', CASE WHEN ${derivedPageSql(alias)} THEN 'private' ELSE 'world' END) <> 'private'- AND NOT COALESCE(${alias}.frontmatter ? 'pinned_question', false)${honorAliasEngines.size > 0+ AND NOT COALESCE(${alias}.frontmatter ? 'pinned_question', false)${honorAliases()? `\n AND NOT (${alias}.frontmatter->>'visibility' IS NULL AND ${privacyAliasSql(alias)})` : ''})`;}@@ -141,7 +140,7 @@ export type Visibility = 'private' | 'world';* values that mean private. Matching is case-insensitive on the trimmed value.* Everything derived from an aliased page (facts, chronicle events, timeline* rows, remember saves into it) is private. Remote page reads honor the aliases- * only when the operator sets `visibility.honor_aliases` (default off).+ * too unless the operator sets `visibility.honor_aliases false`.*/export const PRIVACY_ALIASES: Readonly<Record<string, readonly string[]>> = {access: ['private', 'restricted', 'confidential'],@@ -159,17 +158,34 @@ function hasPrivacyAlias(frontmatter: Record<string, unknown>): boolean {/** SQL twin of hasPrivacyAlias on a page alias (a code-provided literal). */export function privacyAliasSql(alias: string): string {return `(${Object.entries(PRIVACY_ALIASES).map(([key, values]) =>- `lower(btrim(${alias}.frontmatter->>'${key}')) IN (${values.map(v => `'${v}'`).join(',')})`).join(' OR ')})`;+ `COALESCE(lower(btrim(${alias}.frontmatter->>'${key}')) IN (${values.map(v => `'${v}'`).join(',')}), false)`).join(' OR ')})`;}/**- * Brains in this process whose operator set `visibility.honor_aliases`, as last- * read by resolveExcludePrivatePages (the resolver every remote read runs before- * it builds SQL). The fragments are synchronous, so the flag is process-wide:- * one opted-in brain makes every brain in the process hide alias-only pages,- * which only ever hides more. Off (the default), the SQL carries no alias test.+ * `visibility.honor_aliases` per brain in this process, as last read by+ * resolveExcludePrivatePages (the resolver every remote read runs before it builds+ * SQL). The fragments are synchronous, so the setting is process-wide and leans+ * private: the aliases are honored unless a brain turned them off and no brain in+ * the process keeps them on. Unset means on.*/const honorAliasEngines = new Set<BrainEngine>();+const aliasOptOutEngines = new Set<BrainEngine>();+const ALIAS_OPT_OUT_VALUES = ['false', '0', 'off', 'no'];+function honorAliases(): boolean {+ return honorAliasEngines.size > 0 || aliasOptOutEngines.size === 0;+}++/** Reads this brain's `visibility.honor_aliases` into the process setting; true unless it is false/0/off/no. Unreadable keeps the last value. */+export async function readHonorAliases(engine: BrainEngine): Promise<boolean> {+ try {+ const optOut = ALIAS_OPT_OUT_VALUES.includes((await engine.getConfig(HONOR_ALIASES_KEY))?.trim().toLowerCase() ?? '');+ (optOut ? aliasOptOutEngines : honorAliasEngines).add(engine);+ (optOut ? honorAliasEngines : aliasOptOutEngines).delete(engine);+ return !optOut;+ } catch {+ return !aliasOptOutEngines.has(engine);+ }+}/** A page whatever is derived from it must not outrank: private to remote readers, or carrying a privacy alias. */export function isDerivationPrivate(page: { type?: string | null; frontmatter?: unknown }): boolean {@@ -240,6 +256,7 @@ export function isPrivatePage(page: { type?: string | null; frontmatter?: unknowconst frontmatter = typeof page.frontmatter === 'object' && page.frontmatter !== null? page.frontmatter as Record<string, unknown> : {};if (frontmatter.pinned_question != null) return true;+ if (frontmatter.visibility == null && honorAliases() && hasPrivacyAlias(frontmatter)) return true;const derived = page.type === 'atom' || page.type === 'question' || (page.type === 'concept' && frontmatter.synthesized_by != null);return (frontmatter.visibility ?? (derived ? 'private' : 'world')) === 'private';}@@ -290,6 +307,7 @@ let cache = new WeakMap<BrainEngine, { at: number; expose: boolean }>();export function __resetPrivateVisibilityCacheForTests(): void {cache = new WeakMap();honorAliasEngines.clear();+ aliasOptOutEngines.clear();}/**@@ -315,12 +333,7 @@ export async function resolveExcludePrivatePages(} catch {expose = false; // config unreadable → enforce (fail-closed)}- try {- const honor = (await engine.getConfig(HONOR_ALIASES_KEY))?.trim().toLowerCase() ?? '';- if (['true', '1', 'on', 'yes'].includes(honor)) honorAliasEngines.add(engine); else honorAliasEngines.delete(engine);- } catch {- // unreadable: keep the last value read- }+ await readHonorAliases(engine);cache.set(engine, { at: Date.now(), expose });}return !expose;diff --git a/test/visibility-fail-closed-derived-writes.test.ts b/test/visibility-fail-closed-derived-writes.test.tsindex 224150514e..4ada400077 100644--- a/test/visibility-fail-closed-derived-writes.test.ts+++ b/test/visibility-fail-closed-derived-writes.test.ts@@ -12,7 +12,7 @@* otherwise (the v1 contract).* - A page marked private only by a privacy alias (`access`, `confidentiality`)* counts as private for everything derived from it; remote page reads honor the- * aliases only behind `visibility.honor_aliases` (default off).+ * aliases by default; `visibility.honor_aliases false` opts out.* - Connector re-renders keep a page's private label; Google private events render private.* - The doctor check lists what is already labelled wider than its source, and the* visibility repair previews it and changes it only with --apply.@@ -243,17 +243,30 @@ describe('privacy aliases (access, confidentiality) count for everything derived});}, 120_000);- test('remote page reads honor the aliases only with visibility.honor_aliases on', async () => {+ test('remote page reads hide alias-private pages by default; local reads are unchanged; honor_aliases false opts out', async () => {await onEachEngine(async engine => {const s = await source(engine, false);- await putAliased(engine, s.sourceId, 'meetings/aliased-example', 'meeting', { access: 'private' });- const read = () => operationsByName.get_page!.handler(s.remote, { slug: 'meetings/aliased-example' }).then(() => true, () => false);- expect(await read()).toBe(true);- await engine.setConfig('visibility.honor_aliases', 'true');__resetPrivateVisibilityCacheForTests();- try { expect(await read()).toBe(false); }- finally { await engine.executeRaw("DELETE FROM config WHERE key='visibility.honor_aliases'"); __resetPrivateVisibilityCacheForTests(); }- expect(await read()).toBe(true);+ await putAliased(engine, s.sourceId, 'meetings/aliased-example', 'meeting', { access: 'private' }, 'Zephyrquill synthetic agenda.');+ await putAliased(engine, s.sourceId, 'meetings/open-example', 'meeting', { access: 'public' }, 'Zephyrquill open agenda.');+ const read = (ctx: OperationContext, slug: string) => operationsByName.get_page!.handler(ctx, { slug }).then(() => true, () => false);+ const found = async (ctx: OperationContext) => {+ const listed = await operationsByName.list_pages!.handler(ctx, { type: 'meeting' }) as unknown;+ const rows = (Array.isArray(listed) ? listed : (listed as { pages: unknown[] }).pages) as Array<{ slug: string }>;+ return rows.map(row => row.slug).filter(slug => slug.startsWith('meetings/')).sort();+ };+ expect(await read(s.remote, 'meetings/aliased-example')).toBe(false);+ expect(await read(s.remote, 'meetings/open-example')).toBe(true);+ expect(await found(s.remote)).toEqual(['meetings/open-example']);+ expect(await read(s.local, 'meetings/aliased-example')).toBe(true);+ expect(await found(s.local)).toEqual(['meetings/aliased-example', 'meetings/open-example']);+ await engine.setConfig('visibility.honor_aliases', 'false');+ __resetPrivateVisibilityCacheForTests();+ try {+ expect(await read(s.remote, 'meetings/aliased-example')).toBe(true);+ expect(await found(s.remote)).toEqual(['meetings/aliased-example', 'meetings/open-example']);+ } finally { await engine.executeRaw("DELETE FROM config WHERE key='visibility.honor_aliases'"); __resetPrivateVisibilityCacheForTests(); }+ expect(await read(s.remote, 'meetings/aliased-example')).toBe(false);});}, 120_000);});@@ -277,6 +290,7 @@ describe('already-affected rows: listed by doctor, previewed by the repair, chanexpect(check.details).toMatchObject({ alias_pages_without_visibility: 1, looser_events: 1, world_facts_from_private_sources: 1,world_facts_remotely_readable: 1, remotely_readable_fact_ids: [String(fact!.id)] });expect(check.message).not.toContain(meeting);+ expect(check.message).toContain('Remote page reads hide them (to show them: gbrain config set visibility.honor_aliases false).');const home = mkdtempSync(join(tmpdir(), 'gbrain-visibility-repair-'));try {