Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): channel tiers declared once per publication, fence-edit keep scope, trust_proposals store (#5575 lane L1a A3, ENG-4, ENG-18)

garrytan8d82bf596f4f
diff --git a/src/core/persistence/attribution.ts b/src/core/persistence/attribution.ts
index 7f8e9091b9..34eb4b6939 100644
--- a/src/core/persistence/attribution.ts
+++ b/src/core/persistence/attribution.ts
@@ -3,6 +3,7 @@ import type { Principal, SqlEngine, WriteRequest } from './model.ts';
import type { BrainEngine } from '../engine.ts';
import { withWriteAttribution } from './context.ts';
import type { WriteTrust } from '../trust/tier.ts';
+import { requestChannelTrust } from '../trust/channel.ts';
/**
* The actor the database stamps on rows written inside withCoordinatedWrite
@@ -23,6 +24,12 @@ export function requestAttribution(row: Pick<WriteRequest, 'id' | 'principal_kin
return { requestId: row.id, principal: { kind: row.principal_kind, id: row.principal_id } };
}
+/** A journaled publication: the request's actor, and the tier its preparer declared or its channel earns (#5575 A3). */
+export function publicationAttribution(row: Pick<WriteRequest, 'id' | 'principal_kind' | 'principal_id' | 'operation' | 'authority' | 'intent'>, trust?: WriteTrust): WriteAttribution {
+ const declared = trust ?? requestChannelTrust(row);
+ return { ...requestAttribution(row), ...(declared ? { trust: declared } : {}) };
+}
+
/** A write by a known principal that has no journal request (manual links, source lifecycle). */
export function principalAttribution(principal: Principal): WriteAttribution {
return { requestId: null, principal };
diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.ts
index 843ed73fa6..dbcdd445c4 100644
--- a/src/core/persistence/context.ts
+++ b/src/core/persistence/context.ts
@@ -3,6 +3,7 @@ import type { BrainEngine } from '../engine.ts';
import { opError, OperationError } from '../ops/contract.ts';
import type { WriteAttribution } from './attribution.ts';
import { isTrustTier, nestWriteTrust, trustRankSql, type TrustTier, type WriteTrust } from '../trust/tier.ts';
+import type { TrustTable } from '../trust/schema.ts';
interface PublicationContext { brainId: string; sourceIds: ReadonlySet<string>; active: boolean; }
const publication = new AsyncLocalStorage<PublicationContext>();
@@ -11,6 +12,7 @@ const ATTRIBUTION_SETTINGS = ['gbrain.write_request', 'gbrain.write_principal_ki
const TRUST_SETTINGS = ['gbrain.write_trust_tier', 'gbrain.write_origin'] as const;
const TRUST_PROMOTION_SETTING = 'gbrain.write_trust_promotion';
const TRUST_BACKFILL_SETTING = 'gbrain.write_trust_backfill';
+const TRUST_KEEP_SETTING = 'gbrain.write_trust_keep';
/**
* Sets transaction-local settings around `fn` in one round trip each way. An
@@ -126,6 +128,15 @@ export async function currentWriteTrust(engine: Pick<BrainEngine, 'executeRaw'>)
export function withTrustPromotion<T>(engine: Pick<BrainEngine, 'executeRaw'>, ceiling: TrustTier, fn: () => Promise<T>): Promise<T> {
return withTransactionSettings(engine, [TRUST_PROMOTION_SETTING], () => [ceiling], fn);
}
+/**
+ * ENG-1: inside `fn`, a content rewrite of a row in `tables` keeps its stored
+ * tier (it can still lower, never raise). For gbrain-managed fence edits that
+ * rewrite a page body without authoring it (a remember or takes fence append,
+ * a forget or accept strike); the fence row itself carries the writer's tier.
+ */
+export function withTrustKeep<T>(engine: Pick<BrainEngine, 'executeRaw'>, tables: readonly TrustTable[], fn: () => Promise<T>): Promise<T> {
+ return withTransactionSettings(engine, [TRUST_KEEP_SETTING], outer => [[...new Set([...(outer[0] ? outer[0].split(',') : []), ...tables])].join(',')], fn);
+}
/** CEO-10: the deterministic backfill may move rows from `unknown` to any tier below user_confirmed. */
export function withTrustBackfill<T>(engine: Pick<BrainEngine, 'executeRaw'>, fn: () => Promise<T>): Promise<T> {
return withTransactionSettings(engine, [TRUST_BACKFILL_SETTING], () => ['on'], fn);
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index f74069c0e5..a9611e3263 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -18,7 +18,8 @@ import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRec
import type { NativeLockHandle } from './native-lock.ts';
import { withCoordinatedWrite } from './context.ts';
import { lockCoreSources } from './core-guard.ts';
-import { requestAttribution } from './attribution.ts';
+import { publicationAttribution } from './attribution.ts';
+import type { WriteTrust } from '../trust/tier.ts';
import { withFilesystemPublication } from './filesystem-guard.ts';
import { mayReprepare } from './semantic.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
@@ -62,6 +63,8 @@ interface PreparedMutationBase {
*/
postimage?: PageSnapshot | null;
validate?(tx: BrainEngine): Promise<void>;
+ /** #5575: the tier and origin of the rows apply writes; absent: the request's channel tier (trust/channel.ts). */
+ trust?: WriteTrust;
}
/**
* A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700.
@@ -339,7 +342,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await hooks.boundary?.('after_publication', row);
}
prepared.postimage = undefined;
- const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx, snapshot), requestAttribution(row));
+ const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx, snapshot), publicationAttribution(row, prepared.trust));
if (!skill) await classifyUnboundPage(tx, row);
if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = skill ? null : await publicationPostimage(tx, row, prepared);
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 6724075f58..c05523a321 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -39,7 +39,7 @@ import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequ
import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';
import { claimPhaseStamp, enterClaimPhase, startClaimPhase } from './claim-phase.ts';
import { setMemberAttribution, withCoordinatedWrite } from './context.ts';
-import { requestAttribution } from './attribution.ts';
+import { publicationAttribution, requestAttribution } from './attribution.ts';
import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
import { queuePublicationEffects, queuesMentionLinks, reconcileFinishedBatch } from './effect-journal.ts';
import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
@@ -183,7 +183,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
if (persistenceFileHash(file.record.path) !== file.record.beforeHash) throw new OperationError('unexpected_file_bytes', 'The canonical file changed during preparation.', 'The members publish one at a time.');
await withFilesystemPublication([file.record.root], async () => publishPersistenceFile(member.file!, file.record.staging?.publication?.path));
}
- await setMemberAttribution(tx, requestAttribution(row));
+ await setMemberAttribution(tx, publicationAttribution(row, member.trust));
member.postimage = undefined;
const outcome = await member.apply(tx, snapshot);
await classifyUnboundPage(tx, row);
diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.ts
new file mode 100644
index 0000000000..116faa8590
--- /dev/null
+++ b/src/core/trust/channel.ts
@@ -0,0 +1,162 @@
+/**
+ * Write-time trust tiers per channel (#5575: A3, CEO-21, CEO-26/DX-8, ENG-18).
+ * Deterministic, never guessed: the tier comes from who is writing and through
+ * which path, and frontmatter or an agent's `content_origin` can only lower it.
+ *
+ * - Remote MCP / serve-http / thin-client agent writes: agent_written.
+ * - Local CLI `remember` / `put_page` / `capture` and the other journaled
+ * agent verbs: agent_written (a local agent with a shell is
+ * indistinguishable from the human; only CEO-9 confirmation raises).
+ * - `content_origin: tool_output` lowers an agent write to external_untrusted.
+ * - Connector jobs (Google, GitHub), webhook and ingestion-daemon captures and
+ * third-party transcript imports: external_untrusted.
+ * - Owner-source sync / import / reconcile / file repair: operator_curated (or
+ * the source's `sources set-trust` default, never above operator_curated),
+ * lowered by the page's frontmatter markers: the lower-only `trust_tier`
+ * marker, `source_kind` / `ingested_via` / `captured_via` channel stamps,
+ * `transcript_import`, clipper `source_url`, `provenance: auto-extracted`
+ * and `dream_generated`.
+ *
+ * The coordinator declares `preparedTrust ?? requestChannelTrust(row)` once per
+ * publication (persistence/coordinator.ts, group-publish.ts); preparers that
+ * know more (sync markers, derivation inputs) declare their own.
+ */
+import type { WriteRequest } from '../persistence/model.ts';
+import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
+import {
+ OWNER_TIER_FLOOR, compareTrust, contentOriginTier, effectiveWriteTrust, isTrustTier, minTrust,
+ type TrustTier, type WriteTrust,
+} from './tier.ts';
+
+/** Journaled verbs an agent (remote or local) calls directly; their rows are agent_written unless lowered. */
+export const AGENT_WRITE_OPERATIONS: readonly string[] = [
+ 'put_page', 'put_pages', 'capture', 'edit_page', 'delete_page', 'restore_page', 'revert_version', 'remember',
+ 'add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve',
+ 'takes_remove', 'loops_close', 'relink_facts', 'decide_proposal',
+];
+
+/** Intent kinds whose preparer computes the tier from the page (owner-source sync and import paths). */
+const OWNER_SOURCE_KINDS = ['canonical_reconcile', 'managed_file_import', 'managed_file_repair', 'managed_grandfather'];
+
+/** Page frontmatter `source_kind` / `ingested_via` / `captured_via` values written by an ingestion capture (external). */
+export const EXTERNAL_CAPTURE_KINDS: readonly string[] = ['webhook', 'file-watcher', 'inbox-folder', 'cron-scheduler', 'ingest_capture'];
+/** ...and by an agent through a gbrain verb (agent_written). */
+const AGENT_CAPTURE_KINDS = ['put_page', 'capture-cli', 'capture-mcp', 'capture'];
+/**
+ * Harnesses whose `transcript_import` pages are the user's own sessions with
+ * their agent (or their own chat exports): relayed user turns count as
+ * agent_written. Any other harness is a third-party transcript: external.
+ */
+export const OWN_SESSION_HARNESSES: readonly string[] = [
+ 'claude-code', 'codex', 'openclaw', 'cursor', 'hermes', 'gemini-cli', 'opencode', 'chatgpt', 'claude', 'grok',
+];
+
+/** The origin channel name of a journaled request, e.g. `mcp:put_page`, `cli:remember`, `connector:google`. */
+export function requestChannel(row: Pick<WriteRequest, 'operation' | 'authority' | 'intent'>): string {
+ const kind = typeof row.intent?.kind === 'string' ? row.intent.kind : '';
+ if (kind.startsWith('connector_v2_') || kind.startsWith('managed_connector_')) return `connector:${kind}`;
+ if (kind) return kind;
+ return `${row.authority?.remote === true ? 'mcp' : 'cli'}:${row.operation}`;
+}
+
+/** The agent's declared content origin from a request intent (validated at admission); undefined when absent. */
+export function intentContentOrigin(intent: Record<string, unknown> | null | undefined): TrustTier | undefined {
+ const value = intent?.content_origin;
+ return value === undefined || value === null ? undefined : contentOriginTier(value);
+}
+
+/**
+ * The tier a journaled request earns from its channel alone, or undefined for
+ * intents whose preparer must declare one (owner-source sync, derived
+ * maintenance) or that write no tiered rows. Undeclared rows stamp `unknown`.
+ */
+export function requestChannelTrust(row: Pick<WriteRequest, 'id' | 'operation' | 'authority' | 'intent'>): WriteTrust | undefined {
+ const kind = typeof row.intent?.kind === 'string' ? row.intent.kind : '';
+ const origin = { channel: requestChannel(row), request_id: row.id };
+ if (kind.startsWith('connector_v2_') || kind.startsWith('managed_connector_')) return effectiveWriteTrust({ channel: 'external_untrusted', origin });
+ if (row.authority?.remote === true) {
+ const lowered = intentContentOrigin(row.intent);
+ return effectiveWriteTrust({ channel: 'agent_written', lowerTo: lowered ? [lowered] : [], origin });
+ }
+ if (kind.startsWith('managed_sync_') || kind.startsWith('managed_maintenance_') || kind.startsWith('managed_facts_')
+ || kind.startsWith('managed_atom_') || OWNER_SOURCE_KINDS.includes(kind)) return undefined;
+ if (AGENT_WRITE_OPERATIONS.includes(row.operation)) {
+ const lowered = intentContentOrigin(row.intent);
+ return effectiveWriteTrust({ channel: 'agent_written', lowerTo: lowered ? [lowered] : [], origin });
+ }
+ return undefined;
+}
+
+const str = (value: unknown) => (typeof value === 'string' ? value.trim() : '');
+
+/** The tier a single channel stamp names (`source_kind`, `ingested_via`, `captured_via`), or undefined. */
+function stampTier(value: unknown): TrustTier | undefined {
+ const v = str(value);
+ if (!v) return undefined;
+ if (EXTERNAL_CAPTURE_KINDS.includes(v)) return 'external_untrusted';
+ if (v.startsWith('mcp:') || AGENT_CAPTURE_KINDS.includes(v)) return 'agent_written';
+ if (v.startsWith('connector:') || (CONNECTOR_SOURCE_KINDS as readonly string[]).includes(v)) return 'external_untrusted';
+ return undefined;
+}
+
+/**
+ * Every lowering signal in a page's frontmatter (CEO-21). They can only lower:
+ * a `trust_tier: user_confirmed` marker typed by hand is ignored (it names no
+ * tier below the channel's), and nothing here can raise.
+ */
+export function frontmatterTrustCaps(frontmatter: Record<string, unknown> | null | undefined): TrustTier[] {
+ const fm = frontmatter ?? {};
+ const caps: TrustTier[] = [];
+ if (isTrustTier(fm.trust_tier)) caps.push(fm.trust_tier);
+ for (const key of ['source_kind', 'ingested_via', 'captured_via']) {
+ const tier = stampTier(fm[key]);
+ if (tier) caps.push(tier);
+ }
+ const transcript = fm.transcript_import as { harness?: unknown } | undefined;
+ if (transcript && typeof transcript === 'object') {
+ caps.push(OWN_SESSION_HARNESSES.includes(str(transcript.harness).toLowerCase()) ? 'agent_written' : 'external_untrusted');
+ }
+ if (str(fm.source_url) && (str(fm.clipped_at) || str(fm.clipper) || str(fm.captured_via) === 'clipper' || str(fm.type) === 'clipping')) {
+ caps.push('external_untrusted');
+ }
+ if (str(fm.provenance) === 'auto-extracted' || fm.dream_generated === true || str(fm.dream_generated) === 'true') caps.push('agent_written');
+ return caps;
+}
+
+/** A per-source default set by `gbrain sources set-trust` (sources.config.trust_tier), clamped to operator_curated. */
+export function sourceDefaultTier(config: Record<string, unknown> | null | undefined): TrustTier {
+ const value = config?.trust_tier;
+ return isTrustTier(value) ? minTrust(value, OWNER_TIER_FLOOR) : OWNER_TIER_FLOOR;
+}
+
+/**
+ * The tier of an owner-source sync / import of one page: the source default
+ * lowered by the page's markers (connector sources are external outright).
+ */
+export function ownerPageTrust(input: {
+ frontmatter: Record<string, unknown> | null | undefined;
+ sourceConfig?: Record<string, unknown> | null;
+ channel: string;
+ requestId?: string | null;
+ sourceUri?: string | null;
+}): WriteTrust {
+ const kind = str(input.sourceConfig?.kind);
+ const base = (CONNECTOR_SOURCE_KINDS as readonly string[]).includes(kind) ? 'external_untrusted' : sourceDefaultTier(input.sourceConfig);
+ return effectiveWriteTrust({
+ channel: base, lowerTo: frontmatterTrustCaps(input.frontmatter),
+ origin: { channel: input.channel, ...(input.requestId ? { request_id: input.requestId } : {}), ...(input.sourceUri ? { source_uri: input.sourceUri } : {}) },
+ });
+}
+
+/**
+ * CEO-21: the lower-only `trust_tier` marker a write-through stamps into the
+ * canonical file when the write is below operator_curated. An existing lower
+ * marker is kept (min). Returns the frontmatter unchanged at owner tiers.
+ */
+export function stampTrustMarker(frontmatter: Record<string, unknown>, tier: TrustTier): Record<string, unknown> {
+ if (compareTrust(tier, OWNER_TIER_FLOOR) >= 0) return frontmatter;
+ const prior = frontmatter.trust_tier;
+ const marker = isTrustTier(prior) ? minTrust(prior, tier) : tier;
+ if (prior === marker) return frontmatter;
+ return { ...frontmatter, trust_tier: marker };
+}
diff --git a/src/core/trust/decide.ts b/src/core/trust/decide.ts
new file mode 100644
index 0000000000..e59a2aa709
--- /dev/null
+++ b/src/core/trust/decide.ts
@@ -0,0 +1,9 @@
+/**
+ * Entry point for owner trust decisions (#5575 ENG-4): loads every checked
+ * 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';
+
+export { decideTrustProposal } from './proposals.ts';
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
new file mode 100644
index 0000000000..61e88ce194
--- /dev/null
+++ b/src/core/trust/page-handlers.ts
@@ -0,0 +1,6 @@
+/**
+ * Checked handler for `lower_page` trust proposals (#5575 CEO-12): accept
+ * keeps the agent edit at its lowered tier; revert restores the prior owner
+ * version's content and tier through the CEO-9 rule.
+ */
+export {};
diff --git a/src/core/trust/proposals.ts b/src/core/trust/proposals.ts
new file mode 100644
index 0000000000..4c23a30107
--- /dev/null
+++ b/src/core/trust/proposals.ts
@@ -0,0 +1,224 @@
+/**
+ * Trust decisions (#5575: ENG-4, A5/I3, CEO-12): the typed `trust_proposals`
+ * record and its checked handlers. A proposal links the row a decision would
+ * change (`target`) to the row that caused it (`related`): the lower-tier fact
+ * that would supersede a higher-tier one, the higher-tier fact a remote caller
+ * asked to forget, the page an agent edit lowered. `before_state` holds the
+ * exact state the accept path re-checks under lock (tiers, ids, revisions).
+ *
+ * Storage goes through `engine.executeRaw` (the proposals-store.ts pattern).
+ * decide_proposals gets no rows from here; CLI refs are `tp<id>`. Proposals
+ * are inserted inside the publication transaction that created them, so the
+ * proposer is read from that transaction's attribution settings.
+ *
+ * Accept/reject/undo dispatch to one handler per action, registered by the
+ * module that owns the write path (trust/supersede-handlers.ts for facts,
+ * takes and forget; the owner-ops module for lower_page). Every handler runs
+ * only after the caller established the owner's confirmation (CEO-9,
+ * trust/confirm.ts); handlers re-check `before_state` under lock and refuse
+ * stale proposals instead of applying them.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import type { Principal } from '../persistence/model.ts';
+import type { OwnerConfirmation } from './confirm.ts';
+import type { TrustTable } from './schema.ts';
+import { TRUST_PROPOSAL_ACTIONS, TRUST_PROPOSAL_STATUSES } from './schema.ts';
+
+export type TrustProposalAction = typeof TRUST_PROPOSAL_ACTIONS[number];
+export type TrustProposalStatus = typeof TRUST_PROPOSAL_STATUSES[number];
+export type TrustDecision = 'accept' | 'reject' | 'undo';
+
+export interface TrustProposalRow {
+ id: number;
+ action: TrustProposalAction;
+ source_id: string;
+ target_table: TrustTable;
+ target_id: number;
+ related_table: TrustTable | null;
+ related_id: number | null;
+ before_state: Record<string, unknown>;
+ after_state: Record<string, unknown>;
+ proposer: string;
+ proposer_principal_kind: string | null;
+ proposer_principal_id: string | null;
+ write_request_id: string | null;
+ status: TrustProposalStatus;
+ decided_at: string | null;
+ decided_principal_kind: string | null;
+ decided_principal_id: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+/** The typed CLI ref of a trust proposal. */
+export const trustProposalRef = (id: number | string): string => `tp${id}`;
+/** `tp<id>` (or a bare id) to the proposal id; null when the ref names something else. */
+export function parseTrustProposalRef(ref: string): number | null {
+ const m = /^(?:tp)?(\d{1,18})$/.exec(ref.trim());
+ return m ? Number(m[1]) : null;
+}
+
+const json = (value: unknown): Record<string, unknown> => {
+ if (value && typeof value === 'object') return value as Record<string, unknown>;
+ if (typeof value === 'string') { try { return JSON.parse(value) as Record<string, unknown>; } catch { return {}; } }
+ return {};
+};
+const iso = (value: unknown): string | null => value === null || value === undefined ? null : new Date(value as string).toISOString();
+function normalize(r: Record<string, unknown>): TrustProposalRow {
+ return {
+ id: Number(r.id), action: r.action as TrustProposalAction, source_id: String(r.source_id),
+ target_table: r.target_table as TrustTable, target_id: Number(r.target_id),
+ related_table: (r.related_table as TrustTable | null) ?? null, related_id: r.related_id === null || r.related_id === undefined ? null : Number(r.related_id),
+ before_state: json(r.before_state), after_state: json(r.after_state), proposer: String(r.proposer),
+ proposer_principal_kind: (r.proposer_principal_kind as string | null) ?? null, proposer_principal_id: (r.proposer_principal_id as string | null) ?? null,
+ write_request_id: (r.write_request_id as string | null) ?? null, status: r.status as TrustProposalStatus,
+ decided_at: iso(r.decided_at), decided_principal_kind: (r.decided_principal_kind as string | null) ?? null,
+ decided_principal_id: (r.decided_principal_id as string | null) ?? null,
+ created_at: iso(r.created_at)!, updated_at: iso(r.updated_at)!,
+ };
+}
+
+export interface NewTrustProposal {
+ action: TrustProposalAction;
+ sourceId: string;
+ target: { table: TrustTable; id: number };
+ related?: { table: TrustTable; id: number } | null;
+ before: Record<string, unknown>;
+ after?: Record<string, unknown>;
+ /** Short name of the guard that raised it, e.g. `remember.replaces`, `fence_projection`, `remote_forget`, `agent_page_edit`. */
+ proposer: string;
+}
+
+/**
+ * Inserts a pending proposal inside the caller's transaction, or returns the
+ * pending one already recorded for the same (action, target, related): a
+ * retried write or a second agent edit of one page reuses one queue item
+ * (ENG-22). The proposer principal and request come from the transaction's
+ * attribution settings.
+ */
+export async function insertTrustProposal(tx: BrainEngine, input: NewTrustProposal): Promise<{ id: number; created: boolean }> {
+ const params = [input.action, input.sourceId, input.target.table, input.target.id, input.related?.table ?? null, input.related?.id ?? null,
+ JSON.stringify(input.before), JSON.stringify(input.after ?? {}), input.proposer];
+ const [inserted] = await tx.executeRaw<{ id: number }>(
+ `INSERT INTO trust_proposals (action, source_id, target_table, target_id, related_table, related_id, before_state, after_state, proposer,
+ proposer_principal_kind, proposer_principal_id, write_request_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7::text::jsonb, $8::text::jsonb, $9,
+ NULLIF(current_setting('gbrain.write_principal_kind', true), ''), NULLIF(current_setting('gbrain.write_principal_id', true), ''),
+ NULLIF(current_setting('gbrain.write_request', true), '')::uuid)
+ ON CONFLICT DO NOTHING RETURNING id`, params);
+ if (inserted) return { id: Number(inserted.id), created: true };
+ const [existing] = await tx.executeRaw<{ id: number }>(
+ `SELECT id FROM trust_proposals WHERE status = 'pending' AND action = $1 AND target_table = $2 AND target_id = $3
+ AND related_table IS NOT DISTINCT FROM $4 AND related_id IS NOT DISTINCT FROM $5 ORDER BY id LIMIT 1`,
+ [input.action, input.target.table, input.target.id, input.related?.table ?? null, input.related?.id ?? null]);
+ if (!existing) throw new Error('trust proposal insert conflicted but no pending row was found');
+ return { id: Number(existing.id), created: false };
+}
+
+export async function getTrustProposal(engine: BrainEngine, id: number, lock = false): Promise<TrustProposalRow | null> {
+ const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT * FROM trust_proposals WHERE id = $1${lock ? ' FOR UPDATE' : ''}`, [id]);
+ return row ? normalize(row) : null;
+}
+
+export interface TrustProposalFilter {
+ status?: TrustProposalStatus | 'all';
+ sourceId?: string;
+ action?: TrustProposalAction;
+ since?: Date;
+ limit?: number;
+}
+
+export async function listTrustProposals(engine: BrainEngine, filter: TrustProposalFilter = {}): Promise<TrustProposalRow[]> {
+ const status = filter.status ?? 'pending';
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT * FROM trust_proposals
+ WHERE ($1::text = 'all' OR status = $1) AND ($2::text IS NULL OR source_id = $2) AND ($3::text IS NULL OR action = $3)
+ AND ($4::timestamptz IS NULL OR created_at >= $4)
+ ORDER BY created_at, id LIMIT $5`,
+ [status, filter.sourceId ?? null, filter.action ?? null, filter.since?.toISOString() ?? null, Math.min(Math.max(filter.limit ?? 500, 1), 5000)]);
+ return rows.map(normalize);
+}
+
+/** Pending proposals naming a row as target or related (guards and explain read this). */
+export async function pendingTrustProposalsFor(engine: BrainEngine, table: TrustTable, id: number): Promise<TrustProposalRow[]> {
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT * FROM trust_proposals WHERE status = 'pending'
+ AND ((target_table = $1 AND target_id = $2) OR (related_table = $1 AND related_id = $2)) ORDER BY id`, [table, id]);
+ return rows.map(normalize);
+}
+
+/** Compare-and-set on status; records the decider and an after state. False when the proposal was not in `from`. */
+export async function transitionTrustProposal(tx: BrainEngine, id: number, from: TrustProposalStatus, to: TrustProposalStatus,
+ opts: { after?: Record<string, unknown>; decidedBy?: Principal | null } = {}): Promise<boolean> {
+ const rows = await tx.executeRaw<{ id: number }>(
+ `UPDATE trust_proposals SET status = $3, updated_at = now(),
+ after_state = CASE WHEN $4::text IS NULL THEN after_state ELSE $4::text::jsonb END,
+ decided_at = CASE WHEN $3 IN ('accepted', 'rejected', 'undone') THEN now() ELSE decided_at END,
+ decided_principal_kind = COALESCE($5, decided_principal_kind), decided_principal_id = COALESCE($6, decided_principal_id)
+ WHERE id = $1 AND status = $2 RETURNING id`,
+ [id, from, to, opts.after ? JSON.stringify(opts.after) : null, opts.decidedBy?.kind ?? null, opts.decidedBy?.id ?? null]);
+ return rows.length === 1;
+}
+
+// ---------------------------------------------------------------------------
+// Checked handlers
+// ---------------------------------------------------------------------------
+
+export interface TrustDecisionResult {
+ id: number;
+ ref: string;
+ action: TrustProposalAction;
+ decision: TrustDecision;
+ status: TrustProposalStatus | 'refused' | 'not_found' | 'stale';
+ reason?: string;
+ detail?: Record<string, unknown>;
+}
+
+export interface TrustDecisionContext {
+ config?: GBrainConfig;
+ /** How the owner confirmed (trust/confirm.ts requireOwnerConfirmation); required for accept and undo. */
+ confirmation: OwnerConfirmation;
+ /** The owner principal recorded as the decider. */
+ decidedBy?: Principal | null;
+}
+
+export interface TrustProposalHandler {
+ accept(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult>;
+ reject?(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult>;
+ undo?(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult>;
+}
+
+const handlers = new Map<TrustProposalAction, TrustProposalHandler>();
+export function registerTrustProposalHandler(action: TrustProposalAction, handler: TrustProposalHandler): void {
+ handlers.set(action, handler);
+}
+
+export function decisionResult(proposal: Pick<TrustProposalRow, 'id' | 'action'>, decision: TrustDecision,
+ status: TrustDecisionResult['status'], extra: { reason?: string; detail?: Record<string, unknown> } = {}): TrustDecisionResult {
+ return { id: proposal.id, ref: trustProposalRef(proposal.id), action: proposal.action, decision, status, ...extra };
+}
+
+/** The default reject: the proposal closes and nothing else changes. */
+async function rejectOnly(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult> {
+ return await transitionTrustProposal(engine, proposal.id, 'pending', 'rejected', { decidedBy: ctx.decidedBy })
+ ? decisionResult(proposal, 'reject', 'rejected')
+ : decisionResult(proposal, 'reject', 'refused', { reason: (await getTrustProposal(engine, proposal.id))?.status ?? 'not_found' });
+}
+
+/**
+ * Applies one owner decision. The caller has already established the owner's
+ * confirmation for this exact proposal (CEO-9); the handler re-checks the
+ * recorded state under lock. Unknown ids and wrong states are reported, not thrown.
+ */
+export async function decideTrustProposal(engine: BrainEngine, id: number, decision: TrustDecision, ctx: TrustDecisionContext): Promise<TrustDecisionResult> {
+ const proposal = await getTrustProposal(engine, id);
+ if (!proposal) return { id, ref: trustProposalRef(id), action: 'confirm', decision, status: 'not_found' };
+ const want = decision === 'undo' ? 'accepted' : 'pending';
+ if (proposal.status !== want) return decisionResult(proposal, decision, 'refused', { reason: proposal.status });
+ const handler = handlers.get(proposal.action);
+ if (decision === 'reject') return (handler?.reject ?? rejectOnly)(engine, proposal, ctx);
+ if (!handler) return decisionResult(proposal, decision, 'refused', { reason: 'no_handler' });
+ if (decision === 'undo') return handler.undo ? handler.undo(engine, proposal, ctx) : decisionResult(proposal, decision, 'refused', { reason: 'undo_unsupported' });
+ return handler.accept(engine, proposal, ctx);
+}
diff --git a/src/core/trust/schema.ts b/src/core/trust/schema.ts
index 144a209331..e37d4da232 100644
--- a/src/core/trust/schema.ts
+++ b/src/core/trust/schema.ts
@@ -12,6 +12,10 @@
* gbrain.write_origin its origin record, JSON text
* gbrain.write_trust_promotion a tier ceiling for an explicit raise (owner confirmation, CEO-9)
* gbrain.write_trust_backfill 'on' for the deterministic backfill (CEO-10)
+ * gbrain.write_trust_keep comma list of tables whose content rewrites in this scope keep the
+ * stored tier: a gbrain-managed fence edit (remember/takes fence append,
+ * forget or accept strike) rewrites the page body without authoring it,
+ * and the fence row carries its own tier (ENG-1)
*
* Trigger semantics (CEO-12, CEO-16, CEO-10, ENG-13):
* - INSERT: the row gets the writer's tier, or `unknown` without one; a
@@ -20,7 +24,9 @@
* - UPDATE that changes a TRUST_CONTENT_COLUMNS column: an owner-tier writer
* (operator_curated or higher) restamps the row to its tier; any lower
* writer (or none, read as `unknown`) sets min(prior tier, writer tier).
- * - UPDATE that changes no content column keeps the stored tier.
+ * - UPDATE that changes no content column keeps the stored tier, and so does
+ * a content change on a table named by gbrain.write_trust_keep (a fence
+ * edit; it can still lower, never raise).
* - An UPDATE that sets a higher tier is honored under a covering promotion
* ceiling, or under the backfill setting from `unknown` to anything below
* user_confirmed. Inside a writer scope it is otherwise clamped back; with
@@ -89,12 +95,13 @@ const SETTINGS = `
origin_text := NULLIF(current_setting('gbrain.write_origin', true), '');
promo := NULLIF(current_setting('gbrain.write_trust_promotion', true), '');
backfill := COALESCE(current_setting('gbrain.write_trust_backfill', true), '') = 'on';
+ keep := TG_TABLE_NAME = ANY(string_to_array(COALESCE(current_setting('gbrain.write_trust_keep', true), ''), ','));
IF ${rank('writer')} = 0 AND writer IS NOT NULL OR ${rank('promo')} = 0 AND promo IS NOT NULL THEN
RAISE EXCEPTION USING ERRCODE='22023', MESSAGE='gbrain trust setting names no tier', CONSTRAINT='trust_tier_guard';
END IF;`;
const STAMP_TIER_FUNCTION = `CREATE OR REPLACE FUNCTION gbrain_stamp_trust_tier() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
-DECLARE writer text; origin_text text; promo text; backfill boolean; changed boolean; effective text;
+DECLARE writer text; origin_text text; promo text; backfill boolean; keep boolean; changed boolean; effective text;
BEGIN${SETTINGS}
IF ${rank('writer')} > ${rank(`'${OWNER_TIER_FLOOR}'`)} AND (promo IS NULL OR ${rank('writer')} > ${rank('promo')}) THEN
${refuse('a write declared a tier above operator_curated without owner confirmation', `jsonb_build_object('op',TG_OP,'writer',writer)::text`)};
@@ -125,7 +132,7 @@ BEGIN${SETTINGS}
ELSE
RAISE EXCEPTION 'gbrain_stamp_trust_tier is not classified for table %', TG_TABLE_NAME;
END IF;
- IF changed THEN
+ IF changed AND NOT keep THEN
effective := COALESCE(writer, 'unknown');
IF ${rank('effective')} < ${rank(`'${OWNER_TIER_FLOOR}'`)} THEN effective := ${lowerOf('OLD.trust_tier', 'effective')}; END IF;
IF ${rank('NEW.trust_tier')} < ${rank('OLD.trust_tier')} THEN effective := ${lowerOf('NEW.trust_tier', 'effective')}; END IF;
diff --git a/src/core/trust/supersede-handlers.ts b/src/core/trust/supersede-handlers.ts
new file mode 100644
index 0000000000..46926e38f0
--- /dev/null
+++ b/src/core/trust/supersede-handlers.ts
@@ -0,0 +1,5 @@
+/**
+ * Checked handlers for guarded-supersession trust proposals (#5575 A5/I3,
+ * ENG-4): supersede_fact, supersede_take and forget.
+ */
+export {};