Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(trust): put_page reports contested (38-2), confirming either side of a contested fact resolves its proposal (38-4), keyless lexical conflict slot contests higher-tier facts (38-3)

garrytan661696f527be
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index 6e787b1584..ae5fe92b95 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -84,6 +84,7 @@ export const DECIDE_PROPOSAL_STORE: PairProposalStore = {
async function pairStore(name: unknown): Promise<PairProposalStore | null> {
if (name === undefined || name === null) return DECIDE_PROPOSAL_STORE;
if (name === 'trust') return (await import('../trust/supersede-handlers.ts')).TRUST_PAIR_STORE;
+ if (name === 'trust_reverse') return (await import('../trust/supersede-handlers.ts')).TRUST_REVERSE_PAIR_STORE;
return null;
}
diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.ts
index e3f2cccad4..54261159c7 100644
--- a/src/core/persistence/canonical-projections.ts
+++ b/src/core/persistence/canonical-projections.ts
@@ -422,14 +422,14 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par
// #5575: rows more trusted than the writer are never expired by it, and new rows pass the write gate (trust/fence-guard.ts).
const guard = await guardFenceRows(tx, { sourceId, slug, incoming, rows: factRows, cfg: loadWriteGateConfig }, () => pipelined(tx, [expireFacts]));
if (guard.rows.length) await tx.insertFacts(guard.rows, { source_id: sourceId }); // gbrain-allow-direct-insert: canonical fence projection shares the journal publication transaction
- await guard.finish(tx);
+ const contested = await guard.finish(tx);
await pipelined(tx, [...factFields, checkTakes, dropTakes]);
if (takes.length) {
await tx.addTakesBatch(takes.map(t => takesPreparation.toCanonicalBatchInput(id, t)));
await pipelined(tx, [...resolveTakes, ...timelineRows]);
} else await pipelined(tx, timelineRows);
- return { timelineRowsRemoved: removedSummary(removedDates) };
+ return { timelineRowsRemoved: removedSummary(removedDates), ...(contested.length ? { contested } : {}) };
};
}
-export interface CanonicalProjectionResult { timelineRowsRemoved: TimelineRowsRemoved | null }
+export interface CanonicalProjectionResult { timelineRowsRemoved: TimelineRowsRemoved | null; /** #5575 A5: trust proposals the guarded fence re-projection filed. */ contested?: string[] }
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 851bddc45b..e1f779f295 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -20,7 +20,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 { recordContestedFact, supersessionGuarded } from '../trust/supersede-handlers.ts';
+import { lexicalContestCandidate, recordContestedFact, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { storedTrustTier } from '../trust/tier.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
import { fenceAppendPendingTier, withPendingFenceRows } from '../eligibility/fence-overlay.ts';
@@ -88,11 +88,16 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const writerTier = requestChannelTrust(row)?.tier ?? 'unknown';
const contested = decision.status === 'superseded' && supersessionGuarded(writerTier, decision.candidate!.trust_tier);
const status = contested ? 'inserted' : decision.status;
+ // Without a fact vector the slot has no cosine; a lexical same-subject match still contests a more trusted fact (never supersedes).
+ const 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;
const validate = async (tx: BrainEngine) => {
await assertFactNotWithdrawn(tx, row.source_id, input);
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 (decision.status === 'duplicate') {
const duplicate = decision.candidate!;
@@ -155,8 +160,9 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
}
if (status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3
WHERE id=$1 AND source_id=$2 AND expired_at IS NULL`, [decision.candidate!.id, row.source_id, id]);
- const contestedBy = contested ? await recordContestedFact(tx, { sourceId: row.source_id, oldId: decision.candidate!.id,
- oldTier: storedTrustTier(decision.candidate!.trust_tier), newId: id, newTier: writerTier, guard: replaces !== null ? 'remember.replaces' : 'conflict_slot' }) : null;
+ 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;
const flagged = gateField(gate.assessment, `f${id}`, await recordFlaggedRow(tx, gate, { table: 'facts', id, sourceId: row.source_id }));
return { ...outcome(id, status, input.entity_slug, validUntil, degraded, p, status === 'superseded' ? decision.candidate!.id : undefined), ...fencesNormalized,
...(contestedBy ? { contested: contestedBy } : {}), ...(flagged ? { gate: flagged } : {}) };
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 8d7c241899..5eacee5bf0 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -457,6 +457,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;
let removedTimeline: TimelineRowsRemoved | null = null;
let lowered: { proposal_ref: string } | null = null;
+ let contested: string[] = [];
if (!noop) {
const prior = snapshot ? await storedPageTier(tx, row.source_id, row.slug) : null;
// ENG-1: a managed fence edit keeps the page's tier; CEO-12: an agent rewrite that lowers a page files a queue item.
@@ -480,7 +481,9 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
for (const tag of versionTags) await tx.addTag(row.slug, tag, source);
}
// #6007: the page the import just wrote live is the page the projections describe; no re-read.
- removedTimeline = (await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId))?.timelineRowsRemoved ?? null;
+ const projected = await project?.(tx, row.operation === 'restore_page' ? undefined : applied?.pageId);
+ removedTimeline = projected?.timelineRowsRemoved ?? null;
+ contested = projected?.contested ?? [];
autoLinks = await links?.apply(tx);
if (targetDeleted) await tx.softDeletePage(row.slug, source);
// Index installation and terminal receipt share this transaction. The import sealed the projection
@@ -500,7 +503,9 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
...(!noop && quarantineOutcome(ready.parsedPage.frontmatter) ? { quarantined: quarantineOutcome(ready.parsedPage.frontmatter) } : {}),
...(row.operation === 'capture' ? { channel: 'capture', content_hash: p.capture_hash } : {}),
...(edited ? editDiff(row.slug, edited.before, edited.after) : {}), ...fencesNormalized, ...fenceRepairOutcome,
- ...(lowered ? { trust_lowered: lowered } : {}), ...(gate ? { gate } : {}) };
+ ...(lowered ? { trust_lowered: lowered } : {}), ...(gate ? { gate } : {}),
+ // DX-1: a guarded supersession reports contested (the first proposal; every one when the write contested several rows).
+ ...(contested.length ? { contested: { proposal_ref: contested[0], ...(contested.length > 1 ? { proposal_refs: contested } : {}) } } : {}) };
} };
}
diff --git a/src/core/trust/fence-guard.ts b/src/core/trust/fence-guard.ts
index a0d1de5a18..b146c73243 100644
--- a/src/core/trust/fence-guard.ts
+++ b/src/core/trust/fence-guard.ts
@@ -30,8 +30,8 @@ const WRITER_RANK = trustRankSql(`COALESCE(NULLIF(current_setting('gbrain.write_
export interface FenceGuard<T extends FenceFact> {
/** The fence rows to insert (held and rejected rows removed, moved rows removed). */
rows: T[];
- /** After the caller's expiry and insert: proposals for contested rows, receipts for flagged rows. */
- finish(tx: BrainEngine): Promise<void>;
+ /** After the caller's expiry and insert: proposals for contested rows (their tp refs), receipts for flagged rows. */
+ finish(tx: BrainEngine): Promise<string[]>;
}
/**
@@ -85,22 +85,25 @@ export async function guardFenceRows<T extends FenceFact>(tx: BrainEngine, input
return {
rows: inserted,
async finish(db) {
+ const refs: string[] = [];
const at = async (rowNum: number) => (await db.executeRaw<{ id: number; trust_tier: string }>(
`SELECT id, trust_tier FROM facts WHERE source_id = $1 AND source_markdown_slug = $2 AND row_num = $3 AND expired_at IS NULL`, [sourceId, slug, rowNum]))[0];
for (const g of contested) {
const replacement = fresh.has(Number(g.row_num)) ? await at(Number(g.row_num)) : undefined;
if (replacement) {
- await recordContestedFact(db, { sourceId, oldId: Number(g.id), oldTier: storedTrustTier(g.trust_tier), newId: Number(replacement.id),
- newTier: storedTrustTier(replacement.trust_tier), guard: 'fence_projection' });
+ refs.push((await recordContestedFact(db, { sourceId, oldId: Number(g.id), oldTier: storedTrustTier(g.trust_tier), newId: Number(replacement.id),
+ newTier: storedTrustTier(replacement.trust_tier), guard: 'fence_projection' })).proposal_ref);
} else {
- await insertTrustProposal(db, { action: 'forget', sourceId, target: { table: 'facts', id: Number(g.id) }, proposer: 'fence_projection',
+ const { id } = await insertTrustProposal(db, { action: 'forget', sourceId, target: { table: 'facts', id: Number(g.id) }, proposer: 'fence_projection',
before: { guard: 'fence_projection', fact: { id: Number(g.id), tier: storedTrustTier(g.trust_tier) }, writer_tier: trust.tier, slug } });
+ refs.push(`tp${id}`);
}
}
for (const { row, decision } of gated) {
const stored = await at(row.row_num);
if (stored) await recordFlaggedRow(db, decision, { table: 'facts', id: Number(stored.id), sourceId });
}
+ return refs;
},
};
}
diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.ts
index 0bc16b1d98..4e25c872d0 100644
--- a/src/core/trust/owner-actions.ts
+++ b/src/core/trust/owner-actions.ts
@@ -26,6 +26,7 @@ import type { Principal } from '../persistence/model.ts';
import type { OwnerConfirmation } from './confirm.ts';
import { tierRaiseFix } from './confirm.ts';
import { decideTrustProposal } from './decide.ts';
+import { resolveContestedFactOnConfirm } from './supersede-handlers.ts';
import { getTrustProposal, pendingTrustProposalsFor, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';
import {
confirmPage, latestPageVersionId, lowerPageState, readPageTrustState, readPageVersion, revertLoweredPage, revertPageToVersion,
@@ -432,9 +433,12 @@ export async function applyOwnerAction(engine: BrainEngine, input: OwnerActionIn
case 'confirm':
case 'release': {
if (ref?.kind === 'fact' || ref?.kind === 'take') {
- if (!preview.raises) return { action: input.action, ref: preview.ref, status: 'unchanged', tier: 'user_confirmed', prior_tier: 'user_confirmed' };
const read = ref.kind === 'fact' ? readFactTarget : readTakeTarget;
const row = (await read(engine, ref.id))!;
+ // A contested fact: confirming either side resolves its supersede_fact proposal (one value stays current), even when it is already confirmed.
+ const resolved = ref.kind === 'fact' && row.binding === opts.binding ? await resolveContestedFactOnConfirm(engine, ref.id, decision) : null;
+ if (resolved?.status === 'accepted') return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier, detail: { resolved_proposal: resolved.ref } };
+ if (!preview.raises) return { action: input.action, ref: preview.ref, status: 'unchanged', tier: 'user_confirmed', prior_tier: 'user_confirmed' };
const ok = await setRowTier(engine, { table: row.table, id: row.id, sourceId: row.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by,
note: { via: confirmation.via, action: 'confirm', by: principalLabel(by) },
expect: async tx => (await read(tx, ref.id))?.binding === opts.binding });
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index 77f62e7fd9..c7163c1ef0 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -20,18 +20,51 @@ import { normalizeDimension } from '../chronicle/ontology.ts';
import { verbError, type OperationError } from '../ops/contract.ts';
import type { Principal } from '../persistence/model.ts';
import {
- decisionResult, getTrustProposal, insertTrustProposal, registerTrustProposalHandler, transitionTrustProposal, trustProposalRef,
+ decisionResult, getTrustProposal, insertTrustProposal, pendingTrustProposalsFor, registerTrustProposalHandler, transitionTrustProposal, trustProposalRef,
type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,
} from './proposals.ts';
import { tierRaiseFix } from './confirm.ts';
import { queueTierProjection } from './page-write.ts';
-import { compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
+import { compareTrust, effectiveWriteTrust, storedTrustTier, trustRankSql, type TrustTier, type WriteTrust } from './tier.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 {
return compareTrust(writer ?? 'unknown', storedTrustTier(target)) < 0;
}
+/** Word tokens for the keyless conflict slot: NFKC, lowercase, letters and digits only. */
+function slotTokens(text: string): Set<string> {
+ return new Set(text.normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').split(' ').filter(Boolean));
+}
+/** The keyless conflict-slot threshold: shared words over all words (Jaccard) of two claims about one entity. */
+export const LEXICAL_SLOT_THRESHOLD = 0.5;
+
+/**
+ * 38-3: the conflict slot on a brain without fact vectors. The most similar
+ * active fact about the same entity, kind and visibility that is MORE trusted
+ * than the writer, when the two claims share at least half their words and
+ * differ (an exact match is a duplicate, handled first). It only contests
+ * (files a proposal); without a vector the slot never supersedes. Deterministic,
+ * 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> {
+ if (!input.entity_slug) return null;
+ 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]);
+ const mine = slotTokens(input.fact);
+ let best: { id: number; trust_tier: TrustTier; score: number } | null = null;
+ for (const row of rows) {
+ const theirs = slotTokens(row.fact);
+ const shared = [...mine].filter(t => theirs.has(t)).length;
+ const score = shared / (mine.size + theirs.size - shared || 1);
+ if (score >= LEXICAL_SLOT_THRESHOLD && score < 1 && (!best || score > best.score)) best = { id: Number(row.id), trust_tier: storedTrustTier(row.trust_tier), score };
+ }
+ return best ? { id: best.id, trust_tier: best.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 }): Promise<{ proposal_ref: string }> {
const { id } = await insertTrustProposal(tx, {
@@ -158,6 +191,37 @@ export const TRUST_PAIR_STORE: PairProposalStore = {
},
};
+/**
+ * The same proposal read reversed (38-4): the owner confirmed the OLD side of a
+ * contested pair, so the contested new row is superseded by it. Accepting this
+ * view closes the proposal as `rejected` (the lower-tier write lost) and
+ * confirms the old row.
+ */
+export const TRUST_REVERSE_PAIR_STORE: PairProposalStore = {
+ name: 'trust_reverse',
+ async get(engine, id, lock) {
+ const pair = await TRUST_PAIR_STORE.get(engine, id, lock);
+ return pair ? { ...pair, old_fact_id: pair.new_fact_id, new_fact_id: pair.old_fact_id } : null;
+ },
+ transition: (engine, id, from, to, state) => TRUST_PAIR_STORE.transition(engine, id, from, to === 'accepted' ? 'rejected' : to, state),
+ onAccept: (tx, proposal) => TRUST_PAIR_STORE.onAccept!(tx, proposal),
+};
+
+/**
+ * CEO-9 + A5 (38-4): confirming either side of a contested fact resolves its
+ * pending supersede_fact proposal through the checked supersede, so one value
+ * stays current: confirming the contested (new) row accepts the proposal;
+ * confirming the higher-tier (old) row supersedes the contested one. Null when
+ * the fact has no pending supersede_fact proposal.
+ */
+export async function resolveContestedFactOnConfirm(engine: BrainEngine, factId: number, ctx: TrustDecisionContext): Promise<{ ref: string; status: string; reason?: string } | null> {
+ const pending = (await pendingTrustProposalsFor(engine, 'facts', factId)).find(p => p.action === 'supersede_fact');
+ if (!pending) return null;
+ const store = pending.related_id === factId ? TRUST_PAIR_STORE : TRUST_REVERSE_PAIR_STORE;
+ const result = await applyProposalAction(engine, pending.id, 'accept', ctx.config, store);
+ return { ref: trustProposalRef(pending.id), status: result.status, ...(result.reason ? { reason: result.reason } : {}) };
+}
+
function fromPairResult(proposal: TrustProposalRow, decision: TrustDecision, result: ProposalActionResult) {
const status = result.status === 'stale' ? 'superseded' : result.status;
return decisionResult(proposal, decision, status as never, result.reason ? { reason: result.reason } : {});
diff --git a/test/trust-guarded-supersession.test.ts b/test/trust-guarded-supersession.test.ts
index d7ce014df0..a1593247dc 100644
--- a/test/trust-guarded-supersession.test.ts
+++ b/test/trust-guarded-supersession.test.ts
@@ -207,7 +207,10 @@ describe('guarded fence re-projection (A5, ENG-1)', () => {
for (const id of Object.values(before)) await confirmFact(b, id);
const current = await operationsByName.get_page.handler(b.remote, { slug, include_content: true }) as Record<string, any>;
// Row 1 rewritten, row 2 removed, row 3 renumbered to 2 (behind a new row 1 order change).
- await run(b.remote, 'put_page', { slug, content: page('Erin', body([row(1, 'Erin lives in Bergen'), row(2, 'Erin speaks Norwegian')])), expected_revision: current.revision });
+ const rewrite = await run(b.remote, 'put_page', { slug, content: page('Erin', body([row(1, 'Erin lives in Bergen'), row(2, 'Erin speaks Norwegian')])), expected_revision: current.revision });
+ // DX-1 (38-2): the put_page response reports the guarded supersession it filed.
+ expect(rewrite.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ expect(rewrite.contested.proposal_refs).toHaveLength(2);
const after = await engine.executeRaw<{ id: number; fact: string; row_num: number | null; expired_at: unknown; trust_tier: string }>(
'SELECT id::int AS id, fact, row_num, expired_at, trust_tier FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 ORDER BY id', [b.sourceId, slug]);
const by = (fact: string) => after.find(r => r.fact === fact)!;
@@ -294,3 +297,45 @@ describe('owner release of a held fact (CEO-9, B6)', () => {
}
}), 90_000);
});
+
+describe('resolving a contested pair by confirming one side (38-4) and the keyless conflict slot (38-3)', () => {
+ test('without fact vectors a lower-tier same-subject contradiction is contested; confirming the old side supersedes the contested row, confirming the new side accepts', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { previewOwnerAction, applyOwnerAction } = await import('../src/core/trust/owner-actions.ts');
+ const confirm = async (ref: string) => {
+ const preview = await previewOwnerAction(currentEngine!, { action: 'confirm', ref });
+ return applyOwnerAction(currentEngine!, { action: 'confirm', ref }, { binding: preview.binding, confirmation: { via: 'tty' }, by: { kind: 'local_cli', id: 'owner-example' } });
+ };
+ let currentEngine: BrainEngine | null = null;
+ for (const engine of engines) {
+ currentEngine = engine;
+ const b = await brain(engine);
+ await ownerPage(b, 'people/ivy-example', 'Ivy.');
+ // Two confirmed facts and two keyless agent contradictions of them (no replaces, embedding disabled on this brain).
+ const homeFact = await run(b.local, 'remember', { fact: 'Ivy lives in Lisbon', provenance: 'owner', entity: 'people/ivy-example' });
+ const colorFact = await run(b.local, 'remember', { fact: 'Ivy favorite color is blue', provenance: 'owner', entity: 'people/ivy-example' });
+ for (const f of [homeFact, colorFact]) await confirmFact(b, Number(f.id));
+ const moved = await run(b.remote, 'remember', { fact: 'Ivy lives in Porto', provenance: 'chat', entity: 'people/ivy-example' });
+ const green = await run(b.remote, 'remember', { fact: 'Ivy favorite color is green', provenance: 'chat', entity: 'people/ivy-example' });
+ expect(moved.status).toBe('inserted');
+ expect(moved.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ expect(green.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ // Confirm the contested new row: the proposal is accepted and the old value is superseded.
+ const r1 = await confirm(`f${moved.id}`);
+ expect(r1).toMatchObject({ status: 'confirmed', detail: { resolved_proposal: moved.contested.proposal_ref } });
+ expect((await factRow(b, homeFact.id)).expired_at).not.toBeNull();
+ expect(await factRow(b, moved.id)).toMatchObject({ expired_at: null, trust_tier: 'user_confirmed' });
+ // Confirm the old side: the contested row is superseded by it and the proposal closes rejected.
+ const r2 = await confirm(`f${colorFact.id}`);
+ expect(r2).toMatchObject({ status: 'confirmed', detail: { resolved_proposal: green.contested.proposal_ref } });
+ expect(await factRow(b, green.id)).toMatchObject({ superseded_by: Number(colorFact.id) });
+ expect((await factRow(b, green.id)).expired_at).not.toBeNull();
+ expect(await factRow(b, colorFact.id)).toMatchObject({ expired_at: null, trust_tier: 'user_confirmed' });
+ const statuses = await engine.executeRaw<{ status: string }>(`SELECT status FROM trust_proposals WHERE id = ANY($1::bigint[]) ORDER BY id`,
+ [[parseTrustProposalRef(moved.contested.proposal_ref)!, parseTrustProposalRef(green.contested.proposal_ref)!]]);
+ expect(statuses.map(r => r.status)).toEqual(['accepted', 'rejected']);
+ // An unrelated agent fact about the same entity is not contested.
+ const other = await run(b.remote, 'remember', { fact: 'Ivy plays the cello on weekends', provenance: 'chat', entity: 'people/ivy-example' });
+ expect(other.contested).toBeUndefined();
+ }
+ }), 90_000);
+});