Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip: owner opt-in
garrytan98566991e133
diff --git a/src/cli/as-preview.ts b/src/cli/as-preview.tsindex 0dbe349132..ddafc30bda 100644--- a/src/cli/as-preview.ts+++ b/src/cli/as-preview.ts@@ -1,7 +1,8 @@/*** GBRA-218 local `--as <member>`: an operation's reads previewed as one member.* The handler runs under that member's identity with the remote read policy- * (readers and privacy; GST-2059: the brain owner reads with privacy relaxed), while ctx.remote stays false, so upload confinement+ * (readers and privacy; GST-2059: the brain owner reads with privacy relaxed, and GST-2490: with access.owner_reads_restricted+ * on, past readers lists and rules too), while ctx.remote stays false, so upload confinement* and write trust are unchanged. An unknown or ill-formed member is refused* before any work.*/@@ -34,17 +35,20 @@ export async function openAsPreview(engine: BrainEngine, member: string | undefiif (member === undefined) return PASSTHROUGH;let identity: string[];let owner: boolean;+ let ownerReadsRestricted: boolean;try {const resolved = await (await import('../core/access/members.ts')).memberIdentity(engine, member);identity = resolved.identity;- owner = resolved.member === await (await import('../core/access/owner.ts')).ownerMemberId(engine);+ const ownerModule = await import('../core/access/owner.ts');+ owner = resolved.member === await ownerModule.ownerMemberId(engine);+ ownerReadsRestricted = owner && await ownerModule.ownerReadsRestrictedOn(engine);} catch (e: unknown) {await finishCliTeardown({ engine });exitCliError(e, command);}const { withCallerAccess } = await import('../core/search/private-visibility.ts');const folder = await (await import('../core/access/caller.ts')).folderAccessFor(engine, identity);- const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: !owner, owner, privateReadableSources: [] };+ const access = { identity, ...folder, applyRemoteReadPolicy: true, hidePrivate: !owner, owner, ownerReadsRestricted, privateReadableSources: [] };return {run: fn => withCallerAccess(access, fn),context: ctx => ({ ...ctx, accessIdentity: identity, applyRemoteReadPolicy: true }),diff --git a/src/commands/access.ts b/src/commands/access.tsindex f2d3df4d85..8d18ecddc7 100644--- a/src/commands/access.ts+++ b/src/commands/access.ts@@ -28,7 +28,7 @@ import { identityFor, normalizePrincipal, normalizeReaders } from '../core/accesimport { mayActForCovers, singleMemberAudience, type AudiencePrincipal } from '../core/access/audience.ts';import { linkMember, linkMemberByEmail, listMemberLinks, unlinkMember } from '../core/access/actor.ts';import { bindMemberSource, listMemberSources, unbindMemberSource } from '../core/access/member-sources.ts';-import { clearOwner, ownerMemberId, ownerView, setOwner, type OwnerView } from '../core/access/owner.ts';+import { clearOwner, ownerMemberId, ownerReadsRestrictedOn, ownerView, setOwner, setOwnerReadsRestricted, type OwnerView } from '../core/access/owner.ts';import {addGroup, addMember, assertAccessId, disableMember, enableMember, getMember, legacyTokenByName, listGroups, listMembers,parseIdList, previewRemoveGroup, previewRemoveMember, removeGroup, removeGroupMembers, removeMember, setMemberEmail, type MemberRecord,@@ -68,6 +68,10 @@ Owner (one member who owns this brain; credentials bound to it read every page,gbrain access owner Show the owner and the credentials that read as itgbrain access owner set <member> The member must be enabled; bind credentials with --member <id>gbrain access owner clear No owner: every caller reads under the ordinary policy+ gbrain access owner reads-restricted on|off+ Off by default. On: the owner's credentials also read pages that+ readers lists and folder or page rules keep to other members, and+ their derived pages and facts (never another member's member page)Serves several people (GST-363):gbrain access serves One or several, and why (config access.serves, else 2+ enabled members)@@ -141,6 +145,7 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: sif (!rows.length) {throw opError('not_found', `No page "${slug}"${sourceId ? ` in source ${sourceId}` : ''}.`, 'Check the slug with gbrain list or gbrain search.');}+ const optIn = await ownerReadsRestrictedOn(engine) ? await ownerMemberId(engine) : null;const members = await Promise.all((await listMembers(engine)).filter(m => m.status === 'enabled').map(async m => {const identity = identityFor(m.id, m.groups);return { id: m.id, identity, folder: await folderAccessFor(engine, identity) };@@ -159,6 +164,9 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: sif (admitted.length) allowed.push(id);}}+ const ownerOpened = !!optIn && (readers !== null || ruled) && !allowed.includes(optIn) && members.some(m => m.id === optIn)+ && (!row.slug.startsWith(MEMBER_PAGE_PREFIX) || row.slug === `${MEMBER_PAGE_PREFIX}${optIn}`);+ if (ownerOpened) allowed.push(optIn!);const notes = [readers === null ? (ruled ? 'No readable_by, but folder rules cover it: only members who meet every rule read it remotely.' : 'No readable_by: every caller entitled to the source reads it.'): readers.includes('!nobody') ? 'readable_by is malformed, so no remote caller reads it; fix the frontmatter.'@@ -166,6 +174,7 @@ export async function whoCanRead(engine: BrainEngine, slug: string, sourceId?: s...(readers !== null && ruled ? ['Folder rules cover it too: a member must meet readable_by and every rule.'] : []),...(priv ? ['visibility: private also applies: a member still needs private_pages: granted_sources on this source.'] : []),'Derived pages (atoms, facts, chronicle events) of a page that names readers are hidden from every remote caller.',+ ...(ownerOpened ? [`The owner (${optIn}) reads it too, and its derived pages and facts: access.owner_reads_restricted is on (gbrain access owner reads-restricted off turns it off).`] : []),];entries.push({ slug: row.slug, source_id: row.source_id, readers, private: priv, members: readers === null && !ruled ? 'every_source_reader' : allowed, note: notes.join(' ') });}@@ -181,6 +190,8 @@ export interface AccessCheckResult {verdict: 'reads_as_member' | 'unbound' | 'refused';/** GST-2059: the credential reads as the brain owner (config access.owner_member). */owner: boolean;+ /** GST-2490: access.owner_reads_restricted is on, so the owner's credentials read past readers lists and rules. */+ owner_reads_restricted: boolean;explanation: string;audience?: Array<{ principal: string; covered_by_may_act_for: boolean }>;}@@ -210,16 +221,21 @@ export async function accessCheck(engine: BrainEngine, target: { token?: string;const identity = live ? identityFor(member!.id, member!.groups) : [];const mayActFor = Array.isArray(row.may_act_for) ? (row.may_act_for as string[]) : null;const verdict: AccessCheckResult['verdict'] = !member ? 'unbound' : live ? 'reads_as_member' : 'refused';- const owner = live && member!.id === await ownerMemberId(engine);+ const ownerId = await ownerMemberId(engine);+ const owner = live && member!.id === ownerId;+ const ownerReadsRestricted = !!ownerId && await ownerReadsRestrictedOn(engine);const explanation = verdict === 'unbound' ? 'Bound to no member: reads every page its grant allows except pages that name readers (readable_by).': verdict === 'refused' ? `Bound to member "${member!.id}", which is ${member!.status}: the credential is refused at verification (access_member_disabled).`: `Reads as member "${member!.id}"${member!.groups.length ? ` (groups: ${member!.groups.join(', ')})` : ''}: pages naming readers are visible when they list the member or one of its groups, within the grant below.`- + (owner ? ' It is the brain owner: it also reads visibility: private pages, privacy-alias pages, derived and pinned-question pages and private facts in every source the grant reads.' : '');+ + (owner ? ' It is the brain owner: it also reads visibility: private pages, privacy-alias pages, derived and pinned-question pages and private facts in every source the grant reads.' : '')+ + (ownerReadsRestricted ? (owner+ ? ' access.owner_reads_restricted is on: in reads it also reads pages that readers lists and folder or page rules keep to other members, and their derived pages and facts, except another member's own member page.'+ : ` access.owner_reads_restricted is on: the brain owner (${ownerId}) also reads the pages this credential's readers lists and rules keep to it, except its own member page.`) : '');const result: AccessCheckResult = {credential,grant: { scopes: grant.scopes, sources: grant.sources, takes_holders: grant.takesHolders, private_pages: grant.privatePages,operations: grant.allowedOperations ?? 'unrestricted', revision: grant.revision },- member, identity, may_act_for: mayActFor, verdict, owner, explanation,+ member, identity, may_act_for: mayActFor, verdict, owner, owner_reads_restricted: ownerReadsRestricted, explanation,};if (target.as !== undefined) {const audience: NonNullable<AccessCheckResult['audience']> = [];@@ -355,6 +371,9 @@ function ownerLines(v: OwnerView): string[] {: ['Owner: none. Every remote caller reads under the ordinary policy (no visibility: private page without a grant).', 'Name one: gbrain access owner set <member>'];return [`Owner: ${v.owner}`,` Credentials that read as the owner (${v.bound_credentials.length}): ${v.bound_credentials.map(c => `${c.kind} ${c.name}`).join(', ') || 'none'}`,+ v.reads_restricted+ ? ' Owner reads member-restricted pages: on (access.owner_reads_restricted). Its credentials read pages that readers lists and folder or page rules keep to other members, and their derived pages and facts; never another member's own member page. Turn off: gbrain access owner reads-restricted off'+ : ' Owner reads member-restricted pages: off. It reads a page that names readers or sits under a rule only when listed. Turn on: gbrain access owner reads-restricted on',` Bind one: gbrain auth rescope --token <name> --member ${v.owner} (a stdio server: gbrain config set mcp.stdio_member ${v.owner})`];}@@ -374,8 +393,14 @@ async function ownerCmd(engine: BrainEngine, sub: string | undefined, args: striconst v = await clearOwner(engine);return print(json, v, () => ownerLines(v));}+ case 'reads-restricted': {+ const value = positionals(args)[0];+ if (value !== 'on' && value !== 'off') throw usageError('access owner reads-restricted needs on or off.', 'gbrain access owner reads-restricted on|off');+ const v = await setOwnerReadsRestricted(engine, value === 'on', { remote: false });+ return print(json, v, () => ownerLines(v));+ }default:- throw usageError(`Unknown access owner subcommand: ${sub}.`, 'Use gbrain access owner, gbrain access owner set <member> or gbrain access owner clear.');+ throw usageError(`Unknown access owner subcommand: ${sub}.`, 'Use gbrain access owner, gbrain access owner set <member>, gbrain access owner clear or gbrain access owner reads-restricted on|off.');}}diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex fcc7a614e6..2cb7388572 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -205,8 +205,10 @@ export async function resolveAudienceIdentities(engine: Pick<BrainEngine, 'execu* GST-2059: a caller bound to the brain owner (config access.owner_member) reads with its privacy relaxed in every* source its grant reads (owner), with no audience or an audience of the owner alone; member access stays.* GST-363: `stdioMember` is the member an unauthenticated stdio server was started with (serve --stdio-member).+ * GST-2490: `readOnly` (a non-mutating operation) lets an owner read under access.owner_reads_restricted; a write's+ * checks keep the owner's ordinary member access, so its pre-check and its publication agree.*/-export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string, audience?: readonly AudiencePrincipal[] | null, stdioMember?: string): Promise<Partial<CallerAccess>> {+export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | undefined, privateSources: readonly string[] | undefined, transport?: string, audience?: readonly AudiencePrincipal[] | null, stdioMember?: string, readOnly = false): Promise<Partial<CallerAccess>> {const [relaxed, remotePolicy] = await Promise.all([remotePrivacyRelaxed(engine), requestRemotePolicy(engine)]);const restricted = remotePolicy.restricted;if (audience?.length) {@@ -222,6 +224,7 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | uprivateReadableSources: single ? privateSources ?? [] : [],hidePrivate: single ? !relaxed && !owner : true,owner,+ ownerReadsRestricted: owner && readOnly && remotePolicy.ownerReadsRestricted === true,applyRemoteReadPolicy: false,restricted,remotePolicy,@@ -237,6 +240,7 @@ export async function remoteCallerAccess(engine: BrainEngine, auth: AuthInfo | uprivateReadableSources: privateSources ?? [],hidePrivate: !relaxed && !owner,owner,+ ownerReadsRestricted: owner && readOnly && remotePolicy.ownerReadsRestricted === true,applyRemoteReadPolicy: false,restricted,remotePolicy,diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.tsindex 9b454fd11f..10ddc11141 100644--- a/src/core/access/member-facts.ts+++ b/src/core/access/member-facts.ts@@ -194,7 +194,8 @@ export function readersSourcedFactSql(alias: string): string {export function callerIdentityKey(): string {const access = currentCallerAccess();if (!access.actor && !access.identity.length && !access.audienceIdentities.length && !access.audience) return '';- const parts = { actor: access.actor ? [access.actor.system, access.actor.member] : null, identity: access.identity, audience: access.audienceIdentities, entries: access.audience };+ const parts = { actor: access.actor ? [access.actor.system, access.actor.member] : null, identity: access.identity, audience: access.audienceIdentities, entries: access.audience,+ ...(access.ownerReadsRestricted ? { owner_reads_restricted: true } : {}) };return createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 16);}diff --git a/src/core/access/owner.ts b/src/core/access/owner.tsindex deb952c117..944bbeafe3 100644--- a/src/core/access/owner.ts+++ b/src/core/access/owner.ts@@ -5,9 +5,15 @@* `gbrain auth rescope --member <id>`) or a stdio server (config mcp.stdio_member) bound to that live member reads as* the owner (CallerAccess.owner, src/core/access/caller.ts). Everything lives in the database, so a repo-less brain* gets it unchanged. Only the trusted local CLI writes it.+ *+ * GST-2490: the owner opt-in, config access.owner_reads_restricted ('1' on, unset off). With it on, the owner's+ * credentials also read pages a readers list, folder rule or page rule would close to the owner (and their derived pages+ * and facts), except another member's own member page; see OWNER_READS_RESTRICTED_KEY. Off by default, set only by the+ * trusted local operator (setOwnerReadsRestricted refuses a remote caller).*/import type { BrainEngine } from '../engine.ts';-import { OWNER_MEMBER_KEY } from '../search/private-visibility.ts';+import { OWNER_MEMBER_KEY, OWNER_READS_RESTRICTED_KEY } from '../search/private-visibility.ts';+import { hostOnlyError } from '../ops/op-fix.ts';import { ACCESS_ID_RE } from './principals.ts';import { boundCredentials, memberIdentity } from './members.ts';import type { CredentialRef } from './members.ts';@@ -17,6 +23,8 @@ export interface OwnerView {/** The configured value when it names no enabled member (ill-formed, disabled, removed or missing): no caller reads as the owner. */inactive?: { value: string; reason: string };bound_credentials: CredentialRef[];+ /** GST-2490: access.owner_reads_restricted is on (the owner's credentials read past readers lists and rules). */+ reads_restricted: boolean;}/** The owner member id, or null when unset or ill-formed (fail closed). */@@ -32,15 +40,41 @@ export async function ownerMemberId(engine: Pick<BrainEngine, 'getConfig'>): Pro/** The configured owner, whether it is live, and the credentials that read as it. */export async function ownerView(engine: BrainEngine): Promise<OwnerView> {const raw = (await engine.getConfig(OWNER_MEMBER_KEY))?.trim() ?? '';- if (!raw) return { owner: null, bound_credentials: [] };+ const reads_restricted = await ownerReadsRestrictedOn(engine);+ if (!raw) return { owner: null, bound_credentials: [], reads_restricted };try {const { member } = await memberIdentity(engine, raw);- return { owner: member, bound_credentials: await boundCredentials(engine, member) };+ return { owner: member, bound_credentials: await boundCredentials(engine, member), reads_restricted };} catch (e) {- return { owner: null, inactive: { value: raw, reason: e instanceof Error ? e.message : String(e) }, bound_credentials: [] };+ return { owner: null, inactive: { value: raw, reason: e instanceof Error ? e.message : String(e) }, bound_credentials: [], reads_restricted };}}+/** GST-2490: is access.owner_reads_restricted on? Unset, anything but '1', or unreadable is off (nothing widens). */+export async function ownerReadsRestrictedOn(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ try {+ return (await engine.getConfig(OWNER_READS_RESTRICTED_KEY))?.trim() === '1';+ } catch {+ return false;+ }+}++/**+ * GST-2490: turns the owner opt-in on or off. Only the trusted local operator may: a remote caller (anything whose+ * `remote` is not strictly false) is refused before anything is written.+ */+export async function setOwnerReadsRestricted(engine: BrainEngine, on: boolean, ctx: { remote?: boolean }): Promise<OwnerView> {+ if (ctx.remote !== false) {+ throw hostOnlyError({ remote: true, transport: 'http' }, 'permission_denied',+ 'Only the brain operator on the brain host turns the owner opt-in on or off, so nothing was changed.',+ ['gbrain', 'access', 'owner', 'reads-restricted', on ? 'on' : 'off'],+ 'Lets the owner's credentials read pages that readers lists and folder or page rules keep to other members. Whether the owner reads them is the brain operator's decision, never an agent's.');+ }+ if (on) await engine.setConfig(OWNER_READS_RESTRICTED_KEY, '1');+ else await engine.unsetConfig(OWNER_READS_RESTRICTED_KEY);+ return ownerView(engine);+}+/** Names the owner; refuses an ill-formed or non-enabled member before writing anything. */export async function setOwner(engine: BrainEngine, raw: unknown): Promise<OwnerView> {const { member } = await memberIdentity(engine, raw);@@ -51,5 +85,5 @@ export async function setOwner(engine: BrainEngine, raw: unknown): Promise<Owner/** Names no owner: every caller reads under the ordinary read policy again. */export async function clearOwner(engine: BrainEngine): Promise<OwnerView> {await engine.unsetConfig(OWNER_MEMBER_KEY);- return { owner: null, bound_credentials: [] };+ return { owner: null, bound_credentials: [], reads_restricted: await ownerReadsRestrictedOn(engine) };}diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex 108ee8417e..024d89bd2f 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -25,6 +25,7 @@ export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['mcp.stdio_member', // access/caller.ts (GBRA-218): binds a local stdio MCP server to one member; unbound, stdio reads no page that names readers'persistence.adopt_quiet_ms', // persistence/local-edit-adoption.ts (GST-1601): how long a local edit must be quiet before it is adopted, default 5000'access.owner_member', // access/owner.ts (GST-2059): the member who owns this brain; credentials bound to it read private pages (gbrain access owner set)+ 'access.owner_reads_restricted', // access/owner.ts (GST-2490): '1' lets owner-bound credentials read past readers lists and rules (gbrain access owner reads-restricted on)'access.serves', // access/serves.ts (GST-363): one or several; explicit wins over the enabled-member count (gbrain setup --serves several writes it)'mcp.stdio_may_act_for', // access/audience.ts (GBRA-231): whom a local stdio server may act for (_meta.on_behalf_of); unset, stdio refuses every audience'proposals.ttl_hours', 'proposals.max_pending_per_actor', 'proposals.max_pending_per_credential', // persistence/memory-proposals.ts: held QM proposal TTL (168 h) and pending caps (10 per person, 50 per credential)diff --git a/src/core/function-search-path.ts b/src/core/function-search-path.tsindex c282b22a8a..56501f219c 100644--- a/src/core/function-search-path.ts+++ b/src/core/function-search-path.ts@@ -24,7 +24,7 @@ export const LEGACY_SEARCH_PATH_SETTINGS = ['search_path=pg_catalog, public', 'sexport const PINNED_FUNCTION_NAMES = ['auto_enable_rls', 'bump_page_generation_clock_fn', 'bump_page_generation_fn', 'enforce_minion_queue_protocol','gbrain_access_derive_page_readers', 'gbrain_access_folder_rules', 'gbrain_access_mark_restricted', 'gbrain_access_norm_readers',- 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules',+ 'gbrain_access_origin_closed_to_owner', 'gbrain_access_origin_hidden_from_owner', 'gbrain_access_origin_restricted', 'gbrain_access_pending_covers', 'gbrain_access_readers', 'gbrain_access_stamp_folder_rules','gbrain_access_state_unreadable','gbrain_advance_page_revision', 'gbrain_advance_tag_revision', 'gbrain_bump_trust_generation','gbrain_clear_atom_page_state', 'gbrain_count_git_canonical_sources', 'gbrain_count_modifications', 'gbrain_forget_page_retrievals',diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.tsindex 454fa9ae4d..c813e863f2 100644--- a/src/core/minions/tools/brain-allowlist.ts+++ b/src/core/minions/tools/brain-allowlist.ts@@ -331,7 +331,7 @@ function brainTool(op: Operation, opts: BuildBrainToolsOpts): ToolDef {return withCallerAccess(access, () => withReadMode(readMode, async () => run(await attestedReadScope(ctx.engine, opCtx, actor.member, readMode === 'scope'))));})(): opCtx.auth- ? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor), run)+ ? await withCallerAccess(await remoteCallerAccess(ctx.engine, opCtx.auth, [], undefined, actingFor, undefined, op.mutating === false), run): await run();const rejection = op.name === 'put_page' ? putPageRejection(output) : null;if (rejection) throw new Error(rejection);diff --git a/src/core/schema-migrations/v304-access-owner-origin.ts b/src/core/schema-migrations/v304-access-owner-origin.tsnew file mode 100644index 0000000000..bdf565d31a--- /dev/null+++ b/src/core/schema-migrations/v304-access-owner-origin.ts@@ -0,0 +1,63 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// GST-2490 (G6 of GST-2476): the owner opt-in (config access.owner_reads_restricted). Derived pages (an atom, a+// synthesized concept or question, a Life Chronicle event, a derived_from page) of an origin that names readers or sits+// under a folder or page rule are hidden from every remote caller by gbrain_access_origin_restricted (v282, v283, v285),+// the brain owner included, even when the readers or the rule name the owner. With the opt-in on, an owner read uses+// gbrain_access_origin_hidden_from_owner instead: the same arms, but an origin hides its derivatives only when it is+// another member's own member page (memory/members/<id>, the owner's own excluded) or reads as nobody (pending+// coverage). The per-origin test is one function, gbrain_access_origin_closed_to_owner, so a later rule (say, "a caller+// reads a derivative when it reads every origin") swaps that test and keeps the arms. Nothing is rewritten and+// gbrain_access_origin_restricted is untouched, so every other caller reads exactly as before. No schema.sql mirror:+// like v282, v283 and v285, these exist only through migrations. Provisional number: renumbered at the merge slot.+export const v304: Migration = {+ version: 304,+ name: 'access_owner_origin',+ idempotent: true,+ sql: `+CREATE OR REPLACE FUNCTION gbrain_access_origin_closed_to_owner(o_source TEXT, o_slug TEXT, p_owner_page TEXT) RETURNS boolean+ LANGUAGE sql STABLE PARALLEL SAFE SET search_path = pg_catalog, public, pg_temp AS $fn$+ SELECT (starts_with(o_slug, 'memory/members/') AND o_slug IS DISTINCT FROM p_owner_page) OR gbrain_access_pending_covers(o_source, o_slug)+$fn$;+CREATE OR REPLACE FUNCTION gbrain_access_origin_hidden_from_owner(p_id INTEGER, p_source_id TEXT, p_type TEXT, fm JSONB, p_owner_page TEXT) RETURNS boolean+ LANGUAGE plpgsql STABLE PARALLEL SAFE SET search_path = pg_catalog, public, pg_temp AS $fn$+BEGIN+ IF p_type = 'atom' THEN+ IF EXISTS (SELECT 1 FROM pages o WHERE o.source_id = p_source_id AND o.slug IN (SELECT fm->>'source_slug' UNION SELECT a.canonical_slug FROM slug_aliases a WHERE a.source_id = p_source_id AND a.alias_slug = fm->>'source_slug'+ UNION SELECT h.new_slug FROM slug_rename_history h WHERE h.source_id = p_source_id AND h.old_slug = fm->>'source_slug')+ AND gbrain_access_origin_closed_to_owner(o.source_id, o.slug, p_owner_page)) THEN+ RETURN true;+ END IF;+ ELSIF p_type = 'question' OR (p_type = 'concept' AND fm->>'synthesized_by' IS NOT NULL) THEN+ IF EXISTS (SELECT 1 FROM links l JOIN pages i ON i.id = l.to_page_id+ WHERE l.from_page_id = p_id AND l.link_source = 'concept-provenance' AND l.link_type = 'synthesized_from'+ AND (gbrain_access_origin_closed_to_owner(i.source_id, i.slug, p_owner_page)+ OR EXISTS (SELECT 1 FROM pages io WHERE io.source_id = i.source_id+ AND io.slug IN (SELECT i.frontmatter->>'source_slug' UNION SELECT a.canonical_slug FROM slug_aliases a WHERE a.source_id = i.source_id AND a.alias_slug = i.frontmatter->>'source_slug'+ UNION SELECT h.new_slug FROM slug_rename_history h WHERE h.source_id = i.source_id AND h.old_slug = i.frontmatter->>'source_slug')+ AND gbrain_access_origin_closed_to_owner(io.source_id, io.slug, p_owner_page)))) THEN+ RETURN true;+ END IF;+ ELSIF p_type = 'event' AND fm->>'captured_via' LIKE 'life-chronicle:%' THEN+ IF EXISTS (SELECT 1 FROM pages c WHERE c.source_id = p_source_id AND c.slug IN (SELECT fm->'event'->>'depth' UNION SELECT a.canonical_slug FROM slug_aliases a WHERE a.source_id = p_source_id AND a.alias_slug = fm->'event'->>'depth'+ UNION SELECT h.new_slug FROM slug_rename_history h WHERE h.source_id = p_source_id AND h.old_slug = fm->'event'->>'depth')+ AND gbrain_access_origin_closed_to_owner(c.source_id, c.slug, p_owner_page)) THEN+ RETURN true;+ END IF;+ END IF;+ IF jsonb_typeof(fm->'derived_from') IN ('array', 'string') THEN+ RETURN EXISTS (SELECT 1 FROM pages d WHERE d.source_id = p_source_id+ AND gbrain_access_origin_closed_to_owner(d.source_id, d.slug, p_owner_page)+ AND d.slug = ANY(ARRAY(WITH declared(slug) AS (SELECT regexp_replace(x, '\\.md$', '') FROM jsonb_array_elements_text(+ CASE WHEN jsonb_typeof(fm->'derived_from') = 'array' THEN fm->'derived_from' ELSE jsonb_build_array(fm->'derived_from') END) AS x)+ SELECT slug FROM declared UNION SELECT a.canonical_slug FROM slug_aliases a JOIN declared ON a.alias_slug = declared.slug WHERE a.source_id = p_source_id+ UNION SELECT h.new_slug FROM slug_rename_history h JOIN declared ON h.old_slug = declared.slug WHERE h.source_id = p_source_id)));+ END IF;+ RETURN false;+END+$fn$;+`,+};diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 6400fc9b66..d66c711125 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -1322,6 +1322,7 @@ export function knobsHash(if (access.identity.length) parts.push(`xid=${createHash('sha256').update(access.identity.join(',')).digest('hex').slice(0, 16)}`);if (access.audienceIdentities.length) parts.push(`xau=${createHash('sha256').update(JSON.stringify(access.audienceIdentities)).digest('hex').slice(0, 16)}`);if (!access.hidePrivate) parts.push('xhp=0');+ if (access.ownerReadsRestricted) parts.push('xor=1');}const h = createHash('sha256');h.update(parts.join('|'));diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex daee2681a9..f4ae8b3154 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -38,6 +38,14 @@ export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';*/export const OWNER_MEMBER_KEY = 'access.owner_member';+/**+ * GST-2490 (G6 of GST-2476): the owner opt-in. Set to '1' only by the trusted local operator (`gbrain access owner+ * reads-restricted on`); with it on, a read by a credential bound to the owner (CallerAccess.ownerReadsRestricted) reads+ * pages a readers list, folder rule or page rule would close to the owner, and their derived pages and facts, except+ * another member's own member page (memory/members/<id>) and anything derived from it. Off or unset changes nothing.+ */+export const OWNER_READS_RESTRICTED_KEY = 'access.owner_reads_restricted';+/*** #5525 — extracted atoms and synthesized concept pages are derived from* other pages or from private transcripts, so a missing `visibility` field on@@ -170,6 +178,42 @@ function originAllowedSql(p: string): string {OR NOT gbrain_access_origin_restricted(${p}.id, ${p}.source_id, ${p}.type, ${p}.frontmatter))`;}+/** GST-2490: the owner's own member page, when the current record is an owner read under the opt-in (else null). */+function ownerOptInPage(access: CallerAccess): string | null {+ if (!access.ownerReadsRestricted) return null;+ const member = access.identity.find(p => p.startsWith('member:'))?.slice('member:'.length);+ return member && ACCESS_ID_RE.test(member) ? `${MEMBER_PAGE_PREFIX}${member}` : null;+}++/** GST-2490: `alias` is not another member's own member page (the owner's own one passes). */+function notOtherMemberPageSql(alias: string, ownPage: string): string {+ return `(NOT starts_with(${alias}.slug, '${MEMBER_PAGE_PREFIX}') OR ${alias}.slug = '${ownPage}')`;+}++/**+ * GST-2490: originAllowedSql for an owner read under the opt-in. A derived page is hidden only when an origin is another+ * member's own member page or reads as nobody (pending coverage), through gbrain_access_origin_hidden_from_owner, the+ * owner twin of gbrain_access_origin_restricted with the same arms.+ */+function ownerOriginAllowedSql(p: string, ownPage: string): string {+ return `((${p}.type NOT IN ('atom', 'question', 'concept', 'event') AND NOT (${p}.frontmatter ? 'derived_from'))+ OR NOT gbrain_access_origin_hidden_from_owner(${p}.id, ${p}.source_id, ${p}.type, ${p}.frontmatter, '${ownPage}'))`;+}++/**+ * GST-2490: the member-access part for an owner read under the opt-in: what the owner's own identity reads, or any page+ * that is not another member's own member page, outside a prefix that reads as nobody, whose origins pass+ * ownerOriginAllowedSql. Readers lists, folder rules and page rules no longer close a page to the owner.+ */+function ownerAccessSql(pageAlias: string, access: CallerAccess): string {+ const ownPage = ownerOptInPage(access);+ const own = accessAllowedSql(pageAlias, access.identity);+ if (!ownPage) return own;+ const notOther = notOtherMemberPageSql(pageAlias, ownPage);+ if (!access.restricted) return `(${own} OR ${notOther})`;+ return `(${own} OR (${notOther}${coverageSql(pageAlias)} AND ${ownerOriginAllowedSql(pageAlias, ownPage)}))`;+}+/*** `privatePagesFilterFragment` with a cheap first test: a page with no* `visibility` or `derived_from` key (nor, unless the operator turned@@ -242,6 +286,12 @@ export interface CallerAccess {privateReadableSources: readonly string[];hidePrivate: boolean;owner: boolean;+ /**+ * GST-2490: an owner read (owner true, a non-mutating operation) on a brain whose operator turned on+ * access.owner_reads_restricted: readers lists, folder rules and page rules stop closing pages, their derivatives and+ * their facts to the owner, except another member's own member page and what derives from it (ownerAccessSql).+ */+ ownerReadsRestricted: boolean;applyRemoteReadPolicy: boolean;restricted: boolean;/** The fresh remote policy (readRemotePolicyNow) a remote request read when it started; null outside one. */@@ -252,7 +302,7 @@ const callerAccessStore = new AsyncLocalStorage<CallerAccess>();/** The current read's caller-access record (see CallerAccess). */export function currentCallerAccess(): CallerAccess {- return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };+ return callerAccessStore.getStore() ?? { identity: [], audience: null, audienceIdentities: [], actor: null, satisfiedRuleIds: [], folderCoverage: [], privateReadableSources: [], hidePrivate: !processPrivacyRelaxed(), owner: false, ownerReadsRestricted: false, applyRemoteReadPolicy: false, restricted: true, remotePolicy: null };}/** Runs `fn` under `access` merged over the current record; an invalid identity or source id empties that set (fail closed). */@@ -278,6 +328,8 @@ export function withCallerAccess<T>(access: Partial<CallerAccess>, fn: () => T):privateReadableSources: sources.length && sources.every(isValidSourceId) ? Object.freeze([...new Set(sources)]) : Object.freeze([]),hidePrivate: access.hidePrivate ?? (fresh ? true : base.hidePrivate),owner: access.owner ?? (fresh ? false : base.owner),+ ownerReadsRestricted: (access.owner ?? (fresh ? false : base.owner)) && audienceIdentities.length <= 1+ && (access.ownerReadsRestricted ?? (fresh ? false : base.ownerReadsRestricted)),applyRemoteReadPolicy: access.applyRemoteReadPolicy ?? base.applyRemoteReadPolicy,restricted: access.restricted ?? base.restricted,remotePolicy: access.remotePolicy ?? base.remotePolicy,@@ -325,12 +377,16 @@ export function callerIdentities(): readonly (readonly string[])[] {}/** GBRA-231: readersAllow for the current caller (every audience entry must be a reader). */-export function callerReadersAllow(frontmatter: unknown): boolean {+export function callerReadersAllow(frontmatter: unknown, slug?: string): boolean {+ const ownPage = ownerOptInPage(currentCallerAccess());+ if (ownPage && typeof slug === 'string' && (!slug.startsWith(MEMBER_PAGE_PREFIX) || slug === ownPage)) return true;return callerIdentities().every(identity => readersAllow(frontmatter, identity));}/** GBRA-231: readersAllowedSql for the current caller, one conjunct per audience entry. */export function callerReadersAllowedSql(alias: string, row: 'page' | 'snapshot' = 'page'): string {+ const ownPage = ownerOptInPage(currentCallerAccess());+ if (ownPage) return row === 'snapshot' ? 'TRUE' : `(${readersAllowedSql(alias, currentCallerAccess().identity)} OR ${notOtherMemberPageSql(alias, ownPage)})`;return callerIdentities().map(identity => readersAllowedSql(alias, identity, row)).join(' AND ');}@@ -341,6 +397,7 @@ function validAudienceEntry(entry: string): boolean {function callerAccessSql(pageAlias: string): string {const access = currentCallerAccess();+ if (access.ownerReadsRestricted) return ownerAccessSql(pageAlias, access);return access.audienceIdentities.length ? accessAllowedForAllSql(pageAlias, access.audienceIdentities, access.satisfiedRuleIds): accessAllowedSql(pageAlias, access.identity);}@@ -414,9 +471,9 @@ function privacyPartFastSql(pageAlias: string): string {* `source_id` is private-readable or when an operator relaxed privacy. A row* without `source_id` keeps the plain privacy rule.*/-export function isPrivatePageForCaller(page: { type?: string | null; frontmatter?: unknown; source_id?: string | null }): boolean {+export function isPrivatePageForCaller(page: { type?: string | null; frontmatter?: unknown; source_id?: string | null; slug?: string | null }): boolean {const access = currentCallerAccess();- if (!callerReadersAllow(page.frontmatter)) return true;+ if (!callerReadersAllow(page.frontmatter, page.slug ?? undefined)) return true;if (!access.hidePrivate || !isPrivacyPrivatePage(page)) return false;if (typeof page.frontmatter === 'object' && page.frontmatter !== null && (page.frontmatter as Record<string, unknown>).pinned_question != null) return true;return !(typeof page.source_id === 'string' && access.privateReadableSources.includes(page.source_id));@@ -686,9 +743,13 @@ export function privateProvenanceFilterUnderPolicy(factAlias: string): string {const access = currentCallerAccess();const hide = !callerRelaxesPrivacy();const member = access.actor?.member ?? (access.audienceIdentities.length ? null : access.identity.find(p => p.startsWith('member:'))?.slice('member:'.length));- const policy = member && ACCESS_ID_RE.test(member)- ? `CASE WHEN pp.slug = '${MEMBER_PAGE_PREFIX}${member}' THEN ${readPolicyFragment('pp', access.identity, hide, access.satisfiedRuleIds)} ELSE ${readPolicyFragment('pp', [], hide)} END`+ const ownPage = ownerOptInPage(access);+ const otherwise = ownPage+ ? `CASE WHEN starts_with(pp.slug, '${MEMBER_PAGE_PREFIX}') THEN ${readPolicyFragment('pp', [], hide)} ELSE (TRUE${coverageSql('pp')} AND ${ownerOriginAllowedSql('pp', ownPage)} AND ${hide ? privacyPartSql('pp') : 'TRUE'}) END`: readPolicyFragment('pp', [], hide);+ const policy = member && ACCESS_ID_RE.test(member)+ ? `CASE WHEN pp.slug = '${MEMBER_PAGE_PREFIX}${member}' THEN ${readPolicyFragment('pp', access.identity, hide, access.satisfiedRuleIds)} ELSE ${otherwise} END`+ : otherwise;return `(NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id AND pp.slug = ${factAlias}.source_markdown_slug AND NOT (${policy})) AND ${privateEntityFilterForCaller(factAlias)})`;}@@ -846,7 +907,7 @@ export async function remotePrivacyRelaxed(engine: BrainEngine): Promise<booleanreturn expose;}-export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ownerMember?: string | null }+export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ownerMember?: string | null; ownerReadsRestricted?: boolean }/*** The remote read policy read fresh, for publication: whether an operator@@ -857,10 +918,10 @@ export interface RemotePolicy { privacyRelaxed: boolean; restricted: boolean; ow*/export async function readRemotePolicyNow(engine: Pick<BrainEngine, 'executeRaw'>): Promise<RemotePolicy> {try {- const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[REMOTE_PRIVATE_PAGES_KEY, ACCESS_RESTRICTIONS_KEY, OWNER_MEMBER_KEY]]);+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key, value FROM config WHERE key = ANY($1::text[])', [[REMOTE_PRIVATE_PAGES_KEY, ACCESS_RESTRICTIONS_KEY, OWNER_MEMBER_KEY, OWNER_READS_RESTRICTED_KEY]]);return remotePolicyFrom(Object.fromEntries(rows.map(r => [r.key, r.value])));} catch {- return { privacyRelaxed: process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1', restricted: true, ownerMember: null };+ return { privacyRelaxed: process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1', restricted: true, ownerMember: null, ownerReadsRestricted: false };}}@@ -878,7 +939,7 @@ function remotePolicyFrom(config: Record<string, string>): RemotePolicy {const hatch = process.env.GBRAIN_REMOTE_PRIVATE_PAGES === '1';const owner = config[OWNER_MEMBER_KEY]?.trim();return { privacyRelaxed: hatch || ['visible', 'true', '1'].includes(config[REMOTE_PRIVATE_PAGES_KEY] ?? ''), restricted: config[ACCESS_RESTRICTIONS_KEY] === '1',- ownerMember: owner && ACCESS_ID_RE.test(owner) ? owner : null };+ ownerMember: owner && ACCESS_ID_RE.test(owner) ? owner : null, ownerReadsRestricted: config[OWNER_READS_RESTRICTED_KEY]?.trim() === '1' };}/** GBRA-218: does this brain hold member-access restrictions? Read live (the request snapshot answers it inside a read); unreadable counts as yes. */diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex b4ae3db318..617a970244 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -1026,7 +1026,7 @@ export async function dispatchToolCall(auth: opts.auth, transport: opts.transport, audienceAsserted: audience !== null });// GST-1158 E1: an attested read that names sources reads as the scope (access/scope-read.ts), or as the person on an attest_read person credential.readMode = attested?.actor ? attestedReadMode(name, attested.params, attested.read) : null;- access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience, opts.transport === 'stdio' && !opts.auth ? opts.stdioMember : undefined);+ access = readMode === 'scope' ? { ...SCOPE_READ_ACCESS, folderCoverage: (await folderAccessFor(engine, [])).folderCoverage } : attested?.access ?? await remoteCallerAccess(engine, opts.auth, privateSources, opts.transport, audience, opts.transport === 'stdio' && !opts.auth ? opts.stdioMember : undefined, readOnly);// GBRA-284: an attested call reads its grant minus other members' personal sources, a scope read minus every personal source (access/member-sources.ts).if (attested?.actor) scoped = await attestedReadScope(engine, resolved, attested.actor.member, readMode === 'scope');} catch (e) {