Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
A remote remember that restates a private fact is stored private until the operator accepts it (GST-2875) (#9525)
Garry Tan14a41e6a31ca
diff --git a/behavior-changes.d/remember_restated_private_hold_2875.md b/behavior-changes.d/remember_restated_private_hold_2875.mdnew file mode 100644index 0000000000..c1bcc1e668--- /dev/null+++ b/behavior-changes.d/remember_restated_private_hold_2875.md@@ -0,0 +1,4 @@+---+kind: fix+---+A remote remember of the exact claim of a private fact on the same entity that is more trusted than the caller is now stored private with a trust proposal, instead of as a world copy other connected clients could read. The operator lists it with gbrain trust review and makes it world with gbrain trust confirm tp<N>. Other remembers are unchanged.diff --git a/changelog.d/capy-remote-remember-private-restate-hold.md b/changelog.d/capy-remote-remember-private-restate-hold.mdnew file mode 100644index 0000000000..ef17a3b799--- /dev/null+++ b/changelog.d/capy-remote-remember-private-restate-hold.md@@ -0,0 +1,9 @@+---+important: security+---+**A remote `remember` that restates a confirmed private fact as world is now stored private until the brain's operator accepts it, as page writes to that fact's own page already were.**++<!-- behavior-change: remember_restated_private_hold_2875 -->++### Fixed+- A remote caller that remembered the exact claim of a private fact on the same entity, more trusted than itself, got a new world copy that every other connected client could read, so an agent that knew a private claim could publish it. The new fact is now stored private with a trust proposal that carries the widening; `gbrain trust review` lists it and `gbrain trust confirm tp<N>` makes it world. Remembers with no private copy on that entity, with a world copy already present, or with an explicit private visibility are unchanged.diff --git a/src/core/facts/fence-fact-append.ts b/src/core/facts/fence-fact-append.tsindex bf2ad9d3b4..c099943e09 100644--- a/src/core/facts/fence-fact-append.ts+++ b/src/core/facts/fence-fact-append.ts@@ -61,7 +61,8 @@ export type FenceFactAppendInput = {/** The tier the new row's chunks are cut at until its facts row exists (`withPendingFenceRows`); append only. */pendingTier: TrustTier;} & (- | { mode?: 'append'; supersede?: { rowNum: number; validUntil: Date | null } }+ | { mode?: 'append'; supersede?: { rowNum: number; validUntil: Date | null };+ /** GST-2875: the facts row is stored at this visibility while its cell keeps the fact's (a widening the owner decides). */ storedVisibility?: string }| { mode: 'index-existing'; rowNum: number });@@ -110,7 +111,7 @@ function fenceCellFor(fact: FenceFactAppendInput['fact'], rowNum: number, slug:* write created first makes this attempt conflict, and the retry appends to it. File before facts row, as an append.*/export async function prepareFenceFactCreate(engine: BrainEngine, row: WriteRequest, config: GBrainConfig,- input: { fact: NewFact & { valid_from: Date }; pendingTier: TrustTier; frontmatter: string; heading: string }, signal?: AbortSignal): Promise<FenceFactAppend> {+ input: { fact: NewFact & { valid_from: Date }; pendingTier: TrustTier; frontmatter: string; heading: string; storedVisibility?: string }, signal?: AbortSignal): Promise<FenceFactAppend> {const page = { sourceId: row.source_id, slug: row.slug };const [indexedMax] = 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 rowNum = (indexedMax?.n ?? 0) + 1;@@ -125,7 +126,7 @@ export async function prepareFenceFactCreate(engine: BrainEngine, row: WriteRequ}return { prepared, rowNum, fencesNormalized: {}, apply: async tx => {const pageReceipt = await withPageTierKept(tx, page, () => prepared.apply(tx));- return { id: await insertFenceFactRow(tx, row, rowNum, input.fact), pageReceipt };+ return { id: await insertFenceFactRow(tx, row, rowNum, input.storedVisibility ? { ...input.fact, visibility: input.storedVisibility as NewFact['visibility'] } : input.fact), pageReceipt };} };}@@ -192,7 +193,7 @@ export async function prepareFenceFactAppend(engine: BrainEngine, row: WriteRequreturn { prepared, rowNum, fencesNormalized, apply: async tx => {const pageReceipt = await withPageTierKept(tx, page, () => prepared.apply(tx));if (snapshot && isHoldingSlug(row.slug) && !isSegmentedPage(snapshot.page)) await pruneHoldingPageVersions(tx, snapshot.page.id);- return { id: await insert(tx, rowNum, fact), pageReceipt };+ return { id: await insert(tx, rowNum, input.storedVisibility ? { ...fact, visibility: input.storedVisibility as NewFact['visibility'] } : fact), pageReceipt };} };}diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.tsindex 42e243536a..418cb24ef1 100644--- a/src/core/persistence/memory-prepare.ts+++ b/src/core/persistence/memory-prepare.ts@@ -16,7 +16,7 @@ import { requestChannelTrust } from '../trust/channel.ts';import { gateField, gateInput, heldOutcome, loadWriteGateConfig } from '../trust/gate-outcomes.ts';import { decideFactWrite, recordFlaggedRow, recordWriteGateHold } from '../write-gate-store.ts';import { writeGateRejectedError } from '../write-gate.ts';-import { lexicalContestCandidate, recordContestedFact, supersessionGuarded } from '../trust/supersede-handlers.ts';+import { lexicalContestCandidate, recordContestedFact, restatedPrivateCopy, supersessionGuarded } from '../trust/supersede-handlers.ts';import { storedTrustTier } from '../trust/tier.ts';import { fenceAppendPendingTier } from '../eligibility/fence-overlay.ts';import { prepareFenceFactAppend, prepareFenceFactCreate, prepareFenceRowRetirement, requestReceiptFix, type FenceFactAppend } from '../facts/fence-fact-append.ts';@@ -134,12 +134,17 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeconst lexical = (tx: BrainEngine) => decision.status === 'inserted' && !dedupEmbedding && replaces === null ? lexicalContestCandidate(tx, row.source_id, input, writerTier) : Promise.resolve(null);const lexicalOld = await lexical(engine);const contestedOld = contested ? decision.candidate! : lexicalOld;+ // GST-2875: a world write restating a more trusted private claim is stored private; its proposal carries the widening.+ const restated = (tx: BrainEngine) => decision.status !== 'duplicate' && input.visibility === 'world' ? restatedPrivateCopy(tx, row.source_id, input.fact, input.entity_slug, writerTier) : Promise.resolve(null);+ const restatedOld = await restated(engine);+ const widening = restatedOld ? { from: restatedOld.visibility, to: 'world' } : null;const validate = async (tx: BrainEngine) => {await assertFactNotWithdrawn(tx, row.source_id, input, { excludePrivate, remote: row.authority.remote === true });if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict(row);const current = await decide(tx, true);if (candidateState(current) !== candidateState(decision)) conflict(row);if ((await lexical(tx))?.id !== lexicalOld?.id) conflict(row);+ if ((await restated(tx))?.id !== restatedOld?.id) conflict(row);};if (decision.status === 'duplicate') {const duplicate = decision.candidate!;@@ -164,13 +169,13 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequelet fence: FenceFactAppend | undefined;if (p.fence === true && (snapshot || isHoldingSlug(row.slug))) {const old = decision.candidate;- fence = await prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier: fenceAppendPendingTier(writerTier),+ fence = await prepareFenceFactAppend(engine, row, config, snapshot, { fact, pendingTier: fenceAppendPendingTier(writerTier), ...(widening ? { storedVisibility: widening.from } : {}),supersede: status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null ? { rowNum: Number(old.row_num), validUntil: retiredUntil } : undefined }, signal);} else if (p.fence === true && p.member_page === true) {- fence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier),+ fence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier), ...(widening ? { storedVisibility: widening.from } : {}),frontmatter: memberPageFrontmatter(row.slug.slice(MEMBER_PAGE_PREFIX.length)), heading: `# Memory of ${row.slug.slice(MEMBER_PAGE_PREFIX.length)}` }, signal);} else if (p.fence === true && p.scope_page === true) {- fence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier),+ fence = await prepareFenceFactCreate(engine, row, config, { fact, pendingTier: fenceAppendPendingTier(writerTier), ...(widening ? { storedVisibility: widening.from } : {}),frontmatter: scopePageFrontmatter(), heading: '# Scope memory' }, signal);}// GBRA-190 G4: linking a fact saved without an entity retires its holding row in the same publication.@@ -188,7 +193,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequeif (fence) {({ id, pageReceipt } = await fence.apply(tx));} else {- const inserted = await tx.insertFact(fact, { source_id: row.source_id }); // gbrain-allow-direct-insert: journaled source-scoped semantic publication for subjectless or unresolved entity memory+ const inserted = await tx.insertFact(widening ? { ...fact, visibility: widening.from as NewFact['visibility'] } : fact, { source_id: row.source_id }); // gbrain-allow-direct-insert: journaled source-scoped semantic publication for subjectless or unresolved entity memoryid = inserted.id;}if (status === 'superseded') {@@ -198,12 +203,15 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque}const contestedBy = contestedOld ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: contestedOld.id,oldTier: storedTrustTier(contestedOld.trust_tier), newId: id, newTier: writerTier,- guard: replaces !== null ? 'remember.replaces' : contested ? 'conflict_slot' : 'conflict_slot_lexical' }) : null;+ guard: replaces !== null ? 'remember.replaces' : contested ? 'conflict_slot' : 'conflict_slot_lexical',+ ...(widening && restatedOld!.id === contestedOld.id ? { visibility: widening, pageless: !fence } : {}) }) : null;+ const widenedBy = restatedOld && restatedOld.id !== contestedOld?.id ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: restatedOld.id,+ oldTier: restatedOld.trust_tier, newId: id, newTier: writerTier, guard: 'remember.restated_private', visibility: widening!, pageless: !fence }) : null;const flagged = gateField(gate.assessment, `f${id}`, await recordFlaggedRow(tx, gate, { table: 'facts', id, sourceId: row.source_id }));const superseded = status === 'superseded' ? decision.candidate! : undefined;return { ...outcome(id, status, input.entity_slug, validUntil, degraded, p, superseded?.id,superseded !== undefined && superseded.entity_slug == null && input.entity_slug !== null), ...claimColumns(p), ...fence?.fencesNormalized,- ...(contestedBy ? { contested: contestedBy } : {}), ...(flagged ? { gate: flagged } : {}),+ ...(contestedBy ?? widenedBy ? { contested: contestedBy ?? widenedBy } : {}), ...(flagged ? { gate: flagged } : {}),...(pageReceipt?.size_state ? { size_state: pageReceipt.size_state } : {}) };} };}diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.tsindex 0f371f0373..626af9ee27 100644--- a/src/core/trust/supersede-handlers.ts+++ b/src/core/trust/supersede-handlers.ts@@ -72,13 +72,31 @@ export async function lexicalContestCandidate(engine: BrainEngine, sourceId: strreturn best ? { id: best.id, trust_tier: best.trust_tier } : null;}+/**+ * GST-2875: the active non-world fact of `sourceId` on entity `entity` stating exactly `claim`, more trusted than `writer`,+ * while no active world fact states it. A world write of that claim restates it: the write is stored at the copy's visibility+ * and its proposal carries the widening, which only the owner's accept applies (the fence rule of GST-2511, for every+ * remember). Same entity only, as GST-2511 is same page only: the supersede_fact accept refuses a pair across entities.+ */+export async function restatedPrivateCopy(engine: BrainEngine, sourceId: string, claim: string, entity: string | null, writer: TrustTier):+ Promise<{ id: number; visibility: string; trust_tier: TrustTier } | null> {+ const [row] = await engine.executeRaw<{ id: number; visibility: string; trust_tier: string }>(+ `SELECT f.id, f.visibility, f.trust_tier FROM facts f WHERE f.source_id = $1 AND f.fact = $2 AND f.visibility <> 'world'+ AND f.entity_slug IS NOT DISTINCT FROM $4::text AND f.expired_at IS NULL AND (f.valid_until IS NULL OR f.valid_until > now()) AND ${trustRankSql('f.trust_tier')} > ${trustRankSql('$3::text')}+ AND NOT EXISTS (SELECT 1 FROM facts w WHERE w.source_id = $1 AND w.fact = $2 AND w.visibility = 'world' AND w.expired_at IS NULL+ AND (w.valid_until IS NULL OR w.valid_until > now()))+ ORDER BY f.id LIMIT 1`, [sourceId, claim, writer, entity]);+ return row ? { id: Number(row.id), visibility: row.visibility, trust_tier: storedTrustTier(row.trust_tier) } : null;+}+/** The pending supersede_fact proposal for a contested write, inside its publication transaction. */export async function recordContestedFact(tx: BrainEngine, input: { sourceId: string; oldId: number; oldTier: TrustTier; newId: number; newTier: TrustTier; guard: string;- /** GST-2511: the widening the writer asked for; the new row is stored at `from` and the owner's accept sets `to`. */ visibility?: { from: string; to: string } }): Promise<{ proposal_ref: string }> {+ /** GST-2511: the widening the writer asked for; the new row is stored at `from` and the owner's accept sets `to`. */ visibility?: { from: string; to: string };+ /** GST-2875: the new row was written database-only (no page), so no fence can withdraw the widening. */ pageless?: boolean }): Promise<{ proposal_ref: string }> {const { id } = await insertTrustProposal(tx, {action: 'supersede_fact', sourceId: input.sourceId, target: { table: 'facts', id: input.oldId }, related: { table: 'facts', id: input.newId },proposer: input.guard, before: { guard: input.guard, old: { id: input.oldId, tier: input.oldTier }, new: { id: input.newId, tier: input.newTier },- ...(input.visibility ? { visibility: input.visibility } : {}) },+ ...(input.visibility ? { visibility: input.visibility } : {}), ...(input.visibility && input.pageless ? { pageless: true } : {}) },});return { proposal_ref: trustProposalRef(id) };}@@ -178,16 +196,20 @@ function pairOf(row: TrustProposalRow): PairProposal | null {* The visibility change a contested fence widening asked for (GST-2511), from the proposal's before_state; null unless* `newId` is the contested row (the reversed view confirms the old row and widens nothing).*/-async function requestedVisibility(engine: BrainEngine, id: number, newId: number): Promise<{ from: string; to: string } | null> {+async function requestedVisibility(engine: BrainEngine, id: number, newId: number): Promise<{ from: string; to: string; pageless: boolean } | null> {const row = await getTrustProposal(engine, id);const visibility = row?.before_state.visibility as { from?: unknown; to?: unknown } | undefined;- return row?.related_id === newId && typeof visibility?.from === 'string' && typeof visibility.to === 'string' ? { from: visibility.from, to: visibility.to } : null;+ return row?.related_id === newId && typeof visibility?.from === 'string' && typeof visibility.to === 'string'+ ? { from: visibility.from, to: visibility.to, pageless: row.before_state.pageless === true } : null;}/** GST-2511: the page's fence still asks for `visibility` at the fact's row (same number and claim); a later write that narrowed it withdrew the widening. */-async function fenceAsks(engine: BrainEngine, factId: number, visibility: string): Promise<boolean> {+async function fenceAsks(engine: BrainEngine, factId: number, visibility: string, pageless: boolean): Promise<boolean> {const [fact] = await engine.executeRaw<{ fact: string; row_num: number | null; slug: string | null; source_id: string }>('SELECT fact, row_num, source_markdown_slug AS slug, source_id FROM facts WHERE id = $1', [factId]);+ // GST-2875: a restatement written database-only, and still without a page, has no fence that could narrow it. A fence row+ // detached later (url-clone-fences) was not written database-only, so its widening still needs a fence that asks for it.+ if (pageless && fact && !fact.slug && fact.row_num === null) return true;if (!fact?.slug || fact.row_num === null) return false;const snapshot = await engine.readPageSnapshot(fact.slug, { sourceId: fact.source_id });if (!snapshot) return false;@@ -212,7 +234,7 @@ export const TRUST_PAIR_STORE: PairProposalStore = {/** CEO-9: the owner's accept also confirms the new fact, and applies the widening its writer asked for (GST-2511). */async onAccept(tx, proposal) {const requested = await requestedVisibility(tx, proposal.id, proposal.new_fact_id);- const widen = requested && await fenceAsks(tx, proposal.new_fact_id, requested.to) ? requested : null;+ const widen = requested && await fenceAsks(tx, proposal.new_fact_id, requested.to, requested.pageless) ? requested : null;await withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(`UPDATE facts SET trust_tier = 'user_confirmed'${widen ? ', visibility = $3' : ''} WHERE id = $1 AND source_id = $2`,[proposal.new_fact_id, proposal.source_id, ...(widen ? [widen.to] : [])]));diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 929fd730e8..82f363ee2a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -588,6 +588,7 @@ test/refresh-write-barrier.test.tstest/remediation-manual-only.test.tstest/remember-batch-entity-7432.test.tstest/remember-pageless-entity-gst2446.test.ts+test/remember-restated-private-2875.test.tstest/remember-segmented-entity-9213.test.tstest/remember-share-gst2243.test.tstest/remember-strict-held-gst2492.test.tsdiff --git a/test/remember-restated-private-2875.test.ts b/test/remember-restated-private-2875.test.tsnew file mode 100644index 0000000000..26f6a6aa59--- /dev/null+++ b/test/remember-restated-private-2875.test.ts@@ -0,0 +1,214 @@+/**+ * GST-2875: a remote `remember` that restates a confirmed private fact as world is stored private, with a proposal that+ * carries the widening, until the owner accepts it (the rule #9196 / GST-2511 applies to fence rows).+ *+ * 1. Protects: an agent that knows a private claim cannot publish it to every other connected client by remembering it.+ * 2. Fails when: the restated row is stored world, no proposal is filed, a remote recall returns the claim before the+ * accept, the owner's accept does not make it world, or an ordinary remember (no private copy, a world copy, an+ * explicit private visibility) changes.+ * 3. Real seams: MCP operation handlers with remote=true and a source-granted token; PGLite (Postgres when DATABASE_URL+ * is set); managed and unmanaged.+ */+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 type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import type { Principal } from '../src/core/persistence/model.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.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 { withCoordinatedWrite, withTrustPromotion } 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 { decideTrustProposal } from '../src/core/trust/decide.ts';+import { listTrustProposals, parseTrustProposalRef } from '../src/core/trust/proposals.ts';+import { renderFactsTable } from '../src/core/facts-fence.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { readsUnscopedOnPurpose } from './helpers/reads-unscoped.ts';+import { withEnv } from './helpers/with-env.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';++const engines: BrainEngine[] = [];+const urls = new Map<BrainEngine, string>();+const home = mkdtempSync(join(tmpdir(), 'gbrain-open-facts-'));+let closePostgres: (() => Promise<void>) | undefined;+const quiet = { info() {}, warn() {}, error() {} };+/** Every fact the fixtures write is older than this instant (--created-before is required). */++beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ engines.push(pg.engine); urls.set(pg.engine, pg.databaseUrl); closePostgres = pg.close;+ }+}), 120_000);+afterAll(async () => {+ resetGateway();+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++interface Brain { engine: BrainEngine; sourceId: string; remote: OperationContext; local: OperationContext }+/** A source on a shared-shaped brain (no owner, no members) with a token granted only that source. */+async function brain(engine: BrainEngine, managed: boolean): Promise<Brain> {+ const sourceId = `open-${randomUUID().slice(0, 8)}`;+ await disposePersistenceConsumer(engine);+ 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 engine.setConfig('brain.audience', 'shared');+ await registerLocalWriter(engine, 'cli');+ const minted = await mintLegacyToken(engine, { name: `token-${sourceId}`, scopes: ['read', 'write'], sourceGrant: [sourceId], takesHolders: ['world'] });+ await readsUnscopedOnPurpose(engine, minted.id);+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const base = { engine, config: { engine: engine.kind, embedding_disabled: true }, sourceId, dryRun: false, logger: quiet };+ await readLocalWriter(engine, 'cli');+ return {+ engine, sourceId,+ 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'] } },+ local: { ...base, remote: false },+ } as Brain;+}+const run = (ctx: OperationContext, op: string, params: Record<string, unknown>) =>+ operationsByName[op].handler(ctx, { request_id: randomUUID(), ...params }) as Promise<Record<string, any>>;++async function confirmFact(b: Brain, id: number) {+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => withTrustPromotion(tx, 'user_confirmed', () =>+ tx.executeRaw(`UPDATE facts SET trust_tier='user_confirmed' WHERE id=$1`, [id])), TEST_WRITE_ATTRIBUTION));+}+const owner = { confirmation: { via: 'tty' as const } };+const row = (n: number, claim: string, visibility = 'world') => ({ rowNum: n, claim, kind: 'fact', confidence: 1, visibility, notability: 'medium', active: true });+const body = (rows: ReturnType<typeof row>[]) => `Profile.\n\n## Facts\n\n${renderFactsTable(rows as never)}`;+const note = (title: string, text: string) => `---\ntype: note\ntitle: ${title}\n---\n${text}\n`;+const rowsOf = (b: Brain, claim: string) => b.engine.executeRaw<{ id: number; visibility: string; trust_tier: string; row_num: number | null; superseded_by: number | null }>(+ 'SELECT id::int AS id, visibility, trust_tier, row_num, superseded_by::int AS superseded_by FROM facts WHERE source_id=$1 AND fact=$2 AND expired_at IS NULL ORDER BY id', [b.sourceId, claim]);+async function seeded(engine: BrainEngine, managed: boolean, slug: string, claim: string, confirm = true) {+ const b = await brain(engine, managed);+ await run(b.local, 'put_page', { slug, content: note(slug, body([row(1, 'Lives in Turin'), row(2, claim, 'private')])) });+ if (confirm) for (const r of await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [b.sourceId, slug])) await confirmFact(b, Number(r.id));+ return b;+}+async function remoteSees(b: Brain, slug: string, claim: string) {+ __resetPrivateVisibilityCacheForTests();+ return JSON.stringify(await run(b.remote, 'recall', { entity: slug })).includes(claim);+}++describe('GST-2875: a remote remember restating a confirmed private claim', () => {+ for (const managed of [true, false]) {+ test(`is stored private with a widening proposal, hidden from remote reads, and the owner accept makes it world (${managed ? 'managed' : 'unmanaged'})`, async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/lia-example', claim = 'Lia Example keeps bees';+ const b = await seeded(engine, managed, slug, claim);+ const [confirmed] = await rowsOf(b, claim);+ const res = await run(b.remote, 'remember', { fact: claim, provenance: 'chat', entity: slug });+ const ref = res.contested?.proposal_ref ?? res.outcome?.contested?.proposal_ref;+ expect(ref).toMatch(/^tp\d+$/);+ const rows = await rowsOf(b, claim);+ expect(rows.filter(r => r.visibility === 'world')).toEqual([]);+ expect(rows.find(r => r.id === confirmed!.id)).toMatchObject({ visibility: 'private', trust_tier: 'user_confirmed' });+ const restated = rows.find(r => r.id !== confirmed!.id)!;+ expect(restated).toMatchObject({ visibility: 'private', trust_tier: 'agent_written' });+ const proposal = (await listTrustProposals(engine, { status: 'pending' })).find(p => p.id === parseTrustProposalRef(ref)!);+ expect(proposal?.before_state.visibility).toEqual({ from: 'private', to: 'world' });+ expect(await remoteSees(b, slug, claim)).toBe(false);+ expect((await decideTrustProposal(engine, parseTrustProposalRef(ref)!, 'accept', owner)).status).toBe('accepted');+ expect((await rowsOf(b, claim)).find(r => r.id === restated.id)).toMatchObject({ visibility: 'world', trust_tier: 'user_confirmed' });+ expect(await remoteSees(b, slug, claim)).toBe(true);+ }+ }), 180_000);+ }++ test('a later page write keeps the held restatement private until the accept', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/mae-example', claim = 'Mae Example keeps bees';+ const b = await seeded(engine, true, slug, claim);+ await run(b.remote, 'remember', { fact: claim, provenance: 'chat', entity: slug });+ await run(b.remote, 'remember', { fact: 'Mae Example likes tea', provenance: 'chat', entity: slug });+ expect((await rowsOf(b, claim)).map(r => r.visibility)).toEqual(['private', 'private']);+ expect(await remoteSees(b, slug, claim)).toBe(false);+ }+ }), 180_000);++ test('unchanged: no private copy, a world copy already present, or an explicit private remember', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const fresh = await seeded(engine, true, 'people/ned-example', 'Ned Example keeps bees');+ const plain = await run(fresh.remote, 'remember', { fact: 'Ned Example rides a bike', provenance: 'chat', entity: 'people/ned-example' });+ expect(plain.contested).toBeUndefined();+ expect((await rowsOf(fresh, 'Ned Example rides a bike')).map(r => r.visibility)).toEqual(['world']);++ const shared = await brain(engine, true);+ await run(shared.local, 'put_page', { slug: 'people/ola-example', content: note('Ola', body([row(1, 'Ola Example keeps bees')])) });+ for (const r of await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1', [shared.sourceId])) await confirmFact(shared, Number(r.id));+ const again = await run(shared.remote, 'remember', { fact: 'Ola Example keeps bees', provenance: 'chat', entity: 'people/ola-example' });+ expect(again.contested).toBeUndefined();+ expect((await rowsOf(shared, 'Ola Example keeps bees')).map(r => r.visibility).every(v => v === 'world')).toBe(true);++ const kept = await seeded(engine, true, 'people/pia-example', 'Pia Example keeps bees');+ await run(kept.remote, 'remember', { fact: 'Pia Example keeps bees', provenance: 'chat', entity: 'people/pia-example', visibility: 'private' });+ expect((await rowsOf(kept, 'Pia Example keeps bees')).every(r => r.visibility === 'private')).toBe(true);+ expect((await listTrustProposals(engine, { status: 'pending' })).filter(p => (p.before_state as { visibility?: unknown }).visibility && p.source_id === kept.sourceId)).toEqual([]);+ }+ }), 180_000);+ test('the hold pairs with the private copy on the remembered entity, so the owner accept makes it world (review fix)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const claim = 'Keeps bees on the roof';+ const b = await seeded(engine, true, 'people/ada-example', claim);+ await run(b.local, 'put_page', { slug: 'people/bo-example', content: note('Bo', body([row(1, 'Lives in Turin'), row(2, claim, 'private')])) });+ for (const r of await engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [b.sourceId, 'people/bo-example'])) await confirmFact(b, Number(r.id));+ const [other, mine] = await rowsOf(b, claim);+ const res = await run(b.remote, 'remember', { fact: claim, provenance: 'chat', entity: 'people/bo-example' });+ const ref = res.contested?.proposal_ref;+ expect(ref).toMatch(/^tp\d+$/);+ const restated = (await rowsOf(b, claim)).find(r => r.id !== other!.id && r.id !== mine!.id)!;+ expect(restated.visibility).toBe('private');+ expect((await decideTrustProposal(engine, parseTrustProposalRef(ref)!, 'accept', owner)).status).toBe('accepted');+ expect((await rowsOf(b, claim)).find(r => r.id === restated.id)).toMatchObject({ visibility: 'world', trust_tier: 'user_confirmed' });+ expect((await rowsOf(b, claim)).find(r => r.id === other!.id)).toMatchObject({ visibility: 'private', trust_tier: 'user_confirmed' });+ }+ }), 180_000);++ test('a GST-2511 widening whose fence row was detached later is not applied by the accept (review fix)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/yan-example', claim = 'Yan Example keeps bees';+ const b = await seeded(engine, true, slug, claim);+ const current = await run(b.remote, 'get_page', { slug, include_content: true });+ const widened = await run(b.remote, 'put_page', { slug, content: note(slug, body([row(1, 'Lives in Turin'), row(3, claim)])), expected_revision: current.revision });+ expect(widened.contested?.proposal_ref).toMatch(/^tp\d+$/);+ const restated = (await rowsOf(b, claim)).find(r => r.trust_tier !== 'user_confirmed')!;+ expect(restated.visibility).toBe('private');+ // url-clone-fences keeps an appended row database-only before it restores the file.+ await engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () =>+ tx.executeRaw('UPDATE facts SET row_num = NULL, source_markdown_slug = NULL WHERE id = $1', [restated.id]), TEST_WRITE_ATTRIBUTION));+ await decideTrustProposal(engine, parseTrustProposalRef(widened.contested.proposal_ref)!, 'accept', owner);+ expect((await rowsOf(b, claim)).find(r => r.id === restated.id)?.visibility).toBe('private');+ }+ }), 180_000);++ test('a database-only restatement (an entity with no page) is held and the owner accept makes it world', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const claim = 'Zoe Example ships on Fridays', entity = 'people/zoe-example';+ const b = await brain(engine, true);+ await engine.setConfig('sync.write_through', 'false');+ await run(b.local, 'remember', { fact: claim, provenance: 'chat', entity, visibility: 'private' });+ for (const r of await rowsOf(b, claim)) await confirmFact(b, r.id);+ const res = await run(b.remote, 'remember', { fact: claim, provenance: 'chat', entity });+ await engine.setConfig('sync.write_through', 'true');+ const ref = res.contested?.proposal_ref;+ expect(ref).toMatch(/^tp\d+$/);+ const rows = await rowsOf(b, claim);+ const restated = rows.find(r => r.trust_tier === 'agent_written')!;+ expect(rows.map(r => r.row_num)).toEqual([null, null]);+ expect(restated.visibility).toBe('private');+ expect((await decideTrustProposal(engine, parseTrustProposalRef(ref)!, 'accept', owner)).status).toBe('accepted');+ expect((await rowsOf(b, claim)).find(r => r.id === restated.id)).toMatchObject({ visibility: 'world', trust_tier: 'user_confirmed' });+ }+ }), 180_000);+});