Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: remote fact writes apply the same visibility filter as reads
garrytan0a18ebd27ee2
diff --git a/src/core/facts/similar-active.ts b/src/core/facts/similar-active.tsindex 30c4cb6ef7..3a2b3ae5fb 100644--- a/src/core/facts/similar-active.ts+++ b/src/core/facts/similar-active.ts@@ -11,6 +11,7 @@ import { readDecideConfig, providerKind } from '../ai/decide/config.ts';import { hasTypesafeKey } from '../ai/decide/index.ts';import { CONFLICT_MIN_COSINE } from '../ai/decide/conflict.ts';import { REVIEW_WITHDRAW_KEY, reviewWithdrawOn } from './withdrawal.ts';+import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';export const SIMILAR_ACTIVE_LIMIT = 5;@@ -42,7 +43,7 @@ const REVIEW_LINE: Record<SemanticReviewState, string> = {};export async function similarActiveAfterForget(engine: BrainEngine, opts: {- sourceId: string; factId: number; remote: boolean; committed: boolean; semanticReview?: boolean;+ sourceId: string; factId: number; remote: boolean; committed: boolean; semanticReview?: boolean; excludePrivate?: boolean;}): Promise<SimilarActive> {const semantic_review = await reviewState(engine, opts.semanticReview === false);const finish = (state: SimilarActive['state'], candidates: SimilarActive['candidates'], lead: string): SimilarActive =>@@ -60,7 +61,7 @@ export async function similarActiveAfterForget(engine: BrainEngine, opts: {WHERE n.id = $1 AND n.source_id = $2AND c.expired_at IS NULL AND (c.valid_until IS NULL OR c.valid_until > now())AND c.embedding IS NOT NULL AND c.embedding_model = n.embedding_model- AND ($3::boolean = false OR c.visibility = 'world')+ AND ($3::boolean = false OR c.visibility = 'world')${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('c')}` : ''}AND (1 - (c.embedding <=> n.embedding)) >= $4ORDER BY c.embedding <=> n.embedding, c.idLIMIT $5`,diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.tsindex 8c4cfdf45c..1c54f6a0bf 100644--- a/src/core/facts/single-prepare.ts+++ b/src/core/facts/single-prepare.ts@@ -5,6 +5,7 @@ import { cosineSimilarity } from './classify.ts';import { isFactWithdrawn } from './withdrawal.ts';import { assertFactNotPurged } from './withdrawal.ts';import { cosineVerdict } from './capture-dedup.ts';+import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }@@ -35,17 +36,17 @@ export async function assertFactNotWithdrawn(engine: BrainEngine, sourceId: stri* SQL-only, so publication can verify the semantic decision under its guard.* `lane` is the writer's `facts.source`: capture lanes never drop by cosine (#5888).*/-export async function decideSingleFact(engine: BrainEngine, sourceId: string, input: SingleFactIntent, embedding: Float32Array | null, embeddingModel?: string | null, lane?: string | null): Promise<FactDecision> {+export async function decideSingleFact(engine: BrainEngine, sourceId: string, input: SingleFactIntent, embedding: Float32Array | null, embeddingModel?: string | null, lane?: string | null, opts: { excludePrivate?: boolean } = {}): Promise<FactDecision> {const [exact] = await engine.executeRaw<FactCandidate>(`SELECT * FROM facts WHERE source_id=$1AND entity_slug IS NOT DISTINCT FROM $2 AND visibility=$3 AND expired_at IS NULLAND (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)+ 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]);if (exact) return { status: 'duplicate', candidate: { ...exact, id: Number(exact.id) } };if (embedding && input.entity_slug) {const candidates = await engine.findCandidateDuplicates(sourceId, input.entity_slug, input.fact, { embedding, embeddingModel, k: 5, attributedTo: 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[])',+ `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')}` : ''}`,[sourceId, candidates.map(c => c.id)]);let candidate: FactCandidate | null = null;let score = -1;@@ -75,14 +76,14 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in* duplicate. `lock` takes the target row lock inside the publishing transaction.*/export async function decideReplacement(engine: BrainEngine, sourceId: string, input: SingleFactIntent, targetId: number,- opts: { pageSlug: string; remote: boolean; lock?: boolean }): Promise<FactDecision> {+ opts: { pageSlug: string; remote: boolean; lock?: boolean; excludePrivate?: boolean }): Promise<FactDecision> {const notFound = () => verbError('not_found', `No fact with id "${targetId}" to replace.`,'Pass the fact_id of an active fact from recall (facts[].fact_id) about the same entity, or omit replaces to save a new fact.');const [target] = await engine.executeRaw<FactCandidate & { withdrawn: boolean }>(`SELECT f.*,EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=f.source_id AND w.visibility=f.visibilityAND w.fact_hash IN (gbrain_fact_fingerprint(f.fact),gbrain_fact_fingerprint_v1(f.fact))AND (w.subject='*' OR w.subject=COALESCE(f.entity_slug,'*'))) AS withdrawn- FROM facts f WHERE f.id=$1 AND f.source_id=$2${opts.lock ? ' FOR UPDATE OF f' : ''}`, [targetId, sourceId]);+ FROM facts f WHERE f.id=$1 AND f.source_id=$2${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('f')}` : ''}${opts.lock ? ' FOR UPDATE OF f' : ''}`, [targetId, sourceId]);if (!target || (opts.remote && target.visibility !== 'world')) throw notFound();if (target.visibility !== input.visibility) throw notFound();const candidate: FactCandidate = { ...target, id: Number(target.id) };@@ -106,7 +107,7 @@ export async function decideReplacement(engine: BrainEngine, sourceId: string, ithrow verbError('invalid_params', `replaces_cross_page: fact #${targetId} lives on page ${candidate.source_markdown_slug}.`,'Forget the old fact, then remember the new one.');}- const exact = await decideSingleFact(engine, sourceId, input, null);+ const exact = await decideSingleFact(engine, sourceId, input, null, undefined, undefined, { excludePrivate: opts.excludePrivate });if (exact.status === 'duplicate') {if (exact.candidate!.id === candidate.id) return { status: 'duplicate', candidate };throw verbError('invalid_params', `replaces_duplicate: an active fact (#${exact.candidate!.id}) already states this claim.`,diff --git a/src/core/facts/withdrawal.ts b/src/core/facts/withdrawal.tsindex e0f2848d8f..aea6f712b3 100644--- a/src/core/facts/withdrawal.ts+++ b/src/core/facts/withdrawal.ts@@ -5,6 +5,7 @@ import { fenceOperationError } from '../fence-repair/refusal.ts';import { withdrawnFact, withdrawalFenceBlocks } from './withdrawal-overlay.ts';import { ambiguousFenceClaims, discoverWithdrawalTargets, withdrawalDiscoveryFailure } from './withdrawal-discovery.ts';import { dropPurgedFenceRows } from './purge-overlay.ts';+import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';export interface WithdrawalCommit {withdrawn: boolean;@@ -38,7 +39,7 @@ export function reviewWithdrawOn(raw: string | null | undefined): boolean {export async function recordFactWithdrawal(engine: BrainEngine, id: number, sourceId: string, worldOnly = false,- opts: { requestId?: string; semanticReview?: boolean } = {},+ opts: { requestId?: string; semanticReview?: boolean; excludePrivate?: boolean } = {},): Promise<WithdrawalCommit> {return engine.transaction(async tx => {// A managed caller takes this EXCLUSIVE source lock before authority,@@ -46,7 +47,7 @@ export async function recordFactWithdrawal(await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);const visible = await tx.executeRaw<{ visibility: 'private' | 'world'; fact: string; fact_hash: string; subject: string }>(`SELECT visibility,fact,gbrain_fact_fingerprint(fact) AS fact_hash,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2- AND ($3::boolean=false OR visibility='world')`, [id, sourceId, worldOnly]);+ AND ($3::boolean=false OR visibility='world')${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`, [id, sourceId, worldOnly]);if (!visible.length) return { withdrawn: false, pages: [] };const { visibility, fact, fact_hash, subject } = visible[0];// Discovery is keyed on the claim and its subject: a subject-scoped@@ -59,7 +60,7 @@ export async function recordFactWithdrawal(await tx.lockPageKeys(affected.map(({ slug }) => ({ sourceId, slug })));const rows = await tx.executeRaw<{ visibility: string; fact: string; subject: string }>(`SELECT visibility,fact,COALESCE(entity_slug,'*') AS subject FROM facts WHERE id=$1 AND source_id=$2- AND ($3::boolean=false OR visibility='world') FOR UPDATE`, [id, sourceId, worldOnly]);+ AND ($3::boolean=false OR visibility='world')${opts.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''} FOR UPDATE`, [id, sourceId, worldOnly]);if (!rows.length) return { withdrawn: false, pages: [] };const row = rows[0];// Scoped to the forgotten row's entity: the same claim about anotherdiff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex 558a19791e..d3da2bad88 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -25,6 +25,7 @@ import { requestAttribution } from './attribution.ts';import { isTerminal, type WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { retryWriteAdmission } from './admission-retry.ts';+import { privateProvenanceFilterFragment, resolveExcludePrivatePages } from '../search/private-visibility.ts';export { prepareMemoryMutation } from './memory-prepare.ts';/** Only semantic appends without an explicit caller revision can be recomputed. */@@ -166,7 +167,8 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco// Fail fast on an invalid target; the coordinator re-checks it under the row lock before publishing.const { decideReplacement } = await import('../facts/single-prepare.ts');await decideReplacement(ctx.engine, sourceId, { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as never,- visibility: (p.visibility ?? 'world') as never, entity_slug: entitySlug }, Number(p.replaces), { pageSlug: slug, remote: ctx.remote !== false });+ visibility: (p.visibility ?? 'world') as never, entity_slug: entitySlug }, Number(p.replaces),+ { pageSlug: slug, remote: ctx.remote !== false, excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) });}const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,@@ -194,8 +196,9 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foconst reason = typeof p.reason === 'string' && p.reason.trim() ? p.reason.trim() : null;if (!Number.isSafeInteger(id) || id <= 0) throw verbError(operation === 'forget' ? 'not_found' : 'fact_not_found',`No fact with id "${rawId}".`, 'Pass the fact id returned by remember or recall.');+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);// #5575 I3: a remote caller cannot forget a fact more trusted than its own writes; the owner is asked instead.- if (ctx.remote !== false && Number.isSafeInteger(id) && id > 0) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason });+ if (ctx.remote !== false && Number.isSafeInteger(id) && id > 0) await guardRemoteForget(ctx.engine, { sourceId, factId: id, principal, reason, excludePrivate });// Retry the whole withdrawal, so source/principal guards and the connection// are released before backoff. Admission must not retry a nested savepoint.let withdrawn: WithdrawalCommit['pages'] = [];@@ -216,7 +219,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foreturn prior;}const [fact] = await tx.executeRaw<WithdrawalTarget>(`SELECT id,entity_slug,source_markdown_slug,expired_at,trust_tier FROM facts- WHERE id=$1 AND source_id=$2 AND ($3::boolean=false OR visibility='world') FOR UPDATE`, [id, sourceId, ctx.remote !== false]);+ WHERE id=$1 AND source_id=$2 AND ($3::boolean=false OR visibility='world')${excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''} FOR UPDATE`, [id, sourceId, ctx.remote !== false]);if (!fact) throw verbError(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 (ctx.remote !== false && supersessionGuarded('agent_written', fact.trust_tier)) throw remoteForgetRaced(id);@@ -229,7 +232,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foreturn withCoordinatedWrite(tx, [sourceId], async () => {// Even an expired legacy fact acquires a ledger so a stale import cannot// reactivate it. Internal affected-page identities never enter the receipt.- withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id, semanticReview })).pages;+ withdrawn = (await recordFactWithdrawal(tx, id, sourceId, ctx.remote !== false, { requestId: row.id, semanticReview, excludePrivate })).pages;if (reason) await tx.executeRaw(`UPDATE facts SET context=concat_ws(' | ',NULLIF(context,''),$3::text)WHERE id=$1 AND source_id=$2`, [id, sourceId, `forgotten: ${reason}`]);if (operation === 'forget_fact' && fact.expired_at !== null) {@@ -261,6 +264,7 @@ async function withSimilarActive(ctx: OperationContext, operation: 'forget' | 'fconst { similarActiveAfterForget } = await import('../facts/similar-active.ts');const committed = (response.write_request as { state?: string } | undefined)?.state === 'committed' || response.state === 'committed';return { ...response, similar_active: await similarActiveAfterForget(ctx.engine, {- sourceId, factId, remote: ctx.remote !== false, committed, semanticReview: p.semantic_review !== false }) };+ sourceId, factId, remote: ctx.remote !== false, committed, semanticReview: p.semantic_review !== false,+ excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote) }) };} catch { return response; }}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex e1f779f295..1c96ad4d9f 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -25,6 +25,7 @@ import { storedTrustTier } from '../trust/tier.ts';import { pageFencesNormalized } from '../fence-repair/report.ts';import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';import { withPageTierKept } from '../trust/fence-append.ts';+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';function receiptFix(row: WriteRequest): Action {return row.principal_kind === 'local_cli'@@ -80,9 +81,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst dedupEmbedding = p.entity_inferred ? null : embedding;// `replaces`: the caller names the fact this one replaces (checked; the cosine rule does not apply).const replaces = p.replaces !== undefined && p.replaces !== null ? Number(p.replaces) : null;+ const excludePrivate = await resolveExcludePrivatePages(engine, row.authority.remote === true);const decide = (e: BrainEngine, lock = false) => replaces !== null- ? decideReplacement(e, row.source_id, input, replaces, { pageSlug: row.slug, remote: row.authority.remote === true, lock })- : decideSingleFact(e, row.source_id, input, dedupEmbedding, embedding_model);+ ? decideReplacement(e, row.source_id, input, replaces, { pageSlug: row.slug, remote: row.authority.remote === true, lock, excludePrivate })+ : decideSingleFact(e, row.source_id, input, dedupEmbedding, embedding_model, undefined, { excludePrivate });const decision = await decide(engine);// #5575 I3: a lower-tier write never supersedes; it is inserted contested and the owner decides (re-checked under lock by validate).const writerTier = requestChannelTrust(row)?.tier ?? 'unknown';diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.tsindex c7163c1ef0..18bf6573db 100644--- a/src/core/trust/supersede-handlers.ts+++ b/src/core/trust/supersede-handlers.ts@@ -26,6 +26,7 @@ import {import { tierRaiseFix } from './confirm.ts';import { queueTierProjection } from './page-write.ts';import { compareTrust, effectiveWriteTrust, storedTrustTier, trustRankSql, type TrustTier, type WriteTrust } from './tier.ts';+import { privateProvenanceFilterFragment } from '../search/private-visibility.ts';/** I3: a write at `writer` may supersede, expire or forget a row at `target` only when it is at least as trusted. */export function supersessionGuarded(writer: TrustTier | null | undefined, target: unknown): boolean {@@ -108,8 +109,8 @@ export async function forgetRequiresOwner(engine: BrainEngine, input: { sourceId}/** Pre-admission check for a remote forget: a guarded target becomes a `forget` proposal and the verb error. */-export async function guardRemoteForget(engine: BrainEngine, input: { sourceId: string; factId: number; principal: Principal; reason: string | null }): Promise<void> {- const [fact] = await engine.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM facts WHERE id = $1 AND source_id = $2 AND visibility = 'world'`, [input.factId, input.sourceId]);+export async function guardRemoteForget(engine: BrainEngine, input: { sourceId: string; factId: number; principal: Principal; reason: string | null; excludePrivate?: boolean }): Promise<void> {+ const [fact] = await engine.executeRaw<{ trust_tier: string }>(`SELECT trust_tier FROM facts WHERE id = $1 AND source_id = $2 AND visibility = 'world'${input.excludePrivate ? ` AND ${privateProvenanceFilterFragment('facts')}` : ''}`, [input.factId, input.sourceId]);if (!fact || !supersessionGuarded('agent_written', fact.trust_tier)) return;throw await forgetRequiresOwner(engine, { ...input, factTier: storedTrustTier(fact.trust_tier), writerTier: 'agent_written' });}diff --git a/test/e2e/remote-fact-write-private-provenance-postgres.test.ts b/test/e2e/remote-fact-write-private-provenance-postgres.test.tsnew file mode 100644index 0000000000..80cff1ddf1--- /dev/null+++ b/test/e2e/remote-fact-write-private-provenance-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../remote-fact-write-private-provenance.test.ts'));diff --git a/test/remote-fact-write-private-provenance.test.ts b/test/remote-fact-write-private-provenance.test.tsnew file mode 100644index 0000000000..17676fb0d9--- /dev/null+++ b/test/remote-fact-write-private-provenance.test.ts@@ -0,0 +1,201 @@+/**+ * Remote fact writes follow the same page-visibility policy as remote fact+ * reads (#4352 class). A `visibility = 'world'` fact whose provenance page+ * (`source_markdown_slug`) is `visibility: private` is invisible to an+ * untrusted caller, so a remote `forget` of it answers not_found and writes+ * nothing (no withdrawal, no owner proposal), `remember.replaces` cannot name+ * it, `remember`'s duplicate checks never match it, and `forget`'s+ * similar_active candidates never list it. The trusted local CLI is unchanged.+ *+ * Both engines: PGLite always, Postgres through+ * test/e2e/remote-fact-write-private-provenance-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operationsByName } from '../src/core/operations.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { registerLocalWriter, readLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import type { Principal } from '../src/core/persistence/model.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { decideSingleFact } from '../src/core/facts/single-prepare.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++// eslint-disable-next-line @typescript-eslint/no-explicit-any+type R = Record<string, any>;+const ENTITY = 'people/alice-example';+const SECRET_PAGE = 'meetings/secret-sync';+const quiet = { info() {}, warn() {}, error() {} };++for (const kind of testBackends()) {+ describe(`remote fact writes skip private-provenance facts (${kind})`, () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-write-visibility-'));+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let sourceId = '';+ let remote: OperationContext;+ let local: OperationContext;++ const run = (ctx: OperationContext, op: string, params: R) =>+ withEnv({ GBRAIN_HOME: home }, () => operationsByName[op].handler(ctx, { request_id: randomUUID(), ...params }) as Promise<R>);+ const factRow = async (id: number) => (await engine.executeRaw<{ expired_at: unknown; superseded_by: unknown }>(+ 'SELECT expired_at, superseded_by FROM facts WHERE id = $1', [id]))[0]!;+ const withdrawals = async () => Number((await engine.executeRaw<{ n: number | string }>(+ 'SELECT COUNT(*) AS n FROM fact_withdrawals WHERE source_id = $1', [sourceId]))[0]!.n);+ const proposals = async () => Number((await engine.executeRaw<{ n: number | string }>(+ `SELECT COUNT(*) AS n FROM trust_proposals`))[0]!.n);+ const factCount = async () => Number((await engine.executeRaw<{ n: number | string }>(+ 'SELECT COUNT(*) AS n FROM facts WHERE source_id = $1', [sourceId]))[0]!.n);++ /** A world fact about ENTITY whose provenance page is the private meeting. */+ async function hiddenFact(text: string, tier = 'agent_written'): Promise<number> {+ const [row] = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw<{ id: number | string }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_markdown_slug, trust_tier)+ VALUES ($1, $2, $3, 'fact', 'world', 'test', $4, $5) RETURNING id`, [sourceId, ENTITY, text, SECRET_PAGE, tier]), TEST_WRITE_ATTRIBUTION));+ return Number(row!.id);+ }+ async function visibleFact(text: string): Promise<number> {+ return Number((await run(local, 'remember', { fact: text, provenance: 'owner', entity: ENTITY, visibility: 'world' })).id);+ }+ async function sameEmbedding(ids: number[]): Promise<void> {+ const [col] = await engine.executeRaw<{ t: string }>(+ `SELECT format_type(atttypid, atttypmod) AS t FROM pg_attribute WHERE attrelid = 'facts'::regclass AND attname = 'embedding'`);+ const dims = Number(/\((\d+)\)/.exec(col!.t)![1]);+ const literal = `[${Array.from({ length: dims }, (_, i) => (i % 7) / 10).join(',')}]`;+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ `UPDATE facts SET embedding = $1::text::${col!.t.replace(/\(.*$/, '')}, embedding_model = 'test-model' WHERE id = ANY($2::bigint[])`,+ [literal, ids]), TEST_WRITE_ATTRIBUTION));+ }++ beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ if (kind === 'postgres') {+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ sourceId = `wv-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ await registerLocalWriter(engine, 'cli');+ const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await readLocalWriter(engine, 'cli');+ const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };+ remote = { ...base, remote: true, transport: 'http', takesHoldersAllowList: ['world'],+ auth: { token: '', clientId: minted.id, principal: { kind: 'legacy_token', id: minted.id } as Principal, sourceId, allowedSources: [sourceId], scopes: ['read', 'write'] } } as unknown as OperationContext;+ local = { ...base, remote: false } as unknown as OperationContext;+ await run(local, 'put_page', { slug: ENTITY, content: '---\ntype: person\ntitle: Alice Example\n---\nAlice is a founder.\n' });+ await run(local, 'put_page', { slug: SECRET_PAGE, content: '---\ntype: meeting\ntitle: secret sync\nvisibility: private\n---\nA private meeting.\n' });+ __resetPrivateVisibilityCacheForTests();+ }), 180_000);+ afterAll(async () => {+ resetGateway();+ await disposePersistenceConsumer(engine);+ await close?.();+ rmSync(home, { recursive: true, force: true });+ });++ test('remote forget of a private-provenance world fact is not_found and writes nothing; a visible fact still forgets', async () => {+ const hidden = await hiddenFact('SECRETPROV-alpha ships the launch');+ const before = { withdrawals: await withdrawals(), proposals: await proposals() };+ await expect(run(remote, 'forget', { id: String(hidden) })).rejects.toMatchObject({ code: 'not_found' });+ expect(await factRow(hidden)).toMatchObject({ expired_at: null });+ expect(await withdrawals()).toBe(before.withdrawals);+ expect(await proposals()).toBe(before.proposals);++ const visible = await visibleFact('OPENPROV-beta reviews the plan');+ expect((await run(remote, 'forget', { id: String(visible) })).expired).toBe(true);+ expect((await factRow(visible)).expired_at).not.toBeNull();+ }, 90_000);++ test('remote forget of a confirmed private-provenance fact files no owner proposal', async () => {+ const hidden = await hiddenFact('SECRETPROV-gamma owns the budget', 'user_confirmed');+ const before = await proposals();+ await expect(run(remote, 'forget', { id: String(hidden) })).rejects.toMatchObject({ code: 'not_found' });+ expect(await proposals()).toBe(before);+ expect(await factRow(hidden)).toMatchObject({ expired_at: null });+ }, 90_000);++ test('local forget of a private-provenance world fact is unchanged', async () => {+ const hidden = await hiddenFact('SECRETPROV-delta hires a lead');+ expect((await run(local, 'forget', { id: String(hidden) })).expired).toBe(true);+ expect((await factRow(hidden)).expired_at).not.toBeNull();+ }, 90_000);++ test('remote remember.replaces cannot name a private-provenance fact', async () => {+ const hidden = await hiddenFact('SECRETPROV-epsilon leads sales');+ const count = await factCount();+ const attempt = run(remote, 'remember', { fact: 'OPENPROV-zeta leads marketing', provenance: 'web page', entity: ENTITY, replaces: String(hidden) });+ await expect(attempt).rejects.toMatchObject({ code: 'not_found' });+ await attempt.catch((error: Error) => expect(JSON.stringify({ ...error, message: error.message })).not.toContain(SECRET_PAGE));+ expect(await factCount()).toBe(count);+ expect(await factRow(hidden)).toMatchObject({ expired_at: null, superseded_by: null });+ }, 90_000);++ test('remote remember of a private-provenance claim never reports it as already known; local still does', async () => {+ const claim = 'SECRETPROV-lambda buys the company';+ const hidden = await hiddenFact(claim);+ const remoteWrite = await run(remote, 'remember', { fact: claim, provenance: 'web page', entity: ENTITY });+ expect(Number(remoteWrite.id)).not.toBe(hidden);+ expect(JSON.stringify(remoteWrite)).not.toContain(`#${hidden}`);+ const localWrite = await run(local, 'remember', { fact: 'SECRETPROV-mu sells the company', provenance: 'owner', entity: ENTITY });+ const localDup = await run(local, 'remember', { fact: 'SECRETPROV-mu sells the company', provenance: 'owner', entity: ENTITY });+ expect(localDup).toMatchObject({ status: 'duplicate', id: String(localWrite.id) });+ const hiddenLocal = await hiddenFact('SECRETPROV-nu merges the teams');+ expect(await run(local, 'remember', { fact: 'SECRETPROV-nu merges the teams', provenance: 'owner', entity: ENTITY }))+ .toMatchObject({ status: 'duplicate', id: String(hiddenLocal) });+ }, 90_000);++ test('a remote near-duplicate check never matches a fact on a private page; local still does', async () => {+ const page = 'people/carol-example';+ await run(local, 'put_page', { slug: page, content: '---\ntype: person\ntitle: Carol Example\nvisibility: private\n---\nCarol is private.\n' });+ __resetPrivateVisibilityCacheForTests();+ const [row] = await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw<{ id: number | string }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_markdown_slug, trust_tier)+ VALUES ($1, $2, 'SECRETPROV-xi opens a second office', 'fact', 'world', 'test', $2, 'agent_written') RETURNING id`, [sourceId, page]), TEST_WRITE_ATTRIBUTION));+ const hidden = Number(row!.id);+ await sameEmbedding([hidden]);+ await engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => tx.executeRaw(+ 'UPDATE facts SET embedded_text_hash = md5(fact) WHERE id = $1', [hidden]), TEST_WRITE_ATTRIBUTION));+ const [col] = await engine.executeRaw<{ t: string }>(+ `SELECT format_type(atttypid, atttypmod) AS t FROM pg_attribute WHERE attrelid = 'facts'::regclass AND attname = 'embedding'`);+ const dims = Number(/\((\d+)\)/.exec(col!.t)![1]);+ const embedding = Float32Array.from({ length: dims }, (_, i) => (i % 7) / 10);+ const input = { entity_slug: page, fact: 'SECRETPROV-xi is opening another office', kind: 'fact' as const, visibility: 'world' as const };+ const decide = (excludePrivate: boolean) => decideSingleFact(engine, sourceId, input, embedding, 'test-model', 'owner', { excludePrivate });+ expect((await decide(false)).candidate?.id).toBe(hidden);+ expect(await decide(true)).toEqual({ status: 'inserted', candidate: null });+ }, 90_000);++ test('similar_active after a remote forget never lists a private-provenance fact; local still does', async () => {+ const anchorRemote = await visibleFact('OPENPROV-eta closes the round');+ const hiddenTwin = await hiddenFact('SECRETPROV-theta closes the round early');+ const visibleTwin = await visibleFact('OPENPROV-iota closes the round soon');+ await sameEmbedding([anchorRemote, hiddenTwin, visibleTwin]);+ const remoteIds = ((await run(remote, 'forget', { id: String(anchorRemote) })).similar_active?.candidates ?? []).map((c: R) => Number(c.fact_id));+ expect(remoteIds).toContain(visibleTwin);+ expect(remoteIds).not.toContain(hiddenTwin);++ const anchorLocal = await visibleFact('OPENPROV-kappa closes the round late');+ await sameEmbedding([anchorLocal, hiddenTwin, visibleTwin]);+ const localIds = ((await run(local, 'forget', { id: String(anchorLocal) })).similar_active?.candidates ?? []).map((c: R) => Number(c.fact_id));+ expect(localIds).toEqual(expect.arrayContaining([hiddenTwin, visibleTwin]));+ }, 90_000);+ });+}