Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(access): member facts live on memory/members/<member>, readable by that member alone (GST-359 C2)

garrytan156c954faf99
diff --git a/src/core/access/member-facts.ts b/src/core/access/member-facts.ts
new file mode 100644
index 0000000000..43e155460f
--- /dev/null
+++ b/src/core/access/member-facts.ts
@@ -0,0 +1,103 @@
+/**
+ * GST-359 C2 (GBRA-218): member facts. A fact a member saves remotely (an attested actor, or a credential bound to a
+ * member reading as itself) lives on that member's own page, `memory/members/<member>`, whose frontmatter names the
+ * member as its only reader. The fact row is `visibility: private`, so every fact read that admits only world facts
+ * hides it from everyone, and the page's readers (git-backed where a repo exists, the database row on a repo-less
+ * brain) decide the one caller allowed to read it back: `memberFactAdmitSql` admits a private fact only when it sits
+ * on the caller's own member page and that page's readers admit the caller. A fence rebuild re-derives the row from
+ * the page it lives on, so it keeps both.
+ *
+ * Caches and per-session state that a caller's identity changes are keyed by `callerIdentityKey()`, so two people
+ * behind one attest credential and one session id never share an entry.
+ */
+import { createHash } from 'node:crypto';
+import type { OperationContext } from '../ops/contract.ts';
+import { callerAccessAllowedSql, currentCallerAccess, folderRestrictedSql } from '../search/private-visibility.ts';
+import { ACCESS_ID_RE } from './principals.ts';
+
+export const MEMBER_PAGE_PREFIX = 'memory/members/';
+
+export const memberPageSlug = (member: string): string => `${MEMBER_PAGE_PREFIX}${member}`;
+
+/** The member the current caller reads as: the attested actor's, else a lone member identity (never an audience of several). */
+export function callerMember(): string | null {
+ const access = currentCallerAccess();
+ if (access.actor) return access.actor.member;
+ if (access.audienceIdentities.length) return null;
+ const member = access.identity.find(p => p.startsWith('member:'))?.slice('member:'.length) ?? null;
+ return member && ACCESS_ID_RE.test(member) ? member : null;
+}
+
+/** The member page a remote memory write goes to, or null when the caller writes as no single member (local or unbound). */
+export function memberFactPage(ctx: Pick<OperationContext, 'remote'>): string | null {
+ if (ctx.remote === false) return null;
+ const member = callerMember();
+ return member ? memberPageSlug(member) : null;
+}
+
+/** The frontmatter of a member page its first fact creates: the member is its only reader. */
+export function memberPageFrontmatter(member: string): string {
+ return ['---', 'type: note', `title: Memory of ${member}`, 'readable_by:', ` - member:${member}`, '---', ''].join('\n');
+}
+
+/**
+ * The private facts the current caller may read: those on its own member page, while that live page's readers (and
+ * folder rules) admit the caller. FALSE outside a member caller record. `alias` is a code-provided facts alias; the
+ * member id passed ACCESS_ID_RE, whose alphabet has no quote.
+ */
+export function memberFactAdmitSql(alias: string): string {
+ const member = callerMember();
+ if (!member) return 'FALSE';
+ return `(${alias}.visibility = 'private' AND ${alias}.source_markdown_slug = '${memberPageSlug(member)}' AND EXISTS (
+ SELECT 1 FROM pages member_page WHERE member_page.source_id = ${alias}.source_id AND member_page.slug = ${alias}.source_markdown_slug
+ AND member_page.deleted_at IS NULL AND member_page.page_readers && ARRAY['member:${member}']::text[]
+ AND ${callerAccessAllowedSql('member_page')}))`;
+}
+
+/** A remote fact read's visibility list as SQL: the listed values, widened only by memberFactAdmitSql. */
+export function factVisibilitySql(alias: string, visibility: readonly string[]): string {
+ const known = (['world', 'private'] as const).filter(v => visibility.includes(v));
+ const listed = known.length ? `${alias}.visibility IN (${known.map(v => `'${v}'`).join(', ')})` : 'FALSE';
+ if (known.includes('private')) return listed;
+ const own = memberFactAdmitSql(alias);
+ return own === 'FALSE' ? listed : `(${listed} OR ${own})`;
+}
+
+/** Facts on any member page, as SQL: writers that dedup, supersede or contest never cross from one member's page to another. */
+export function onMemberPageSql(alias: string): string {
+ return `starts_with(COALESCE(${alias}.source_markdown_slug, ''), '${MEMBER_PAGE_PREFIX}')`;
+}
+
+/**
+ * Facts whose source page names readers or sits under a folder rule, as SQL. Derivations that write their output onto
+ * another page (consolidation into takes, relinking onto an entity page) skip them: the output would lose the readers.
+ */
+export function readersSourcedFactSql(alias: string): string {
+ return `EXISTS (SELECT 1 FROM pages readers_page WHERE readers_page.source_id = ${alias}.source_id AND readers_page.slug = ${alias}.source_markdown_slug
+ AND (readers_page.page_readers IS NOT NULL OR readers_page.frontmatter ? 'readable_by' OR ${folderRestrictedSql('readers_page')}))`;
+}
+
+/**
+ * A short hash of everything about the current caller that changes what a read returns (the attested actor, the
+ * member identity, an audience), or '' outside a member or audience record. Cache and session-state keys append it.
+ */
+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 };
+ return createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 16);
+}
+
+/** A per-session state key (the delta cursor, context_pack's session) for the current caller: `base` plus the identity key. */
+export function callerSessionKey(base: string | null): string | null {
+ const key = callerIdentityKey();
+ return key ? `${base ?? 'remote'}#id:${key}` : base;
+}
+
+/** Whether a stored write's actor is the current caller's: both unattested, or the same system and member. */
+export function sameAttestedActor(stored: unknown): boolean {
+ const actor = currentCallerAccess().actor ?? null;
+ const row = stored && typeof stored === 'object' && !Array.isArray(stored) ? stored as { system?: unknown; member?: unknown } : null;
+ if (!actor || !row) return !actor && !row;
+ return row.system === actor.system && row.member === actor.member;
+}
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index 106e4d7b64..4798df33f9 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -40,6 +40,7 @@ import { DEFAULT_WRITE_GATE_CONFIG, type WriteGateConfig } from '../../write-gat
import { loadImportSanityConfig } from '../../import-screen.ts';
import { decideTakeWrite, recordFlaggedRow, recordWriteGateHold, type GatedRowDecision } from '../../write-gate-store.ts';
import type { TaintInput, WriteTrust } from '../../trust/tier.ts';
+import { readersSourcedFactSql } from '../../access/member-facts.ts';
export interface ConsolidatePhaseOpts {
dryRun?: boolean;
@@ -183,6 +184,7 @@ export async function runPhaseConsolidate(
AND (attributed_to IS NULL OR attributed_to = 'user')
AND ($2::boolean=false OR visibility='world')
AND ($1::text IS NULL OR source_id=$1)
+ AND NOT ${readersSourcedFactSql('facts')}
GROUP BY source_id, entity_slug
HAVING COUNT(*) >= $3
`, [opts.sourceId ?? null, managed, minPerBucket]);
@@ -227,7 +229,10 @@ export async function runPhaseConsolidate(
});
// Takes here are the user's own (holder 'self'): a claim the assistant or
// a named third party asserted is never promoted into one.
- const unconsolidated = candidates.filter(f => (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));
+ // GST-359 C2: a fact on a page that names readers (a member page) never becomes a take on the entity page.
+ const restricted = new Set((await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE id = ANY($1::bigint[]) AND ${readersSourcedFactSql('facts')}`,
+ [candidates.map(f => f.id)])).map(row => Number(row.id)));
+ const unconsolidated = candidates.filter(f => !restricted.has(f.id) && (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));
if (unconsolidated.length < minPerBucket) {
bucketsSkipped += 1;
continue;
diff --git a/src/core/engine-sql/facts.ts b/src/core/engine-sql/facts.ts
index e7750b9844..0e1e997b05 100644
--- a/src/core/engine-sql/facts.ts
+++ b/src/core/engine-sql/facts.ts
@@ -30,6 +30,7 @@ import { compileRowNormalizer } from './normalize.ts';
import { projectionEligibleSql } from '../eligibility/sql.ts';
import { FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING } from '../facts/insert-guard-schema.ts';
import { privateProvenanceFilterUnderPolicy } from '../search/private-visibility.ts';
+import { factVisibilitySql } from '../access/member-facts.ts';
import { storedTrustTier } from '../trust/tier.ts';
import { ensureWellFormed } from '../text-safe.ts';
@@ -57,6 +58,11 @@ function eligibilityClause(opts: FactListOpts | undefined) {
return opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``;
}
+/** GST-359 C2: a visibility list, widened only to the caller's own member-page private facts (access/member-facts.ts). */
+function visibilityClause(visibility: readonly string[] | null) {
+ return visibility ? sqlFragment`AND ${trustedSql(factVisibilitySql('facts', visibility))}` : sqlFragment``;
+}
+
function privacyClause(opts: { excludePrivate?: boolean } | undefined) {
return opts?.excludePrivate ? sqlFragment` AND ${trustedSql(privateProvenanceFilterUnderPolicy('facts'))}` : sqlFragment``;
}
@@ -420,7 +426,7 @@ export async function listFactsByEntity(
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}
${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}
+ ${visibilityClause(visibility)}${privacyClause(opts)}
${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}
${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}${eligibilityClause(opts)}
ORDER BY valid_from DESC, id DESC
@@ -449,7 +455,7 @@ export async function listFactsSince(
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}
${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${eligibilityClause(opts)}
+ ${visibilityClause(visibility)}${privacyClause(opts)}${eligibilityClause(opts)}
ORDER BY ${eventTime ? sqlFragment`COALESCE(valid_from, created_at)` : sqlFragment`created_at`} DESC, id DESC
LIMIT ${limit} OFFSET ${offset}
`)).rows;
@@ -488,7 +494,7 @@ export async function listFactsKeyset(
WHERE source_id = ${source_id}
${afterCondition}${recallNarrowing(opts)}
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${eligibilityClause(opts)}
+ ${visibilityClause(visibility)}${privacyClause(opts)}${eligibilityClause(opts)}
ORDER BY created_at ASC, id ASC
LIMIT ${limit}
`)).rows;
@@ -516,7 +522,7 @@ export async function listFactsBySession(
${activeOnly ? sqlFragment`AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now())` : sqlFragment``}
${unconsolidatedOnly ? sqlFragment`AND consolidated_at IS NULL` : sqlFragment``}
${kinds ? sqlFragment`AND kind = ANY(${kinds}::text[])` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}
+ ${visibilityClause(visibility)}${privacyClause(opts)}
${excludeAuditRows ? sqlFragment`AND source != ALL(${AUDIT_ROW_SOURCES}::text[])` : sqlFragment``}
${grepPat ? sqlFragment`AND fact ILIKE ${grepPat} ESCAPE '\\'` : sqlFragment``}${eligibilityClause(opts)}
ORDER BY created_at DESC, id DESC
@@ -544,7 +550,7 @@ export async function listSupersessions(
WHERE source_id = ${source_id}
AND superseded_by IS NOT NULL
${since ? sqlFragment`AND COALESCE(expired_at, valid_until) >= ${since}` : sqlFragment``}
- ${visibility ? sqlFragment`AND visibility = ANY(${visibility}::text[])` : sqlFragment``}${privacyClause(opts)}${opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``}
+ ${visibilityClause(visibility)}${privacyClause(opts)}${opts?.eligibility ? sqlFragment` AND ${trustedSql(projectionEligibleSql('facts', 'facts', opts.eligibility))}` : sqlFragment``}
ORDER BY COALESCE(expired_at, valid_until) DESC, id DESC
LIMIT ${limit}
`)).rows;
@@ -702,7 +708,7 @@ export async function findTrajectory(exec: LegacyUnscopedRead, opts: import('../
WHERE ${useArray ? sqlFragment`source_id = ANY(${sourceIds}::text[])` : sqlFragment`source_id = ${sourceId}`}
AND entity_slug = ${opts.entitySlug}
AND expired_at IS NULL
- ${remoteFilter ? sqlFragment`AND visibility = 'world'` : sqlFragment``}${privacyClause(opts)}
+ ${remoteFilter ? visibilityClause(['world']) : sqlFragment``}${privacyClause(opts)}
${metric !== null ? sqlFragment`AND claim_metric = ${metric}` : sqlFragment``}
${kind === 'metric' ? sqlFragment`AND claim_metric IS NOT NULL` : sqlFragment``}
${kind === 'event' ? sqlFragment`AND event_type IS NOT NULL` : sqlFragment``}
diff --git a/src/core/facts/meta-hook.ts b/src/core/facts/meta-hook.ts
index 011d969036..627ffde11e 100644
--- a/src/core/facts/meta-hook.ts
+++ b/src/core/facts/meta-hook.ts
@@ -5,8 +5,9 @@
*
* - Best-effort: own try/catch in the dispatcher; any error here degrades
* to no-_meta rather than failing the tool call.
- * - Cache key is (source_id, session_id, hash(takesHoldersAllowList sorted)).
- * Visibility-aware: cache entries don't bleed across token tiers.
+ * - Cache key is (source_id, session_id, hash(takesHoldersAllowList sorted),
+ * caller identity hash). Visibility-aware: cache entries don't bleed across
+ * token tiers or across the people one credential reads for.
* - 30s TTL per session. A successful mutating tool call on the engine
* drops that engine's entries (`invalidateHotMemoryForEngine`, called by
* dispatch on every MCP transport), and every hit revalidates the
@@ -44,6 +45,7 @@ import { trustFields } from '../eligibility/labels.ts';
import { eligibilityCacheField, readTrustGeneration } from '../eligibility/generation.ts';
import { callerRelaxesPrivacy, resolveExcludePrivatePages } from '../search/private-visibility.ts';
import { isConfigTruthy } from '../config.ts';
+import { callerIdentityKey } from '../access/member-facts.ts';
const DEFAULT_TTL_MS = 30_000;
const DEFAULT_TOP_K = 10;
@@ -132,7 +134,8 @@ export async function getBrainHotMemoryMeta(
// Don't inject on tool calls that themselves manipulate hot memory —
// the agent doesn't need the brain's hot memory wrapped around its own
// recall response.
- if (name === 'recall' || name === 'extract_facts' || name === 'forget_fact') return undefined;
+ // GST-359 C2: nor on QM's memory pair, whose own answer is the member's memory.
+ if (name === 'recall' || name === 'extract_facts' || name === 'forget_fact' || name === 'memory_recall' || name === 'memory_write') return undefined;
const sourceId = ctx.sourceId ?? 'default';
// CX2-11: session identity is the TYPED OperationContext.sessionId field,
@@ -186,7 +189,10 @@ export async function getBrainHotMemoryMeta(
}
// The effective eligibility is part of the key: two connections with
// different floors never share an entry.
- const cacheKey = `${engineCacheField(ctx.engine)}::${encodeCacheField(sourceId)}::${tier}::${encodeCacheField(sessionId ?? '_')}::${allowListHash}::${encodeCacheField(eligibilityCacheField(policy))}::${sessionOnly ? 'session-only' : 'fallback'}`;
+ // GST-359 C2: and the caller's identity (attested actor, member, audience): a member's own private facts ride the
+ // payload, so two people behind one credential and one session id never share an entry. Unbound callers add nothing.
+ const identityKey = ctx.remote === false ? '' : callerIdentityKey();
+ const cacheKey = `${engineCacheField(ctx.engine)}::${encodeCacheField(sourceId)}::${tier}::${encodeCacheField(sessionId ?? '_')}::${allowListHash}::${encodeCacheField(eligibilityCacheField(policy))}::${sessionOnly ? 'session-only' : 'fallback'}${identityKey ? `::xid=${identityKey}` : ''}`;
// Cache hit?
const cached = _cache.get(cacheKey);
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index a532991e8c..6520977d2d 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -10,6 +10,7 @@ import { readSupersessionThreshold } from './supersession-threshold.ts';
import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';
import { pageNotVisibleError } from '../persistence/page-visibility.ts';
import { slugUnderBoundPrefixes } from '../ops/context.ts';
+import { onMemberPageSql } from '../access/member-facts.ts';
export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
@@ -17,6 +18,12 @@ export interface SingleFactIntent {
fact: string; kind: FactRow['kind']; visibility: FactRow['visibility']; entity_slug: string | null;
/** Speaker of the new claim; a fact another known speaker asserted is never its duplicate. */
attributed_to?: FactAttribution | null;
+ /**
+ * GST-359 C2: the member page a member's fact goes to (access/member-facts.ts). Its duplicates and supersession
+ * candidates are only facts on that page (the writer's own, so the readers filter is not applied to them); a write
+ * with no page_slug never matches a fact on any member page.
+ */
+ page_slug?: string;
}
/** Provider work belongs to preparation, never to a page/source transaction. `disabled`: the brain opted out of embedding. */
export async function prepareFactEmbedding(fact: string, signal?: AbortSignal, disabled = false): Promise<{ embedding: Float32Array | null; embedding_model: string | null; degraded: boolean }> {
@@ -105,13 +112,14 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
const [exact] = await engine.executeRaw<FactCandidate>(`SELECT * FROM facts WHERE source_id=$1
AND entity_slug IS NOT DISTINCT FROM $2 AND visibility=$3 AND expired_at IS NULL
AND (valid_until IS NULL OR valid_until>now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($4)
- AND ($5::text IS NULL OR attributed_to IS NULL OR attributed_to=$5)${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}
- ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact, input.attributed_to ?? null]);
+ AND ($5::text IS NULL OR attributed_to IS NULL OR attributed_to=$5)${opts.excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}
+ AND ${input.page_slug ? 'source_markdown_slug=$6' : `($6::text IS NULL AND NOT ${onMemberPageSql('facts')})`}
+ ORDER BY id LIMIT 1`, [sourceId, input.entity_slug, input.visibility, input.fact, input.attributed_to ?? null, input.page_slug ?? null]);
if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };
if (embedding && input.entity_slug) {
const candidates = await listSupersessionCandidates(engine, sourceId, input.entity_slug, input.fact, embedding, embeddingModel, undefined, input.attributed_to ?? null);
const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null; trust_tier: FactRow['trust_tier'] }>(
- `SELECT id,source_markdown_slug,row_num,trust_tier FROM facts WHERE source_id=$1 AND id=ANY($2::int[])${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`,
+ `SELECT id,source_markdown_slug,row_num,trust_tier FROM facts WHERE source_id=$1 AND id=ANY($2::int[])${opts.excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`,
[sourceId, candidates.map(c => c.id)]);
let candidate: FactCandidate | null = null;
let score = -1;
@@ -123,7 +131,7 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
// side effect. Cross-page supersession requires a separate multi-page op.
if (!c.embedding || c.visibility !== input.visibility || c.expired_at ||
c.valid_until && new Date(c.valid_until).getTime() <= Date.now() ||
- c.source_markdown_slug && c.source_markdown_slug !== input.entity_slug) continue;
+ (input.page_slug ? c.source_markdown_slug !== input.page_slug : c.source_markdown_slug && c.source_markdown_slug !== input.entity_slug)) continue;
const next = cosineSimilarity(embedding, c.embedding);
if (next > score) { score = next; candidate = c; }
}
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index 6c84996649..ea03457ec0 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -52,6 +52,7 @@ import { stampPageTrust, stampRowTrust } from '../eligibility/stamp.ts';
import type { TrustTier } from '../trust/tier.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { parseSinceParam } from '../facts/since-parse.ts';
+import { callerSessionKey } from '../access/member-facts.ts';
import { parseQuestionParam, questionRecallNotices, rankFactsByQuestion, recallHintNotice, unlinkedNamesakes, type EntityCandidate, type QuestionRecall } from '../facts/question-recall.ts';
// ============================================================
@@ -1009,7 +1010,9 @@ const delta: Operation = {
// anything else (true, undefined via cast bypass) is remote. Remote callers
// use their auth client id; an auth-LESS or blank-id remote (stdio MCP)
// gets the shared 'remote' sentinel — never collapsed into 'local'.
- const clientId = ctx.remote === false ? null : ctx.auth?.clientId?.trim() || 'remote';
+ // GST-359 C2: plus the caller's identity (attested actor, member, audience), so two people behind one credential
+ // and one session id never share a cursor.
+ const clientId = ctx.remote === false ? null : callerSessionKey(ctx.auth?.clientId?.trim() || 'remote');
const includePrivate = p.include_private === true && ctx.remote === false;
const budgetTokens =
typeof p.budget_tokens === 'number' && Number.isFinite(p.budget_tokens) && p.budget_tokens > 0
diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.ts
index d33c9e69c9..ee2e402cf2 100644
--- a/src/core/persistence/authority.ts
+++ b/src/core/persistence/authority.ts
@@ -12,6 +12,7 @@ import type { Principal, SqlEngine, WriteAuthority, WriteRequest } from './model
import { authorizePageVisibility, excludesPrivateWrites } from './page-visibility.ts';
import { currentCallerAccess } from '../search/private-visibility.ts';
import { parseStoredActor, storedActorIdentity } from '../access/actor.ts';
+import { sameAttestedActor } from '../access/member-facts.ts';
import { pipelined, transactionMemo } from '../page-state/transactions.ts';
function deny(message: string): never { throw new OperationError('permission_denied', message, 'Inspect the current writer registration and source/operation grants.'); }
@@ -271,6 +272,8 @@ export async function ownRequestAccessible(ctx: OperationContext, row: WriteRequ
const engine = onceReads(ctx.engine);
const auth = await submissionAuthority({ ...ctx, engine }, row.operation, row.source_id, row.source_incarnation, row.slug);
if (auth.principal.kind !== row.principal_kind || auth.principal.id !== row.principal_id) return false;
+ // GST-359 C2: under one attest credential, a receipt belongs to the person it was written for.
+ if (!sameAttestedActor(row.authority?.actingFor)) return false;
await authorizeStoredRequest(engine, row);
return true;
} catch (error) {
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index c845e677c5..488f46a360 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -34,6 +34,7 @@ import { localHostId } from './identity.ts';
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { BACKOFF_ELAPSED } from './transient-retry.ts';
import { segmentWriteScope } from '../page-body/ingest.ts';
+import { sameAttestedActor } from '../access/member-facts.ts';
import {
isTerminal, principalKey, requestPrincipal, recoveryFiles,
type JournalLimits, type Principal, type RecoveryRecord, type RequestState,
@@ -233,7 +234,8 @@ export function intentDigest(a: Pick<WriteAdmission, 'operation' | 'sourceId' |
return digest({ operation: a.operation, source_id: a.sourceId, slug: a.slug, intent: a.callerIntent });
}
export function assertReplayIntent(row: WriteRequest, expectedDigest: string): WriteRequest {
- if (row.digest !== expectedDigest) throw opError('idempotency_conflict', 'This request_id was used for a different write; send a new one or omit it.',
+ // GST-359 C2: a request_id another person's attested write used is a different write, never a replay of it.
+ if (row.digest !== expectedDigest || !sameAttestedActor(row.authority?.actingFor)) throw opError('idempotency_conflict', 'This request_id was used for a different write; send a new one or omit it.',
'A request_id is reused only to retry the same write. Send this write again with a new request_id or without one; the earlier write keeps its receipt.',
{ fix: readFix(`Reads the earlier write's receipt (request ${row.request_id}), read-only.`, row.principal_kind === 'local_cli'
? { argv: ['gbrain', 'write-request', '--', row.request_id] }
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 939ddefcbe..1a8d4a7875 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -30,6 +30,7 @@ import { prepareMemoryMutation } from './memory-prepare.ts';
import { retryWriteAdmission } from './admission-retry.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';
import { markBeliefCommits } from '../belief/append.ts';
+import { memberFactPage } from '../access/member-facts.ts';
export { prepareMemoryMutation } from './memory-prepare.ts';
/** Only semantic appends without an explicit caller revision can be recomputed. */
@@ -78,8 +79,9 @@ class InferredTargetRejected extends Error { constructor(readonly warning: Entit
* malformed fences and any owner claim, so it can fall back instead.
*/
async function planRememberTarget(ctx: OperationContext, sourceId: string, source: RememberSource, entitySlug: string | null,
- inferred: { fact: string; visibility: string } | null, call: RememberCall) {
- const slug = entitySlug ?? 'memory/unattributed';
+ inferred: { fact: string; visibility: string } | null, call: RememberCall, memberPage: string | null = null) {
+ // GST-359 C2: a member's remote fact goes to its own member page, created by the first one; the entity is metadata only.
+ const slug = memberPage ?? entitySlug ?? 'memory/unattributed';
validatePageSlug(slug);
enforceClientSlugFence(ctx, slug, 'remember'); enforceSubagentSlugFence(ctx, slug, 'remember');
const authority = await submissionAuthority(ctx, 'remember', sourceId, source.incarnation, slug);
@@ -92,7 +94,7 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');
// Wave B: a segmented entity page over the single-string ceiling cannot take a fence row; named or inferred, the save refuses
// before admission instead of misfiling it. Below the ceiling an inferred target's checks read the page back whole, as preparation does.
- if (entitySlug !== null && snapshot && segmentedOverCeiling(snapshot.page)) {
+ if ((entitySlug !== null || memberPage) && snapshot && segmentedOverCeiling(snapshot.page)) {
throw segmentedRememberRefusal(slug, sourceId, inferred !== null, await rememberCarry(ctx, call, snapshot.page));
}
const whole = inferred && snapshot && isSegmentedPage(snapshot.page) ? await materializedPage(ctx.engine, snapshot.page) : snapshot?.page;
@@ -100,7 +102,7 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
|| parseFactsFence(whole!.compiled_truth).warnings.length)) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
// Preserve the stub guard: a fallback name remains DB-only until a real
// entity page exists. No placeholder page is created by remember.
- const fence = entitySlug !== null && snapshot !== null;
+ const fence = memberPage !== null || (entitySlug !== null && snapshot !== null);
const sandbox = ctx.viaSubagent === true && !(ctx.allowedSlugPrefixes?.length);
const configuredWriteThrough = !/^(false|0|off|no)$/i.test(await ctx.engine.getConfig('sync.write_through') ?? 'true');
const writeThrough = configuredWriteThrough && !sandbox;
@@ -108,7 +110,7 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
else if (!configuredWriteThrough) authority.databaseOnlyReason = 'disabled_by_config';
// An inferred link never designates an owner or reports a missing one.
const target = fence ? await resolveFactWriteTarget(ctx.engine, sourceId, source,
- { sandbox, fileBacked: Boolean(snapshot!.page.source_path), remote: ctx.remote !== false }).catch((error: unknown) => {
+ { sandbox, fileBacked: Boolean(snapshot?.page.source_path), remote: ctx.remote !== false }).catch((error: unknown) => {
if (inferred && error instanceof OperationError) throw new InferredTargetRejected('ENTITY_LINK_FAILED');
throw error;
}) : null;
@@ -189,19 +191,22 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
const validUntil = parseTtlParam(p.ttl);
const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;
const resolved = entity ? await resolveRememberEntity(ctx, sourceId, entity) : null;
- const call: RememberCall = { p, visibilityDefaulted: opts.visibilityDefaulted === true };
- const inference = entity === null ? await inferRememberTarget(ctx, sourceId, source, call) : null;
+ // GST-359 C2: a remote member's fact is private, on its member page, and never inferred onto another page.
+ const memberPage = memberFactPage(ctx);
+ const call: RememberCall = memberPage ? { p: { ...p, visibility: 'private', infer_entity: false }, visibilityDefaulted: false }
+ : { p, visibilityDefaulted: opts.visibilityDefaulted === true };
+ const inference = entity === null && !memberPage ? await inferRememberTarget(ctx, sourceId, source, call) : null;
const linked = inference && 'target' in inference ? inference : null;
const entitySlug = linked?.target.slug ?? resolved?.slug ?? null;
// A source-scoped absent identity serializes subjectless facts. Bound writers
// cannot use it to escape their namespace grant.
- const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null, call);
+ const { slug, authority, snapshot, fence, binding, writeThrough } = linked?.target ?? await planRememberTarget(ctx, sourceId, source, entitySlug, null, call, memberPage);
const { assertFactNotWithdrawn, decideReplacement, replacementVisibility } = await import('../facts/single-prepare.ts');
const defaultedVisibility = await rememberVisibility(ctx, call, snapshot?.page);
const visibility = call.visibilityDefaulted && p.replaces !== undefined && p.replaces !== null
? await replacementVisibility(ctx.engine, sourceId, Number(p.replaces), defaultedVisibility, { remote: ctx.remote !== false })
: defaultedVisibility;
- const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility, entity_slug: entitySlug };
+ const factIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never, visibility, entity_slug: entitySlug, ...(memberPage ? { page_slug: memberPage } : {}) };
// Fail fast on an invalid target or a withdrawn claim; the coordinator re-checks both under its locks before publishing.
if (p.replaces !== undefined && p.replaces !== null) {
// Fail fast on an invalid target; the coordinator re-checks it under the row lock before publishing.
@@ -214,7 +219,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records
// it, so recall's session_id filter finds single facts too. Identity only — never a trust surface.
intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: typeof p.valid_from === 'string' ? new Date(p.valid_from).toISOString() : new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,
- visibility, ...(call.visibilityDefaulted ? { visibility_defaulted: true } : {}),
+ visibility, ...(call.visibilityDefaulted ? { visibility_defaulted: true } : {}), ...(memberPage ? { member_page: true } : {}),
...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}),
session_id: ctx.sessionId ?? null },
authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 9eae09e04f..5d5eee637e 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -32,6 +32,7 @@ import { withPageTierKept } from '../trust/fence-append.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';
import { tightenToPage } from '../facts/visibility.ts';
import { noteBelief } from '../belief/ledger.ts';
+import { MEMBER_PAGE_PREFIX, memberPageFrontmatter, onMemberPageSql } from '../access/member-facts.ts';
function receiptFix(row: WriteRequest): Action {
return row.principal_kind === 'local_cli'
@@ -66,13 +67,32 @@ function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', en
/** The newest active fact in this source and visibility that states the same normalized claim without an entity. */
async function activeUnlinkedCopy(engine: BrainEngine, sourceId: string, input: SingleFactIntent, excludePrivate: boolean): Promise<number | null> {
+ // GST-359 C2: a member's fact links only its own page's unlinked copy; no other write links one on a member page.
const [row] = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts
WHERE source_id=$1 AND visibility=$2 AND entity_slug IS NULL AND expired_at IS NULL
- AND (valid_until IS NULL OR valid_until > now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}
- ORDER BY id DESC LIMIT 1`, [sourceId, input.visibility, input.fact]);
+ AND (valid_until IS NULL OR valid_until > now()) AND gbrain_fact_fingerprint(fact)=gbrain_fact_fingerprint($3)${excludePrivate && !input.page_slug ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}
+ AND ${input.page_slug ? 'source_markdown_slug=$4' : `($4::text IS NULL AND NOT ${onMemberPageSql('facts')})`}
+ ORDER BY id DESC LIMIT 1`, [sourceId, input.visibility, input.fact, input.page_slug ?? null]);
return row ? Number(row.id) : null;
}
+/**
+ * GST-359 C2: a member's first fact creates its member page (frontmatter readable_by the member alone) through the
+ * same put path as every fence append, so it is git-first wherever a repo exists. The put requires the page still
+ * absent; a sibling that created it first makes this attempt conflict and the retry appends to it.
+ */
+async function prepareMemberPageCreation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal: AbortSignal | undefined, writerTier: Parameters<typeof fenceAppendPendingTier>[0],
+ fenceRow: Omit<Parameters<typeof upsertFactRow>[1], 'rowNum'>): Promise<{ page: PreparedMutation; rowNum: number }> {
+ const [indexed] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);
+ const appended = upsertFactRow(`# Memory of ${row.slug.slice(MEMBER_PAGE_PREFIX.length)}\n`, { ...fenceRow, rowNum: (indexed?.n ?? 0) + 1 });
+ const { expected_revision: _ignored, ...intent } = row.intent ?? {};
+ const content = `${memberPageFrontmatter(row.slug.slice(MEMBER_PAGE_PREFIX.length))}\n${appended.body}`;
+ const page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums: [appended.rowNum], tier: fenceAppendPendingTier(writerTier) },
+ () => preparePageMutation(engine, { ...row, intent: { ...intent, content, force: false } }, config, undefined, signal));
+ if (page.observedRevision !== null) conflict(row);
+ return { page, rowNum: appended.rowNum };
+}
+
/** Every retry renders the semantic append from the latest coherent snapshot. */
export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal): Promise<PreparedMutation> {
signal?.throwIfAborted();
@@ -83,9 +103,12 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
}
const p = row.intent;
const input: SingleFactIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as SingleFactIntent['kind'],
- visibility: (p.visibility ?? 'world') as SingleFactIntent['visibility'], entity_slug: p.entity_slug as string | null };
+ visibility: (p.visibility ?? 'world') as SingleFactIntent['visibility'], entity_slug: p.entity_slug as string | null,
+ ...(p.member_page === true ? { page_slug: row.slug } : {}) };
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
- if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');
+ // GST-359 C2: a member page another write created after this one was accepted is the same page, not a recreation.
+ const createdSince = p.member_page === true && row.page_id === null && snapshot !== null && !snapshot.page.deleted_at;
+ if ((snapshot?.page.id ?? null) !== row.page_id && !createdSince) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted entity was deleted or recreated.');
// A defaulted visibility never lands broader than the target page as it stands at publication.
if (p.visibility_defaulted === true && snapshot) input.visibility = tightenToPage(input.visibility, await withFolderRestricted(engine, snapshot.page));
if (p.expected_revision !== undefined) assertPageRevision(snapshot, engineMutationPrecondition(parseMutationPrecondition(p)));
@@ -182,6 +205,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums: [appended.rowNum], tier: fenceAppendPendingTier(writerTier) },
() => preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal));
if (page.observedRevision !== observedRevision) conflict(row);
+ } else if (p.fence === true && p.member_page === true) {
+ const created = await prepareMemberPageCreation(engine, row, config, signal, writerTier, { claim: input.fact, kind: input.kind, visibility: input.visibility,
+ confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom), validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context });
+ ({ page, rowNum } = created);
}
// The belief ledger records the superseded fact in its own stream, so that stream's page key is held too.
const supersededStream = status === 'superseded' ? decision.candidate!.source_markdown_slug ?? decision.candidate!.entity_slug ?? null : null;
diff --git a/src/core/search/fact-relevance.ts b/src/core/search/fact-relevance.ts
index 9bc9fb612a..450d2451ab 100644
--- a/src/core/search/fact-relevance.ts
+++ b/src/core/search/fact-relevance.ts
@@ -27,7 +27,8 @@ import type { TrustTier } from '../trust/tier.ts';
import { AUDIT_ROW_SOURCES } from '../facts/audit-sources.ts';
import { factsFtsDocument, getFtsLanguage } from '../fts-language.ts';
import { getEmbeddingModel } from '../ai/gateway.ts';
-import { privateProvenanceFilterFragment } from './private-visibility.ts';
+import { privateProvenanceFilterUnderPolicy } from './private-visibility.ts';
+import { factVisibilitySql } from '../access/member-facts.ts';
import { quarantinedProvenanceFilterFragment } from '../quarantine.ts';
import { namedEntity } from './entity-anchor.ts';
import { projectionEligibleSql } from '../eligibility/sql.ts';
@@ -140,8 +141,8 @@ function poolPredicate(scope: FactPoolScope, filters: FactPoolFilters | undefine
filters?.includeExpired ? 'f.source_id = ANY($1::text[])' : 'f.source_id = ANY($1::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL',
filters?.includeExpired ? 'f.source != ALL($2::text[])' : '(f.valid_until IS NULL OR f.valid_until > now()) AND f.source != ALL($2::text[])',
quarantinedProvenanceFilterFragment('f'),
- ...(scope.remote ? [`f.visibility = 'world'`] : []),
- ...(scope.excludePrivate ? [privateProvenanceFilterFragment('f')] : []),
+ ...(scope.remote ? [factVisibilitySql('f', ['world'])] : []),
+ ...(scope.excludePrivate ? [privateProvenanceFilterUnderPolicy('f')] : []),
projectionEligibleSql('facts', 'f', { floor: scope.minTrust, suppressFlagged: scope.suppressFlagged }),
];
if (filters?.entities) {
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index 978c2471a0..f158a981ae 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -605,14 +605,18 @@ export function privateTimelineEventFilterForCaller(timelineAlias: string): stri
*/
/**
* GBRA-218: privateProvenanceFilterFragment for the fact reads a caller gates on `excludePrivate`. The readers part
- * always applies (a world fact held in or extracted from a page that names readers stays hidden from every remote
- * caller, as with the plain fragment); the privacy part is dropped when an operator relaxed privacy for this remote
- * read, which is what the hatches did to these reads before member access (`excludePrivate` was false then).
- * Outside a remote record nothing relaxes it.
+ * always applies, judged as the caller: a fact held in or extracted from a page that names readers reaches only the
+ * callers that page admits (none outside a caller record); the privacy part is dropped when an operator relaxed
+ * privacy for this remote read, which is what the hatches did to these reads before member access (`excludePrivate`
+ * was false then). Outside a remote record nothing relaxes it.
*/
export function privateProvenanceFilterUnderPolicy(factAlias: string): string {
+ // GST-359 C2: judged as the caller (its member identity, or every audience entry), so a fact on a page that names
+ // readers reaches exactly the callers who read that page; outside a caller record the identity is empty (hide all).
+ const access = currentCallerAccess();
+ const identity = access.audienceIdentities.length ? { all: access.audienceIdentities } : access.identity;
return `NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = ${factAlias}.source_id ` +
- `AND pp.slug = ${factAlias}.source_markdown_slug AND NOT ${readPolicyFragment('pp', [], !callerRelaxesPrivacy())})`;
+ `AND pp.slug = ${factAlias}.source_markdown_slug AND NOT ${readPolicyFragment('pp', identity, !callerRelaxesPrivacy(), access.satisfiedRuleIds)})`;
}
/** True only inside a remote caller record whose read an operator relaxed (the env hatch or the config opt-out). */
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index f5ce0362b9..a0adf8d4eb 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -21,6 +21,7 @@ import { currentWriteTrust, withTrustPromotion, withWriteAttribution } from '../
import { normalizeDimension } from '../chronicle/ontology.ts';
import { verbError, type OperationError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
+import { onMemberPageSql } from '../access/member-facts.ts';
import {
decisionResult, getTrustProposal, insertTrustProposal, pendingTrustProposalsFor, registerTrustProposalHandler, transitionTrustProposal, trustProposalRef,
type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,
@@ -52,12 +53,14 @@ export const LEXICAL_SLOT_THRESHOLD = 0.5;
* zero model calls.
*/
export async function lexicalContestCandidate(engine: BrainEngine, sourceId: string,
- input: { fact: string; kind: string; visibility: string; entity_slug: string | null }, writer: TrustTier): Promise<{ id: number; trust_tier: TrustTier } | null> {
+ input: { fact: string; kind: string; visibility: string; entity_slug: string | null; page_slug?: string }, writer: TrustTier): Promise<{ id: number; trust_tier: TrustTier } | null> {
if (!input.entity_slug) return null;
+ // GST-359 C2: a member's fact contests only facts on its own member page; no other write contests one there.
const rows = await engine.executeRaw<{ id: number; fact: string; trust_tier: string }>(
`SELECT id, fact, trust_tier FROM facts WHERE source_id = $1 AND entity_slug = $2 AND kind = $3 AND visibility = $4
AND expired_at IS NULL AND (valid_until IS NULL OR valid_until > now()) AND ${trustRankSql('trust_tier')} > ${trustRankSql('$5::text')}
- ORDER BY id DESC LIMIT 200`, [sourceId, input.entity_slug, input.kind, input.visibility, writer]);
+ AND ${input.page_slug ? 'source_markdown_slug = $6' : `($6::text IS NULL AND NOT ${onMemberPageSql('facts')})`}
+ ORDER BY id DESC LIMIT 200`, [sourceId, input.entity_slug, input.kind, input.visibility, writer, input.page_slug ?? null]);
const mine = slotTokens(input.fact);
let best: { id: number; trust_tier: TrustTier; score: number } | null = null;
for (const row of rows) {