Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(trust): owner actions scaffold (#5575 L1a-owner)
garrytan96c6f6837744
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 6b163228bd..bd7ec3a95c 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -71,6 +71,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (row.operation === 'remember') return (await import('./memory-mutations.ts')).prepareMemoryMutation(e, row, cfg, signal);if (row.operation === 'loops_close' && row.intent?.kind === 'retire_loop_fact') return (await import('./loop-fact-retirement.ts')).prepareLoopFactRetirement(e, row, cfg);if (row.operation === 'decide_proposal') return (await import('../facts/proposal-supersede.ts')).prepareProposalMutation(e, row, cfg);+ if (row.operation === 'trust_owner_page') return (await import('../trust/page-handlers.ts')).prepareTrustOwnerPageMutation(e, row, cfg);if (row.operation === 'relink_facts') return (await import('../facts/relink-publish.ts')).prepareRelinkMutation(e, row, cfg);if (['takes_add','takes_update','takes_supersede','takes_resolve','takes_remove'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 7a16127fd1..4e5a031f42 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -221,6 +221,7 @@ import { v217 } from './v217-persistence-request-claim-phase.ts';import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';import { v219 } from './v219-pages-reconcile-name-indexes.ts';import { v230 } from './v230-trust-tiers.ts';+import { v233 } from './v233-trust-allow-rules.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -440,4 +441,5 @@ export const MIGRATIONS: Migration[] = [v218,v219,v230,+ v233,];diff --git a/src/core/schema-migrations/v233-trust-allow-rules.ts b/src/core/schema-migrations/v233-trust-allow-rules.tsnew file mode 100644index 0000000000..3e58218ca0--- /dev/null+++ b/src/core/schema-migrations/v233-trust-allow-rules.ts@@ -0,0 +1,19 @@+import type { Migration } from './types.ts';+import { TRUST_ALLOW_RULES_SQL } from '../trust/allow-rules.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Memory trust (#5575 DX-14, ENG-20): `trust_allow_rules`, the owner's+// receipted allow rules for the write gate (`gbrain trust allow`). A rule+// names a source and optionally a server-stamped source URI prefix and one+// reason family; removal keeps the row with removed_at as its receipt. A new+// table with no backfill. Provisional number: renumbered at merge time. No+// schema.sql mirror: like the trust tier schema (v230), it exists only+// through migrations.+export const v233: Migration = {+ version: 233,+ name: 'trust_allow_rules',+ idempotent: true,+ sql: TRUST_ALLOW_RULES_SQL,+};diff --git a/src/core/trust/allow-rules.ts b/src/core/trust/allow-rules.tsnew file mode 100644index 0000000000..53b090cc0a--- /dev/null+++ b/src/core/trust/allow-rules.ts@@ -0,0 +1,166 @@+/**+ * Owner allow rules for the write gate (#5575: DX-14, ENG-20). A rule says+ * "content from this source (optionally under this server-stamped URI prefix,+ * optionally only for this reason family) is benign; stop quarantining it",+ * so recurring external content does not re-quarantine after every sync.+ *+ * Rules are local-only owner state (`gbrain trust allow`), receipted by their+ * own row (who added it, when, why; removal keeps the row with `removed_at`),+ * and listed in `gbrain trust review`. They match only server-stamped fields:+ * the `pages.source_id`, `pages.source_uri` and `pages.source_kind` columns the+ * write path records, never frontmatter an author controls.+ *+ * `matchTrustAllowRule` is pure so the gate (write-gate.ts) can call it with+ * rules it prefetched for a batch, without a database call in the screen.+ */+import type { BrainEngine } from '../engine.ts';+import type { Principal } from '../persistence/model.ts';+import { opError } from '../ops/contract.ts';+import { isValidSourceId } from '../source-id.ts';++// TODO(L2a-merge): unify with write-gate.ts WriteGateReasonFamily (same four families).+export const TRUST_ALLOW_REASON_FAMILIES = ['override', 'standing_instruction', 'exfiltration', 'credential'] as const;+export type TrustAllowReasonFamily = typeof TRUST_ALLOW_REASON_FAMILIES[number];++export const TRUST_ALLOW_RULES_SQL = `CREATE TABLE IF NOT EXISTS trust_allow_rules (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ uri_prefix TEXT CHECK (uri_prefix IS NULL OR (length(uri_prefix) BETWEEN 1 AND 2048)),+ reason_family TEXT CHECK (reason_family IS NULL OR reason_family IN (${TRUST_ALLOW_REASON_FAMILIES.map(f => `'${f}'`).join(',')})),+ created_by TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ removed_at TIMESTAMPTZ,+ removed_by TEXT,+ reason TEXT CHECK (reason IS NULL OR length(reason) <= 500)+);+CREATE INDEX IF NOT EXISTS trust_allow_rules_active_idx ON trust_allow_rules (source_id) WHERE removed_at IS NULL;+CREATE UNIQUE INDEX IF NOT EXISTS trust_allow_rules_active_unique ON trust_allow_rules+ (source_id, COALESCE(uri_prefix, ''), COALESCE(reason_family, '')) WHERE removed_at IS NULL;+`;++export interface TrustAllowRule {+ id: number;+ ref: string;+ source_id: string;+ uri_prefix: string | null;+ reason_family: TrustAllowReasonFamily | null;+ created_by: string;+ created_at: string;+ removed_at: string | null;+ removed_by: string | null;+ reason: string | null;+}++/** The typed ref of an allow rule. */+export const allowRuleRef = (id: number | string): string => `a${id}`;+export function parseAllowRuleRef(ref: string): number | null {+ const m = /^a?(\d{1,18})$/.exec(ref.trim());+ return m ? Number(m[1]) : null;+}++export const principalLabel = (principal: Principal | null | undefined): string => principal ? `${principal.kind}:${principal.id}` : 'host:unregistered';++export interface TrustAllowRuleInput {+ sourceId: string;+ uriPrefix?: string | null;+ reasonFamily?: string | null;+ reason?: string | null;+}++/** Validates a rule as the CLI or the owner IPC received it; returns the normalized fields. */+export function normalizeTrustAllowRule(input: TrustAllowRuleInput): { sourceId: string; uriPrefix: string | null; reasonFamily: TrustAllowReasonFamily | null; reason: string | null } {+ if (!isValidSourceId(input.sourceId)) {+ throw opError('invalid_params', 'trust allow needs --source <id> naming an active source.', 'Pass --source with a source id; gbrain sources list shows them.');+ }+ const uriPrefix = input.uriPrefix ?? null;+ if (uriPrefix !== null && (uriPrefix.length < 1 || uriPrefix.length > 2048 || /[\s\u0000-\u001f\u007f]/.test(uriPrefix))) {+ throw opError('invalid_params', '--uri-prefix must be 1 to 2048 characters with no whitespace or control characters.',+ 'Pass the stored source URI prefix exactly, e.g. --uri-prefix https://calendar.example.com/; gbrain trust explain shows a page\'s source_uri.');+ }+ const reasonFamily = input.reasonFamily ?? null;+ if (reasonFamily !== null && !(TRUST_ALLOW_REASON_FAMILIES as readonly string[]).includes(reasonFamily)) {+ throw opError('invalid_params', `--reason-family must be one of ${TRUST_ALLOW_REASON_FAMILIES.join(', ')}.`,+ `Pass one of: ${TRUST_ALLOW_REASON_FAMILIES.join(', ')}, or omit it to allow every family from the source.`);+ }+ const reason = input.reason ?? null;+ if (reason !== null && reason.length > 500) throw opError('invalid_params', '--reason must be at most 500 characters.', 'Shorten --reason.');+ return { sourceId: input.sourceId, uriPrefix, reasonFamily: reasonFamily as TrustAllowReasonFamily | null, reason };+}++const iso = (value: unknown): string | null => value === null || value === undefined ? null : new Date(value as string).toISOString();+function normalize(r: Record<string, unknown>): TrustAllowRule {+ const id = Number(r.id);+ return {+ id, ref: allowRuleRef(id), source_id: String(r.source_id), uri_prefix: (r.uri_prefix as string | null) ?? null,+ reason_family: (r.reason_family as TrustAllowReasonFamily | null) ?? null, created_by: String(r.created_by),+ created_at: iso(r.created_at)!, removed_at: iso(r.removed_at), removed_by: (r.removed_by as string | null) ?? null,+ reason: (r.reason as string | null) ?? null,+ };+}++/** Adds a rule, or returns the active rule with the same (source, prefix, family). */+export async function addTrustAllowRule(engine: Pick<BrainEngine, 'executeRaw'>, input: TrustAllowRuleInput, by: Principal | null): Promise<{ rule: TrustAllowRule; created: boolean }> {+ const rule = normalizeTrustAllowRule(input);+ const [source] = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1 AND NOT archived', [rule.sourceId]);+ if (!source) {+ throw opError('invalid_params', `Source ${rule.sourceId} is not an active source on this brain.`, 'Pass --source with an active source id; gbrain sources list shows them.');+ }+ const [inserted] = await engine.executeRaw<Record<string, unknown>>(+ `INSERT INTO trust_allow_rules (source_id, uri_prefix, reason_family, created_by, reason) VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT DO NOTHING RETURNING *`, [rule.sourceId, rule.uriPrefix, rule.reasonFamily, principalLabel(by), rule.reason]);+ if (inserted) return { rule: normalize(inserted), created: true };+ const [existing] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT * FROM trust_allow_rules WHERE removed_at IS NULL AND source_id = $1+ AND uri_prefix IS NOT DISTINCT FROM $2 AND reason_family IS NOT DISTINCT FROM $3 ORDER BY id LIMIT 1`,+ [rule.sourceId, rule.uriPrefix, rule.reasonFamily]);+ return { rule: normalize(existing!), created: false };+}++/** Marks a rule removed (the row stays as the receipt). Null when no active rule has that id. */+export async function removeTrustAllowRule(engine: Pick<BrainEngine, 'executeRaw'>, id: number, by: Principal | null): Promise<TrustAllowRule | null> {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ 'UPDATE trust_allow_rules SET removed_at = now(), removed_by = $2 WHERE id = $1 AND removed_at IS NULL RETURNING *', [id, principalLabel(by)]);+ return row ? normalize(row) : null;+}++export async function getTrustAllowRule(engine: Pick<BrainEngine, 'executeRaw'>, id: number): Promise<TrustAllowRule | null> {+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM trust_allow_rules WHERE id = $1', [id]);+ return row ? normalize(row) : null;+}++export async function listTrustAllowRules(engine: Pick<BrainEngine, 'executeRaw'>, opts: { sourceIds?: string[]; includeRemoved?: boolean } = {}): Promise<TrustAllowRule[]> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT * FROM trust_allow_rules WHERE ($1::boolean OR removed_at IS NULL) AND ($2::text[] IS NULL OR source_id = ANY($2::text[])) ORDER BY id`,+ [opts.includeRemoved === true, opts.sourceIds?.length ? opts.sourceIds : null]);+ return rows.map(normalize);+}++/** The server-stamped fields of a write the gate assessed. Never frontmatter. */+export interface TrustAllowCandidate {+ sourceId: string;+ /** `pages.source_uri` as the write path stamped it (connector or capture URI), or null. */+ sourceUri: string | null;+ /** The reason families the gate flagged. */+ families: readonly string[];+}++/**+ * The active rules that cover every flagged family of the candidate, or null+ * when some family is not covered. A rule covers a family when it names that+ * family or no family; it applies when its source matches and its URI prefix+ * (if any) prefixes the server-stamped source URI. A candidate with no+ * families matches nothing (there is nothing to allow).+ */+export function matchTrustAllowRule(rules: readonly Pick<TrustAllowRule, 'id' | 'source_id' | 'uri_prefix' | 'reason_family' | 'removed_at'>[],+ candidate: TrustAllowCandidate): number[] | null {+ if (candidate.families.length === 0) return null;+ const applicable = rules.filter(rule => rule.removed_at === null && rule.source_id === candidate.sourceId+ && (rule.uri_prefix === null || (candidate.sourceUri !== null && candidate.sourceUri.startsWith(rule.uri_prefix))));+ const used = new Set<number>();+ for (const family of new Set(candidate.families)) {+ const cover = applicable.find(rule => rule.reason_family === null || rule.reason_family === family);+ if (!cover) return null;+ used.add(cover.id);+ }+ return [...used].sort((a, b) => a - b);+}diff --git a/src/core/trust/owner-actions.ts b/src/core/trust/owner-actions.tsnew file mode 100644index 0000000000..7381b9ef39--- /dev/null+++ b/src/core/trust/owner-actions.ts@@ -0,0 +1,478 @@+/**+ * Owner trust actions (#5575: A4, CEO-9, CEO-12, DX-2, DX-3, DX-7, DX-13,+ * DX-14, ENG-10, ENG-15): confirm, drop, release, revert, allow and the+ * `disable --all` kill switch, shared by the local CLI, the resident owner's+ * IPC administration (persistence/administration.ts) and the `confirm_memory`+ * op (ops/trust.ts).+ *+ * Every action runs in two steps. `previewOwnerAction` reads the target and+ * returns what the owner approves: a one-line summary, the typed token, the+ * exact command, whether the action raises trust (CEO-9) and a `binding` that+ * names the target's exact state (row content and tier, page revision,+ * proposal status). `applyOwnerAction` previews again under the same rules,+ * refuses with `preview_changed` when the binding moved, and refuses a+ * raising action without a confirmation. The confirmation itself is+ * established by the caller: the CLI's typed-token TTY prompt, or a+ * memory_confirm connection (trust/confirm.ts). Over IPC the prompt happens+ * in the invoking CLI and the resident owner re-runs the preview and checks+ * the binding before applying (DX-2).+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import type { Principal } from '../persistence/model.ts';+import type { OwnerConfirmation } from './confirm.ts';+import { tierRaiseFix } from './confirm.ts';+import { decideTrustProposal } from './decide.ts';+import { getTrustProposal, pendingTrustProposalsFor, trustProposalRef, type TrustDecisionResult, type TrustProposalRow } from './proposals.ts';+import {+ confirmPage, latestPageVersionId, lowerPageState, readPageTrustState, readPageVersion, revertLoweredPage, revertPageToVersion,+ setRowTier, versionTier, type PageActionResult,+} from './page-handlers.ts';+import { formatTrustRef, pageRef, parseTrustRef, resolvePageRef, type TrustRef } from './refs.ts';+import { storedTrustTier, trustLabel, type TrustTier } from './tier.ts';+import {+ addTrustAllowRule, getTrustAllowRule, normalizeTrustAllowRule, parseAllowRuleRef, principalLabel, removeTrustAllowRule, type TrustAllowRule,+} from './allow-rules.ts';++export const OWNER_ACTIONS = ['confirm', 'drop', 'release', 'revert', 'allow', 'allow_remove', 'disable', 'enable'] as const;+export type OwnerActionName = typeof OWNER_ACTIONS[number];++export interface OwnerActionInput {+ action: OwnerActionName;+ /** The typed ref (confirm, drop, release, revert, allow_remove). */+ ref?: string;+ /** Routing for a bare page slug, and the source of an allow rule. */+ source?: string | null;+ /** revert p:<source>/<slug> --version <id>. */+ version?: number;+ uri_prefix?: string | null;+ reason_family?: string | null;+ reason?: string | null;+}++export interface OwnerActionPreview {+ action: OwnerActionName;+ ref: string;+ summary: string;+ /** What the owner types on the TTY (the ref, or a hash8 for long refs). */+ token: string;+ /** The exact local command that performs this action (never with --yes). */+ command: string[];+ /** CEO-9: the action raises trust (or lowers protection), so it needs the owner's confirmation. */+ raises: boolean;+ /** The target's exact approved state; apply refuses when it moved. */+ binding: string;+ tier?: TrustTier;+ target_tier?: TrustTier;+ /** Page actions: the page revision and (revert) the version the owner approved. */+ revision?: string;+ version_id?: number;+}++export interface OwnerActionResult {+ action: OwnerActionName;+ ref: string;+ status: string;+ tier?: TrustTier;+ prior_tier?: TrustTier;+ detail?: Record<string, unknown>;+}++export interface OwnerApplyOptions {+ /** The binding from the preview the owner approved. */+ binding: string;+ /** How the owner confirmed; required when the preview raises. */+ confirmation: OwnerConfirmation | null;+ by?: Principal | null;+ config?: GBrainConfig;+ /** A memory_confirm caller's context (managed page writes admit under its authority). */+ ctx?: OperationContext;+}++const hash8 = (value: string): string => createHash('sha256').update(value).digest('hex').slice(0, 8);+const bindingOf = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex');+const snippet = (text: unknown, max = 80): string => {+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();+ return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;+};+const trustCommand = (...args: string[]): string[] => ['gbrain', 'trust', ...args];++function notFound(ref: string, what: string): Error {+ return opError('not_found', `No ${what} ${ref}.`, 'Check the ref; gbrain trust review lists what is waiting for you.');+}++// ---------------------------------------------------------------------------+// Targets+// ---------------------------------------------------------------------------++interface RowTarget { table: 'facts' | 'takes'; id: number; sourceId: string; tier: TrustTier; text: string; binding: string; live: boolean }++async function readFactTarget(engine: BrainEngine, id: number): Promise<RowTarget | null> {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT id, source_id, trust_tier, fact, entity_slug, kind, claim_metric, claim_value, claim_unit, claim_period, value, event_type, dimension, context,+ expired_at, superseded_by FROM facts WHERE id = $1`, [id]);+ if (!row) return null;+ return { table: 'facts', id, sourceId: String(row.source_id), tier: storedTrustTier(row.trust_tier), text: String(row.fact ?? ''),+ binding: bindingOf({ ...row, expired_at: row.expired_at ? String(row.expired_at) : null }), live: !row.expired_at };+}++async function readTakeTarget(engine: BrainEngine, id: number): Promise<RowTarget | null> {+ const [row] = await engine.executeRaw<Record<string, unknown>>(+ `SELECT t.id, p.source_id, t.trust_tier, t.claim, t.kind, t.holder, t.active, t.superseded_by+ FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.id = $1`, [id]);+ if (!row) return null;+ return { table: 'takes', id, sourceId: String(row.source_id), tier: storedTrustTier(row.trust_tier), text: String(row.claim ?? ''),+ binding: bindingOf(row), live: row.active !== false };+}++// TODO(L2a-merge): replace this adapter with write-gate-store.ts (getWriteGateHold, releaseWriteGateHold,+// dropWriteGateHold) and the gate's publish-at-user_confirmed path. It reads the same write_gate_holds table.+export interface HoldRow { id: number; kind: 'fact' | 'take'; source_id: string; slug: string; status: string; tier: TrustTier; reason_families: string[]; payload: Record<string, unknown>; last_seen_at: string }+export interface HoldStoreAdapter {+ get(engine: BrainEngine, id: number): Promise<HoldRow | null>;+ list(engine: BrainEngine, opts: { sourceId?: string; since?: Date }): Promise<HoldRow[]>;+ /** Marks the hold released and publishes its payload at user_confirmed in `tx`; false when it was no longer held. */+ release(tx: BrainEngine, id: number, by: string): Promise<boolean>;+ drop(tx: BrainEngine, id: number, by: string): Promise<boolean>;+}+async function holdTableExists(engine: BrainEngine): Promise<boolean> {+ const [row] = await engine.executeRaw<{ t: string | null }>(`SELECT to_regclass('write_gate_holds')::text AS t`);+ return !!row?.t;+}+const holdColumns = `id, kind, source_id, slug, status, tier, reason_families, payload, last_seen_at`;+function holdRow(r: Record<string, unknown>): HoldRow {+ const payload = typeof r.payload === 'string' ? JSON.parse(r.payload) as Record<string, unknown> : (r.payload as Record<string, unknown> | null) ?? {};+ return { id: Number(r.id), kind: r.kind as HoldRow['kind'], source_id: String(r.source_id), slug: String(r.slug ?? ''), status: String(r.status),+ tier: storedTrustTier(r.tier), reason_families: (r.reason_families as string[] | null) ?? [], payload, last_seen_at: new Date(r.last_seen_at as string).toISOString() };+}+const decideHoldSql = (status: 'released' | 'dropped') =>+ `UPDATE write_gate_holds SET status = '${status}', decided_at = now(), decided_by = $2 WHERE id = $1 AND status = 'held' RETURNING id`;+const defaultHoldStore: HoldStoreAdapter = {+ async get(engine, id) {+ if (!(await holdTableExists(engine))) return null;+ const [row] = await engine.executeRaw<Record<string, unknown>>(`SELECT ${holdColumns} FROM write_gate_holds WHERE id = $1`, [id]);+ return row ? holdRow(row) : null;+ },+ async list(engine, opts) {+ if (!(await holdTableExists(engine))) return [];+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT ${holdColumns} FROM write_gate_holds WHERE status = 'held' AND ($1::text IS NULL OR source_id = $1)+ AND ($2::timestamptz IS NULL OR last_seen_at >= $2) ORDER BY id LIMIT 1000`, [opts.sourceId ?? null, opts.since?.toISOString() ?? null]);+ return rows.map(holdRow);+ },+ async release() {+ throw opError('unavailable', 'Releasing a held write needs the write gate\'s publish path, which this build does not include; nothing was changed.',+ 'Upgrade gbrain on the brain host, then run gbrain trust release again.');+ },+ async drop(tx, id, by) { return (await tx.executeRaw(decideHoldSql('dropped'), [id, by])).length === 1; },+};+let holdStore: HoldStoreAdapter = defaultHoldStore;+/** Test seam (and the L2a merge point): the hold store the owner actions use. */+export function __setHoldStoreForTests(store: HoldStoreAdapter | null): void { holdStore = store ?? defaultHoldStore; }+export function currentHoldStore(): HoldStoreAdapter { return holdStore; }++// ---------------------------------------------------------------------------+// Kill switch (DX-13)+// ---------------------------------------------------------------------------++/** `gbrain trust disable --all`: the values it writes. */+export const TRUST_KILL_SWITCH_VALUES: Readonly<Record<string, string>> = Object.freeze({+ 'write_gate.external_mode': 'off',+ 'write_gate.agent_mode': 'off',+ 'trust.agent_activation': 'allow',+});+/** The receipt of the last disable/enable: who, when, and the values the disable replaced. */+export const TRUST_KILL_SWITCH_KEY = 'trust.kill_switch';+interface KillSwitchReceipt { state: 'disabled' | 'enabled'; at: string; by: string; prior?: Record<string, string | null>; disabled_at?: string }++async function readKillSwitch(engine: BrainEngine): Promise<KillSwitchReceipt | null> {+ const raw = await engine.getConfig(TRUST_KILL_SWITCH_KEY);+ if (!raw) return null;+ try { return JSON.parse(raw) as KillSwitchReceipt; } catch { return null; }+}+async function currentSwitchValues(engine: BrainEngine): Promise<Record<string, string | null>> {+ const out: Record<string, string | null> = {};+ for (const key of Object.keys(TRUST_KILL_SWITCH_VALUES)) out[key] = await engine.getConfig(key);+ return out;+}++// ---------------------------------------------------------------------------+// Preview+// ---------------------------------------------------------------------------++function requireRef(input: OwnerActionInput): TrustRef {+ if (!input.ref) throw opError('invalid_params', `trust ${input.action} needs a ref.`, 'Pass a ref such as f12, t3, h4, tp7 or p:<source>/<slug>; gbrain trust review lists them.');+ return parseTrustRef(input.ref);+}++function unsupported(action: OwnerActionName, ref: TrustRef): Error {+ return opError('invalid_params', `trust ${action} does not apply to ${formatTrustRef(ref)}.`,+ 'confirm takes f<id>, t<id>, p:<source>/<slug>, tp<id> or h<id>; drop takes tp<id> or h<id>; release takes h<id>; revert takes tp<id> (an agent-edit item) or a page; allow --remove takes a<id>.');+}++function proposalSummary(p: TrustProposalRow, verb: 'Accept' | 'Dismiss' | 'Revert'): string {+ if (p.action === 'lower_page') {+ const s = lowerPageState(p);+ const page = pageRef(p.source_id, s.slug);+ if (verb === 'Accept') return `Endorse the agent edit of ${page}: raise it from "${trustLabel(s.edited_tier)}" to "confirmed by you"`;+ if (verb === 'Revert') return `Revert the agent edit of ${page}: restore version ${s.version_id ?? '?'} and its tier "${trustLabel(s.prior_tier)}"`;+ return `Dismiss ${trustProposalRef(p.id)}: ${page} stays "${trustLabel(s.edited_tier)}"`;+ }+ const target = `${p.target_table === 'facts' ? 'f' : p.target_table === 'takes' ? 't' : ''}${p.target_id}`;+ const related = p.related_id === null ? '' : ` with ${p.related_table === 'facts' ? 'f' : p.related_table === 'takes' ? 't' : ''}${p.related_id}`;+ const what = p.action === 'forget' ? `forget ${target}` : p.action.startsWith('supersede') ? `supersede ${target}${related}` : `${p.action.replace('_', ' ')} ${target}${related}`;+ return verb === 'Accept' ? `Accept ${trustProposalRef(p.id)}: ${what} (raises trust over "${trustLabel(storedTrustTier(p.before_state.prior_tier ?? p.before_state.tier))}")`+ : `Dismiss ${trustProposalRef(p.id)}: do not ${what}`;+}++async function proposalBinding(engine: BrainEngine, p: TrustProposalRow): Promise<string> {+ const page = p.action === 'lower_page' ? await readPageTrustState(engine, p.source_id, lowerPageState(p).slug) : null;+ return bindingOf({ id: p.id, status: p.status, updated_at: p.updated_at, page: page?.revision ?? null });+}++async function previewConfirm(engine: BrainEngine, ref: TrustRef, input: OwnerActionInput): Promise<OwnerActionPreview> {+ if (ref.kind === 'fact' || ref.kind === 'take') {+ const label = formatTrustRef(ref);+ const row = ref.kind === 'fact' ? await readFactTarget(engine, ref.id) : await readTakeTarget(engine, ref.id);+ if (!row) throw notFound(label, ref.kind);+ if (!row.live) throw opError('invalid_params', `${label} is no longer active (expired, superseded or forgotten); there is nothing to confirm.`, 'Confirm the row that replaced it instead; gbrain trust explain shows its history.');+ return { action: 'confirm', ref: label, token: label, command: trustCommand('confirm', label), raises: row.tier !== 'user_confirmed', binding: row.binding,+ tier: row.tier, target_tier: 'user_confirmed', summary: `Raise ${ref.kind} ${label} ("${snippet(row.text)}") from "${trustLabel(row.tier)}" to "confirmed by you"` };+ }+ if (ref.kind === 'page') {+ const { sourceId, slug } = await resolvePageRef(engine, ref, input.source);+ const label = pageRef(sourceId, slug);+ const state = await readPageTrustState(engine, sourceId, slug);+ if (!state) throw notFound(label, 'page');+ return { action: 'confirm', ref: label, token: hash8(`${label}@${state.revision}`), command: trustCommand('confirm', label),+ raises: state.tier !== 'user_confirmed' || state.hasMarker, binding: state.revision, tier: state.tier, target_tier: 'user_confirmed', revision: state.revision,+ summary: `Raise page ${label} from "${trustLabel(state.tier)}" to "confirmed by you"${state.hasMarker ? ' and remove its trust_tier marker' : ''}` };+ }+ if (ref.kind === 'proposal') {+ const p = await getTrustProposal(engine, ref.id);+ if (!p) throw notFound(trustProposalRef(ref.id), 'trust proposal');+ return { action: 'confirm', ref: trustProposalRef(p.id), token: trustProposalRef(p.id), command: trustCommand('confirm', trustProposalRef(p.id)),+ raises: true, binding: await proposalBinding(engine, p), target_tier: 'user_confirmed', summary: proposalSummary(p, 'Accept') };+ }+ if (ref.kind === 'hold') return previewHold(engine, ref.id, 'release');+ throw unsupported('confirm', ref);+}++async function previewHold(engine: BrainEngine, id: number, action: 'release' | 'drop'): Promise<OwnerActionPreview> {+ const label = `h${id}`;+ const hold = await holdStore.get(engine, id);+ if (!hold) throw notFound(label, 'held write');+ const text = hold.payload.fact ?? hold.payload.claim ?? '';+ return { action, ref: label, token: label, command: trustCommand(action, label), raises: action === 'release',+ binding: bindingOf({ id: hold.id, status: hold.status, last_seen_at: hold.last_seen_at }), tier: hold.tier,+ ...(action === 'release' ? { target_tier: 'user_confirmed' as TrustTier } : {}),+ summary: action === 'release'+ ? `Release held ${hold.kind} ${label} ("${snippet(text)}", ${hold.reason_families.join(', ') || 'detector error'}) into memory as "confirmed by you"`+ : `Drop held ${hold.kind} ${label} ("${snippet(text)}"); it stays out of memory` };+}++async function previewRevert(engine: BrainEngine, ref: TrustRef, input: OwnerActionInput): Promise<OwnerActionPreview> {+ if (ref.kind === 'proposal') {+ const p = await getTrustProposal(engine, ref.id);+ if (!p) throw notFound(trustProposalRef(ref.id), 'trust proposal');+ if (p.action !== 'lower_page') throw opError('invalid_params', `${trustProposalRef(p.id)} is a ${p.action} proposal; only agent-edit items (lower_page) revert.`, `Use gbrain trust confirm ${trustProposalRef(p.id)} or gbrain trust drop ${trustProposalRef(p.id)}.`);+ const s = lowerPageState(p);+ return { action: 'revert', ref: trustProposalRef(p.id), token: trustProposalRef(p.id), command: trustCommand('revert', trustProposalRef(p.id)),+ raises: true, binding: await proposalBinding(engine, p), tier: s.edited_tier, target_tier: s.prior_tier, summary: proposalSummary(p, 'Revert') };+ }+ if (ref.kind !== 'page') throw unsupported('revert', ref);+ const { sourceId, slug } = await resolvePageRef(engine, ref, input.source);+ const label = pageRef(sourceId, slug);+ const state = await readPageTrustState(engine, sourceId, slug);+ if (!state) throw notFound(label, 'page');+ let versionId = input.version ?? null;+ if (versionId === null) {+ const lowered = (await pendingTrustProposalsFor(engine, 'pages', state.pageId)).find(p => p.action === 'lower_page');+ versionId = (lowered ? lowerPageState(lowered).version_id : null) ?? await latestPageVersionId(engine, state.pageId);+ }+ if (versionId === null) throw opError('not_found', `${label} has no earlier version to revert to.`, `gbrain history ${slug} lists a page's versions.`);+ const version = await readPageVersion(engine, state.pageId, versionId);+ if (!version) throw opError('not_found', `Version ${versionId} is not in the history of ${label}.`, `List the page's versions with gbrain history ${slug} and pass one of their ids to --version.`);+ const tier = versionTier(version);+ return { action: 'revert', ref: label, token: hash8(`${label}@${state.revision}#${versionId}`), command: [...trustCommand('revert', label), '--version', String(versionId)],+ raises: true, binding: bindingOf({ revision: state.revision, version: versionId }), tier: state.tier, target_tier: tier, revision: state.revision, version_id: versionId,+ summary: `Revert page ${label} to version ${versionId}: restore its content and its tier "${trustLabel(tier)}"${version.trust_tier ? '' : ' (a version from before trust tiers reads as unverified origin)'}` };+}++/** Reads the target and returns what the owner approves. Read-only. */+export async function previewOwnerAction(engine: BrainEngine, input: OwnerActionInput): Promise<OwnerActionPreview> {+ switch (input.action) {+ case 'confirm': return previewConfirm(engine, requireRef(input), input);+ case 'release': {+ const ref = requireRef(input);+ if (ref.kind !== 'hold') throw unsupported('release', ref);+ return previewHold(engine, ref.id, 'release');+ }+ case 'drop': {+ const ref = requireRef(input);+ if (ref.kind === 'hold') return previewHold(engine, ref.id, 'drop');+ if (ref.kind !== 'proposal') throw unsupported('drop', ref);+ const p = await getTrustProposal(engine, ref.id);+ if (!p) throw notFound(trustProposalRef(ref.id), 'trust proposal');+ return { action: 'drop', ref: trustProposalRef(p.id), token: trustProposalRef(p.id), command: trustCommand('drop', trustProposalRef(p.id)),+ raises: false, binding: await proposalBinding(engine, p), summary: proposalSummary(p, 'Dismiss') };+ }+ case 'revert': return previewRevert(engine, requireRef(input), input);+ case 'allow': {+ const rule = normalizeTrustAllowRule({ sourceId: input.source ?? '', uriPrefix: input.uri_prefix, reasonFamily: input.reason_family, reason: input.reason });+ const command = [...trustCommand('allow', '--source', rule.sourceId), ...(rule.uriPrefix ? ['--uri-prefix', rule.uriPrefix] : []),+ ...(rule.reasonFamily ? ['--reason-family', rule.reasonFamily] : [])];+ return { action: 'allow', ref: `allow:${rule.sourceId}`, token: `allow-${rule.sourceId}`, command, raises: true, binding: bindingOf(rule),+ summary: `Stop holding ${rule.reasonFamily ? `"${rule.reasonFamily}" ` : ''}instruction-like content from source ${rule.sourceId}${rule.uriPrefix ? ` under ${rule.uriPrefix}` : ''}` };+ }+ case 'allow_remove': {+ const id = input.ref ? parseAllowRuleRef(input.ref) : null;+ if (id === null) throw opError('invalid_params', 'trust allow --remove needs an allow rule ref a<id>.', 'gbrain trust review lists the allow rules with their refs.');+ const rule = await getTrustAllowRule(engine, id);+ if (!rule || rule.removed_at) throw notFound(`a${id}`, 'active allow rule');+ return { action: 'allow_remove', ref: rule.ref, token: rule.ref, command: trustCommand('allow', '--remove', rule.ref), raises: false,+ binding: bindingOf(rule), summary: `Remove allow rule ${rule.ref} (source ${rule.source_id}${rule.uri_prefix ? `, ${rule.uri_prefix}` : ''})` };+ }+ case 'disable': {+ const values = await currentSwitchValues(engine);+ return { action: 'disable', ref: 'trust:all', token: 'disable-all', command: trustCommand('disable', '--all'), raises: true, binding: bindingOf(values),+ summary: 'Turn the memory trust protections off: write_gate.external_mode=off, write_gate.agent_mode=off, trust.agent_activation=allow' };+ }+ case 'enable': {+ const receipt = await readKillSwitch(engine);+ return { action: 'enable', ref: 'trust:all', token: 'enable-all', command: trustCommand('disable', '--all', '--undo'), raises: false,+ binding: bindingOf({ receipt, values: await currentSwitchValues(engine) }), summary: 'Restore the memory trust protections the last disable --all turned off' };+ }+ }+}++/** DX-3: the fix an owner action emits when it needs the user. Tier-raising actions never carry --yes and are never `run`. */+export function ownerActionFix(preview: OwnerActionPreview) {+ return tierRaiseFix(preview.command, `${preview.summary}. Only the owner can do this, in an interactive terminal on the brain host.`,+ `Run on the brain host, in a terminal: ${preview.command.join(' ')}`);+}++// ---------------------------------------------------------------------------+// Apply+// ---------------------------------------------------------------------------++function fromDecision(action: OwnerActionName, d: TrustDecisionResult): OwnerActionResult {+ if (d.status === 'stale' || d.status === 'refused' || d.status === 'not_found') {+ throw opError('preview_changed', `${d.ref} could not be decided (${d.status}${d.reason ? `: ${d.reason}` : ''}); nothing was changed.`,+ 'Run gbrain trust review to see its current state.');+ }+ return { action, ref: d.ref, status: d.status, ...(d.detail ? { detail: d.detail } : {}) };+}++function asPageResult(action: OwnerActionName, r: PageActionResult): OwnerActionResult {+ return { action, ref: r.ref, status: r.status, tier: r.tier, prior_tier: r.prior_tier,+ detail: { ...(r.marker_removed !== undefined ? { marker_removed: r.marker_removed } : {}), ...(r.version_id !== undefined ? { version_id: r.version_id } : {}) } };+}++/**+ * Applies one owner action the owner approved. Re-reads the target, refuses+ * when it changed since the preview (`preview_changed`) or when a raising+ * action has no confirmation (`confirmation_required`), then performs it.+ */+export async function applyOwnerAction(engine: BrainEngine, input: OwnerActionInput, opts: OwnerApplyOptions): Promise<OwnerActionResult> {+ const preview = await previewOwnerAction(engine, input);+ if (preview.binding !== opts.binding) {+ throw opError('preview_changed', `${preview.ref} changed after you approved it; nothing was changed.`,+ 'Run the command again: it shows the current state and asks for a new confirmation.');+ }+ if (preview.raises && !opts.confirmation) {+ throw opError('confirmation_required', `${preview.summary} needs the owner's confirmation; nothing was changed.`,+ 'Do not retry with --yes. Tell the user to run the command in fix in an interactive terminal on the brain host.', { fix: ownerActionFix(preview) });+ }+ const confirmation = opts.confirmation ?? { via: 'tty' as const };+ const by = opts.by ?? null;+ const decision = { confirmation, decidedBy: by, ...(opts.config ? { config: opts.config } : {}) };+ const ref = input.ref ? parseTrustRef(input.ref) : null;+ switch (input.action) {+ case 'confirm':+ case 'release': {+ if (ref?.kind === 'fact' || ref?.kind === 'take') {+ if (!preview.raises) return { action: input.action, ref: preview.ref, status: 'unchanged', tier: 'user_confirmed', prior_tier: 'user_confirmed' };+ const read = ref.kind === 'fact' ? readFactTarget : readTakeTarget;+ const row = (await read(engine, ref.id))!;+ const ok = await setRowTier(engine, { table: row.table, id: row.id, sourceId: row.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by,+ note: { via: confirmation.via, action: 'confirm', by: principalLabel(by) },+ expect: async tx => (await read(tx, ref.id))?.binding === opts.binding });+ if (!ok) throw opError('preview_changed', `${preview.ref} changed after you approved it; nothing was changed.`, 'Run the command again.');+ return { action: input.action, ref: preview.ref, status: 'confirmed', tier: 'user_confirmed', prior_tier: row.tier };+ }+ if (ref?.kind === 'page') {+ const { sourceId, slug } = await resolvePageRef(engine, ref, input.source);+ if (!preview.raises) return { action: 'confirm', ref: preview.ref, status: 'unchanged', tier: 'user_confirmed', prior_tier: 'user_confirmed' };+ return asPageResult('confirm', await confirmPage(engine, { sourceId, slug, expectedRevision: preview.revision!, confirmation, by, config: opts.config, ctx: opts.ctx }));+ }+ if (ref?.kind === 'proposal') return fromDecision('confirm', await decideTrustProposal(engine, ref.id, 'accept', decision));+ if (ref?.kind === 'hold') {+ const released = await engine.transaction(tx => holdStore.release(tx, ref.id, principalLabel(by)));+ if (!released) throw opError('preview_changed', `h${ref.id} was decided meanwhile; nothing was changed.`, 'Run gbrain trust review.');+ return { action: 'release', ref: preview.ref, status: 'released', tier: 'user_confirmed', prior_tier: preview.tier };+ }+ throw unsupported(input.action, ref!);+ }+ case 'drop': {+ if (ref?.kind === 'hold') {+ if (!(await engine.transaction(tx => holdStore.drop(tx, ref.id, principalLabel(by))))) throw opError('preview_changed', `h${ref.id} was decided meanwhile; nothing was changed.`, 'Run gbrain trust review.');+ return { action: 'drop', ref: preview.ref, status: 'dropped' };+ }+ if (ref?.kind === 'proposal') return fromDecision('drop', await decideTrustProposal(engine, ref.id, 'reject', decision));+ throw unsupported('drop', ref!);+ }+ case 'revert': {+ if (ref?.kind === 'proposal') {+ const p = (await getTrustProposal(engine, ref.id))!;+ if (p.status !== 'pending') throw opError('preview_changed', `${trustProposalRef(p.id)} is ${p.status}; nothing was changed.`, 'Run gbrain trust review.');+ return fromDecision('revert', await revertLoweredPage(engine, p, decision));+ }+ if (ref?.kind === 'page') {+ const { sourceId, slug } = await resolvePageRef(engine, ref, input.source);+ return asPageResult('revert', await revertPageToVersion(engine, { sourceId, slug, expectedRevision: preview.revision!, versionId: preview.version_id!, confirmation, by, config: opts.config, ctx: opts.ctx }));+ }+ throw unsupported('revert', ref!);+ }+ case 'allow': {+ const { rule, created } = await addTrustAllowRule(engine, { sourceId: input.source ?? '', uriPrefix: input.uri_prefix, reasonFamily: input.reason_family, reason: input.reason }, by);+ return { action: 'allow', ref: rule.ref, status: created ? 'added' : 'unchanged', detail: { rule } };+ }+ case 'allow_remove': {+ const rule = await removeTrustAllowRule(engine, parseAllowRuleRef(input.ref!)!, by);+ if (!rule) throw opError('preview_changed', `${preview.ref} was removed meanwhile.`, 'Run gbrain trust review.');+ return { action: 'allow_remove', ref: rule.ref, status: 'removed', detail: { rule: rule as TrustAllowRule } };+ }+ case 'disable': {+ const prior = await currentSwitchValues(engine);+ const at = new Date().toISOString();+ const receipt: KillSwitchReceipt = { state: 'disabled', at, by: principalLabel(by), prior };+ for (const [key, value] of Object.entries(TRUST_KILL_SWITCH_VALUES)) await engine.setConfig(key, value);+ await engine.setConfig(TRUST_KILL_SWITCH_KEY, JSON.stringify(receipt));+ return { action: 'disable', ref: preview.ref, status: 'disabled', detail: { values: { ...TRUST_KILL_SWITCH_VALUES }, prior, at } };+ }+ case 'enable': {+ const last = await readKillSwitch(engine);+ const current = await currentSwitchValues(engine);+ const restored: string[] = [];+ for (const [key, wrote] of Object.entries(TRUST_KILL_SWITCH_VALUES)) {+ // Restore only what the disable still owns: a value the owner changed since stays.+ if (last?.state !== 'disabled' || current[key] !== wrote) continue;+ const prior = last.prior?.[key] ?? null;+ if (prior === null) await engine.unsetConfig(key); else await engine.setConfig(key, prior);+ restored.push(key);+ }+ const at = new Date().toISOString();+ await engine.setConfig(TRUST_KILL_SWITCH_KEY, JSON.stringify({ state: 'enabled', at, by: principalLabel(by), ...(last?.at ? { disabled_at: last.at } : {}) } satisfies KillSwitchReceipt));+ return { action: 'enable', ref: preview.ref, status: last?.state === 'disabled' ? 'enabled' : 'unchanged', detail: { restored, at } };+ }+ }+}++/** The kill switch receipt and current values (review and explain show it). */+export async function trustKillSwitchState(engine: BrainEngine): Promise<{ receipt: KillSwitchReceipt | null; values: Record<string, string | null> }> {+ return { receipt: await readKillSwitch(engine), values: await currentSwitchValues(engine) };+}diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.tsindex 61e88ce194..574c426cd7 100644--- a/src/core/trust/page-handlers.ts+++ b/src/core/trust/page-handlers.ts@@ -1,6 +1,377 @@/**- * 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.+ * Owner page actions and the checked handler for `lower_page` trust proposals+ * (#5575: CEO-9, CEO-12, CEO-21, ENG-10, ENG-22).+ *+ * - Confirm a page: raise it to user_confirmed. When the page carries the+ * lower-only `trust_tier` frontmatter marker (CEO-21), the marker is removed+ * through the canonical page write path (a journaled `trust_owner_page`+ * mutation on a managed brain, `importFromContent` otherwise) written at+ * user_confirmed under the promotion capability; otherwise only the tier+ * column changes.+ * - Revert a page to a version: restore that version's content and its+ * snapshotted tier (page_versions.trust_tier; legacy versions read as+ * `unknown`), bound to the page revision the owner approved.+ * - lower_page proposals (inserted by the CEO-12 guard when an agent write+ * replaced a higher-tier page): accept = the owner endorses the edited page+ * (confirm it); reject = dismiss, the page stays lowered; revert+ * (`revertLoweredPage`) = restore the prior owner version's content and tier.+ *+ * Every function here runs after the caller established the owner's+ * confirmation (trust/confirm.ts); each re-checks the page revision it was+ * approved for and refuses with `preview_changed` when the page moved on.+ * Fence rows (facts, takes, timeline) keep their own tiers on these rewrites.*/-export {};+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { GBrainConfig } from '../config.ts';+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import type { PreparedMutation } from '../persistence/coordinator.ts';+import type { Principal, WriteRequest } from '../persistence/model.ts';+import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';+import type { PageType } from '../types.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import type { PageVersion } from '../page-state/version-types.ts';+import { maintenanceAttribution, principalAttribution, withWriteAttribution } from '../persistence/attribution.ts';+import { withCoordinatedWrite, withTrustKeep, withTrustPromotion } from '../persistence/context.ts';+import type { OwnerConfirmation } from './confirm.ts';+import { MEMORY_CONFIRM_SCOPE } from './confirm.ts';+import { pageRef } from './refs.ts';+import {+ decisionResult, registerTrustProposalHandler, transitionTrustProposal,+ type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow,+} from './proposals.ts';+import { effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';++/** The journaled operation that publishes an owner page action on a managed brain. */+export const TRUST_OWNER_PAGE_OPERATION = 'trust_owner_page';+/** Fence projections keep their own tiers when an owner action rewrites the page around them. */+const FENCE_TABLES = ['facts', 'takes', 'timeline_entries'] as const;++export interface PageTrustState {+ pageId: number;+ sourceId: string;+ slug: string;+ tier: TrustTier;+ revision: string;+ hasMarker: boolean;+ snapshot: PageSnapshot;+}++/** The page as an owner action sees it: tier, revision and whether the CEO-21 marker is present. Null when absent or deleted. */+export async function readPageTrustState(engine: BrainEngine, sourceId: string, slug: string): Promise<PageTrustState | null> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot || snapshot.page.deleted_at) return null;+ const [row] = await engine.executeRaw<{ trust_tier: string }>('SELECT trust_tier FROM pages WHERE id = $1', [snapshot.page.id]);+ return {+ pageId: snapshot.page.id, sourceId, slug, tier: storedTrustTier(row?.trust_tier), revision: snapshot.revision,+ hasMarker: Object.hasOwn(snapshot.page.frontmatter ?? {}, 'trust_tier'), snapshot,+ };+}++function changedSincePreview(ref: string, what: string): Error {+ return opError('preview_changed', `${ref} changed after you approved ${what}; nothing was changed.`,+ 'Run the command again: it shows the page as it is now and asks for a new confirmation.');+}++/** The page with the CEO-21 marker removed, as canonical markdown. */+function markdownWithoutMarker(snapshot: PageSnapshot): string {+ const { trust_tier: _marker, ...frontmatter } = (snapshot.page.frontmatter ?? {}) as Record<string, unknown>;+ return serializeMarkdown(frontmatter, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {+ type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,+ });+}++/** One version's canonical markdown, the way revert_version restores it (page-prepare.ts). */+function versionMarkdown(snapshot: PageSnapshot, version: PageVersion): string {+ const page = { ...snapshot.page, compiled_truth: version.compiled_truth, frontmatter: version.frontmatter,+ ...(version.timeline != null ? { timeline: version.timeline } : {}),+ ...(version.title != null ? { title: version.title } : {}),+ ...(version.type != null ? { type: version.type as PageType } : {}) };+ return serializePageToMarkdown(page, version.tags ?? snapshot.tags);+}++export async function readPageVersion(engine: BrainEngine, pageId: number, versionId: number): Promise<(PageVersion & { trust_tier: string | null }) | null> {+ const [version] = await engine.executeRaw<PageVersion & { trust_tier: string | null }>(+ 'SELECT * FROM page_versions WHERE id = $1 AND page_id = $2', [versionId, pageId]);+ return version ?? null;+}++/** The most recent version of a page (the content just before its latest archived write). */+export async function latestPageVersionId(engine: BrainEngine, pageId: number): Promise<number | null> {+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM page_versions WHERE page_id = $1 ORDER BY id DESC LIMIT 1', [pageId]);+ return row ? Number(row.id) : null;+}++const ownerTrust = (tier: TrustTier, channel: string, via: OwnerConfirmation['via']): WriteTrust =>+ effectiveWriteTrust({ channel: tier, origin: { channel: `owner:${channel}`, connector: via } });++async function managed(engine: BrainEngine): Promise<boolean> {+ const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');+ return managedPersistenceEnabled(engine);+}++async function attributionFor(engine: BrainEngine, by: Principal | null | undefined) {+ return by ? principalAttribution(by) : maintenanceAttribution(engine);+}++/**+ * A tier-only change of one row (no content column changes), inside the+ * coordinator capability on a managed brain. Raising needs `ceiling`.+ */+export async function setRowTier(engine: BrainEngine, input: {+ table: 'facts' | 'takes' | 'pages'; id: number; sourceId: string; tier: TrustTier; ceiling?: TrustTier;+ expect?: (tx: BrainEngine) => Promise<boolean>; by?: Principal | null; note?: Record<string, unknown>;+ also?: (tx: BrainEngine) => Promise<void>;+}): Promise<boolean> {+ const attribution = await attributionFor(engine, input.by);+ const enabled = await managed(engine);+ return engine.transaction(async tx => {+ const run = async () => {+ if (input.expect && !(await input.expect(tx))) return false;+ const update = () => tx.executeRaw<{ id: number }>(+ `UPDATE ${input.table} SET trust_tier = $2,+ write_origin = COALESCE(write_origin, '{}'::jsonb) || jsonb_build_object('owner_decision', $3::text::jsonb)+ WHERE id = $1 RETURNING id`, [input.id, input.tier, JSON.stringify({ tier: input.tier, at: new Date().toISOString(), ...input.note })]);+ const rows = input.ceiling ? await withTrustPromotion(tx, input.ceiling, update) : await update();+ if (rows.length !== 1) return false;+ await input.also?.(tx);+ return true;+ };+ return enabled ? withCoordinatedWrite(tx, [input.sourceId], run, attribution) : withWriteAttribution(tx, attribution, run);+ });+}++export interface PageActionInput {+ sourceId: string;+ slug: string;+ /** The page revision the owner approved. */+ expectedRevision: string;+ confirmation: OwnerConfirmation;+ by?: Principal | null;+ config?: GBrainConfig;+ /** A lower_page proposal this action decides, closed in the same transaction. */+ proposal?: { id: number; to: 'accepted' | 'rejected'; after: Record<string, unknown> };+ /** The remote context of a memory_confirm caller (managed admission authority); local CLI otherwise. */+ ctx?: OperationContext;+}++export interface PageActionResult {+ status: 'confirmed' | 'reverted' | 'unchanged';+ ref: string;+ tier: TrustTier;+ prior_tier: TrustTier;+ marker_removed?: boolean;+ version_id?: number;+}++type OwnerPageIntent = {+ mode: 'confirm' | 'revert';+ expected_revision: string;+ version_id?: number;+ via: OwnerConfirmation['via'];+ proposal?: PageActionInput['proposal'];+};++/** Closes a decided proposal inside the publication transaction, or refuses (it was decided meanwhile). */+async function closeProposal(tx: BrainEngine, proposal: PageActionInput['proposal'], by: Principal | null | undefined): Promise<void> {+ if (!proposal) return;+ if (!(await transitionTrustProposal(tx, proposal.id, 'pending', proposal.to, { after: proposal.after, decidedBy: by ?? null }))) {+ throw opError('preview_changed', `Trust proposal tp${proposal.id} was decided by someone else meanwhile; nothing was changed.`,+ 'Run gbrain trust review to see its current state.');+ }+}++/** Raises a page to user_confirmed (removing the CEO-21 marker when present). */+export async function confirmPage(engine: BrainEngine, input: PageActionInput): Promise<PageActionResult> {+ const ref = pageRef(input.sourceId, input.slug);+ const state = await readPageTrustState(engine, input.sourceId, input.slug);+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Check the ref; gbrain trust review lists pages waiting for you.');+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, 'its confirmation');+ if (state.tier === 'user_confirmed' && !state.hasMarker) {+ await engine.transaction(tx => closeProposal(tx, input.proposal, input.by));+ return { status: 'unchanged', ref, tier: state.tier, prior_tier: state.tier };+ }+ if (!state.hasMarker) {+ const ok = await setRowTier(engine, {+ table: 'pages', id: state.pageId, sourceId: input.sourceId, tier: 'user_confirmed', ceiling: 'user_confirmed', by: input.by,+ note: { via: input.confirmation.via, action: 'confirm' },+ expect: async tx => (await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision === input.expectedRevision,+ also: tx => closeProposal(tx, input.proposal, input.by),+ });+ if (!ok) throw changedSincePreview(ref, 'its confirmation');+ return { status: 'confirmed', ref, tier: 'user_confirmed', prior_tier: state.tier, marker_removed: false };+ }+ await publishOwnerPage(engine, input, { mode: 'confirm', expected_revision: input.expectedRevision, via: input.confirmation.via, proposal: input.proposal },+ markdownWithoutMarker(state.snapshot), 'user_confirmed');+ return { status: 'confirmed', ref, tier: 'user_confirmed', prior_tier: state.tier, marker_removed: true };+}++/** The tier a version restores: its snapshot tier, `unknown` for legacy versions. */+export const versionTier = (version: { trust_tier?: string | null }): TrustTier => storedTrustTier(version.trust_tier);++/** Restores a version's content and its snapshotted tier. */+export async function revertPageToVersion(engine: BrainEngine, input: PageActionInput & { versionId: number }): Promise<PageActionResult> {+ const ref = pageRef(input.sourceId, input.slug);+ const state = await readPageTrustState(engine, input.sourceId, input.slug);+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Check the ref; gbrain history <slug> lists its versions.');+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, 'the revert');+ const version = await readPageVersion(engine, state.pageId, input.versionId);+ if (!version) throw opError('not_found', `Version ${input.versionId} is not in the history of ${ref}.`, `List the page's versions with gbrain history ${input.slug} and pass one of their ids to --version.`);+ const tier = versionTier(version);+ await publishOwnerPage(engine, input, { mode: 'revert', expected_revision: input.expectedRevision, version_id: input.versionId, via: input.confirmation.via, proposal: input.proposal },+ versionMarkdown(state.snapshot, version), tier);+ return { status: 'reverted', ref, tier, prior_tier: state.tier, version_id: input.versionId };+}++/**+ * Publishes an owner page write at `tier`. A content rewrite by an owner-tier+ * writer restamps the page (CEO-12); user_confirmed needs the promotion+ * ceiling, and a lower restored tier lowers it (min with the prior tier).+ */+async function publishOwnerPage(engine: BrainEngine, input: PageActionInput, intent: OwnerPageIntent, markdown: string, tier: TrustTier): Promise<void> {+ if (await managed(engine)) {+ await submitOwnerPage(engine, input, intent);+ return;+ }+ const { importFromContent } = await import('../import-file.ts');+ const attribution = await attributionFor(engine, input.by);+ const trust = ownerTrust(tier, intent.mode, intent.via);+ await engine.transaction(tx => withWriteAttribution(tx, { ...attribution, trust }, () => withTrustPromotion(tx, tier, () =>+ withTrustKeep(tx, FENCE_TABLES, async () => {+ if ((await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision !== input.expectedRevision) {+ throw changedSincePreview(pageRef(input.sourceId, input.slug), intent.mode === 'confirm' ? 'its confirmation' : 'the revert');+ }+ await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, forceRechunk: intent.mode === 'revert', allowEmptyOverwrite: intent.mode === 'revert' });+ await closeProposal(tx, intent.proposal, input.by);+ }))));+}++/** Admits the journaled owner page mutation and waits for its publication (the decide_proposal precedent). */+async function submitOwnerPage(engine: BrainEngine, input: PageActionInput, intent: OwnerPageIntent): Promise<void> {+ const { initializeLocalPersistence, requestPrincipalForContext } = await import('../persistence/page-mutations.ts');+ const { submissionAuthority } = await import('../persistence/authority.ts');+ const { admitWrite } = await import('../persistence/journal.ts');+ const { assertPersistenceAccepting, waitForWrite, writeResponse } = await import('../persistence/service.ts');+ const { getWorktreeBinding } = await import('../persistence/ownership.ts');+ const config = input.config ?? ({ engine: engine.kind } as GBrainConfig);+ const ctx = input.ctx ?? ({ engine, sourceId: input.sourceId, remote: false, config, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext);+ assertPersistenceAccepting(engine);+ await initializeLocalPersistence(ctx);+ const principal = await requestPrincipalForContext(ctx);+ const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation, archived FROM sources WHERE id = $1', [input.sourceId]);+ if (!source || source.archived) throw opError('source_changed', `Source ${input.sourceId} is archived or missing; nothing was changed.`, 'Restore the source first (the user\'s call).');+ const authority = await submissionAuthority(ctx, TRUST_OWNER_PAGE_OPERATION, input.sourceId, source.incarnation, input.slug);+ const snapshot = await engine.readPageSnapshot(input.slug, { sourceId: input.sourceId });+ const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');+ const binding = snapshot && writeThrough ? await getWorktreeBinding(engine, input.sourceId) : null;+ if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';+ const row = await admitWrite(engine, {+ principal, operation: TRUST_OWNER_PAGE_OPERATION, sourceId: input.sourceId, sourceIncarnation: source.incarnation, slug: input.slug,+ pageId: snapshot?.page.id ?? null, requestId: randomUUID(), callerIntent: intent, intent, authority,+ worktreeId: binding?.worktree_id ?? null, topologyGeneration: binding?.topology_generation ?? null,+ });+ writeResponse(await waitForWrite(engine, row, config, 30_000));+}++/**+ * The coordinator preparer for `trust_owner_page` (persistence/service.ts).+ * The resident owner re-validates here: a remote request needs a recorded+ * memory_confirm scope; the page must still be at the approved revision.+ */+export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {+ const intent = row.intent as unknown as OwnerPageIntent | null;+ if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || (intent.mode !== 'confirm' && intent.mode !== 'revert') || typeof intent.expected_revision !== 'string'+ || (row.authority.remote && !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE))) {+ throw opError('confirmation_required', 'This owner page action is not confirmed by the owner; nothing was changed.',+ 'Run the gbrain trust command on the brain host in an interactive terminal.');+ }+ const ref = pageRef(row.source_id, row.slug);+ const state = await readPageTrustState(engine, row.source_id, row.slug);+ if (!state || state.revision !== intent.expected_revision) throw changedSincePreview(ref, intent.mode === 'confirm' ? 'its confirmation' : 'the revert');+ let content: string;+ let tier: TrustTier = 'user_confirmed';+ if (intent.mode === 'revert') {+ const version = Number.isSafeInteger(intent.version_id) ? await readPageVersion(engine, state.pageId, intent.version_id!) : null;+ if (!version) throw opError('not_found', `Version ${String(intent.version_id)} is not in the history of ${ref}.`, `List versions with gbrain history ${row.slug}.`);+ content = versionMarkdown(state.snapshot, version);+ tier = versionTier(version);+ } else content = markdownWithoutMarker(state.snapshot);+ const { preparePageMutation } = await import('../persistence/page-prepare.ts');+ const page = await preparePageMutation(engine, { ...row, operation: intent.mode === 'revert' ? 'revert_version' : 'put_page',+ intent: { ...(intent as unknown as Record<string, unknown>), version_id: intent.version_id } }, config,+ intent.mode === 'revert' ? undefined : { content, expectedRevision: intent.expected_revision });+ const apply = page.apply;+ page.trust = ownerTrust(tier, intent.mode, intent.via);+ page.apply = (tx, preimage) => withTrustPromotion(tx, tier, () => withTrustKeep(tx, FENCE_TABLES, async () => {+ const outcome = await apply(tx, preimage);+ await closeProposal(tx, intent.proposal, { kind: row.principal_kind as Principal['kind'], id: row.principal_id });+ return { ...outcome, trust_action: intent.mode, trust_tier: tier };+ }));+ return page;+}++// ---------------------------------------------------------------------------+// lower_page proposals (CEO-12)+// ---------------------------------------------------------------------------++export interface LowerPageState {+ slug: string;+ prior_tier: TrustTier;+ prior_revision: string | null;+ version_id: number | null;+ /** The latest agent edit (after_state). */+ edited_revision: string | null;+ edited_tier: TrustTier;+}++export function lowerPageState(proposal: TrustProposalRow): LowerPageState {+ const b = proposal.before_state;+ const a = proposal.after_state;+ return {+ slug: String(b.slug ?? ''), prior_tier: storedTrustTier(b.prior_tier),+ prior_revision: typeof b.prior_revision === 'string' ? b.prior_revision : null,+ version_id: b.version_id === null || b.version_id === undefined ? null : Number(b.version_id),+ edited_revision: typeof a.revision === 'string' ? a.revision : null, edited_tier: storedTrustTier(a.tier),+ };+}++async function staleUnlessAt(engine: BrainEngine, proposal: TrustProposalRow, state: LowerPageState): Promise<PageTrustState | TrustDecisionResult> {+ const page = state.slug ? await readPageTrustState(engine, proposal.source_id, state.slug) : null;+ if (!page || page.pageId !== proposal.target_id) return decisionResult(proposal, 'accept', 'stale', { reason: 'page_missing' });+ if (state.edited_revision && page.revision !== state.edited_revision) return decisionResult(proposal, 'accept', 'stale', { reason: 'page_changed_since' });+ return page;+}++/** Revert decision of a lower_page proposal: restore the prior owner version's content and tier. */+export async function revertLoweredPage(engine: BrainEngine, proposal: TrustProposalRow, ctx: TrustDecisionContext): Promise<TrustDecisionResult> {+ const state = lowerPageState(proposal);+ if (state.version_id === null) return decisionResult(proposal, 'reject', 'refused', { reason: 'no_prior_version' });+ const page = await staleUnlessAt(engine, proposal, state);+ if (!('pageId' in page)) return { ...page, decision: 'reject' };+ const result = await revertPageToVersion(engine, {+ sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, versionId: state.version_id,+ confirmation: ctx.confirmation, by: ctx.decidedBy, config: ctx.config,+ proposal: { id: proposal.id, to: 'rejected', after: { ...proposal.after_state, resolution: 'reverted', restored_tier: state.prior_tier } },+ });+ return decisionResult(proposal, 'reject', 'rejected', { reason: 'reverted', detail: { ...result } });+}++registerTrustProposalHandler('lower_page', {+ async accept(engine, proposal, ctx) {+ const state = lowerPageState(proposal);+ const page = await staleUnlessAt(engine, proposal, state);+ if (!('pageId' in page)) return page;+ const result = await confirmPage(engine, {+ sourceId: proposal.source_id, slug: state.slug, expectedRevision: page.revision, confirmation: ctx.confirmation,+ by: ctx.decidedBy, config: ctx.config,+ proposal: { id: proposal.id, to: 'accepted', after: { ...proposal.after_state, resolution: 'confirmed' } },+ });+ return decisionResult(proposal, 'accept', 'accepted', { detail: { ...result } });+ },+ async reject(engine, proposal, ctx) {+ return await transitionTrustProposal(engine, proposal.id, 'pending', 'rejected', { after: { ...proposal.after_state, resolution: 'dismissed' }, decidedBy: ctx.decidedBy })+ ? decisionResult(proposal, 'reject', 'rejected', { reason: 'dismissed' })+ : decisionResult(proposal, 'reject', 'refused', { reason: 'not_pending' });+ },+});diff --git a/src/core/trust/refs.ts b/src/core/trust/refs.tsnew file mode 100644index 0000000000..22c2a4b4ce--- /dev/null+++ b/src/core/trust/refs.ts@@ -0,0 +1,87 @@+/**+ * Typed refs of `gbrain trust` (#5575 DX-7): `f<id>` fact, `t<id>` take,+ * `h<id>` write-gate hold, `tp<id>` trust proposal, `a<id>` allow rule, and+ * `p:<source>/<slug>` page. A bare slug names a page too: it resolves to its+ * source through `--source`, or to the only source holding it; a slug that+ * lives in several sources refuses and lists them (like `quarantine clear`).+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { isValidSourceId } from '../source-id.ts';++export type TrustRef =+ | { kind: 'fact'; id: number }+ | { kind: 'take'; id: number }+ | { kind: 'hold'; id: number }+ | { kind: 'proposal'; id: number }+ | { kind: 'allow_rule'; id: number }+ | { kind: 'page'; sourceId: string | null; slug: string };++const ID = '(\\d{1,18})';+const PATTERNS: Array<[RegExp, TrustRef['kind']]> = [+ [new RegExp(`^tp${ID}$`), 'proposal'],+ [new RegExp(`^f${ID}$`), 'fact'],+ [new RegExp(`^t${ID}$`), 'take'],+ [new RegExp(`^h${ID}$`), 'hold'],+ [new RegExp(`^a${ID}$`), 'allow_rule'],+];++const refHelp = 'Use f<id> (fact), t<id> (take), h<id> (held write), tp<id> (trust proposal), p:<source>/<slug> or a page slug; gbrain trust review lists them.';++/** Parses one ref. A page ref without a source keeps `sourceId: null` for `resolvePageRef`. */+export function parseTrustRef(raw: string): TrustRef {+ const ref = raw.trim();+ for (const [pattern, kind] of PATTERNS) {+ const m = pattern.exec(ref);+ if (m) return { kind, id: Number(m[1]) } as TrustRef;+ }+ if (ref.startsWith('p:')) {+ const body = ref.slice(2);+ const slash = body.indexOf('/');+ const sourceId = slash > 0 ? body.slice(0, slash) : '';+ const slug = slash > 0 ? body.slice(slash + 1) : '';+ if (!isValidSourceId(sourceId) || !slug) {+ throw opError('invalid_params', `Page ref ${JSON.stringify(ref)} must be p:<source>/<slug>.`, `Write the page as p:<source>/<slug>, e.g. p:default/notes/alice-example. ${refHelp}`);+ }+ return { kind: 'page', sourceId, slug };+ }+ if (!ref || ref.startsWith('-') || /\s/.test(ref)) throw opError('invalid_params', `Not a trust ref: ${JSON.stringify(raw)}.`, refHelp);+ return { kind: 'page', sourceId: null, slug: ref };+}++/** The canonical ref text of a page. */+export const pageRef = (sourceId: string, slug: string): string => `p:${sourceId}/${slug}`;++/** The canonical text of any ref (pages need their resolved source). */+export function formatTrustRef(ref: TrustRef): string {+ switch (ref.kind) {+ case 'fact': return `f${ref.id}`;+ case 'take': return `t${ref.id}`;+ case 'hold': return `h${ref.id}`;+ case 'proposal': return `tp${ref.id}`;+ case 'allow_rule': return `a${ref.id}`;+ case 'page': return ref.sourceId ? pageRef(ref.sourceId, ref.slug) : ref.slug;+ }+}++/**+ * Resolves a page ref to its source: an explicit `--source` must agree with a+ * `p:` ref's source; a bare slug takes `--source`, else the one source that+ * holds the slug. Refuses an ambiguous slug instead of picking a source.+ */+export async function resolvePageRef(engine: Pick<BrainEngine, 'executeRaw'>, ref: Extract<TrustRef, { kind: 'page' }>, explicitSource?: string | null): Promise<{ sourceId: string; slug: string }> {+ if (ref.sourceId && explicitSource && ref.sourceId !== explicitSource) {+ throw opError('invalid_params', `${pageRef(ref.sourceId, ref.slug)} names source ${ref.sourceId}, but --source is ${explicitSource}.`,+ 'Drop --source, or pass the page ref with the source you mean.');+ }+ const sourceId = ref.sourceId ?? explicitSource ?? null;+ if (sourceId) return { sourceId, slug: ref.slug };+ const rows = await engine.executeRaw<{ source_id: string }>(+ 'SELECT source_id FROM pages WHERE slug = $1 AND deleted_at IS NULL ORDER BY source_id', [ref.slug]);+ if (rows.length > 1) {+ throw opError('invalid_params', `Slug "${ref.slug}" exists in ${rows.length} sources: ${rows.map(r => r.source_id).join(', ')}.`,+ `Pick one with --source <id>, or write the page as ${pageRef(rows[0]!.source_id, ref.slug)}.`);+ }+ if (rows.length === 0) throw opError('page_not_found', `No page "${ref.slug}" in any source.`, 'Check the slug; gbrain trust review lists pages waiting for you.');+ return { sourceId: rows[0]!.source_id, slug: ref.slug };+}