Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): memory_confirm scope, read floors, confirm helper, attribution trust fields, backfill and doctor (#5575 lane F)

garrytanffef71e55f49
diff --git a/admin/src/lib/scope-constants.ts b/admin/src/lib/scope-constants.ts
index de541115d8..09e2037ba7 100644
--- a/admin/src/lib/scope-constants.ts
+++ b/admin/src/lib/scope-constants.ts
@@ -10,14 +10,17 @@
* or `bun run verify` will reject the change.
*/
-export type Scope = 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent' | 'skill_editor' | 'skill_publisher' | 'skills_member_self';
+export type Scope = 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent' | 'skill_editor' | 'skill_publisher' | 'skills_member_self' | 'memory_confirm';
// MIRROR OF src/core/scope.ts ALLOWED_SCOPES_LIST — keep alphabetically sorted.
// v0.38: 'agent' added for the submit_agent remote-MCP op (sibling to admin,
// NOT implied — existing admin clients must re-register to opt in).
+// memory_confirm is listed for display only: the server refuses to grant it
+// over the admin API (local CLI only, src/core/scope.ts LOCAL_CLI_ONLY_SCOPES).
export const ALLOWED_SCOPES_LIST: ReadonlyArray<Scope> = [
'admin',
'agent',
+ 'memory_confirm',
'read',
'skill_editor',
'skill_publisher',
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index e224ec1878..b4229bcde4 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -2516,6 +2516,14 @@ More: [docs/guides/data-ingestion.md#credential-redaction](../../docs/guides/dat
|---|---|---|---|---|---|---|
| Dream triage did not re-judge a transcript because its last judge verdict was truncated, refused or unparseable and its backoff has not ended. | An unreliable verdict is never cached, so without a backoff the same input was paid for every cycle; it waits 24h, doubling per repeat up to 7 days, and a content or triage-model change re-judges at once. | Leave it (it is retried after the backoff), or ask the user before `gbrain dream retriage --force`, which re-judges every transcript now and pays per file. Run: gbrain dream retriage --dry-run --json | agent | `repeat the read that failed` | 1 | yes |
+### trust_raise_refused
+
+<a id="trust_raise_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A write tried to raise the trust tier of a fact, take, page or timeline entry without the owner's confirmation, so nothing was changed. | Only the owner can make memory more trusted: confirming on an interactive terminal, or through a connection that holds the memory_confirm scope. The database refuses any other raise so a bug or an agent write cannot promote its own content. | Do not retry. Ask the user to confirm the row themselves on the brain host (gbrain trust confirm <ref>), or leave its tier as it is. | user | `repeat the read that failed` | 3 | no |
+
### trusted_local_only
<a id="trusted_local_only"></a>
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 54af2c3937..046a371214 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -384,6 +384,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
{ name: 'pages', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/pages.ts') },
// selfHelp: #6259 router (list, clear, scan); its usage prints before any engine is opened.
{ name: 'quarantine', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/quarantine.ts') },
+ // #5575: memory trust. Observational startup: `trust backfill --dry-run` runs with no migrations and no writes.
+ { name: 'trust', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, json: 'document', skipStartupHooks: true, startup: 'observational', load: () => import('./commands/trust.ts') },
// selfHelp: v0.43 (#2095): watch ships WATCH_HELP (flags + the stdin-turn protocol).
// thin client: v0.43 (#2095): watch streams against a LOCAL engine; thin clients get the
// volunteer_context MCP op instead.
diff --git a/src/cli/commands/trust.ts b/src/cli/commands/trust.ts
new file mode 100644
index 0000000000..a8f9d40e48
--- /dev/null
+++ b/src/cli/commands/trust.ts
@@ -0,0 +1,53 @@
+/**
+ * `gbrain trust`: the memory-trust noun (#5575, DX-7). This module dispatches
+ * `backfill` (A8, DX-5); the other subcommands (review, confirm, release,
+ * drop, revert, explain, allow, disable) join the same record. The record is
+ * startup: 'observational', so `backfill --dry-run` runs on a probe-only
+ * engine with no migrations and no writes; applying completes startup first.
+ */
+import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';
+import type { BrainEngine } from '../../core/engine.ts';
+import { TRUST_TIERS, trustLabel } from '../../core/trust/tier.ts';
+import { runTrustBackfill, type TrustBackfillReport } from '../../core/trust/backfill.ts';
+import type { CliDispatchContext } from '../command-table.ts';
+
+export const TRUST_USAGE = [
+ 'Usage: gbrain trust backfill [--dry-run] [--resume] [--batch-size N] [--json]',
+ ' Classifies rows written before trust tiers (facts, takes, timeline entries, pages) from deterministic signals:',
+ ' connector sources, page source_kind, transcript/extraction/dream provenance, facts and takes source tags, and',
+ ' the journaled request that wrote the row. Rows with no signal stay "unverified origin"; nothing becomes',
+ ' "confirmed by you". --dry-run is read-only (no migrations, no writes) and works before the trust migration;',
+ ' it reports the projected count per table and tier. --resume continues an interrupted run.',
+].join('\n');
+
+function render(report: TrustBackfillReport): string {
+ const lines = [`Trust backfill (${report.mode === 'dry_run' ? 'dry run, nothing written' : 'applied'}; schema: ${report.schema}):`];
+ for (const t of report.tables) {
+ const parts = TRUST_TIERS.filter(tier => t.projected[tier] > 0).map(tier => `${trustLabel(tier)} ${t.projected[tier]}`);
+ lines.push(` ${t.table}: ${t.rows} row(s)${t.updated !== undefined ? `, ${t.updated} classified now` : ''}${parts.length ? ` -> ${parts.join(', ')}` : ''}`);
+ }
+ lines.push(` ${report.at_or_below_agent_written_pct}% of ${report.rows} row(s) at "written by an agent" or below; ${report.unknown_pct}% "unverified origin".`);
+ if (report.resume_command) lines.push(` Resume with: ${report.resume_command}`);
+ return lines.join('\n');
+}
+
+export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
+ const [sub, ...rest] = args;
+ if (!sub || args.includes('--help') || args.includes('-h') || sub !== 'backfill') {
+ console.log(TRUST_USAGE);
+ if (sub && sub !== 'backfill' && !args.includes('--help') && !args.includes('-h')) setCliExitVerdict(2);
+ return;
+ }
+ const dryRun = rest.includes('--dry-run');
+ const sizeAt = rest.indexOf('--batch-size');
+ const batchSize = sizeAt >= 0 ? Number(rest[sizeAt + 1]) : undefined;
+ if (batchSize !== undefined && (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 100_000)) {
+ console.error('--batch-size must be an integer from 1 to 100000.');
+ setCliExitVerdict(2);
+ return;
+ }
+ if (!dryRun) await ctx.completeStartup?.(engine);
+ const report = await runTrustBackfill(engine, { dryRun, resume: rest.includes('--resume'), ...(batchSize ? { batchSize } : {}) });
+ if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(report, null, 2)}\n`);
+ else console.log(render(report));
+}
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 885749fca4..fecdad0efd 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -24,6 +24,8 @@ import { loadConfig, toEngineConfig } from '../core/config.ts';
import { createEngine } from '../core/engine-factory.ts';
import type { BrainEngine } from '../core/engine.ts';
import { assertAllowedScopes } from '../core/scope.ts';
+import { isTrustTier, TRUST_TIERS, type TrustTier } from '../core/trust/tier.ts';
+import { setMinTrust, setTokenMinTrust } from '../core/trust/min-trust.ts';
import { generateToken, isUndefinedColumnError, isUndefinedTableError } from '../core/utils.ts';
import { TOKEN_ID_RE, insertUnifiedToken } from '../core/token-mint.ts';
import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
@@ -71,8 +73,8 @@ async function withConfiguredSql<T>(
}
}
-async function create(name: string, opts: { takesHolders?: string[]; scopes?: string[] } = {}) {
- if (!name) { console.error('Usage: auth create <name> [--takes-holders world,garry] [--scopes read,write]'); process.exit(1); }
+async function create(name: string, opts: { takesHolders?: string[]; scopes?: string[]; minTrust?: TrustTier } = {}) {
+ if (!name) { console.error('Usage: auth create <name> [--takes-holders world,garry] [--scopes read,write] [--min-trust <tier>]'); process.exit(1); }
// #4043 least-privilege: validate scopes at mint time — the verify path
// treats a filtered-empty scopes array as DENY, so a typo must fail loudly
// here, never silently brick (or widen) the token.
@@ -99,14 +101,16 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
// permissions JSONB mirror older binaries read). Scopes land in the
// original-schema scopes TEXT[] column; omitted → NULL → the historical
// grandfathered full-access grant.
- await insertUnifiedToken(engine, {
+ const [row] = await insertUnifiedToken(engine, {
name, tokenHash: hash, ...(opts.scopes !== undefined ? { scopes: opts.scopes } : {}),
grant: { sources: { kind: 'default' }, takesHolders, allowedOperations: null },
});
+ // #5575 (CEO-18): the read floor; the CLI is the only writer of it.
+ if (opts.minTrust) await setTokenMinTrust(engine, row!.id, opts.minTrust);
const scopeLine = opts.scopes !== undefined
? `scopes=${JSON.stringify(opts.scopes)}`
: 'scopes=full access (grandfathered — pass --scopes read,write to narrow)';
- console.log(`Token created for "${name}" (takes_holders=${JSON.stringify(takesHolders)}, ${scopeLine}):\n`);
+ console.log(`Token created for "${name}" (takes_holders=${JSON.stringify(takesHolders)}, ${scopeLine}${opts.minTrust ? `, min_trust=${opts.minTrust}` : ''}):\n`);
console.log(` ${token}\n`);
console.log('Save this token — it will not be shown again.');
console.log(`Revoke with: gbrain auth revoke "${name}" (or gbrain auth revoke --id <id> from auth list)`);
@@ -122,6 +126,26 @@ async function create(name: string, opts: { takesHolders?: string[]; scopes?: st
}
}
+/** `auth set-min-trust <client|token> <tier|none>` (#5575, CEO-18): local-only, the one way to change a read floor. */
+async function setMinTrustCmd(rest: string[]) {
+ const [target, value] = rest.filter(a => !a.startsWith('--'));
+ if (!target || !value || (value !== 'none' && !isTrustTier(value))) {
+ console.error(`Usage: auth set-min-trust <client_id|token id|token name> <${TRUST_TIERS.join('|')}|none>`);
+ process.exit(1);
+ }
+ try {
+ await withConfiguredSql(async (_sql, engine) => {
+ const change = await setMinTrust(engine, target, value === 'none' ? null : value as TrustTier);
+ if (rest.includes('--json')) { console.log(JSON.stringify(change)); return; }
+ console.log(`${change.kind === 'oauth_client' ? 'OAuth client' : 'Token'} "${change.name}" (${change.id}): min_trust ${change.before ?? 'none'} -> ${change.after ?? 'none'}.`);
+ console.log('Applies on its next request: reads never return rows below this tier, whatever min_trust the client asks for.');
+ });
+ } catch (e: any) {
+ console.error('Error:', e.message);
+ process.exit(1);
+ }
+}
+
/** `auth permissions <name> set-takes-holders <list>`: alias of `auth rescope --token <name> --takes-holders <list>`. */
async function permissions(name: string, action: string, value: string | undefined) {
if (!name || action !== 'set-takes-holders' || !value) {
@@ -1157,7 +1181,7 @@ async function clientsCmd(args: string[]) {
* register-client #3990 normalization precedent). Validation against the
* allowed scope set happens in create() so the error path exits cleanly.
*/
-export function parseAuthCreateArgs(rest: string[]): { name: string; takesHolders?: string[]; scopes?: string[]; error?: string } {
+export function parseAuthCreateArgs(rest: string[]): { name: string; takesHolders?: string[]; scopes?: string[]; minTrust?: TrustTier; error?: string } {
const takesIdx = rest.indexOf('--takes-holders');
const takesValue = takesIdx >= 0 ? rest[takesIdx + 1] : undefined;
// Fail closed on a missing/flag-like value: `--scopes` as the last arg
@@ -1177,8 +1201,13 @@ export function parseAuthCreateArgs(rest: string[]): { name: string; takesHolder
const scopes = scopesValue !== undefined
? scopesValue.split(/[\s,]+/).map(s => s.trim()).filter(Boolean)
: undefined;
- const positional = rest.find(a => !a.startsWith('--') && a !== takesValue && a !== scopesValue);
- return { name: positional || '', takesHolders, ...(scopes !== undefined ? { scopes } : {}) };
+ const minIdx = rest.indexOf('--min-trust');
+ const minValue = minIdx >= 0 ? rest[minIdx + 1] : undefined;
+ if (minIdx >= 0 && !isTrustTier(minValue)) {
+ return { name: '', error: `the min-trust flag requires a tier: ${TRUST_TIERS.join(', ')}` };
+ }
+ const positional = rest.find(a => !a.startsWith('--') && a !== takesValue && a !== scopesValue && a !== minValue);
+ return { name: positional || '', takesHolders, ...(scopes !== undefined ? { scopes } : {}), ...(isTrustTier(minValue) ? { minTrust: minValue } : {}) };
}
const AUTH_USAGE = `GBrain Token Management
@@ -1191,7 +1220,7 @@ Admin dashboard login (running HTTP server):
This does not create an MCP bearer token. See docs/mcp/DEPLOY.md.
Usage:
- gbrain auth create <name> [--takes-holders world,garry,brain] [--scopes read,write]
+ gbrain auth create <name> [--takes-holders world,garry,brain] [--scopes read,write] [--min-trust <tier>]
Create a legacy bearer token. v0.28: --takes-holders
sets the per-token allow-list for the takes.holder
field (default: ["world"]). MCP-bound calls to
@@ -1199,6 +1228,12 @@ Usage:
--scopes narrows the token to the listed op scopes
(comma or space separated; omit = full access,
grandfathered).
+ --min-trust sets the token's read floor: reads never
+ return rows below that trust tier (${TRUST_TIERS.join(', ')});
+ memory_confirm in --scopes lets the token confirm
+ memory as you (local CLI only; never via admin API)
+ gbrain auth set-min-trust <client|token> <tier|none> Set or clear the read floor of an OAuth client (id)
+ or legacy token (id or name). Local CLI only.
gbrain auth list List all tokens (id, scopes, usage)
gbrain auth revoke <name> Revoke a legacy token (ALL active rows with that name)
gbrain auth revoke --id <uuid> Revoke exactly one token by id (names are not unique)
@@ -1306,9 +1341,10 @@ export async function runAuth(args: string[]): Promise<void> {
console.error(`Error: ${parsed.error}`);
process.exit(1);
}
- await create(parsed.name, { takesHolders: parsed.takesHolders, scopes: parsed.scopes });
+ await create(parsed.name, { takesHolders: parsed.takesHolders, scopes: parsed.scopes, minTrust: parsed.minTrust });
return;
}
+ case 'set-min-trust': await setMinTrustCmd(rest); return;
case 'list': await list(); return;
case 'revoke': {
if (rest[0] === '--id') { await revokeById(rest[1] || ''); return; }
diff --git a/src/commands/doctor/checks/trust-tiers.ts b/src/commands/doctor/checks/trust-tiers.ts
new file mode 100644
index 0000000000..4be7c54cd2
--- /dev/null
+++ b/src/commands/doctor/checks/trust-tiers.ts
@@ -0,0 +1,52 @@
+/**
+ * trust_tiers (#5575, A8/DX-5): stored trust tier counts per table (facts,
+ * takes, timeline entries, pages) and the share still `unknown`. Warns while
+ * the deterministic backfill has never completed (or was interrupted) and
+ * unknown rows remain, with `fix.next: run` naming `gbrain trust backfill`.
+ * After a complete backfill, rows no signal could classify stay `unknown`
+ * and the check is ok with the percentage. A brain before the trust
+ * migration is ok (tiers arrive with it). Read-only.
+ */
+import type { Check } from '../../doctor.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { readTrustBackfillState, readTrustTierCounts } from '../../../core/trust/backfill.ts';
+import { TRUST_TIERS } from '../../../core/trust/tier.ts';
+import { isUndefinedColumnError } from '../../../core/utils.ts';
+
+
+async function runTrustTiers(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ try {
+ const tables = await readTrustTierCounts(engine);
+ const totals = Object.fromEntries(TRUST_TIERS.map(tier => [tier, tables.reduce((n, t) => n + t.counts[tier], 0)]));
+ const rows = tables.reduce((n, t) => n + t.rows, 0);
+ const unknownPct = rows === 0 ? 0 : Math.round((totals.unknown / rows) * 10_000) / 100;
+ const state = await readTrustBackfillState(engine);
+ const details = { rows, by_tier: totals, unknown_pct: unknownPct, tables: tables.map(t => ({ table: t.table, rows: t.rows, by_tier: t.counts })),
+ backfill: { interrupted: state.interrupted, completed_at: state.completedAt } };
+ const needsBackfill = totals.unknown > 0 && (state.interrupted || !state.completedAt);
+ if (!needsBackfill) {
+ checks.push({ name: 'trust_tiers', status: 'ok', details,
+ message: rows === 0 ? 'No facts, takes, timeline entries or pages yet.'
+ : `${unknownPct}% of ${rows} row(s) have an unverified origin (unknown tier)${state.completedAt ? '; the backfill has classified every row it has a signal for' : ''}.` });
+ return checks;
+ }
+ const argv = state.interrupted ? ['gbrain', 'trust', 'backfill', '--resume'] : ['gbrain', 'trust', 'backfill'];
+ checks.push({ name: 'trust_tiers', status: 'warn', details,
+ message: `${totals.unknown} of ${rows} row(s) (${unknownPct}%) have an unverified origin and the trust backfill has ${state.interrupted ? 'not finished' : 'not run'}. `
+ + `Run ${argv.join(' ')} on the brain host (gbrain trust backfill --dry-run previews it); it classifies rows from deterministic signals only and never marks anything confirmed.`,
+ fix: agentFix(argv, 'Classifies legacy rows from deterministic signals in resumable batches; it never raises a row to confirmed and changes no content.', 'trust_tiers',
+ { preview_argv: ['gbrain', 'trust', 'backfill', '--dry-run', '--json'] }) });
+ } catch (err) {
+ if (isUndefinedColumnError(err, 'trust_tier')) {
+ checks.push({ name: 'trust_tiers', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates trust tiers; they arrive with the migration that adds them.' });
+ } else {
+ checks.push(checkError('trust_tiers', 'read trust tier counts', err));
+ }
+ }
+ return checks;
+}
+
+export const trustTiersEntry: DoctorEntry = { name: 'trust_tiers', emits: ['trust_tiers'], run: runTrustTiers };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 8219954d4e..4fe4504594 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -95,6 +95,7 @@ import { edgeValidityEntry } from './checks/edge-validity.ts';
import { coreMemoryEntry } from './checks/core-memory.ts';
import { plannerStatsEntry } from './checks/planner-stats.ts';
import { revisionBackfillEntry } from './checks/revision-backfill.ts';
+import { trustTiersEntry } from './checks/trust-tiers.ts';
import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';
import { agentContractEntry } from './checks/agent-contract.ts';
import { chatFallbackChainEntry } from './checks/chat-fallback.ts';
@@ -174,6 +175,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
retrievalFeedbackEntry,
transcriptSecretExposureEntry,
revisionBackfillEntry,
+ trustTiersEntry,
coreMemoryEntry,
fenceIntegrityEntry,
searchModeEntry,
diff --git a/src/commands/serve-http-api-keys.ts b/src/commands/serve-http-api-keys.ts
index b11649d540..4906af7c16 100644
--- a/src/commands/serve-http-api-keys.ts
+++ b/src/commands/serve-http-api-keys.ts
@@ -16,7 +16,7 @@ import { cliRenderContext, toAgentError, type Action } from '../core/agent-outpu
import { grantFromTokenRow } from '../core/grants/model.ts';
import { opError } from '../core/ops/contract.ts';
import { sqlQueryForEngine } from '../core/sql-query.ts';
-import { ALLOWED_SCOPES_LIST, isScope } from '../core/scope.ts';
+import { ALLOWED_SCOPES_LIST, isScope, localCliOnlyScopeViolation } from '../core/scope.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { isValidHolder } from '../core/takes-fence.ts';
import { mintLegacyToken, revokeLegacyTokenById, TOKEN_ID_RE } from '../core/token-mint.ts';
@@ -75,6 +75,12 @@ export async function parseApiKeyMintRequest(engine: BrainEngine, body: unknown)
`Resubmit with scopes from: ${valid}.`, 'A misspelled scope is refused at mint time so it never mints a key with a different grant than asked.',
createFix(['--scopes', 'read,write'], 'Mints the same key with the default read,write scopes.'));
}
+ const localOnly = localCliOnlyScopeViolation(scopesParam ?? []);
+ if (localOnly) {
+ throw invalid(localOnly, 'Resubmit without memory_confirm, or ask the user to mint the key on the brain host with gbrain auth create.',
+ 'Confirming memory as the owner is granted only by the local CLI, never by the admin API.',
+ { ...createFix(['--scopes', 'read,write,memory_confirm'], 'Mints the key with memory_confirm from the local CLI on the brain host.'), actor: 'user' });
+ }
const scopes = scopesParam ?? (defaultsApplied.push('scopes'), [...API_KEY_DEFAULT_SCOPES]);
const sourcesParam = listParam(raw.sources);
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 7e71f73a44..46a1909524 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -18,7 +18,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'agent': ['--allow-old-serve', '--brain', '--detach', '--fanout-manifest', '--federated-read', '--flags', '--follow', '--harness', '--help', '--http', '--json', '--max-turns', '--mcp-only', '--model', '--no-follow', '--path', '--port', '--preset', '--reissue', '--scopes', '--show-token', '--since', '--source', '--subagent-def', '--surface', '--timeout-ms', '--token-ttl', '--tools', '--url', '--word', '--yes'],
'anomalies': ['--brain', '--help', '--json', '--lookback-days', '--mcp-only', '--sigma', '--since', '--source'],
'apply-migrations': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--apply', '--apply-rewrites', '--backup-confirmed', '--brain', '--break-lock', '--confirm-quiesced', '--content-root', '--dry-run', '--export-db-only', '--export-source', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--help', '--host-dir', '--http', '--json', '--list', '--locks', '--migrate-only', '--migration', '--mode', '--no-autopilot-install', '--non-interactive', '--prefer-postgres', '--probe', '--require-db', '--skip-verify', '--source', '--uninstall', '--url', '--yes'],
- 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
+ 'auth': ['--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all-new', '--allowed-operations', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cleanup-dead-local-locks', '--client', '--confirm-quiesced', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr-insecure', '--expected-epoch', '--expected-state', '--federated-read', '--fix', '--force', '--grant-types', '--help', '--id', '--if-version', '--json', '--limit', '--manifest', '--max-concurrent', '--migrate-legacy', '--min-trust', '--no-pull', '--operations', '--path', '--probe', '--profile', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--replace', '--request-id', '--reset-default', '--retry-failed', '--scopes', '--self-transfer', '--shared-skills', '--slug-prefixes', '--source', '--source-ids', '--sources', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],
'autopilot': ['--apply', '--batch', '--brain', '--check', '--dimensions', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--ff-only', '--force', '--force-retry', '--from-pages', '--help', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--markdown', '--max-cost', '--max-rss', '--max-runtime', '--max-usd', '--migrate-only', '--model', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed-cache', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--output', '--params', '--path', '--pause', '--phase', '--probe', '--reason', '--refresh-cache', '--remediation-plan', '--repo', '--resume', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--source', '--stale', '--status', '--swap-only', '--target', '--trust', '--uninstall', '--user', '--verify', '--version', '--yes'],
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--accept-pending', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--wait'],
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -108,20 +108,20 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--no-llm', '--only', '--probe', '--remediate', '--remediation-plan', '--scopes', '--skip', '--slug', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait-drain', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait-drain', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--full', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
'salience': ['--brain', '--days', '--help', '--json', '--kind', '--limit', '--mcp-only', '--slug-prefix', '--source'],
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],
- 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
+ 'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--error-unmatch', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--min-trust', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--porcelain', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--untracked-files', '--url', '--usage', '--wait', '--wait-drain', '--yes'],
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
@@ -129,6 +129,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
+ 'trust': ['--batch-size', '--brain', '--dry-run', '--help', '--json', '--resume', '--source'],
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
@@ -216,6 +217,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'takes': ['--brain'],
'think': ['--brain', '--source'],
'transcripts': ['--brain', '--source'],
+ 'trust': ['--brain'],
'waiting': ['--brain', '--source'],
'watch': ['--brain', '--source'],
'whoknows': ['--brain'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index ca91770ab1..44708bd196 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -62,6 +62,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'connector_held_items',
'git_held_files',
'fence_integrity',
+ // #5575: stored trust tier counts and the legacy-row backfill.
+ 'trust_tiers',
'credential_projection_pending',
'derived_visibility',
'extractor_facts_expired',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2d4b3a8598..864d23fd14 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -338,6 +338,7 @@ export const CODES = {
topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },
transcript_secret_exposure: { class: 'unavailable', summary: "Imported conversation pages may still carry a typed credential from before the labeled-credential detector, or the last audit found some; pages are never rewritten automatically.", why: 'Re-ingest skips unchanged sessions, so pages imported before the detector keep any password typed in prose until someone reviews them.', docs: 'docs/guides/data-ingestion.md#credential-redaction', suggestion: 'Run the read-only audit to list affected slugs (never values), then review, edit or (after asking the user) remove each page, and ask the user to rotate any real credential.', fix: { argv: ['gbrain', 'transcripts', 'audit-secrets', '--json'], consent: [], actor: 'agent', why: 'Lists conversation pages that still carry a credential with hit counts per pattern; changes no page.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'transcript_secret_exposure', '--json'] } } },
triage_unreliable_backoff: { class: 'retryable', summary: "Dream triage did not re-judge a transcript because its last judge verdict was truncated, refused or unparseable and its backoff has not ended.", why: 'An unreliable verdict is never cached, so without a backoff the same input was paid for every cycle; it waits 24h, doubling per repeat up to 7 days, and a content or triage-model change re-judges at once.', docs: 'docs/guides/error-codes.md#triage_unreliable_backoff', suggestion: 'Leave it (it is retried after the backoff), or ask the user before `gbrain dream retriage --force`, which re-judges every transcript now and pays per file.', fix: { argv: ['gbrain', 'dream', 'retriage', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the transcripts that still need a verdict without any judge call, read-only.', requires_exclusive: false } },
+ trust_raise_refused: { class: 'consent', exit: 3, actor: 'user', summary: "A write tried to raise the trust tier of a fact, take, page or timeline entry without the owner's confirmation, so nothing was changed.", why: "Only the owner can make memory more trusted: confirming on an interactive terminal, or through a connection that holds the memory_confirm scope. The database refuses any other raise so a bug or an agent write cannot promote its own content.", docs: 'docs/guides/error-codes.md#trust_raise_refused', suggestion: 'Do not retry. Ask the user to confirm the row themselves on the brain host (gbrain trust confirm <ref>), or leave its tier as it is.' },
trusted_local_only: { class: 'host_only', summary: 'The operation runs only from the trusted local CLI on the brain host; no MCP connection can call it.', legacy_error: 'permission_denied', suggestion: 'Ask the user to run the named gbrain command on the brain host.' },
unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },
unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index e32ba42bdd..4c1ac5ae3f 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -54,6 +54,7 @@ import { NO_SOURCES } from './source-id.ts';
export { assertValidSlugPrefixes } from './grants/encoding.ts';
import type { SqlQuery, SqlValue } from './sql-query.ts';
+import { storedMinTrust } from './trust/tier.ts';
export type { SqlQuery, SqlValue };
export interface AgentClientBindings {
@@ -897,6 +898,8 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
// WP4: per-client surface + operator-lock marker (amendment 19).
...(rowSurface !== undefined ? { surface: rowSurface } : {}),
...(rowSurfaceSetBy !== undefined ? { surfaceSetBy: rowSurfaceSetBy } : {}),
+ // #5575 (CEO-18): the client's read floor; current_grant is the whole row, so no projection rung needs it.
+ ...(storedMinTrust(currentGrant.min_trust) ? { minTrust: storedMinTrust(currentGrant.min_trust) } : {}),
} as CoreAuthInfo as SdkAuthInfo;
}
@@ -936,6 +939,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
// floor, the one case that may widen unqualified reads.
...authSourcesFromGrant(grant),
takesHoldersAllowList: grant.takesHolders ?? undefined,
+ ...(storedMinTrust(legacyRows[0].min_trust) ? { minTrust: storedMinTrust(legacyRows[0].min_trust) } : {}),
} as CoreAuthInfo as SdkAuthInfo;
}
diff --git a/src/core/ops/attribution.ts b/src/core/ops/attribution.ts
index 3e1160bf3d..7456a41096 100644
--- a/src/core/ops/attribution.ts
+++ b/src/core/ops/attribution.ts
@@ -17,6 +17,7 @@ import { opError, type Operation, type OperationContext } from './contract.ts';
import type { McpCall } from '../agent-output.ts';
import { opTransport, paramUse, readFix } from './op-fix.ts';
import { readHolders, readPolicyOpts } from './context.ts';
+import { storedTrustTier, type TrustTier, type WriteOrigin } from '../trust/tier.ts';
const DOCS = 'docs/mcp/ADMIN.md#write-attribution';
@@ -28,6 +29,14 @@ interface StoredAttribution {
at?: Date | string | null;
}
+interface StoredTrust { trust_tier: string | null; write_origin: unknown }
+/** jsonb reads back as an object on both engines; a text-shaped value (a driver path that hands jsonb back undecoded) is parsed. */
+function originObject(value: unknown): WriteOrigin | null {
+ if (value === null || value === undefined) return null;
+ if (typeof value === 'string') { try { return JSON.parse(value) as WriteOrigin; } catch { return null; } }
+ return typeof value === 'object' ? value as WriteOrigin : null;
+}
+
const iso = (value: Date | string | null | undefined): string | null =>
value == null ? null : value instanceof Date ? value.toISOString() : new Date(value).toISOString();
@@ -74,12 +83,12 @@ export async function resolveWriteAttributions(engine: BrainEngine, stored: Stor
/** `get_versions` for trusted and admin callers: each snapshot with its origin and archiving writer. */
export async function attributeVersions<V extends PageVersionMetadata>(
engine: BrainEngine, versions: V[],
-): Promise<Array<V & { written_by: WriteAttributionView; archived_by: WriteAttributionView }>> {
+): Promise<Array<V & { written_by: WriteAttributionView; archived_by: WriteAttributionView; trust_tier: TrustTier }>> {
if (!versions.length) return [];
const rows = await engine.executeRaw<{ id: number; w_req: string | null; w_kind: string | null; w_id: string | null;
- a_req: string | null; a_kind: string | null; a_id: string | null }>(
+ a_req: string | null; a_kind: string | null; a_id: string | null; trust_tier: string | null }>(
`SELECT id, write_request_id::text AS w_req, write_principal_kind AS w_kind, write_principal_id AS w_id,
- archived_write_request_id::text AS a_req, archived_principal_kind AS a_kind, archived_principal_id AS a_id
+ archived_write_request_id::text AS a_req, archived_principal_kind AS a_kind, archived_principal_id AS a_id, trust_tier
FROM page_versions WHERE id = ANY($1::int[])`, [versions.map(v => v.id)]);
const byId = new Map(rows.map(r => [Number(r.id), r]));
const stored = versions.flatMap(v => {
@@ -90,7 +99,8 @@ export async function attributeVersions<V extends PageVersionMetadata>(
];
});
const views = await resolveWriteAttributions(engine, stored);
- return versions.map((v, i) => ({ ...v, written_by: views[2 * i], archived_by: views[2 * i + 1] }));
+ // ENG-10: a legacy snapshot (taken before tiers) reads as unknown.
+ return versions.map((v, i) => ({ ...v, written_by: views[2 * i], archived_by: views[2 * i + 1], trust_tier: storedTrustTier(byId.get(Number(v.id))?.trust_tier) }));
}
const SLUG = /^[a-z0-9][a-z0-9/_.-]{0,254}$/i;
@@ -125,7 +135,8 @@ const get_write_attribution: Operation = {
outputRedaction: 'no_stored_text',
description: 'Admin read: who created and who last changed a page, or one of its facts, takes or timeline entries. '
+ 'Each attribution names the request id, operation, principal (kind, id, current name), time and origin '
- + '(request, maintenance or unrecorded). Remote callers stay inside their source grant and see only world facts.',
+ + '(request, maintenance or unrecorded), plus the row\'s trust_tier and write_origin (for derived rows, the inputs that set the tier). '
+ + 'Remote callers stay inside their source grant and see only world facts.',
params: {
slug: { type: 'string', required: true, description: 'Slug of the page to attribute (or the page that holds the fact, take or timeline entry).' },
fact: { type: 'number', description: 'Attribute this fact id (a fact about or fenced on the page) instead of the page.' },
@@ -154,18 +165,19 @@ const get_write_attribution: Operation = {
{ docs: DOCS, ...(SLUG.test(slug) ? { fix: readFix('Searches for pages near the slug you passed.', { argv: ['gbrain', 'search', slug], mcp: { tool: 'search', arguments: { query: slug } } }) } : {}) });
}
const sourceId = page.source_id ?? 'default';
- const [live] = await ctx.engine.executeRaw<{ revision: string; req: string | null; kind: string | null; pid: string | null }>(
- `SELECT knowledge_revision::text AS revision, revision_write_request_id::text AS req, revision_principal_kind AS kind, revision_principal_id AS pid
- FROM pages WHERE id = $1`, [page.id]);
+ const [live] = await ctx.engine.executeRaw<{ revision: string; req: string | null; kind: string | null; pid: string | null } & StoredTrust>(
+ `SELECT knowledge_revision::text AS revision, revision_write_request_id::text AS req, revision_principal_kind AS kind, revision_principal_id AS pid,
+ trust_tier, write_origin FROM pages WHERE id = $1`, [page.id]);
const liveStored: StoredAttribution = { request_id: live?.req ?? null, principal_kind: live?.kind ?? null, principal_id: live?.pid ?? null };
let target: Record<string, unknown> = { kind: 'page', slug: page.slug, source_id: sourceId, page_id: page.id };
let created: StoredAttribution;
let last: StoredAttribution;
+ let trust: StoredTrust = { trust_tier: live?.trust_tier ?? null, write_origin: live?.write_origin ?? null };
const row = rowTarget(ctx, page.id, page.slug, sourceId, { fact, take, timeline });
if (row) {
const [found] = await ctx.engine.executeRaw<{ id: number; w_req: string | null; w_kind: string | null; w_id: string | null; created_at: Date | string | null;
- l_req: string | null; l_kind: string | null; l_id: string | null; last_written_at: Date | string | null }>(row.sql, row.params);
+ l_req: string | null; l_kind: string | null; l_id: string | null; last_written_at: Date | string | null } & StoredTrust>(row.sql, row.params);
if (!found) {
throw opError(row.kind === 'fact' ? 'fact_not_found' : 'not_found', `No ${row.label} is visible on page '${page.slug}'.`,
'List the page\'s rows (fix), then call again with an id from that list.', {
@@ -177,6 +189,7 @@ const get_write_attribution: Operation = {
target = { kind: row.kind, id: Number(found.id), ...(row.kind === 'take' ? { row_num: take } : {}), slug: page.slug, source_id: sourceId, page_id: page.id };
created = { request_id: found.w_req, principal_kind: found.w_kind, principal_id: found.w_id, at: found.created_at };
last = { request_id: found.l_req, principal_kind: found.l_kind, principal_id: found.l_id, at: found.last_written_at };
+ trust = { trust_tier: found.trust_tier, write_origin: found.write_origin };
} else {
const [oldest] = await ctx.engine.executeRaw<{ req: string | null; kind: string | null; pid: string | null }>(
`SELECT write_request_id::text AS req, write_principal_kind AS kind, write_principal_id AS pid
@@ -187,10 +200,12 @@ const get_write_attribution: Operation = {
const [createdView, lastView, liveView] = await resolveWriteAttributions(ctx.engine, [created, last, liveStored]);
const versions = p.versions === true
? (await attributeVersions(ctx.engine, (await ctx.engine.getVersions(page.slug, policy)).filter(v => Number(v.page_id) === Number(page.id))))
- .map(v => ({ id: v.id, knowledge_revision: v.knowledge_revision ?? null, snapshot_at: iso(v.snapshot_at), written_by: v.written_by, archived_by: v.archived_by }))
+ .map(v => ({ id: v.id, knowledge_revision: v.knowledge_revision ?? null, snapshot_at: iso(v.snapshot_at), trust_tier: v.trust_tier, written_by: v.written_by, archived_by: v.archived_by }))
: undefined;
return {
target, created: createdView, last: lastView,
+ // CEO-1: the stored tier and its origin record (for a derived row, a bounded sample of the inputs that set it).
+ trust_tier: storedTrustTier(trust.trust_tier), write_origin: originObject(trust.write_origin),
live_revision: { knowledge_revision: live?.revision ?? null, written_by: liveView },
...(versions ? { versions } : {}),
};
@@ -200,7 +215,8 @@ const get_write_attribution: Operation = {
function rowTarget(ctx: OperationContext, pageId: number, slug: string, sourceId: string,
ids: { fact?: number; take?: number; timeline?: number }): RowTarget | undefined {
const cols = `write_request_id::text AS w_req, write_principal_kind AS w_kind, write_principal_id AS w_id, created_at,
- last_write_request_id::text AS l_req, last_write_principal_kind AS l_kind, last_write_principal_id AS l_id, last_written_at`;
+ last_write_request_id::text AS l_req, last_write_principal_kind AS l_kind, last_write_principal_id AS l_id, last_written_at,
+ trust_tier, write_origin`;
if (ids.fact !== undefined) {
return { kind: 'fact', label: `fact #${ids.fact}`, list: { tool: 'recall', arguments: { entity: slug } },
sql: `SELECT id, ${cols} FROM facts WHERE id = $1 AND source_id = $2 AND (entity_slug = $3 OR source_markdown_slug = $3)
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 2ae6b49ec5..2b1fe8ed3c 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -18,6 +18,7 @@ import { publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from '../p
import type { Action, Notice } from '../agent-output.ts';
import type { RegistryCode } from '../error-registry.ts';
import type { WriteAuthority } from '../persistence/model.ts';
+import type { TrustTier } from '../trust/tier.ts';
import type { StdioSurfaceState } from '../../mcp/surface.ts';
/** Agent contract v1: the wire renderer for `fix`/`notices` in toJSON(), registered by agent-output.ts on load. */
@@ -372,6 +373,14 @@ export interface AuthInfo {
* projection degraded, or the brain predates migration v127.
*/
surface?: string;
+ /**
+ * #5575 (CEO-18): the token's read floor (`oauth_clients.min_trust` /
+ * `access_tokens.min_trust`), set only by the local CLI (`gbrain auth create
+ * --min-trust`, `gbrain auth set-min-trust`). Every read op applies
+ * max(this floor, the caller's `min_trust` param), so a client can raise it
+ * but never lower it. Undefined = no floor (or a brain before the column).
+ */
+ minTrust?: TrustTier;
/** Current transport ceiling applied to this authenticated request. */
effectiveSurface?: 'verbs' | 'starter' | 'full';
/**
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 88bdbdaf13..e6d79fa487 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -39,6 +39,8 @@ export interface PublicationFailure { code: string; message: string; detail?: Pu
const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;
const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;
const GUARD_PREFIX = 'writer_coordinator_required:';
+/** trust/schema.ts: the tier trigger's refusal of a raise without owner confirmation. */
+const TRUST_PREFIX = 'trust_raise_refused:';
const RELATIONSHIP_TEXT: Record<string, string> = {
different_source: 'a row in a source this publication does not own',
missing_source: 'a row whose source could not be resolved',
@@ -77,6 +79,11 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {
return { code: 'writer_coordinator_required', detail, message:
`The managed-writer database guard refused ${detail.op ? `an ${detail.op}` : 'a write'}${table ? ` on ${table}` : ''}: ${what}. Nothing was committed.` };
}
+ if (message.startsWith(TRUST_PREFIX) || constraint === 'trust_tier_guard') {
+ return { code: 'trust_raise_refused', detail: { origin: 'database_trigger', sqlstate, raiser: raiser ?? 'gbrain_stamp_trust_tier', ...(table ? { table } : {}),
+ ...guardDetail(e.detail) },
+ message: `The trust-tier guard refused a write${table ? ` on ${table}` : ''}: raising a tier needs the owner's confirmation. Nothing was committed.` };
+ }
return { code: 'storage_error', message: `Publication failed (P0001${raiser ? ` in ${raiser}` : ''}). Inspect owner diagnostics.`,
detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };
}
diff --git a/src/core/scope.ts b/src/core/scope.ts
index 9a43712752..de5bd5ee56 100644
--- a/src/core/scope.ts
+++ b/src/core/scope.ts
@@ -22,7 +22,7 @@
* vs user-account-mgmt — neither implies the other).
*/
-export type Scope = 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent' | 'skill_editor' | 'skill_publisher' | 'skills_member_self';
+export type Scope = 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent' | 'skill_editor' | 'skill_publisher' | 'skills_member_self' | 'memory_confirm';
export const ALLOWED_SCOPES: ReadonlySet<Scope> = new Set<Scope>([
'read',
@@ -34,6 +34,7 @@ export const ALLOWED_SCOPES: ReadonlySet<Scope> = new Set<Scope>([
'skill_editor',
'skill_publisher',
'skills_member_self',
+ 'memory_confirm',
]);
/**
@@ -43,6 +44,7 @@ export const ALLOWED_SCOPES: ReadonlySet<Scope> = new Set<Scope>([
export const ALLOWED_SCOPES_LIST: ReadonlyArray<Scope> = Object.freeze([
'admin',
'agent',
+ 'memory_confirm',
'read',
'skill_editor',
'skill_publisher',
@@ -69,6 +71,24 @@ export const DCR_REGISTRABLE_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['read'
*/
const DCR_MACHINE_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['read']);
+/**
+ * #5575 (CEO-6): scopes only the trusted local CLI may grant
+ * (`gbrain auth create --scopes ...,memory_confirm`, `auth register-client`,
+ * `auth rescope`). `memory_confirm` lets a connection confirm memory as the
+ * owner (raise a trust tier), so the admin HTTP API, the admin SPA, `gbrain mcp
+ * admin`, API-key minting and dynamic registration all refuse it, and no
+ * grant profile or grandfathered token carries it.
+ */
+export const LOCAL_CLI_ONLY_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['memory_confirm']);
+
+/** null when no local-CLI-only scope is requested; otherwise the refusal message naming the local command. */
+export function localCliOnlyScopeViolation(requested: readonly string[]): string | null {
+ const over = [...new Set(requested.filter(s => LOCAL_CLI_ONLY_SCOPES.has(s as Scope)))];
+ if (over.length === 0) return null;
+ return `Scope "${over.join(' ')}" lets a connection confirm memory as the owner, so only the local CLI on the brain host can grant it: `
+ + '`gbrain auth create <name> --scopes read,write,memory_confirm` or `gbrain auth rescope --client <client_id> --scopes ...`.';
+}
+
/**
* null when the requested DCR scopes fit under the ceiling; otherwise the
* `invalid_client_metadata` message naming the offending scopes + remedy.
@@ -79,6 +99,8 @@ export function dcrScopeViolation(requested: readonly string[], grantTypes: read
if (requested.includes('agent')) {
return 'agent scope requires an operator-approved grant with explicit delegation bindings; dynamic registration cannot grant it';
}
+ const localOnly = localCliOnlyScopeViolation(requested);
+ if (localOnly) return localOnly;
const machine = grantTypes.includes('client_credentials');
const ceiling = machine ? DCR_MACHINE_SCOPES : DCR_REGISTRABLE_SCOPES;
const over = [...new Set(requested.filter((s) => isScope(s) && !ceiling.has(s)))];
@@ -109,8 +131,8 @@ export function dcrScopeViolation(requested: readonly string[], grantTypes: read
* `dcrScopeViolation` — authorization_code is the DCR default and may hold
* both, so advertising `read` alone would under-describe it.
* - DCR disabled: every scope except operator-only `agent`, which also needs
- * delegation bindings no OAuth request can carry. Operator-registered
- * clients see the full set they may hold.
+ * delegation bindings no OAuth request can carry, and the local-CLI-only
+ * `memory_confirm`. Operator-registered clients see the full set they may hold.
*
* Narrowed discovery never narrows an operator-registered client: one that
* omits `scope` at /authorize or /token receives its full registered set
@@ -120,7 +142,7 @@ export function dcrScopeViolation(requested: readonly string[], grantTypes: read
export function scopesSupportedForDiscovery(opts: { enableDcr: boolean }): Scope[] {
return opts.enableDcr
? ALLOWED_SCOPES_LIST.filter((s) => DCR_REGISTRABLE_SCOPES.has(s))
- : ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent');
+ : ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent' && !LOCAL_CLI_ONLY_SCOPES.has(s));
}
/**
@@ -132,6 +154,10 @@ export function scopesSupportedForDiscovery(opts: { enableDcr: boolean }): Scope
* token still needs to be re-registered with explicit bindings to submit
* subagent jobs. This prevents existing admin clients from silently gaining
* agent-dispatch capability on upgrade.
+ *
+ * #5575: `memory_confirm` (confirm memory as the owner) is a sibling too:
+ * admin never implies it, so grandfathered full-access tokens and admin
+ * clients cannot raise a trust tier.
*/
const IMPLIES: Record<Scope, ReadonlySet<Scope>> = {
admin: new Set(['admin', 'sources_admin', 'users_admin', 'write', 'read']),
@@ -143,6 +169,7 @@ const IMPLIES: Record<Scope, ReadonlySet<Scope>> = {
skill_editor: new Set(['skill_editor']),
skill_publisher: new Set(['skill_publisher']),
skills_member_self: new Set(['skills_member_self']),
+ memory_confirm: new Set(['memory_confirm']),
};
/**
@@ -304,6 +331,9 @@ export function normalizeScopesInput(raw: unknown): string {
// Validate against ALLOWED_SCOPES (throws InvalidScopeError on miss).
assertAllowedScopes(deduped);
+ // Every caller of this normalizer is an admin HTTP surface (or its remote CLI), never the local CLI.
+ const localOnly = localCliOnlyScopeViolation(deduped);
+ if (localOnly) throw new Error(localOnly);
return deduped.join(' ');
}
diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.ts
new file mode 100644
index 0000000000..14465e2d5c
--- /dev/null
+++ b/src/core/trust/backfill.ts
@@ -0,0 +1,319 @@
+/**
+ * `gbrain trust backfill` (#5575: A8, CEO-17, DX-5): classifies rows written
+ * before trust tiers existed, from deterministic signals only. Rows with no
+ * signal stay `unknown`; content_chunks are never touched (chunk tier is its
+ * page's at read time); page_versions keep `unknown` (ENG-10).
+ *
+ * Signals, combined as the minimum (least trusted) of every one that applies:
+ * - the row's source is a connector source (`sources.config.kind` google or
+ * github): external_untrusted (connector free text is attacker-controllable;
+ * legacy rows cannot tell structured fields apart);
+ * - pages.source_kind: webhook / file-watcher / inbox-folder / cron-scheduler
+ * (ingestion captures) external_untrusted; mcp:* / put_page / capture-cli
+ * agent_written;
+ * - frontmatter transcript_import, provenance: auto-extracted, dream_generated:
+ * agent_written (model- or session-derived);
+ * - facts.source lane tags (the facts backstop, conversation-facts and
+ * extract_facts lanes) and takes.source take_proposals#: agent_written;
+ * - post-v193 rows through write_request_id -> persistence_requests (CEO-17):
+ * connector jobs external_untrusted, remote callers agent_written, managed
+ * sync/import/reconcile/file-repair of an owner source operator_curated,
+ * plain local put_page/capture/remember/takes/timeline writes and model
+ * maintenance agent_written, anything else no signal;
+ * - facts on a page's fence, takes and timeline rows also take their page's
+ * tier when the page has one (taint from the page they live on).
+ *
+ * The highest tier the backfill can assign is operator_curated; it never
+ * assigns user_confirmed (CEO-10, enforced again by the tier trigger).
+ *
+ * `dryRun` is strictly read-only: SELECTs inside a READ ONLY transaction, no
+ * checkpoint, no config. It works on a brain whose schema predates the trust
+ * columns (or attribution, or provenance columns) by classifying from the
+ * columns that exist, and reports which signal families were available.
+ * Applying runs in bounded batches (resumable cursor in op_checkpoints, the
+ * resumePageRevisionBackfill precedent) under the backfill setting, inside
+ * withCoordinatedWrite for each batch's sources on a managed brain.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { FACTS_BACKSTOP_SOURCES } from '../facts/capture-sources.ts';
+import { opError } from '../ops/contract.ts';
+import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
+import { withCoordinatedWrite, withTrustBackfill } from '../persistence/context.ts';
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import type { TrustTable } from './schema.ts';
+import { TRUST_TIER_RANK, TRUST_TIERS, isTrustTier, trustRankSql, trustTierFromRankSql, type TrustTier } from './tier.ts';
+
+export const TRUST_BACKFILL_COMMAND = 'gbrain trust backfill --resume';
+/** Config key: when the last complete apply finished (doctor `trust_tiers` stops recommending the backfill). */
+export const TRUST_BACKFILL_COMPLETED_KEY = 'trust.backfill_completed_at';
+const CHECKPOINT_OP = 'trust-backfill';
+const CHECKPOINT_KEY = 'v1';
+const DEFAULT_BATCH = 2000;
+/** Pages first: facts, takes and timeline rows take their page's classified tier. */
+const BACKFILL_ORDER: readonly TrustTable[] = ['pages', 'facts', 'takes', 'timeline_entries'];
+
+export interface TrustBackfillOptions {
+ dryRun?: boolean;
+ resume?: boolean;
+ batchSize?: number;
+ log?: (line: string) => void;
+}
+export type TierCounts = Record<TrustTier, number>;
+export interface TrustBackfillTableReport {
+ table: TrustTable;
+ rows: number;
+ /** Stored tiers now (absent on a brain without the trust columns). */
+ current?: TierCounts;
+ /** Tiers after a backfill: stored non-unknown tiers kept, unknown rows classified. */
+ projected: TierCounts;
+ /** Apply only: rows this run moved off `unknown`. */
+ updated?: number;
+}
+export interface TrustBackfillReport {
+ mode: 'dry_run' | 'apply';
+ schema: 'trust_columns' | 'pre_trust';
+ status: 'complete' | 'partial';
+ tables: TrustBackfillTableReport[];
+ rows: number;
+ projected: TierCounts;
+ /** Rows at agent_written or below (agent_written, unknown, external_untrusted): the CEO-25 review-burden gauge. */
+ at_or_below_agent_written: number;
+ at_or_below_agent_written_pct: number;
+ unknown_pct: number;
+ /** Signal families the schema could read. */
+ signals: string[];
+ resume_command?: string;
+}
+
+const zero = (): TierCounts => Object.fromEntries(TRUST_TIERS.map(tier => [tier, 0])) as TierCounts;
+const pct = (n: number, d: number) => (d === 0 ? 0 : Math.round((n / d) * 10_000) / 100);
+const quoted = (values: readonly string[]) => values.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
+const rank = (tier: TrustTier) => TRUST_TIER_RANK[tier];
+
+type Columns = { has(table: string, column: string): boolean; table(table: string): boolean };
+
+async function readColumns(engine: BrainEngine): Promise<Columns> {
+ const rows = await engine.executeRaw<{ table_name: string; column_name: string }>(
+ `SELECT table_name, column_name FROM information_schema.columns
+ WHERE table_schema = current_schema() AND table_name = ANY($1::text[])`,
+ [['pages', 'facts', 'takes', 'timeline_entries', 'sources', 'persistence_requests']]);
+ const set = new Set(rows.map(r => `${r.table_name}.${r.column_name}`));
+ const tables = new Set(rows.map(r => r.table_name));
+ return { has: (table, column) => set.has(`${table}.${column}`), table: name => tables.has(name) };
+}
+
+/** Builds the rank expressions for one schema shape. Every term yields a rank or NULL (no signal). */
+function classifier(cols: Columns) {
+ const signals = new Set<string>();
+ const connector = (sourceAlias: string) => {
+ if (!cols.has('sources', 'config')) return null;
+ signals.add('connector_source');
+ return `CASE WHEN ${sourceAlias}.config->>'kind' IN (${quoted(CONNECTOR_SOURCE_KINDS)}) THEN ${rank('external_untrusted')} END`;
+ };
+ const requests = cols.has('persistence_requests', 'operation') && cols.has('persistence_requests', 'intent') && cols.has('persistence_requests', 'authority');
+ const request = (r: string) => {
+ if (!requests) return null;
+ signals.add('write_request');
+ const kind = `${r}.intent->>'kind'`;
+ return `CASE WHEN ${r}.id IS NULL THEN NULL
+ WHEN ${kind} LIKE 'connector\\_v2\\_%' OR ${kind} LIKE 'managed\\_connector\\_%' THEN ${rank('external_untrusted')}
+ WHEN ${r}.authority->>'remote' = 'true' THEN ${rank('agent_written')}
+ WHEN ${kind} LIKE 'managed\\_sync\\_%' OR ${kind} IN ('managed_file_import','canonical_reconcile','managed_file_repair') THEN ${rank('operator_curated')}
+ WHEN ${kind} LIKE 'managed\\_facts\\_%' OR ${kind} LIKE 'managed\\_atom\\_%' OR ${kind} LIKE 'managed\\_maintenance\\_%' THEN ${rank('agent_written')}
+ WHEN ${r}.intent IS NOT NULL AND ${kind} IS NULL AND ${r}.operation IN ('put_page','capture','remember','edit_page','delete_page','restore_page',
+ 'revert_version','add_tag','remove_tag','add_timeline_entry','takes_add','takes_update','takes_supersede','takes_resolve','takes_remove') THEN ${rank('agent_written')}
+ END`;
+ };
+ const requestJoin = (table: string, column: string, alias: string, row: string) =>
+ requests && cols.has(table, column) ? `LEFT JOIN persistence_requests ${alias} ON ${alias}.id = ${row}.${column}` : '';
+ const pageTerms = (p: string, s: string, r: string): string[] => {
+ const terms: string[] = [];
+ const c = connector(s); if (c) terms.push(c);
+ if (cols.has('pages', 'source_kind')) {
+ signals.add('pages_source_kind');
+ terms.push(`CASE WHEN ${p}.source_kind IN ('webhook','file-watcher','inbox-folder','cron-scheduler') THEN ${rank('external_untrusted')}
+ WHEN ${p}.source_kind LIKE 'mcp:%' OR ${p}.source_kind IN ('put_page','capture-cli') THEN ${rank('agent_written')} END`);
+ }
+ if (cols.has('pages', 'frontmatter')) {
+ signals.add('frontmatter_provenance');
+ terms.push(`CASE WHEN ${p}.frontmatter ? 'transcript_import' OR ${p}.frontmatter->>'provenance' = 'auto-extracted'
+ OR ${p}.frontmatter->>'dream_generated' = 'true' THEN ${rank('agent_written')} END`);
+ }
+ if (cols.has('pages', 'revision_write_request_id')) { const q = request(r); if (q) terms.push(q); }
+ return terms;
+ };
+ const least = (terms: string[]) => (terms.length ? `LEAST(${terms.join(', ')})` : 'NULL::int');
+ const hasTrust = cols.has('pages', 'trust_tier');
+ /** The tier a row's page contributes: its stored tier when classified, else the page's own signals. */
+ const pageTaint = (p: string, s: string, r: string) => {
+ const rule = least(pageTerms(p, s, r));
+ return hasTrust ? `CASE WHEN ${p}.id IS NULL THEN NULL WHEN ${p}.trust_tier <> 'unknown' THEN ${trustRankSql(`${p}.trust_tier`)} ELSE ${rule} END` : rule;
+ };
+ const pageJoins = (p: string, s: string, r: string, on: string) =>
+ `LEFT JOIN pages ${p} ON ${on} ${cols.has('sources', 'config') ? `LEFT JOIN sources ${s} ON ${s}.id = ${p}.source_id` : ''} ${requestJoin('pages', 'revision_write_request_id', r, p)}`;
+
+ /** FROM clause and rule-rank expression per table; `x` is the row alias, `src` the expression naming its source. */
+ const forTable = (table: TrustTable): { from: string; rule: string; src: string } => {
+ if (table === 'pages') {
+ return { from: `pages x ${cols.has('sources', 'config') ? 'LEFT JOIN sources s ON s.id = x.source_id' : ''} ${requestJoin('pages', 'revision_write_request_id', 'r', 'x')}`,
+ rule: least(pageTerms('x', 's', 'r')), src: 'x.source_id' };
+ }
+ if (table === 'facts') {
+ const terms: string[] = [];
+ const c = connector('s'); if (c) terms.push(c);
+ if (cols.has('facts', 'source')) {
+ signals.add('facts_source_lane');
+ terms.push(`CASE WHEN x.source IN (${quoted(FACTS_BACKSTOP_SOURCES)}) OR x.source LIKE 'cli:extract-conversation-facts%' THEN ${rank('agent_written')} END`);
+ }
+ if (cols.has('facts', 'write_request_id')) { const q = request('r'); if (q) terms.push(q); }
+ const fenced = cols.has('facts', 'source_markdown_slug');
+ if (fenced) terms.push(pageTaint('pg', 'ps', 'pr'));
+ return {
+ from: `facts x ${cols.has('sources', 'config') ? 'LEFT JOIN sources s ON s.id = x.source_id' : ''} ${requestJoin('facts', 'write_request_id', 'r', 'x')}
+ ${fenced ? pageJoins('pg', 'ps', 'pr', 'pg.source_id = x.source_id AND pg.slug = x.source_markdown_slug') : ''}`,
+ rule: least(terms), src: 'x.source_id',
+ };
+ }
+ const terms: string[] = [pageTaint('pg', 'ps', 'pr')];
+ if (cols.has('sources', 'config')) terms.push(`CASE WHEN ps.config->>'kind' IN (${quoted(CONNECTOR_SOURCE_KINDS)}) THEN ${rank('external_untrusted')} END`);
+ if (table === 'takes' && cols.has('takes', 'source')) {
+ signals.add('takes_source');
+ terms.push(`CASE WHEN x.source LIKE 'take\\_proposals#%' THEN ${rank('agent_written')} END`);
+ }
+ if (cols.has(table, 'write_request_id')) { const q = request('r'); if (q) terms.push(q); }
+ return { from: `${table} x ${pageJoins('pg', 'ps', 'pr', 'pg.id = x.page_id')} ${requestJoin(table, 'write_request_id', 'r', 'x')}`,
+ rule: least(terms), src: 'pg.source_id' };
+ };
+ return { forTable, signals, hasTrust };
+}
+
+async function readCursor(engine: BrainEngine): Promise<Partial<Record<TrustTable, number>>> {
+ const [row] = await engine.executeRaw<{ keys: unknown }>(
+ 'SELECT completed_keys AS keys FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [CHECKPOINT_OP, CHECKPOINT_KEY]);
+ const keys = typeof row?.keys === 'string' ? JSON.parse(row.keys) : row?.keys;
+ return Array.isArray(keys) && keys[0] && typeof keys[0] === 'object' ? keys[0] as Partial<Record<TrustTable, number>> : {};
+}
+async function saveCursor(engine: BrainEngine, cursor: Partial<Record<TrustTable, number>>): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op, fingerprint, completed_keys) VALUES ($1, $2, $3::text::jsonb)
+ ON CONFLICT (op, fingerprint) DO UPDATE SET completed_keys = EXCLUDED.completed_keys, updated_at = now()`,
+ [CHECKPOINT_OP, CHECKPOINT_KEY, JSON.stringify([cursor])]);
+}
+
+function summarize(mode: TrustBackfillReport['mode'], schema: TrustBackfillReport['schema'], tables: TrustBackfillTableReport[],
+ signals: Set<string>, status: TrustBackfillReport['status']): TrustBackfillReport {
+ const projected = zero();
+ for (const t of tables) for (const tier of TRUST_TIERS) projected[tier] += t.projected[tier];
+ const rows = tables.reduce((n, t) => n + t.rows, 0);
+ const low = projected.agent_written + projected.unknown + projected.external_untrusted;
+ return {
+ mode, schema, status, tables, rows, projected,
+ at_or_below_agent_written: low, at_or_below_agent_written_pct: pct(low, rows), unknown_pct: pct(projected.unknown, rows),
+ signals: [...signals].sort(),
+ ...(status === 'partial' ? { resume_command: TRUST_BACKFILL_COMMAND } : {}),
+ };
+}
+
+/** The read-only projection: counts by table x tier, in keyset batches inside one READ ONLY transaction. */
+async function dryRun(engine: BrainEngine, batch: number): Promise<TrustBackfillReport> {
+ return engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION READ ONLY');
+ const cols = await readColumns(tx);
+ const { forTable, signals, hasTrust } = classifier(cols);
+ const tables: TrustBackfillTableReport[] = [];
+ for (const table of BACKFILL_ORDER) {
+ if (!cols.table(table)) continue;
+ const { from, rule } = forTable(table);
+ const ruleTier = trustTierFromRankSql(rule);
+ const report: TrustBackfillTableReport = { table, rows: 0, ...(hasTrust ? { current: zero() } : {}), projected: zero() };
+ for (let after = 0; ;) {
+ const rows = await tx.executeRaw<{ last: number | string; n: number | string; current: string | null; tier: string }>(
+ `SELECT max(id) AS last, count(*) AS n, current, tier FROM (
+ SELECT x.id, ${hasTrust ? 'x.trust_tier' : 'NULL::text'} AS current,
+ ${hasTrust ? `CASE WHEN x.trust_tier <> 'unknown' THEN x.trust_tier ELSE ${ruleTier} END` : ruleTier} AS tier
+ FROM ${from} WHERE x.id > $1 ORDER BY x.id LIMIT $2) b
+ GROUP BY current, tier`, [after, batch]);
+ if (rows.length === 0) break;
+ for (const row of rows) {
+ const n = Number(row.n);
+ report.rows += n;
+ report.projected[isTrustTier(row.tier) ? row.tier : 'unknown'] += n;
+ if (report.current && isTrustTier(row.current)) report.current[row.current] += n;
+ after = Math.max(after, Number(row.last));
+ }
+ }
+ tables.push(report);
+ }
+ return summarize('dry_run', hasTrust ? 'trust_columns' : 'pre_trust', tables, signals, 'complete');
+ });
+}
+
+export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillOptions = {}): Promise<TrustBackfillReport> {
+ const batch = opts.batchSize ?? DEFAULT_BATCH;
+ if (opts.dryRun) return dryRun(engine, batch);
+ const log = opts.log ?? ((line: string) => process.stderr.write(`${line}\n`));
+ const cols = await readColumns(engine);
+ if (!cols.has('pages', 'trust_tier')) {
+ throw opError('migrations_pending', 'This brain has no trust_tier columns yet, so there is nothing to backfill.',
+ 'Apply the pending schema migrations on the brain host, then run the backfill. gbrain trust backfill --dry-run previews it without them.', {
+ fix: { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent', requires_exclusive: true,
+ why: 'Applies the pending schema migrations, including the trust tier columns.', verify: { argv: ['gbrain', 'trust', 'backfill', '--dry-run', '--json'] } },
+ });
+ }
+ const { forTable, signals } = classifier(cols);
+ const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton = 1');
+ const attribution = await maintenanceAttribution(engine);
+ const cursor = opts.resume ? await readCursor(engine) : {};
+ const tables: TrustBackfillTableReport[] = [];
+ for (const table of BACKFILL_ORDER) {
+ const { from, rule, src } = forTable(table);
+ let updated = 0;
+ for (let after = cursor[table] ?? 0; ;) {
+ const ids = (await engine.executeRaw<{ id: number | string }>(
+ `SELECT id FROM ${table} WHERE id > $1 AND trust_tier = 'unknown' ORDER BY id LIMIT $2`, [after, batch])).map(r => Number(r.id));
+ if (ids.length === 0) break;
+ const sources = (await engine.executeRaw<{ source_id: string | null }>(
+ `SELECT DISTINCT ${src} AS source_id FROM ${from} WHERE x.id = ANY($1::bigint[])`, [ids])).map(r => r.source_id).filter((s): s is string => !!s);
+ const apply = (tx: BrainEngine) => withTrustBackfill(tx, async () => (await tx.executeRaw<{ id: number }>(
+ `WITH b AS (SELECT x.id, ${trustTierFromRankSql(rule)} AS tier FROM ${from} WHERE x.id = ANY($1::bigint[]))
+ UPDATE ${table} t SET trust_tier = b.tier, write_origin = COALESCE(t.write_origin, '{"channel":"trust_backfill"}'::jsonb)
+ FROM b WHERE t.id = b.id AND t.trust_tier = 'unknown' AND b.tier <> 'unknown' RETURNING t.id`, [ids])).length);
+ updated += await engine.transaction(tx => brain?.enabled && sources.length
+ ? withCoordinatedWrite(tx, sources, () => apply(tx), attribution)
+ : apply(tx));
+ after = ids[ids.length - 1]!;
+ cursor[table] = after;
+ await saveCursor(engine, cursor);
+ log(`[trust backfill] ${table}: ${updated} row(s) classified, through id ${after}`);
+ }
+ tables.push({ table, rows: 0, projected: zero(), updated });
+ }
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [CHECKPOINT_OP, CHECKPOINT_KEY]);
+ await engine.setConfig(TRUST_BACKFILL_COMPLETED_KEY, new Date().toISOString());
+ const counts = await readTrustTierCounts(engine);
+ for (const t of tables) {
+ const c = counts.find(row => row.table === t.table);
+ if (c) { t.rows = c.rows; t.projected = c.counts; t.current = c.counts; }
+ }
+ return summarize('apply', 'trust_columns', tables, signals, 'complete');
+}
+
+/** Doctor: the stored backfill state (an interrupted run's cursor, and when a complete run finished). */
+export async function readTrustBackfillState(engine: BrainEngine): Promise<{ interrupted: boolean; completedAt: string | null }> {
+ const [row] = await engine.executeRaw<{ n: number | string }>(
+ 'SELECT count(*) AS n FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [CHECKPOINT_OP, CHECKPOINT_KEY]);
+ return { interrupted: Number(row?.n ?? 0) > 0, completedAt: await engine.getConfig(TRUST_BACKFILL_COMPLETED_KEY) };
+}
+
+export interface TrustTierTableCounts { table: TrustTable; rows: number; counts: TierCounts }
+
+/** Stored tier counts per table (doctor `trust_tiers`). Throws on a brain without the columns. */
+export async function readTrustTierCounts(engine: BrainEngine): Promise<TrustTierTableCounts[]> {
+ const out: TrustTierTableCounts[] = [];
+ for (const table of BACKFILL_ORDER) {
+ const rows = await engine.executeRaw<{ tier: string; n: number | string }>(`SELECT trust_tier AS tier, count(*) AS n FROM ${table} GROUP BY trust_tier`);
+ const counts = zero();
+ for (const row of rows) counts[isTrustTier(row.tier) ? row.tier : 'unknown'] += Number(row.n);
+ out.push({ table, rows: rows.reduce((n, r) => n + Number(r.n), 0), counts });
+ }
+ return out;
+}
diff --git a/src/core/trust/confirm.ts b/src/core/trust/confirm.ts
new file mode 100644
index 0000000000..8107ec4e78
--- /dev/null
+++ b/src/core/trust/confirm.ts
@@ -0,0 +1,103 @@
+/**
+ * Owner confirmation for tier-raising actions (#5575: CEO-9, CEO-14, DX-3,
+ * ENG-15). One rule: raising any fact, take or page tier (confirm, accepting a
+ * trust proposal, quarantine release, reverting an agent edit) needs either an
+ * interactive TTY on the local CLI where the user types a target-specific
+ * token (the ref or a hash8, never y/N), or a connection holding the
+ * `memory_confirm` scope. `--yes` never confirms, and every fix emitted for a
+ * tier-raising action is `tell_user_to_run` with no `--yes`.
+ *
+ * The TTY check is the shared `isInteractive` seam (core/interaction.ts);
+ * tests drive both modes through `__setConfirmationIoForTests` without a pty.
+ * The ops that use this (confirm_memory, trust review actions) live in
+ * src/core/ops/trust.ts.
+ */
+import type { Action } from '../agent-output.ts';
+import { isInteractive, readLine, type InteractiveProbe } from '../interaction.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { databaseRefusal } from '../persistence/publication-failure.ts';
+import { hasScope } from '../scope.ts';
+
+export const MEMORY_CONFIRM_SCOPE = 'memory_confirm';
+
+export interface ConfirmationIo {
+ probe?: InteractiveProbe;
+ input?: NodeJS.ReadableStream;
+ output?: NodeJS.WritableStream;
+ timeoutMs?: number;
+}
+let testIo: ConfirmationIo | null = null;
+/** CEO-14 test override: a probe that reports a TTY (or not) and the streams the prompt reads and writes. */
+export function __setConfirmationIoForTests(io: ConfirmationIo | null): void { testIo = io; }
+
+export interface ConfirmationTarget {
+ /** The typed ref the user sees, e.g. `f123`, `tp7`, `p:default/notes/x`. */
+ ref: string;
+ /** What the user must type; defaults to `ref`. Use a hash8 when the ref is long. */
+ token?: string;
+ /** One line naming the change, e.g. "Raise fact f123 to confirmed by you". */
+ summary: string;
+ /** The exact local command that performs this action on a TTY (no `--yes`). */
+ command: string[];
+}
+
+export type TypedConfirmation = 'confirmed' | 'declined' | 'non_interactive';
+
+/** ENG-15: the user types the target's token; anything else (or EOF, or a timeout) declines. */
+export async function promptTypedConfirmation(target: ConfirmationTarget, io: ConfirmationIo = testIo ?? {}): Promise<TypedConfirmation> {
+ if (!isInteractive(io.probe)) return 'non_interactive';
+ const token = target.token ?? target.ref;
+ const read = await readLine({
+ prompt: `${target.summary}\nType ${token} to confirm (anything else cancels): `,
+ probe: io.probe, input: io.input, output: io.output, timeoutMs: io.timeoutMs,
+ });
+ return read.kind === 'line' && read.text === token ? 'confirmed' : 'declined';
+}
+
+/** DX-3: a fix for a tier-raising action. Always the user's to run; refuses an argv that would auto-confirm. */
+export function tierRaiseFix(argv: string[], why: string, userMessage?: string): Action {
+ if (argv.some(arg => arg === '--yes' || arg === '-y' || arg.startsWith('--yes='))) {
+ throw new Error(`tier-raising fix must not carry --yes: ${argv.join(' ')}`);
+ }
+ return { argv, consent: [], actor: 'user', why, requires_exclusive: false, ...(userMessage ? { user_message: userMessage } : {}) };
+}
+
+export type OwnerConfirmation = { via: 'memory_confirm_scope' } | { via: 'tty' };
+
+/**
+ * Establishes the owner's confirmation for one tier-raising action, or throws.
+ * A remote connection needs `memory_confirm` (`insufficient_scope` otherwise);
+ * the local CLI needs an interactive TTY and the typed token
+ * (`confirmation_required` otherwise). `--yes` is deliberately not an input.
+ */
+export async function requireOwnerConfirmation(ctx: OperationContext, target: ConfirmationTarget): Promise<OwnerConfirmation> {
+ const fix = tierRaiseFix(target.command,
+ 'Raising trust needs the owner: run this on the brain host in an interactive terminal and type the confirmation token when asked.',
+ `Run on the brain host, in a terminal: ${target.command.join(' ')}`);
+ if (ctx.remote !== false) {
+ if (hasScope(ctx.auth?.scopes ?? [], MEMORY_CONFIRM_SCOPE)) return { via: 'memory_confirm_scope' };
+ throw opError('insufficient_scope', `This connection cannot confirm memory: ${target.summary.toLowerCase()} needs the owner.`,
+ 'Do not retry. Tell the user to run the command in fix on the brain host; only they can confirm memory.',
+ { why: 'Confirming memory raises its trust tier, which only the owner may do (an interactive terminal on the brain host, or a connection granted memory_confirm by the local CLI).', fix });
+ }
+ const answer = await promptTypedConfirmation(target);
+ if (answer === 'confirmed') return { via: 'tty' };
+ throw opError('confirmation_required', answer === 'declined'
+ ? `Not confirmed: the typed token did not match ${target.token ?? target.ref}. Nothing was changed.`
+ : 'This needs the owner to confirm in an interactive terminal; nothing was changed.',
+ 'Do not retry with --yes (it never confirms). Tell the user to run the command in fix in an interactive terminal on the brain host.',
+ { why: 'Raising trust is the owner\'s decision, so it needs a person at a terminal typing the confirmation token; piped input, agents and --yes cannot confirm.', fix });
+}
+
+/**
+ * The tier trigger's database refusal (trust/schema.ts) as the registered
+ * `trust_raise_refused` error, for direct writers outside the coordinator
+ * (the coordinator classifies it through publication-failure.ts). Null when
+ * `error` is something else.
+ */
+export function trustRaiseRefusal(error: unknown): OperationError | null {
+ const refusal = databaseRefusal(error);
+ if (refusal?.code !== 'trust_raise_refused') return null;
+ return opError('trust_raise_refused', refusal.message,
+ 'Do not retry. Ask the user to confirm the row on the brain host, or leave its tier as it is.');
+}
diff --git a/src/core/trust/min-trust.ts b/src/core/trust/min-trust.ts
new file mode 100644
index 0000000000..25fedc6770
--- /dev/null
+++ b/src/core/trust/min-trust.ts
@@ -0,0 +1,67 @@
+/**
+ * Per-token read floors (#5575, CEO-18). `oauth_clients.min_trust` and
+ * `access_tokens.min_trust` hold the lowest trust tier a connection may read;
+ * token verification carries it as `AuthInfo.minTrust` and read ops apply
+ * max(floor, caller param). Only the trusted local CLI writes it
+ * (`gbrain auth create --min-trust`, `gbrain auth set-min-trust`); no MCP or
+ * admin HTTP surface can change it.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { isUndefinedColumnError } from '../utils.ts';
+import { opError } from '../ops/contract.ts';
+import type { TrustTier } from './tier.ts';
+
+export interface MinTrustChange {
+ kind: 'oauth_client' | 'legacy_token';
+ id: string;
+ name: string;
+ before: TrustTier | null;
+ after: TrustTier | null;
+}
+
+function migrationsPending(): Error {
+ return opError('migrations_pending', 'This brain is missing the per-token min_trust column, so it cannot store a read floor.',
+ 'Apply the pending schema migrations on the brain host, then set the floor again.', {
+ why: 'Read floors live in a column the memory-trust migration adds.',
+ fix: { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent', requires_exclusive: true,
+ why: 'Applies the pending schema migrations, including the min_trust column; no user decision needed.', verify: { argv: ['gbrain', 'doctor', '--json'] } },
+ });
+}
+
+async function guarded<T>(fn: () => Promise<T>): Promise<T> {
+ try { return await fn(); }
+ catch (error) { if (isUndefinedColumnError(error, 'min_trust')) throw migrationsPending(); throw error; }
+}
+
+/** Sets a legacy token's floor by row id (the mint path already knows the id). */
+export async function setTokenMinTrust(engine: BrainEngine, tokenId: string, tier: TrustTier | null): Promise<void> {
+ await guarded(() => engine.executeRaw('UPDATE access_tokens SET min_trust = $1 WHERE id = $2::uuid', [tier, tokenId]));
+}
+
+/**
+ * Sets the floor of one connection named by OAuth client id, legacy token id
+ * or active legacy token name (names are not unique: an ambiguous name is
+ * refused). `null` clears it. Returns the before/after values.
+ */
+export async function setMinTrust(engine: BrainEngine, target: string, tier: TrustTier | null): Promise<MinTrustChange> {
+ return guarded(async () => {
+ const [client] = await engine.executeRaw<{ id: string; name: string | null; before: string | null }>(
+ `UPDATE oauth_clients c SET min_trust = $2 FROM (SELECT client_id, min_trust FROM oauth_clients WHERE client_id = $1 AND deleted_at IS NULL FOR UPDATE) prior
+ WHERE c.client_id = prior.client_id RETURNING c.client_id AS id, c.client_name AS name, prior.min_trust AS before`, [target, tier]);
+ if (client) return { kind: 'oauth_client', id: client.id, name: client.name ?? client.id, before: client.before as TrustTier | null, after: tier };
+ const tokens = await engine.executeRaw<{ id: string; name: string; before: string | null }>(
+ `SELECT id::text AS id, name, min_trust AS before FROM access_tokens
+ WHERE revoked_at IS NULL AND (id::text = $1 OR name = $1)`, [target]);
+ if (tokens.length > 1) {
+ throw opError('invalid_params', `${tokens.length} active tokens are named "${target}".`,
+ 'Name the token by its id from gbrain auth list instead.');
+ }
+ const token = tokens[0];
+ if (!token) {
+ throw opError('not_found', `No active OAuth client or token is named "${target}".`,
+ 'List clients with gbrain auth clients and tokens with gbrain auth list, then pass a client id, token id or token name.');
+ }
+ await setTokenMinTrust(engine, token.id, tier);
+ return { kind: 'legacy_token', id: token.id, name: token.name, before: token.before as TrustTier | null, after: tier };
+ });
+}
diff --git a/src/core/trust/tier.ts b/src/core/trust/tier.ts
index 07100de70b..3693a4ab98 100644
--- a/src/core/trust/tier.ts
+++ b/src/core/trust/tier.ts
@@ -84,6 +84,16 @@ export function storedTrustTier(value: unknown): TrustTier {
return isTrustTier(value) ? value : 'unknown';
}
+/**
+ * A per-token read floor (`oauth_clients.min_trust`, `access_tokens.min_trust`,
+ * CEO-18) read back at token verification: NULL means no floor; a value that
+ * names no tier (a damaged row) fails closed to the strictest floor.
+ */
+export function storedMinTrust(value: unknown): TrustTier | undefined {
+ if (value === null || value === undefined) return undefined;
+ return isTrustTier(value) ? value : 'user_confirmed';
+}
+
/** SQL expression mapping a tier-valued expression to its rank (unrecognized and NULL -> 0). */
export function trustRankSql(expr: string): string {
return `(CASE ${expr} ${TRUST_TIERS.map(tier => `WHEN '${tier}' THEN ${TRUST_TIER_RANK[tier]}`).join(' ')} ELSE 0 END)`;
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index 6460221a06..b7e35850e3 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -54,6 +54,7 @@ import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';
import { redactUrlsInText } from '../core/url-redact.ts';
import { authSourcesFromGrant } from '../core/grants/model.ts';
import { resolveTokenGrant, touchTokenLastUsed } from '../core/grants/legacy-token.ts';
+import { storedMinTrust } from '../core/trust/tier.ts';
export { parseLegacyTokenScope } from '../core/legacy-token-scope.ts';
const DEFAULT_BODY_CAP = 1024 * 1024; // 1 MiB
@@ -288,6 +289,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
sourceId,
...(grant.allowedOperations === null ? {} : { allowedOperations: grant.allowedOperations }),
...(allowedSources ? { allowedSources } : {}),
+ ...(storedMinTrust(row.min_trust) ? { minTrust: storedMinTrust(row.min_trust) } : {}),
};
return {
ok: true,
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index fb6d78f5a9..a825353ea3 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1658,6 +1658,78 @@
"name": "revision_backfill",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "backfill": {
+ "completed_at": null,
+ "interrupted": false
+ },
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "tables": [
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "pages"
+ },
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "facts"
+ },
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "takes"
+ },
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "timeline_entries"
+ }
+ ],
+ "unknown_pct": 0
+ },
+ "message": "No facts, takes, timeline entries or pages yet.",
+ "name": "trust_tiers",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 1530d5fcbe..4226f027c6 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1735,6 +1735,78 @@
"name": "revision_backfill",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "backfill": {
+ "completed_at": null,
+ "interrupted": false
+ },
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "tables": [
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "pages"
+ },
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "facts"
+ },
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "takes"
+ },
+ {
+ "by_tier": {
+ "agent_written": 0,
+ "external_untrusted": 0,
+ "operator_curated": 0,
+ "tool_observed": 0,
+ "unknown": 0,
+ "user_confirmed": 0
+ },
+ "rows": 0,
+ "table": "timeline_entries"
+ }
+ ],
+ "unknown_pct": 0
+ },
+ "message": "No facts, takes, timeline entries or pages yet.",
+ "name": "trust_tiers",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 8ebebeac1e..21bab3eae0 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -685,6 +685,10 @@
"category": "meta",
"name": "revision_backfill"
},
+ {
+ "category": "brain",
+ "name": "trust_tiers"
+ },
{
"category": "brain",
"name": "core_memory"