Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#5575 memory trust after master v0.60.115.0: migrations v222-v226, content_origin under the full-surface default, bulk-write grant test, KEY_FILES split
garrytane2a0e6da3706
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 26fea30187..fc70eafc06 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -42,7 +42,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/timeline-citations.ts` — `parseInlineCitationTimelineEntries`: inline `[Source: <source>, YYYY-MM-DD]` citations become timeline candidates whose summary is the citing paragraph without the citation. #6184: a comment-only line is a paragraph boundary and `stripHtmlComments` removes `<!-- … -->` spans (and dangling `<!--`/`-->`) before the summary is built, so section and materialized-row markers are never filed as entries. #6226: a citation files one entry per dated `source, date` segment (a `;` splits sources only after a date), summaries unwrap paired emphasis, and `supersededInlineCitationEntries` returns what the older one-source reading filed and the current reading no longer does; `timeline-extract.ts:supersededCitationTimeline` runs it with both extractors' bullet skips and `retractRemovedTimelineEntries` retracts those rows when their detail is extractor-written (`hasExtractorDetail`: empty or `Source: <source>`). The dated-bullet regexes (`TIMELINE_LINE_RE`, `_CN`, `isDatedTimelineLine`) live here and `link-extraction.ts` imports them.- `src/core/transcripts.ts` — `listRecentTranscripts(engine, opts)` library reused by both the `gbrain transcripts recent` CLI and the `get_recent_transcripts` MCP op. Reads `dream.synthesize.session_corpus_dir` + `dream.synthesize.meeting_transcripts_dir` config (same as `discoverTranscripts`); walks `.txt` files within `days`; applies the `isDreamOutput` guard from `transcript-discovery.ts` (skips dream-generated files); returns `{path, date, mtime, length, summary}[]` sorted newest-first. Summary mode (default true) = first non-empty line + ~250 trailing chars; full mode caps at 100KB/file. Missing/non-existent corpus dirs return `[]`, not error. Trust gate lives in the op handler, not here: the op throws `permission_denied` for `ctx.remote === true`; this is a trusted library function used by both the gated op and the local CLI.-- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`. Write side (lane L1a): `channel.ts` computes the tier once per write from the channel (`requestChannelTrust`: agent verbs agent_written, `content_origin: tool_output` external_untrusted, connector jobs external_untrusted; owner sync/import `ownerImportTrust`: operator_curated or the `sources set-trust` default, lowered by frontmatter markers `frontmatterTrustCaps`) and `stampTrustMarker` (the lower-only `trust_tier` marker, CEO-21); `page-write.ts` wires it into page-prepare (marker stamp, fence edits keep the page tier via `withTrustKeep`, `lower_page` proposals on agent rewrites, the page gate tier); `proposals.ts` is the `trust_proposals` store and handler dispatch (`decide.ts` loads every handler); `supersede-handlers.ts` is guarded supersession (`supersessionGuarded`, contested fact/take/ontology proposals, remote `forget_requires_owner`, the trust store for the checked decide_proposals supersede); `fence-guard.ts` guards the facts-fence re-projection and gates new fence rows; `gate-outcomes.ts` is the DX-1 `gate` field and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15). `owner-actions.ts`: `previewOwnerAction` / `applyOwnerAction` for confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and a `binding` of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with `preview_changed` and a raising action without a confirmation with `confirmation_required` (`ownerActionFix` is the DX-3 `tell_user_to_run` fix). Fact and take confirms are tier-only updates under `withTrustPromotion` (inside `withCoordinatedWrite` on a managed brain); the hold store is an isolated adapter over `write_gate_holds` (`__setHoldStoreForTests`, `TODO(L2a-merge)`); `disable --all` writes `write_gate.external_mode=off`, `write_gate.agent_mode=off`, `trust.agent_activation=allow` with the `trust.kill_switch` receipt that `--undo` restores from. `page-handlers.ts`: `confirmPage` (removes the CEO-21 `trust_tier` marker through a journaled `trust_owner_page` mutation on a managed brain, `importFromContent` otherwise; tier only when no marker), `revertPageToVersion` (the version's content and its snapshot tier, `unknown` for legacy versions), the coordinator preparer `prepareTrustOwnerPageMutation` (dispatched from `persistence/service.ts`; re-checks the approved revision and refuses a remote request without `memory_confirm`), and the `lower_page` handler (accept = confirm, reject = dismiss, `revertLoweredPage` = restore the prior owner version). `refs.ts`: typed refs `f<id>`, `t<id>`, `h<id>`, `tp<id>`, `a<id>`, `p:<source>/<slug>`, bare slugs resolved by `--source` or a single source (ambiguity refuses). `review.ts`: `buildTrustReview` (pending proposals, lowered pages, unconfirmed standing preferences, holds, allow rules, kill-switch state, grouped by day and page, complete argv) and `explainTrust`. `allow-rules.ts`: the `trust_allow_rules` table (migration v225, receipted, removal keeps the row) and the pure `matchTrustAllowRule` over server-stamped fields. `owner-ipc.ts`: the `trust_read` / `trust_preview` / `trust_apply` administration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests: `test/trust-owner-actions.test.ts` (PGLite and Postgres), `test/trust-owner-ipc.test.ts`, `test/trust-cli.test.ts`. `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated. Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.+- `src/core/trust/` — memory trust tiers (#5575). `tier.ts`: the six tiers in filter order (`user_confirmed` > `operator_curated` > `tool_observed` > `agent_written` > `unknown` > `external_untrusted`), `TRUST_TIER_LABELS` (the fixed user-facing labels; enums only in JSON), `minTrust`/`maxTrust`/`admitsTrust`/`tiersAtOrAbove`, `contentOriginTier` (`tool_output` lowers to external), `storedMinTrust` (a damaged token floor fails closed to the strictest), and `effectiveWriteTrust`, which computes a write's tier once (derived writes capped at `agent_written` and their least trusted input; `write_origin.taint_inputs` keeps the 32 least trusted with `taint_inputs_truncated`/`taint_input_count`). `schema.ts` (migration only, like attribution): `trust_tier` + `write_origin` on facts, takes, timeline_entries and pages, the page_versions snapshot, `min_trust` on oauth_clients/access_tokens, `trust_proposals`, and the BEFORE ROW `trust_tier_stamp` trigger (fires last: INSERT gets the writer's tier from `gbrain.write_trust_tier` or `unknown`; a `TRUST_CONTENT_COLUMNS` change restamps for an owner-tier writer and takes min(prior, writer) otherwise; an unchanged row keeps its tier; a raise needs `gbrain.write_trust_promotion` covering it, or `gbrain.write_trust_backfill` from `unknown` to below `user_confirmed`, else `trust_raise_refused`). Writers declare through `WriteAttribution.trust`, `withWriteTrust` and `maintenanceTransaction(…, trust)` (`persistence/context.ts`; nested declarations combine as min, a group member resets). `confirm.ts`: `requireOwnerConfirmation` (a remote caller needs `memory_confirm`; the local CLI needs a TTY where the user types the target token; `--yes` never confirms), `tierRaiseFix`, `trustRaiseRefusal`, test seam `__setConfirmationIoForTests`. `min-trust.ts`: the local-only floor writes behind `gbrain auth create --min-trust` and `gbrain auth set-min-trust`. `backfill.ts`: `gbrain trust backfill` (deterministic signals, read-only dry run that works before the migration, resumable batches inside `withCoordinatedWrite` on managed brains) and the doctor `trust_tiers` counts. Tests: `test/trust-tier.test.ts`, `test/trust-tier-schema.test.ts` and `test/trust-backfill.test.ts` (PGLite and Postgres), `test/trust-confirm-scope.test.ts`. Write side (lane L1a): `channel.ts` computes the tier once per write from the channel (`requestChannelTrust`: agent verbs agent_written, `content_origin: tool_output` external_untrusted, connector jobs external_untrusted; owner sync/import `ownerImportTrust`: operator_curated or the `sources set-trust` default, lowered by frontmatter markers `frontmatterTrustCaps`) and `stampTrustMarker` (the lower-only `trust_tier` marker, CEO-21); `page-write.ts` wires it into page-prepare (marker stamp, fence edits keep the page tier via `withTrustKeep`, `lower_page` proposals on agent rewrites, the page gate tier); `proposals.ts` is the `trust_proposals` store and handler dispatch (`decide.ts` loads every handler); `supersede-handlers.ts` is guarded supersession (`supersessionGuarded`, contested fact/take/ontology proposals, remote `forget_requires_owner`, the trust store for the checked decide_proposals supersede); `fence-guard.ts` guards the facts-fence re-projection and gates new fence rows; `gate-outcomes.ts` is the DX-1 `gate` field and the held-write verb error. Owner actions: owner actions (#5575 lane L1a-owner: A4, CEO-2, CEO-9, CEO-12, DX-2, DX-7, DX-10, DX-13, DX-14, DX-15, ENG-15). `owner-actions.ts`: `previewOwnerAction` / `applyOwnerAction` for confirm, drop, release, revert, allow, allow_remove, disable and enable: the preview names the summary, the typed token (the ref, or a hash8 for page refs), the exact command, whether the action raises trust and a `binding` of the target's exact state (row content and tier, page revision, proposal status); apply re-previews, refuses a moved binding with `preview_changed` and a raising action without a confirmation with `confirmation_required` (`ownerActionFix` is the DX-3 `tell_user_to_run` fix). Fact and take confirms are tier-only updates under `withTrustPromotion` (inside `withCoordinatedWrite` on a managed brain); the hold store is an isolated adapter over `write_gate_holds` (`__setHoldStoreForTests`, `TODO(L2a-merge)`); `disable --all` writes `write_gate.external_mode=off`, `write_gate.agent_mode=off`, `trust.agent_activation=allow` with the `trust.kill_switch` receipt that `--undo` restores from. `page-handlers.ts`: `confirmPage` (removes the CEO-21 `trust_tier` marker through a journaled `trust_owner_page` mutation on a managed brain, `importFromContent` otherwise; tier only when no marker), `revertPageToVersion` (the version's content and its snapshot tier, `unknown` for legacy versions), the coordinator preparer `prepareTrustOwnerPageMutation` (dispatched from `persistence/service.ts`; re-checks the approved revision and refuses a remote request without `memory_confirm`), and the `lower_page` handler (accept = confirm, reject = dismiss, `revertLoweredPage` = restore the prior owner version). `refs.ts`: typed refs `f<id>`, `t<id>`, `h<id>`, `tp<id>`, `a<id>`, `p:<source>/<slug>`, bare slugs resolved by `--source` or a single source (ambiguity refuses). `review.ts`: `buildTrustReview` (pending proposals, lowered pages, unconfirmed standing preferences, holds, allow rules, kill-switch state, grouped by day and page, complete argv) and `explainTrust`. `allow-rules.ts`: the `trust_allow_rules` table (migration v225, receipted, removal keeps the row) and the pure `matchTrustAllowRule` over server-stamped fields. `owner-ipc.ts`: the `trust_read` / `trust_preview` / `trust_apply` administration handlers a resident owner serves over its 0600 socket to the verified local CLI only. Tests: `test/trust-owner-actions.test.ts` (PGLite and Postgres), `test/trust-owner-ipc.test.ts`, `test/trust-cli.test.ts`. Derived-row taint (`taint.ts`, `derived-gate.ts`, `timeline-projection.ts`): see [security](security.md).- `src/core/eligibility/{policy,sql,labels,registry,stamp,activation,scan,explain}.ts` — the one reversible read eligibility policy for memory trust (#5575 A6, A7, CEO-18, CEO-20, DX-6, DX-10, ENG-8, ENG-14). `policy.ts`: `resolveReadEligibility` returns the effective floor (the strictest of `AuthInfo.minTrust`, the caller's `min_trust` and `trust.read_policy=filter`'s own `unknown` floor; label mode adds nothing, so ordering is byte-identical) and, for proactive reads, `suppressFlagged` unless `trust.agent_activation=allow`. `sql.ts`: vetted predicates over a caller alias (closed vocabularies only): `trustFloorSql`, `pageEligibleSql` (spliced by `buildVisibilityClause` and `pageReadFilter`, so every search arm filters before LIMIT; a chunk's tier is its page's), `projectionEligibleSql` (facts, takes and timeline reads: a quarantined page's projections and `needs_rederive` rows are hidden, never expired) and `activationSuppressedSql` (tier at or below `agent_written` plus an instruction-family `write_gate_receipts` flag). `labels.ts`: `trust_tier` + a short server-stamped `origin`; compact per-item text labels with the fixed words, `unknown` as a short origin line, and the `<external-data>` envelope only below `unknown`. `registry.ts`: `OP_READ_TRUST` classifies every read-scope op `filtered | labeled | text_free` (the dispatcher refuses a `labeled` op for a floored token) and `PROACTIVE_SURFACES` lists the injecting surfaces, each calling `proactiveEligibility(ctx, id)`; drift-tested by `test/eligibility-registry.test.ts`. `stamp.ts` labels rows after ranking and backstops the floor for rows a stage adds by slug; explicit reads mark flagged rows `unconfirmed`. `activation.ts` partitions proactive candidates (`partitionForActivation`, `pageActivationVerdicts`) and builds the `memory_suppressed` notice (count + `gbrain trust review`, never content). `scan.ts` (`gbrain trust scan`, doctor `trust_scan`) records flag receipts for agent-written-or-lower rows written before the gate, in resumable keyset batches bounded by the id ceiling of its first run (later rows are gated by their writers; a detector bump rescans). `explain.ts` is the `gbrain trust explain` data API: tier, origin, receipts and the per-surface decision for a typed ref. Tests: `test/eligibility-{policy,registry,reads}.test.ts`.- `src/core/eligibility/fence-overlay.ts` + `src/core/trust/fence-append.ts` — the facts-fence eligibility overlay for chunks (#5575 ENG-1). `loadFenceChunkOverlay(engine, { sourceId, slug, compiled_truth, timeline })` reads, in one query and only when the body has world fence rows, which rows to omit (a `write_gate_holds` hold on the row's fingerprint, through the `registerFactHoldFingerprint` seam for the write gate's `holdFingerprint`; a `fact_purges` tombstone, the backstop to L3's import overlay) and which to demote (stored `facts.trust_tier` below the page tier, or a row a fence append is publishing, declared with `withPendingFenceRows`). `prepareMarkdownChunks(page, maxTokens, overlay)` (`markdown-chunks.ts`) drops both from the page's chunks and emits demoted rows as trailing chunks whose first line is `fenceTrustMarker(tier)` (a `compactTrustLabel` line with origin `facts-fence`); without overlay rows the output is byte-identical. The importer (`prepareFenceAwareMarkdownChunks`), projection rebuilds (`ProjectionSnapshot.fenceOverlay`), embed's chunkless rebuilds (`prepareProseChunks`) and evidence delivery's page document (`pageEvidenceText`) all cut through it; `healOversizedChunks` keeps the marker on every split piece. `eligibility/stamp.ts` labels a row carrying a marker min(page tier, marker tier) with origin `facts-fence` and applies floors at that tier; a marker can only lower. `withPageTierKept(tx, page, fn)` restores the page's prior `trust_tier`/`write_origin` after a fence append's page write (promotion capped at the prior tier when raising back), used by `fence-write.ts` (legacy mirror), `memory-prepare.ts` (remember) and `facts-prepare.ts` (managed entity facts). Tests: `test/fence-chunk-overlay.test.ts` (PGLite and Postgres via `test/e2e/fence-chunk-overlay-postgres.test.ts`).- `src/core/types.ts` extension + `src/core/operations.ts:search` + `src/core/import-file.ts` + `src/cli.ts` + `src/core/search/telemetry.ts` — the wiring layer for the retrieval-quality stack. `SearchResult` carries `evidence`, `create_safety`, `title_match_boost`, `alias_hit` (all optional; evidence/create_safety reference the union types in `evidence.ts`). The `search` MCP op uses a cheap-hybrid path by default and accepts a per-call `mode` (conservative|balanced|tokenmax) honored ONLY for trusted/local callers (`resolvePerCallMode(ctx, ...)` — remote callers use the configured mode so a remote provider can't force tokenmax spend); every search path stamps evidence fail-soft. `importFromContent` projects frontmatter `aliases:` into `page_aliases` via `normalizeAliasList` + `engine.setPageAliases` so new + changed pages register aliases at ingest. `src/cli.ts` carries the `gbrain search diagnose` dispatch (lazy import) and reconciles the `search` CLI path with the cheap-hybrid op. `src/core/search/telemetry.ts` carries in its rollup the rank-1 base_score drift signal (sum/count + 3 coarse buckets, aggregate not per-query), surfaced via `gbrain search stats`, backed by migration v111's `search_telemetry` columns. Tests: `test/cli-search-dispatch.test.ts`, `test/search/per-call-mode.test.ts`, `test/search/telemetry-rank1.test.ts`, `test/search/title-boost-stage.test.ts`, `test/search/alias-hop.test.ts`, `test/search/evidence.test.ts`, `test/search/searchvector-maxpool.test.ts`, `test/search/pre-migration-failopen.test.ts`.diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.mdindex 5978c09bd7..0a60182c28 100644--- a/docs/architecture/key-files/security.md+++ b/docs/architecture/key-files/security.md@@ -28,6 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ssrf-validate.ts` — DNS-rebinding-defended URL validation. `validateAndResolveUrl(url)` resolves the hostname via `dns.lookup({all: true, family: 0})`, checks EVERY A and AAAA record against the internal-IP deny list, and returns the resolved IP so callers fetch by IP (validation IP === fetch IP defeats DNS rebinding). `fetchWithSSRFGuard(url, opts)` does redirect-aware fetching with per-hop re-validation (max 3 hops by default). Reusable across all URL-fetching features. Test seam `__setDnsLookupForTests` for hermetic tests.+- `src/core/trust/taint.ts`, `derived-gate.ts`, `timeline-projection.ts` (#5575 derived rows; the rest of `src/core/trust/` is in [core utilities 2](core-utilities-2.md)): `taint.ts` (I2, ENG-3/ENG-7): `readTaintInputs`/`deriveTrust` read the stored tiers of every row a deriver placed in its prompt (a vanished input reads `unknown`); `derivedWriteTrust` caps model output at `agent_written` and a deterministic projection (fence or timeline parse) at `operator_curated`; `recordTaintEdges` writes the complete `derivation_inputs` edges; `lowerToDerivedTier`/`lowerDerivedPage` lower a derived row whose republish changed no content column; `derivedMaintenanceTransaction` is the unmanaged deriver seam; `declareDerivation`/`declaredWriteTrust` carry a derivation in a maintenance or facts intent (the preparer stamps it, never above `agent_written`); `readDerivedTaintShare` is the doctor CEO-24 diagnostic. `derived-gate.ts`: the derivers' row-level write gate at the declared tier (`derivedGateConfig`, `applyGateDecision`: insert + flag receipt, hold, or skip a reject; `recordTimelineFlag`). `timeline-projection.ts`: `gbrain extract` timeline walks stamped per page tier and gated. Tests: `test/trust-taint.test.ts`, `test/trust-taint-origin.test.ts` (PGLite and Postgres), `test/trust-taint-dream.test.ts`.- `src/core/trust/claim.ts` + `claim-state.ts` + `claim-notice.ts`, `src/commands/trust-claim.ts`: #5575 legacy content. `gbrain trust claim-sources` (local CLI; typed source id on a TTY, `--yes` never counts, non-TTY refuses `confirmation_required` with a tell_user_to_run fix) records a claim in `sources.config` (`trust_tier: operator_curated`, `trust_claimed_at`, `trust_claim_lifted_at`) and lifts the source's legacy `unknown` rows (ids at or below `write_gate.scan_baseline`) through `trust/backfill.ts` scoped to the claimed sources (own cursor, `write_origin.channel` `trust_claim`), lowered by `frontmatterTrustCapsSql` (channel.ts, pinned to `frontmatterTrustCaps`) and every backfill signal, never above operator_curated; connector sources refuse. Doctor `trust_sources_unclaimed`, `gbrain post-upgrade` and the behavior-change notice name the claim (`actor: user`, tell_user_to_run); doctor `trust_scan`'s fix is the user's to run; the scan refuses while a lift is pending; explain and review show pending rows as owner tier. Guide: `docs/guides/memory-trust.md`. Tests: `test/trust-claim.test.ts`.- `src/core/write-gate.ts` + `src/core/write-gate-patterns.ts` — the #5575 blocking write gate, separate from observe-only `guardrails.ts` (never imported). Deterministic and model-free (P8): `WRITE_GATE_PATTERNS` (bounded clones of the detection-grade `think/sanitize.ts` `INJECTION_DETECTION_PATTERNS`, the exported transcript `IMPERATIVE_RES`, plus standing-instruction (incl. agent-addressed rules with long run-ups, concealment and act-without-asking clauses), exfiltration (incl. passive "must be emailed to <address>" rules and direct cc/bcc) and credential patterns; families `override`, `standing_instruction`, `exfiltration`, `credential`). `detectInstructionLike` decodes tag characters, strips invisibles and NFKC-folds compatibility forms only when present, finds anchor words in one allocation-light hash pass (one tight loop per word), then runs each pattern only on 4 KB windows (overlap `MAX_MATCH_CHARS` + `MAX_PRECEDING_CHARS`) holding its anchors, tracked as sliding per-window anchor counts, and inside a window only within the pattern's longest match (`write-gate-regex.ts`, the analysis the regex lint uses) of its own anchor words, except `WHOLE_WINDOW_PATTERNS`; `preceded` regexes check context before a rare-token match, a `neg` group rejects negated matches. `assessPageForGate` (title, body minus managed fence table rows, frontmatter strings), `assessFactForGate` (fact, context, value, provenance, pre-sanitized `source_text`), `assessTakeForGate` and `assessTimelineForGate` scan every attacker-controllable field plus origin strings. Verdicts by tier: owner tiers never assessed; `external_untrusted` -> `write_gate.external_mode` (`quarantine` default, `flag`, `reject`, `off`), detector error -> quarantine; `agent_written`/`unknown` -> `flag` (`write_gate.agent_mode=off`), detector error -> allow. `writeGateOutcome` is the DX-1 `gate` shape; `writeHeldError` / `writeGateRejectedError` build the `write_held` / `write_gate_rejected` refusals (families only, no pattern names). `scripts/check-write-gate-regex.ts` (in verify) proves every pattern bounded. Tests: `test/write-gate.test.ts`, `test/write-gate-perf.slow.test.ts`, `test/write-gate-anchor-ranges.test.ts` (sampled matches of every narrowed pattern hold an anchor word within its longest match), and `test/write-gate-detector-differential.test.ts` (identical hits to the pre-optimization detector v2 kept as `test/helpers/write-gate-detector-reference.ts`, over the detector corpora, BrainBench fixtures, docs/skills and a seeded random corpus).diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.tsindex 273b68b4f5..17a4c36246 100644--- a/src/core/persistence/params.ts+++ b/src/core/persistence/params.ts@@ -52,8 +52,9 @@ export const CONTENT_ORIGIN_PARAM: ParamDef = {type: 'string',enum: ['user_said', 'tool_output', 'inferred'],description: 'Where the content came from: user_said, tool_output (web page, email, file or other tool text: stored as untrusted), inferred. Set it.',- // Like remember.replaces: advertised on the verbs and full surfaces, accepted on every surface (dispatch validates- // against the registry), off the starter schema so its list stays inside its size budget; safety never depends on it.+ // Like remember.replaces: advertised on the full surface (what new registrations and memory-writer grants use) and on+ // verbs, accepted on every surface (dispatch validates against the registry), and off the opt-in starter schema, which+ // keeps its size budget (test/mcp-schema-budget.test.ts); safety never depends on it.fullSurfaceOnly: true,};/** Page mutation params plus `content_origin`, for verbs whose caller supplies the content (put_page, put_pages, capture, edit_page, remember). */diff --git a/test/trust-confirm-scope.test.ts b/test/trust-confirm-scope.test.tsindex 7c2977be0c..93bec0f568 100644--- a/test/trust-confirm-scope.test.ts+++ b/test/trust-confirm-scope.test.ts@@ -25,6 +25,7 @@ import {} from '../src/core/scope.ts';import { GRANT_PROFILES, grantFromTokenRow } from '../src/core/grants/model.ts';import { resolveGrantProfile } from '../src/core/grants/profiles.ts';+import { AGENT_WRITE_OPERATIONS } from '../src/core/trust/channel.ts';import { mintLegacyToken } from '../src/core/token-mint.ts';import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';import { sqlQueryForEngine } from '../src/core/sql-query.ts';@@ -94,6 +95,18 @@ describe('memory_confirm scope (CEO-6)', () => {}});+ test('bulk-write grants (full surface, put_pages) cannot confirm or raise a tier', () => {+ const writer = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' });+ expect(writer.surface).toBe('full');+ expect(writer.allowedOperations).toContain('put_pages');+ // put_pages publishes at the agent channel tier; only memory_confirm (never implied) confirms.+ expect(AGENT_WRITE_OPERATIONS).toContain('put_pages');+ for (const profile of ['memory-writer', 'coding-agent'] as const) {+ const patch = resolveGrantProfile({ profile, sourceId: 'default', boundSlugPrefixes: ['wiki/agents/'] });+ expect({ profile, confirm: hasScope(patch.scopes ?? [], 'memory_confirm') }).toEqual({ profile, confirm: false });+ }+ });+test('a grandfathered null-scope token never holds it', () => {const grant = grantFromTokenRow({ id: randomUUID(), scopes: null, permissions: null, source_grant: null });expect(grant.scopes).toEqual(['read', 'write', 'admin']);