Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(trust): trust backfill --repair-unknown-markers repairs pre-fix unknown markers page by page (#6550)

garrytanf970c8d8f531
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index c9c38dd25a..5e2a5c1ba2 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -32,6 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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. `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/trust/marker-repair.ts`: #6550 `gbrain trust backfill --repair-unknown-markers` (local CLI, `src/cli/commands/trust.ts`). `previewMarkerRepair` lists live pages whose frontmatter `trust_tier` is `unknown` while the row is higher, with evidence (first `page_versions` snapshot showing the marker vs the fixed release `UNKNOWN_MARKER_FIX_RELEASE`: its commit time bounds the first run, `upgrade-state.json` can name it; whether the oldest kept version had the marker), an `assessment` (`consistent_with_6550` only when a pre-fix snapshot shows it and the first import did not, else `ambiguous`), pages already lowered through the marker (with their revert command), a `preview_hash` and the apply argv naming only the consistent pages. `applyMarkerRepair` refuses `preview_changed` unless the fresh preview hashes to `--expect`, then calls `page-handlers.ts` `repairPageMarker` per named slug: the `trust_owner_page` mode `repair_marker` (refused for remote requests) rewrites the marker to `repairedMarker(stored tier)` (none at owner tiers) at the previewed revision and keeps the tier. `review.ts` adds a `repair` command to `lower_page` items an `unknown` marker caused. Pinned by `test/trust-channel-writes.test.ts` (#6550 repair) and `test/trust-cli.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 6c76d03414..df99da8e0d 100644
--- a/docs/guides/memory-trust.md
+++ b/docs/guides/memory-trust.md
@@ -131,6 +131,50 @@ 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.
+## Repair unknown markers
+
+Before v0.60.249.0, an agent edit of a page with no tier yet wrote a
+`trust_tier: unknown` marker into its frontmatter (#6550). The backfill later
+gave the page its real tier, but the marker stayed. Agents copy the
+frontmatter back when they edit, so the next agent edit lowered the page to
+"unverified origin" and filed a `lower_page` item you never needed to see.
+`gbrain trust review` adds a `repair` command to those items.
+
+```bash
+gbrain trust backfill --repair-unknown-markers # read-only preview
+```
+
+The preview lists every page whose marker is `unknown` while its stored tier
+is higher. For each page it shows the slug, the current marker, the stored
+tier, the proposed marker and the tier after a repair (unchanged). It also
+shows the evidence:
+
+- the first saved version that shows the marker, and whether that was before
+ or after this brain first ran the fixed release (the release date is a hard
+ bound; an upgrade recorded in `~/.gbrain/upgrade-state.json` is more precise);
+- whether the page already had the marker when it was first imported.
+
+The time a marker appeared cannot prove it was accidental, so gbrain never
+decides for you. Pages with a version from before the fix that shows the
+marker, and no marker at first import, are listed as consistent with #6550,
+and the printed apply command names them. Every other page is listed as
+ambiguous. A page imported with the marker was probably marked on purpose.
+Pages an agent edit already lowered are listed with their `gbrain trust
+revert` command. Revert them first, then run the preview again.
+
+The preview ends with the exact command:
+
+```bash
+gbrain trust backfill --repair-unknown-markers --slug notes/a-example --expect mr_0123456789abcdef
+```
+
+Apply rewrites only the pages you name with `--slug` (repeatable). They must
+be at the revisions the preview showed, and the preview must still hash to
+`--expect`; otherwise it refuses with `preview_changed` and changes nothing.
+The marker becomes the page's stored tier (pages at "your notes" or higher
+get no marker), and the page keeps its tier. This runs on the local CLI only.
+Run the preview again to verify: repaired pages no longer show.
+
## Scan older memory (only when you agree)
```bash
diff --git a/src/cli/commands/trust.ts b/src/cli/commands/trust.ts
index 78642c7da8..2667f47955 100644
--- a/src/cli/commands/trust.ts
+++ b/src/cli/commands/trust.ts
@@ -1,6 +1,6 @@
/**
* `gbrain trust`: the memory-trust noun (#5575, DX-7). This module dispatches
- * `backfill` (A8, DX-5), `scan` (DX-6) and `claim-sources` (legacy content, trust/claim.ts),
+ * `backfill` (A8, DX-5; `--repair-unknown-markers`, #6550 trust/marker-repair.ts), `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` and `claim-sources --dry-run` run on a
@@ -24,6 +24,13 @@ export const TRUST_BACKFILL_USAGE = [
' "confirmed by you". --dry-run is read-only (no migrations, no writes) and works before the trust migration;',
' it reports the projected count per table and tier. --resume continues an interrupted run.',
'',
+ 'Usage: gbrain trust backfill --repair-unknown-markers [--source ID] [--slug SLUG ... --expect HASH] [--json]',
+ ' Lists pages whose trust_tier frontmatter marker is "unknown" while their stored tier is higher (an agent edit',
+ ' before v0.60.249.0 stamped it), with the evidence for each, and ends with the exact apply command. Nothing is',
+ ' classified for you: apply rewrites only the pages you name with --slug (repeatable), at the revisions of the',
+ ' preview whose hash you pass to --expect. The marker becomes the stored tier (none at owner tiers); the tier',
+ ' stays. Local CLI only. Docs: docs/guides/memory-trust.md#repair-unknown-markers',
+ '',
'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 it reads as flagged (and, under trust.agent_activation',
@@ -51,6 +58,32 @@ async function refuse(args: string[], message: string, suggestion: string): Prom
await reportTrustCliError(opError('invalid_params', message, suggestion), jsonRequested(args));
}
+/** `trust backfill --repair-unknown-markers` (#6550): preview by default; `--slug ... --expect HASH` applies. */
+async function runMarkerRepair(engine: BrainEngine, rest: string[], args: string[]): Promise<void> {
+ const value = (flag: string) => { const at = rest.indexOf(flag); return at >= 0 ? rest[at + 1] : undefined; };
+ const slugs = rest.flatMap((arg, i) => arg === '--slug' && rest[i + 1] && !rest[i + 1]!.startsWith('--') ? [rest[i + 1]!] : []);
+ const expect = value('--expect');
+ const sourceId = value('--source') ?? null;
+ if ((slugs.length > 0) !== (expect !== undefined) || (expect !== undefined && (!expect || expect.startsWith('--')))) {
+ await refuse(args, 'Applying the marker repair needs both the pages (--slug, repeatable) and the preview hash (--expect).',
+ 'Run gbrain trust backfill --repair-unknown-markers to preview, then run the command it prints after "Apply with:", naming only the pages you judge accidental.');
+ return;
+ }
+ const { applyMarkerRepair, previewMarkerRepair, renderMarkerRepairPreview } = await import('../../core/trust/marker-repair.ts');
+ try {
+ const result = expect !== undefined && !rest.includes('--dry-run')
+ ? await applyMarkerRepair(engine, { slugs, expect, sourceId })
+ : await previewMarkerRepair(engine, { sourceId });
+ if (jsonRequested(args)) await writeStdoutFinal(`${JSON.stringify(result, null, 2)}\n`);
+ else if (result.mode === 'preview') console.log(renderMarkerRepairPreview(result));
+ else console.log([...result.repaired.map(r => `Repaired ${r.page}: marker unknown -> ${r.marker_after ?? 'removed'} (tier stays ${r.tier}).`),
+ `Verify with: ${result.verify.join(' ')}`].join('\n'));
+ } catch (error) {
+ if (await reportTrustCliError(error, jsonRequested(args))) return;
+ throw error;
+ }
+}
+
export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
const [sub, ...rest] = args;
const known = sub === 'backfill' || sub === 'scan' || sub === 'claim-sources' || isTrustOwnerSubcommand(sub);
@@ -98,6 +131,11 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC
scan.complete ? ' Complete. Flagged rows carry their flag wherever they are read (and stay out of proactive context under trust.agent_activation suppress) until confirmed (gbrain trust review).' : ` Continue with: ${scan.resume_command}`].join('\n'));
return;
}
+ if (rest.includes('--repair-unknown-markers')) {
+ await ctx.completeStartup?.(engine);
+ await runMarkerRepair(engine, rest, args);
+ return;
+ }
if (!dryRun) await ctx.completeStartup?.(engine);
const { runTrustBackfill } = await import('../../core/trust/backfill.ts');
const report = await runTrustBackfill(engine, { dryRun, resume: rest.includes('--resume'), ...(batchSize ? { batchSize } : {}) });
diff --git a/src/core/trust/confirm.ts b/src/core/trust/confirm.ts
index 8107ec4e78..c8fa5a2dde 100644
--- a/src/core/trust/confirm.ts
+++ b/src/core/trust/confirm.ts
@@ -62,7 +62,8 @@ export function tierRaiseFix(argv: string[], why: string, userMessage?: string):
return { argv, consent: [], actor: 'user', why, requires_exclusive: false, ...(userMessage ? { user_message: userMessage } : {}) };
}
-export type OwnerConfirmation = { via: 'memory_confirm_scope' } | { via: 'tty' };
+/** `preview_hash`: the operator named the page and the preview hash on the local CLI (#6550 marker repair, never remote). */
+export type OwnerConfirmation = { via: 'memory_confirm_scope' } | { via: 'tty' } | { via: 'preview_hash' };
/**
* Establishes the owner's confirmation for one tier-raising action, or throws.
diff --git a/src/core/trust/marker-repair.ts b/src/core/trust/marker-repair.ts
new file mode 100644
index 0000000000..4b188df3df
--- /dev/null
+++ b/src/core/trust/marker-repair.ts
@@ -0,0 +1,199 @@
+/**
+ * #6550 repair: `gbrain trust backfill --repair-unknown-markers` (local CLI only).
+ *
+ * Before v0.60.249.0 an agent edit of an unclassified legacy page stamped a
+ * permanent `trust_tier: unknown` marker into its frontmatter. The backfill
+ * later classified the row higher (it ignores an `unknown` marker), so the
+ * next agent round trip carried the marker back, lowered the page to
+ * unknown and filed a spurious `lower_page` item.
+ *
+ * Timing alone cannot prove a marker was accidental, so nothing here
+ * classifies a page. The preview lists every live page whose marker is
+ * `unknown` while its stored tier is higher, with the evidence for each:
+ * - the first `page_versions` snapshot that shows the marker, placed before
+ * or after the brain first ran the fixed release (the release's own commit
+ * time is a hard lower bound; `upgrade-state.json` can name the upgrade);
+ * - whether the page as first imported (its oldest kept version, or the
+ * page itself when it was never rewritten) already had the marker.
+ * Pages whose evidence is consistent with the #6550 stamp are the ones the
+ * printed apply command names; the rest are listed as ambiguous. Apply needs
+ * the operator to name each page (`--slug`) and the preview hash (`--expect`),
+ * and rewrites only those pages at their previewed revisions
+ * (page-handlers.ts `repairPageMarker`): the marker becomes the stored tier
+ * (none at owner tiers) and the row keeps its tier.
+ */
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import type { BrainEngine } from '../engine.ts';
+import { gbrainPath } from '../config.ts';
+import { shellQuote } from '../agent-output.ts';
+import { opError } from '../ops/contract.ts';
+import { repairPageMarker, repairedMarker } from './page-handlers.ts';
+import { trustProposalRef } from './proposals.ts';
+import { pageRef } from './refs.ts';
+import { storedTrustTier, type TrustTier } from './tier.ts';
+
+export const TRUST_MARKER_REPAIR_COMMAND = ['gbrain', 'trust', 'backfill', '--repair-unknown-markers'] as const;
+/** The first release whose agent edits no longer stamp `unknown` markers. */
+export const UNKNOWN_MARKER_FIX_RELEASE = '0.60.249.0';
+/** That release's commit time: no brain ran it earlier. */
+export const UNKNOWN_MARKER_FIX_RELEASED_AT = '2026-10-15T17:34:32Z';
+
+export interface FixedReleaseRun {
+ version: string;
+ /** When this brain's host first ran the fixed release, if `upgrade-state.json` records the upgrade into it. */
+ first_run_at: string | null;
+ basis: 'upgrade_state' | 'release_time';
+}
+
+export interface MarkerRepairCandidate {
+ source_id: string;
+ slug: string;
+ page: string;
+ revision: string;
+ marker: 'unknown';
+ stored_tier: TrustTier;
+ /** The marker after a repair; null removes it (owner tiers carry none). */
+ proposed_marker: TrustTier | null;
+ /** The page's tier after a repair: unchanged. */
+ proposed_tier: TrustTier;
+ evidence: {
+ first_marker_snapshot: { version_id: number; snapshot_at: string } | null;
+ relative_to_fixed_release: 'before' | 'after' | 'unknown';
+ in_original_import: boolean;
+ };
+ assessment: 'consistent_with_6550' | 'ambiguous';
+ reasons: string[];
+}
+
+export interface MarkerRepairPreview {
+ mode: 'preview';
+ fixed_release: FixedReleaseRun;
+ candidates: MarkerRepairCandidate[];
+ /** Pages an agent edit already lowered to unknown through the marker: revert the item first, then preview again. */
+ lowered: Array<{ page: string; ref: string; prior_tier: TrustTier; revert: string[] }>;
+ preview_hash: string;
+ apply_command: string[];
+}
+
+export interface MarkerRepairApplied {
+ mode: 'applied';
+ repaired: Array<{ page: string; marker_before: 'unknown'; marker_after: TrustTier | null; tier: TrustTier }>;
+ verify: string[];
+}
+
+/** The fixed release's first run on this host, from the recorded upgrade when it crossed the release. */
+export async function fixedReleaseRun(): Promise<FixedReleaseRun> {
+ const { compareReleases } = await import('../behavior-change-notice.ts');
+ try {
+ const state = JSON.parse(readFileSync(gbrainPath('upgrade-state.json'), 'utf8')) as { last_upgrade?: { from?: unknown; to?: unknown; ts?: unknown } };
+ const { from, to, ts } = state.last_upgrade ?? {};
+ if (typeof from === 'string' && typeof to === 'string' && typeof ts === 'string' && Number.isFinite(Date.parse(ts))
+ && compareReleases(from, UNKNOWN_MARKER_FIX_RELEASE) < 0 && compareReleases(to, UNKNOWN_MARKER_FIX_RELEASE) >= 0) {
+ return { version: UNKNOWN_MARKER_FIX_RELEASE, first_run_at: new Date(ts).toISOString(), basis: 'upgrade_state' };
+ }
+ } catch { /* no recorded upgrade: the release time still bounds the first run */ }
+ return { version: UNKNOWN_MARKER_FIX_RELEASE, first_run_at: null, basis: 'release_time' };
+}
+
+function relativeTo(at: string, run: FixedReleaseRun): MarkerRepairCandidate['evidence']['relative_to_fixed_release'] {
+ const ms = Date.parse(at);
+ if (ms < Date.parse(UNKNOWN_MARKER_FIX_RELEASED_AT) || (run.first_run_at && ms < Date.parse(run.first_run_at))) return 'before';
+ return run.first_run_at ? 'after' : 'unknown';
+}
+
+const markerSql = (fm: string) => `jsonb_typeof(${fm}->'trust_tier') = 'string' AND ${fm}->>'trust_tier' = 'unknown'`;
+
+/** Read-only: the candidates, the lowered pages and the hash an apply binds to. */
+export async function previewMarkerRepair(engine: BrainEngine, opts: { sourceId?: string | null } = {}): Promise<MarkerRepairPreview> {
+ const run = await fixedReleaseRun();
+ const rows = await engine.executeRaw<{ id: number; source_id: string; slug: string; trust_tier: string }>(
+ `SELECT id, source_id, slug, trust_tier FROM pages
+ WHERE deleted_at IS NULL AND ${markerSql('frontmatter')} AND trust_tier IS NOT NULL AND trust_tier <> 'unknown'
+ AND ($1::text IS NULL OR source_id = $1) ORDER BY source_id, slug`, [opts.sourceId ?? null]);
+ const candidates: MarkerRepairCandidate[] = [];
+ for (const row of rows) {
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot) continue;
+ const [first] = await engine.executeRaw<{ id: number; snapshot_at: string | Date }>(
+ `SELECT id, snapshot_at FROM page_versions WHERE page_id = $1 AND ${markerSql('frontmatter')} ORDER BY id LIMIT 1`, [row.id]);
+ const [oldest] = await engine.executeRaw<{ marked: boolean }>(
+ `SELECT ${markerSql('frontmatter')} AS marked FROM page_versions WHERE page_id = $1 ORDER BY id LIMIT 1`, [row.id]);
+ const firstSnapshot = first ? { version_id: Number(first.id), snapshot_at: new Date(first.snapshot_at).toISOString() } : null;
+ const relative = firstSnapshot ? relativeTo(firstSnapshot.snapshot_at, run) : 'unknown';
+ const inOriginal = oldest ? oldest.marked === true : true;
+ const reasons: string[] = [];
+ if (inOriginal) reasons.push(oldest ? 'the page as first imported already had the marker (likely deliberate)' : 'the page was never rewritten, so the marker was in it from the start (likely deliberate)');
+ if (!firstSnapshot) reasons.push('no saved version shows when the marker appeared');
+ else if (relative === 'after') reasons.push('the marker first shows after this brain first ran the fixed release');
+ else if (relative === 'unknown') reasons.push('no recorded upgrade shows whether the marker predates the fixed release on this brain');
+ const stored = storedTrustTier(row.trust_tier);
+ candidates.push({
+ source_id: row.source_id, slug: row.slug, page: pageRef(row.source_id, row.slug), revision: snapshot.revision, marker: 'unknown',
+ stored_tier: stored, proposed_marker: repairedMarker(stored), proposed_tier: stored,
+ evidence: { first_marker_snapshot: firstSnapshot, relative_to_fixed_release: relative, in_original_import: inOriginal },
+ assessment: reasons.length ? 'ambiguous' : 'consistent_with_6550',
+ reasons: reasons.length ? reasons : ['a version before the fixed release shows the marker, and the page as first imported did not have it'],
+ });
+ }
+ const lowered = (await engine.executeRaw<{ id: number; source_id: string; slug: string; prior_tier: string }>(
+ `SELECT tp.id, p.source_id, p.slug, tp.before_state->>'prior_tier' AS prior_tier FROM trust_proposals tp JOIN pages p ON p.id = tp.target_id
+ WHERE tp.status = 'pending' AND tp.action = 'lower_page' AND tp.target_table = 'pages' AND p.deleted_at IS NULL
+ AND p.trust_tier = 'unknown' AND ${markerSql('p.frontmatter')} AND COALESCE(tp.before_state->>'prior_tier', 'unknown') <> 'unknown'
+ AND ($1::text IS NULL OR p.source_id = $1) ORDER BY p.source_id, p.slug`, [opts.sourceId ?? null]))
+ .map(r => ({ page: pageRef(r.source_id, r.slug), ref: trustProposalRef(Number(r.id)), prior_tier: storedTrustTier(r.prior_tier), revert: ['gbrain', 'trust', 'revert', trustProposalRef(Number(r.id))] }));
+ const preview_hash = `mr_${createHash('sha256').update(JSON.stringify(candidates.map(c => [c.source_id, c.slug, c.revision, c.stored_tier]))).digest('hex').slice(0, 16)}`;
+ const named = candidates.filter(c => c.assessment === 'consistent_with_6550');
+ const apply_command = [...TRUST_MARKER_REPAIR_COMMAND, ...(opts.sourceId ? ['--source', opts.sourceId] : []),
+ ...(named.length ? named.flatMap(c => ['--slug', c.slug]) : ['--slug', '<SLUG>']), '--expect', preview_hash];
+ return { mode: 'preview', fixed_release: run, candidates, lowered, preview_hash, apply_command };
+}
+
+/** Rewrites the markers of exactly the named pages, when the preview still hashes to `expect`. */
+export async function applyMarkerRepair(engine: BrainEngine, opts: { slugs: readonly string[]; expect: string; sourceId?: string | null }): Promise<MarkerRepairApplied> {
+ const preview = await previewMarkerRepair(engine, { sourceId: opts.sourceId });
+ const again = shellQuote([...TRUST_MARKER_REPAIR_COMMAND, ...(opts.sourceId ? ['--source', opts.sourceId] : [])]);
+ if (preview.preview_hash !== opts.expect) {
+ throw opError('preview_changed', `The marker-repair candidates changed since the preview you approved (${opts.expect}, now ${preview.preview_hash}); nothing was changed.`,
+ `Run ${again} again and name the pages from the new preview.`);
+ }
+ const pages = [...new Set(opts.slugs)].map(slug => {
+ const matches = preview.candidates.filter(c => c.slug === slug);
+ if (matches.length !== 1) {
+ throw opError('invalid_params', matches.length ? `${slug} is a candidate in ${matches.length} sources; nothing was changed.` : `${slug} is not in the marker-repair preview; nothing was changed.`,
+ matches.length ? `Pass --source with the page's source (${matches.map(m => m.source_id).join(', ')}).` : `Name only pages the preview lists (${again}).`);
+ }
+ return matches[0]!;
+ });
+ const repaired: MarkerRepairApplied['repaired'] = [];
+ for (const page of pages) {
+ const result = await repairPageMarker(engine, { sourceId: page.source_id, slug: page.slug, expectedRevision: page.revision, confirmation: { via: 'preview_hash' } });
+ repaired.push({ page: page.page, marker_before: 'unknown', marker_after: result.marker, tier: result.tier });
+ }
+ return { mode: 'applied', repaired, verify: [...TRUST_MARKER_REPAIR_COMMAND, ...(opts.sourceId ? ['--source', opts.sourceId] : [])] };
+}
+
+/** The human preview; it always ends with the exact apply command. */
+export function renderMarkerRepairPreview(preview: MarkerRepairPreview): string {
+ const run = preview.fixed_release;
+ const lines = [`Pages whose trust_tier marker is "unknown" while their stored tier is higher (#6550). Nothing was changed.`,
+ `Fixed release ${run.version}: ${run.first_run_at ? `this host upgraded into it at ${run.first_run_at}` : `released ${UNKNOWN_MARKER_FIX_RELEASED_AT}; no recorded upgrade names when this host first ran it`}.`];
+ for (const group of ['consistent_with_6550', 'ambiguous'] as const) {
+ const items = preview.candidates.filter(c => c.assessment === group);
+ if (!items.length) continue;
+ lines.push('', group === 'consistent_with_6550' ? 'Consistent with the #6550 stamp (named in the apply command):' : 'Ambiguous (repair only a page you judge accidental; add its --slug):');
+ for (const c of items) {
+ const snap = c.evidence.first_marker_snapshot;
+ lines.push(` ${c.slug} marker unknown, stored ${c.stored_tier}, proposed ${c.proposed_marker ? `marker ${c.proposed_marker}` : 'no marker'} (tier stays ${c.proposed_tier})`,
+ ` evidence: ${snap ? `first version with the marker v${snap.version_id} at ${snap.snapshot_at} (${c.evidence.relative_to_fixed_release} the fixed release)` : 'no version shows the marker'}; in the page as first imported: ${c.evidence.in_original_import ? 'yes' : 'no'}`,
+ ` ${c.reasons.join('; ')}`);
+ }
+ }
+ if (!preview.candidates.length) lines.push('', 'No page has an "unknown" marker below its stored tier.');
+ if (preview.lowered.length) {
+ lines.push('', 'Already lowered to "unknown" through the marker (revert the item, then run this preview again):');
+ for (const l of preview.lowered) lines.push(` ${l.page} was ${l.prior_tier}: ${shellQuote(l.revert)}`);
+ }
+ lines.push('', `Preview hash: ${preview.preview_hash}`, `Apply with: ${shellQuote(preview.apply_command)}`);
+ return lines.join('\n');
+}
diff --git a/src/core/trust/page-handlers.ts b/src/core/trust/page-handlers.ts
index 69c5279e8b..b0495718e0 100644
--- a/src/core/trust/page-handlers.ts
+++ b/src/core/trust/page-handlers.ts
@@ -15,6 +15,9 @@
* replaced a higher-tier page): accept = the owner endorses the edited page
* (confirm it); reject = dismiss, the page stays lowered; revert
* (`revertLoweredPage`) = restore the prior owner version's content and tier.
+ * - #6550 marker repair (`repairPageMarker`, local CLI only): rewrite a page's
+ * `trust_tier: unknown` marker to its stored tier (removed at owner tiers);
+ * the row keeps its tier. trust/marker-repair.ts decides which pages.
*
* Every function here runs after the caller established the owner's
* confirmation (trust/confirm.ts); each re-checks the page revision it was
@@ -42,7 +45,7 @@ import {
decisionResult, registerTrustProposalHandler, transitionTrustProposal, type TrustProposalAction,
type TrustDecisionContext, type TrustDecisionResult, type TrustProposalRow,
} from './proposals.ts';
-import { effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
+import { OWNER_TIER_FLOOR, compareTrust, effectiveWriteTrust, storedTrustTier, type TrustTier, type WriteTrust } from './tier.ts';
/** The journaled operation that publishes an owner page action on a managed brain. */
export const TRUST_OWNER_PAGE_OPERATION = 'trust_owner_page';
@@ -75,9 +78,10 @@ function changedSincePreview(ref: string, what: string): Error {
'Run the command again: it shows the page as it is now and asks for a new confirmation.');
}
-/** The page with the CEO-21 marker removed, as canonical markdown. */
-function markdownWithoutMarker(snapshot: PageSnapshot): string {
- const { trust_tier: _marker, ...frontmatter } = (snapshot.page.frontmatter ?? {}) as Record<string, unknown>;
+/** The page with the CEO-21 marker removed (or set to `marker`), as canonical markdown. */
+function markdownWithoutMarker(snapshot: PageSnapshot, marker: TrustTier | null = null): string {
+ const { trust_tier: _marker, ...rest } = (snapshot.page.frontmatter ?? {}) as Record<string, unknown>;
+ const frontmatter = marker ? { ...rest, trust_tier: marker } : rest;
return serializeMarkdown(frontmatter, snapshot.page.compiled_truth ?? '', snapshot.page.timeline ?? '', {
type: (snapshot.page.type as PageType) ?? 'note', title: snapshot.page.title ?? '', tags: snapshot.tags,
});
@@ -159,7 +163,7 @@ export interface PageActionInput {
}
export interface PageActionResult {
- status: 'confirmed' | 'reverted' | 'unchanged';
+ status: 'confirmed' | 'reverted' | 'repaired' | 'unchanged';
ref: string;
tier: TrustTier;
prior_tier: TrustTier;
@@ -168,7 +172,7 @@ export interface PageActionResult {
}
type OwnerPageIntent = {
- mode: 'confirm' | 'revert';
+ mode: 'confirm' | 'revert' | 'repair_marker';
expected_revision: string;
version_id?: number;
via: OwnerConfirmation['via'];
@@ -209,6 +213,23 @@ export async function confirmPage(engine: BrainEngine, input: PageActionInput):
return { status: 'confirmed', ref, tier: 'user_confirmed', prior_tier: state.tier, marker_removed: true };
}
+/** #6550: the marker a repaired page carries: its stored tier, none at owner tiers (CEO-21 stamps none there). */
+export const repairedMarker = (tier: TrustTier): TrustTier | null => compareTrust(tier, OWNER_TIER_FLOOR) >= 0 ? null : tier;
+
+const ACTION_NAMES: Record<OwnerPageIntent['mode'], string> = { confirm: 'its confirmation', revert: 'the revert', repair_marker: 'the marker repair' };
+
+/** #6550: rewrites the page's marker to `repairedMarker(stored tier)`, bound to the previewed revision; the row keeps its tier. */
+export async function repairPageMarker(engine: BrainEngine, input: PageActionInput): Promise<PageActionResult & { marker: TrustTier | null }> {
+ const ref = pageRef(input.sourceId, input.slug);
+ const state = await readPageTrustState(engine, input.sourceId, input.slug);
+ if (!state) throw opError('page_not_found', `No live page ${ref}.`, 'Run gbrain trust backfill --repair-unknown-markers again to see the current candidates.');
+ if (state.revision !== input.expectedRevision) throw changedSincePreview(ref, ACTION_NAMES.repair_marker);
+ const marker = repairedMarker(state.tier);
+ await publishOwnerPage(engine, input, { mode: 'repair_marker', expected_revision: input.expectedRevision, via: input.confirmation.via },
+ markdownWithoutMarker(state.snapshot, marker), state.tier);
+ return { status: 'repaired', ref, tier: state.tier, prior_tier: state.tier, marker };
+}
+
/** The tier a version restores: its snapshot tier, `unknown` for legacy versions. */
export const versionTier = (version: { trust_tier?: string | null }): TrustTier => storedTrustTier(version.trust_tier);
@@ -242,10 +263,10 @@ async function publishOwnerPage(engine: BrainEngine, input: PageActionInput, int
await engine.transaction(tx => withWriteAttribution(tx, { ...attribution, trust }, () => withTrustPromotion(tx, tier, () =>
withTrustKeep(tx, FENCE_TABLES, async () => {
if ((await tx.readPageSnapshot(input.slug, { sourceId: input.sourceId }))?.revision !== input.expectedRevision) {
- throw changedSincePreview(pageRef(input.sourceId, input.slug), intent.mode === 'confirm' ? 'its confirmation' : 'the revert');
+ throw changedSincePreview(pageRef(input.sourceId, input.slug), ACTION_NAMES[intent.mode]);
}
// forceRechunk: the trust_tier marker is hash-ephemeral, so removing it alone would read as unchanged content.
- await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, preserveGateMarkers: intent.mode === 'confirm', forceRechunk: true, allowEmptyOverwrite: intent.mode === 'revert' });
+ await importFromContent(tx, input.slug, markdown, { sourceId: input.sourceId, noEmbed: true, preserveGateMarkers: intent.mode !== 'revert', forceRechunk: true, allowEmptyOverwrite: intent.mode === 'revert' });
await closeProposal(tx, intent.proposal, input.by);
}))));
}
@@ -284,14 +305,14 @@ async function submitOwnerPage(engine: BrainEngine, input: PageActionInput, inte
*/
export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const intent = row.intent as unknown as OwnerPageIntent | null;
- if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || (intent.mode !== 'confirm' && intent.mode !== 'revert') || typeof intent.expected_revision !== 'string'
- || (row.authority.remote && !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE))) {
+ if (row.operation !== TRUST_OWNER_PAGE_OPERATION || !intent || !Object.hasOwn(ACTION_NAMES, intent.mode) || typeof intent.expected_revision !== 'string'
+ || (row.authority.remote && (intent.mode === 'repair_marker' || !(row.authority.scopes ?? []).includes(MEMORY_CONFIRM_SCOPE)))) {
throw opError('confirmation_required', 'This owner page action is not confirmed by the owner; nothing was changed.',
'Run the gbrain trust command on the brain host in an interactive terminal.');
}
const ref = pageRef(row.source_id, row.slug);
const state = await readPageTrustState(engine, row.source_id, row.slug);
- if (!state || state.revision !== intent.expected_revision) throw changedSincePreview(ref, intent.mode === 'confirm' ? 'its confirmation' : 'the revert');
+ if (!state || state.revision !== intent.expected_revision) throw changedSincePreview(ref, ACTION_NAMES[intent.mode]);
let content: string;
let tags: string[] | undefined;
let tier: TrustTier = 'user_confirmed';
@@ -301,6 +322,9 @@ export async function prepareTrustOwnerPageMutation(engine: BrainEngine, row: Wr
content = versionMarkdown(state.snapshot, version);
tags = version.tags ?? undefined;
tier = versionTier(version);
+ } else if (intent.mode === 'repair_marker') {
+ tier = state.tier;
+ content = markdownWithoutMarker(state.snapshot, repairedMarker(tier));
} else content = markdownWithoutMarker(state.snapshot);
// The request keeps its own operation, so page-prepare stamps no CEO-21 marker and files no lower_page item for it.
const { preparePageMutation } = await import('../persistence/page-prepare.ts');
diff --git a/src/core/trust/review.ts b/src/core/trust/review.ts
index 1c7698f2d9..db821797ec 100644
--- a/src/core/trust/review.ts
+++ b/src/core/trust/review.ts
@@ -20,6 +20,7 @@ import { opError } from '../ops/contract.ts';
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 { TRUST_MARKER_REPAIR_COMMAND } from './marker-repair.ts';
import { formatTrustRef, pageRef, parseTrustRef, resolvePageRef } from './refs.ts';
import { compareTrust, OWNER_TIER_FLOOR, storedTrustTier, trustLabel, USER_SAID_ORIGIN_MARKER, type TrustTier } from './tier.ts';
import { isUserSaid, trustFields, trustLabelWords } from '../eligibility/labels.ts';
@@ -46,7 +47,7 @@ export interface TrustReviewItem {
label: string;
summary: string;
/** Complete argv per decision (DX-7). Tier-raising ones are the user's to run on a TTY (DX-3). */
- commands: Partial<Record<'confirm' | 'drop' | 'release' | 'revert' | 'explain', string[]>>;
+ commands: Partial<Record<'confirm' | 'drop' | 'release' | 'revert' | 'repair' | 'explain', string[]>>;
}
export interface TrustReviewFilter {
@@ -113,7 +114,15 @@ async function pageOf(engine: BrainEngine, p: TrustProposalRow): Promise<string
return null;
}
-function proposalItem(p: TrustProposalRow, page: string | null): TrustReviewItem {
+/** #6550: an agent edit lowered the page to unknown only because its frontmatter still carries an `unknown` marker. */
+async function loweredByUnknownMarker(engine: BrainEngine, p: TrustProposalRow): Promise<boolean> {
+ const s = lowerPageState(p);
+ if (s.edited_tier !== 'unknown' || s.prior_tier === 'unknown') return false;
+ const [row] = await engine.executeRaw<{ marker: string | null }>(`SELECT frontmatter->>'trust_tier' AS marker FROM pages WHERE id = $1`, [p.target_id]);
+ return row?.marker === 'unknown';
+}
+
+function proposalItem(p: TrustProposalRow, page: string | null, markerRepair = false): TrustReviewItem {
const ref = trustProposalRef(p.id);
if (p.action === 'lower_page') {
const s = lowerPageState(p);
@@ -121,7 +130,8 @@ function proposalItem(p: TrustProposalRow, page: string | null): TrustReviewItem
ref, kind: 'lowered_page', detail: p.action, source_id: p.source_id, page, day: day(p.updated_at), created_at: p.created_at,
tier: s.edited_tier, label: trustLabel(s.edited_tier),
summary: `An agent edit lowered ${page ?? `page ${p.target_id}`} from "${trustLabel(s.prior_tier)}" to "${trustLabel(s.edited_tier)}"`,
- commands: { confirm: trust('confirm', ref), ...(s.version_id !== null ? { revert: trust('revert', ref) } : {}), drop: trust('drop', ref), explain: trust('explain', ref) },
+ commands: { confirm: trust('confirm', ref), ...(s.version_id !== null ? { revert: trust('revert', ref) } : {}), drop: trust('drop', ref),
+ ...(markerRepair ? { repair: [...TRUST_MARKER_REPAIR_COMMAND] } : {}), explain: trust('explain', ref) },
};
}
const tier = storedTrustTier(p.after_state.tier ?? p.before_state.related_tier ?? p.before_state.new_tier);
@@ -178,7 +188,7 @@ export async function buildTrustReview(engine: BrainEngine, filter: TrustReviewF
: filter.kind === 'lowered_page' ? 'lower_page' : undefined;
for (const p of await listTrustProposals(engine, { status: 'pending', sourceId: filter.sourceId, action, since: filter.since, limit: 1000 })) {
if (filter.kind === 'proposal' && p.action === 'lower_page') continue;
- items.push(proposalItem(p, await pageOf(engine, p)));
+ items.push(proposalItem(p, await pageOf(engine, p), p.action === 'lower_page' && await loweredByUnknownMarker(engine, p)));
}
}
if (wants(filter, 'preference')) items.push(...await standingPreferences(engine, filter));
diff --git a/test/fixtures/goldens/trust/help.txt b/test/fixtures/goldens/trust/help.txt
index 0c18b9d1ee..0be3a317a6 100644
--- a/test/fixtures/goldens/trust/help.txt
+++ b/test/fixtures/goldens/trust/help.txt
@@ -32,6 +32,13 @@ Usage: gbrain trust backfill [--dry-run] [--resume] [--batch-size N] [--json]
"confirmed by you". --dry-run is read-only (no migrations, no writes) and works before the trust migration;
it reports the projected count per table and tier. --resume continues an interrupted run.
+Usage: gbrain trust backfill --repair-unknown-markers [--source ID] [--slug SLUG ... --expect HASH] [--json]
+ Lists pages whose trust_tier frontmatter marker is "unknown" while their stored tier is higher (an agent edit
+ before v0.60.249.0 stamped it), with the evidence for each, and ends with the exact apply command. Nothing is
+ classified for you: apply rewrites only the pages you name with --slug (repeatable), at the revisions of the
+ preview whose hash you pass to --expect. The marker becomes the stored tier (none at owner tiers); the tier
+ stays. Local CLI only. Docs: docs/guides/memory-trust.md#repair-unknown-markers
+
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 it reads as flagged (and, under trust.agent_activation
diff --git a/test/trust-channel-writes.test.ts b/test/trust-channel-writes.test.ts
index 51f2ba5e83..096b35dfb5 100644
--- a/test/trust-channel-writes.test.ts
+++ b/test/trust-channel-writes.test.ts
@@ -288,6 +288,74 @@ describe('channel tiers on journaled writes', () => {
}
}), 90_000);
+ test('#6550 repair: a marker stamped before the fix files a spurious lower_page; the approved repair stops it and leaves unnamed and deliberate markers alone', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const b = await brain(engine);
+ const backfill = (slug: string) => b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => withTrustBackfill(tx, () => tx.executeRaw(
+ `UPDATE pages SET trust_tier='agent_written' WHERE source_id=$1 AND slug=$2`, [b.sourceId, slug])), TEST_WRITE_ATTRIBUTION));
+ const edit = async (slug: string, body: string) => {
+ const got = await run(b.remote, 'get_page', { slug, include_content: true });
+ return run(b.remote, 'put_page', { slug, content: String(got.content ?? '').replace(/\n[^\n]*\n?$/, `\n${body}\n`), force: true });
+ };
+ const lowerItems = async (slug: string) => (await listTrustProposals(engine, { sourceId: b.sourceId, action: 'lower_page' }))
+ .filter(p => p.target_id === Number(rowIds.get(slug)));
+ const rowIds = new Map<string, number>();
+ // A legacy page the pre-fix release stamped: imported clean, then agent edits carried `trust_tier: unknown`.
+ const stamped = async (slug: string) => {
+ await run(b.local, 'put_page', { slug, content: page('Legacy', 'Written before trust tiers.') });
+ await b.engine.transaction(tx => withCoordinatedWrite(tx, [b.sourceId], () => tx.executeRaw(
+ `UPDATE pages SET trust_tier='unknown', frontmatter = frontmatter - 'trust_tier' - 'source_kind' - 'ingested_via' WHERE source_id=$1 AND slug=$2`,
+ [b.sourceId, slug]), TEST_WRITE_ATTRIBUTION));
+ await run(b.remote, 'put_page', { slug, content: page('Legacy', 'Stamped by an old agent edit.', 'trust_tier: unknown\n'), force: true });
+ await edit(slug, 'Edited again before the fix.');
+ };
+ for (const slug of ['notes/legacy-a', 'notes/legacy-c']) await stamped(slug);
+ // A deliberate marker: the page was imported with it.
+ await run(b.local, 'put_page', { slug: 'notes/marked-b', content: page('Marked', 'Unverified on purpose.', 'trust_tier: unknown\n') });
+ await edit('notes/marked-b', 'An agent added a line.');
+ for (const slug of ['notes/legacy-a', 'notes/legacy-c', 'notes/marked-b', 'notes/legacy-d']) {
+ if (slug === 'notes/legacy-d') await stamped(slug);
+ const row = await pageRow(b, slug);
+ rowIds.set(slug, Number(row.id));
+ expect(row.frontmatter.trust_tier).toBe('unknown');
+ await b.engine.executeRaw(`UPDATE page_versions SET snapshot_at = '2026-09-01T00:00:00Z' WHERE page_id = $1`, [row.id]);
+ await backfill(slug);
+ }
+ // Without a repair, the round trip after the backfill files a spurious lower_page.
+ await edit('notes/legacy-d', 'Edited after the backfill.');
+ expect((await pageRow(b, 'notes/legacy-d')).trust_tier).toBe('unknown');
+ expect(await lowerItems('notes/legacy-d')).toHaveLength(1);
+ const { applyMarkerRepair, previewMarkerRepair, renderMarkerRepairPreview } = await import('../src/core/trust/marker-repair.ts');
+ const review = await buildTrustReview(engine, { sourceId: b.sourceId });
+ expect(review.items.find(i => i.page === `p:${b.sourceId}/notes/legacy-d`)?.commands.repair).toEqual(['gbrain', 'trust', 'backfill', '--repair-unknown-markers']);
+ const preview = await previewMarkerRepair(engine, { sourceId: b.sourceId });
+ const bySlug = new Map(preview.candidates.map(c => [c.slug, c]));
+ expect([...bySlug.keys()]).toEqual(['notes/legacy-a', 'notes/legacy-c', 'notes/marked-b']);
+ expect(bySlug.get('notes/legacy-a')).toMatchObject({ marker: 'unknown', stored_tier: 'agent_written', proposed_marker: 'agent_written', proposed_tier: 'agent_written',
+ assessment: 'consistent_with_6550', evidence: { relative_to_fixed_release: 'before', in_original_import: false } });
+ expect(bySlug.get('notes/marked-b')).toMatchObject({ assessment: 'ambiguous', evidence: { in_original_import: true } });
+ expect(preview.lowered.map(l => l.page)).toEqual([`p:${b.sourceId}/notes/legacy-d`]);
+ expect(preview.apply_command).toEqual(['gbrain', 'trust', 'backfill', '--repair-unknown-markers', '--source', b.sourceId,
+ '--slug', 'notes/legacy-a', '--slug', 'notes/legacy-c', '--expect', preview.preview_hash]);
+ const text = renderMarkerRepairPreview(preview);
+ expect(text.trimEnd().split('\n').at(-1)).toBe(`Apply with: gbrain trust backfill --repair-unknown-markers --source ${b.sourceId} --slug notes/legacy-a --slug notes/legacy-c --expect ${preview.preview_hash}`);
+ await expect(applyMarkerRepair(engine, { slugs: ['notes/legacy-a'], expect: 'mr_0000000000000000', sourceId: b.sourceId })).rejects.toMatchObject({ code: 'preview_changed' });
+ // The operator names only legacy-a.
+ const applied = await applyMarkerRepair(engine, { slugs: ['notes/legacy-a'], expect: preview.preview_hash, sourceId: b.sourceId });
+ expect(applied.repaired).toEqual([{ page: `p:${b.sourceId}/notes/legacy-a`, marker_before: 'unknown', marker_after: 'agent_written', tier: 'agent_written' }]);
+ expect((await pageRow(b, 'notes/legacy-a')).frontmatter.trust_tier).toBe('agent_written');
+ await edit('notes/legacy-a', 'Edited after the repair.');
+ expect((await pageRow(b, 'notes/legacy-a')).trust_tier).toBe('agent_written');
+ expect(await lowerItems('notes/legacy-a')).toHaveLength(0);
+ for (const slug of ['notes/legacy-c', 'notes/marked-b']) {
+ const row = await pageRow(b, slug);
+ expect([row.frontmatter.trust_tier, row.trust_tier]).toEqual(['unknown', 'agent_written']);
+ }
+ // A stale hash refuses: the preview changed when legacy-a was repaired.
+ await expect(applyMarkerRepair(engine, { slugs: ['notes/legacy-c'], expect: preview.preview_hash, sourceId: b.sourceId })).rejects.toMatchObject({ code: 'preview_changed' });
+ }
+ }), 120_000);
+
test('CEO-12: an agent rewrite of an owner page lowers it and files one lower_page proposal that later edits fold into', async () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
const b = await brain(engine);
diff --git a/test/trust-cli.test.ts b/test/trust-cli.test.ts
index 94cee1b94f..a8cede4fb6 100644
--- a/test/trust-cli.test.ts
+++ b/test/trust-cli.test.ts
@@ -39,6 +39,23 @@ describe('gbrain trust help (DX-7)', () => {
expect(lines.join('\n')).toContain('Usage: gbrain trust <review|confirm');
});
+ test('#6550: --repair-unknown-markers applies only with both --slug and --expect, refusing before touching the engine', async () => {
+ const { run } = await import('../src/cli/commands/trust.ts');
+ const errors: string[] = [];
+ const error = console.error;
+ const write = process.stderr.write;
+ console.error = (...args: unknown[]) => { errors.push(args.join(' ')); };
+ process.stderr.write = ((chunk: string | Uint8Array) => { errors.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try {
+ for (const args of [['--slug', 'notes/a'], ['--expect', 'mr_0123456789abcdef'], ['--slug', 'notes/a', '--expect']]) {
+ await run(null as never, ['backfill', '--repair-unknown-markers', ...args], {} as never);
+ expect(process.exitCode).toBe(2);
+ process.exitCode = 0;
+ }
+ } finally { console.error = error; process.stderr.write = write; }
+ expect(errors.join('\n')).toContain('needs both the pages (--slug, repeatable) and the preview hash (--expect)');
+ });
+
test('quarantine help lists the trust aliases', async () => {
const r = await runCli(['quarantine', '--help'], { home });
expect(r.stdout).toContain('release <h<id>> | drop <h<id>>');