Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#5575 memory trust: claim your sources; ask before scanning legacy content

garrytan26b0266b5060
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index e062dd1c7a..219e5b23e1 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -28,6 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.
+- `src/core/trust/claim.ts` + `claim-state.ts` + `claim-notice.ts`, `src/commands/trust-claim.ts`: #5575 legacy content. `gbrain trust claim-sources` (local CLI; typed source id on a TTY, `--yes` never counts, non-TTY refuses `confirmation_required` with an ask_user fix) records a claim in `sources.config` (`trust_tier: operator_curated`, `trust_claimed_at`, `trust_claim_lifted_at`) and lifts the source's legacy `unknown` rows (ids at or below `write_gate.scan_baseline`) through `trust/backfill.ts` scoped to the claimed sources (own cursor, `write_origin.channel` `trust_claim`), lowered by `frontmatterTrustCapsSql` (channel.ts, pinned to `frontmatterTrustCaps`) and every backfill signal, never above operator_curated; connector sources refuse. Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the behavior-change notice ask (ask_user); doctor `trust_scan` asks before scanning; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`.
- `src/core/write-gate.ts` + `src/core/write-gate-patterns.ts` — the #5575 blocking write gate, separate from observe-only `guardrails.ts` (never imported). Deterministic and model-free (P8): `WRITE_GATE_PATTERNS` (bounded clones of the detection-grade `think/sanitize.ts` `INJECTION_DETECTION_PATTERNS`, the exported transcript `IMPERATIVE_RES`, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed to <address>" rules and direct cc/bcc) and credential patterns; families `override`, `standing_instruction`, `exfiltration`, `credential`). `detectInstructionLike` decodes tag characters, strips invisibles and NFKC-folds compatibility forms only when present, finds anchor words in one allocation-light hash pass (one tight loop per word), then runs each pattern only on 4 KB windows (overlap `MAX_MATCH_CHARS` + `MAX_PRECEDING_CHARS`) holding its anchors, tracked as sliding per-window anchor counts, and inside a window only within the pattern's longest match (`write-gate-regex.ts`, the analysis the regex lint uses) of its own anchor words, except `WHOLE_WINDOW_PATTERNS`; `preceded` regexes check context before a rare-token match, a `neg` group rejects negated matches. `assessPageForGate` (title, body minus managed fence table rows, frontmatter strings), `assessFactForGate` (fact, context, value, provenance, pre-sanitized `source_text`), `assessTakeForGate` and `assessTimelineForGate` scan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed; `external_untrusted` -> `write_gate.external_mode` (`quarantine` default, `flag`, `reject`, `off`), detector error -> quarantine; `agent_written`/`unknown` -> `flag` (`write_gate.agent_mode=off`), detector error -> allow. `writeGateOutcome` is the DX-1 `gate` shape; `writeHeldError` / `writeGateRejectedError` build the `write_held` / `write_gate_rejected` refusals (families only, no pattern names). `scripts/check-write-gate-regex.ts` (in verify) proves every pattern bounded. Tests: `test/write-gate.test.ts`, `test/write-gate-perf.slow.test.ts`, `test/write-gate-anchor-ranges.test.ts` (sampled matches of every narrowed pattern hold an anchor word within its longest match), and `test/write-gate-detector-differential.test.ts` (identical hits to the pre-optimization detector v2 kept as `test/helpers/write-gate-detector-reference.ts`, over the detector corpora, BrainBench fixtures, docs/skills and a seeded random corpus).
- `src/core/write-gate-store.ts` + `src/core/write-gate-schema.ts` — `write_gate_receipts` (flag/quarantine verdicts per persisted target, unique on target, content hash and detector version; pattern names only) and `write_gate_holds` (quarantined facts/takes kept out of `facts`/`takes`, unique on source, slug, fingerprint and detector version; re-arrival re-opens a decided hold). Writers record inside their publication transaction: `recordPageGateReceipt` resolves the live page row, `recordWriteGateReceipt`, `recordWriteGateHold`; `decideFactWrite` / `decideTakeWrite` return insert/hold/reject per row and `recordFlaggedRow` receipts an inserted flagged row. Owner review: `listWriteGateHolds`, `getWriteGateHold`, `releaseWriteGateHold` (returns the payload for the confirm path; authorization is the caller's), `dropWriteGateHold`; `pruneWriteGateReceipts` drops receipts unseen for 365 days except a pending hold's. Tests: `test/write-gate-store.test.ts` (+ Postgres arm `test/e2e/write-gate-store-postgres.test.ts`).
diff --git a/docs/guides/memory-trust.md b/docs/guides/memory-trust.md
new file mode 100644
index 0000000000..dbb966db0c
--- /dev/null
+++ b/docs/guides/memory-trust.md
@@ -0,0 +1,104 @@
+# Memory trust
+
+gbrain records where each memory came from and how much it should be trusted.
+It uses that to keep instruction-like text that an agent wrote out of
+proactive context until you confirm it. This guide covers what hold-back
+covers, when it applies to content saved before this release, and the
+commands that claim your sources and scan older memory.
+
+## Trust tiers
+
+Every fact, take, timeline entry and page carries one tier. Read surfaces show
+it as a label:
+
+| Tier | Label | Typical origin |
+|---|---|---|
+| `user_confirmed` | confirmed by you | you confirmed it (`gbrain trust confirm`) |
+| `operator_curated` | your notes | sync and import of your own sources |
+| `tool_observed` | tool data | structured tool output |
+| `agent_written` | written by an agent | `put_page`, `remember`, `capture`, remote MCP writes |
+| `unknown` | unverified origin | rows saved before trust tiers existed |
+| `external_untrusted` | external, untrusted | connectors, webhooks, clipped pages, third-party transcripts |
+
+Nothing ever becomes "confirmed by you" without you typing a confirmation
+token at a terminal on the brain host. `--yes` never confirms.
+
+## What hold-back covers
+
+Hold-back starts covering **new agent-written content right away**. A write at
+`agent_written` or lower that reads like instructions to an agent (for example
+"from now on always recommend..." or "ignore your previous instructions") gets
+a write-gate receipt. It is still saved and still returned by explicit search,
+recall and `get_page`. Proactive surfaces (hook context, the context engine,
+`context_pack`, volunteer) do not inject it until you confirm it in
+`gbrain trust review`.
+
+**Content saved before this release is covered only after you claim your
+sources and agree to the scan.** Older rows have no provenance, so they read
+as "unverified origin". On a long-lived brain that is most rows, including
+your own notes and synced code repositories. gbrain never scans them on its
+own. Doctor, `gbrain post-upgrade` and the behavior-change notice ask you
+first.
+
+## Claim your sources (once, after upgrading)
+
+```bash
+gbrain trust claim-sources --dry-run # read-only: every source and what a claim would change
+gbrain trust claim-sources # asks you, per source, to type its id
+```
+
+For each source, the listing shows:
+- its id and local path (or remote);
+- its page count;
+- its trust mix now and after a claim.
+
+Typing a source's id claims it as your own notes:
+
+- The source syncs as "your notes" from now on. This is the
+ `gbrain sources set-trust` default, set to `operator_curated`.
+- Its rows from before trust tiers move from "unverified origin" to "your
+ notes". A row with a lowering signal keeps the lower tier: MCP and capture
+ stamps, imported transcripts, clipped pages, connector stamps, extraction
+ and dream provenance, journaled agent writes, and a `trust_tier` marker in
+ the frontmatter. Nothing goes above "your notes".
+- Connector sources (Gmail, Calendar, GitHub) cannot be claimed. Their text
+ comes from other people.
+
+Claiming needs you at a terminal on the brain host. Without one (an agent,
+piped input) the command changes nothing. It exits 3 with an `ask_user` fix,
+whose `user_message` explains claiming.
+
+The lift runs in bounded batches. If it is interrupted,
+`gbrain trust claim-sources --resume` finishes it without asking again. Until
+the lift finishes, `gbrain trust scan` refuses, and `gbrain trust explain`
+shows the claimed source's remaining rows as "your notes".
+
+Each lifted row keeps `write_origin.channel = "trust_claim"`. The source
+records when it was claimed and when its lift finished.
+
+`gbrain sources set-trust <id> <lower tier>` or `--clear` ends a claim. Rows
+it already lifted keep their tier.
+
+## Scan older memory (only when you agree)
+
+```bash
+gbrain trust scan
+```
+
+The scan runs the write gate's deterministic detector over older rows at
+"written by an agent" or below. It records a receipt for each instruction-like
+row. It never deletes, moves or rewrites anything, but flagged rows stop
+reaching proactive context until you confirm them. Doctor's `trust_scan`
+check therefore asks you before an agent runs it (`fix.next: ask_user`).
+Claim your own sources first, so your notes are not treated as unverified.
+
+## Doctor checks
+
+- `trust_sources_unclaimed` warns while unclaimed, non-connector sources hold
+ rows from before trust tiers, with `fix.next: ask_user` naming
+ `gbrain trust claim-sources`. It also warns, with the resume command, while
+ a claim's lift has not finished. A fresh or empty brain is ok.
+- `trust_scan` warns while older rows at "written by an agent" or below have
+ not been scanned. Its fix asks you first.
+- `trust_tiers` reports the tier mix and recommends `gbrain trust backfill`.
+ The backfill classifies older rows from deterministic signals only.
diff --git a/src/cli/commands/trust.ts b/src/cli/commands/trust.ts
index 0fe2225cb3..aecedbd73b 100644
--- a/src/cli/commands/trust.ts
+++ b/src/cli/commands/trust.ts
@@ -1,8 +1,9 @@
/**
* `gbrain trust`: the memory-trust noun (#5575, DX-7). This module dispatches
- * `backfill` (A8, DX-5) and `scan` (DX-6), and hands the owner subcommands (review, confirm,
+ * `backfill` (A8, DX-5), `scan` (DX-6) and `claim-sources` (legacy content, trust/claim.ts),
+ * and hands the owner subcommands (review, confirm,
* release, drop, revert, explain, allow, disable) to src/commands/trust.ts.
- * The record is startup: 'observational', so `backfill --dry-run` runs on a
+ * The record is startup: 'observational', so `backfill --dry-run` and `claim-sources --dry-run` run on a
* probe-only engine with no migrations and no writes; every other subcommand
* completes startup first. While a resident serve holds a PGLite brain,
* src/cli.ts routes the owner subcommands to it before any engine opens.
@@ -13,6 +14,7 @@ import { TRUST_TIERS, trustLabel } from '../../core/trust/tier.ts';
import type { TrustBackfillReport } from '../../core/trust/backfill.ts';
import type { CliDispatchContext } from '../command-table.ts';
import { TRUST_OWNER_USAGE, isTrustOwnerSubcommand, localTrustBackend, reportTrustCliError, runTrustOwnerCommand } from '../../commands/trust.ts';
+import { TRUST_CLAIM_USAGE } from '../../commands/trust-claim.ts';
export const TRUST_BACKFILL_USAGE = [
'Usage: gbrain trust backfill [--dry-run] [--resume] [--batch-size N] [--json]',
@@ -26,8 +28,10 @@ export const TRUST_BACKFILL_USAGE = [
' Runs the write gate\'s deterministic detector over agent-written and lower rows written before the gate,',
' recording a receipt for each instruction-like row so proactive surfaces stop injecting it until you confirm',
' it (gbrain trust review). Changes no row; resumable (rerun to continue); a detector upgrade rescans.',
+ ' Nothing runs it for you: an agent asks you first. Claim your own sources first (gbrain trust claim-sources)',
+ ' so your older notes are not treated as unverified.',
].join('\n');
-export const TRUST_USAGE = `${TRUST_OWNER_USAGE}\n\n${TRUST_BACKFILL_USAGE}`;
+export const TRUST_USAGE = `${TRUST_OWNER_USAGE}\n\n${TRUST_BACKFILL_USAGE}\n\n${TRUST_CLAIM_USAGE}`;
function render(report: TrustBackfillReport): string {
const lines = [`Trust backfill (${report.mode === 'dry_run' ? 'dry run, nothing written' : 'applied'}; schema: ${report.schema}):`];
@@ -48,15 +52,20 @@ async function refuse(args: string[], message: string, suggestion: string): Prom
export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
const [sub, ...rest] = args;
- const known = sub === 'backfill' || sub === 'scan' || isTrustOwnerSubcommand(sub);
+ const known = sub === 'backfill' || sub === 'scan' || sub === 'claim-sources' || isTrustOwnerSubcommand(sub);
if (args.includes('--help') || args.includes('-h') || (!sub && !jsonRequested(args))) {
- console.log(sub === 'backfill' || sub === 'scan' ? TRUST_BACKFILL_USAGE : TRUST_USAGE);
+ console.log(sub === 'backfill' || sub === 'scan' ? TRUST_BACKFILL_USAGE : sub === 'claim-sources' ? TRUST_CLAIM_USAGE : TRUST_USAGE);
return;
}
if (!known) {
if (!jsonRequested(args)) console.log(TRUST_USAGE);
await refuse(args, !sub || sub.startsWith('-') ? 'gbrain trust needs a subcommand.' : `Unknown trust subcommand '${sub}'.`,
- 'gbrain trust --help lists the subcommands (review, confirm, explain, backfill, scan and the rest).');
+ 'gbrain trust --help lists the subcommands (review, confirm, explain, backfill, scan, claim-sources and the rest).');
+ return;
+ }
+ if (sub === 'claim-sources') {
+ const { runTrustClaimSources } = await import('../../commands/trust-claim.ts');
+ await runTrustClaimSources(engine, rest, { completeStartup: ctx.completeStartup ? e => ctx.completeStartup!(e) : undefined });
return;
}
if (sub !== 'backfill' && sub !== 'scan') {
@@ -79,7 +88,9 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC
if (sub === 'scan') {
await ctx.completeStartup?.(engine);
const { runTrustScan } = await import('../../core/eligibility/scan.ts');
- const scan = await runTrustScan(engine, batchSize ? { batchSize } : {});
+ let scan;
+ try { scan = await runTrustScan(engine, batchSize ? { batchSize } : {}); }
+ catch (error) { if (await reportTrustCliError(error, jsonRequested(args))) return; throw error; }
if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(scan, null, 2)}\n`);
else console.log([`Trust scan (detector v${scan.detector_version}):`,
...scan.tables.map(t => ` ${t.table}: ${t.scanned} row(s) scanned, ${t.flagged} flagged${t.done ? '' : ' (more to scan)'}`),
diff --git a/src/commands/doctor/checks/trust-scan.ts b/src/commands/doctor/checks/trust-scan.ts
index 592eade2aa..cb21fe7d5b 100644
--- a/src/commands/doctor/checks/trust-scan.ts
+++ b/src/commands/doctor/checks/trust-scan.ts
@@ -2,16 +2,24 @@
* trust_scan (#5575, DX-6 / ENG-8): rows at `agent_written` or lower that
* the write gate's current detector has not scanned. Activation control
* (CEO-20) only covers scanned rows, so unscanned legacy rows can still be
- * injected by proactive surfaces; the fix runs `gbrain trust scan`, which
- * records flag receipts in bounded, resumable batches and changes no row.
+ * injected by proactive surfaces. The fix is `fix.next: ask_user`: `gbrain
+ * trust scan` records flag receipts in bounded, resumable batches and changes
+ * no row, but a flagged row stops reaching proactive context, so the scan of
+ * legacy content runs only after the user agrees (and ideally after they
+ * claimed their own sources: trust_sources_unclaimed).
* A brain before the trust or write-gate migrations is ok. Read-only.
*/
import type { Check } from '../../doctor.ts';
-import { agentFix, checkError } from '../check-fix.ts';
+import { checkError, doctorVerify } from '../check-fix.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { readTrustScanState } from '../../../core/eligibility/scan.ts';
import { isUndefinedColumnError, isUndefinedTableError } from '../../../core/utils.ts';
+const SCAN_USER_MESSAGE = 'gbrain can check your memory written before its write gate for text that reads like instructions to an AI '
+ + '(for example "from now on always say..."). Anything it flags stays in your brain and in search, but agents stop getting it automatically '
+ + 'until you confirm it in gbrain trust review. If some sources are your own notes, claim them first (gbrain trust claim-sources) so the check '
+ + 'treats them as yours. Run the check now?';
+
async function runTrustScan(ctx: DoctorContext): Promise<Check[]> {
const engine = connectedEngine(ctx);
const checks: Check[] = [];
@@ -25,8 +33,11 @@ async function runTrustScan(ctx: DoctorContext): Promise<Check[]> {
}
checks.push({ name: 'trust_scan', status: 'warn', details,
message: `${state.total_unscanned} agent-written or lower row(s) have not been scanned by the write-gate detector (v${state.detector_version}), `
- + 'so proactive surfaces cannot yet withhold instruction-like ones. Run gbrain trust scan on the brain host; it records receipts in resumable batches and changes no row.',
- fix: agentFix(['gbrain', 'trust', 'scan'], 'Scans legacy agent-written rows with the deterministic detector and records flag receipts; it never hides, moves or rewrites a row.', 'trust_scan') });
+ + 'so proactive surfaces do not withhold instruction-like ones yet. Ask the user before running gbrain trust scan: it records receipts in resumable batches and changes no row, '
+ + 'but flagged rows (their own older notes included, unless they claimed those sources first with gbrain trust claim-sources) stop reaching proactive context until confirmed.',
+ fix: { argv: ['gbrain', 'trust', 'scan'], consent: ['destructive'], actor: 'agent', requires_exclusive: false, verify: doctorVerify('trust_scan'),
+ why: 'Scans legacy agent-written and unverified rows with the deterministic detector and records flag receipts; it moves, deletes or rewrites nothing, but flagged rows stop reaching proactive context until the owner confirms them, so it runs only after the user agrees.',
+ user_message: SCAN_USER_MESSAGE } });
} catch (err) {
if (isUndefinedColumnError(err, 'trust_tier') || isUndefinedTableError(err)) {
checks.push({ name: 'trust_scan', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates the write gate; the scan arrives with its migration.' });
diff --git a/src/commands/doctor/checks/trust-sources-unclaimed.ts b/src/commands/doctor/checks/trust-sources-unclaimed.ts
new file mode 100644
index 0000000000..7a29d26dc7
--- /dev/null
+++ b/src/commands/doctor/checks/trust-sources-unclaimed.ts
@@ -0,0 +1,49 @@
+/**
+ * trust_sources_unclaimed (#5575, legacy content): warns while live,
+ * non-connector sources the owner has not claimed hold rows still at
+ * `unknown` (written before trust tiers, so they have no provenance), and
+ * while a claim's lift has not finished. The fix is `fix.next: ask_user`:
+ * relay what claiming means; only the owner can claim, at a terminal
+ * (`gbrain trust claim-sources`, trust/claim.ts). A fresh or empty brain, or a
+ * brain before the trust migration, is ok. Read-only.
+ */
+import type { Check } from '../../doctor.ts';
+import { checkError } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { claimSourcesFix, readUnclaimedLegacySources } from '../../../core/trust/claim.ts';
+import { TRUST_CLAIM_RESUME_COMMAND } from '../../../core/trust/claim-state.ts';
+import { isUndefinedColumnError } from '../../../core/utils.ts';
+
+const VERIFY = { argv: ['gbrain', 'doctor', '--only', 'trust_sources_unclaimed', '--json'] };
+
+async function runTrustSourcesUnclaimed(ctx: DoctorContext): Promise<Check[]> {
+ const engine = connectedEngine(ctx);
+ const checks: Check[] = [];
+ try {
+ const { unclaimed, pending } = await readUnclaimedLegacySources(engine);
+ const rows = unclaimed.reduce((n, s) => n + s.legacy_unknown, 0);
+ const details = { unclaimed, pending, legacy_unknown: rows };
+ if (pending.length) {
+ checks.push({ name: 'trust_sources_unclaimed', status: 'warn', details,
+ message: `A claim did not finish lifting ${pending.join(', ')}. Run ${TRUST_CLAIM_RESUME_COMMAND.join(' ')} on the brain host; it continues the confirmed claim and asks nothing.`,
+ fix: { argv: [...TRUST_CLAIM_RESUME_COMMAND], consent: [], actor: 'agent', requires_exclusive: false, verify: VERIFY,
+ why: 'Finishes the backfill of sources the owner already claimed, in resumable batches; nothing goes above "your notes".' } });
+ } else if (unclaimed.length === 0) {
+ checks.push({ name: 'trust_sources_unclaimed', status: 'ok', details, message: 'No unclaimed source holds rows from before trust tiers.' });
+ } else {
+ checks.push({ name: 'trust_sources_unclaimed', status: 'warn', details,
+ message: `${rows} row(s) from before trust tiers in ${unclaimed.length} unclaimed source(s) (${unclaimed.map(s => s.id).join(', ')}) read as "unverified origin". `
+ + 'Ask the user whether these are their own notes; if so they run gbrain trust claim-sources in a terminal on the brain host (gbrain trust claim-sources --dry-run --json previews it).',
+ fix: claimSourcesFix('trust_sources_unclaimed') });
+ }
+ } catch (err) {
+ if (isUndefinedColumnError(err, 'trust_tier')) {
+ checks.push({ name: 'trust_sources_unclaimed', status: 'ok', details: { schema: 'pre_trust' }, message: 'This schema predates trust tiers; claiming arrives with the migration that adds them.' });
+ } else {
+ checks.push(checkError('trust_sources_unclaimed', 'read unclaimed sources', err));
+ }
+ }
+ return checks;
+}
+
+export const trustSourcesUnclaimedEntry: DoctorEntry = { name: 'trust_sources_unclaimed', emits: ['trust_sources_unclaimed'], run: runTrustSourcesUnclaimed };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index bedaedef89..ed2ef546b1 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -97,6 +97,7 @@ import { plannerStatsEntry } from './checks/planner-stats.ts';
import { revisionBackfillEntry } from './checks/revision-backfill.ts';
import { trustTiersEntry } from './checks/trust-tiers.ts';
import { trustScanEntry } from './checks/trust-scan.ts';
+import { trustSourcesUnclaimedEntry } from './checks/trust-sources-unclaimed.ts';
import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';
import { agentContractEntry } from './checks/agent-contract.ts';
import { chatFallbackChainEntry } from './checks/chat-fallback.ts';
@@ -178,6 +179,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
revisionBackfillEntry,
trustTiersEntry,
trustScanEntry,
+ trustSourcesUnclaimedEntry,
coreMemoryEntry,
fenceIntegrityEntry,
searchModeEntry,
diff --git a/src/commands/sources-trust.ts b/src/commands/sources-trust.ts
index 68cdaa472a..392b72c472 100644
--- a/src/commands/sources-trust.ts
+++ b/src/commands/sources-trust.ts
@@ -5,11 +5,13 @@
* only lower: the highest accepted value is operator_curated (the owner-sync
* tier), and page frontmatter markers still lower further. Trusted local CLI
* only (the sources command has no MCP surface). Applies to rows written by
- * the next sync or import; existing rows keep their tier.
+ * the next sync or import; existing rows keep their tier. Any value but
+ * operator_curated (or --clear) ends a `gbrain trust claim-sources` claim.
*/
import type { BrainEngine } from '../core/engine.ts';
import { normalizeSourceConfig, parseSourceConfig } from '../core/sources-load.ts';
import { OWNER_TIER_FLOOR, TRUST_TIERS, compareTrust, isTrustTier, trustLabel } from '../core/trust/tier.ts';
+import { dropClaimUnlessOwnerDefault, isClaimedConfig } from '../core/trust/claim-state.ts';
const ACCEPTED = TRUST_TIERS.filter(tier => compareTrust(tier, OWNER_TIER_FLOOR) <= 0);
export const SOURCES_SET_TRUST_USAGE = `Usage: gbrain sources set-trust <id> <${ACCEPTED.join('|')}> | --clear`;
@@ -30,9 +32,11 @@ export async function runSetTrust(engine: BrainEngine, args: string[]): Promise<
process.exit(4);
}
const config = parseSourceConfig(src.config);
+ const claimed = isClaimedConfig(config);
if (value === '--clear') delete config.trust_tier;
else config.trust_tier = value;
- await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(normalizeSourceConfig(config)), id]);
+ await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(normalizeSourceConfig(dropClaimUnlessOwnerDefault(config))), id]);
+ if (claimed && value !== OWNER_TIER_FLOOR) console.log(`Source "${id}" is no longer claimed (gbrain trust claim-sources); rows it already lifted keep their tier.`);
console.log(value === '--clear'
? `Source "${id}" syncs at the owner default again (${OWNER_TIER_FLOOR}: "${trustLabel(OWNER_TIER_FLOOR)}"), lowered by page markers. Existing rows keep their tier.`
: `Source "${id}" now syncs at ${value} ("${trustLabel(value as never)}") or lower. It applies to pages the next sync or import writes; existing rows keep their tier.`);
diff --git a/src/commands/trust-claim.ts b/src/commands/trust-claim.ts
new file mode 100644
index 0000000000..a4f3b8b2c3
--- /dev/null
+++ b/src/commands/trust-claim.ts
@@ -0,0 +1,126 @@
+/**
+ * `gbrain trust claim-sources` (#5575, legacy content; trust/claim.ts): lists
+ * each source (id, local path or remote, page count, the tier mix now and
+ * after a claim) and asks the owner, per claimable source, to type its id.
+ * Claimed sources get the per-source default operator_curated and their
+ * legacy unverified rows are lifted (never above "your notes"; rows with a
+ * lowering signal keep it). Trusted local CLI only; `--yes` never claims.
+ *
+ * --dry-run [--json] the listing, read-only
+ * --source <id> ask only about this source (repeatable)
+ * --resume finish the lift of sources already claimed (asks nothing)
+ * --batch-size N lift batch size
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { jsonRequested, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { opError } from '../core/ops/contract.ts';
+import {
+ claimSourcesFix, connectorRefusal, liftClaimedSources, listClaimSources, recordSourceClaims,
+ type ClaimLiftReport, type ClaimSource,
+} from '../core/trust/claim.ts';
+import { promptTypedConfirmation } from '../core/trust/confirm.ts';
+import { TRUST_TIERS, trustLabel } from '../core/trust/tier.ts';
+import type { TierCounts } from '../core/trust/backfill.ts';
+import { reportTrustCliError } from './trust.ts';
+
+export const TRUST_CLAIM_USAGE = [
+ 'Usage: gbrain trust claim-sources [--dry-run] [--source <id>]... [--resume] [--batch-size N] [--json]',
+ ' Claim your own sources once, after upgrading: each source shows its local path or remote, page count and',
+ ' the trust mix now and after claiming, and you type its id to claim it. A claimed source syncs as "your notes"',
+ ' and its rows from before trust tiers move from "unverified origin" to "your notes", except rows that say',
+ ' they were captured, clipped, imported, extracted or written by an agent (they keep their lower tier).',
+ ' Nothing becomes "confirmed by you". Connector sources (Google, GitHub) cannot be claimed. --dry-run lists',
+ ' without writing; --resume finishes an interrupted claim. Needs you at a terminal; --yes never claims.',
+].join('\n');
+
+const mix = (counts: TierCounts | undefined) =>
+ counts ? TRUST_TIERS.filter(t => counts[t] > 0).map(t => `${trustLabel(t)} ${counts[t]}`).join(', ') || 'no rows' : 'not yet classified';
+
+function describe(s: ClaimSource): string[] {
+ const where = s.local_path ?? s.remote_url ?? 'no local path';
+ const state = s.blocker === 'connector' ? `${s.kind} connector: cannot be claimed`
+ : s.blocker === 'archived' ? 'archived' : s.pending ? 'claimed; lift not finished (gbrain trust claim-sources --resume)'
+ : s.claimed ? 'claimed' : s.blocker === 'no_legacy_rows' ? 'nothing to lift' : `${s.legacy_unknown} legacy row(s) with unverified origin`;
+ return [
+ ` ${s.id} (${where}): ${s.pages} page(s); ${state}`,
+ ` now: ${mix(s.current)}`,
+ ...(s.claimable ? [` if claimed: ${mix(s.projected_if_claimed)}`] : []),
+ ];
+}
+
+function renderLift(lift: ClaimLiftReport): string[] {
+ if (!lift.sources.length) return [];
+ const moved = Object.values(lift.updated).reduce((n, v) => n + v, 0);
+ return [
+ `Lifted ${moved} legacy row(s) in ${lift.sources.map(s => s.id).join(', ')}; ${lift.kept_lower} row(s) kept a lower tier from their own signals.`,
+ ...lift.sources.map(s => ` ${s.id}: ${mix(s.tiers)}`),
+ ];
+}
+
+function flagValues(args: string[], flag: string): string[] {
+ const out: string[] = [];
+ args.forEach((a, i) => { if (a === flag && args[i + 1]) out.push(args[i + 1]!); else if (a.startsWith(`${flag}=`)) out.push(a.slice(flag.length + 1)); });
+ return out;
+}
+
+export async function runTrustClaimSources(engine: BrainEngine, args: string[], opts: { completeStartup?: (e: BrainEngine) => Promise<void> } = {}): Promise<void> {
+ const json = jsonRequested(args);
+ try {
+ const sizeAt = args.indexOf('--batch-size');
+ const batchSize = sizeAt >= 0 ? Number(args[sizeAt + 1]) : undefined;
+ if (batchSize !== undefined && (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 100_000)) {
+ throw opError('invalid_params', '--batch-size must be an integer from 1 to 100000.', 'Run gbrain trust claim-sources --batch-size 500, or omit --batch-size.');
+ }
+ const sized = batchSize ? { batchSize } : {};
+ if (args.includes('--dry-run')) {
+ const listing = await listClaimSources(engine, sized);
+ if (json) await writeStdoutFinal(`${JSON.stringify({ mode: 'dry_run', ...listing }, null, 2)}\n`);
+ else console.log([`Claim sources (dry run, nothing written; schema: ${listing.schema}):`, ...listing.sources.flatMap(describe)].join('\n'));
+ return;
+ }
+ await opts.completeStartup?.(engine);
+ if (args.includes('--resume')) {
+ const lift = await liftClaimedSources(engine, { ...sized, log: line => process.stderr.write(`${line}\n`) });
+ if (json) await writeStdoutFinal(`${JSON.stringify({ mode: 'resume', claimed: [], lift }, null, 2)}\n`);
+ else console.log(lift.sources.length ? renderLift(lift).join('\n') : 'No claimed source is waiting for its lift.');
+ return;
+ }
+ const listing = await listClaimSources(engine, sized);
+ if (listing.schema === 'pre_trust') {
+ throw opError('migrations_pending', 'This brain has no trust tier columns yet, so there is nothing to claim.', 'Run gbrain apply-migrations --yes on the brain host, then gbrain trust claim-sources.');
+ }
+ const named = flagValues(args, '--source');
+ for (const id of named) {
+ const s = listing.sources.find(x => x.id === id);
+ if (!s) throw opError('unknown_source', `Source "${id}" does not exist.`, 'List sources with gbrain trust claim-sources --dry-run.');
+ if (s.blocker === 'connector') throw connectorRefusal(id, s.kind ?? 'connector');
+ }
+ const asked = listing.sources.filter(s => s.claimable && (named.length === 0 || named.includes(s.id)));
+ if (!json) console.log(['Your sources:', ...listing.sources.filter(s => named.length === 0 || named.includes(s.id)).flatMap(describe)].join('\n'));
+ if (args.includes('--yes') && !json) console.log('Note: --yes never claims a source; type each id to claim it.');
+ const claimed: string[] = [];
+ for (const s of asked) {
+ const answer = await promptTypedConfirmation({
+ ref: s.id, command: ['gbrain', 'trust', 'claim-sources', '--source', s.id],
+ summary: `Claim source "${s.id}" as your own notes? Its ${s.legacy_unknown} legacy row(s) become "your notes" unless they say they were captured, clipped, imported or agent-written.`,
+ });
+ if (answer === 'non_interactive') {
+ throw opError('confirmation_required', 'Claiming sources needs the owner at a terminal; nothing was changed.',
+ 'Relay user_message to the user and stop. Only they can claim, by running the command in a terminal on the brain host.',
+ { why: 'Claiming raises legacy rows to "your notes"; that is the owner\'s decision, so it needs a person typing each source id. Piped input, agents and --yes cannot claim.', fix: claimSourcesFix() });
+ }
+ if (answer === 'confirmed') claimed.push(s.id);
+ else if (!json) console.log(` ${s.id}: not claimed.`);
+ }
+ await recordSourceClaims(engine, claimed);
+ const lift = await liftClaimedSources(engine, { ...sized, log: line => process.stderr.write(`${line}\n`) });
+ if (json) { await writeStdoutFinal(`${JSON.stringify({ mode: 'apply', claimed, lift }, null, 2)}\n`); return; }
+ console.log([
+ asked.length === 0 ? 'No source needs claiming.' : claimed.length ? `Claimed: ${claimed.join(', ')}.` : 'No source was claimed.',
+ ...renderLift(lift),
+ ].join('\n'));
+ } catch (error) {
+ if (!(await reportTrustCliError(error, json))) throw error;
+ }
+}
+
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 1b13c7c4e4..77f679aec6 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -716,6 +716,8 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// Temporal typed edges: one-shot [AGENT] notice (live-by-default graph reads + relationship check), best-effort.
await (await import('../core/temporal-edges-upgrade-notice.ts')).printTemporalEdgesUpgradeNotice(engine);
+ // #5575 memory trust: [AGENT] ask_user while unclaimed sources hold legacy rows; never claims or scans (best-effort).
+ await (await import('../core/trust/claim-notice.ts')).printTrustClaimUpgradeNotice(engine);
// Ambient-writeback consent ask (WP8): one-shot for EXISTING installs
// upgrading into the feature. Personal brains only; double-gated on
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 6ab9552823..9555aa7da7 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -313,6 +313,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.108.0', text: 'A job error during worker shutdown now records `worker_shutdown: <handler error>` instead of bare `worker_shutdown`, and an `UnrecoverableError` thrown then dead-letters at once instead of running again.' },
{ since: '0.60.108.0', text: '`gbrain jobs supervisor stop` can now report `unverified` (exit 1) and `stale_pid_file` (exit 0, nothing signaled), and on Linux the supervisor PID file has a second line with the process start time; read only its first line.' },
{ since: '0.60.108.0', text: '`thinking: off` calls on native Google and OpenAI routes (eval judges, the synthesize triage judge, fence repair\'s model tier) now send the model\'s thinking switch (`thinkingBudget: 0`, `reasoningEffort: none`) and, where reasoning cannot be turned off (Gemini 2.5 Pro and 3.x, gpt-5/-mini/-nano, o-series), a 32,000-token reply cap; `eval takes-quality --budget-usd` and `eval cross-modal --max-usd` price that cap, so a budget that passed before can refuse earlier.' },
+ { since: '0.60.110.0', text: 'Memory trust: new agent-written content that reads as instructions to an agent is held back from proactive context until you confirm it (`gbrain trust review`). Content written before this release is held back only after you claim your own sources (`gbrain trust claim-sources`, in a terminal) and agree to `gbrain trust scan`; neither runs on its own.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
@@ -348,6 +349,23 @@ export function behaviorChangesNotice(chain: ChainDisclosure | null, opts: { rem
return { code: BEHAVIOR_NOTICE_CODE, kind: 'safety', why, fix };
}
+/**
+ * #5575 legacy content: while unclaimed sources hold rows from before trust
+ * tiers, the notice's fix becomes the claim ask (`fix.next: ask_user`, the
+ * user_message explains claiming), unless it already carries the chat
+ * fallback removal. Best-effort: any fault keeps the notice as built.
+ */
+export async function withTrustClaimAsk(engine: BrainEngine, notice: Notice | null): Promise<Notice | null> {
+ if (!notice || (notice.fix?.argv && notice.fix.argv.join(' ') !== DOCTOR_ARGV.join(' '))) return notice;
+ try {
+ const { claimSourcesFix, readUnclaimedLegacySources, CLAIM_USER_MESSAGE } = await import('./trust/claim.ts');
+ if ((await readUnclaimedLegacySources(engine)).unclaimed.length === 0) return notice;
+ return { ...notice, fix: claimSourcesFix(), user_message: CLAIM_USER_MESSAGE };
+ } catch {
+ return notice;
+ }
+}
+
// ── delivery ────────────────────────────────────────────────────────────────
/** notice × brain × channel (× client) already handled in this process: one look per process. */
@@ -418,7 +436,7 @@ export async function takeLocalBehaviorNotice(
const after = laterRelease(await brainBaseline(engine, brainKey, { persist: true, now: opts.now }), localShownThrough(brainKey, channel));
if (compareReleases(BEHAVIOR_NOTICE_SINCE, after) <= 0) return null;
if (claimMarker(brainKey, channel) === 'shown') return null;
- return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { after });
+ return withTrustClaimAsk(engine, behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { after }));
} catch {
if (key) handled.delete(key);
return null;
@@ -472,7 +490,7 @@ export async function takeHttpBehaviorNotice(
const after = laterRelease(baseline, readHttpShown(raw)[client]?.since ?? PREDATES);
if (compareReleases(BEHAVIOR_NOTICE_SINCE, after) <= 0) return null;
try { await engine.setConfig(HTTP_SHOWN_KEY, recordHttpShown(raw, client, new Date(opts.now ?? Date.now()).toISOString())); } catch { /* deliver anyway */ }
- return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { remote: true, after });
+ return withTrustClaimAsk(engine, behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { remote: true, after }));
} catch {
if (key) handled.delete(key);
return null;
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 6209528481..be52dba115 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -96,7 +96,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'protocol': ['--access', '--add', '--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', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
- 'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--brain', '--break-lock', '--client', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
+ 'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--background', '--brain', '--break-lock', '--client', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'recall': ['--accept-pending', '--access', '--add', '--all-subjects', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--purge', '--query', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--apply', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--include-ambiguous', '--json', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--skip', '--slug', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
@@ -129,7 +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': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--since', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
+ 'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--since', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'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'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index af379791cc..b79a16ec7a 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -64,9 +64,10 @@ 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.
+ // #5575: stored trust tier counts, the legacy-row backfill, scan and source claims.
'trust_tiers',
'trust_scan',
+ 'trust_sources_unclaimed',
'credential_projection_pending',
'derived_visibility',
'extractor_facts_expired',
diff --git a/src/core/eligibility/scan.ts b/src/core/eligibility/scan.ts
index 8a7d1e98e3..97d4d85409 100644
--- a/src/core/eligibility/scan.ts
+++ b/src/core/eligibility/scan.ts
@@ -10,6 +10,9 @@
* only makes the row ineligible for proactive injection until the owner
* confirms it. Zero model calls.
*
+ * Refuses (recovery_required) while a claimed source's lift is unfinished
+ * (trust/claim.ts): those legacy rows are about to become owner tier.
+ *
* Bounded and resumable: keyset batches by id per table, with the cursor
* (the detector version it was taken under and the id ceiling it covers:
* the max ids the write gate went live at (`write_gate.scan_baseline`), or,
@@ -28,6 +31,8 @@ import { recordWriteGateReceipt } from '../write-gate-store.ts';
import { WRITE_GATE_SCAN_BASELINE_KEY } from '../write-gate-schema.ts';
import { storedTrustTier, TRUST_TIER_RANK, TRUST_TIERS, type TrustTier } from '../trust/tier.ts';
import { ACTIVATION_TIER_CEILING } from './sql.ts';
+import { opError } from '../ops/contract.ts';
+import { claimPendingSql, TRUST_CLAIM_RESUME_COMMAND } from '../trust/claim-state.ts';
export type ScanTable = 'pages' | 'facts' | 'takes' | 'timeline_entries';
export const SCAN_TABLES: readonly ScanTable[] = ['pages', 'facts', 'takes', 'timeline_entries'];
@@ -135,6 +140,15 @@ export interface TrustScanOptions {
*/
export async function runTrustScan(engine: BrainEngine, opts: TrustScanOptions = {}): Promise<TrustScanReport> {
const batchSize = Math.max(1, Math.min(opts.batchSize ?? DEFAULT_SCAN_BATCH, 10_000));
+ // A claimed source's legacy rows are owner tier once its lift finishes; scanning them first would flag the owner's own notes.
+ const pending = await engine.executeRaw<{ id: string }>(`SELECT s.id FROM sources s WHERE ${claimPendingSql('s')} ORDER BY s.id`);
+ if (pending.length) {
+ throw opError('recovery_required', `Claimed source(s) ${pending.map(r => r.id).join(', ')} have not finished their lift, so the scan would treat the owner's notes as unverified.`,
+ 'Run the fix (it finishes the claim the owner already confirmed), then run the scan again.', {
+ fix: { argv: [...TRUST_CLAIM_RESUME_COMMAND], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Finishes lifting the claimed sources\' legacy rows in resumable batches; nothing goes above "your notes".', verify: { argv: ['gbrain', 'doctor', '--only', 'trust_sources_unclaimed', '--json'] } },
+ });
+ }
const cursor = await currentCursor(engine);
if (!cursor.until) {
cursor.until = {};
diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.ts
index f63d1113b8..fc21865c95 100644
--- a/src/core/trust/backfill.ts
+++ b/src/core/trust/backfill.ts
@@ -34,18 +34,23 @@
* resumePageRevisionBackfill precedent) under the backfill setting, inside
* withCoordinatedWrite for each batch's sources on a managed brain.
*/
+import { createHash } from 'node:crypto';
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 { frontmatterTrustCapsSql } from './channel.ts';
+import { claimedSourceSql, legacyRowSql, notConnectorSourceSql, readLegacyCeilings, type LegacyCeilings } from './claim-state.ts';
import { TRUST_BACKFILL_COMPLETED_KEY, type TrustTable } from './schema.ts';
import { TRUST_TIER_RANK, TRUST_TIERS, isTrustTier, trustRankSql, trustTierFromRankSql, type TrustTier } from './tier.ts';
export { TRUST_BACKFILL_COMPLETED_KEY };
export const TRUST_BACKFILL_COMMAND = 'gbrain trust backfill --resume';
const CHECKPOINT_OP = 'trust-backfill';
+/** The claim lift's own cursor, so it never resumes (or clears) a full backfill's. */
+const CLAIM_CHECKPOINT_OP = 'trust-claim';
const CHECKPOINT_KEY = 'v1';
const DEFAULT_BATCH = 2000;
/** Pages first: facts, takes and timeline rows take their page's classified tier. */
@@ -56,6 +61,14 @@ export interface TrustBackfillOptions {
resume?: boolean;
batchSize?: number;
log?: (line: string) => void;
+ /**
+ * Only rows of these sources (the claim lift, trust/claim.ts): its own
+ * resumable cursor, `write_origin.channel` `trust_claim`, and no global
+ * backfill completion stamp.
+ */
+ sources?: readonly string[];
+ /** Dry run only: project these sources as if claimed. */
+ assumeClaimed?: readonly string[];
}
export type TierCounts = Record<TrustTier, number>;
export interface TrustBackfillTableReport {
@@ -102,8 +115,21 @@ async function readColumns(engine: BrainEngine): Promise<Columns> {
}
/** Builds the rank expressions for one schema shape. Every term yields a rank or NULL (no signal). */
-function classifier(cols: Columns) {
+function classifier(cols: Columns, assumeClaimed: readonly string[] = [], ceilings: LegacyCeilings = null) {
const signals = new Set<string>();
+ /** The source aliased `s` is claimed (or projected as claimed): its rows with no lowering signal are operator_curated. */
+ const claimed = (s: string) => {
+ if (!cols.has('sources', 'config')) return null;
+ signals.add('claimed_source');
+ return assumeClaimed.length
+ ? `(${claimedSourceSql(s)} OR (${s}.id IN (${quoted(assumeClaimed)}) AND ${notConnectorSourceSql(s)}))`
+ : claimedSourceSql(s);
+ };
+ /** A claim lifts only legacy rows (claim-state.ts): `row` is the classified row's alias in `table`. */
+ const claimTerm = (s: string, table: TrustTable, row: string) => {
+ const c = claimed(s);
+ return c ? `CASE WHEN ${c} AND ${legacyRowSql(table, row, ceilings)} THEN ${rank('operator_curated')} END` : null;
+ };
const connector = (sourceAlias: string) => {
if (!cols.has('sources', 'config')) return null;
signals.add('connector_source');
@@ -142,10 +168,22 @@ function classifier(cols: Columns) {
return terms;
};
const least = (terms: string[]) => (terms.length ? `LEAST(${terms.join(', ')})` : 'NULL::int');
+ /**
+ * A page's rule: its signals, and on a claimed source operator_curated lowered by every frontmatter signal
+ * an owner sync would apply (`frontmatterTrustCaps`), so a claim never lifts a captured, clipped, imported
+ * or marked page above what it says it is.
+ */
+ const pageRule = (p: string, s: string, r: string) => {
+ const terms = pageTerms(p, s, r);
+ const c = claimed(s);
+ if (!c) return least(terms);
+ const caps = cols.has('pages', 'frontmatter') ? frontmatterTrustCapsSql(`${p}.frontmatter`) : [];
+ return `CASE WHEN ${c} AND ${legacyRowSql('pages', p, ceilings)} THEN ${least([String(rank('operator_curated')), ...caps, ...terms])} ELSE ${least(terms)} END`;
+ };
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));
+ const rule = pageRule(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) =>
@@ -155,11 +193,12 @@ function classifier(cols: Columns) {
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' };
+ rule: pageRule('x', 's', 'r'), src: 'x.source_id' };
}
if (table === 'facts') {
const terms: string[] = [];
const c = connector('s'); if (c) terms.push(c);
+ const own = claimTerm('s', 'facts', 'x'); if (own) terms.push(own);
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`);
@@ -175,6 +214,7 @@ function classifier(cols: Columns) {
}
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`);
+ const own = claimTerm('ps', table, 'x'); if (own) terms.push(own);
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`);
@@ -186,18 +226,21 @@ function classifier(cols: Columns) {
return { forTable, signals, hasTrust };
}
-async function readCursor(engine: BrainEngine): Promise<Partial<Record<TrustTable, number>>> {
+async function readCursor(engine: BrainEngine, op = CHECKPOINT_OP, key = CHECKPOINT_KEY): 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]);
+ 'SELECT completed_keys AS keys FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [op, 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> {
+async function saveCursor(engine: BrainEngine, cursor: Partial<Record<TrustTable, number>>, op = CHECKPOINT_OP, key = CHECKPOINT_KEY): 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])]);
+ [op, key, JSON.stringify([cursor])]);
}
+/** A claim lift's cursor key: one per set of sources, so lifting another set never skips its rows. */
+const claimCursorKey = (sources: readonly string[]) => createHash('sha256').update([...sources].sort().join('\n')).digest('hex').slice(0, 16);
+
function summarize(mode: TrustBackfillReport['mode'], schema: TrustBackfillReport['schema'], tables: TrustBackfillTableReport[],
signals: Set<string>, status: TrustBackfillReport['status']): TrustBackfillReport {
const projected = zero();
@@ -213,15 +256,17 @@ function summarize(mode: TrustBackfillReport['mode'], schema: TrustBackfillRepor
}
/** 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> {
+async function dryRun(engine: BrainEngine, batch: number, opts: Pick<TrustBackfillOptions, 'sources' | 'assumeClaimed'> = {}): 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 ceilings = cols.has('sources', 'config') ? await readLegacyCeilings(tx).catch(() => null) : null;
+ const { forTable, signals, hasTrust } = classifier(cols, opts.assumeClaimed, ceilings);
const tables: TrustBackfillTableReport[] = [];
for (const table of BACKFILL_ORDER) {
if (!cols.table(table)) continue;
- const { from, rule } = forTable(table);
+ const { from, rule, src } = forTable(table);
+ const only = opts.sources ? ` AND ${src} IN (${quoted(opts.sources)})` : '';
const ruleTier = trustTierFromRankSql(rule);
const report: TrustBackfillTableReport = { table, rows: 0, ...(hasTrust ? { current: zero() } : {}), projected: zero() };
for (let after = 0; ;) {
@@ -229,7 +274,7 @@ async function dryRun(engine: BrainEngine, batch: number): Promise<TrustBackfill
`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
+ FROM ${from} WHERE x.id > $1${only} ORDER BY x.id LIMIT $2) b
GROUP BY current, tier`, [after, batch]);
if (rows.length === 0) break;
for (const row of rows) {
@@ -248,7 +293,8 @@ async function dryRun(engine: BrainEngine, batch: number): Promise<TrustBackfill
export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillOptions = {}): Promise<TrustBackfillReport> {
const batch = opts.batchSize ?? DEFAULT_BATCH;
- if (opts.dryRun) return dryRun(engine, batch);
+ if (opts.dryRun) return dryRun(engine, batch, opts);
+ if (opts.sources && opts.sources.length === 0) return summarize('apply', 'trust_columns', [], new Set(), 'complete');
const log = opts.log ?? ((line: string) => process.stderr.write(`${line}\n`));
const cols = await readColumns(engine);
if (!cols.has('pages', 'trust_tier')) {
@@ -258,35 +304,41 @@ export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillO
why: 'Applies the pending schema migrations, including the trust tier columns.', verify: { argv: ['gbrain', 'doctor', '--json'] } },
});
}
- const { forTable, signals } = classifier(cols);
+ const { forTable, signals } = classifier(cols, [], await readLegacyCeilings(engine).catch(() => null));
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 scoped = opts.sources !== undefined;
+ const op = scoped ? CLAIM_CHECKPOINT_OP : CHECKPOINT_OP;
+ const key = scoped ? claimCursorKey(opts.sources!) : CHECKPOINT_KEY;
+ const origin = JSON.stringify({ channel: scoped ? 'trust_claim' : 'trust_backfill' });
+ const cursor = opts.resume || scoped ? await readCursor(engine, op, key) : {};
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));
+ const ids = (await engine.executeRaw<{ id: number | string }>(scoped
+ ? `SELECT x.id FROM ${from} WHERE x.id > $1 AND x.trust_tier = 'unknown' AND ${src} = ANY($3::text[]) ORDER BY x.id LIMIT $2`
+ : `SELECT id FROM ${table} WHERE id > $1 AND trust_tier = 'unknown' ORDER BY id LIMIT $2`, scoped ? [after, batch, [...opts.sources!]] : [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);
+ UPDATE ${table} t SET trust_tier = b.tier, write_origin = COALESCE(t.write_origin, $2::text::jsonb)
+ FROM b WHERE t.id = b.id AND t.trust_tier = 'unknown' AND b.tier <> 'unknown' RETURNING t.id`, [ids, origin])).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}`);
+ await saveCursor(engine, cursor, op, key);
+ log(`[trust ${scoped ? 'claim' : '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.executeRaw('DELETE FROM op_checkpoints WHERE op = $1 AND fingerprint = $2', [op, key]);
+ if (scoped) return summarize('apply', 'trust_columns', tables, signals, 'complete');
await engine.setConfig(TRUST_BACKFILL_COMPLETED_KEY, new Date().toISOString());
const counts = await readTrustTierCounts(engine);
for (const t of tables) {
diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.ts
index 0d3f060f04..e8b5e47570 100644
--- a/src/core/trust/channel.ts
+++ b/src/core/trust/channel.ts
@@ -25,7 +25,7 @@ import type { BrainEngine } from '../engine.ts';
import type { WriteRequest } from '../persistence/model.ts';
import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
import {
- OWNER_TIER_FLOOR, compareTrust, contentOriginTier, effectiveWriteTrust, isTrustTier, minTrust,
+ OWNER_TIER_FLOOR, TRUST_TIER_RANK, compareTrust, contentOriginTier, effectiveWriteTrust, isTrustTier, minTrust, trustRankSql,
type TrustTier, type WriteTrust,
} from './tier.ts';
@@ -137,6 +137,31 @@ export function frontmatterTrustCaps(frontmatter: Record<string, unknown> | null
return caps;
}
+/**
+ * `frontmatterTrustCaps` as SQL over a jsonb frontmatter expression: one rank
+ * term per signal (NULL when it does not apply), for `LEAST(...)` in the trust
+ * backfill of claimed sources (trust/claim.ts). `fm` is a trusted alias or
+ * column expression, never caller input; every literal comes from the lists
+ * above. Kept in step with `frontmatterTrustCaps` by test/trust-claim.test.ts.
+ */
+export function frontmatterTrustCapsSql(fm: string): string[] {
+ const list = (values: readonly string[]) => values.map(v => `'${v.replace(/'/g, "''")}'`).join(',');
+ const text = (key: string, base = fm) => `(CASE WHEN jsonb_typeof(${base}->'${key}') = 'string' THEN NULLIF(btrim(${base}->>'${key}', E' \\t\\n\\r'), '') END)`;
+ const stamp = (key: string) => `CASE WHEN ${text(key)} IN (${list(EXTERNAL_CAPTURE_KINDS)}) THEN ${TRUST_TIER_RANK.external_untrusted}
+ WHEN ${text(key)} LIKE 'mcp:%' OR ${text(key)} IN (${list(AGENT_CAPTURE_KINDS)}) THEN ${TRUST_TIER_RANK.agent_written}
+ WHEN ${text(key)} LIKE 'connector:%' OR ${text(key)} IN (${list(CONNECTOR_SOURCE_KINDS)}) THEN ${TRUST_TIER_RANK.external_untrusted} END`;
+ return [
+ `CASE WHEN jsonb_typeof(${fm}->'trust_tier') = 'string' THEN NULLIF(${trustRankSql(`(${fm}->>'trust_tier')`)}, 0) END`,
+ ...['source_kind', 'ingested_via', 'captured_via'].map(stamp),
+ `CASE WHEN jsonb_typeof(${fm}->'transcript_import') IN ('object', 'array') THEN
+ CASE WHEN lower(${text('harness', `(${fm}->'transcript_import')`)}) IN (${list(OWN_SESSION_HARNESSES)}) THEN ${TRUST_TIER_RANK.agent_written} ELSE ${TRUST_TIER_RANK.external_untrusted} END END`,
+ `CASE WHEN ${text('source_url')} IS NOT NULL AND (${text('clipped_at')} IS NOT NULL OR ${text('clipper')} IS NOT NULL
+ OR ${text('captured_via')} = 'clipper' OR ${text('type')} = 'clipping') THEN ${TRUST_TIER_RANK.external_untrusted} END`,
+ `CASE WHEN ${text('provenance')} = 'auto-extracted' OR ${fm}->'dream_generated' = 'true'::jsonb OR ${text('dream_generated')} = 'true'
+ THEN ${TRUST_TIER_RANK.agent_written} END`,
+ ];
+}
+
/** A per-source default set by `gbrain sources set-trust` (sources.config.trust_tier), clamped to operator_curated. */
export function sourceDefaultTier(config: Record<string, unknown> | null | undefined): TrustTier {
const value = config?.trust_tier;
diff --git a/src/core/trust/claim-notice.ts b/src/core/trust/claim-notice.ts
new file mode 100644
index 0000000000..53735998e8
--- /dev/null
+++ b/src/core/trust/claim-notice.ts
@@ -0,0 +1,46 @@
+/**
+ * `gbrain post-upgrade` (#5575, legacy content): while unclaimed sources hold
+ * rows from before trust tiers, an [AGENT] ask_user block asks the agent to
+ * relay what claiming means; only the owner claims, at a terminal
+ * (`gbrain trust claim-sources`, trust/claim.ts). It repeats on every
+ * post-upgrade until nothing is left to claim. A claim whose lift did not
+ * finish gets the resume command instead. Never runs the claim or the scan.
+ * Best-effort: never blocks the upgrade.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { agentBlock } from '../agent-markers.ts';
+import { CLAIM_USER_MESSAGE, readUnclaimedLegacySources } from './claim.ts';
+import { TRUST_CLAIM_COMMAND, TRUST_CLAIM_RESUME_COMMAND } from './claim-state.ts';
+
+export async function trustClaimUpgradeNotice(engine: Pick<BrainEngine, 'executeRaw'>): Promise<string[] | null> {
+ const { unclaimed, pending } = await readUnclaimedLegacySources(engine);
+ const verify = 'gbrain doctor --only trust_sources_unclaimed --json';
+ if (pending.length) {
+ return ['', ...agentBlock({
+ why: `A claim of ${pending.join(', ')} did not finish lifting its legacy rows.`,
+ actor: 'agent', next: `run: ${TRUST_CLAIM_RESUME_COMMAND.join(' ')}`, verify,
+ }).trimEnd().split('\n'), ''];
+ }
+ if (!unclaimed.length) return null;
+ const rows = unclaimed.reduce((n, s) => n + s.legacy_unknown, 0);
+ return ['', ...agentBlock({
+ ask: `Are ${unclaimed.map(s => s.id).join(', ')} the user's own notes? If so, the user claims them in a terminal.`,
+ why: `${rows} row(s) written before trust tiers in ${unclaimed.length} unclaimed source(s) read as "unverified origin". New agent-written content is already held back `
+ + 'when it reads as instructions; older content is covered only after the user claims their sources and agrees to gbrain trust scan, which nothing runs on its own.',
+ actor: 'user', next: `ask_user: ${TRUST_CLAIM_COMMAND.join(' ')}`,
+ if_yes: `Tell the user to run ${TRUST_CLAIM_COMMAND.join(' ')} in a terminal on the brain host; it asks them to type each source id (--yes never claims). Preview: gbrain trust claim-sources --dry-run --json.`,
+ if_no: 'Run nothing; those rows stay "unverified origin" and nothing is withheld unless the user later agrees to gbrain trust scan.',
+ verify,
+ }, { showUser: CLAIM_USER_MESSAGE }).trimEnd().split('\n'), ''];
+}
+
+export async function printTrustClaimUpgradeNotice(engine: Pick<BrainEngine, 'executeRaw'>, log: (line: string) => void = console.log): Promise<boolean> {
+ try {
+ const lines = await trustClaimUpgradeNotice(engine);
+ if (!lines) return false;
+ for (const line of lines) log(line);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/trust/claim-state.ts b/src/core/trust/claim-state.ts
new file mode 100644
index 0000000000..4cee3563f8
--- /dev/null
+++ b/src/core/trust/claim-state.ts
@@ -0,0 +1,88 @@
+/**
+ * Claimed sources (#5575, legacy content): which sources the owner has
+ * claimed as their own notes with `gbrain trust claim-sources`
+ * (trust/claim.ts). A claim lives in `sources.config` beside the
+ * `sources set-trust` default it sets:
+ *
+ * trust_tier 'operator_curated' (the per-source default)
+ * trust_claimed_at when the owner confirmed the claim
+ * trust_claim_lifted_at when the claim's backfill finished for the source
+ *
+ * A source is claimed while both of the first two hold and it is not a
+ * connector source; `sources set-trust` to a lower tier or `--clear` drops
+ * the claim. A claimed source whose lift has not finished is "pending": its
+ * legacy `unknown` rows are treated as owner tier by the scan, explain and
+ * review, because the lift will make them so (or lower, by their own signals).
+ *
+ * "Legacy" rows are the ones that existed when trust tiers and the write gate
+ * arrived: ids at or below each table's max id recorded then
+ * (`write_gate.scan_baseline`, migration v221; zero on a brain created
+ * since). A row a writer stored as `unknown` later is not legacy, so a claim
+ * never lifts it and a fresh brain never reads as unclaimed.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';
+import { WRITE_GATE_SCAN_BASELINE_KEY } from '../write-gate-schema.ts';
+import { OWNER_TIER_FLOOR } from './tier.ts';
+
+export const TRUST_CLAIMED_AT_KEY = 'trust_claimed_at';
+export const TRUST_CLAIM_LIFTED_AT_KEY = 'trust_claim_lifted_at';
+export const TRUST_CLAIM_COMMAND = ['gbrain', 'trust', 'claim-sources'] as const;
+export const TRUST_CLAIM_RESUME_COMMAND = ['gbrain', 'trust', 'claim-sources', '--resume'] as const;
+
+const connectorList = CONNECTOR_SOURCE_KINDS.map(k => `'${k}'`).join(',');
+
+/** SQL predicate: the `sources` row aliased `alias` is not a connector source. `alias` is a trusted alias, never caller input. */
+export function notConnectorSourceSql(alias: string): string {
+ return `COALESCE(${alias}.config->>'kind', '') NOT IN (${connectorList})`;
+}
+
+/** SQL predicate: the `sources` row aliased `alias` is a claimed source. */
+export function claimedSourceSql(alias: string): string {
+ return `(${alias}.config ? '${TRUST_CLAIMED_AT_KEY}' AND ${alias}.config->>'trust_tier' = '${OWNER_TIER_FLOOR}' AND ${notConnectorSourceSql(alias)})`;
+}
+
+/** SQL predicate: a claimed source whose lift has not finished. */
+export function claimPendingSql(alias: string): string {
+ return `(${claimedSourceSql(alias)} AND NOT (${alias}.config ? '${TRUST_CLAIM_LIFTED_AT_KEY}'))`;
+}
+
+export function isConnectorConfig(config: Record<string, unknown> | null | undefined): boolean {
+ return (CONNECTOR_SOURCE_KINDS as readonly unknown[]).includes(config?.kind);
+}
+
+export function isClaimedConfig(config: Record<string, unknown> | null | undefined): boolean {
+ return typeof config?.[TRUST_CLAIMED_AT_KEY] === 'string' && config?.trust_tier === OWNER_TIER_FLOOR && !isConnectorConfig(config);
+}
+
+/** The config after `sources set-trust`: any value but operator_curated (or --clear) ends a claim. */
+export function dropClaimUnlessOwnerDefault(config: Record<string, unknown>): Record<string, unknown> {
+ if (config.trust_tier === OWNER_TIER_FLOOR) return config;
+ const { [TRUST_CLAIMED_AT_KEY]: _claimed, [TRUST_CLAIM_LIFTED_AT_KEY]: _lifted, ...rest } = config;
+ return rest;
+}
+
+export type LegacyCeilings = Partial<Record<'pages' | 'facts' | 'takes' | 'timeline_entries', number>> | null;
+
+/** Each table's max id when the trust migrations ran, or null (no baseline recorded: every row counts as legacy). */
+export async function readLegacyCeilings(engine: Pick<BrainEngine, 'executeRaw'>): Promise<LegacyCeilings> {
+ const [row] = await engine.executeRaw<{ value: string }>('SELECT value FROM config WHERE key = $1', [WRITE_GATE_SCAN_BASELINE_KEY]);
+ if (!row) return null;
+ try {
+ const until = (JSON.parse(row.value) as { until?: Record<string, unknown> }).until;
+ if (!until || typeof until !== 'object') return null;
+ const out: NonNullable<LegacyCeilings> = {};
+ for (const table of ['pages', 'facts', 'takes', 'timeline_entries'] as const) {
+ const n = Number(until[table]);
+ out[table] = Number.isFinite(n) ? Math.trunc(n) : 0;
+ }
+ return out;
+ } catch {
+ return null;
+ }
+}
+
+/** SQL predicate: the `table` row aliased `alias` is a legacy row. `alias` is a trusted alias; the ceiling is an integer. */
+export function legacyRowSql(table: 'pages' | 'facts' | 'takes' | 'timeline_entries', alias: string, ceilings: LegacyCeilings): string {
+ return ceilings ? `${alias}.id <= ${Math.trunc(ceilings[table] ?? 0)}` : 'TRUE';
+}
diff --git a/src/core/trust/claim.ts b/src/core/trust/claim.ts
new file mode 100644
index 0000000000..a7d85697a5
--- /dev/null
+++ b/src/core/trust/claim.ts
@@ -0,0 +1,226 @@
+/**
+ * `gbrain trust claim-sources` (#5575, legacy content): the owner claims
+ * their own sources once, at upgrade. Rows written before trust tiers have
+ * no provenance, so they project to `unknown` and an old brain reads as
+ * almost entirely "unverified origin". Claiming a source says "this is mine":
+ *
+ * - the source gets the per-source default operator_curated (the
+ * `sources set-trust` store, claim-state.ts) plus a claim receipt;
+ * - its legacy `unknown` rows are lifted through the trust backfill
+ * (backfill.ts, the backfill setting CEO-10 allows: unknown ->
+ * operator_curated, never user_confirmed). A row with a lowering signal
+ * keeps it: mcp:* and capture stamps, transcript imports, clipped pages,
+ * connector origins, extraction and dream provenance, journaled agent
+ * writes and the lower-only trust_tier marker. Never above operator_curated.
+ *
+ * Connector sources (google, github) cannot be claimed: their text is third
+ * party. Claiming needs the owner at a terminal typing each source id
+ * (trust/confirm.ts; `--yes` never counts); without one the command refuses
+ * with an ask_user fix. The lift is bounded (keyset batches), resumable
+ * (`--resume`, its own cursor) and receipted (each lifted row's
+ * `write_origin.channel` is `trust_claim`; the source records when it was
+ * claimed and when its lift finished). `--dry-run` is read-only.
+ *
+ * Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the
+ * behavior-change notice ask the user while unclaimed sources hold legacy
+ * rows (`readUnclaimedLegacySources`).
+ */
+import type { Action } from '../agent-output.ts';
+import type { BrainEngine } from '../engine.ts';
+import { opError } from '../ops/contract.ts';
+import { normalizeSourceConfig, parseSourceConfig } from '../sources-load.ts';
+import { runTrustBackfill, type TierCounts } from './backfill.ts';
+import {
+ claimedSourceSql, isClaimedConfig, isConnectorConfig, legacyRowSql, notConnectorSourceSql, readLegacyCeilings,
+ TRUST_CLAIM_COMMAND, TRUST_CLAIM_LIFTED_AT_KEY, TRUST_CLAIMED_AT_KEY,
+} from './claim-state.ts';
+import { OWNER_TIER_FLOOR, TRUST_TIERS, isTrustTier } from './tier.ts';
+
+export type ClaimBlocker = 'connector' | 'archived' | 'claimed' | 'no_legacy_rows';
+
+export interface ClaimSource {
+ id: string;
+ name: string;
+ local_path: string | null;
+ remote_url: string | null;
+ kind: string | null;
+ pages: number;
+ /** Rows (pages, facts, takes, timeline entries) still at `unknown`: legacy rows a claim would lift. */
+ legacy_unknown: number;
+ claimed: boolean;
+ /** Claimed, but the lift has not finished (`--resume` finishes it). */
+ pending: boolean;
+ /** Stored tiers now (absent before the trust migration). */
+ current?: TierCounts;
+ /** Tiers after a claim and its lift: unknown rows at operator_curated unless their own signals say lower. */
+ projected_if_claimed: TierCounts;
+ claimable: boolean;
+ blocker?: ClaimBlocker;
+}
+
+export interface ClaimSourcesListing { schema: 'trust_columns' | 'pre_trust'; sources: ClaimSource[] }
+
+const zero = (): TierCounts => Object.fromEntries(TRUST_TIERS.map(tier => [tier, 0])) as TierCounts;
+const add = (into: TierCounts, from: TierCounts | undefined) => { if (from) for (const tier of TRUST_TIERS) into[tier] += from[tier]; };
+
+interface SourceRow { id: string; name: string; local_path: string | null; config: unknown; archived: boolean }
+
+async function sourceRows(engine: BrainEngine): Promise<SourceRow[]> {
+ return engine.executeRaw<SourceRow>('SELECT id, name, local_path, config, archived FROM sources ORDER BY id');
+}
+
+/**
+ * Every source with its page count, legacy unknown rows and the tier mix a
+ * claim would produce, in one read-only pass per source (the backfill dry run
+ * scoped to it, projected as claimed). Works before the trust migration.
+ */
+export async function listClaimSources(engine: BrainEngine, opts: { batchSize?: number } = {}): Promise<ClaimSourcesListing> {
+ let schema: ClaimSourcesListing['schema'] = 'trust_columns';
+ const out: ClaimSource[] = [];
+ const legacyCounts = await legacyUnknownBySource(engine).catch(() => null);
+ for (const row of await sourceRows(engine)) {
+ const config = parseSourceConfig(row.config);
+ const report = await runTrustBackfill(engine, { dryRun: true, sources: [row.id], assumeClaimed: [row.id], ...(opts.batchSize ? { batchSize: opts.batchSize } : {}) });
+ schema = report.schema;
+ const projected = zero();
+ const current = report.schema === 'trust_columns' ? zero() : undefined;
+ for (const t of report.tables) { add(projected, t.projected); add(current as TierCounts, t.current); }
+ const legacy = report.schema === 'pre_trust' || !legacyCounts ? report.rows : legacyCounts.get(row.id) ?? 0;
+ const claimed = isClaimedConfig(config);
+ const pending = claimed && typeof config[TRUST_CLAIM_LIFTED_AT_KEY] !== 'string';
+ const blocker: ClaimBlocker | undefined = isConnectorConfig(config) ? 'connector' : row.archived ? 'archived'
+ : claimed ? 'claimed' : legacy === 0 ? 'no_legacy_rows' : undefined;
+ out.push({
+ id: row.id, name: row.name, local_path: row.local_path,
+ remote_url: typeof config.remote_url === 'string' ? config.remote_url : null,
+ kind: typeof config.kind === 'string' ? config.kind : null,
+ pages: report.tables.find(t => t.table === 'pages')?.rows ?? 0,
+ legacy_unknown: legacy, claimed, pending,
+ ...(current ? { current } : {}), projected_if_claimed: projected,
+ claimable: !blocker, ...(blocker ? { blocker } : {}),
+ });
+ }
+ return { schema, sources: out };
+}
+
+/** Records the claim on each source (per-source default operator_curated plus the receipt). Refuses connector and archived sources. */
+export async function recordSourceClaims(engine: BrainEngine, ids: readonly string[], now = new Date()): Promise<void> {
+ for (const id of ids) {
+ const [row] = await engine.executeRaw<{ config: unknown; archived: boolean }>('SELECT config, archived FROM sources WHERE id = $1', [id]);
+ if (!row) throw opError('unknown_source', `Source "${id}" does not exist.`, 'List sources with gbrain trust claim-sources --dry-run.');
+ const config = parseSourceConfig(row.config);
+ if (isConnectorConfig(config)) throw connectorRefusal(id, String(config.kind));
+ if (row.archived) throw opError('unknown_source', `Source "${id}" is archived.`, 'Restore it first (gbrain sources restore), or leave it unclaimed.');
+ const next: Record<string, unknown> = { ...config, trust_tier: OWNER_TIER_FLOOR, [TRUST_CLAIMED_AT_KEY]: now.toISOString() };
+ delete next[TRUST_CLAIM_LIFTED_AT_KEY];
+ await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(normalizeSourceConfig(next)), id]);
+ }
+}
+
+export function connectorRefusal(id: string, kind: string) {
+ return opError('invalid_params', `Source "${id}" is a ${kind} connector source, so it cannot be claimed as your own notes.`,
+ 'Claim only sources that hold your own files; connector text comes from other people and stays "external, untrusted".');
+}
+
+export interface ClaimLiftReport {
+ sources: Array<{ id: string; tiers: TierCounts }>;
+ /** Rows the lift moved off `unknown`, per table. */
+ updated: Record<string, number>;
+ /** Rows in the lifted sources below operator_curated after the lift (their own signals kept them lower). */
+ kept_lower: number;
+}
+
+/**
+ * Lifts every claimed source whose lift has not finished, through the
+ * backfill setting in bounded, resumable batches, then stamps each source's
+ * lift receipt. Idempotent: a finished source is skipped.
+ */
+export async function liftClaimedSources(engine: BrainEngine, opts: { batchSize?: number; log?: (line: string) => void } = {}): Promise<ClaimLiftReport> {
+ const pending = (await sourceRows(engine))
+ .filter(r => { const c = parseSourceConfig(r.config); return isClaimedConfig(c) && typeof c[TRUST_CLAIM_LIFTED_AT_KEY] !== 'string'; })
+ .map(r => r.id);
+ if (pending.length === 0) return { sources: [], updated: {}, kept_lower: 0 };
+ const report = await runTrustBackfill(engine, { sources: pending, ...(opts.batchSize ? { batchSize: opts.batchSize } : {}), log: opts.log ?? (() => {}) });
+ const at = new Date().toISOString();
+ for (const id of pending) {
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id = $1', [id]);
+ const config = parseSourceConfig(row?.config);
+ if (!isClaimedConfig(config)) continue;
+ await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2',
+ [JSON.stringify(normalizeSourceConfig({ ...config, [TRUST_CLAIM_LIFTED_AT_KEY]: at })), id]);
+ }
+ const tiers = new Map(pending.map(id => [id, zero()]));
+ const counts = await engine.executeRaw<{ source_id: string; tier: string; n: number | string }>(
+ `SELECT source_id, tier, sum(n)::bigint AS n FROM (
+ SELECT p.source_id, p.trust_tier AS tier, count(*) AS n FROM pages p WHERE p.source_id = ANY($1::text[]) GROUP BY 1, 2
+ UNION ALL SELECT f.source_id, f.trust_tier, count(*) FROM facts f WHERE f.source_id = ANY($1::text[]) GROUP BY 1, 2
+ UNION ALL SELECT p.source_id, t.trust_tier, count(*) FROM takes t JOIN pages p ON p.id = t.page_id WHERE p.source_id = ANY($1::text[]) GROUP BY 1, 2
+ UNION ALL SELECT p.source_id, te.trust_tier, count(*) FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE p.source_id = ANY($1::text[]) GROUP BY 1, 2
+ ) c GROUP BY source_id, tier`, [pending]);
+ let keptLower = 0;
+ for (const c of counts) {
+ const tier = isTrustTier(c.tier) ? c.tier : 'unknown';
+ tiers.get(c.source_id)![tier] += Number(c.n);
+ if (tier !== OWNER_TIER_FLOOR && tier !== 'user_confirmed') keptLower += Number(c.n);
+ }
+ return {
+ sources: pending.map(id => ({ id, tiers: tiers.get(id)! })),
+ updated: Object.fromEntries(report.tables.map(t => [t.table, t.updated ?? 0])),
+ kept_lower: keptLower,
+ };
+}
+
+export interface UnclaimedLegacySources {
+ /** Unclaimed, non-connector, live sources holding rows at `unknown`, with that count. */
+ unclaimed: Array<{ id: string; legacy_unknown: number }>;
+ /** Claimed sources whose lift has not finished. */
+ pending: string[];
+}
+
+/**
+ * Doctor, post-upgrade and the behavior-change notice: the sources a claim
+ * would help. A brain before the trust migration throws (callers report it
+ * as pre-trust); a fresh or empty brain has none.
+ */
+export async function readUnclaimedLegacySources(engine: Pick<BrainEngine, 'executeRaw'>): Promise<UnclaimedLegacySources> {
+ const legacy = await legacyUnknownBySource(engine);
+ const rows = await engine.executeRaw<{ id: string; claimed: boolean; lifted: boolean }>(
+ `SELECT s.id, ${claimedSourceSql('s')} AS claimed, (s.config ? '${TRUST_CLAIM_LIFTED_AT_KEY}') AS lifted
+ FROM sources s WHERE NOT s.archived AND ${notConnectorSourceSql('s')} ORDER BY s.id`);
+ return {
+ unclaimed: rows.filter(r => !r.claimed && (legacy.get(r.id) ?? 0) > 0).map(r => ({ id: r.id, legacy_unknown: legacy.get(r.id)! })),
+ pending: rows.filter(r => r.claimed && !r.lifted).map(r => r.id),
+ };
+}
+
+/** Legacy rows (claim-state.ts) still at `unknown`, per source, across pages, facts, takes and timeline entries. */
+async function legacyUnknownBySource(engine: Pick<BrainEngine, 'executeRaw'>): Promise<Map<string, number>> {
+ const ceilings = await readLegacyCeilings(engine);
+ const rows = await engine.executeRaw<{ source_id: string; n: number | string }>(
+ `SELECT source_id, sum(n)::bigint AS n FROM (
+ SELECT p.source_id, count(*) AS n FROM pages p WHERE p.trust_tier = 'unknown' AND p.deleted_at IS NULL AND ${legacyRowSql('pages', 'p', ceilings)} GROUP BY 1
+ UNION ALL SELECT f.source_id, count(*) FROM facts f WHERE f.trust_tier = 'unknown' AND ${legacyRowSql('facts', 'f', ceilings)} GROUP BY 1
+ UNION ALL SELECT p.source_id, count(*) FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.trust_tier = 'unknown' AND ${legacyRowSql('takes', 't', ceilings)} GROUP BY 1
+ UNION ALL SELECT p.source_id, count(*) FROM timeline_entries te JOIN pages p ON p.id = te.page_id WHERE te.trust_tier = 'unknown' AND ${legacyRowSql('timeline_entries', 'te', ceilings)} GROUP BY 1
+ ) u GROUP BY source_id`);
+ return new Map(rows.map(r => [r.source_id, Number(r.n)]));
+}
+
+export const CLAIM_USER_MESSAGE = 'Your older notes were saved before gbrain tracked where memory comes from, so they read as "unverified origin". '
+ + 'Claiming a source tells gbrain those files are your own notes: they become "your notes", except pages that say they were captured, '
+ + 'clipped, imported or written by an agent, which keep their lower trust. Connector sources (Gmail, Calendar, GitHub) cannot be claimed. '
+ + 'To claim, run `gbrain trust claim-sources` in a terminal on the brain host; it shows each source and asks you to type its id.';
+
+/**
+ * The ask for an unclaimed brain: relay `user_message`; only the user can
+ * claim (the command needs them at a terminal typing each source id).
+ */
+export function claimSourcesFix(verifyCheck = 'trust_sources_unclaimed'): Action {
+ return {
+ argv: [...TRUST_CLAIM_COMMAND], consent: ['destructive'], actor: 'agent', requires_exclusive: false,
+ why: 'Claiming raises legacy rows of the sources the owner confirms from "unverified origin" to "your notes" (never to "confirmed by you"); it is the owner\'s decision and needs them at a terminal.',
+ user_message: CLAIM_USER_MESSAGE,
+ preview_argv: [...TRUST_CLAIM_COMMAND, '--dry-run', '--json'],
+ verify: { argv: ['gbrain', 'doctor', '--only', verifyCheck, '--json'] },
+ };
+}
diff --git a/src/core/trust/review.ts b/src/core/trust/review.ts
index 8d15117108..fa0794c852 100644
--- a/src/core/trust/review.ts
+++ b/src/core/trust/review.ts
@@ -21,7 +21,8 @@ import { currentHoldStore, trustKillSwitchState } from './owner-actions.ts';
import { getTrustProposal, listTrustProposals, pendingTrustProposalsFor, trustProposalRef, type TrustProposalAction, type TrustProposalRow } from './proposals.ts';
import { lowerPageState, readPageTrustState } from './page-handlers.ts';
import { formatTrustRef, pageRef, parseTrustRef, resolvePageRef } from './refs.ts';
-import { storedTrustTier, trustLabel, type TrustTier } from './tier.ts';
+import { OWNER_TIER_FLOOR, storedTrustTier, trustLabel, type TrustTier } from './tier.ts';
+import { claimPendingSql, TRUST_CLAIM_RESUME_COMMAND } from './claim-state.ts';
import { listTrustAllowRules, type TrustAllowRule } from './allow-rules.ts';
import { isQuarantined } from '../quarantine.ts';
@@ -140,6 +141,7 @@ async function standingPreferences(engine: BrainEngine, filter: TrustReviewFilte
const rows = await engine.executeRaw<{ id: number; source_id: string; kind: string; fact: string; trust_tier: string; slug: string | null; created_at: string }>(
`SELECT f.id, f.source_id, f.kind, f.fact, f.trust_tier, f.source_markdown_slug AS slug, f.created_at FROM facts f
WHERE f.kind IN ('preference', 'commitment') AND f.trust_tier IN ('agent_written', 'unknown', 'external_untrusted') AND f.expired_at IS NULL
+ AND NOT (f.trust_tier = 'unknown' AND EXISTS (SELECT 1 FROM sources cs WHERE cs.id = f.source_id AND ${claimPendingSql('cs')}))
AND ($1::text IS NULL OR f.source_id = $1) AND ($2::timestamptz IS NULL OR f.created_at >= $2)
AND EXISTS (SELECT 1 FROM write_gate_receipts r WHERE r.target_table = 'facts' AND r.target_id = f.id::text
AND r.verdict = 'flag' AND 'standing_instruction' = ANY(r.reason_families))
@@ -247,6 +249,21 @@ export interface TrustExplanation {
pending_proposals: Array<{ ref: string; action: string; commands: string[][] }>;
activation: string;
text?: string;
+ /** The row is still `unknown` in a source the owner claimed whose lift has not finished: shown as owner tier. */
+ claimed_source?: 'lift_pending';
+}
+
+/**
+ * A legacy `unknown` row in a claimed source whose lift has not finished is
+ * labeled and explained as owner tier: the lift makes it so (or lower, by its
+ * own signals; `gbrain trust claim-sources --resume` finishes it).
+ */
+async function claimView(engine: BrainEngine, sourceId: string, tier: TrustTier): Promise<{ tier: TrustTier; label: string; claimed_source?: 'lift_pending' }> {
+ if (tier !== 'unknown') return { tier, label: trustLabel(tier) };
+ const [pending] = await engine.executeRaw<{ id: string }>(`SELECT s.id FROM sources s WHERE s.id = $1 AND ${claimPendingSql('s')}`, [sourceId]);
+ return pending
+ ? { tier: OWNER_TIER_FLOOR, label: `${trustLabel(OWNER_TIER_FLOOR)} (claimed source; finish with ${TRUST_CLAIM_RESUME_COMMAND.join(' ')})`, claimed_source: 'lift_pending' }
+ : { tier, label: trustLabel(tier) };
}
// The write gate receipts for one row (write_gate_receipts), newest first.
@@ -299,10 +316,12 @@ export async function explainTrust(engine: BrainEngine, refOrQuery: string, opts
const [row] = await engine.executeRaw<{ source_id: string; trust_tier: string; write_origin: unknown; text: string }>(sql, [ref.id]);
if (!row) throw opError('not_found', `No ${ref.kind} ${formatTrustRef(ref)}.`, 'Check the ref; gbrain trust review lists items.');
const tier = storedTrustTier(row.trust_tier);
+ const view = await claimView(engine, row.source_id, tier);
const table = ref.kind === 'fact' ? 'facts' : 'takes';
const gate = await gateReceipts(engine, table, ref.id);
- return [{ ref: formatTrustRef(ref), kind: ref.kind, source_id: row.source_id, tier, label: trustLabel(tier), write_origin: originOf(row.write_origin),
- gate, pending_proposals: await proposalsFor(engine, table, ref.id), activation: await activationNote(engine, tier, gate, false), text: snippet(row.text, 200) }];
+ return [{ ref: formatTrustRef(ref), kind: ref.kind, source_id: row.source_id, tier, label: view.label, write_origin: originOf(row.write_origin),
+ gate, pending_proposals: await proposalsFor(engine, table, ref.id), activation: await activationNote(engine, view.tier, gate, false), text: snippet(row.text, 200),
+ ...(view.claimed_source ? { claimed_source: view.claimed_source } : {}) }];
}
case 'page': {
let resolved;
@@ -314,8 +333,10 @@ export async function explainTrust(engine: BrainEngine, refOrQuery: string, opts
const [row] = await engine.executeRaw<{ write_origin: unknown }>('SELECT write_origin FROM pages WHERE id = $1', [state.pageId]);
const gate = await gateReceipts(engine, 'pages', state.pageId);
const quarantined = isQuarantined(state.snapshot.page.frontmatter);
- return [{ ref: pageRef(sourceId, slug), kind: 'page', source_id: sourceId, tier: state.tier, label: trustLabel(state.tier), write_origin: originOf(row?.write_origin),
- gate, quarantined, pending_proposals: await proposalsFor(engine, 'pages', state.pageId), activation: await activationNote(engine, state.tier, gate, quarantined) }];
+ const view = await claimView(engine, sourceId, state.tier);
+ return [{ ref: pageRef(sourceId, slug), kind: 'page', source_id: sourceId, tier: state.tier, label: view.label, write_origin: originOf(row?.write_origin),
+ gate, quarantined, pending_proposals: await proposalsFor(engine, 'pages', state.pageId), activation: await activationNote(engine, view.tier, gate, quarantined),
+ ...(view.claimed_source ? { claimed_source: view.claimed_source } : {}) }];
}
case 'hold': {
const hold = await currentHoldStore().get(engine, ref.id);
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 1ac718373f..b11d3480c0 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -1779,6 +1779,17 @@
"name": "trust_scan",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "legacy_unknown": 0,
+ "pending": [],
+ "unclaimed": []
+ },
+ "message": "No unclaimed source holds rows from before trust tiers.",
+ "name": "trust_sources_unclaimed",
+ "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 57cf3d20d8..4ff179c0b4 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -1856,6 +1856,17 @@
"name": "trust_scan",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "legacy_unknown": 0,
+ "pending": [],
+ "unclaimed": []
+ },
+ "message": "No unclaimed source holds rows from before trust tiers.",
+ "name": "trust_sources_unclaimed",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 5f00db7729..38e1ac2dc0 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1846,6 +1846,17 @@
"name": "trust_scan",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "legacy_unknown": 0,
+ "pending": [],
+ "unclaimed": []
+ },
+ "message": "No unclaimed source holds rows from before trust tiers.",
+ "name": "trust_sources_unclaimed",
+ "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 d7a565100b..7a9c78deee 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -701,6 +701,10 @@
"category": "brain",
"name": "trust_scan"
},
+ {
+ "category": "brain",
+ "name": "trust_sources_unclaimed"
+ },
{
"category": "brain",
"name": "core_memory"
diff --git a/test/fixtures/goldens/trust/help.txt b/test/fixtures/goldens/trust/help.txt
index ed9f6e0fc6..489b29cd4e 100644
--- a/test/fixtures/goldens/trust/help.txt
+++ b/test/fixtures/goldens/trust/help.txt
@@ -36,3 +36,13 @@ Usage: gbrain trust scan [--batch-size N] [--json]
Runs the write gate's deterministic detector over agent-written and lower rows written before the gate,
recording a receipt for each instruction-like row so proactive surfaces stop injecting it until you confirm
it (gbrain trust review). Changes no row; resumable (rerun to continue); a detector upgrade rescans.
+ Nothing runs it for you: an agent asks you first. Claim your own sources first (gbrain trust claim-sources)
+ so your older notes are not treated as unverified.
+
+Usage: gbrain trust claim-sources [--dry-run] [--source <id>]... [--resume] [--batch-size N] [--json]
+ Claim your own sources once, after upgrading: each source shows its local path or remote, page count and
+ the trust mix now and after claiming, and you type its id to claim it. A claimed source syncs as "your notes"
+ and its rows from before trust tiers move from "unverified origin" to "your notes", except rows that say
+ they were captured, clipped, imported, extracted or written by an agent (they keep their lower tier).
+ Nothing becomes "confirmed by you". Connector sources (Google, GitHub) cannot be claimed. --dry-run lists
+ without writing; --resume finishes an interrupted claim. Needs you at a terminal; --yes never claims.
diff --git a/test/trust-claim.test.ts b/test/trust-claim.test.ts
new file mode 100644
index 0000000000..a121a87fc3
--- /dev/null
+++ b/test/trust-claim.test.ts
@@ -0,0 +1,310 @@
+/**
+ * `gbrain trust claim-sources` (#5575, legacy content) and the asks around it.
+ *
+ * Protects: the owner claims a source only by typing its id on a terminal
+ * (--yes never counts; without a terminal the command refuses with an
+ * ask_user fix and changes nothing); a claim sets the per-source default
+ * operator_curated and lifts the source's legacy unknown rows through the
+ * backfill, never above operator_curated, while rows with a lowering signal
+ * (mcp:* and capture stamps, transcript imports, clipped pages, connector
+ * stamps, backstop facts, the lower-only trust_tier marker) keep their lower
+ * tier; connector sources cannot be claimed; an interrupted lift resumes, and
+ * until it does the scan refuses and explain shows the rows as owner tier;
+ * `--dry-run` writes nothing; `sources set-trust` to a lower tier ends a
+ * claim. Doctor `trust_sources_unclaimed` warns with ask_user while unclaimed
+ * legacy rows exist and never on a fresh brain; doctor `trust_scan` asks
+ * before scanning; post-upgrade and the behavior-change notice carry the ask.
+ * Also pins the SQL frontmatter caps to `frontmatterTrustCaps`.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { PassThrough } from 'node:stream';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { renderAction, type Action } from '../src/core/agent-output.ts';
+import { __setConfirmationIoForTests } from '../src/core/trust/confirm.ts';
+import { frontmatterTrustCaps, frontmatterTrustCapsSql } from '../src/core/trust/channel.ts';
+import { claimSourcesFix, listClaimSources, liftClaimedSources, recordSourceClaims, readUnclaimedLegacySources } from '../src/core/trust/claim.ts';
+import { TRUST_CLAIM_LIFTED_AT_KEY, TRUST_CLAIMED_AT_KEY } from '../src/core/trust/claim-state.ts';
+import { trustClaimUpgradeNotice } from '../src/core/trust/claim-notice.ts';
+import { runTrustBackfill } from '../src/core/trust/backfill.ts';
+import { explainTrust } from '../src/core/trust/review.ts';
+import { TRUST_TIER_RANK } from '../src/core/trust/tier.ts';
+import { runTrustScan } from '../src/core/eligibility/scan.ts';
+import { runTrustClaimSources } from '../src/commands/trust-claim.ts';
+import { runSetTrust } from '../src/commands/sources-trust.ts';
+import { trustSourcesUnclaimedEntry } from '../src/commands/doctor/checks/trust-sources-unclaimed.ts';
+import { trustScanEntry } from '../src/commands/doctor/checks/trust-scan.ts';
+import { withTrustClaimAsk } from '../src/core/behavior-change-notice.ts';
+import { FACTS_BACKSTOP_SOURCES } from '../src/core/facts/capture-sources.ts';
+import { WRITE_GATE_SCAN_BASELINE_KEY } from '../src/core/write-gate-schema.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: BrainEngine;
+/** A brain nothing seeds: fresh-install expectations. */
+let fresh: BrainEngine;
+beforeAll(async () => {
+ const pg = new PGLiteEngine(); await pg.connect({}); await pg.initSchema();
+ engine = pg;
+ // Every row the tests seed stands in for content from before trust tiers: the baseline the trust migrations record covers it.
+ await engine.executeRaw('UPDATE config SET value = $2 WHERE key = $1', [WRITE_GATE_SCAN_BASELINE_KEY,
+ JSON.stringify({ detector_version: 0, until: { pages: 1e12, facts: 1e12, takes: 1e12, timeline_entries: 1e12 } })]);
+ const empty = new PGLiteEngine(); await empty.connect({}); await empty.initSchema();
+ fresh = empty;
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); await fresh.disconnect(); });
+afterEach(() => { __setConfirmationIoForTests(null); process.exitCode = 0; });
+
+const cli = { transport: 'cli' as const, isCallable: () => false, preapproved: () => true };
+const render = (fix: unknown) => renderAction(fix as Action, cli);
+const doctor = async (entry: { run: (ctx: DoctorContext) => Promise<unknown> }, db = engine) => (await entry.run({ engine: db } as unknown as DoctorContext) as Check[])[0]!;
+
+function tty(answer: string) {
+ const input = new PassThrough();
+ const output = new PassThrough();
+ let prompt = '';
+ output.on('data', chunk => { prompt += String(chunk); });
+ __setConfirmationIoForTests({ probe: { stdinIsTTY: true, stdoutIsTTY: true, env: { GBRAIN_INTERACTIVE: '1' } }, input, output, timeoutMs: 2000 });
+ input.write(`${answer}\n`);
+ return { prompt: () => prompt };
+}
+const nonTty = () => __setConfirmationIoForTests({ probe: { stdinIsTTY: false, stdoutIsTTY: false, env: {} } });
+
+/** Runs the CLI, returning what it printed on stdout (console.log) and stderr. */
+async function runCli(args: string[]): Promise<{ out: string; err: string }> {
+ const out: string[] = [];
+ const err: string[] = [];
+ const log = console.log;
+ const write = process.stderr.write.bind(process.stderr);
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ process.stderr.write = ((chunk: string | Uint8Array) => { err.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try { await runTrustClaimSources(engine, args); } finally { console.log = log; process.stderr.write = write; }
+ return { out: out.join('\n'), err: err.join('') };
+}
+
+/** One owner source with a row per signal class (all `unknown`), plus a github connector source. */
+async function seed() {
+ const tag = randomUUID().slice(0, 8);
+ const src = `own-${tag}`, gh = `gh-${tag}`;
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path) VALUES($1,$1,'/home/alice-example/notes')`, [src]);
+ await engine.executeRaw(`INSERT INTO sources(id,name,config) VALUES($1,$1,'{"kind":"github"}'::jsonb)`, [gh]);
+ const pages: Record<string, number> = {};
+ const page = async (key: string, source: string, sourceKind: string | null, frontmatter: Record<string, unknown> = {}) => {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO pages(slug,type,title,compiled_truth,source_id,source_kind,frontmatter)
+ VALUES($1,'note','T','Plain notes about acme-example.',$2,$3,$4::text::jsonb) RETURNING id`, [`p/${key}`, source, sourceKind, JSON.stringify(frontmatter)]);
+ pages[key] = Number(row!.id);
+ };
+ await page('plain', src, null);
+ await page('mcp', src, 'mcp:put_page');
+ await page('capture', src, null, { captured_via: 'capture' });
+ await page('own-transcript', src, null, { transcript_import: { harness: 'codex' } });
+ await page('other-transcript', src, null, { transcript_import: { harness: 'zoom' } });
+ await page('clipped', src, null, { source_url: 'https://example.com/a', clipped_at: '2026-01-01' });
+ await page('marker', src, null, { trust_tier: 'agent_written' });
+ await page('confirmed-marker', src, null, { trust_tier: 'user_confirmed' });
+ await page('connector-stamp', src, null, { ingested_via: 'connector:gmail' });
+ await page('gh-plain', gh, null);
+ const fact = async (source: string, fenced: string | null) => {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,source_markdown_slug,row_num)
+ VALUES($1,'e','claim','fact',$2,$3,$4) RETURNING id`, [src, source, fenced, fenced ? 1 : null]);
+ return Number(row!.id);
+ };
+ const facts = { plain: await fact('manual', null), backstop: await fact(FACTS_BACKSTOP_SOURCES[0]!, null), onPlain: await fact('manual', 'p/plain'), onMcp: await fact('manual', 'p/mcp') };
+ const [take] = await engine.executeRaw<{ id: number }>(`INSERT INTO takes(page_id,row_num,claim,kind,holder,weight) VALUES($1,1,'A take','take','brain',0.5) RETURNING id`, [pages.plain]);
+ const [entry] = await engine.executeRaw<{ id: number }>(`INSERT INTO timeline_entries(page_id,date,summary) VALUES($1,'2026-01-01','Clipped event') RETURNING id`, [pages.clipped]);
+ return { src, gh, pages, facts, take: Number(take!.id), entry: Number(entry!.id) };
+}
+
+const tierOf = async (table: string, id: number) => (await engine.executeRaw<{ t: string }>(`SELECT trust_tier AS t FROM ${table} WHERE id=$1`, [id]))[0]!.t;
+const configOf = async (id: string) => {
+ const [row] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [id]);
+ return (typeof row!.config === 'string' ? JSON.parse(row!.config) : row!.config) as Record<string, unknown>;
+};
+const snapshot = async (src: string) => JSON.stringify({
+ pages: await engine.executeRaw(`SELECT id, trust_tier, write_origin FROM pages WHERE source_id=$1 ORDER BY id`, [src]),
+ facts: await engine.executeRaw(`SELECT id, trust_tier FROM facts WHERE source_id=$1 ORDER BY id`, [src]),
+ config: await configOf(src),
+ checkpoints: await engine.executeRaw(`SELECT op, fingerprint FROM op_checkpoints ORDER BY op, fingerprint`),
+});
+
+describe('trust claim-sources', () => {
+ test('the SQL frontmatter caps match frontmatterTrustCaps', async () => {
+ const samples: Array<Record<string, unknown>> = [
+ {}, { trust_tier: 'agent_written' }, { trust_tier: 'user_confirmed' }, { trust_tier: 'bogus' }, { trust_tier: 5 },
+ { source_kind: 'webhook' }, { source_kind: 'mcp:remember' }, { ingested_via: 'capture-cli' }, { captured_via: ' connector:gmail ' }, { source_kind: 'github' },
+ { source_kind: 'sync' }, { transcript_import: { harness: 'Claude-Code' } }, { transcript_import: { harness: 'zoom' } }, { transcript_import: [] },
+ { transcript_import: 'yes' }, { source_url: 'https://x', clipped_at: '2026' }, { source_url: 'https://x' }, { source_url: ' ', clipper: 'x' },
+ { source_url: 'https://x', captured_via: 'clipper' }, { source_url: 'https://x', type: 'clipping' }, { provenance: 'auto-extracted' },
+ { dream_generated: true }, { dream_generated: 'true' }, { dream_generated: false }, { provenance: 'manual', source_kind: 'inbox-folder', trust_tier: 'tool_observed' },
+ ];
+ const sql = `SELECT LEAST(${frontmatterTrustCapsSql('v.fm').join(', ')}) AS r FROM (SELECT $1::text::jsonb AS fm) v`;
+ for (const fm of samples) {
+ const [row] = await engine.executeRaw<{ r: number | null }>(sql, [JSON.stringify(fm)]);
+ const caps = frontmatterTrustCaps(fm);
+ const expected = caps.length ? Math.min(...caps.map(t => TRUST_TIER_RANK[t])) : null;
+ expect({ fm, rank: row!.r === null ? null : Number(row!.r) }).toEqual({ fm, rank: expected });
+ }
+ });
+
+ test('--dry-run lists each source with its projection and writes nothing', async () => {
+ const s = await seed();
+ const before = await snapshot(s.src);
+ const listing = await listClaimSources(engine);
+ const { out } = await runCli(['--dry-run']);
+ expect(await snapshot(s.src)).toBe(before);
+ const own = listing.sources.find(x => x.id === s.src)!;
+ expect(own).toMatchObject({ local_path: '/home/alice-example/notes', pages: 9, claimable: true, claimed: false });
+ expect(own.current!.unknown).toBe(own.legacy_unknown);
+ expect(own.projected_if_claimed.user_confirmed).toBe(0);
+ expect(own.projected_if_claimed.operator_curated).toBe(5);
+ expect(listing.sources.find(x => x.id === s.gh)).toMatchObject({ claimable: false, blocker: 'connector' });
+ expect(out).toContain(`${s.src} (/home/alice-example/notes): 9 page(s)`);
+ expect(out).toContain('github connector: cannot be claimed');
+ });
+
+ test('without a terminal it refuses with an ask_user fix and changes nothing', async () => {
+ const s = await seed();
+ const before = await snapshot(s.src);
+ nonTty();
+ const { err } = await runCli(['--source', s.src, '--yes']);
+ expect(err).toContain('confirmation_required');
+ expect(await snapshot(s.src)).toBe(before);
+ const fix = render(claimSourcesFix());
+ expect(fix.next).toBe('ask_user');
+ expect(fix.argv).toEqual(['gbrain', 'trust', 'claim-sources']);
+ expect(fix.user_message).toContain('gbrain trust claim-sources');
+ expect(fix.user_message).toContain('your notes');
+ });
+
+ test('typing the id claims the source: legacy rows become your notes, lowering signals keep their tier, nothing is confirmed', async () => {
+ const s = await seed();
+ const io = tty(s.src);
+ await runCli(['--source', s.src]);
+ expect(io.prompt()).toContain(`Type ${s.src} to confirm`);
+ const config = await configOf(s.src);
+ expect(config.trust_tier).toBe('operator_curated');
+ expect(typeof config[TRUST_CLAIMED_AT_KEY]).toBe('string');
+ expect(typeof config[TRUST_CLAIM_LIFTED_AT_KEY]).toBe('string');
+ const p = s.pages;
+ expect({
+ plain: await tierOf('pages', p.plain!), mcp: await tierOf('pages', p.mcp!), capture: await tierOf('pages', p.capture!),
+ ownTranscript: await tierOf('pages', p['own-transcript']!), otherTranscript: await tierOf('pages', p['other-transcript']!),
+ clipped: await tierOf('pages', p.clipped!), marker: await tierOf('pages', p.marker!), confirmedMarker: await tierOf('pages', p['confirmed-marker']!),
+ connectorStamp: await tierOf('pages', p['connector-stamp']!), gh: await tierOf('pages', p['gh-plain']!),
+ factPlain: await tierOf('facts', s.facts.plain), factBackstop: await tierOf('facts', s.facts.backstop),
+ factOnPlain: await tierOf('facts', s.facts.onPlain), factOnMcp: await tierOf('facts', s.facts.onMcp),
+ take: await tierOf('takes', s.take), entry: await tierOf('timeline_entries', s.entry),
+ }).toEqual({
+ plain: 'operator_curated', mcp: 'agent_written', capture: 'agent_written', ownTranscript: 'agent_written', otherTranscript: 'external_untrusted',
+ clipped: 'external_untrusted', marker: 'agent_written', confirmedMarker: 'operator_curated', connectorStamp: 'external_untrusted', gh: 'unknown',
+ factPlain: 'operator_curated', factBackstop: 'agent_written', factOnPlain: 'operator_curated', factOnMcp: 'agent_written',
+ take: 'operator_curated', entry: 'external_untrusted',
+ });
+ const [origin] = await engine.executeRaw<{ c: string }>(`SELECT write_origin->>'channel' AS c FROM pages WHERE id=$1`, [p.plain]);
+ expect(origin!.c).toBe('trust_claim');
+ expect((await readUnclaimedLegacySources(engine)).unclaimed.map(u => u.id)).not.toContain(s.src);
+ });
+
+ test('a wrong token declines; --yes never claims', async () => {
+ const s = await seed();
+ tty('yes');
+ const { out } = await runCli(['--source', s.src, '--yes']);
+ expect(out).toContain('--yes never claims');
+ expect(out).toContain(`${s.src}: not claimed`);
+ expect((await configOf(s.src))[TRUST_CLAIMED_AT_KEY]).toBeUndefined();
+ expect(await tierOf('pages', s.pages.plain!)).toBe('unknown');
+ });
+
+ test('connector sources cannot be claimed', async () => {
+ const s = await seed();
+ tty(s.gh);
+ const { err } = await runCli(['--source', s.gh]);
+ expect(err).toContain('invalid_params');
+ expect(err).toContain('connector');
+ await expect(recordSourceClaims(engine, [s.gh])).rejects.toMatchObject({ code: 'invalid_params' });
+ expect(await tierOf('pages', s.pages['gh-plain']!)).toBe('unknown');
+ });
+
+ test('an interrupted lift resumes; until then the scan refuses and explain shows owner tier', async () => {
+ const s = await seed();
+ await recordSourceClaims(engine, [s.src]);
+ let batches = 0;
+ await expect(runTrustBackfill(engine, { sources: [s.src], batchSize: 1, log: () => { if (++batches === 2) throw new Error('interrupted'); } })).rejects.toThrow('interrupted');
+ const pending = await doctor(trustSourcesUnclaimedEntry);
+ expect(pending.status).toBe('warn');
+ expect(render(pending.fix).argv).toEqual(['gbrain', 'trust', 'claim-sources', '--resume']);
+ await expect(runTrustScan(engine)).rejects.toMatchObject({ code: 'recovery_required' });
+ const [still] = await engine.executeRaw<{ slug: string }>(`SELECT slug FROM pages WHERE source_id=$1 AND trust_tier='unknown' ORDER BY id LIMIT 1`, [s.src]);
+ const [explained] = await explainTrust(engine, `p:${s.src}/${still!.slug}`);
+ expect(explained).toMatchObject({ tier: 'unknown', claimed_source: 'lift_pending' });
+ expect(explained!.label).toStartWith('your notes');
+ tty('unused');
+ await runCli(['--resume']);
+ expect(await tierOf('pages', s.pages.plain!)).toBe('operator_curated');
+ expect(await tierOf('pages', s.pages.mcp!)).toBe('agent_written');
+ expect((await readUnclaimedLegacySources(engine)).pending).not.toContain(s.src);
+ expect((await liftClaimedSources(engine)).sources).toEqual([]);
+ });
+
+ test('sources set-trust to a lower tier ends the claim', async () => {
+ const s = await seed();
+ await recordSourceClaims(engine, [s.src]);
+ const log = console.log;
+ console.log = () => {};
+ try { await runSetTrust(engine, [s.src, 'agent_written']); } finally { console.log = log; }
+ const config = await configOf(s.src);
+ expect(config.trust_tier).toBe('agent_written');
+ expect(config[TRUST_CLAIMED_AT_KEY]).toBeUndefined();
+ });
+});
+
+describe('the asks around claiming', () => {
+ test('doctor trust_sources_unclaimed: ok on a fresh brain, ask_user while unclaimed legacy rows exist', async () => {
+ expect((await doctor(trustSourcesUnclaimedEntry, fresh)).status).toBe('ok');
+ expect(await trustClaimUpgradeNotice(fresh)).toBeNull();
+ expect(await withTrustClaimAsk(fresh, { code: 'behavior_changes', kind: 'safety', why: 'w', fix: { argv: ['gbrain', 'doctor', '--only', 'behavior_changes', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'x' } }))
+ .toMatchObject({ fix: { argv: ['gbrain', 'doctor', '--only', 'behavior_changes', '--json'] } });
+ const s = await seed();
+ const check = await doctor(trustSourcesUnclaimedEntry);
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain(s.src);
+ expect(check.message).not.toContain(s.gh);
+ const fix = render(check.fix);
+ expect(fix.next).toBe('ask_user');
+ expect(fix.argv).toEqual(['gbrain', 'trust', 'claim-sources']);
+ });
+
+ test('a row stored as unknown after the trust migrations is not legacy: no warning, and a claim never lifts it', async () => {
+ const [page] = await fresh.executeRaw<{ id: number }>(`INSERT INTO pages(slug,type,title,compiled_truth,source_id) VALUES('p/late','note','T','x','default') RETURNING id`);
+ expect((await fresh.executeRaw<{ t: string }>('SELECT trust_tier AS t FROM pages WHERE id=$1', [page!.id]))[0]!.t).toBe('unknown');
+ expect((await doctor(trustSourcesUnclaimedEntry, fresh)).status).toBe('ok');
+ await recordSourceClaims(fresh, ['default']);
+ await liftClaimedSources(fresh);
+ expect((await fresh.executeRaw<{ t: string }>('SELECT trust_tier AS t FROM pages WHERE id=$1', [page!.id]))[0]!.t).toBe('unknown');
+ });
+
+ test('doctor trust_scan asks before scanning legacy content', async () => {
+ await seed();
+ // These rows stand in for content from before the write gate: no scan baseline bounds them.
+ await engine.executeRaw('DELETE FROM config WHERE key = $1', [WRITE_GATE_SCAN_BASELINE_KEY]);
+ const check = await doctor(trustScanEntry);
+ expect(check.status).toBe('warn');
+ const fix = render(check.fix);
+ expect(fix.next).toBe('ask_user');
+ expect(fix.argv).toEqual(['gbrain', 'trust', 'scan']);
+ expect(fix.user_message).toContain('claim');
+ });
+
+ test('post-upgrade and the behavior-change notice carry the ask_user block', async () => {
+ await seed();
+ const lines = (await trustClaimUpgradeNotice(engine))!.join('\n');
+ expect(lines).toContain('[AGENT]');
+ expect(lines).toContain('next: ask_user: gbrain trust claim-sources');
+ expect(lines).toContain('[SHOW USER]');
+ expect(lines).not.toContain('gbrain trust scan --');
+ const notice = await withTrustClaimAsk(engine, { code: 'behavior_changes', kind: 'safety', why: 'w', fix: { argv: ['gbrain', 'doctor', '--only', 'behavior_changes', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'x' } });
+ expect(render(notice!.fix).next).toBe('ask_user');
+ expect(notice!.user_message).toContain('gbrain trust claim-sources');
+ });
+});