Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Fix trust caps on legacy chronicle events, legacy-token MCP surface, purge leftovers, encoded secrets, drift report provenance
garrytand75511f8508d
diff --git a/behavior-changes.d/audit_secrets_escaped_encoded_8265.md b/behavior-changes.d/audit_secrets_escaped_encoded_8265.mdnew file mode 100644index 0000000000..04aaa85571--- /dev/null+++ b/behavior-changes.d/audit_secrets_escaped_encoded_8265.md@@ -0,0 +1 @@+The opt-in high-entropy assignment detector now also catches a credential whose key quote is escaped (`{\"password\":\"…\"}`, JSON inside a JSON string, with up to three backslashes) and one after a URL-encoded separator (`password%3D…`, `token%3A…`). The value stops before an escaped closing quote and, after an encoded separator, before the next `%26` parameter; a URL-encoded URL value is treated as a reference, not a secret. `gbrain doctor` asks once for a fresh `gbrain transcripts audit-secrets` run: it is read-only, makes no model or network call, and on a 5 MB synthetic transcript took about a third of a second. Pages that hold such a line show up as affected; import-time redaction is unchanged.diff --git a/behavior-changes.d/chronicle_events_trust_cap_9284.md b/behavior-changes.d/chronicle_events_trust_cap_9284.mdnew file mode 100644index 0000000000..4a7feaeccb--- /dev/null+++ b/behavior-changes.d/chronicle_events_trust_cap_9284.md@@ -0,0 +1 @@+Legacy Life Chronicle event pages (captured_via: life-chronicle:auto) are now capped at agent_written and at the tier of their depth page when gbrain trust claim-sources lifts a source, so they no longer read as your own notes; rows a claim already lifted change only when you run gbrain trust claim-sources --relower (preview with gbrain trust claim-sources --relower --dry-run first, and add --source <id> for a source whose claim has ended), and gbrain doctor counts them.diff --git a/docs/architecture/key-files/core-cycle-patterns.md b/docs/architecture/key-files/core-cycle-patterns.mdindex 9fff90d4db..06dac4ced6 100644--- a/docs/architecture/key-files/core-cycle-patterns.md+++ b/docs/architecture/key-files/core-cycle-patterns.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELPatterns, drift reports and the cycle modules listed after them.- `src/core/cycle/patterns.ts` — Patterns phase: cross-session theme detection over reflections within `dream.patterns.lookback_days` (default 30). Names a pattern only when ≥`dream.patterns.min_evidence` (default 3) reflections support it. Reflection excerpts use the shared UTF-16-safe truncator; a raw `.slice(0, 600)` can split an emoji pair and make Postgres reject the subagent job's JSONB payload. Single Sonnet subagent; same allow-list path as synthesize (imports `loadAllowedSlugPrefixes` + `loadOutputRoot` from synthesize.ts — the reflections lookup, prompt slug templates, and allow-list all honor `dream.synthesize.output_root`, default 'wiki'). Subagent job/wait timeouts are config keys `dream.patterns.subagent_timeout_ms` / `dream.patterns.subagent_wait_timeout_ms` (defaults 30/35 min, mirroring the `dream.synthesize.*` pair). The phase status reflects the child outcome: non-`completed` outcome with zero writes → `fail` (error code `PATTERNS_CHILD_<OUTCOME>`); non-`completed` with partial writes → `warn`. Runs AFTER `extract` so the graph is fresh. The fan-out sets `require_writes: true` so an all-writes-failed child dead-letters instead of reporting completed. Budget clamping: clamped to the remaining parent-job budget via `clampSubagentBudgets` when the cycle threads `deadlineAtMs` — the clamp template synthesize.ts reuses; `MIN_PATTERNS_SUBAGENT_BUDGET_MS` gates an honest skip, and `CYCLE_DEADLINE_RESERVE_MS` is re-exported here from its base-phase.ts home. Evidence watermark: a `completed` child stamps the newest consumed reflection `updated_at` into the state row `dream.patterns.last_evidence_ts` (never `now()`; fail/warn/timeout paths don't stamp, so a dead child retries next tick), and a later run skips `no_new_evidence` while no reflection in the window is newer — autopilot's hourly global tick becomes a free skip until a reflection actually changes; an absent/unparseable stamp fails open; `--once` bypasses the gate but a completed forced run still s... (line truncated to 2000 chars) Reflection excerpts in the subagent prompt and the quote-grounding sources are the reflection's `publicBody`, so neither carries a facts row other than world or a takes row (test: `test/cycle-world-fence-rows.test.ts`).-- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws.+- `src/core/cycle/drift.ts` report publication (#6052): a managed drift report whose publish is held (`publishOrHold`) is not linked in the detail, `reports_written` is 0 and `publish_deferred` 1, the detail names the hold (accepted and still publishing, or not admitted under database contention), and the phase is `partial`; every other publish error still throws. Both publish paths carry the report's derivation (#9208): channel `derive:drift` over the judged pages, whose timeline entries are the judge's evidence, so the report takes their least trusted tier capped at `agent_written`.- `src/core/cycle/phases/consolidate.ts` — the consolidate phase: clusters facts per page and promotes the best claim into a take. `cycle.consolidate.enabled` (default on; an explicit falsy value returns `skipped`, #6667) is read inside the phase; `dream --phase consolidate --once` bypasses it. Take identity for the upsert lookup is `(page_id, claim)` restricted to rows this phase authors (`kind='fact' AND holder='self'`) — `since_date` is NOT identity (it derives from MIN(valid_from) of the cluster and moves whenever extract_facts re-inserts, which degraded the lookup into duplicate INSERTs); deliberately NOT filtered on `active` (a superseded take still owns its claim — skipping it would resurrect a retired claim via the INSERT path); `ORDER BY id` keeps the pick deterministic across pre-existing duplicate rows. A resolved take is immutable — its id is reused for consolidation but the row is left untouched. Managed local consolidation passes the cycle source ID, publishes take, contributing facts and validity changes atomically: a fenced member on the entity page is closed in its `## Facts` fence row in the same page publication and its `valid_until` derives from that cell, an unfenced member is closed in the database, and a member fenced on another page stays open (test `test/consolidate-fenced-close-reimport.test.ts`). Retired/resolved matching takes produce a durable skipped receipt; semantic intent excludes vectors/timestamps/cache metadata, while a genuine newer fact/page snapshot changes request identity. Only live world-visible evidence is promoted; private facts remain private. #5575 ENG-3: fact tiers are read per bucket and external_untrusted facts cluster in a separate pass, so an external claim never shares a take with owner facts. Each cluster's take is written at `derive:consolidate` = min(cluster fact tiers, agent_written): unmanaged, the take insert or re-promotion, consolidation marks and valid_until writeback are one `derivedMaintenanceTransaction` (a re-promotion lowers the existing take to min(existing, cluster), even a resolved one); managed, the request carries `declareDerivation`. Edges: take -> every cluster fact. The unmanaged path runs the write gate (`decideTakeWrite`, config read once per run via `loadImportSanityConfig`) on each... (line truncated to 2000 chars)diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex e9e3145bb9..a5990bbbf7 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/mcp-registration.ts` — `REGISTRATION_SURFACE` (`full` since S0, wave 0: callable and advertised; README, docs/mcp, INSTALL_FOR_AGENTS.md and the plugin manifests name the same value, which the S0 grep test in `test/mcp-registration.test.ts` keeps so), `stdioServeArgv(bin, surface = REGISTRATION_SURFACE)` (`null` → bare `serve`) and `registeredSurface(text)` (an existing entry's pinned surface, `null` for bare, `undefined` when no serve command is visible): every stdio registration gbrain writes builds from them (readiness `harness_wiring`, init's quickstart, `bootstrap hooks` for Claude Code / Codex / opencode, the plugin generator, which also refuses root plugin manifests pinned elsewhere). The OpenClaw manifest stays a bare `serve`. Also the HTTP+bearer wiring helpers `connect.ts` re-exports. Test: `test/mcp-registration.test.ts`.- `src/core/serve-log.ts` — serve's own log hygiene (#7246), installed by `src/cli/commands/serve.ts` before `runServe`. For each of stderr, and stdout under `--http` only (stdio serve's stdout is the JSON-RPC channel), whose descriptor is a regular file, it routes console and stream writes through a `ServeLogFile`: `LineDeduper` writes the first occurrence of a line at once and counts repeats inside the window (a leading timestamp ignored), then writes one `[gbrain serve-log] repeated N more time(s) in the last Ws: <line>` line when the window ends or the process exits; rotation is copy-then-truncate on the inherited append-mode descriptor (`<log>.N-1` → `<log>.N`, `<log>` → `<log>.1`, truncate), each write placed at the file's current end, and only when the descriptor's path is known (`/proc/self/fd` or the `serveLogPath`/`serveErrPath` inode) and still names the same inode. TTYs, pipes and journald are untouched. `GBRAIN_SERVE_LOG_MAX_BYTES` (10 MiB; 0 off), `GBRAIN_SERVE_LOG_MAX_FILES` (5), `GBRAIN_SERVE_LOG_DEDUPE_SECONDS` (600; 0 off). Tests: `test/serve-log-7246.test.ts`.- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`; D1: an empty list or one with no caller-visible name returns the catalog plus `did_you_mean` drawn only from `visibleOpsForCaller`, never echoing the requested names, so an invisible existing op and a nonexistent one answer byte-identically), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. `{tools}` returns each visible op's registry schema, so a starter client also gets the `fullSurfaceOnly` params its tools/list leaves out (dispatch accepts them on every surface). `{surface, tools}` together (GBRA-449) runs the `{surface}` branch first, exactly as alone (refusals included), then the `{tools}` branch against the resulting surface, and answers the descriptor shape plus `surface_change` (the surface answer). Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`, `test/request-tools-combined-gbra449.test.ts`.-- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject; reads `--surface v` and `--surface=v` through `flagValues` in `src/core/direct-pool-profile.ts`, and a repeated flag takes the narrowest), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases). `--access read-only` (`parseAccessFlag`, either form through `flagValues`, any read-only value wins; stdio only; HTTP refuses it) intersects the surface with `isReadOnlyOperation` (read scope, not mutating, no required capability scope); `src/mcp/server.ts` uses that one set for tools/list, the capabilities resource (`access`), skill resources and dispatch `allowedOps`. Pinned by `test/serve-stdio-read-only.test.ts`. `mcp.advertised_surface` (`resolveAdvertisedSurface`, DB plane > file plane) narrows only what `tools/list` shows (`advertisedOps`, never wider than the callable set); dispatch keeps the ceiling. Stdio lists the advertised set plus tools `request_tools` described in this session (`OperationContext.revealTools` → `tools/list_changed`); the OAuth HTTP server lists a client's own row surface in full and otherwise the advertised set; the simple bearer transport reads the file plane once at startup. Initialize instructions carry `hiddenCallable` and name `request_tools` when tools are unlisted. `NEW_INSTALL_ADVERTISED_SURFACE` is what a fresh `gbrain init` writes (`'full'` writes nothing; the held-out agent benchmark picks verbs or starter). Pinned by `test/mcp-advertised-surface.test.ts`. Once a session widens (`request_tools {surface}`), the whole widened surface is listed.+- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject; reads `--surface v` and `--surface=v` through `flagValues` in `src/core/direct-pool-profile.ts`, and a repeated flag takes the narrowest), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped), gives a legacy bearer token (`principal.kind === 'legacy_token'`, no client row) the clamped ceiling instead of the DCR default (#9266), and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases). `--access read-only` (`parseAccessFlag`, either form through `flagValues`, any read-only value wins; stdio only; HTTP refuses it) intersects the surface with `isReadOnlyOperation` (read scope, not mutating, no required capability scope); `src/mcp/server.ts` uses that one set for tools/list, the capabilities resource (`access`), skill resources and dispatch `allowedOps`. Pinned by `test/serve-stdio-read-only.test.ts`. `mcp.advertised_surface` (`resolveAdvertisedSurface`, DB plane > file plane) narrows only what `tools/list` shows (`advertisedOps`, never wider than the callable set); dispatch keeps the ceiling. Stdio lists the advertised set plus tools `request_tools` described in this session (`OperationContext.revealTools` → `tools/list_changed`); the OAuth HTTP server lists a client's own row surface in full and otherwise the advertised set; the simple bearer transport reads the file plane once at startup. Initialize instructions carry `hiddenCallable` and name `request_tools` when tools are unlisted. `NEW_INSTALL_ADVERTISED_SURFACE` is what a fresh `gbrain init` writes (`'full'` writes nothing; the held-out agent benchmark picks verbs or starter). Pinned by `test/mcp-advertised-surface.test.ts`. Once a session widens (`request_tools {surface}`), the whole widened surface is listed.- `src/mcp/tool-catalog.ts` — `renderToolCatalogMarkdown()`: the docs/TOOL_CATALOG.md renderer. Config-independent + deterministic (no engine/config reads, no timestamps): non-localOnly ops grouped one section per `Operation.area`, per-op first-sentence description (from `buildToolDefs`'s non-strict shape), scope, STARTER_OPS membership, publish-gate key. Generated by `scripts/generate-tool-catalog.ts`; freshness-guarded by `scripts/check-tool-catalog-fresh.sh` in `bun run verify` (the METRIC_GLOSSARY pattern). Pinned by test/tool-catalog.test.ts.diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.mdindex fd63f38957..927c9cc362 100644--- a/docs/operations/mcp-surface-runbook.md+++ b/docs/operations/mcp-surface-runbook.md@@ -149,6 +149,8 @@ Dual-plane read (DB > file), applied on each client's next request,ceiling-bounded like everything else; unset means NULL-surface clientsresolve to the server ceiling. Pre-seed importantclients with an explicit `rescope-client --surface full` before flipping it.+The default applies to OAuth clients only; legacy bearer tokens keep the+server ceiling and stay bounded by their scope, source and operation grants.## Move 3 — flip strict params from warn to rejectdiff --git a/src/commands/doctor/checks/trust-sources-unclaimed.ts b/src/commands/doctor/checks/trust-sources-unclaimed.tsindex 0c4f73f15a..f1800367e4 100644--- a/src/commands/doctor/checks/trust-sources-unclaimed.ts+++ b/src/commands/doctor/checks/trust-sources-unclaimed.ts@@ -7,14 +7,15 @@* (`gbrain trust claim-sources`, trust/claim.ts). A fresh or empty brain, or a* 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.+ * extract_atoms atoms, #9284 legacy Life Chronicle events) and names the+ * lower-only `claim-sources --relower`, with `--source` flags when a source+ * whose claim has since ended holds such rows. 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 { TRUST_CLAIM_RESUME_COMMAND, claimedSourceSql, notConnectorSourceSql } from '../../../core/trust/claim-state.ts';import { relowerClaimedRows, TRUST_RELOWER_COMMAND, type TrustRelowerReport } from '../../../core/trust/backfill.ts';import { isMissingSchemaObject } from '../../../core/utils.ts';@@ -28,17 +29,21 @@ async function runTrustSourcesUnclaimed(ctx: DoctorContext): Promise<Check[]> {const rows = unclaimed.reduce((n, s) => n + s.legacy_unknown, 0);const details = { unclaimed, pending, legacy_unknown: rows };let relower: TrustRelowerReport;+ let owned: Array<{ id: string; claimed: boolean }>;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'],+ } else if ((relower = await relowerClaimedRows(engine, { dryRun: true, sources: (owned = await engine.executeRaw<{ id: string; claimed: boolean }>(+ `SELECT s.id, ${claimedSourceSql('s')} AS claimed FROM sources s WHERE ${notConnectorSourceSql('s')}`)).map(s => s.id) })).rows > 0) {+ const ended = relower.sources.filter(id => !owned.find(s => s.id === id)?.claimed);+ const named = ended.length ? relower.sources.flatMap(id => ['--source', id]) : [];+ checks.push({ name: 'trust_sources_unclaimed', status: 'warn', details: { ...details, relower: { rows: relower.rows, sources: relower.sources, 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, or Life Chronicle events, from before gbrain recorded that). `+ + `Preview with ${[...TRUST_RELOWER_COMMAND, '--dry-run', ...named].join(' ')}, then run ${[...TRUST_RELOWER_COMMAND, ...named].join(' ')}; it only lowers.`,+ fix: { argv: [...TRUST_RELOWER_COMMAND, ...named], consent: [], actor: 'agent', requires_exclusive: false, verify: VERIFY,+ preview_argv: [...TRUST_RELOWER_COMMAND, '--dry-run', '--json', ...named],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.' });diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex af239ac466..5e5785bc20 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -104,8 +104,10 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {/*** WP4 (D2): resolve this request's effective surface from the caller's- * verified auth. The config default (`mcp.default_surface_dcr`) is read- * dual-plane ONLY when the client row carries no usable surface — the+ * verified auth. A legacy bearer token has no client row to pre-seed, so it+ * keeps the (clamped) ceiling; its scope, source and operation grants still+ * bound it (#9266). The config default (`mcp.default_surface_dcr`) is read+ * dual-plane ONLY when an OAuth client row carries no usable surface — the* common full-surface path pays no extra config read. Unknown row values* are ignored with a warn-once per client (amendment 18). Never throws:* surface resolution must not take a request down. On a default-surface@@ -120,6 +122,7 @@ export function mountMcp(app: Express, ctx: ServeHttpContext): void {// min() can never go below the narrowest surface: a 'verbs' ceiling makes// the row/default resolution a no-op, so skip the awaited config read.if (ceiling === 'verbs') return { ceiling, effective: ceiling };+ if (authInfo.principal?.kind === 'legacy_token') return { ceiling, effective: ceiling };const rowSurface = resolveClientRowSurface(authInfo.surface, authInfo.clientId);if (rowSurface !== null) return { ceiling, effective: minSurface(ceiling, rowSurface) };try {diff --git a/src/core/belief/purge-mirror.ts b/src/core/belief/purge-mirror.tsindex 414a00f218..3e6dc5f030 100644--- a/src/core/belief/purge-mirror.ts+++ b/src/core/belief/purge-mirror.ts@@ -153,6 +153,10 @@ async function replayOne(tx: BrainEngine, intent: PurgeMirrorIntent, ledger: booconst { scrubPurgedNameStores } = await import('../persistence/purge-name-stores.ts');await scrubPurgedNameStores(tx, src, [restored.slug]);}+ const { scrubPurgedSlugHolds, scrubPurgedSlugStores } = await import('../persistence/purge-slug-stores.ts');+ await scrubPurgedSlugStores(tx, src, [restored.slug], { ifPresent: true });+ const [holds] = await tx.executeRaw<{ present: boolean }>("SELECT to_regclass('write_gate_holds') IS NOT NULL AND to_regclass('write_gate_receipts') IS NOT NULL AS present");+ if (holds?.present) await scrubPurgedSlugHolds(tx, src, [{ slug: restored.slug }]);};}} else {diff --git a/src/core/chronicle/publish.ts b/src/core/chronicle/publish.tsindex 2d3aa608e4..07803ed8f4 100644--- a/src/core/chronicle/publish.ts+++ b/src/core/chronicle/publish.ts@@ -44,6 +44,7 @@ import type { ChronicleEventProposal } from './extract-events.ts';import { resolveChronicleEventSlugs } from './event-identity.ts';import { declareDerivation, deriveTrust } from '../trust/taint.ts';import { derivationWriteTrust } from '../trust/page-write.ts';+import { CHRONICLE_CAPTURED_VIA } from '../trust/channel.ts';import { derivedGateConfig, derivedGateInput, timelineRowAllowed } from '../trust/derived-gate.ts';import { assessTimelineForGate, type WriteGateAssessment } from '../write-gate.ts';import { recordWriteGateReceipt } from '../write-gate-store.ts';@@ -54,10 +55,9 @@ import { planManagedGeneration, recordActivation, type ActivationIntent } from 'import { CHRONICLE_EVENT_KIND, CHRONICLE_RETIRED_BY, chronicleEventAdapter, chronicleEventItem, chronicleOwnerKey, depthInputPin, depthPinBroken,orphanedDepthKeys, ownedEventHashes, pinDepth, verifiedChronicleRetirement, type ChronicleDepthPin, type ChronicleGenerationContext } from '../generations/adapters/chronicle-events.ts';-export { CHRONICLE_RETIRED_BY, depthPinBroken, ownedEventHashes, pinDepth, type ChronicleDepthPin };+export { CHRONICLE_CAPTURED_VIA, CHRONICLE_RETIRED_BY, depthPinBroken, ownedEventHashes, pinDepth, type ChronicleDepthPin };export const CHRONICLE_EVENT_INTENT = 'managed_maintenance_chronicle_event';export const CHRONICLE_RETIRE_INTENT = 'managed_maintenance_chronicle_retire';-export const CHRONICLE_CAPTURED_VIA = 'life-chronicle:auto';export interface BuiltChronicleEvent {slug: string;diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.tsindex 93811b81a4..eebfb86dc3 100644--- a/src/core/cycle/drift.ts+++ b/src/core/cycle/drift.ts@@ -33,6 +33,7 @@ import { serializeMarkdown } from '../markdown.ts';import { OperationError } from '../ops/contract.ts';import { DRIFT_REPORT_KIND, publishSinglePage } from '../generations/adapters/single-page.ts';import { publishOrHold, type PublicationHold } from '../persistence/accepted-pending.ts';+import { declareDerivation, deriveTrust } from '../trust/taint.ts';export interface DriftPhaseOpts {brainDir?: string;@@ -372,17 +373,19 @@ export async function runPhaseDrift(// Typed `note` (+ report_type) so the default pack declares it (#5881).// Lands in the default source (brain-global artifact, same-day re-runs// upsert the same slug).+ const derivation = await deriveTrust(engine, [...new Set(judged.map(j => j.candidate.pageId))].map(id => ({ table: 'pages' as const, id })),+ { channel: 'derive:drift' });if (maintenance) {const snapshot = await engine.readPageSnapshot(reportSlug, { sourceId: 'default' });const report = serializeMarkdown({ report_type: 'drift' }, buildReportBody(judged, config, modelId), '',{ type: 'note', title: `Drift report ${cycleDate}`, tags: [] });// #6052: a held report is not on the page yet, so it is neither linked nor counted as written.reportHold = await publishOrHold(() => publishMaintenancePage(engine, maintenance, reportSlug!, report,- { expectedRevision: snapshot?.revision ?? null, file: false }));+ { expectedRevision: snapshot?.revision ?? null, file: false, derivation: declareDerivation(derivation.trust, derivation.inputs) }));if (reportHold) reportSlug = undefined;} else {try {- await publishSinglePage(engine, { kind: DRIFT_REPORT_KIND, sourceId: 'default', slug: reportSlug, expectedRevision: reportRevision,+ await publishSinglePage(engine, { kind: DRIFT_REPORT_KIND, sourceId: 'default', slug: reportSlug, expectedRevision: reportRevision, derivation,page: { type: 'note', frontmatter: { report_type: 'drift' }, title: `Drift report ${cycleDate}`, compiled_truth: buildReportBody(judged, config, modelId) } });} catch (e) {if (!(e instanceof OperationError && e.code === 'generation_fenced')) throw e;diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 5f5a4b7092..bea2029245 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -42,6 +42,7 @@ import { quoteIdentifier, resolveWriteColumnFromConfigRows } from '../search/embimport { pickCanonicalOrigin } from '../persistence/origin-guard.ts';import { scrubPurgedSlugs } from '../feedback/store.ts';import { scrubPurgedNameStores } from '../persistence/purge-name-stores.ts';+import { scrubPurgedSlugHolds, scrubPurgedSlugStores } from '../persistence/purge-slug-stores.ts';import { expireGonePageFacts } from '../facts/gone-page-facts.ts';/**@@ -211,7 +212,8 @@ export async function deletePage(exec: SqlExecutor, slug: string, opts?: { sourc* RETURNING slug projects the actually-deleted set so the caller can filter* pagesAffected. #9068: the rows that name a deleted page outside any foreign* key (retrieval logs and ratings, the volunteer log, the gazetteer, captured- * eval slugs) go in the same transaction, after the page row: a feedback write+ * eval slugs; #9146: the slug-keyed stores and the slug's write-gate holds) go+ * in the same transaction, after the page row: a feedback write* holding the row commits first and is scrubbed, and a later one finds no page.*/export async function deletePages(exec: SqlExecutor, slugs: string[], opts: { sourceId: string }): Promise<string[]> {@@ -230,6 +232,8 @@ export async function deletePages(exec: SqlExecutor, slugs: string[], opts: { soconst deleted = rows.map(r => r.slug);await scrubPurgedSlugs(tx, opts.sourceId, deleted);await scrubPurgedNameStores(tx, opts.sourceId, deleted);+ await scrubPurgedSlugStores(tx, opts.sourceId, deleted);+ await scrubPurgedSlugHolds(tx, opts.sourceId, deleted.map(slug => ({ slug })));return deleted;});}@@ -351,7 +355,7 @@ export async function purgeDeletedPages(const { rows: texts } = await tx.run<{ source_id: string; sha: string }>(sqlFragment`SELECT DISTINCT m.source_id, encode(m.sha256, 'hex') AS sha FROM page_body_manifest m JOIN pages p ON p.id = m.page_idWHERE p.deleted_at IS NOT NULL AND p.deleted_at < now() - (${hours} || ' hours')::interval${excludedManifest}`);- const { rows } = await tx.run<{ slug: string; source_id: string }>(sqlFragment`+ const { rows } = await tx.run<{ slug: string; source_id: string; deleted_at: string }>(sqlFragment`DELETE FROM pagesWHERE deleted_at IS NOT NULLAND deleted_at < now() - (${hours} || ' hours')::interval@@ -362,7 +366,7 @@ export async function purgeDeletedPages(AND ${trustedSql(atomRetirementPurgeHold('pages'))}-- GBRA-161: every derived retirement waits out its hold (derivedRetirementPurgeHold).AND ${trustedSql(derivedRetirementPurgeHold('pages'))}${excluded}- RETURNING slug, source_id+ RETURNING slug, source_id, deleted_at::text AS deleted_at`);await expireGonePageFacts(tx, rows);if (rows.length) await tx.run(sqlFragment`DELETE FROM page_body_stagings s USING unnest(${rows.map(r => r.source_id)}::text[], ${rows.map(r => r.slug)}::text[]) AS d(source_id, slug)@@ -372,11 +376,14 @@ export async function purgeDeletedPages(WHERE t.source_id = d.source_id AND t.sha256 = decode(d.sha, 'hex')AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)AND NOT ${trustedSql(stagingNeedsTextSql('t'))}`);- const bySource = new Map<string, string[]>();- for (const r of rows) bySource.set(r.source_id, [...bySource.get(r.source_id) ?? [], r.slug]);+ const bySource = new Map<string, Array<{ slug: string; deletedAt: string }>>();+ for (const r of rows) bySource.set(r.source_id, [...bySource.get(r.source_id) ?? [], { slug: r.slug, deletedAt: r.deleted_at }]);for (const [sourceId, purged] of bySource) {- await scrubPurgedSlugs(tx, sourceId, purged);- await scrubPurgedNameStores(tx, sourceId, purged);+ const slugs = purged.map(p => p.slug);+ await scrubPurgedSlugs(tx, sourceId, slugs);+ await scrubPurgedNameStores(tx, sourceId, slugs);+ await scrubPurgedSlugStores(tx, sourceId, slugs);+ await scrubPurgedSlugHolds(tx, sourceId, purged);}const slugs = rows.map((r) => r.slug);return { slugs, count: slugs.length };diff --git a/src/core/persistence/page-purge.ts b/src/core/persistence/page-purge.tsindex 3131503219..b127b6d1d0 100644--- a/src/core/persistence/page-purge.ts+++ b/src/core/persistence/page-purge.ts@@ -62,6 +62,7 @@ import { noteBelief } from '../belief/ledger.ts';import { appendPurgeIntent } from '../belief/purge-mirror.ts';import { scrubPurgedSlugs } from '../feedback/store.ts';import { scrubPurgedNameStores } from './purge-name-stores.ts';+import { scrubPurgedSlugStores } from './purge-slug-stores.ts';import { appendDerivedHidden, bumpPurgeEpoch, derivedBeliefTargets, derivedStreamSlugs, pageLifetimesOf, pagePurgeClaims, redactCarryingFields, redactPurgedKeys, registerLiveCarriers,sourceHasBeliefEvents, type LedgerPurgeReport } from '../belief/purge.ts';@@ -324,13 +325,7 @@ export async function purgePageInTransaction(tx: BrainEngine, row: WriteRequest,if (cleared === null) missingCaches.push('query_cache');removed.query_cache = cleared ?? 0;removed.facts = await count('DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 RETURNING 1', [sourceId, slug]);- removed.take_proposals = await count('DELETE FROM take_proposals WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);- removed.open_loops = await count('DELETE FROM open_loops WHERE source_id=$1 AND page_slug=$2 RETURNING 1', [sourceId, slug]);- removed.core_edit_notices = await count('DELETE FROM core_edit_notices WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);- // #6619: the page's free-text aliases and the redirects that resolve to it; a redirect from this slug to another page stays.- removed.page_aliases = await count('DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 RETURNING 1', [sourceId, slug]);- removed.slug_aliases = await count('DELETE FROM slug_aliases WHERE source_id=$1 AND canonical_slug=$2 RETURNING 1', [sourceId, slug]);- removed.slug_rename_history = await count('DELETE FROM slug_rename_history WHERE source_id=$1 AND new_slug=$2 RETURNING 1', [sourceId, slug]);+ Object.assign(removed, await scrubPurgedSlugStores(tx, sourceId, [slug]));// #6511 [R2]: the preparation sweep's targets, plus the tail past its ceiling and the rows pending at scan time, re-tested here.const recheck = await lookup('tail_recheck', () => recheckRequestsCarrying(tx, sourceId, needles, prepared.sweep,{ exclude: row.id, beforePending: () => faultPoint('purge:pending_recheck', { requestId: row.request_id, sourceId, operation: row.operation }) }));diff --git a/src/core/persistence/purge-deleted.ts b/src/core/persistence/purge-deleted.tsindex 06346d087e..038f29f6b4 100644--- a/src/core/persistence/purge-deleted.ts+++ b/src/core/persistence/purge-deleted.ts@@ -20,6 +20,7 @@ import { ItemRun, type ItemFailure } from '../item-failure.ts';import { readUnreviewedSyncTombstones, syncDeleteHeld } from './sync-delete-tombstones.ts';import { scrubPurgedSlugs } from '../feedback/store.ts';import { scrubPurgedNameStores } from './purge-name-stores.ts';+import { scrubPurgedSlugHolds, scrubPurgedSlugStores } from './purge-slug-stores.ts';import { expireGonePageFacts } from '../facts/gone-page-facts.ts';import { maintenanceTransaction } from './attribution.ts';import { maintenancePublishWaitMs } from './maintenance-wait.ts';@@ -143,12 +144,14 @@ async function expireRecordedTombstones(engine: BrainEngine, olderThanHours: numawait tx.lockPageKeys(slugs.map(slug => ({ sourceId: row.source_id, slug })));return withBeliefBatch(tx, { sourceId: row.source_id, slugs, publicationId, op: 'purge_deleted_pages', hardDeleteEvent: 'page.expired', report },async () => {- const gone = await tx.executeRaw<{ source_id: string; slug: string }>(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} AND ${atomRetirementPurgeHold('pages')} AND ${derivedRetirementPurgeHold('pages')} RETURNING source_id, slug`,+ const gone = await tx.executeRaw<{ source_id: string; slug: string; deleted_at: string }>(`DELETE FROM pages WHERE id = $1 AND deleted_at IS NOT NULL AND deleted_at < now() - ($2 || ' hours')::interval AND ${identityDowngradePurgeHold('pages')} AND ${atomRetirementPurgeHold('pages')} AND ${derivedRetirementPurgeHold('pages')} RETURNING source_id, slug, deleted_at::text AS deleted_at`,[row.id, hours]);await expireGonePageFacts(tx, gone);if (gone.length > 0) {await scrubPurgedSlugs(tx, row.source_id, [row.slug]);await scrubPurgedNameStores(tx, row.source_id, [row.slug]);+ await scrubPurgedSlugStores(tx, row.source_id, [row.slug]);+ await scrubPurgedSlugHolds(tx, row.source_id, [{ slug: row.slug, deletedAt: gone[0].deleted_at }]);}return gone.length > 0;});diff --git a/src/core/persistence/purge-slug-stores.ts b/src/core/persistence/purge-slug-stores.tsnew file mode 100644index 0000000000..288b5c165b--- /dev/null+++ b/src/core/persistence/purge-slug-stores.ts@@ -0,0 +1,52 @@+import type { BrainEngine } from '../engine.ts';++/** Each store keyed to a page by source and slug outside any foreign key, with its slug column, keyed as the purge receipt names it. */+const SLUG_STORES: ReadonlyArray<readonly [table: string, column: string]> = [+ ['take_proposals', 'page_slug'], ['open_loops', 'page_slug'], ['core_edit_notices', 'slug'],+ ['page_aliases', 'slug'], ['slug_aliases', 'canonical_slug'], ['slug_rename_history', 'new_slug'],+];++/**+ * #9146: the six stores keyed to a page by source and slug with no foreign key to pages: proposed takes, open loops,+ * core-edit notices (which keep a copy of the page text), the page's free-text aliases, the redirects that resolve to+ * it and the rename rows that end at it (a redirect from this slug to another page stays). A purge's cascade never+ * reaches them, so every hard delete of a page calls this inside its transaction; a soft delete keeps them, because+ * restore_page can bring the page back. `ifPresent` skips a store the database does not have (a restored archive+ * older than it). Returns rows removed per store, keyed as the purge receipt names them.+ */+export async function scrubPurgedSlugStores(+ engine: Pick<BrainEngine, 'executeRaw'>,+ sourceId: string,+ slugs: readonly string[],+ opts: { ifPresent?: boolean } = {},+): Promise<Record<string, number>> {+ if (!slugs.length) return {};+ const removed: Record<string, number> = {};+ for (const [table, column] of SLUG_STORES) {+ if (opts.ifPresent) {+ const [present] = await engine.executeRaw<{ present: boolean }>('SELECT to_regclass($1) IS NOT NULL AS present', [table]);+ if (!present?.present) continue;+ }+ removed[table] = (await engine.executeRaw(`DELETE FROM ${table} WHERE source_id = $1 AND ${column} = ANY($2::text[]) RETURNING 1`, [sourceId, [...slugs]])).length;+ }+ return removed;+}++/**+ * #9146: the write-gate holds of hard-deleted pages and their receipts. An immediate hard delete drops every hold of+ * the slug, as the direct purge does. A tombstone expiry passes each page's `deletedAt` (text, so microseconds+ * survive) and drops only holds created up to it: a hold that arrived after the soft delete is a later write, kept+ * for review.+ */+export async function scrubPurgedSlugHolds(+ engine: Pick<BrainEngine, 'executeRaw'>,+ sourceId: string,+ pages: ReadonlyArray<{ slug: string; deletedAt?: string | null }>,+): Promise<{ write_gate_holds: number; write_gate_receipts: number }> {+ if (!pages.length) return { write_gate_holds: 0, write_gate_receipts: 0 };+ const holds = (await engine.executeRaw<{ id: string }>(`DELETE FROM write_gate_holds h USING unnest($2::text[], $3::timestamptz[]) AS d(slug, upto)+ WHERE h.source_id = $1 AND h.slug = d.slug AND (d.upto IS NULL OR h.created_at <= d.upto) RETURNING h.id::text AS id`,+ [sourceId, pages.map(p => p.slug), pages.map(p => p.deletedAt ?? null)])).map(h => h.id);+ const receipts = holds.length ? (await engine.executeRaw("DELETE FROM write_gate_receipts WHERE target_table = 'write_gate_holds' AND target_id = ANY($1::text[]) RETURNING 1", [holds])).length : 0;+ return { write_gate_holds: holds.length, write_gate_receipts: receipts };+}diff --git a/src/core/secret-scan-assignment.ts b/src/core/secret-scan-assignment.tsindex ee4100d614..e6cf4afef7 100644--- a/src/core/secret-scan-assignment.ts+++ b/src/core/secret-scan-assignment.ts@@ -80,11 +80,22 @@ export const HIGH_ENTROPY_REQUIRES_NON_DIGIT_RE = /[^0-9]/;// the sentence's full stop and its bare echoes still scrub.// Both keep the 12-4096 bounds and the digit + entropy gates. Each also has// an ESCAPE_BOUNDARY twin (#7978): `\\npassword=…` in escaped tool output.+//+// ESCAPED AND ENCODED SYNTAX (#8265). The key may close, and a quoted value+// open, on up to three backslashes before the quote (`{\"password\":\"…\"}`,+// JSON inside a JSON string), and the separator may be URL-encoded+// (`password%3D…`, `token%3A…`). The quoted value never ends on a backslash,+// so an escaped closing quote stays outside it. After an encoded separator the+// value never takes `%26` (the next encoded parameter; `&` is outside both+// classes), and a quoted value never opens there. The escapes and the encoded+// separator sit in group 1, so offsets and fingerprints stay on the stored+// bytes. A URL-encoded URL (`https%3A%2F%2F…`) is a reference like a plain one.export const assignmentKey = (boundary: string) =>- `${boundary}(?:(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]{0,64}|[A-Za-z][A-Za-z0-9_-]{0,63}[_-]key)["']?\\s*[:=]\\s*`;-export const ASSIGNMENT_QUOTED_SOURCE = (key: string) => `(${key}["'])([^"'\\s]{12,4096})`;+ `${boundary}(?:(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]{0,64}|[A-Za-z][A-Za-z0-9_-]{0,63}[_-]key)(?:\\\\{0,3}["'])?(?:\\s*[:=]\\s*|%3[AaDd])`;+export const ASSIGNMENT_QUOTED_SOURCE = (key: string) => `(${key}(?<!%3[AaDd])\\\\{0,3}["'])([^"'\\s]{11,4095}[^"'\\s\\\\])`;export const ASSIGNMENT_UNQUOTED_SOURCE = (key: string) =>- `(${key})([A-Za-z0-9+/_=\\-!#$%*@^~.?<>]{11,4095}[A-Za-z0-9+/_=\\-#$%*@^~<>])`;+ `(${key})((?<=%3[AaDd])(?:[A-Za-z0-9+/_=\\-!#$*@^~.?<>]|%(?!26)){11,4095}(?:[A-Za-z0-9+/_=\\-#$*@^~<>]|%(?!26))` ++ `|(?<!%3[AaDd])[A-Za-z0-9+/_=\\-!#$%*@^~.?<>]{11,4095}[A-Za-z0-9+/_=\\-#$%*@^~<>])`;/** The legacy (pre-punctuation) value class, whole-value form. */const LEGACY_ASSIGNMENT_VALUE_RE = /^[A-Za-z0-9+/_=-]+$/;/** A dotted member path in code (`process.env.DB_PASSWORD_2`): every segment an identifier. */@@ -103,7 +114,7 @@ const DOTTED_IDENTIFIER_RE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;* with a letter is the accepted miss.*/export function assignmentValueIsSecretShaped(value: string): boolean {- if (/^[A-Za-z][A-Za-z0-9+.-]{0,31}:\/\//.test(value)) return false;+ if (/^[A-Za-z][A-Za-z0-9+.-]{0,31}(?::\/\/|%3A%2F%2F)/i.test(value)) return false;if (value.startsWith('./') || value.startsWith('~/') || value.startsWith('${') || value.startsWith('$(')) return false;if (value.startsWith('<REDACTED:') || DOTTED_IDENTIFIER_RE.test(value)) return false;return !(value.startsWith('/') && !LEGACY_ASSIGNMENT_VALUE_RE.test(value));diff --git a/src/core/source-delete.ts b/src/core/source-delete.tsindex eaee1e55cf..84ab0f9657 100644--- a/src/core/source-delete.ts+++ b/src/core/source-delete.ts@@ -74,16 +74,20 @@ export async function deleteSourceRow(* #9068: CTEs that remove what names a removed source's pages outside a foreign key, for source `$1`, each only* when `gate` holds: the source's retrieval_event_pages, retrieval_event_links, retrieval_feedback and* context_volunteer_events rows, and each eval candidate's captured slugs that no other source the candidate covers- * still has a page for (retrieval_weights and mention_gazetteer_entries cascade from sources). Every removal runs+ * still has a page for (retrieval_weights and mention_gazetteer_entries cascade from sources). #9146: also the+ * source's core_edit_notices and write_gate_holds with the holds' receipts (take_proposals, open_loops, page_aliases,+ * slug_aliases and slug_rename_history cascade from sources). Every removal runs* them in the statement that deletes the sources row (gated on that delete), so the source and those rows go* together, then again in a later statement: that statement reads past a feedback write or eval capture that held one* of the source's page rows while the delete waited for it (a later one finds no page).*/export function removedSourceScrubCtes(gate: string): string {- const deletes = ['retrieval_event_pages', 'retrieval_event_links', 'retrieval_feedback', 'context_volunteer_events']+ const deletes = ['retrieval_event_pages', 'retrieval_event_links', 'retrieval_feedback', 'context_volunteer_events', 'core_edit_notices'].map(table => `scrub_${table} AS (DELETE FROM ${table} WHERE source_id = $1 AND ${gate})`);+ const holds = [`scrub_write_gate_holds AS (DELETE FROM write_gate_holds WHERE source_id = $1 AND ${gate} RETURNING id::text AS id)`,+ `scrub_write_gate_receipts AS (DELETE FROM write_gate_receipts r USING scrub_write_gate_holds h WHERE r.target_table = 'write_gate_holds' AND r.target_id = h.id)`];const elsewhere = (slug: string) => `EXISTS (SELECT 1 FROM pages pg WHERE pg.slug = ${slug} AND pg.source_id = ANY(c.source_ids) AND pg.source_id <> $1)`;- return [...deletes, `scrub_eval_candidates AS (UPDATE eval_candidates c+ return [...deletes, ...holds, `scrub_eval_candidates AS (UPDATE eval_candidates cSET retrieved_slugs = ARRAY(SELECT u.s FROM unnest(c.retrieved_slugs) WITH ORDINALITY AS u(s, n) WHERE ${elsewhere('u.s')} ORDER BY u.n)WHERE $1 = ANY(c.source_ids) AND EXISTS (SELECT 1 FROM unnest(c.retrieved_slugs) AS r(s) WHERE NOT ${elsewhere('r.s')}) AND ${gate})`].join(',\n ');}diff --git a/src/core/transcripts/secret-audit.ts b/src/core/transcripts/secret-audit.tsindex 70378ce0bc..51e3563415 100644--- a/src/core/transcripts/secret-audit.ts+++ b/src/core/transcripts/secret-audit.ts@@ -17,7 +17,7 @@ import type { BrainEngine } from '../engine.ts';import { scanText } from '../secret-scan.ts';/** Bump when the transcript-lane detectors change, so doctor asks for a fresh audit. */-export const TRANSCRIPT_SECRET_AUDIT_VERSION = 4;+export const TRANSCRIPT_SECRET_AUDIT_VERSION = 5;export const TRANSCRIPT_SECRET_AUDIT_KEY = 'transcripts.secret_audit';const BATCH = 25;const LINES_PER_PAGE = 20;diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.tsindex 36809622ce..f30d93dc63 100644--- a/src/core/trust/backfill.ts+++ b/src/core/trust/backfill.ts@@ -14,6 +14,10 @@* - frontmatter transcript_import, provenance: auto-extracted, dream_generated,* extracted_by: extract_atoms-* (legacy atoms, #6533): agent_written (model-* or session-derived);+ * - on a claimed source, a Life Chronicle event (`captured_via`+ * life-chronicle:auto, #9284) is also capped at the tier of its depth page+ * (`event.depth`, same source): that page's stored tier and its own+ * frontmatter caps;* - facts.source lane tags (the facts backstop, conversation-facts and* extract_facts lanes) and takes.source take_proposals#: agent_written;* - post-v193 rows through write_request_id -> persistence_requests (CEO-17):@@ -47,7 +51,7 @@ import { markBeliefCommits } from '../belief/append.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';import { readManagedMode } from '../persistence/managed-mode.ts';import { edgeTrimSql } from '../edge-whitespace.ts';-import { EXTRACT_ATOMS_EXTRACTOR_PREFIX, frontmatterTrustCapsSql } from './channel.ts';+import { CHRONICLE_CAPTURED_VIA, EXTRACT_ATOMS_EXTRACTOR_PREFIX, frontmatterTrustCapsSql } from './channel.ts';import { claimedSourceSql, legacyRowSql, notConnectorSourceSql, readLegacyCeilings, type LegacyCeilings } from './claim-state.ts';import { TRUST_BACKFILL_COMPLETED_KEY, type TrustTable } from './schema.ts';import { TRUST_TIER_RANK, TRUST_TIERS, isTrustTier, trustRankSql, trustTierFromRankSql, type TrustTier } from './tier.ts';@@ -176,16 +180,31 @@ function classifier(cols: Columns, assumeClaimed: readonly string[] = [], ceilinreturn terms;};const least = (terms: string[]) => (terms.length ? `LEAST(${terms.join(', ')})` : 'NULL::int');+ /**+ * #9284: a legacy Life Chronicle event is model-extracted from its depth page (`event.depth`, a live page in the+ * same source), so it ranks no higher than that page: its stored tier (when classified) and its frontmatter caps.+ * A missing depth page adds no cap (the event's own agent_written cap still applies).+ */+ const chronicleDepthCap = (p: string) => {+ const d = 'chronicle_depth';+ const depthCaps = least(frontmatterTrustCapsSql(`${d}.frontmatter`));+ return `CASE WHEN ${p}.type = 'event' AND jsonb_typeof(${p}.frontmatter->'captured_via') = 'string'+ AND ${edgeTrimSql(`${p}.frontmatter->>'captured_via'`)} = '${CHRONICLE_CAPTURED_VIA}'+ AND jsonb_typeof(${p}.frontmatter->'event') = 'object' AND jsonb_typeof(${p}.frontmatter->'event'->'depth') = 'string'+ THEN (SELECT ${cols.has('pages', 'trust_tier') ? `CASE WHEN ${d}.trust_tier <> 'unknown' THEN LEAST(${trustRankSql(`${d}.trust_tier`)}, ${depthCaps}) ELSE ${depthCaps} END` : depthCaps}+ FROM pages ${d} WHERE ${d}.source_id = ${p}.source_id AND ${d}.slug = ${p}.frontmatter->'event'->>'depth'${cols.has('pages', 'deleted_at') ? ` AND ${d}.deleted_at IS NULL` : ''}+ LIMIT 1) END`;+ };/*** A page's rule: its signals, and on a claimed source operator_curated lowered by every frontmatter signal* an owner sync would apply (`frontmatterTrustCaps`), so a claim never lifts a captured, clipped, imported- * or marked page above what it says it is.+ * or marked page above what it says it is, nor a Life Chronicle event above its depth page.*/const pageRule = (p: string, s: string, r: string) => {const terms = pageTerms(p, s, r);const c = claimed(s);if (!c) return least(terms);- const caps = cols.has('pages', 'frontmatter') ? frontmatterTrustCapsSql(`${p}.frontmatter`) : [];+ const caps = cols.has('pages', 'frontmatter') ? [...frontmatterTrustCapsSql(`${p}.frontmatter`), chronicleDepthCap(p)] : [];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');@@ -379,6 +398,8 @@ export interface TrustRelowerReport {rows: number;/** Up to 20 affected pages, for the preview. */sample: Array<{ source_id: string; slug: string; from: TrustTier; to: TrustTier }>;+ /** Sources holding at least one of those rows. */+ sources: string[];}/**@@ -387,16 +408,23 @@ export interface TrustRelowerReport {* `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.+ * run is read-only and reports the same rows the apply lowers. #9284: named `sources` also cover a+ * non-connector source whose claim `sources set-trust` ended, classified as if still claimed, so the rows that+ * claim lifted can still be lowered; without `sources` only claimed sources are considered.*/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 (!cols.has('pages', 'trust_tier') || !cols.has('pages', 'write_origin') || !cols.has('sources', 'config')) return { mode, tables: [], rows: 0, sample: [], sources: [] };+ const targets = opts.sources+ ? await engine.executeRaw<{ id: string; claimed: boolean }>(`SELECT s.id, ${claimedSourceSql('s')} AS claimed FROM sources s+ WHERE s.id = ANY($1::text[]) AND ${notConnectorSourceSql('s')} ORDER BY s.id`, [[...opts.sources]])+ : await engine.executeRaw<{ id: string; claimed: boolean }>(`SELECT s.id, true AS claimed FROM sources s WHERE ${claimedSourceSql('s')} ORDER BY s.id`);+ const claimed = targets.map(r => r.id);+ const ended = targets.filter(r => !r.claimed).map(r => r.id);+ const { forTable } = classifier(cols, ended, await readLegacyCeilings(engine).catch(() => null), true);+ const report: TrustRelowerReport = { mode, tables: [], rows: 0, sample: [], sources: [] };+ const affected = new Set<string>();if (claimed.length === 0) return report;const managedBrain = opts.dryRun ? false : await readManagedMode(engine);const attribution = opts.dryRun ? null : await maintenanceAttribution(engine);@@ -416,6 +444,7 @@ export async function relowerClaimedRows(engine: BrainEngine, opts: { dryRun?: bfor (const row of rows) {const target = isTrustTier(row.to_tier) ? row.to_tier : 'unknown';to[target]++;+ affected.add(row.source_id);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 });}@@ -437,6 +466,7 @@ export async function relowerClaimedRows(engine: BrainEngine, opts: { dryRun?: blowered.push(...await engine.transaction(tx => managedBrain ? withCoordinatedWrite(tx, sources, () => apply(tx), attribution!) : apply(tx)));if (publications.length) await markBeliefCommits(engine, publications).catch(() => undefined);}+ report.sources = [...affected].sort();// W1 #6783 §12 (b): after every table is relowered (the dry run reports exactly these rows), what was derived from them follows.if (lowered.length) await engine.transaction(tx => managedBrain? withCoordinatedWrite(tx, claimed, () => propagateTierLowering(tx, lowered), attribution!) : propagateTierLowering(tx, lowered));diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.tsindex 3024da1418..cc4dc9749b 100644--- a/src/core/trust/channel.ts+++ b/src/core/trust/channel.ts@@ -43,10 +43,12 @@ export const AGENT_WRITE_OPERATIONS: readonly string[] = [*/const OWNER_SOURCE_KINDS = ['canonical_reconcile', 'managed_file_import', 'managed_file_repair', 'managed_grandfather', 'managed_quarantine_clear'];+/** The `captured_via` stamp of a Life Chronicle event page (chronicle/publish.ts): model-extracted from its depth page. */+export const CHRONICLE_CAPTURED_VIA = 'life-chronicle:auto';/** Page frontmatter `source_kind` / `ingested_via` / `captured_via` values written by an ingestion capture (external). */export const EXTERNAL_CAPTURE_KINDS: readonly string[] = ['webhook', 'file-watcher', 'inbox-folder', 'cron-scheduler', 'ingest_capture'];-/** ...and by an agent through a gbrain verb (agent_written). */-const AGENT_CAPTURE_KINDS = ['put_page', 'capture-cli', 'capture-mcp', 'capture'];+/** ...and by an agent through a gbrain verb, or by the Life Chronicle extractor (agent_written). */+const AGENT_CAPTURE_KINDS = ['put_page', 'capture-cli', 'capture-mcp', 'capture', CHRONICLE_CAPTURED_VIA];/*** Harnesses whose `transcript_import` pages are the user's own sessions with* their agent (or their own chat exports): relayed user turns count asdiff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex 06b4eb1eaf..c470baf530 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -336,9 +336,10 @@ export function resolveClientRowSurface(/*** Dual-plane resolution for `mcp.default_surface_dcr` — the surface applied* to clients whose row surface is NULL (oauth_clients carries no DCR-origin- * marker, so the default applies to ALL null-surface clients; operators+ * marker, so the default applies to ALL null-surface OAuth clients; operators* pre-seed important clients with `gbrain auth rescope-client <id> --surface- * full`). DB plane wins, file plane falls back, absent/unparseable on both =+ * full`). Legacy bearer tokens have no client row and keep the server ceiling+ * (#9266). DB plane wins, file plane falls back, absent/unparseable on both =* null (caller falls back to the server ceiling — pre-WP4 behavior). A* failed DB read falls to the file plane; surface resolution must never take* a request down.diff --git a/test/drift-report-derivation-9208.test.ts b/test/drift-report-derivation-9208.test.tsnew file mode 100644index 0000000000..8b094d1e33--- /dev/null+++ b/test/drift-report-derivation-9208.test.ts@@ -0,0 +1,78 @@+/**+ * #9208: the drift phase's report (reports/drift-<date>) is derived from the+ * pages whose takes were judged; the judge's evidence is those same pages'+ * timeline entries. The report must carry that derivation (channel+ * derive:drift, the least trusted judged page, capped at agent_written) on+ * both publish paths, as the dream summary does, instead of landing with+ * trust_tier 'unknown' and no write_origin.+ *+ * PGLite ($0): an unmanaged brain (publishSinglePage) and a managed brain+ * (publishMaintenancePage). Synthetic content only.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { runPhaseDrift } from '../src/core/cycle/drift.ts';+import { _resetBudgetMeterWarningsForTest } from '../src/core/cycle/budget-meter.ts';+import { withWriteTrust } from '../src/core/persistence/context.ts';+import type { TrustTier } from '../src/core/trust/tier.ts';+import { managedBrain } from './helpers/managed-brain.ts';++const CYCLE_DATE = '2031-04-14';+const REPORT = `reports/drift-${CYCLE_DATE}`;+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++async function seed(engine: BrainEngine, tier: TrustTier) {+ await engine.transaction(tx => withWriteTrust(tx, { tier, origin: { channel: 'sync' } }, async () => {+ const page = await tx.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'A person at Acme.', timeline: '', frontmatter: {} });+ await tx.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Acme will ship the widget this year', kind: 'take', holder: 'world', weight: 0.6 }]);+ await tx.addTimelineEntriesBatch([{ slug: 'people/alice-example', date: '2031-04-10', source: 'meeting', summary: 'Widget launch slipped' }]);+ }));+ await engine.setConfig('dream.drift.enabled', 'true');+ await engine.setConfig('dream.drift.budget', '1.0');+ await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');+}++async function drift(engine: BrainEngine) {+ _resetBudgetMeterWarningsForTest();+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-9208-'));+ dirs.push(dir);+ const result = await runPhaseDrift(engine, {+ dryRun: false, forceEnabled: true, cycleDate: CYCLE_DATE, auditPath: join(dir, 'drift-audit.jsonl'),+ judge: async () => ({ drifted: true, confidence: 0.9, reasoning: 'Evidence moved.' }),+ });+ expect(result.status).toBe('complete');+ const [row] = await engine.executeRaw<{ trust_tier: string | null; write_origin: { channel?: string } | string | null }>(+ 'SELECT trust_tier, write_origin FROM pages WHERE slug = $1', [REPORT]);+ expect(row).toBeDefined();+ const origin = typeof row!.write_origin === 'string' ? JSON.parse(row!.write_origin) : row!.write_origin;+ return { tier: row!.trust_tier, channel: origin?.channel ?? null };+}++const CASES: Array<[TrustTier, TrustTier]> = [['operator_curated', 'agent_written'], ['external_untrusted', 'external_untrusted']];++describe('#9208 drift report carries a derive:drift derivation', () => {+ for (const [input, expected] of CASES) {+ test(`unmanaged (publishSinglePage): ${input} judged page -> ${expected}`, async () => {+ const engine = new PGLiteEngine();+ await engine.connect({});+ try {+ await engine.initSchema();+ await seed(engine, input);+ expect(await drift(engine)).toEqual({ tier: expected, channel: 'derive:drift' });+ } finally {+ await engine.disconnect();+ }+ }, 120_000);++ test(`managed (publishMaintenancePage): ${input} judged page -> ${expected}`, async () => {+ await managedBrain(async ({ engine }) => {+ expect(await drift(engine)).toEqual({ tier: expected, channel: 'derive:drift' });+ }, { setup: ({ engine }) => seed(engine, input) });+ }, 180_000);+ }+});diff --git a/test/e2e/mcp-legacy-token-dcr-surface-9266.test.ts b/test/e2e/mcp-legacy-token-dcr-surface-9266.test.tsnew file mode 100644index 0000000000..b15a55faa5--- /dev/null+++ b/test/e2e/mcp-legacy-token-dcr-surface-9266.test.ts@@ -0,0 +1,126 @@+/**+ * #9266: `mcp.default_surface_dcr` is the default for OAuth clients whose+ * oauth_clients row carries no surface. A legacy bearer token has no such row+ * (and no way to pre-seed one), so it keeps the server ceiling and stays+ * bounded by its own scope, source and operation grants.+ *+ * Real `gbrain serve --http` processes against a hermetic PGLite brain:+ * - legacy token (read+write, operations whoami+add_link) under the starter+ * default: add_link is listed and callable, put_page stays refused;+ * - an OAuth client with no surface row still resolves to starter;+ * - GBRAIN_MCP_FORCE_SURFACE=starter still clamps the legacy token.+ *+ * Run: bash scripts/run-e2e.sh test/e2e/mcp-legacy-token-dcr-surface-9266.test.ts+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { keylessBrainEnv } from '../helpers/provider-env.ts';+import { startServeHttp, type ServeHttp } from '../helpers/serve-http.ts';+import { mintClientCredentialsToken } from '../../src/core/remote-mcp-probe.ts';++const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');++describe('#9266 mcp.default_surface_dcr applies to OAuth clients only (PGLite + real serve --http)', () => {+ let home: string;+ let env: Record<string, string>;+ let legacyToken = '';+ let clientId = '';+ let clientSecret = '';++ const gbrain = (args: string[], input?: string) =>+ execFileSync(process.execPath, ['--no-env-file', CLI, ...args], { cwd: process.cwd(), env, encoding: 'utf8', input });++ async function withServer<T>(extraEnv: Record<string, string>, fn: (server: ServeHttp) => Promise<T>): Promise<T> {+ const server = await startServeHttp({ cwd: process.cwd(), env: { ...env, ...extraEnv } });+ try { return await fn(server); } finally { await server.stop(); }+ }++ async function withClient<T>(server: ServeHttp, bearer: string, fn: (client: Client) => Promise<T>): Promise<T> {+ const transport = new StreamableHTTPClientTransport(new URL(`${server.base}/mcp`), {+ requestInit: { headers: { Authorization: `Bearer ${bearer}` } },+ });+ const client = new Client({ name: 'gbrain-9266-e2e', version: '1' }, { capabilities: {} });+ await client.connect(transport);+ try { return await fn(client); } finally { try { await client.close(); } catch { /* best-effort */ } }+ }++ const toolNames = async (client: Client) => (await client.listTools()).tools.map(t => t.name);++ async function callText(client: Client, name: string, args: Record<string, unknown>): Promise<{ isError: boolean; text: string }> {+ try {+ const res = await client.callTool({ name, arguments: args }) as { isError?: boolean; content?: Array<{ text?: string }> };+ return { isError: res.isError === true, text: (res.content ?? []).map(c => c.text ?? '').join('\n') };+ } catch (e) {+ return { isError: true, text: e instanceof Error ? e.message : String(e) };+ }+ }++ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-9266-'));+ env = keylessBrainEnv(process.env, home, { DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_MCP_FORCE_SURFACE: undefined });+ gbrain(['init', '--pglite', '--no-embedding', '--non-interactive']);+ gbrain(['put', 'people/alice-example', '--content-origin', 'user_said'], '---\ntitle: Alice Example\ntype: person\n---\nAlice works at Acme.\n');+ gbrain(['put', 'companies/acme-example', '--content-origin', 'user_said'], '---\ntitle: Acme Example\ntype: company\n---\nAcme makes widgets.\n');++ const created = gbrain(['auth', 'create', 'legacy-a', '--scopes', 'read,write']);+ legacyToken = (created.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];+ if (!legacyToken) throw new Error(`auth create did not yield a token:\n${created}`);+ gbrain(['auth', 'rescope', '--token', 'legacy-a', '--operations', 'whoami,add_link', '--sources', 'default']);++ const reg = gbrain(['auth', 'register-client', 'oauth-a', '--grant-types', 'client_credentials', '--scopes', 'read write',+ '--token-endpoint-auth-method', 'client_secret_post']);+ clientId = (reg.match(/Client ID:\s+(\S+)/) ?? ['', ''])[1];+ clientSecret = (reg.match(/Client Secret:\s+(\S+)/) ?? ['', ''])[1];+ if (!clientId || !clientSecret) throw new Error(`register-client did not yield credentials:\n${reg}`);++ gbrain(['config', 'set', 'mcp.default_surface_dcr', 'starter']);+ }, 120_000);++ afterAll(() => {+ if (home) rmSync(home, { recursive: true, force: true });+ });++ test('legacy token keeps the server ceiling: add_link listed and callable, put_page still refused', async () => {+ await withServer({}, server => withClient(server, legacyToken, async client => {+ const names = await toolNames(client);+ expect(names).toContain('add_link');+ expect(names).toContain('whoami');+ expect(names).not.toContain('put_page');++ const linked = await callText(client, 'add_link', { from: 'people/alice-example', to: 'companies/acme-example' });+ expect(linked).toMatchObject({ isError: false });++ const put = await callText(client, 'put_page', { slug: 'notes/denied-example', content: 'x' });+ expect(put.isError).toBe(true);+ }));+ }, 120_000);++ test('an OAuth client with no surface row still resolves to the starter default', async () => {+ await withServer({}, async server => {+ const minted = await mintClientCredentialsToken(`${server.base}/token`, clientId, clientSecret, { scope: 'read write' });+ if (!minted.ok) throw new Error(`client_credentials mint failed: ${JSON.stringify(minted)}`);+ await withClient(server, minted.token.access_token, async client => {+ const names = await toolNames(client);+ expect(names).toContain('whoami');+ expect(names).not.toContain('add_link');+ const linked = await callText(client, 'add_link', { from: 'people/alice-example', to: 'companies/acme-example' });+ expect(linked.isError).toBe(true);+ });+ });+ }, 120_000);++ test('GBRAIN_MCP_FORCE_SURFACE=starter still clamps the legacy token', async () => {+ await withServer({ GBRAIN_MCP_FORCE_SURFACE: 'starter' }, server => withClient(server, legacyToken, async client => {+ const names = await toolNames(client);+ expect(names).toContain('whoami');+ expect(names).not.toContain('add_link');+ const linked = await callText(client, 'add_link', { from: 'people/alice-example', to: 'companies/acme-example' });+ expect(linked.isError).toBe(true);+ }));+ }, 120_000);+});diff --git a/test/mcp-legacy-token-surface-agreement-9266.test.ts b/test/mcp-legacy-token-surface-agreement-9266.test.tsnew file mode 100644index 0000000000..d04e539dfc--- /dev/null+++ b/test/mcp-legacy-token-surface-agreement-9266.test.ts@@ -0,0 +1,76 @@+/**+ * #9266: under `mcp.default_surface_dcr = starter`, the server gives a legacy+ * bearer token the server ceiling (it has no oauth_clients row to pre-seed)+ * and gives a NULL-surface OAuth client the starter default. The doctor+ * `grant_new_ops_available` check and the advisor `mcp-client-fit` collector+ * must give the same answer. The server side is pinned over real HTTP by+ * test/e2e/mcp-legacy-token-dcr-surface-9266.test.ts.+ *+ * PGLite in-memory ($0).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { mintLegacyToken } from '../src/core/token-mint.ts';+import { checkGrantNewOps } from '../src/commands/doctor/checks/grant-new-ops.ts';+import { collectMcpClientFit, __setUsageNagStatePathForTests, MIN_CALLS_FOR_FIT } from '../src/core/advisor/collect-mcp-client-fit.ts';+import type { AdvisorContext } from '../src/core/advisor/types.ts';++let engine: PGLiteEngine;+let nagDir: string;+const cfg = { engine: 'pglite' } as any;+const OPS = ['whoami', 'add_link'];++type Finding = { kind: string; id: string; name: string; blockers: Array<Record<string, unknown>>; excluded_operations: { server_ceiling: string[] } };++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ nagDir = mkdtempSync(join(tmpdir(), 'gbrain-9266-nag-'));+ __setUsageNagStatePathForTests(join(nagDir, 'nag.json'));+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ await engine.setConfig('mcp.default_surface_dcr', 'starter');+ await mintLegacyToken(engine, { name: 'legacy-a', scopes: ['read', 'write'], takesHolders: ['world'], allowedOperations: OPS });+ await provider.registerClientManual('oauth-a', ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,+ { allowedOperations: OPS });+ for (let i = 0; i < MIN_CALLS_FOR_FIT + 5; i++) {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status) VALUES ('legacy-a', 'legacy-a', 'whoami', 5, 'success')`);+ }+}, 60_000);++afterAll(async () => {+ __setUsageNagStatePathForTests(null);+ await engine?.disconnect();+ rmSync(nagDir, { recursive: true, force: true });+}, 15_000);++describe('#9266 doctor and advisor agree with the server for a legacy token under the starter default', () => {+ test('doctor grant_new_ops: the token keeps the server ceiling, the NULL-surface client gets the starter default', async () => {+ const check = await checkGrantNewOps(engine, { cfg });+ const found = (check.details?.grants ?? []) as Finding[];+ const token = found.find(f => f.kind === 'legacy_token' && f.name === 'legacy-a')!;+ const client = found.find(f => f.kind === 'oauth_client' && f.name === 'oauth-a')!;+ expect(check.details?.server_surface).toBe('full');++ expect(token).toBeDefined();+ expect(token.excluded_operations.server_ceiling).toEqual([]);+ expect(token.blockers.map(b => b.blocker)).not.toContain('server_ceiling');++ expect(client).toBeDefined();+ expect(client.excluded_operations.server_ceiling).toContain('add_link');+ expect(client.blockers).toContainEqual(expect.objectContaining({ blocker: 'server_ceiling', surface: 'starter' }));+ });++ test('advisor mcp-client-fit proposes no client rescope for the legacy token', async () => {+ const ctx: AdvisorContext = { engine, config: {} as AdvisorContext['config'], version: '0.0.0.0', workspace: null, skillsDir: null, now: new Date(), remote: false };+ const findings = await collectMcpClientFit.collect(ctx);+ expect(findings.map(f => f.id)).not.toContain('mcp_starter_fit:legacy-a');+ expect(JSON.stringify(findings)).not.toContain('rescope-client legacy-a');+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 874f285734..118d6e884a 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -527,6 +527,7 @@ test/purge-name-stores-9068.test.tstest/purge-read-surfaces.test.tstest/purge-root-metafile-7613.test.tstest/purge-scrub-followups-9068.test.ts+test/purge-slug-stores-9146.test.tstest/purge-sync-tombstone-hold-7130.test.tstest/qm-attest-write-boundary.test.tstest/qm-memory-propose.test.ts@@ -704,6 +705,7 @@ test/think-remote-model.test.tstest/timeline-chunk-reuse.test.tstest/transcript-redaction-key-names.test.tstest/trust-channel-writes.test.ts+test/trust-claim-chronicle-9284.test.tstest/trust-guarded-supersession.test.tstest/trust-held-removals.test.tstest/trust-keep-maintenance-reimport-8352.test.tsdiff --git a/test/purge-slug-stores-9146.test.ts b/test/purge-slug-stores-9146.test.tsnew file mode 100644index 0000000000..a9f6bc4026--- /dev/null+++ b/test/purge-slug-stores-9146.test.ts@@ -0,0 +1,244 @@+/**+ * #9146: every hard delete of a page removes the six stores keyed to it by source and slug.+ *+ * 1. Protects: delete_page purge:true, the expired-tombstone purge, the belief ledger's per-tombstone expiry, the batch+ * deletePages, a restore that replays a page purge and a managed connector delete that expires delete the source's+ * take_proposals, open_loops (page_slug), core_edit_notices, page_aliases (slug), slug_aliases (canonical_slug) and+ * slug_rename_history (new_slug) rows for the slug, in the delete's transaction. An immediate hard delete also drops+ * the slug's write_gate_holds and their receipts; a tombstone expiry drops only holds created up to the soft+ * delete, so a write held after it stays for review. Removing a source drops its core_edit_notices and+ * write_gate_holds (the other stores cascade from sources).+ * 2. Fails when: any of those stores keeps the purged page's rows, a tombstone expiry drops a hold that arrived after+ * the soft delete, a source removal leaves its notices or holds, or a scrub reaches another source's or another+ * page's rows.+ * 3. Existing coverage: purge-name-stores-9068 and purge-scrub-followups-9068 pin the name and retrieval stores on the+ * same paths; only the direct purge removed these six.+ * 4. Real seams: PGLite, and Postgres when DATABASE_URL is set (test/postgres-unit-arms.txt); the belief-ledger,+ * restore and managed connector cases are PGLite only; the delete_page op, purgeDeletedPagesCoordinated,+ * deletePages, a PGLite backup and restore, the managed connector session, removeSource; repo-less brain, no+ * provider calls.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations } from '../src/core/operations.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { purgeDeletedPagesCoordinated } from '../src/core/persistence/purge-deleted.ts';+import { withConnectorSync } from '../src/core/persistence/connector-sync.ts';+import { parseGoogleSourceConfig } from '../src/core/google/google-source.ts';+import { removeSource } from '../src/core/sources-ops.ts';+import { createPgliteBackup, restorePgliteBackup } from '../src/core/backup/snapshot.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { beliefBrain, beliefPage, openFileBeliefBrain, withFileBeliefBrain } from './helpers/belief-ledger.ts';+import { createConnectorFixture, googleConfig, options, settleConnectorWrites } from './helpers/connector-fixture.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-slug-stores-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const OTHER = 'companies/acme-example';+const STORES = ['take_proposals', 'open_loops', 'core_edit_notices', 'page_aliases', 'slug_aliases', 'slug_rename_history'] as const;+const KEY: Record<string, string> = { take_proposals: 'page_slug', open_loops: 'page_slug', core_edit_notices: 'slug', page_aliases: 'slug', slug_aliases: 'canonical_slug', slug_rename_history: 'new_slug' };++const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,+ config: { engine: engine.kind, embedding_disabled: true, storage: { backend: 'local', bucket: 'b', localPath: join(home, 'storage') } },+ logger: { info() {}, warn() {}, error() {} } } as OperationContext);+const op = (name: string) => operations.find(o => o.name === name)!;++/** A write-gate hold for the slug created `ago` before now, labelled `when`, with its receipt. */+async function hold(engine: BrainEngine, sourceId: string, slug: string, when: string, ago = '0 seconds') {+ const [row] = await engine.executeRaw<{ id: string }>(`INSERT INTO write_gate_holds (kind, source_id, slug, fingerprint, detector_version, tier, payload, created_at)+ VALUES ('fact', $1, $2, $3, 1, 'quarantine', $4::text::jsonb, now() - $5::interval) RETURNING id::text AS id`,+ [sourceId, slug, randomUUID(), JSON.stringify({ when }), ago]);+ await engine.executeRaw(`INSERT INTO write_gate_receipts (target_table, target_id, source_id, content_hash, tier, detector_version, verdict, request_id)+ VALUES ('write_gate_holds', $1, $2, $3, 'quarantine', 1, 'quarantine', $4)`, [row.id, sourceId, randomUUID(), `${slug}|${when}`]);+}++/** One row per slug-keyed store for the page in `sourceId`, and a hold created `holdAgo` before now. */+async function slugRows(engine: BrainEngine, sourceId: string, slug: string, holdAgo = '0 seconds') {+ const marker = randomUUID();+ await engine.executeRaw(`INSERT INTO take_proposals (source_id, page_slug, content_hash, prompt_version, proposal_run_id, claim_text, kind, holder, weight, model_id)+ VALUES ($1, $2, $3, 'v1', 'run-1', 'Proposed claim about the page', 'take', 'self', 0.5, 'model-a')`, [sourceId, slug, marker]);+ await engine.executeRaw(`INSERT INTO open_loops (source_id, dedup_key, loop_type, summary, page_slug, detector)+ VALUES ($1, $2, 'commitment_owed_by_me', 'Loop found on the page', $3, 'manual')`, [sourceId, marker, slug]);+ await engine.executeRaw(`INSERT INTO core_edit_notices (source_id, slug, base_text, actor) VALUES ($1, $2, 'Copy of the page text', 'agent')`, [sourceId, slug]);+ await engine.executeRaw(`INSERT INTO page_aliases (source_id, alias_norm, slug, origin, alias_text) VALUES ($1, $2, $3, 'declared', 'Alias text')`, [sourceId, `alias ${marker}`, slug]);+ await engine.executeRaw('INSERT INTO slug_aliases (source_id, alias_slug, canonical_slug) VALUES ($1, $2, $3)', [sourceId, `old/${marker}`, slug]);+ await engine.executeRaw('INSERT INTO slug_rename_history (source_id, old_slug, new_slug) VALUES ($1, $2, $3)', [sourceId, `renamed/${marker}`, slug]);+ await hold(engine, sourceId, slug, 'before', holdAgo);+}++/** The page in default and source-b and OTHER in default, each with one row per store and a hold from an hour ago. */+async function seed(engine: BrainEngine, slug: string) {+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('source-b', 'source-b') ON CONFLICT DO NOTHING`);+ for (const sourceId of ['default', 'source-b']) {+ await importFromContent(engine, slug, `---\ntitle: ${slug}\ntype: person\n---\n# ${slug}\n\nBody text.\n`, { noEmbed: true, sourceId });+ await slugRows(engine, sourceId, slug, '1 hour');+ }+ if (!(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2', ['default', OTHER])).length) {+ await importFromContent(engine, OTHER, `---\ntitle: Acme Example\ntype: company\n---\n# Acme Example\n\nBody text.\n`, { noEmbed: true, sourceId: 'default' });+ await slugRows(engine, 'default', OTHER, '1 hour');+ }+}++/** Per store, the sources that still hold a row for the slug; holds and their receipts as `source:when`. */+async function residue(engine: BrainEngine, slug: string) {+ const out: Record<string, string[]> = {};+ for (const table of STORES) out[table] = (await engine.executeRaw<{ s: string }>(`SELECT DISTINCT source_id AS s FROM ${table} WHERE ${KEY[table]} = $1 ORDER BY 1`, [slug])).map(r => r.s);+ out.write_gate_holds = (await engine.executeRaw<{ s: string }>(`SELECT source_id || ':' || (payload->>'when') AS s FROM write_gate_holds WHERE slug = $1 ORDER BY 1`, [slug])).map(r => r.s);+ out.write_gate_receipts = (await engine.executeRaw<{ s: string }>(`SELECT source_id || ':' || split_part(request_id, '|', 2) AS s FROM write_gate_receipts+ WHERE target_table = 'write_gate_holds' AND split_part(request_id, '|', 1) = $1 ORDER BY 1`, [slug])).map(r => r.s);+ return out;+}+const only = (sources: string[], holds: string[]) => ({ ...Object.fromEntries(STORES.map(t => [t, sources])), write_gate_holds: holds, write_gate_receipts: holds });+const SEEDED = only(['default', 'source-b'], ['default:before', 'source-b:before']);+const ONLY_SOURCE_B = only(['source-b'], ['source-b:before']);+const stores = (r: Record<string, string[]>) => Object.fromEntries(STORES.map(t => [t, r[t]]));++async function otherUntouched(engine: BrainEngine) {+ expect(await residue(engine, OTHER)).toEqual(only(['default'], ['default:before']));+}++beforeAll(async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const backends = testBackends();+ if (backends.includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine); closePostgres = pg.close;+ }+ for (const engine of engines) await registerLocalWriter(engine, 'cli');+}), 120_000);+afterAll(async () => {+ for (const engine of engines) await disposePersistenceConsumer(engine);+ await engines.find(e => e.kind === 'pglite')?.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true });+}, 60_000);++describe('#9146 every hard delete removes the page\'s slug-keyed stores', () => {+ test('(A) delete_page purge:true scrubs the source\'s rows and its holds', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/alice-example';+ await seed(engine, slug);+ expect(await residue(engine, slug)).toEqual(SEEDED);+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ const result = await op('delete_page').handler(ctx(engine), { slug, purge: true, request_id: randomUUID(), expected_revision: snapshot!.revision }) as Record<string, any>;+ expect(result.status).toBe('purged');+ expect({ engine: engine.kind, residue: await residue(engine, slug) }).toEqual({ engine: engine.kind, residue: ONLY_SOURCE_B });+ await otherUntouched(engine);+ }+ }), 120_000);++ test('(B) the expired-tombstone purge scrubs the rows and keeps a hold that arrived after the soft delete', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/bob-example';+ await seed(engine, slug);+ await engine.softDeletePage(slug, { sourceId: 'default' });+ expect(await residue(engine, slug)).toEqual(SEEDED);+ await hold(engine, 'default', slug, 'after');+ const purged = await purgeDeletedPagesCoordinated(engine, 0);+ expect(purged.slugs).toContain(slug);+ expect({ engine: engine.kind, residue: await residue(engine, slug) })+ .toEqual({ engine: engine.kind, residue: only(['source-b'], ['default:after', 'source-b:before']) });+ await otherUntouched(engine);+ }+ }), 120_000);++ test('(D) the batch deletePages scrubs the rows and the slug\'s holds', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/carol-example';+ await seed(engine, slug);+ expect(await engine.deletePages([slug], { sourceId: 'default' })).toEqual([slug]);+ expect({ engine: engine.kind, residue: await residue(engine, slug) }).toEqual({ engine: engine.kind, residue: ONLY_SOURCE_B });+ await otherUntouched(engine);+ }+ }), 120_000);++ test('removing a source drops its notices and holds along with the stores that cascade', () => withEnv({ GBRAIN_HOME: home }, async () => {+ for (const engine of engines) {+ const slug = 'people/dave-example';+ await seed(engine, slug);+ await removeSource(engine, { id: 'source-b', yes: true });+ expect({ engine: engine.kind, residue: await residue(engine, slug) }).toEqual({ engine: engine.kind, residue: only(['default'], ['default:before']) });+ await otherUntouched(engine);+ }+ }), 120_000);+});++const pgliteTest = testBackends().includes('pglite') ? test : test.skip;++pgliteTest('#9146 (C) a recorded tombstone the belief ledger expires scrubs the rows and keeps a later hold', () => beliefBrain(async b => {+ const slug = 'people/alice-example', src = b.sourceId;+ await b.put(slug, beliefPage({ title: 'Alice Example', prose: 'Body of the page.' }));+ await b.put(OTHER, beliefPage({ title: 'Acme Example', prose: 'Body of the other page.' }));+ await slugRows(b.engine, src, slug, '200 hours');+ await slugRows(b.engine, src, OTHER, '200 hours');+ await b.engine.executeRaw(`UPDATE pages SET deleted_at = now() - interval '100 hours' WHERE source_id = $1 AND slug = $2`, [src, slug]);+ await hold(b.engine, src, slug, 'after', '50 hours');+ const purged = await purgeDeletedPagesCoordinated(b.engine, 72);+ expect(purged.slugs).toContain(slug);+ expect(await residue(b.engine, slug)).toEqual(only([], [`${src}:after`]));+ expect(await residue(b.engine, OTHER)).toEqual(only([src], [`${src}:before`]));+}), 120_000);++pgliteTest('#9146 (E) a restore that replays a page purge scrubs the rows and holds from the restored brain', () => withFileBeliefBrain('restore-9146', async fb => {+ const src = 'restore-9146', slug = 'people/alice-example';+ await fb.open(async b => {+ await b.put(slug, beliefPage({ title: 'Alice Example', prose: 'Body of the page.' }));+ await b.put(OTHER, beliefPage({ title: 'Acme Example', prose: 'Body of the other page.' }));+ await slugRows(b.engine, src, slug);+ await slugRows(b.engine, src, OTHER);+ });+ const archive = join(fb.home, 'archive.gbrain-backup');+ await createPgliteBackup({ root: fb.home, output: archive });+ await fb.open(async b => {+ const snapshot = await b.engine.readPageSnapshot(slug, { sourceId: src });+ await op('delete_page').handler(b.ctx, { slug, purge: true, expected_revision: snapshot!.revision, request_id: randomUUID() });+ });+ const into = join(fb.home, 'restored');+ const result = await restorePgliteBackup({ archive, into });+ expect(result.purge_replay.replays.map(x => x.scope)).toEqual(['page']);+ const { brain, close } = await openFileBeliefBrain(join(into, '.gbrain', 'brain.pglite'), src, join(into, 'content'));+ try {+ expect(await residue(brain.engine, slug)).toEqual(only([], []));+ expect(await residue(brain.engine, OTHER)).toEqual(only([src], [`${src}:before`]));+ } finally { await close(); }+}), 300_000);++describe('#9146 a managed connector delete that expires scrubs the same rows', () => {+ const fixture = createConnectorFixture();+ beforeAll(fixture.setup, 120_000);+ afterAll(fixture.teardown);++ pgliteTest('connector_v2_delete, then the tombstone purge', () => withEnv(fixture.env, async () => {+ for (const engine of fixture.engines.filter(e => e.kind === 'pglite')) {+ const f = await fixture.source(engine, googleConfig);+ const cfg = parseGoogleSourceConfig(googleConfig, f.dir);+ const slug = 'people/alice-example', path = `${slug}.md`;+ await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => {+ await managed!.importMarkdown(path, `---\ntype: person\ntitle: Alice Example\n---\n# Alice Example\n\nBody.\n`);+ await managed!.importMarkdown(`${OTHER}.md`, `---\ntype: company\ntitle: Acme Example\n---\n# Acme Example\n\nBody.\n`);+ });+ await settleConnectorWrites(engine, f.id);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await slugRows(engine, f.id, slug, '1 hour');+ await slugRows(engine, f.id, OTHER);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => { expect(await managed!.delete(slug, path)).toBe(true); });+ await settleConnectorWrites(engine, f.id);+ expect(await engine.executeRaw('SELECT 1 FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NOT NULL', [f.id, slug])).toHaveLength(1);+ const purged = await purgeDeletedPagesCoordinated(engine, 0);+ expect(purged.slugs).toContain(slug);+ expect(stores(await residue(engine, slug))).toEqual(stores(only([], [])));+ expect(stores(await residue(engine, OTHER))).toEqual(stores(only([f.id], [])));+ await disposePersistenceConsumer(engine);+ }+ }), 240_000);+});diff --git a/test/secret-scan-encoded-assignment-8265.test.ts b/test/secret-scan-encoded-assignment-8265.test.tsnew file mode 100644index 0000000000..2f0d10988b--- /dev/null+++ b/test/secret-scan-encoded-assignment-8265.test.ts@@ -0,0 +1,94 @@+/**+ * #8265: `high_entropy_assignment` missed a key whose closing quote is escaped (`{\"password\":\"<v>\"}`, JSON inside a+ * JSON string, the usual shape of tool output) and a URL-encoded separator (`password%3D<v>`, `token%3A<v>`). The+ * value is still bounded: it never takes the backslash of an escaped closing quote, and after an encoded separator it+ * never takes the next parameter (`&`, `%26`). Offsets and fingerprints stay on the stored bytes.+ *+ * Every value is assembled at runtime from random parts (gitleaks, CEO-10).+ */+import { createHash } from 'node:crypto';+import { describe, expect, test } from 'bun:test';+import { redactFindings, scanText } from '../src/core/secret-scan.ts';+import { alnum } from './helpers/provider-keys.ts';++const OPTS = { highEntropy: true } as const;+const MARK = '<REDACTED:high_entropy_assignment>';+const secret = () => `Q7x${alnum(21)}9`;+const fingerprint = (v: string) => `sha256:${createHash('sha256').update(v).digest('hex').slice(0, 16)}`;+const found = (line: string) => scanText(line, OPTS).map((f) => f.pattern);++describe('#8265 escaped-quote JSON keys', () => {+ for (const depth of [1, 2, 3]) {+ const q = `${'\\'.repeat(depth)}"`;+ test(`${depth} backslash(es) before each quote: claimed, value only`, () => {+ const v = secret();+ const line = `{${q}password${q}:${q}${v}${q},${q}n${q}:1}`;+ const [hit] = scanText(line, OPTS);+ expect(hit?.pattern).toBe('high_entropy_assignment');+ expect(hit?.fingerprint).toBe(fingerprint(v));+ expect(redactFindings(line, OPTS).text).toBe(`{${q}password${q}:${q}${MARK}${q},${q}n${q}:1}`);+ });+ }++ test('single-quoted, escaped, with spaces around the colon', () => {+ const v = secret();+ const line = `{\\'api_key\\' : \\'${v}\\'}`;+ expect(redactFindings(line, OPTS).text).toBe(`{\\'api_key\\' : \\'${MARK}\\'}`);+ });++ test('an escaped key with an unquoted value', () => {+ const v = secret();+ const line = `x \\"SMTP_PASSWORD\\"=${v} done`;+ expect(redactFindings(line, OPTS).text).toBe(`x \\"SMTP_PASSWORD\\"=${MARK} done`);+ });+});++describe('#8265 URL-encoded separators', () => {+ for (const sep of ['%3D', '%3d', '%3A', '%3a']) {+ test(`password${sep}<value>: claimed, value only`, () => {+ const v = secret();+ const line = `body=user%3Dalice-example%26password${sep}${v}`;+ const [hit] = scanText(line, OPTS);+ expect(hit?.pattern).toBe('high_entropy_assignment');+ expect(hit?.fingerprint).toBe(fingerprint(v));+ expect(redactFindings(line, OPTS).text).toBe(`body=user%3Dalice-example%26password${sep}${MARK}`);+ });+ }++ test('the value stops at the next encoded or literal parameter', () => {+ const v = secret();+ expect(redactFindings(`a=b%26token%3D${v}%26page%3D2`, OPTS).text).toBe(`a=b%26token%3D${MARK}%26page%3D2`);+ expect(redactFindings(`a=b%26token%3D${v}&page=2`, OPTS).text).toBe(`a=b%26token%3D${MARK}&page=2`);+ });++ test('a value that itself carries percent-escapes keeps them', () => {+ const v = `${alnum(10)}%21${alnum(10)}4`;+ expect(redactFindings(`client_secret%3D${v}%26x%3D1`, OPTS).text).toBe(`client_secret%3D${MARK}%26x%3D1`);+ });++ test('a plain separator still keeps a %26 that sits inside the value', () => {+ const v = `${alnum(10)}%26${alnum(10)}4`;+ expect(redactFindings(`password=${v} next`, OPTS).text).toBe(`password=${MARK} next`);+ });+});++describe('#8265 no new findings on ordinary text', () => {+ const LINES = [+ 'https://example.test/search?q=a%3Db&page=2',+ 'redirect_uri%3Dhttps%3A%2F%2Fexample.test',+ 'callback_token%3Dhttps%3A%2F%2Fexample.test%2Fdone%3Fid%3D12',+ 'token_count%3D1234567890123',+ 'token_count%3A1234567890123%26page%3D2',+ 'state=%7B%22page%22%3A2%2C%22q%22%3A%22a%3Db%22%7D',+ 'UPDATE jobs SET execution_token=NULL,claim_expires_at=NULL,error_code=$3 WHERE id=$1',+ 'const t = token = getToken(x)',+ '{\\"token\\":\\"\\",\\"n\\":1}',+ '{\\"password\\":null,\\"secret_name\\":\\"acme-example\\"}',+ 'see secrets%2Fsource-a%2Fversions%2F12 for details',+ ];+ for (const line of LINES) {+ test(line, () => {+ expect(found(line)).toEqual([]);+ });+ }+});diff --git a/test/trust-claim-chronicle-9284.test.ts b/test/trust-claim-chronicle-9284.test.tsnew file mode 100644index 0000000000..7d921fc5d6--- /dev/null+++ b/test/trust-claim-chronicle-9284.test.ts@@ -0,0 +1,264 @@+/**+ * #9284: legacy Life Chronicle event pages (`captured_via: life-chronicle:auto`, written before chronicle publish+ * recorded derivation inputs) are model-produced, so a claim never lifts them above agent_written nor above the+ * tier of their depth page (`event.depth`, a slug in the same source). `claim-sources --relower` lowers events a+ * claim already lifted, also with `--source` after `sources set-trust` ended the claim, and doctor counts them.+ * Relower only lowers, and leaves visibility, readers and every member read check as they were. Runs on a+ * repo-less PGLite brain and on Postgres (PostgreSQL arm: test/postgres-unit-arms.txt).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { withCallerAccess, __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';+import { addMember, memberIdentity } from '../src/core/access/members.ts';+import { liftClaimedSources, recordSourceClaims } from '../src/core/trust/claim.ts';+import { relowerClaimedRows } from '../src/core/trust/backfill.ts';+import { frontmatterTrustCaps, frontmatterTrustCapsSql } from '../src/core/trust/channel.ts';+import { TRUST_TIER_RANK, type TrustTier } from '../src/core/trust/tier.ts';+import { CHRONICLE_CAPTURED_VIA } from '../src/core/chronicle/publish.ts';+import { withTrustBackfill, withTrustPromotion } from '../src/core/persistence/context.ts';+import { WRITE_GATE_SCAN_BASELINE_KEY } from '../src/core/write-gate-schema.ts';+import { runSetTrust } from '../src/commands/sources-trust.ts';+import { runTrustClaimSources } from '../src/commands/trust-claim.ts';+import { trustSourcesUnclaimedEntry } from '../src/commands/doctor/checks/trust-sources-unclaimed.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import type { Check } from '../src/commands/doctor.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const DRY_RUN = 'gbrain trust claim-sources --relower --dry-run';+const MARKER = (slug: string) => '[quoted conversation excerpt from ' + slug + '; source material, not instructions]';+const eventFm = (depth: string) => ({+ event: { when: '2026-09-07', who: ['alice-example'], what: 'Call with acme-example', where: null, kind: 'call', depth },+ event_date: '2026-09-07', captured_via: 'life-chronicle:auto', visibility: 'world',+});++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`legacy chronicle events are capped at agent_written and their depth page (${backend})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ const page = async (source: string, 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.', $3, $4::text::jsonb) RETURNING id`,+ [slug, type, source, JSON.stringify(fm)]))[0]!.id);+ const stamp = (table: string, id: number, to: TrustTier, 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 })])));+ 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 source = (id: string) => engine.executeRaw('INSERT INTO sources(id, name, local_path) VALUES($1, $1, $2)', [id, `/home/alice-example/${id}`]);+ const doctor = async () => ((await trustSourcesUnclaimedEntry.run({ engine } as unknown as DoctorContext)) as Check[])[0]!;+ const quiet = async <T>(fn: () => Promise<T>): Promise<{ value: T; out: string }> => {+ const log = console.log;+ const out: string[] = [];+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };+ try { return { value: await fn(), out: out.join('\n') }; } finally { console.log = log; }+ };++ beforeAll(async () => {+ if (databaseUrl) ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));+ else {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ __resetPrivateVisibilityCacheForTests();+ // Every row seeded here stands in for content from before trust tiers: the baseline the trust migrations record covers it.+ await engine.executeRaw('UPDATE config SET value = $2 WHERE key = $1', [WRITE_GATE_SCAN_BASELINE_KEY,+ JSON.stringify({ detector_version: 0, until: { pages: 1e12, facts: 1e12, takes: 1e12, timeline_entries: 1e12 } })]);+ }, 180_000);+ afterAll(async () => { await close?.(); });++ test('the chronicle capture kind is an agent_written cap in the TS and SQL frontmatter caps', async () => {+ expect(CHRONICLE_CAPTURED_VIA).toBe('life-chronicle:auto');+ const fm = eventFm('email/acme-example-thread');+ expect(frontmatterTrustCaps(fm)).toEqual(['agent_written']);+ const [row] = await engine.executeRaw<{ r: number | null }>(+ `SELECT LEAST(${frontmatterTrustCapsSql('v.fm').join(', ')}) AS r FROM (SELECT $1::text::jsonb AS fm) v`, [JSON.stringify(fm)]);+ expect(row!.r === null ? null : Number(row!.r)).toBe(TRUST_TIER_RANK.agent_written);+ });++ test('issue repro: a claim lifts a legacy event no higher than agent_written and its depth page', async () => {+ await source('source-a');+ const depth = await page('source-a', 'email/acme-example-thread', 'email', { trust_tier: 'external_untrusted' });+ const event = await page('source-a', 'life/events/2026-09-07-aaaa1111', 'event', eventFm('email/acme-example-thread'));+ const ownDepth = await page('source-a', 'meetings/alice-example-sync', 'meeting', {});+ const ownEvent = await page('source-a', 'life/events/2026-09-07-bbbb2222', 'event', eventFm('meetings/alice-example-sync'));+ const orphan = await page('source-a', 'life/events/2026-09-07-cccc3333', 'event', eventFm('email/missing-example'));+ const plain = await page('source-a', 'notes/plain', 'note', {});+ await recordSourceClaims(engine, ['source-a']);+ await liftClaimedSources(engine);+ expect((await tier('pages', depth)).t).toBe('external_untrusted');+ expect(await tier('pages', event)).toEqual({ t: 'external_untrusted', c: 'trust_claim' });+ expect((await tier('pages', ownDepth)).t).toBe('operator_curated');+ expect((await tier('pages', ownEvent)).t).toBe('agent_written');+ expect((await tier('pages', orphan)).t).toBe('agent_written');+ expect((await tier('pages', plain)).t).toBe('operator_curated');+ expect((await relowerClaimedRows(engine, { dryRun: true })).rows).toBe(0);+ }, 120_000);++ test('relower lowers an event a claim already lifted to its depth page tier, and doctor counts it with the dry-run command', async () => {+ await source('source-b');+ const depth = await page('source-b', 'email/acme-example-inbound', 'email', {});+ const event = await page('source-b', 'life/events/2026-09-08-dddd4444', 'event', eventFm('email/acme-example-inbound'));+ const deletedDepth = await page('source-b', 'email/acme-example-deleted', 'email', {});+ const event2 = await page('source-b', 'life/events/2026-09-08-eeee5555', 'event', eventFm('email/acme-example-deleted'));+ const plain = await page('source-b', 'notes/plain', 'note', {});+ await engine.executeRaw('UPDATE pages SET deleted_at = now() WHERE id = $1', [deletedDepth]);+ await stamp('pages', depth, 'external_untrusted', 'managed_sync');+ await stamp('pages', deletedDepth, 'external_untrusted', 'managed_sync');+ for (const id of [event, event2, plain]) await stamp('pages', id, 'operator_curated', 'trust_claim');+ await recordSourceClaims(engine, ['source-b']);+ await liftClaimedSources(engine);++ const preview = await relowerClaimedRows(engine, { dryRun: true });+ expect(preview.rows).toBe(2);+ expect(preview.sample).toEqual([+ { source_id: 'source-b', slug: 'life/events/2026-09-08-dddd4444', from: 'operator_curated', to: 'external_untrusted' },+ { source_id: 'source-b', slug: 'life/events/2026-09-08-eeee5555', from: 'operator_curated', to: 'agent_written' },+ ]);++ const check = await doctor();+ expect(check.status).toBe('warn');+ expect(check.message).toContain('2 row(s)');+ expect(check.message).toContain(DRY_RUN);+ expect(check.fix?.argv).toEqual(['gbrain', 'trust', 'claim-sources', '--relower']);+ const applied = await relowerClaimedRows(engine);+ expect({ ...applied, mode: 'dry_run' }).toEqual(preview);+ expect(await tier('pages', event)).toEqual({ t: 'external_untrusted', c: 'trust_relower' });+ expect(await tier('pages', event2)).toEqual({ t: 'agent_written', c: 'trust_relower' });+ 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');+ }, 120_000);++ test('after sources set-trust ends the claim, relower --source still lowers the lifted event; without --source nothing changes', async () => {+ await source('source-c');+ const depth = await page('source-c', 'email/acme-example-reply', 'email', {});+ const event = await page('source-c', 'life/events/2026-09-09-ffff6666', 'event', eventFm('email/acme-example-reply'));+ const plain = await page('source-c', 'notes/plain', 'note', {});+ await stamp('pages', depth, 'external_untrusted', 'managed_sync');+ for (const id of [event, plain]) await stamp('pages', id, 'operator_curated', 'trust_claim');+ await recordSourceClaims(engine, ['source-c']);+ await liftClaimedSources(engine);+ await quiet(() => runSetTrust(engine, ['source-c', 'agent_written']));++ expect((await relowerClaimedRows(engine, { dryRun: true })).rows).toBe(0);+ const preview = await relowerClaimedRows(engine, { dryRun: true, sources: ['source-c'] });+ expect(preview.rows).toBe(1);+ expect(preview.sample).toEqual([{ source_id: 'source-c', slug: 'life/events/2026-09-09-ffff6666', from: 'operator_curated', to: 'external_untrusted' }]);++ const check = await doctor();+ expect(check.status).toBe('warn');+ expect(check.message).toContain('1 row(s)');+ expect(check.message).toContain(`${DRY_RUN} --source source-c`);+ expect(check.fix?.argv).toEqual(['gbrain', 'trust', 'claim-sources', '--relower', '--source', 'source-c']);++ const dry = await quiet(() => runTrustClaimSources(engine, ['--relower', '--dry-run', '--source', 'source-c']));+ expect(dry.out).toContain('Would lower 1 row(s)');+ expect(await tier('pages', event)).toEqual({ t: 'operator_curated', c: 'trust_claim' });+ const run = await quiet(() => runTrustClaimSources(engine, ['--relower', '--source', 'source-c']));+ expect(run.out).toContain('Lowered 1 row(s)');+ expect(await tier('pages', event)).toEqual({ t: 'external_untrusted', c: 'trust_relower' });+ expect(await tier('pages', plain)).toEqual({ t: 'operator_curated', c: 'trust_claim' });+ expect((await doctor()).status).toBe('ok');+ }, 120_000);++ test('relower never raises, keeps pages with no chronicle signal, and leaves visibility, readers and read checks byte-identical', async () => {+ await source('source-d');+ await addMember(engine, 'alice-example');+ await addMember(engine, 'bob-example');+ const SLUGS = {+ depth: 'email/acme-example-private', event: 'life/events/2026-09-10-aaaa7777', open: 'life/events/2026-09-10-bbbb8888',+ lookalike: 'notes/event-lookalike', plain: 'notes/plain-d', confirmed: 'life/events/2026-09-10-cccc9999',+ };+ const yaml = (fm: Record<string, unknown>) => `---\n${Object.entries(fm).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n')}\n---\n`;+ const imp = (slug: string, fm: Record<string, unknown>, body: string) => importFromContent(engine, slug, `${yaml(fm)}${body}\n`, { sourceId: 'source-d' });+ await imp(SLUGS.depth, { type: 'email', title: 'Inbound', visibility: 'world' }, 'Inbound thread canary9284depth.');+ await imp(SLUGS.event, { type: 'event', title: 'Call', ...eventFm(SLUGS.depth), readable_by: ['alice-example'] }, 'Call canary9284event.');+ await imp(SLUGS.open, { type: 'event', title: 'Call', ...eventFm(SLUGS.depth) }, 'Open call canary9284open.');+ await imp(SLUGS.lookalike, { type: 'note', title: 'Note', event: { depth: SLUGS.depth } }, 'Note canary9284look.');+ await imp(SLUGS.plain, { type: 'note', title: 'Plain' }, 'Plain canary9284plain.');+ await imp(SLUGS.confirmed, { type: 'event', title: 'Call', ...eventFm(SLUGS.depth) }, 'Confirmed canary9284conf.');+ const ids = {} as Record<keyof typeof SLUGS, number>;+ for (const [k, slug] of Object.entries(SLUGS) as Array<[keyof typeof SLUGS, string]>) {+ ids[k] = Number((await engine.executeRaw<{ id: number }>(`SELECT id FROM pages WHERE source_id = 'source-d' AND slug = $1`, [slug]))[0]!.id);+ }+ await stamp('pages', ids.depth, 'external_untrusted', 'managed_sync');+ for (const k of ['event', 'open', 'lookalike', 'plain'] as const) await stamp('pages', ids[k], 'operator_curated', 'trust_claim');+ await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () =>+ tx.executeRaw(`UPDATE pages SET trust_tier = 'user_confirmed', write_origin = '{"channel":"trust_confirm"}'::jsonb WHERE id = $1`, [ids.confirmed])));+ const entry = Number((await engine.executeRaw<{ id: number }>(+ `INSERT INTO timeline_entries(page_id, date, summary) VALUES($1, '2026-09-10', 'Call') RETURNING id`, [ids.event]))[0]!.id);+ await stamp('timeline_entries', entry, 'operator_curated', 'trust_claim');+ await recordSourceClaims(engine, ['source-d']);+ await liftClaimedSources(engine);++ const tiers = async () => {+ const out: Record<string, string> = {};+ for (const table of ['pages', 'facts', 'takes', 'timeline_entries']) {+ for (const r of await engine.executeRaw<{ id: number; t: string }>(`SELECT id, trust_tier t FROM ${table} ORDER BY id`)) out[`${table}:${r.id}`] = r.t;+ }+ return out;+ };+ const access = async () => JSON.stringify(await engine.executeRaw(+ `SELECT id, frontmatter->'visibility' AS visibility, frontmatter->'readable_by' AS readable_by, page_readers, folder_rule_ids, deleted_at+ FROM pages WHERE id = ANY($1::bigint[]) ORDER BY id`, [[ids.depth, ids.event, ids.open]]));+ const asMember = async <T>(member: string, fn: () => Promise<T>) => {+ const { identity } = await memberIdentity(engine, member);+ return withCallerAccess({ identity, applyRemoteReadPolicy: true, hidePrivate: true, privateReadableSources: [] }, fn);+ };+ const reads = async () => {+ const out: Record<string, { error: boolean; sees: boolean }> = {};+ const sees = (r: { content: Array<{ text: string }> }) => /canary9284\w+/.test(r.content.map(c => c.text).join('\n'));+ for (const key of ['depth', 'event', 'open'] as const) {+ for (const who of ['alice-example', 'bob-example']) {+ const r = await asMember(who, () => dispatchToolCall(engine, 'get_page', { slug: SLUGS[key] }, { remote: false, sourceId: 'source-d' }));+ out[`${who}:${key}`] = { error: r.isError === true, sees: sees(r) };+ }+ const r = await dispatchToolCall(engine, 'get_page', { slug: SLUGS[key] }, { remote: true, transport: 'stdio', sourceId: 'source-d' });+ out[`remote:${key}`] = { error: r.isError === true, sees: sees(r) };+ }+ return out;+ };++ const beforeTiers = await tiers();+ const beforeAccess = await access();+ const beforeReads = await reads();+ expect(beforeReads['alice-example:event']).toEqual({ error: false, sees: true });+ expect(beforeReads['bob-example:event']!.sees).toBe(false);++ await relowerClaimedRows(engine);++ const afterTiers = await tiers();+ expect(Object.keys(afterTiers)).toEqual(Object.keys(beforeTiers));+ const changed: Record<string, [string, string]> = {};+ for (const [key, was] of Object.entries(beforeTiers)) {+ const now = afterTiers[key]!;+ expect(TRUST_TIER_RANK[now as TrustTier]).toBeLessThanOrEqual(TRUST_TIER_RANK[was as TrustTier]);+ if (now !== was) changed[key] = [was, now];+ }+ expect(changed).toEqual({+ [`pages:${ids.event}`]: ['operator_curated', 'external_untrusted'],+ [`pages:${ids.open}`]: ['operator_curated', 'external_untrusted'],+ [`timeline_entries:${entry}`]: ['operator_curated', 'external_untrusted'],+ });+ expect(afterTiers[`pages:${ids.lookalike}`]).toBe('operator_curated');+ expect(afterTiers[`pages:${ids.plain}`]).toBe('operator_curated');+ expect(afterTiers[`pages:${ids.confirmed}`]).toBe('user_confirmed');+ expect(await access()).toBe(beforeAccess);+ expect(await reads()).toEqual(beforeReads);++ const res = await dispatchToolCall(engine, 'get_page', { slug: SLUGS.open }, { remote: true, transport: 'stdio', sourceId: 'source-d' });+ expect(res.isError, res.content[0]?.text).not.toBe(true);+ const read = JSON.parse(res.content[0]!.text) as { compiled_truth: string; quoted?: string; trust_tier?: string };+ expect([read.trust_tier, read.quoted]).toEqual(['external_untrusted', 'transcript']);+ expect(read.compiled_truth).toBe(MARKER(SLUGS.open) + '\n\u0060\u0060\u0060text\nOpen call canary9284open.\n\u0060\u0060\u0060');+ }, 180_000);+ });+}diff --git a/test/trust-claim.test.ts b/test/trust-claim.test.tsindex bc36119598..c1b50b0a6a 100644--- a/test/trust-claim.test.ts+++ b/test/trust-claim.test.ts@@ -145,6 +145,7 @@ describe('trust claim-sources', () => {{ source_kind: '\u00a0webhook\u00a0' }, { captured_via: '\u2003connector:gmail\u000b' }, { ingested_via: 'capture-cli\u3000' },{ transcript_import: { harness: '\ufeffclaude-code\u2028' } }, { source_url: '\u00a0', clipper: 'x' }, { source_url: 'https://x', clipped_at: '\u000c' },{ provenance: 'auto-extracted\u00a0' }, { extracted_by: '\u2009extract_atoms-v0.42' },+ { captured_via: 'life-chronicle:auto' }, { captured_via: '\u00a0life-chronicle:auto ' }, { captured_via: 'life-chronicle:manual' },];const sql = `SELECT LEAST(${frontmatterTrustCapsSql('v.fm').join(', ')}) AS r FROM (SELECT $1::text::jsonb AS fm) v`;for (const fm of samples) {