Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): lower-only claim-sources --relower repair for lifted atoms (#6533)

time-attack657c84de43ab
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 05186e64d3..c9c38dd25a 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `USER_SAID_TRUST_LABEL` (the label of an `agent_written` row whose `write_origin.content_origin` is `user_said`; the tier never rises, the eval harness reads the constant), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`. Write side (lane L1a): `channel.ts` computes the tier once per write from the channel (`requestChannelTrust`: agent verbs agent_written, `content_origin: tool_output` external_untrusted, connector jobs external_untrusted; owner sync/import `ownerImportTrust`: operator_curated or the `sources set-trust` default, lowered by frontmatter markers `frontmatterTrustCaps`) and `stampTrustMarker` (the lower-only `trust_tier` marker, CEO-21); `page-write.ts` wires it into page-prepare (marker stamp, fence edits keep the page tier via `withTrustKeep`, `lower_page` proposals on agent rewrites, the page gate tier); `proposals.ts` is the `trust_proposals` store and handler dispatch (`decide.ts` loads every handler); `supersede-handlers.ts` is guarded supersession (`supersessionGuarded`, contested fact/take/ontology proposals, remote `forget_requires_owner`, the trust store for the checked decide_proposals supersede); `fence-guard.ts` guards the facts-fence re-projection and gates new fence rows; `gate-outcomes.ts` is the DX-1 `gate` field and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15). `owner-actions.ts`: `previewOwnerAction` / `applyOwnerAction` for confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and a `binding` of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with `preview_changed` and a raising action without a confirmation with `confirmation_required` (`ownerActionFix` is the DX-3 `tell_user_to_run` fix). Fact and take confirms are tier-only updates under `withTrustPromotion` (inside `withCoordinatedWrite` on a managed brain); the hold store is an isolated adapter over `write_gate_holds` (`__setHoldStoreForTests`, `TODO(L2a-merge)`); `disable --all` writes `write_gate.external_mode=off`, `write_gate.agent_mode=off`, `trust.agent_activation=allow` with the `trust.kill_switch` receipt that `--undo` restores from. `page-handlers.ts`: `confirmPage` (removes the CEO-21 `trust_tier` marker through a journaled `trust_owner_page` mutation on a managed brain, `importFromContent` otherwise; tier only when no marker), `revertPageToVersion` (the version's content and its snapshot tier, `unknown` for legacy versions), the coordinator preparer `prepareTrustOwnerPageMutation` (dispatched from `persistence/service.ts`; re-checks the approved revision and refuses a remote request without `memory_confirm`), and the `lower_page` handler (accept = confirm, reject = dismiss, `revertLoweredPage` = restore the prior owner version). `refs.ts`: typed refs `f<id>`, `t<id>`, `h<id>`, `tp<id>`, `a<id>`, `p:<source>/<slug>`, bare slugs resolved by `--source` or a single source (ambiguity refuses). `review.ts`: `buildTrustReview` (pending proposals, lowered pages, unconfirmed standing preferences, holds, allow rules, kill-switch state, grouped by day and page, complete argv) and `explainTrust`. `allow-rules.ts`: the `trust_allow_rules` table (migration v229, receipted, removal keeps the row) and the pure `matchTrustAllowRule` over server-stamped fields. `owner-ipc.ts`: the `trust_read` / `trust_preview` / `trust_apply` administration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests: `test/trust-owner-actions.test.ts` (PGLite and Postgres), `test/trust-owner-ipc.test.ts`, `test/trust-cli.test.ts`. Derived-row taint (`taint.ts`, `derived-gate.ts`, `timeline-projection.ts`): see [security](security.md).
- `src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts` — the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14). `policy.ts`: `resolveReadEligibility` returns the effective floor (the strictest of `AuthInfo.minTrust`, the caller's `min_trust` and `trust.read_policy=filter`'s own `unknown` floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, `suppressFlagged` unless `trust.agent_activation=allow`. `sql.ts`: vetted predicates over a caller alias (closed vocabularies only): `trustFloorSql`, `pageEligibleSql` (spliced by `buildVisibilityClause` and `pageReadFilter`, so every search arm filters before LIMIT; a chunk's tier is its page's), `projectionEligibleSql` (facts, takes and timeline reads: a quarantined page's projections and `needs_rederive` rows are hidden, never expired) and `activationSuppressedSql` (tier at or below `agent_written` plus an instruction-family `write_gate_receipts` flag). `labels.ts`: `trust_tier` + a short server-stamped `origin` (`trustFields` appends `:user_said` for a relayed user statement, which `trustLabelWords` reads as `USER_SAID_TRUST_LABEL` unless the row is flagged unconfirmed); compact per-item text labels with the fixed words, `unknown` as a short origin line, and the `<external-data>` envelope only below `unknown`. `registry.ts`: `OP_READ_TRUST` classifies every read-scope op `filtered | labeled | text_free` (the dispatcher refuses a `labeled` op for a floored token) and `PROACTIVE_SURFACES` lists the injecting surfaces, each calling `proactiveEligibility(ctx, id)`; drift-tested by `test/eligibility-registry.test.ts`. `stamp.ts` labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows `unconfirmed`. `activation.ts` partitions proactive candidates (`partitionForActivation`, `pageActivationVerdicts`) and builds the `memory_suppressed` notice (count + `gbrain trust review`, never content). `scan.ts` (`gbrain trust scan`, doctor `trust_scan`) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans). `explain.ts` is the `gbrain trust explain` data API: tier, origin, receipts and the per-surface decision for a typed ref. Tests: `test/eligibility-{policy,registry,reads}.test.ts`.
- `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is above): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` (and `lowerDerivedPageIn`, the same inside a caller's coordinated transaction) lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated. Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.
-- `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 a tell_user_to_run 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 name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; 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/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 a tell_user_to_run 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 name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. `claim-sources --relower [--dry-run]` (`relowerClaimedRows`, backfill.ts) is the lower-only #6533 repair: `trust_claim` rows whose page rule now ranks below their stored tier (legacy `extracted_by: extract_atoms-*` atoms) drop to it, pages first with child rows following through the relower-mode page taint, receipt `write_origin.channel` `trust_relower`; the dry run reports the same rows; doctor `trust_sources_unclaimed` names it. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`, `test/trust-claim-relower.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` (`flag` default per the paid eval, `quarantine` opt-in, `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. `assessPageForGate` / `assessWriteGate` take an optional `WriteGateWork` accumulator (`createWriteGateWork`) the detector fills per assessment with the work it did (normalization and anchor-pass input units, windows, pattern checks past the prefilter, regex executions, searched characters); nothing is kept between calls (#6490). Tests: `test/write-gate.test.ts`, `test/write-gate-perf.slow.test.ts` (quiet-round absolute p95 with the receipt insert, 5 MB linear bounds), `test/write-gate-work-counters-6490.test.ts` (the counters pinned per corpus; four mutants fail it: disabled prefilter, REACH x8, a per-window normalization pass, a pattern anchored on `the`), `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
index a69024093a..6c76d03414 100644
--- a/docs/guides/memory-trust.md
+++ b/docs/guides/memory-trust.md
@@ -120,6 +120,14 @@ 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.
+Atoms extracted before gbrain recorded `extracted_by` as an agent signal
+could be lifted to "your notes" by an earlier claim (#6533).
+`gbrain trust claim-sources --relower --dry-run` lists the claim-lifted rows
+whose own signals now say lower, and `gbrain trust claim-sources --relower`
+lowers them. It only lowers: it never raises a row, it touches only rows with
+`write_origin.channel = "trust_claim"`, rows on a lowered page follow it, and
+each lowered row records `write_origin.channel = "trust_relower"`.
+
`gbrain sources set-trust <id> <lower tier>` or `--clear` ends a claim. Rows
it already lifted keep their tier.
@@ -143,7 +151,9 @@ Claim your own sources first, so your notes are not treated as unverified.
- `trust_sources_unclaimed` warns while unclaimed, non-connector sources hold
rows from before trust tiers, with `fix.next: tell_user_to_run` 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.
+ a claim's lift has not finished, and names `gbrain trust claim-sources
+ --relower` while claim-lifted rows rank above their own signals. 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 is yours to run (`tell_user_to_run`).
- `trust_tiers` reports the tier mix and recommends `gbrain trust backfill`.
diff --git a/src/commands/doctor/checks/trust-sources-unclaimed.ts b/src/commands/doctor/checks/trust-sources-unclaimed.ts
index 2139b06d85..eb8609e37d 100644
--- a/src/commands/doctor/checks/trust-sources-unclaimed.ts
+++ b/src/commands/doctor/checks/trust-sources-unclaimed.ts
@@ -5,13 +5,17 @@
* while a claim's lift has not finished. The fix is `fix.next:
* tell_user_to_run`: 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.
+ * brain before the trust migration, is ok. #6533: once claims finished, it also
+ * warns while claim-lifted rows rank above their own signals (legacy
+ * extract_atoms atoms) and names the lower-only `claim-sources --relower`.
+ * 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 { relowerClaimedRows, TRUST_RELOWER_COMMAND, type TrustRelowerReport } from '../../../core/trust/backfill.ts';
import { isUndefinedColumnError } from '../../../core/utils.ts';
const VERIFY = { argv: ['gbrain', 'doctor', '--only', 'trust_sources_unclaimed', '--json'] };
@@ -23,11 +27,19 @@ async function runTrustSourcesUnclaimed(ctx: DoctorContext): Promise<Check[]> {
const { unclaimed, pending } = await readUnclaimedLegacySources(engine);
const rows = unclaimed.reduce((n, s) => n + s.legacy_unknown, 0);
const details = { unclaimed, pending, legacy_unknown: rows };
+ let relower: TrustRelowerReport;
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 ((relower = await relowerClaimedRows(engine, { dryRun: true })).rows > 0) {
+ checks.push({ name: 'trust_sources_unclaimed', status: 'warn', details: { ...details, relower: { rows: relower.rows, sample: relower.sample.slice(0, 5) } },
+ message: `${relower.rows} row(s) a claim lifted to "your notes" say they were written by an agent (atoms extracted before gbrain recorded that). `
+ + `Preview with ${[...TRUST_RELOWER_COMMAND, '--dry-run'].join(' ')}, then run ${TRUST_RELOWER_COMMAND.join(' ')}; it only lowers.`,
+ fix: { argv: [...TRUST_RELOWER_COMMAND], consent: [], actor: 'agent', requires_exclusive: false, verify: VERIFY,
+ preview_argv: [...TRUST_RELOWER_COMMAND, '--dry-run', '--json'],
+ why: 'Lowers claim-lifted rows to the tier their own signals name (lower only; nothing is raised or confirmed).' } });
} 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 {
diff --git a/src/commands/trust-claim.ts b/src/commands/trust-claim.ts
index a98209530f..310ccd6c00 100644
--- a/src/commands/trust-claim.ts
+++ b/src/commands/trust-claim.ts
@@ -10,6 +10,8 @@
* --source <id> ask only about this source (repeatable)
* --resume finish the lift of sources already claimed (asks nothing)
* --batch-size N lift batch size
+ * --relower [--dry-run] lower-only repair (#6533): rows a claim lifted whose own signals now say lower
+ * (legacy extract_atoms atoms) go back down; --dry-run previews, asks nothing
*/
import type { BrainEngine } from '../core/engine.ts';
import { jsonRequested, writeStdoutFinal } from '../core/cli-force-exit.ts';
@@ -20,17 +22,20 @@ import {
} 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 { relowerClaimedRows, TRUST_RELOWER_COMMAND, 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]',
+ ' gbrain trust claim-sources --relower [--dry-run] [--source <id>]... [--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.',
+ ' --relower only lowers: rows a claim lifted whose own signals now say they were written by an agent (atoms',
+ ' extracted before gbrain recorded that) go back to that tier. --relower --dry-run lists them first.',
].join('\n');
const mix = (counts: TierCounts | undefined) =>
@@ -72,6 +77,22 @@ export async function runTrustClaimSources(engine: BrainEngine, args: string[],
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('--relower')) {
+ const named = flagValues(args, '--source');
+ const dryRun = args.includes('--dry-run');
+ if (!dryRun) await opts.completeStartup?.(engine);
+ const report = await relowerClaimedRows(engine, { dryRun, ...(named.length ? { sources: named } : {}) });
+ if (json) { await writeStdoutFinal(`${JSON.stringify(report, null, 2)}\n`); return; }
+ if (report.rows === 0) { console.log('No claimed row needs lowering.'); return; }
+ console.log([
+ dryRun ? `Would lower ${report.rows} row(s) a claim lifted above what they say they are (dry run, nothing written):`
+ : `Lowered ${report.rows} row(s) a claim lifted above what they say they are:`,
+ ...report.tables.filter(t => t.rows > 0).map(t => ` ${t.table}: ${mix(t.to)}`),
+ ...report.sample.map(r => ` ${r.source_id}/${r.slug}: ${trustLabel(r.from)} -> ${trustLabel(r.to)}`),
+ ...(dryRun ? [`Apply with: ${TRUST_RELOWER_COMMAND.join(' ')}${named.map(id => ` --source ${id}`).join('')}`] : []),
+ ].join('\n'));
+ return;
+ }
if (args.includes('--dry-run')) {
const listing = await listClaimSources(engine, sized);
if (json) await writeStdoutFinal(`${JSON.stringify({ mode: 'dry_run', ...listing }, null, 2)}\n`);
diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.ts
index 88489168f3..e05c7e7091 100644
--- a/src/core/trust/backfill.ts
+++ b/src/core/trust/backfill.ts
@@ -117,7 +117,7 @@ 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, assumeClaimed: readonly string[] = [], ceilings: LegacyCeilings = null) {
+function classifier(cols: Columns, assumeClaimed: readonly string[] = [], ceilings: LegacyCeilings = null, relower = false) {
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) => {
@@ -185,10 +185,16 @@ function classifier(cols: Columns, assumeClaimed: readonly string[] = [], ceilin
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. */
+ /**
+ * The tier a row's page contributes: its stored tier when classified, else the page's own signals. In the
+ * relower pass a page the claim lifted contributes the tier it is about to be lowered to, so the read-only
+ * preview and the apply (which lowers pages first) report the same child rows (#6533).
+ */
const pageTaint = (p: string, s: string, r: string) => {
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 stored = trustRankSql(`${p}.trust_tier`);
+ const classified = relower ? `CASE WHEN ${p}.write_origin->>'channel' = 'trust_claim' THEN LEAST(${stored}, COALESCE(${rule}, ${stored})) ELSE ${stored} END` : stored;
+ return hasTrust ? `CASE WHEN ${p}.id IS NULL THEN NULL WHEN ${p}.trust_tier <> 'unknown' THEN ${classified} ELSE ${rule} END` : rule;
};
const pageJoins = (p: string, s: string, r: string, on: string) =>
`LEFT JOIN pages ${p} ON ${on} ${cols.has('sources', 'config') ? `LEFT JOIN sources ${s} ON ${s}.id = ${p}.source_id` : ''} ${requestJoin('pages', 'revision_write_request_id', r, p)}`;
@@ -352,6 +358,68 @@ export async function runTrustBackfill(engine: BrainEngine, opts: TrustBackfillO
return summarize('apply', 'trust_columns', tables, signals, 'complete');
}
+export const TRUST_RELOWER_COMMAND = ['gbrain', 'trust', 'claim-sources', '--relower'] as const;
+
+export interface TrustRelowerReport {
+ mode: 'dry_run' | 'apply';
+ /** Rows the claim lifted that their own signals now place lower, per table and target tier. */
+ tables: Array<{ table: TrustTable; rows: number; to: TierCounts }>;
+ rows: number;
+ /** Up to 20 affected pages, for the preview. */
+ sample: Array<{ source_id: string; slug: string; from: TrustTier; to: TrustTier }>;
+}
+
+/**
+ * #6533 repair, lower only: rows a claim lifted (`write_origin.channel` `trust_claim`) whose own page rule
+ * now ranks below their stored tier (legacy extract_atoms atoms the claim made "your notes" before
+ * `extracted_by` was a signal) are lowered to that rule, pages first so facts, takes and timeline rows on a
+ * lowered page follow it. Each lowered row's `write_origin.channel` becomes `trust_relower`, so a rerun finds
+ * nothing. Nothing is ever raised, and rows a person or a later write classified are not touched. The dry
+ * run is read-only and reports the same rows the apply lowers.
+ */
+export async function relowerClaimedRows(engine: BrainEngine, opts: { dryRun?: boolean; sources?: readonly string[] } = {}): Promise<TrustRelowerReport> {
+ const cols = await readColumns(engine);
+ const mode: TrustRelowerReport['mode'] = opts.dryRun ? 'dry_run' : 'apply';
+ if (!cols.has('pages', 'trust_tier') || !cols.has('pages', 'write_origin') || !cols.has('sources', 'config')) return { mode, tables: [], rows: 0, sample: [] };
+ const { forTable } = classifier(cols, [], await readLegacyCeilings(engine).catch(() => null), true);
+ const claimed = (await engine.executeRaw<{ id: string }>(`SELECT s.id FROM sources s WHERE ${claimedSourceSql('s')} ORDER BY s.id`))
+ .map(r => r.id).filter(id => !opts.sources || opts.sources.includes(id));
+ const report: TrustRelowerReport = { mode, tables: [], rows: 0, sample: [] };
+ if (claimed.length === 0) return report;
+ const managedBrain = opts.dryRun ? false : await readManagedMode(engine);
+ const attribution = opts.dryRun ? null : await maintenanceAttribution(engine);
+ const origin = JSON.stringify({ channel: 'trust_relower' });
+ for (const table of BACKFILL_ORDER) {
+ if (!cols.table(table) || !cols.has(table, 'write_origin')) continue;
+ const { from, rule, src } = forTable(table);
+ const candidates = `SELECT x.id, ${src} AS source_id, ${table === 'pages' ? 'x.slug' : 'NULL::text'} AS slug, x.trust_tier AS from_tier,
+ ${trustTierFromRankSql(rule)} AS to_tier
+ FROM ${from}
+ WHERE x.write_origin->>'channel' = 'trust_claim' AND ${src} = ANY($1::text[])
+ AND (${rule}) IS NOT NULL AND (${rule}) < ${trustRankSql('x.trust_tier')}`;
+ const rows = await engine.executeRaw<{ id: number | string; source_id: string; slug: string | null; from_tier: string; to_tier: string }>(
+ `${candidates} ORDER BY x.id`, [claimed]);
+ const to = zero();
+ for (const row of rows) {
+ const target = isTrustTier(row.to_tier) ? row.to_tier : 'unknown';
+ to[target]++;
+ if (row.slug !== null && report.sample.length < 20 && isTrustTier(row.from_tier)) {
+ report.sample.push({ source_id: row.source_id, slug: row.slug, from: row.from_tier, to: target });
+ }
+ }
+ report.tables.push({ table, rows: rows.length, to });
+ report.rows += rows.length;
+ if (opts.dryRun || rows.length === 0) continue;
+ const ids = rows.map(r => Number(r.id));
+ const sources = [...new Set(rows.map(r => r.source_id))];
+ const apply = (tx: BrainEngine) => withTrustBackfill(tx, () => tx.executeRaw(
+ `WITH b AS (${candidates} AND x.id = ANY($2::bigint[]))
+ UPDATE ${table} t SET trust_tier = b.to_tier, write_origin = $3::text::jsonb FROM b WHERE t.id = b.id`, [claimed, ids, origin]));
+ await engine.transaction(tx => managedBrain ? withCoordinatedWrite(tx, sources, () => apply(tx), attribution!) : apply(tx));
+ }
+ return report;
+}
+
/** Doctor: the stored backfill state (an interrupted run's cursor, and when a complete run finished). */
export async function readTrustBackfillState(engine: BrainEngine): Promise<{ interrupted: boolean; completedAt: string | null }> {
const [row] = await engine.executeRaw<{ n: number | string }>(
diff --git a/test/trust-claim-relower.test.ts b/test/trust-claim-relower.test.ts
new file mode 100644
index 0000000000..e4e076e6ac
--- /dev/null
+++ b/test/trust-claim-relower.test.ts
@@ -0,0 +1,71 @@
+/**
+ * #6533 repair (D16): brains that ran `trust claim-sources` before extracted_by
+ * was a signal hold legacy extract_atoms atoms at operator_curated. The
+ * lower-only `claim-sources --relower` pass returns exactly the claim-lifted
+ * rows whose own signals now rank lower, never raises, never touches rows a
+ * claim did not lift, previews the same rows it applies, and doctor names it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { liftClaimedSources, recordSourceClaims } from '../src/core/trust/claim.ts';
+import { relowerClaimedRows } from '../src/core/trust/backfill.ts';
+import { withTrustBackfill } from '../src/core/persistence/context.ts';
+import { WRITE_GATE_SCAN_BASELINE_KEY } from '../src/core/write-gate-schema.ts';
+import { trustSourcesUnclaimedEntry } from '../src/commands/doctor/checks/trust-sources-unclaimed.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: BrainEngine;
+beforeAll(async () => {
+ const pg = new PGLiteEngine(); await pg.connect({}); await pg.initSchema(); engine = pg;
+ 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 } })]);
+}, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+
+const tier = async (table: string, id: number) =>
+ (await engine.executeRaw<{ t: string; c: string | null }>(`SELECT trust_tier t, write_origin->>'channel' c FROM ${table} WHERE id=$1`, [id]))[0]!;
+const doctor = async () => ((await trustSourcesUnclaimedEntry.run({ engine } as never)) as Check[])[0]!;
+
+test('relower lowers only claim-lifted rows whose own signals rank lower, and doctor guides it', async () => {
+ await engine.executeRaw(`INSERT INTO sources(id,name,local_path) VALUES('own','own','/home/alice-example/notes')`);
+ const page = async (slug: string, type: string, fm: object) => Number((await engine.executeRaw<{ id: number }>(
+ `INSERT INTO pages(slug,type,title,compiled_truth,source_id,frontmatter) VALUES($1,$2,'T','Body.','own',$3::text::jsonb) RETURNING id`,
+ [slug, type, JSON.stringify(fm)]))[0]!.id);
+ const atomFm = { type: 'atom', extracted_by: 'extract_atoms-v0.41.2.1', source_slug: 'originals/x' };
+ const atom = await page('atoms/2026-09-07/x', 'atom', atomFm);
+ const syncedAtom = await page('atoms/2026-09-07/synced', 'atom', atomFm);
+ const plain = await page('notes/plain', 'note', {});
+ const entry = Number((await engine.executeRaw<{ id: number }>(
+ `INSERT INTO timeline_entries(page_id,date,summary) VALUES($1,'2026-09-07','Atom event') RETURNING id`, [atom]))[0]!.id);
+ await recordSourceClaims(engine, ['own']);
+ // What a claim did before #6533: the atoms and the atom's timeline row lifted to "your notes".
+ const stamp = (table: string, id: number, to: string, channel: string) => engine.transaction(tx => withTrustBackfill(tx, () =>
+ tx.executeRaw(`UPDATE ${table} SET trust_tier=$2, write_origin=$3::text::jsonb WHERE id=$1`, [id, to, JSON.stringify({ channel })])));
+ await stamp('pages', atom, 'operator_curated', 'trust_claim');
+ await stamp('timeline_entries', entry, 'operator_curated', 'trust_claim');
+ await stamp('pages', syncedAtom, 'operator_curated', 'managed_sync');
+ await liftClaimedSources(engine);
+ expect((await tier('pages', plain)).t).toBe('operator_curated');
+
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('gbrain trust claim-sources --relower');
+ expect(check.fix?.argv).toEqual(['gbrain', 'trust', 'claim-sources', '--relower']);
+
+ const before = JSON.stringify(await engine.executeRaw(`SELECT id, trust_tier, write_origin FROM pages ORDER BY id`));
+ const preview = await relowerClaimedRows(engine, { dryRun: true });
+ expect(JSON.stringify(await engine.executeRaw(`SELECT id, trust_tier, write_origin FROM pages ORDER BY id`))).toBe(before);
+ expect(preview.rows).toBe(2);
+ expect(preview.sample).toEqual([{ source_id: 'own', slug: 'atoms/2026-09-07/x', from: 'operator_curated', to: 'agent_written' }]);
+
+ const applied = await relowerClaimedRows(engine);
+ expect({ ...applied, mode: 'dry_run' }).toEqual(preview);
+ expect(await tier('pages', atom)).toEqual({ t: 'agent_written', c: 'trust_relower' });
+ expect(await tier('timeline_entries', entry)).toEqual({ t: 'agent_written', c: 'trust_relower' });
+ expect(await tier('pages', syncedAtom)).toEqual({ t: 'operator_curated', c: 'managed_sync' });
+ expect(await tier('pages', plain)).toEqual({ t: 'operator_curated', c: 'trust_claim' });
+
+ expect((await relowerClaimedRows(engine, { dryRun: true })).rows).toBe(0);
+ expect((await doctor()).status).toBe('ok');
+});