Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

The brain owner's agents can forget facts on pages that list the owner as a reader

garrytan52b2fa91972b
diff --git a/src/core/persistence/forget-prepare.ts b/src/core/persistence/forget-prepare.ts
index 31cc43dec9..183f0c7cf4 100644
--- a/src/core/persistence/forget-prepare.ts
+++ b/src/core/persistence/forget-prepare.ts
@@ -21,7 +21,8 @@ import { serializePageToMarkdown } from '../markdown.ts';
import { isSegmentedPage } from '../page-body/page-shape.ts';
import { planFactWithdrawal, recordFactWithdrawal } from '../facts/withdrawal.ts';
import { rebuildPendingPageProjections } from '../page-state/projections.ts';
-import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { ownerReadPolicyFragment, privateProvenanceFilterFragment, readPolicyFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';
+import { folderAccessForAll, memberIdentityFor } from '../access/caller.ts';
import { remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { materializedPage } from './segmented-apply.ts';
import { prepareFileTarget, snapshotLedger, unreadPageFile } from './page-prepare.ts';
@@ -29,7 +30,7 @@ import { pageIdentityError } from './page-identity.ts';
import { MEMBER_PAGE_PREFIX, onOwnedMemoryPageSql } from '../access/member-facts.ts';
import { storedOwnerSpeaksForItself } from './page-visibility.ts';
import type { CompanionPage, PageMutationFile, PreparedMutation } from './coordinator.ts';
-import type { WriteRequest } from './model.ts';
+import type { WriteAuthority, WriteRequest } from './model.ts';
import { UNATTRIBUTED_MEMORY_SLUG } from '../facts-fence.ts';
import { prepareFenceRowRetirement } from '../facts/fence-fact-append.ts';
@@ -72,14 +73,26 @@ export async function refuseForgetReachingOtherCopies(tx: BrainEngine, sourceId:
'Keep the fact. To withdraw the claim everywhere, ask the user to forget it on the brain host.');
}
+/** The owner's member identity and the folder rules it satisfies, as ownerReachesFact judges them. */
+export interface OwnerReader { identity: readonly string[]; satisfied: readonly string[] }
+
+/** GST-2346: the OwnerReader of a stored write's principal, re-resolved live (a member disabled or unbound reads as nobody). */
+export async function storedOwnerReader(engine: BrainEngine, authority: WriteAuthority): Promise<OwnerReader> {
+ const identity = await memberIdentityFor(engine, authority);
+ return { identity, satisfied: (await folderAccessForAll(engine, [identity])).satisfiedRuleIds };
+}
+
/**
- * GST-2346 D1: whether fact id is one the brain owner's own credential withdraws besides shared facts and the facts on
- * its member page: a private fact on no member or scope page, held by a page no remote writer is kept from (or by no
- * page). A fact on a private page or on a page that names readers stays with the brain host.
+ * GST-2346 D1: whether fact id is one the brain owner's own credential withdraws besides the facts every remote caller
+ * reads and the facts on its member page: a fact on no member or scope page whose source page and entity page (each
+ * where one exists) the owner both reads under GST-2490's owner read rule and may write as a member (readers that name
+ * it, folder rules it satisfies, no private visibility). A fact on or about a private page, another member's page or a
+ * page whose readers leave the owner out stays with the brain host; the owner opt-in to read such pages never widens this.
*/
-export async function ownerReachesPrivateFact(engine: BrainEngine, id: number, sourceId: string): Promise<boolean> {
- return (await engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND visibility='private'
- AND NOT ${onOwnedMemoryPageSql('facts')} AND ${privateProvenanceFilterFragment('facts')}`, [id, sourceId])).length > 0;
+export async function ownerReachesFact(engine: BrainEngine, id: number, sourceId: string, owner: OwnerReader): Promise<boolean> {
+ const page = `(${ownerReadPolicyFragment('pp', owner.identity, owner.satisfied)} AND ${readPolicyFragment('pp', owner.identity, true, owner.satisfied)})`;
+ return (await engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND NOT ${onOwnedMemoryPageSql('facts')}
+ AND NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id=facts.source_id AND pp.slug IN (facts.source_markdown_slug, facts.entity_slug) AND NOT ${page})`, [id, sourceId])).length > 0;
}
/**
@@ -106,13 +119,16 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque
const reason = typeof p.reason === 'string' && p.reason.trim() ? p.reason.trim() : null;
// GST-359 D: a member's withdrawal of a fact on its own member page (submitForgetMutation records the page).
const ownPage = remote && typeof p.member_page === 'string' && p.member_page === row.slug && row.slug.startsWith(MEMBER_PAGE_PREFIX) ? row.slug : null;
- // GST-2346 D1: the owner's withdrawal of a private fact off its member page (submitForgetMutation marks it). The owner
- // is judged again here from the stored principal, so a request whose writer is no longer the owner reads the fact as
- // any remote caller does: not found. Such a withdrawal never reaches a copy on a page kept from remote writers.
+ // GST-2346 D1: the owner's withdrawal of a fact off its member page that other remote callers do not reach
+ // (submitForgetMutation marks it). The owner and the fact's page are judged again here from the stored principal, so a
+ // request whose writer is no longer the owner, or whose page no longer names it, reads the fact as any remote caller
+ // does: not found. The fact itself is judged by ownerReachesFact; another copy of the claim on a page kept from remote
+ // writers still refuses the withdrawal.
const ownerReach = remote && !ownPage && p.owner_reach === true && Number.isSafeInteger(id) && id > 0
- && await storedOwnerSpeaksForItself(engine, row.authority) && await ownerReachesPrivateFact(engine, id, sourceId);
+ && await storedOwnerSpeaksForItself(engine, row.authority) && await ownerReachesFact(engine, id, sourceId, await storedOwnerReader(engine, row.authority));
const worldOnly = remote && !ownerReach;
- const excludePrivate = ownerReach || await resolveExcludePrivatePages(engine, remote);
+ const excludePrivate = !ownerReach && await resolveExcludePrivatePages(engine, remote);
+ const copiesHidden = ownerReach || excludePrivate;
const missing = () => verbError(row.operation === 'forget' ? 'not_found' : 'fact_not_found',
`No fact with id "${rawId}".`, 'Ids come from remember/recall. Recall the entity first to find the right fact.');
if (!Number.isSafeInteger(id) || id <= 0) throw missing();
@@ -169,9 +185,10 @@ export async function prepareForgetMutation(engine: BrainEngine, row: WriteReque
validate: async tx => {
// Under the publication's locks: the fact is still visible, no more trusted than a remote caller, and reaches no other copy.
const current = await readForgetTarget(tx, id, sourceId, worldOnly, excludePrivate, true, ownPage);
- if (!current || (ownerReach && !await storedOwnerSpeaksForItself(tx, row.authority))) throw missing();
+ if (!current || (ownerReach && !(await storedOwnerSpeaksForItself(tx, row.authority)
+ && await ownerReachesFact(tx, id, sourceId, await storedOwnerReader(tx, row.authority))))) throw missing();
if (remote && supersessionGuarded('agent_written', current.trust_tier)) throw remoteForgetRaced(id);
- if (!ownPage) await refuseForgetReachingOtherCopies(tx, sourceId, current, worldOnly, excludePrivate);
+ if (!ownPage) await refuseForgetReachingOtherCopies(tx, sourceId, current, worldOnly, copiesHidden);
await held?.validate?.(tx);
},
apply: async (tx, preimage) => {
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 3f5355ea30..3f279ed5d0 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -25,7 +25,7 @@ import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts
import { grantedWriteSource, writeGrantRefusal } from './write-grant.ts';
import type { WriteRequest } from './model.ts';
import { prepareMemoryMutation } from './memory-prepare.ts';
-import { ownerReachesPrivateFact, readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';
+import { ownerReachesFact, readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';
import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';
import { callerIsOwner, currentCallerAccess, folderRestricted, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';
import { projectionEligibleSql } from '../eligibility/sql.ts';
@@ -277,7 +277,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
await decideReplacement(ctx.engine, sourceId, factIntent, Number(p.replaces),
{ pageSlug: slug, remote: ctx.remote !== false, excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote), slugPrefixes: authority.slugPrefixes });
}
- await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });
+ await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent, { excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote), remote: ctx.remote !== false });
const row = await admitWrite(ctx.engine, { origin: ctx.admissionOrigin, principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,
slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId, callerIntent,
// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records
@@ -396,7 +396,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
? `Fact #${rawId} is one this credential reads but cannot withdraw. Nothing was forgotten.`
: `Fact #${rawId} is not on your member page ${ownPage}, so this credential cannot withdraw it. Nothing was forgotten.`,
ownerSpeaksForItself(ctx)
- ? `The brain owner's credential withdraws shared facts, facts on its member page and private facts on pages it can write. The brain host withdraws this one with gbrain forget ${rawId}.`
+ ? `The brain owner's credential withdraws shared facts, facts on its member page and other facts it reads on pages it can write. The brain host withdraws this one with gbrain forget ${rawId}.`
: `A member credential withdraws only the facts on its own member page. The brain host withdraws this one with gbrain forget ${rawId}.`);
let ownerReach = false;
if (ownPage && !mine) {
@@ -405,23 +405,28 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
if (currentCallerAccess().actor) throw missing();
const readable = callerIsOwner() ? 'TRUE' : factVisibilitySql('facts', ['world']);
const eligible = projectionEligibleSql('facts', 'facts', await resolveReadEligibility(ctx));
- const reads = (await ctx.engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND ${readable} AND ${eligible}${excludePrivate ? ` AND ${privateProvenanceFilterUnderPolicy('facts')}` : ''}`, [id, sourceId])).length > 0;
- if (!reads) throw missing();
- // GST-2346 D1: the owner speaking for itself also withdraws a private fact it reads on a page its credential may
- // write (one the brain host wrote); preparation judges the owner again from the stored principal.
- ownerReach = ownerSpeaksForItself(ctx) && await ownerReachesPrivateFact(ctx.engine, id, sourceId);
+ const readsUnder = async (provenance: string) => (await ctx.engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND ${readable} AND ${eligible}${provenance}`, [id, sourceId])).length > 0;
+ const reads = await readsUnder(excludePrivate ? ` AND ${privateProvenanceFilterUnderPolicy('facts')}` : '');
+ // GST-2346 D1: the owner speaking for itself also withdraws a fact it reads on a page its credential may write: a
+ // private one the brain host wrote, or one on a page whose readers name the owner (GST-2490's owner read rule, for
+ // this withdrawal only). Preparation judges the owner and the page again from the stored principal.
+ const access = currentCallerAccess();
+ ownerReach = ownerSpeaksForItself(ctx) && await ownerReachesFact(ctx.engine, id, sourceId, { identity: access.identity, satisfied: access.satisfiedRuleIds })
+ && (reads || await readsUnder(''));
+ if (!reads && !ownerReach) throw missing();
if (!ownerReach) throw hostWithdraws();
ownPage = null;
}
- // The owner's private-fact withdrawal reads the fact as the brain host does, and never reaches a copy on a page kept from remote writers.
+ // The owner's withdrawal judged the fact itself (ownerReachesFact) and never reaches a copy on a page kept from remote writers.
const worldOnly = remote && !ownerReach;
+ const targetHidden = !ownerReach && excludePrivate;
const hidePrivate = ownerReach || excludePrivate;
// #5575 I3: a remote caller cannot forget a fact more trusted than its own writes; the owner is asked instead.
if (remote) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });
const [source] = await ctx.engine.executeRaw<RememberSource>(
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
if (!source || source.archived) throw sourceInactive(sourceId);
- const fact = await readForgetTarget(ctx.engine, id, sourceId, worldOnly, hidePrivate, false, ownPage);
+ const fact = await readForgetTarget(ctx.engine, id, sourceId, worldOnly, targetHidden, false, ownPage);
if (!fact) throw missing();
if (remote && supersessionGuarded('agent_written', fact.trust_tier)) {
// guardRemoteForget reads shared facts only: a more trusted private fact the owner reaches asks the owner the same way.
@@ -439,7 +444,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
// The pages a withdrawal strikes publish through the source's canonical worktree, as remember's do. A source whose
// root has no owner refuses when a canonical file carries the claim (Git is the parent: a database-only withdrawal
// would come back on a rebuild from Git); a claim only database-only pages carry is withdrawn database-only.
- const plan = await planFactWithdrawal(ctx.engine, id, sourceId, worldOnly, ownPage ? undefined : hidePrivate, ownPage);
+ const plan = await planFactWithdrawal(ctx.engine, id, sourceId, worldOnly, ownPage ? undefined : targetHidden, ownPage);
// GST-2492: a fact held on memory/unattributed for an entity with no page is struck there too (its row names the entity).
const heldOn = fact.source_markdown_slug === UNATTRIBUTED_MEMORY_SLUG && fact.entity_slug !== null ? UNATTRIBUTED_MEMORY_SLUG : null;
const struck = plan ? plan.slugs.filter(page => plan.subject === '*' || plan.subject === page || page === heldOn) : [];
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 5e24c21b39..ca2be60db1 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -226,6 +226,17 @@ function ownerAccessSql(pageAlias: string, access: CallerAccess, ownPage: string
return `(${page} AND ${ownerOriginAllowedSql(pageAlias, access, ownPage)})`;
}
+/**
+ * GST-2346: GST-2490's owner read rule (ownerAccessSql, the opt-in off) and the privacy part, for the owner's explicit
+ * identity and satisfied folder rules outside its read record, so a stored write can judge what its owner writer reads.
+ * access.owner_reads_restricted never applies here: a page kept to other members stays closed.
+ */
+export function ownerReadPolicyFragment(pageAlias: string, identity: readonly string[], satisfied: readonly string[]): string {
+ const access: CallerAccess = { ...currentCallerAccess(), identity, satisfiedRuleIds: satisfied, ownerLineage: true, ownerReadsRestricted: false, restricted: true };
+ const ownPage = ownerReadPage(access);
+ return ownPage ? `(${ownerAccessSql(pageAlias, access, ownPage)} AND ${privacyPartSql(pageAlias)})` : 'FALSE';
+}
+
/**
* `privatePagesFilterFragment` with a cheap first test: a page with no
* `visibility` or `derived_from` key (nor, unless the operator turned