Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): guarded supersession for remember (replaces and conflict slot) and remote forget, trust proposals reuse the checked decide_proposals supersede (#5575 A5/I3, ENG-4, DX-1)

garrytan1d32a3485e05
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 9381c7574e..90872dee85 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -1014,6 +1014,14 @@ More: [docs/guides/repair.md#fix-not-writable](../../docs/guides/repair.md#fix-n
More: [docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately](../../docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately)
+### forget_requires_owner
+
+<a id="forget_requires_owner"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A remote caller asked to forget a fact more trusted than its own writes, so nothing was forgotten and the owner was asked instead. | Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired. | Do not retry. Tell the user the fact needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host). | user | `repeat the read that failed` | 3 | no |
+
### frontmatter_slug_conflict
<a id="frontmatter_slug_conflict"></a>
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index bee2a28ce6..d6bc9a1828 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -60,11 +60,12 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/eval/shared/autocut-replay.ts', reason: 'script-reachable' },
{ path: 'src/mcp/http-transport.ts', reason: 'script-reachable' },
{ path: 'src/mcp/tool-catalog.ts', reason: 'script-reachable' },
+ { path: 'src/core/trust/decide.ts', reason: 'held: memory-trust owner decisions (#5575 lane L1a); confirm_memory and gbrain trust confirm/drop/revert (owner-ops sub-lane, same feature PR) are its runtime callers; drop this row when they land' },
+ { path: 'src/core/trust/page-handlers.ts', reason: 'held: memory-trust lower_page handler (#5575 CEO-12), loaded by trust/decide.ts; drop this row when the owner ops land' },
{ path: 'src/core/archive-crawler-config.ts', reason: "held: skills/archive-crawler/SKILL.md describes the scan_paths safety fence as code-enforced; wire-or-retract is a product decision" },
{ path: 'src/core/progressive-batch/orchestrator.ts', reason: 'held: TODOS.md keeps an open item to re-compose progressive-batch with --workers on the 3 reindex sites (callers dropped in the v0.41.17.0 merge)' },
{ path: 'src/core/progressive-batch/retrofit-wrap.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },
{ path: 'src/core/progressive-batch/stage-report.ts', reason: 'held: progressive-batch re-compose item still open in TODOS.md' },
- { path: 'src/core/trust/confirm.ts', reason: 'held: memory-trust foundation (#5575 lane F); confirm_memory and gbrain trust review/release/revert (lane L1) are its runtime callers in the same feature PR; drop this row when they land' },
{ path: 'src/core/ingestion/daemon.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (public gbrain/ingestion export, docs/guides/data-ingestion.md)' },
{ path: 'src/core/ingestion/dedup.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/skillpack-load.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 3e4a989cfa..386031e65d 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -165,6 +165,7 @@ export const CODES = {
file_removed_during_scan: { class: 'retryable', summary: "A file lint listed was removed before lint read it, so it was not linted.", why: "Another process deleted or renamed the file during the run; lint reports it and continues with the remaining files.", docs: 'docs/guides/repair.md#file-removed-during-scan', suggestion: "Re-run gbrain lint on the same target; it lints the files present now." },
file_too_large: { class: 'caller', summary: "The file is over the import size limit (5 MB for Markdown and code, 10 MiB for any sync read), so it was not imported.", why: "Size limits bound parsing, chunking and embedding cost. The same bytes refuse on every retry.", suggestion: 'Split the file into smaller files, or leave it out of the source (sync.exclude), then sync or import again.' },
follow_approval_required: { class: 'caller', summary: "Following a brain's shared skills needs the user's explicit follow approval.", docs: 'docs/guides/shared-brain-skills.md#approve-publication-following-and-editing-separately' },
+ forget_requires_owner: { class: 'consent', exit: 3, actor: 'user', summary: "A remote caller asked to forget a fact more trusted than its own writes, so nothing was forgotten and the owner was asked instead.", why: "Lower-trust writers cannot overwrite, supersede or forget what the owner confirmed or curated (#5575 guarded supersession). The request became a trust proposal the owner can accept on the brain host; forget's frozen expired meaning is unchanged because nothing expired.", docs: 'docs/guides/error-codes.md#forget_requires_owner', suggestion: 'Do not retry. Tell the user the fact needs their decision and give them the command in fix (gbrain trust confirm <proposal_ref> on the brain host).' },
frontmatter_slug_conflict: { class: 'caller', summary: "The file's frontmatter `slug:` names a different page than its path does.", why: "The path decides a file's page; a conflicting declared slug would overwrite or fork another page, so the file is refused until one of them changes.", suggestion: 'Remove the `slug:` line or make it match the path, then commit and sync again.' },
full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
gate_failed: { class: 'caller', summary: "The eval gate found retrieval regressions or correctness below its thresholds." },
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index fc73b4c4d9..bbda356b20 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -31,6 +31,7 @@ import { readFix } from '../ops/op-fix.ts';
import { getProposal, transitionProposal, type ProposalRow } from '../ai/decide/proposals-store.ts';
import { strikeFenceRow, supersededFact } from './forget.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { withTrustKeep } from '../persistence/context.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
@@ -61,6 +62,32 @@ export interface ProposalActionResult {
reason?: string;
}
+/**
+ * The proposal record a checked supersede reads and transitions: decide_proposals
+ * (S9) by default, or another typed store with the same pair shape (#5575
+ * trust_proposals, registered by trust/supersede-handlers.ts). `onAccept` /
+ * `onUndo` run inside the same transaction after the facts change.
+ */
+export type PairProposal = Pick<ProposalRow, 'id' | 'source_id' | 'old_fact_id' | 'new_fact_id' | 'status' | 'before_state' | 'after_state'>;
+export interface PairProposalStore {
+ name: string;
+ get(engine: BrainEngine, id: number, lock?: boolean): Promise<PairProposal | null>;
+ transition(engine: BrainEngine, id: number, from: string, to: string, state?: { before?: string | null; after?: string | null }): Promise<boolean>;
+ onAccept?(tx: BrainEngine, proposal: PairProposal): Promise<void>;
+ onUndo?(tx: BrainEngine, proposal: PairProposal): Promise<void>;
+}
+export const DECIDE_PROPOSAL_STORE: PairProposalStore = {
+ name: 'decide', get: getProposal,
+ transition: (engine, id, from, to, state) => transitionProposal(engine, id, from as ProposalRow['status'], to as ProposalRow['status'], state),
+};
+const pairStores = new Map<string, PairProposalStore>([[DECIDE_PROPOSAL_STORE.name, DECIDE_PROPOSAL_STORE]]);
+export function registerPairProposalStore(store: PairProposalStore): void { pairStores.set(store.name, store); }
+async function pairStore(name: unknown): Promise<PairProposalStore | null> {
+ if (name === undefined || name === null) return DECIDE_PROPOSAL_STORE;
+ if (name === 'trust' && !pairStores.has('trust')) await import('../trust/supersede-handlers.ts');
+ return typeof name === 'string' ? pairStores.get(name) ?? null : null;
+}
+
export class ProposalConflictError extends Error {
constructor(message: string) { super(message); this.name = 'ProposalConflictError'; }
}
@@ -137,7 +164,7 @@ export function undoRefusal(state: { before: SupersedeState; after: SupersedeSta
// Database units (shared by the unmanaged and managed paths)
// ---------------------------------------------------------------------------
-async function expireOld(tx: BrainEngine, proposal: ProposalRow): Promise<void> {
+async function expireOld(tx: BrainEngine, proposal: PairProposal): Promise<void> {
const rows = await tx.executeRaw<{ id: number }>(
`UPDATE facts SET expired_at = now(), valid_until = LEAST(COALESCE(valid_until, now()), now()), superseded_by = $3
WHERE id = $1 AND source_id = $2 AND expired_at IS NULL RETURNING id`,
@@ -146,24 +173,26 @@ async function expireOld(tx: BrainEngine, proposal: ProposalRow): Promise<void>
}
/** Record the after state (read back inside the transaction) and move the proposal to accepted. */
-async function finishAccept(tx: BrainEngine, proposal: ProposalRow, before: SupersedeState, fenceAfter: FenceState | null): Promise<void> {
+async function finishAccept(tx: BrainEngine, proposal: PairProposal, before: SupersedeState, fenceAfter: FenceState | null, store: PairProposalStore): Promise<void> {
const [oldF, newF] = await Promise.all([loadPairFact(tx, proposal.old_fact_id), loadPairFact(tx, proposal.new_fact_id)]);
const after: SupersedeState = { old: factFields(oldF!), new: factFields(newF!), fence: fenceAfter };
- if (!await transitionProposal(tx, proposal.id, 'pending', 'accepted', { before: JSON.stringify(before), after: JSON.stringify(after) })) {
+ if (!await store.transition(tx, proposal.id, 'pending', 'accepted', { before: JSON.stringify(before), after: JSON.stringify(after) })) {
throw new ProposalConflictError('the proposal is no longer pending');
}
+ await store.onAccept?.(tx, proposal);
}
-async function applyUndoDb(tx: BrainEngine, proposal: ProposalRow, before: SupersedeState, after: SupersedeState): Promise<void> {
+async function applyUndoDb(tx: BrainEngine, proposal: PairProposal, before: SupersedeState, after: SupersedeState, store: PairProposalStore): Promise<void> {
const rows = await tx.executeRaw<{ id: number }>(
`UPDATE facts SET expired_at = $3::timestamptz, valid_until = $4::timestamptz, superseded_by = $5
WHERE id = $1 AND source_id = $2 AND superseded_by IS NOT DISTINCT FROM $6 RETURNING id`,
[proposal.old_fact_id, proposal.source_id, before.old.expired_at, before.old.valid_until, before.old.superseded_by, after.old.superseded_by]);
if (rows.length !== 1) throw new ProposalConflictError('the old fact changed during undo');
- if (!await transitionProposal(tx, proposal.id, 'accepted', 'undone')) throw new ProposalConflictError('the proposal is no longer accepted');
+ if (!await store.transition(tx, proposal.id, 'accepted', 'undone')) throw new ProposalConflictError('the proposal is no longer accepted');
+ await store.onUndo?.(tx, proposal);
}
-function parseStates(p: ProposalRow): { before: SupersedeState; after: SupersedeState } | null {
+function parseStates(p: PairProposal): { before: SupersedeState; after: SupersedeState } | null {
try { return p.before_state && p.after_state ? { before: JSON.parse(p.before_state), after: JSON.parse(p.after_state) } : null; } catch { return null; }
}
@@ -202,15 +231,15 @@ async function withFenceLocks<T>(engine: BrainEngine, slug: string | null, sourc
return withSourceFilesystemLock(engine, target.writeRoot, () => withPageLock(slug, () => run(target.filePath), { timeoutMs: 5_000 }));
}
-async function acceptUnmanaged(engine: BrainEngine, proposal: ProposalRow): Promise<ProposalActionResult> {
+async function acceptUnmanaged(engine: BrainEngine, proposal: PairProposal, store: PairProposalStore): Promise<ProposalActionResult> {
const first = await loadPairFact(engine, proposal.old_fact_id);
return withFenceLocks(engine, first?.source_markdown_slug ?? null, proposal.source_id, async (filePath) => {
- const fresh = await getProposal(engine, proposal.id);
+ const fresh = await store.get(engine, proposal.id);
if (!fresh || fresh.status !== 'pending') return { id: proposal.id, action: 'accept', status: 'refused', reason: fresh?.status ?? 'not_found' };
const [oldF, newF] = await Promise.all([loadPairFact(engine, fresh.old_fact_id), loadPairFact(engine, fresh.new_fact_id)]);
const stale = staleReason(fresh, oldF, newF, Date.now());
if (stale) {
- await transitionProposal(engine, fresh.id, 'pending', 'stale');
+ await store.transition(engine, fresh.id, 'pending', 'stale');
return { id: fresh.id, action: 'accept', status: 'stale', reason: stale };
}
const slug = oldF!.source_markdown_slug;
@@ -222,12 +251,13 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: ProposalRow): Prom
const before: SupersedeState = { old: factFields(oldF!), new: factFields(newF!), fence: plan ? fence(plan.before, snapshot?.revision ?? null) : null };
let published = false;
try {
- await maintenanceTransaction(engine, async (tx) => {
+ // The strike edits a managed fence without authoring the page: it keeps its trust tier (#5575 ENG-1).
+ await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => {
const revision = plan ? await mirrorBody(tx, slug!, fresh.source_id, plan.body, fileBody !== null) : null;
await expireOld(tx, fresh);
- await finishAccept(tx, fresh, before, plan ? fence(plan.after, revision) : null);
+ await finishAccept(tx, fresh, before, plan ? fence(plan.after, revision) : null, store);
if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
- });
+ }));
} catch (err) {
if (published) writeFileSync(filePath!, fileBody!, 'utf-8');
throw err;
@@ -236,10 +266,10 @@ async function acceptUnmanaged(engine: BrainEngine, proposal: ProposalRow): Prom
});
}
-async function undoUnmanaged(engine: BrainEngine, proposal: ProposalRow): Promise<ProposalActionResult> {
+async function undoUnmanaged(engine: BrainEngine, proposal: PairProposal, store: PairProposalStore): Promise<ProposalActionResult> {
const first = await loadPairFact(engine, proposal.old_fact_id);
return withFenceLocks(engine, first?.source_markdown_slug ?? null, proposal.source_id, async (filePath) => {
- const fresh = await getProposal(engine, proposal.id);
+ const fresh = await store.get(engine, proposal.id);
if (!fresh || fresh.status !== 'accepted') return { id: proposal.id, action: 'undo', status: 'refused', reason: fresh?.status ?? 'not_found' };
const states = parseStates(fresh);
if (!states) return { id: fresh.id, action: 'undo', status: 'refused', reason: 'no_recorded_state' };
@@ -259,11 +289,11 @@ async function undoUnmanaged(engine: BrainEngine, proposal: ProposalRow): Promis
}
let published = false;
try {
- await maintenanceTransaction(engine, async (tx) => {
+ await maintenanceTransaction(engine, (tx) => withTrustKeep(tx, ['pages'], async () => {
if (plan) await mirrorBody(tx, before.fence!.slug, fresh.source_id, plan.body, fileBody !== null);
- await applyUndoDb(tx, fresh, before, after);
+ await applyUndoDb(tx, fresh, before, after, store);
if (plan && fileBody !== null) { publishFile(filePath!, plan.body); published = true; }
- });
+ }));
} catch (err) {
if (published) writeFileSync(filePath!, fileBody!, 'utf-8');
throw err;
@@ -280,15 +310,16 @@ const proposalsFix = (why: string) => readFix(why, { argv: ['gbrain', 'decide',
/** Coordinator preparer: the same plan as the unmanaged path, published by the coordinator as one unit. */
export async function prepareProposalMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
- const p = row.intent as { proposal_id?: number; action?: ProposalAction } | null;
+ const p = row.intent as { proposal_id?: number; action?: ProposalAction; store?: string } | null;
const id = Number(p?.proposal_id);
- if (row.operation !== DECIDE_PROPOSAL_OPERATION || !Number.isSafeInteger(id) || (p?.action !== 'accept' && p?.action !== 'undo') || row.authority.remote) {
+ const store = await pairStore(p?.store);
+ if (row.operation !== DECIDE_PROPOSAL_OPERATION || !Number.isSafeInteger(id) || (p?.action !== 'accept' && p?.action !== 'undo') || row.authority.remote || !store) {
throw opError('permission_denied', 'Unsupported decide proposal intent.',
`Request ${row.request_id} in source ${row.source_id} is not a local accept or undo of a proposal, so the coordinator refused it and nothing changed. Decide proposals from the brain host's CLI with gbrain decide proposals accept or undo.`,
{ fix: proposalsFix('Lists proposals with their ids and status, read-only.') });
}
const action = p.action;
- const proposal = await getProposal(engine, id);
+ const proposal = await store.get(engine, id);
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
const observedRevision = snapshot?.revision ?? null;
const done = (outcome: Record<string, unknown>): PreparedMutation => ({ observedRevision, noop: true, apply: async () => outcome });
@@ -296,7 +327,7 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
if (proposal.status !== (action === 'accept' ? 'pending' : 'accepted')) return done({ id, action, status: 'refused', reason: proposal.status });
const [oldF, newF] = await Promise.all([loadPairFact(engine, proposal.old_fact_id), loadPairFact(engine, proposal.new_fact_id)]);
const unchanged = async (tx: BrainEngine) => {
- const current = await getProposal(tx, id, true);
+ const current = await store.get(tx, id, true);
const [o, n] = await Promise.all([loadPairFact(tx, proposal.old_fact_id, true), loadPairFact(tx, proposal.new_fact_id, true)]);
if (current?.status !== proposal.status || !o || !n || !oldF || !newF || !sameFields(factFields(o), factFields(oldF)) || !sameFields(factFields(n), factFields(newF))) {
throw opError('revision_conflict', 'The proposal or its facts changed during preparation.',
@@ -317,7 +348,7 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
if (action === 'accept') {
const stale = staleReason(proposal, oldF, newF, Date.now());
if (stale) return { observedRevision, validate: unchanged, apply: async (tx) => {
- await transitionProposal(tx, id, 'pending', 'stale');
+ await store.transition(tx, id, 'pending', 'stale');
return { id, action, status: 'stale', reason: stale };
} };
const plan = oldF!.source_markdown_slug === row.slug && snapshot ? planAcceptFence(snapshot.page.compiled_truth, oldF!, newF!, formatFenceDate(new Date())) : null;
@@ -329,7 +360,7 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
await expireOld(tx, proposal);
await page?.apply(tx);
const revision = plan ? (await tx.readPageSnapshot(row.slug, { sourceId: row.source_id }))?.revision ?? null : null;
- await finishAccept(tx, proposal, before, plan ? fence(plan.after, revision) : null);
+ await finishAccept(tx, proposal, before, plan ? fence(plan.after, revision) : null, store);
return { id, action, status: 'accepted' };
} };
}
@@ -346,7 +377,7 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
}
return { observedRevision, file: page?.file, validate: async (tx) => { await unchanged(tx); await page?.validate?.(tx); }, apply: async (tx) => {
await page?.apply(tx);
- await applyUndoDb(tx, proposal, before, after);
+ await applyUndoDb(tx, proposal, before, after, store);
return { id, action, status: 'undone' };
} };
}
@@ -356,7 +387,7 @@ async function preparePage(engine: BrainEngine, row: WriteRequest, config: GBrai
return preparePageMutation(engine, row, config);
}
-async function submitManaged(engine: BrainEngine, proposal: ProposalRow, action: ProposalAction, config: GBrainConfig): Promise<ProposalActionResult> {
+async function submitManaged(engine: BrainEngine, proposal: PairProposal, action: ProposalAction, config: GBrainConfig, store: PairProposalStore): Promise<ProposalActionResult> {
const { initializeLocalPersistence, requestPrincipalForContext } = await import('../persistence/page-mutations.ts');
const { submissionAuthority } = await import('../persistence/authority.ts');
const { admitWrite } = await import('../persistence/journal.ts');
@@ -380,7 +411,7 @@ async function submitManaged(engine: BrainEngine, proposal: ProposalRow, action:
const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
const binding = snapshot && writeThrough ? await getWorktreeBinding(engine, sourceId) : null;
if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';
- const intent = { proposal_id: proposal.id, action };
+ const intent = { proposal_id: proposal.id, action, ...(store === DECIDE_PROPOSAL_STORE ? {} : { store: store.name }) };
const row = await admitWrite(engine, {
principal, operation: DECIDE_PROPOSAL_OPERATION, sourceId, sourceIncarnation: source.incarnation, slug, pageId: snapshot?.page.id ?? null,
requestId: randomUUID(), callerIntent: intent, intent, authority, worktreeId: binding?.worktree_id ?? null, topologyGeneration: binding?.topology_generation ?? null,
@@ -397,13 +428,14 @@ async function managed(engine: BrainEngine): Promise<boolean> {
}
/** Accept or undo one proposal through the brain's supersede write path. */
-export async function applyProposalAction(engine: BrainEngine, id: number, action: ProposalAction, config?: GBrainConfig): Promise<ProposalActionResult> {
- const proposal = await getProposal(engine, id);
+export async function applyProposalAction(engine: BrainEngine, id: number, action: ProposalAction, config?: GBrainConfig,
+ store: PairProposalStore = DECIDE_PROPOSAL_STORE): Promise<ProposalActionResult> {
+ const proposal = await store.get(engine, id);
if (!proposal) return { id, action, status: 'not_found' };
const want = action === 'accept' ? 'pending' : 'accepted';
if (proposal.status !== want) return { id, action, status: 'refused', reason: proposal.status };
- if (await managed(engine)) return submitManaged(engine, proposal, action, config ?? ({ engine: engine.kind } as GBrainConfig));
- return action === 'accept' ? acceptUnmanaged(engine, proposal) : undoUnmanaged(engine, proposal);
+ if (await managed(engine)) return submitManaged(engine, proposal, action, config ?? ({ engine: engine.kind } as GBrainConfig), store);
+ return action === 'accept' ? acceptUnmanaged(engine, proposal, store) : undoUnmanaged(engine, proposal, store);
}
export async function rejectProposal(engine: BrainEngine, id: number): Promise<ProposalActionResult> {
diff --git a/src/core/facts/single-prepare.ts b/src/core/facts/single-prepare.ts
index 9d4ae34443..5d15198863 100644
--- a/src/core/facts/single-prepare.ts
+++ b/src/core/facts/single-prepare.ts
@@ -6,7 +6,7 @@ import { isFactWithdrawn } from './withdrawal.ts';
import { assertFactNotPurged } from './withdrawal.ts';
import { cosineVerdict } from './capture-dedup.ts';
-export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null };
+export type FactCandidate = FactRow & { source_markdown_slug: string | null; row_num: number | null; trust_tier?: string | null };
export interface FactDecision { status: 'inserted' | 'duplicate' | 'superseded'; candidate: FactCandidate | null; }
export interface SingleFactIntent {
fact: string; kind: FactRow['kind']; visibility: FactRow['visibility']; entity_slug: string | null;
@@ -44,8 +44,8 @@ export async function decideSingleFact(engine: BrainEngine, sourceId: string, in
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 }>(
- 'SELECT id,source_markdown_slug,row_num FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
+ const metadata = await engine.executeRaw<{ id: number; source_markdown_slug: string | null; row_num: number | null; trust_tier: string | null }>(
+ 'SELECT id,source_markdown_slug,row_num,trust_tier FROM facts WHERE source_id=$1 AND id=ANY($2::int[])',
[sourceId, candidates.map(c => c.id)]);
let candidate: FactCandidate | null = null;
let score = -1;
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index f44f1f9fd7..512935c945 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -1,3 +1,4 @@
+import { guardRemoteForget, remoteForgetRaced, supersessionGuarded } from '../trust/supersede-handlers.ts';
import { randomUUID } from 'node:crypto';
import type { OperationContext } from '../ops/contract.ts';
import { opError, OperationError, verbError } from '../ops/contract.ts';
@@ -179,7 +180,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
return response;
}
-interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; }
+interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; trust_tier?: string | null; }
/** Withdrawal commits independently of filesystem ownership and request FIFO. */
export async function submitForgetMutation(ctx: OperationContext, operation: 'forget' | 'forget_fact', params: Record<string, unknown>): Promise<Record<string, unknown>> {
@@ -192,6 +193,8 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
const 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.');
+ // #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 });
// 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'] = [];
@@ -211,10 +214,11 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
assertReplayIntent(prior, intentDigest({ operation, sourceId, slug: prior.slug, callerIntent }));
return prior;
}
- const [fact] = await tx.executeRaw<WithdrawalTarget>(`SELECT id,entity_slug,source_markdown_slug,expired_at FROM facts
- WHERE id=$1 AND source_id=$2 AND ($3::boolean=false OR visibility='world')`, [id, sourceId, ctx.remote !== false]);
+ 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]);
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);
const slug = fact.source_markdown_slug ?? fact.entity_slug ?? 'memory/unattributed';
enforceClientSlugFence(ctx, slug, operation); enforceSubagentSlugFence(ctx, slug, operation);
const authority = await submissionAuthority({ ...ctx, engine: tx }, operation, sourceId, source.incarnation, slug);
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index 022bc90802..b8f64538e6 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -16,6 +16,9 @@ import type { WriteRequest } from './model.ts';
import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';
import { inferenceNote } from '../facts/subject-infer-write.ts';
import { normalizeTargetFences } from '../fence-repair/import-step.ts';
+import { requestChannelTrust } from '../trust/channel.ts';
+import { recordContestedFact, supersessionGuarded } from '../trust/supersede-handlers.ts';
+import { storedTrustTier } from '../trust/tier.ts';
import { pageFencesNormalized } from '../fence-repair/report.ts';
function receiptFix(row: WriteRequest): Action {
@@ -31,7 +34,7 @@ function conflict(row: WriteRequest): never {
function candidateState(value: Awaited<ReturnType<typeof decideSingleFact>>): string {
const c = value.candidate;
return JSON.stringify([value.status, c?.id, c?.fact, c?.kind, c?.visibility,
- c?.valid_until ? new Date(c.valid_until).toISOString() : null, c?.source_markdown_slug, c?.row_num]);
+ c?.valid_until ? new Date(c.valid_until).toISOString() : null, c?.source_markdown_slug, c?.row_num, c?.trust_tier ?? null]);
}
export const NO_ENTITY_HINT = 'Saved without an entity, so entity-scoped recall will not find it. Pass `entity` (the person, company or project this fact is about) to link it.';
function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', entitySlug: string | null, validUntil: Date | string | null, degraded: boolean, p: Record<string, unknown>, supersededId?: number) {
@@ -76,6 +79,10 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
? 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);
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';
+ const contested = decision.status === 'superseded' && supersessionGuarded(writerTier, decision.candidate!.trust_tier);
+ const status = contested ? 'inserted' : decision.status;
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);
@@ -106,7 +113,7 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
rowNum = appended.rowNum;
let body = appended.body;
const old = decision.candidate;
- if (decision.status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) {
+ if (status === 'superseded' && old?.source_markdown_slug === row.slug && old.row_num != null) {
const rows = parseFactsFence(body).facts.map(f => f.rowNum === old.row_num
? { ...f, active: false, supersededBy: rowNum, context: `superseded by #${rowNum}` } : f);
body = replaceOrInsertFactsFence(body, renderFactsTable(rows));
@@ -132,8 +139,11 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
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
id = inserted.id;
}
- if (decision.status === 'superseded') await tx.executeRaw(`UPDATE facts SET expired_at=now(),superseded_by=$3
+ 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]);
- return { ...outcome(id, decision.status, input.entity_slug, validUntil, degraded, p, decision.status === 'superseded' ? decision.candidate!.id : undefined), ...fencesNormalized };
+ 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;
+ return { ...outcome(id, status, input.entity_slug, validUntil, degraded, p, status === 'superseded' ? decision.candidate!.id : undefined), ...fencesNormalized,
+ ...(contestedBy ? { contested: contestedBy } : {}) };
} };
}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 48cfd73ded..2b85158a5c 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -462,8 +462,7 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
`The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
- const preparedImport: PreparedMutation = { observedRevision: snapshot?.revision ?? null,
- trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath),
+ const preparedImport: PreparedMutation = { observedRevision: snapshot?.revision ?? null, trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath),
// Tells the #5470 screen the content is unchanged; publication still queues its effects.
contentUnchanged: ready.noop && !moved && !writeback,
...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),
diff --git a/src/core/trust/decide.ts b/src/core/trust/decide.ts
index e59a2aa709..a1a05dc80c 100644
--- a/src/core/trust/decide.ts
+++ b/src/core/trust/decide.ts
@@ -3,7 +3,11 @@
* handler, then dispatches. Callers (the confirm/review ops, the CLI, IPC
* delegation) establish the owner's confirmation first (trust/confirm.ts).
*/
-import './supersede-handlers.ts';
-import './page-handlers.ts';
+import { SUPERSEDE_HANDLER_ACTIONS } from './supersede-handlers.ts';
+import { PAGE_HANDLER_ACTIONS } from './page-handlers.ts';
+import type { TrustProposalAction } from './proposals.ts';
+
+/** Every trust proposal action with a registered accept handler. */
+export const TRUST_HANDLER_ACTIONS: readonly TrustProposalAction[] = [...SUPERSEDE_HANDLER_ACTIONS, ...PAGE_HANDLER_ACTIONS];
export { decideTrustProposal } from './proposals.ts';
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index 61e88ce194..0e55fb4fd0 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -3,4 +3,6 @@
* keeps the agent edit at its lowered tier; revert restores the prior owner
* version's content and tier through the CEO-9 rule.
*/
-export {};
+import type { TrustProposalAction } from './proposals.ts';
+
+export const PAGE_HANDLER_ACTIONS: readonly TrustProposalAction[] = [];
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
index 46926e38f0..d050beb7f9 100644
--- a/src/core/trust/supersede-handlers.ts
+++ b/src/core/trust/supersede-handlers.ts
@@ -1,5 +1,165 @@
/**
- * Checked handlers for guarded-supersession trust proposals (#5575 A5/I3,
- * ENG-4): supersede_fact, supersede_take and forget.
+ * Guarded supersession (#5575 A5/I3, ENG-4): a write whose tier is lower than
+ * the fact or take it would supersede (or forget) does not change it. The new
+ * row is inserted active and contested, and a `trust_proposals` row links the
+ * higher-tier target to it; the owner's accept applies the supersession
+ * through the checked decide_proposals primitives (facts/proposal-supersede.ts,
+ * managed and unmanaged paths) and confirms the new row (CEO-9). Writers make
+ * the decision in prepare and re-check it in validate(tx) under lock.
+ *
+ * before_state records the guard: `{ guard, old: {id, tier}, new: {id, tier} }`
+ * (ids and tiers only, never claim text). The checked supersede's own
+ * before/after record lives in after_state.supersede.
*/
-export {};
+import type { BrainEngine } from '../engine.ts';
+import {
+ applyProposalAction, registerPairProposalStore, type PairProposal, type PairProposalStore, type ProposalActionResult,
+} from '../facts/proposal-supersede.ts';
+import { withTrustPromotion, withWriteAttribution } from '../persistence/context.ts';
+import { verbError, type OperationError } from '../ops/contract.ts';
+import type { Principal } from '../persistence/model.ts';
+import {
+ decisionResult, getTrustProposal, insertTrustProposal, registerTrustProposalHandler, transitionTrustProposal, trustProposalRef,
+ type TrustDecision, type TrustDecisionContext, type TrustProposalAction, type TrustProposalRow,
+} from './proposals.ts';
+import { tierRaiseFix } from './confirm.ts';
+import { compareTrust, storedTrustTier, type TrustTier } 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;
+}
+
+/** 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, {
+ 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 } },
+ });
+ return { proposal_ref: trustProposalRef(id) };
+}
+
+/** The pending supersede_take proposal for a contested take write. */
+export async function recordContestedTake(tx: BrainEngine, input: { sourceId: string; oldId: number; oldTier: TrustTier; newId: number; newTier: TrustTier; guard: string }): Promise<{ proposal_ref: string }> {
+ const { id } = await insertTrustProposal(tx, {
+ action: 'supersede_take', sourceId: input.sourceId, target: { table: 'takes', id: input.oldId }, related: { table: 'takes', id: input.newId },
+ proposer: input.guard, before: { guard: input.guard, old: { id: input.oldId, tier: input.oldTier }, new: { id: input.newId, tier: input.newTier } },
+ });
+ return { proposal_ref: trustProposalRef(id) };
+}
+
+/**
+ * A remote `forget` of a higher-tier fact (DX-1): files a `forget` proposal in
+ * its own transaction (attributed to the caller) and returns the verb error
+ * `forget_requires_owner` carrying its ref. The frozen `forget.expired`
+ * meaning is untouched: nothing was expired. A retry reuses the same proposal.
+ */
+export async function forgetRequiresOwner(engine: BrainEngine, input: { sourceId: string; factId: number; factTier: TrustTier; writerTier: TrustTier; principal: Principal; reason: string | null }): Promise<OperationError> {
+ const { id } = await engine.transaction(tx => withWriteAttribution(tx, { requestId: null, principal: input.principal }, () => insertTrustProposal(tx, {
+ action: 'forget', sourceId: input.sourceId, target: { table: 'facts', id: input.factId }, proposer: 'remote_forget',
+ before: { guard: 'remote_forget', fact: { id: input.factId, tier: input.factTier }, writer_tier: input.writerTier, ...(input.reason ? { has_reason: true } : {}) },
+ })));
+ const ref = trustProposalRef(id);
+ // Frozen MEMORY_VERBS v1 pair: `error` stays scope_denied, `code` is the canonical forget_requires_owner.
+ const error = verbError('scope_denied',
+ `forget_requires_owner: fact #${input.factId} is ${input.factTier}; an agent cannot forget it. Proposal ${ref} asks the owner.`,
+ `Do not retry. Tell the user fact #${input.factId} needs their decision: they can forget it with gbrain trust confirm ${ref} on the brain host.`,
+ JSON.stringify({ proposal_ref: ref, fact_id: String(input.factId) }));
+ error.canonical = 'forget_requires_owner';
+ error.fix = tierRaiseFix(['gbrain', 'trust', 'confirm', ref],
+ 'Forgetting a fact the owner confirmed or curated is their decision; the confirm prompt applies the forget.',
+ `Run on the brain host, in a terminal: gbrain trust confirm ${ref}`);
+ return error;
+}
+
+/** 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]);
+ if (!fact || !supersessionGuarded('agent_written', fact.trust_tier)) return;
+ throw await forgetRequiresOwner(engine, { ...input, factTier: storedTrustTier(fact.trust_tier), writerTier: 'agent_written' });
+}
+
+/** The target's tier rose between the pre-check and the locked read: refuse without changing anything; a retry files the proposal. */
+export function remoteForgetRaced(factId: number): OperationError {
+ const error = verbError('scope_denied', `forget_requires_owner: fact #${factId} became more trusted while this forget was prepared; nothing was forgotten.`,
+ 'Retry once to file the owner proposal, then tell the user it needs their decision.');
+ error.canonical = 'forget_requires_owner';
+ return error;
+}
+
+// ---------------------------------------------------------------------------
+// trust_proposals as a checked-supersede store
+// ---------------------------------------------------------------------------
+
+/** decide_proposals says `stale` where trust_proposals says `superseded` (the proposal no longer applies). */
+const toPair = (status: string) => (status === 'superseded' ? 'stale' : status);
+const fromPair = (status: string) => (status === 'stale' ? 'superseded' : status);
+
+function pairOf(row: TrustProposalRow): PairProposal | null {
+ if ((row.action !== 'supersede_fact') || row.related_id === null) return null;
+ const supersede = row.after_state.supersede as { before?: unknown; after?: unknown } | undefined;
+ return {
+ id: row.id, source_id: row.source_id, old_fact_id: row.target_id, new_fact_id: row.related_id, status: toPair(row.status) as PairProposal['status'],
+ before_state: supersede?.before ? JSON.stringify(supersede.before) : null, after_state: supersede?.after ? JSON.stringify(supersede.after) : null,
+ };
+}
+
+export const TRUST_PAIR_STORE: PairProposalStore = {
+ name: 'trust',
+ async get(engine, id, lock) {
+ const row = await getTrustProposal(engine, id, lock);
+ return row ? pairOf(row) : null;
+ },
+ async transition(engine, id, from, to, state) {
+ const row = await getTrustProposal(engine, id, true);
+ if (!row) return false;
+ const after = state?.before || state?.after
+ ? { ...row.after_state, supersede: { before: state.before ? JSON.parse(state.before) : null, after: state.after ? JSON.parse(state.after) : null } }
+ : undefined;
+ return transitionTrustProposal(engine, id, fromPair(from) as TrustProposalRow['status'], fromPair(to) as TrustProposalRow['status'], after ? { after } : {});
+ },
+ /** CEO-9: the owner's accept also confirms the new fact. */
+ async onAccept(tx, proposal) {
+ await withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw(
+ `UPDATE facts SET trust_tier = 'user_confirmed' WHERE id = $1 AND source_id = $2`, [proposal.new_fact_id, proposal.source_id]));
+ },
+ /** Undo returns the new fact to the tier it had before the accept confirmed it (lowering needs no promotion). */
+ async onUndo(tx, proposal) {
+ const row = await getTrustProposal(tx, proposal.id);
+ const prior = storedTrustTier((row?.before_state.new as { tier?: unknown } | undefined)?.tier);
+ await tx.executeRaw(`UPDATE facts SET trust_tier = $3 WHERE id = $1 AND source_id = $2`, [proposal.new_fact_id, proposal.source_id, prior]);
+ },
+};
+registerPairProposalStore(TRUST_PAIR_STORE);
+
+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 } : {});
+}
+
+/** The actions this module registers handlers for (supersede_take joins when the takes guard lands). */
+export const SUPERSEDE_HANDLER_ACTIONS: readonly TrustProposalAction[] = ['supersede_fact', 'forget'];
+
+registerTrustProposalHandler('supersede_fact', {
+ async accept(engine, proposal, ctx: TrustDecisionContext) {
+ return fromPairResult(proposal, 'accept', await applyProposalAction(engine, proposal.id, 'accept', ctx.config, TRUST_PAIR_STORE));
+ },
+ async undo(engine, proposal, ctx: TrustDecisionContext) {
+ return fromPairResult(proposal, 'undo', await applyProposalAction(engine, proposal.id, 'undo', ctx.config, TRUST_PAIR_STORE));
+ },
+});
+
+/** The owner applies the forget a remote caller asked for, as a trusted local forget. */
+registerTrustProposalHandler('forget', {
+ async accept(engine, proposal, ctx: TrustDecisionContext) {
+ const { submitForgetMutation } = await import('../persistence/memory-mutations.ts');
+ const local = { engine, sourceId: proposal.source_id, remote: false as const, dryRun: false,
+ config: ctx.config ?? ({ engine: engine.kind } as never), logger: { info() {}, warn() {}, error() {} } };
+ const outcome = await submitForgetMutation(local as never, 'forget', { id: String(proposal.target_id), request_id: crypto.randomUUID(),
+ reason: `owner accepted ${trustProposalRef(proposal.id)}` });
+ if (!await transitionTrustProposal(engine, proposal.id, 'pending', 'accepted', { decidedBy: ctx.decidedBy, after: { forget: { expired: (outcome as { expired?: unknown }).expired ?? null } } })) {
+ return decisionResult(proposal, 'accept', 'refused', { reason: (await getTrustProposal(engine, proposal.id))?.status ?? 'not_found' });
+ }
+ return decisionResult(proposal, 'accept', 'accepted', { detail: { fact_id: String(proposal.target_id) } });
+ },
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 5c0044305a..23c8484c1e 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -102,5 +102,7 @@ test/sync-frontmatter-slug-conflict.test.ts
test/sync-group-member-order.test.ts
test/sync-legacy-holds.test.ts
test/takes-vector-lifecycle-5885.serial.test.ts
+test/trust-channel-writes.test.ts
+test/trust-guarded-supersession.test.ts
test/withdrawal-overlay-concurrency.test.ts
test/withdrawal-publication-file.test.ts
diff --git a/test/trust-guarded-supersession.test.ts b/test/trust-guarded-supersession.test.ts
new file mode 100644
index 0000000000..7b29eda2db
--- /dev/null
+++ b/test/trust-guarded-supersession.test.ts
@@ -0,0 +1,164 @@
+/**
+ * Guarded supersession (#5575 A5/I3, ENG-4, DX-1): a lower-tier remember
+ * (replaces or the conflict slot) never supersedes a higher-tier fact; it is
+ * inserted contested with a supersede_fact trust proposal that the owner's
+ * accept applies through the checked supersede (and confirms the new fact),
+ * undo restores; a remote forget of a higher-tier fact returns
+ * forget_requires_owner with a forget proposal (same ref on retry) that the
+ * owner's accept applies. Runs on PGLite, and on Postgres when DATABASE_URL
+ * is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } 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 { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { withCoordinatedWrite, withTrustBackfill } from '../src/core/persistence/context.ts';
+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import {
+ frontmatterTrustCaps, ownerPageTrust, requestChannelTrust, sourceDefaultTier, stampTrustMarker,
+} from '../src/core/trust/channel.ts';
+import { listTrustProposals } from '../src/core/trust/proposals.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { renderFactsTable } from '../src/core/facts-fence.ts';
+import { runSetTrust } from '../src/commands/sources-trust.ts';
+
+const engines: BrainEngine[] = [];
+const home = mkdtempSync(join(tmpdir(), 'gbrain-trust-channel-'));
+let closePostgres: (() => Promise<void>) | undefined;
+const quiet = { info() {}, warn() {}, error() {} };
+
+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); 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 }
+async function brain(engine: BrainEngine): Promise<Brain> {
+ const sourceId = `trust-${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 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');
+ 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>>;
+const page = (title: string, body: string, extra = '') => `---\ntype: note\ntitle: ${title}\n${extra}---\n${body}\n`;
+async function pageRow(b: Brain, slug: string) {
+ const [row] = await b.engine.executeRaw<{ trust_tier: string; frontmatter: Record<string, unknown>; id: number; compiled_truth: string }>(
+ 'SELECT id, trust_tier, frontmatter, compiled_truth FROM pages WHERE source_id=$1 AND slug=$2', [b.sourceId, slug]);
+ return row;
+}
+/** An owner page: imported, then classified operator_curated through the deterministic backfill seam. */
+async function ownerPage(b: Brain, slug: string, body: string) {
+ await run(b.local, 'put_page', { slug, content: page('Owner', body) });
+ // Lowering to unknown is always allowed; the backfill may then raise unknown to operator_curated (CEO-10).
+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], async () => {
+ await tx.executeRaw(`UPDATE pages SET trust_tier='unknown', frontmatter = frontmatter - 'trust_tier' - 'source_kind' - 'ingested_via' WHERE source_id=$1 AND slug=$2`, [b.sourceId, slug]);
+ await withTrustBackfill(tx, () => tx.executeRaw(`UPDATE pages SET trust_tier='operator_curated' WHERE source_id=$1 AND slug=$2`, [b.sourceId, slug]));
+ }, TEST_WRITE_ATTRIBUTION));
+ return (await pageRow(b, slug))!;
+}
+
+import { withTrustPromotion } from '../src/core/persistence/context.ts';
+import { decideTrustProposal } from '../src/core/trust/decide.ts';
+import { parseTrustProposalRef } from '../src/core/trust/proposals.ts';
+
+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 factRow = async (b: Brain, id: unknown) => (await b.engine.executeRaw<{ trust_tier: string; expired_at: unknown; superseded_by: number | null }>(
+ 'SELECT trust_tier, expired_at, superseded_by FROM facts WHERE id=$1', [Number(id)]))[0]!;
+const owner = { confirmation: { via: 'tty' as const } };
+
+describe('guarded supersession', () => {
+ test('a lower-tier remember.replaces is inserted contested; owner accept supersedes and confirms; undo restores', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ await ownerPage(b, 'people/alice-example', 'Alice.');
+ const old = await run(b.local, 'remember', { fact: 'Alice lives in Paris', provenance: 'owner', entity: 'people/alice-example' });
+ await confirmFact(b, Number(old.id));
+ const agent = await run(b.remote, 'remember', { fact: 'Alice lives in Berlin', provenance: 'web page', entity: 'people/alice-example', replaces: String(old.id) });
+ expect(agent.status).toBe('inserted');
+ expect(agent.contested?.proposal_ref).toMatch(/^tp\d+$/);
+ expect((await factRow(b, old.id)).expired_at).toBeNull();
+ expect((await factRow(b, agent.id)).trust_tier).toBe('agent_written');
+ const id = parseTrustProposalRef(agent.contested.proposal_ref)!;
+ const accepted = await decideTrustProposal(engine, id, 'accept', owner);
+ expect(accepted.status).toBe('accepted');
+ expect(await factRow(b, old.id)).toMatchObject({ superseded_by: Number(agent.id) });
+ expect((await factRow(b, old.id)).expired_at).not.toBeNull();
+ expect((await factRow(b, agent.id)).trust_tier).toBe('user_confirmed');
+ const undone = await decideTrustProposal(engine, id, 'undo', owner);
+ expect(undone.status).toBe('undone');
+ expect((await factRow(b, old.id)).expired_at).toBeNull();
+ expect((await factRow(b, agent.id)).trust_tier).toBe('agent_written');
+ // An equal-tier replace supersedes as before.
+ const again = await run(b.remote, 'remember', { fact: 'Alice lives in Rome', provenance: 'web page', entity: 'people/alice-example', replaces: String(agent.id) });
+ expect(again.status).toBe('superseded');
+ expect(again.contested).toBeUndefined();
+ }
+ }), 90_000);
+
+ test('a remote forget of a higher-tier fact is forget_requires_owner with one proposal; the owner accept forgets it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ await ownerPage(b, 'people/bob-example', 'Bob.');
+ const fact = await run(b.local, 'remember', { fact: 'Bob is allergic to nuts', provenance: 'owner', entity: 'people/bob-example' });
+ await confirmFact(b, Number(fact.id));
+ const requestId = randomUUID();
+ const attempt = async () => { try { await operationsByName.forget.handler(b.remote, { id: String(fact.id), request_id: requestId }); return null; } catch (e) { return e as { code: string; canonicalCode: string; detail?: string; fix?: { argv: string[] } }; } };
+ const first = await attempt();
+ expect(first?.code).toBe('scope_denied');
+ expect(first?.canonicalCode).toBe('forget_requires_owner');
+ const ref = JSON.parse(first!.detail!).proposal_ref as string;
+ expect(first!.fix!.argv).toEqual(['gbrain', 'trust', 'confirm', ref]);
+ expect(first!.fix!.argv).not.toContain('--yes');
+ const second = await attempt();
+ expect(JSON.parse(second!.detail!).proposal_ref).toBe(ref);
+ expect((await factRow(b, fact.id)).expired_at).toBeNull();
+ const accepted = await decideTrustProposal(engine, parseTrustProposalRef(ref)!, 'accept', owner);
+ expect(accepted.status).toBe('accepted');
+ expect((await factRow(b, fact.id)).expired_at).not.toBeNull();
+ // An agent-tier fact is forgotten by a remote caller as before.
+ const own = await run(b.remote, 'remember', { fact: 'Bob likes jazz', provenance: 'chat', entity: 'people/bob-example' });
+ const forgot = await operationsByName.forget.handler(b.remote, { id: String(own.id), request_id: randomUUID() }) as Record<string, unknown>;
+ expect(forgot.expired).toBe(true);
+ }
+ }), 90_000);
+});