Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(write-gate): deterministic instruction detector with bounded patterns (#5575 B1, ENG-16)
garrytan668eed42c40a
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex e224ec1878..ac39086d21 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2670,6 +2670,26 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| Execution claim changed before publication. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### write_gate_rejected++<a id="write_gate_rejected"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`. | Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry. | Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision. | agent | `repeat the read that failed` | 1 | no |++Reasons: `override`, `standing_instruction`, `exfiltration`, `credential`, `detector_error`.++### write_held++<a id="write_held"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The write gate held this content for the owner's review instead of saving it as memory. | Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold. | Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision. | user | `repeat the read that failed` | 3 | no |++Reasons: `override`, `standing_instruction`, `exfiltration`, `credential`, `detector_error`.+### write_pending<a id="write_pending"></a>diff --git a/package.json b/package.jsonindex da62fb8295..ea83eec12c 100644--- a/package.json+++ b/package.json@@ -141,6 +141,7 @@"check:guard-self-test": "bash scripts/guard-self-test.sh","build:error-codes": "bun scripts/build-error-codes.ts","check:error-codes": "bun scripts/build-error-codes.ts --check",+ "check:write-gate-regex": "bun scripts/check-write-gate-regex.ts","build:agent-protocol": "bun scripts/build-agent-protocol.ts","check:agent-protocol": "bun scripts/build-agent-protocol.ts --check","check:agent-contract": "bun scripts/check-agent-contract.ts",diff --git a/scripts/check-write-gate-regex.ts b/scripts/check-write-gate-regex.tsnew file mode 100644index 0000000000..30a2019acf--- /dev/null+++ b/scripts/check-write-gate-regex.ts@@ -0,0 +1,154 @@+#!/usr/bin/env bun+/**+ * #5575 (ENG-16) regex-safety lint for the write gate detector.+ *+ * Every pattern in `WRITE_GATE_PATTERNS` (src/core/write-gate-patterns.ts)+ * must be safe to run on attacker-controlled text of any size:+ * - no unbounded quantifier (`*`, `+`, `{n,}`) and no bound above 200,+ * - no repeated group that itself contains a repeat (nested quantifiers),+ * - no backreference,+ * - a longest possible match of at most MAX_MATCH_CHARS, and a `preceded`+ * context of at most MAX_PRECEDING_CHARS (together the window overlap,+ * so a match straddling two scan windows is still found),+ * - non-global and non-sticky (`.test()` keeps no state), with at least one+ * lowercase prefilter anchor.+ *+ * Usage: bun scripts/check-write-gate-regex.ts (exit 0 clean, 1 on violations)+ * Self-test seam: with GBRAIN_GUARD_ROOT set, the guard checks the patterns+ * listed in <root>/patterns.json ({ name, source, flags, anchors, preceded? }+ * objects) instead of the real table (scripts/guard-self-test.sh fixtures).+ */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { MAX_MATCH_CHARS, MAX_PRECEDING_CHARS, WRITE_GATE_PATTERNS, type WriteGatePattern } from '../src/core/write-gate-patterns.ts';++export const MAX_QUANTIFIER_BOUND = 200;++interface Node { max: number; repeats: boolean }++/** Static analysis of one regex source: its longest match and every safety violation. */+export function analyzeRegexSource(source: string): { maxLength: number; errors: string[] } {+ const errors: string[] = [];+ let pos = 0;++ const atomWidth = (): Node & { group: boolean } => {+ const ch = source[pos]!;+ if (ch === '\\') {+ const next = source[pos + 1] ?? '';+ if (/[1-9]/.test(next) || next === 'k') errors.push(`backreference at ${pos}`);+ if (next === 'u' && source[pos + 2] === '{') { pos = source.indexOf('}', pos) + 1; return { max: 1, repeats: false, group: false }; }+ const len = next === 'u' ? 6 : next === 'x' ? 4 : next === 'c' ? 3 : 2;+ pos += len;+ return { max: next === 'b' || next === 'B' ? 0 : 1, repeats: false, group: false };+ }+ if (ch === '[') {+ pos++;+ while (pos < source.length && source[pos] !== ']') pos += source[pos] === '\\' ? 2 : 1;+ pos++;+ return { max: 1, repeats: false, group: false };+ }+ if (ch === '(') {+ pos++;+ let lookaround = false;+ if (source[pos] === '?') {+ const m = /^\?(?::|=|!|<=|<!|<[A-Za-z_][A-Za-z0-9_]*>)/.exec(source.slice(pos));+ if (!m) { errors.push(`unsupported group syntax at ${pos}`); return { max: 0, repeats: false, group: true }; }+ lookaround = ['?=', '?!', '?<=', '?<!'].includes(m[0]);+ pos += m[0].length;+ }+ const inner = alternation();+ if (source[pos] !== ')') errors.push(`unclosed group at ${pos}`);+ pos++;+ return { max: lookaround ? 0 : inner.max, repeats: inner.repeats, group: true };+ }+ if (ch === '^' || ch === '$') { pos++; return { max: 0, repeats: false, group: false }; }+ pos++;+ return { max: 1, repeats: false, group: false };+ };++ const quantifier = (): { lo: number; hi: number } | null => {+ const ch = source[pos];+ let q: { lo: number; hi: number } | null = null;+ if (ch === '?') { q = { lo: 0, hi: 1 }; pos++; }+ else if (ch === '*') { q = { lo: 0, hi: Infinity }; pos++; }+ else if (ch === '+') { q = { lo: 1, hi: Infinity }; pos++; }+ else if (ch === '{') {+ const m = /^\{(\d+)(,(\d*))?\}/.exec(source.slice(pos));+ if (!m) return null;+ q = { lo: Number(m[1]), hi: m[2] === undefined ? Number(m[1]) : m[3] === '' ? Infinity : Number(m[3]) };+ pos += m[0].length;+ }+ if (q && source[pos] === '?') pos++;+ return q;+ };++ const sequence = (): Node => {+ let max = 0;+ let repeats = false;+ while (pos < source.length && source[pos] !== '|' && source[pos] !== ')') {+ const start = pos;+ const atom = atomWidth();+ const q = quantifier();+ if (!q) { max += atom.max; repeats ||= atom.repeats; continue; }+ if (q.hi === Infinity) errors.push(`unbounded quantifier after "${source.slice(start, pos)}"`);+ else if (q.hi > MAX_QUANTIFIER_BOUND) errors.push(`quantifier bound ${q.hi} over ${MAX_QUANTIFIER_BOUND} after "${source.slice(start, pos)}"`);+ if (atom.group && atom.repeats && q.hi > 1) errors.push(`nested quantifier in "${source.slice(start, pos)}"`);+ const hi = Number.isFinite(q.hi) ? q.hi : MAX_QUANTIFIER_BOUND;+ max += atom.max * hi;+ repeats ||= atom.repeats || q.hi > 1;+ }+ return { max, repeats };+ };++ function alternation(): Node {+ let node = sequence();+ while (source[pos] === '|') {+ pos++;+ const next = sequence();+ node = { max: Math.max(node.max, next.max), repeats: node.repeats || next.repeats };+ }+ return node;+ }++ const root = alternation();+ if (pos < source.length) errors.push(`unbalanced ")" at ${pos}`);+ return { maxLength: root.max, errors };+}++export function checkWriteGatePatterns(patterns: readonly WriteGatePattern[] = WRITE_GATE_PATTERNS): string[] {+ const problems: string[] = [];+ const names = new Set<string>();+ for (const p of patterns) {+ if (names.has(p.name)) problems.push(`${p.name}: duplicate pattern name`);+ names.add(p.name);+ if (p.rx.global || p.rx.sticky) problems.push(`${p.name}: global or sticky flag (stateful .test())`);+ if (!p.anchors.length || p.anchors.some(a => !a || a !== a.toLowerCase())) problems.push(`${p.name}: needs non-empty lowercase prefilter anchors`);+ const { maxLength, errors } = analyzeRegexSource(p.rx.source);+ for (const e of errors) problems.push(`${p.name}: ${e}`);+ if (maxLength > MAX_MATCH_CHARS) problems.push(`${p.name}: longest match ${maxLength} chars exceeds MAX_MATCH_CHARS ${MAX_MATCH_CHARS}`);+ if (p.preceded) {+ if (p.preceded.global || p.preceded.sticky) problems.push(`${p.name}: preceded regex is global or sticky`);+ if (!p.preceded.source.endsWith('$')) problems.push(`${p.name}: preceded regex must end with $ (it checks the text right before the match)`);+ const ctx = analyzeRegexSource(p.preceded.source);+ for (const e of ctx.errors) problems.push(`${p.name} (preceded): ${e}`);+ if (ctx.maxLength > MAX_PRECEDING_CHARS) problems.push(`${p.name}: preceded context ${ctx.maxLength} chars exceeds MAX_PRECEDING_CHARS ${MAX_PRECEDING_CHARS}`);+ }+ }+ return problems;+}++function fixturePatterns(root: string): WriteGatePattern[] {+ const rows = JSON.parse(readFileSync(join(root, 'patterns.json'), 'utf8')) as Array<{ name: string; source: string; flags?: string; anchors: string[]; preceded?: string }>;+ return rows.map(r => ({ name: r.name, family: 'override', rx: new RegExp(r.source, r.flags ?? 'i'), anchors: r.anchors, ...(r.preceded ? { preceded: new RegExp(r.preceded, 'i') } : {}) }));+}++if (import.meta.main) {+ const root = process.env.GBRAIN_GUARD_ROOT;+ const problems = checkWriteGatePatterns(root ? fixturePatterns(root) : WRITE_GATE_PATTERNS);+ if (problems.length) {+ console.error(`write-gate regex safety: ${problems.length} violation(s)`);+ for (const p of problems) console.error(` - ${p}`);+ process.exit(1);+ }+ console.log(`write-gate regex safety: ${WRITE_GATE_PATTERNS.length} patterns bounded (max match <= ${MAX_MATCH_CHARS} chars).`);+}diff --git a/scripts/guards-manifest.tsv b/scripts/guards-manifest.tsvindex 4d58b29dcf..24ae32b4a2 100644--- a/scripts/guards-manifest.tsv+++ b/scripts/guards-manifest.tsv@@ -89,3 +89,4 @@ check-test-env-opt-ins.ts scanner yes D7 (GBRA-47): execution-gating process.envcheck-postgres-lane-coverage.ts scanner yes GBRA-47 D8 (TS AST): a test file outside test/e2e/ with a DATABASE_URL-gated PostgreSQL arm (testBackends(), gated process.env.DATABASE_URL) must be named by a DATABASE_URL workflow step, a test/e2e registerPostgresTests wrapper, a tests/heavy script or the backend matrix; reasoned ALLOWLIST, stale rows failcheck-weight-coverage.ts scanner yes C2 (GBRA-47): weight-map entries naming missing files fail; unweighted share per lane warns, failing only on the scheduled runcheck-recipe-pricing.ts scanner yes X1 (wave 9 lane A, D22): every model a recipe touchpoint lists resolves through isModelPriceable or is named in the recipe's unpriced_models; stale markers fail; GBRAIN_GUARD_ROOT seam reads <root>/recipes.json against the real price tables+check-write-gate-regex.ts scanner yes #5575 ENG-16: write-gate detector patterns (WRITE_GATE_PATTERNS) are bounded (no * + {n,}, bound <= 200, no nested repeats, no backrefs), longest match <= MAX_MATCH_CHARS, preceded contexts $-anchored and <= MAX_PRECEDING_CHARS, non-global with lowercase anchors; GBRAIN_GUARD_ROOT reads <root>/patterns.jsondiff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex c06ca0af21..f134a5fd93 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -76,6 +76,8 @@ CHECKS=("check:orphan-modules"# agent contract v1 (A2): generated docs/guides/error-codes.md matches the registry"check:error-codes"+ # #5575 ENG-16: write-gate detector patterns are bounded and window-safe+ "check:write-gate-regex"# agent contract v1 scanner (B9): shrink-only per-rule baselines"check:agent-contract"# No-op placeholder assertions (expect(true).toBe(true) and friends) indiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 2d4b3a8598..fa978c75d7 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -357,6 +357,8 @@ export const CODES = {withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },+ write_gate_rejected: { class: 'caller', summary: "The write gate refused external instruction-like content because the operator set `write_gate.external_mode` to `reject`.", why: "Text from an untrusted source that reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request) is refused instead of held under that setting, so nothing was written. The same content refuses on every retry.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], suggestion: 'Tell the user the content was refused; whether to accept it or switch `write_gate.external_mode` back to `quarantine` is their decision.' },+ write_held: { class: 'consent', summary: "The write gate held this content for the owner's review instead of saving it as memory.", why: "Content from an untrusted source read like an instruction to an agent, so it was quarantined in the write-gate holding table. It is not searchable or recalled until the owner releases it; retrying the same write only re-opens the same hold.", reasons: ['override', 'standing_instruction', 'exfiltration', 'credential', 'detector_error'], actor: 'user', exit: 3, suggestion: 'Do not retry. Tell the user what was held and give them the release command from the fix; releasing is their decision.' },write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },writer_admin_intent_required: { class: 'host_only', summary: "Topology changes require an action-specific --admin-intent and the --expected-state from a reviewed writer status." },writer_admin_locked: { class: 'host_only', summary: "Writer administration is locked; deactivation was not applied." },diff --git a/src/core/think/sanitize.ts b/src/core/think/sanitize.tsindex ae015a60ee..aac0fbe4ed 100644--- a/src/core/think/sanitize.ts+++ b/src/core/think/sanitize.ts@@ -56,6 +56,22 @@ export const INJECTION_PATTERNS: Array<{ name: string; rx: RegExp; replacement:{ name: 'eval-shell', rx: /\b(?:eval|exec|system|shell)\s*\(/gi, replacement: '[redacted](' },];+/**+ * #5575 write gate: non-global clones of the detection-grade subset+ * (instruction overrides and output exfiltration), so `.test()` keeps no+ * `lastIndex` state. Tag breakouts, the case-sensitive acronym, `verbatim` and+ * `eval-shell` are render safety or too broad for a detector and stay+ * rewrite-only. `src/core/write-gate-patterns.ts` bounds their quantifiers.+ */+const DETECTION_FAMILY: Readonly<Record<string, 'override' | 'exfiltration'>> = {+ 'ignore-prior': 'override', 'forget-everything': 'override', disregard: 'override', 'new-instructions': 'override',+ 'system-prompt': 'override', 'role-jailbreak': 'override', 'do-anything-now-phrase': 'override', 'dan-mode': 'override',+ 'print-system': 'exfiltration',+};+export const INJECTION_DETECTION_PATTERNS: ReadonlyArray<{ name: string; family: 'override' | 'exfiltration'; rx: RegExp }> = INJECTION_PATTERNS+ .filter(p => DETECTION_FAMILY[p.name])+ .map(p => ({ name: p.name, family: DETECTION_FAMILY[p.name], rx: new RegExp(p.rx.source, p.rx.flags.replace('g', '')) }));+/*** Sanitize a single take claim before embedding into a model prompt.* Returns the cleaned text + a list of patterns that matched (for telemetry).diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.tsindex 2957368103..4863617328 100644--- a/src/core/transcripts/render.ts+++ b/src/core/transcripts/render.ts@@ -89,9 +89,10 @@ export function defaultUserPatternsPath(): string {* Agent-directed imperative shapes. Detection only STAMPS A COUNT into the* page's transcript_import frontmatter (hash-covered, idempotent) so readers* and future triage can see the page carries instruction-shaped content —- * it never hides or rewrites the text.+ * it never hides or rewrites the text. The write gate+ * (`src/core/write-gate-patterns.ts`) reuses them as `override` patterns.*/-const IMPERATIVE_RES: readonly RegExp[] = [+export const IMPERATIVE_RES: readonly RegExp[] = [/\b(ignore|disregard|forget)\s+(all\s+|any\s+)?(previous|prior|above|earlier)\s+(instructions|context|rules)\b/i,/\byou\s+(must|should)\s+now\s+(act|behave|respond)\b/i,/\bnew\s+system\s+prompt\b/i,diff --git a/src/core/write-gate-patterns.ts b/src/core/write-gate-patterns.tsnew file mode 100644index 0000000000..661a553e07--- /dev/null+++ b/src/core/write-gate-patterns.ts@@ -0,0 +1,204 @@+/**+ * #5575 write gate: the deterministic instruction detector's pattern table.+ *+ * Pure data, no model call (P8 zero-LLM write contract). Four reason+ * families: `override` (instruction overrides, from `think/sanitize.ts`+ * INJECTION_PATTERNS and `transcripts/render.ts` IMPERATIVE_RES),+ * `standing_instruction` (rules addressed to an agent: "from now on ...",+ * "assistant, always ...", "when asked about X say Y"), `exfiltration`+ * (forwarding or leaking data to an address or URL as a standing rule, a+ * templated exfil URL, revealing the system prompt) and `credential` (asking+ * for keys, passwords and tokens to be shared).+ *+ * Patterns run against text `normalizeForGate` already prepared: NFKC,+ * zero-width and bidi controls removed, lowercased, whitespace collapsed to+ * single spaces with paragraph breaks kept as `\n`. Every quantifier is+ * bounded so a match spans at most `MAX_MATCH_CHARS` characters+ * (`scripts/check-write-gate-regex.ts` proves both in `bun run verify`), and+ * `anchors` is a cheap substring prefilter: a pattern only runs on a window+ * containing one of them.+ */+import { INJECTION_DETECTION_PATTERNS } from './think/sanitize.ts';+import { IMPERATIVE_RES } from './transcripts/render.ts';++export type WriteGateReasonFamily = 'override' | 'standing_instruction' | 'exfiltration' | 'credential';+export const WRITE_GATE_REASON_FAMILIES: readonly WriteGateReasonFamily[] = ['override', 'standing_instruction', 'exfiltration', 'credential'];++export interface WriteGatePattern {+ name: string;+ family: WriteGateReasonFamily;+ rx: RegExp;+ /**+ * Prefilter: the pattern runs only on a window containing one of these.+ * Each anchor is lowercase words (or `@`); a window "contains" it when it+ * has a whole word equal to the anchor's longest word, so every word of an+ * anchor must appear exactly (not as a prefix) in any text the pattern matches.+ */+ anchors: readonly string[];+ /** A second prefilter group: the window must also contain one of these. */+ requires?: readonly string[];+ /** A match directly preceded by a negation ("never", "not", "n't", "no") does not count. */+ negatable?: boolean;+ /**+ * Context before the match: the pattern counts only where this `$`-anchored+ * regex matches the `MAX_PRECEDING_CHARS` characters before it, and its+ * optional `neg` group (a negation word) did not take part. Lets a pattern+ * start scanning at its rare token (an address, a "from now on", a+ * credential noun) instead of a common verb.+ */+ preceded?: RegExp;+}++/** Longest text a single pattern can match; windows overlap by this much (plus the preceding context). */+export const MAX_MATCH_CHARS = 400;+/** Longest context a `preceded` regex may need before a match. */+export const MAX_PRECEDING_CHARS = 260;+/** Bound substituted for `+` and `*` in the cloned rewrite patterns. */+export const CLONE_QUANTIFIER_BOUND = 24;++/**+ * Rewrite unbounded `+` / `*` quantifiers to `{1,max}` / `{0,max}`. Escapes+ * and character classes are copied verbatim, so `\+` and `[+*]` keep their+ * meaning; a lazy `?` after the quantifier stays valid.+ */+export function boundQuantifiers(source: string, max = CLONE_QUANTIFIER_BOUND): string {+ let out = '';+ for (let i = 0; i < source.length; i++) {+ const ch = source[i]!;+ if (ch === '\\') { out += source.slice(i, i + 2); i++; continue; }+ if (ch === '[') {+ let j = i + 1;+ while (j < source.length && source[j] !== ']') j += source[j] === '\\' ? 2 : 1;+ out += source.slice(i, j + 1);+ i = j;+ continue;+ }+ out += ch === '+' ? `{1,${max}}` : ch === '*' ? `{0,${max}}` : ch;+ }+ return out;+}++const CLONE_REQUIRES: Readonly<Record<string, readonly string[]>> = {+ 'new-instructions': ['new', 'updated', 'revised'], 'do-anything-now-phrase': ['now', 'mode'], 'dan-mode': ['mode'],+ 'print-system': ['print', 'output', 'reveal', 'show'], 'role-jailbreak': ['you'],+};+const CLONE_ANCHORS: Readonly<Record<string, readonly string[]>> = {+ 'ignore-prior': ['ignore'], 'forget-everything': ['forget'], disregard: ['disregard'], 'new-instructions': ['instruction', 'instructions'],+ 'system-prompt': ['system'], 'role-jailbreak': ['now', 'actually', 'really'], 'do-anything-now-phrase': ['anything', 'developer'],+ 'dan-mode': ['dan'], 'print-system': ['system', 'instruction', 'instructions', 'hidden'],+};+const IMPERATIVE_META: ReadonlyArray<{ name: string; anchors: readonly string[]; requires?: readonly string[] }> = [+ { name: 'imperative-ignore-previous', anchors: ['ignore', 'disregard', 'forget'] },+ { name: 'imperative-act-now', anchors: ['now'], requires: ['must', 'should'] },+ { name: 'imperative-new-system-prompt', anchors: ['system'] },+];++const SENT = '[^.!?]';+const FUTURE = '(?:from now on|going forward|henceforth|from this point (?:on|forward)|in (?:all )?future (?:answers|responses|replies|conversations|sessions|chats))';+const AGENT = '(?:ai assistant|assistant|chatbot|ai agent|agent|llm|claude|chatgpt|gpt|gemini|copilot|grok|bot|ai)';+const SPEECH = '(?:say|tell|respond|reply|answer|recommend|mention|claim|state|describe|refer|suggest|output|report|deny|confirm|praise|promote|call|treat|use|ignore|include)';+const ACTION = '(?:forward|send|email|e-mail|cc|bcc|share|reveal|upload|post|transfer|wire|pay|delete|remove|run|execute|invoke|book|buy|approve|grant|disclose)';+const STRICT_SPEECH = '(?:say|tell|respond|reply|answer|recommend|mention|claim|state|deny|reveal|disclose|describe|suggest|output)';+const EXFIL_VERB = '(?:forward|send|email|e-mail|cc|bcc|copy|post|upload|transfer|wire|share|leak|exfiltrate|sync|mirror|report|submit)';+const STANDING = '(?:always|from now on|going forward|henceforth|whenever|every time|automatically|silently|secretly|quietly|without (?:telling|notifying|asking)|all future|any future|every future|in (?:the )?future)';+const ADDRESS = '(?:[a-z0-9._%+-]{1,64}@[a-z0-9-]{1,63}\\.[a-z]{2,24}|https?:\\/\\/|www\\.)';+const CREDENTIAL = '(?:api[ _-]?keys?|passwords?|passphrases?|credentials?|secret keys?|access tokens?|auth(?:entication)? tokens?|bearer tokens?|refresh tokens?|private keys?|ssh keys?|seed phrases?|recovery (?:codes?|phrases?)|2fa codes?|one-time (?:codes?|passwords?)|session (?:cookies?|tokens?)|\\.env files?)';++/**+ * Literal spaces in a pattern source become `\s{1,4}` (and ` ?` becomes+ * `\s{0,4}`), so a doubled space or a hard-wrapped line cannot split a+ * phrase; character classes are copied verbatim.+ */+export function spaced(source: string): string {+ let out = '';+ for (let i = 0; i < source.length; i++) {+ const ch = source[i]!;+ if (ch === '\\') { out += source.slice(i, i + 2); i++; continue; }+ if (ch === '[') {+ let j = i + 1;+ while (j < source.length && source[j] !== ']') j += source[j] === '\\' ? 2 : 1;+ out += source.slice(i, j + 1);+ i = j;+ continue;+ }+ if (ch !== ' ') { out += ch; continue; }+ if (source[i + 1] === '?') { out += '\\s{0,4}'; i++; } else out += '\\s{1,4}';+ }+ return out;+}++function own(name: string, family: WriteGateReasonFamily, source: string, anchors: readonly string[],+ extra: Pick<WriteGatePattern, 'requires' | 'negatable'> & { preceded?: string } = {}): WriteGatePattern {+ const { preceded, ...rest } = extra;+ return { name, family, rx: new RegExp(spaced(source), 'i'), anchors, ...rest, ...(preceded ? { preceded: new RegExp(`${spaced(preceded)}$`, 'i') } : {}) };+}++const AGENT_ANCHORS = ['assistant', 'chatbot', 'agent', 'llm', 'claude', 'chatgpt', 'gpt', 'gemini', 'copilot', 'grok', 'bot', 'ai'];+const STANDING_ANCHORS = ['always', 'from now on', 'going forward', 'henceforth', 'whenever', 'every time', 'automatically', 'silently', 'secretly', 'quietly', 'without', 'future'];+const ADDRESS_ANCHORS = ['@', 'http', 'https', 'www'];+const FUTURE_ANCHORS = ['from now on', 'going forward', 'henceforth', 'from this point', 'future answers', 'future responses', 'future replies', 'future conversations', 'future sessions', 'future chats'];+const CREDENTIAL_ANCHORS = ['key', 'keys', 'api', 'apikey', 'password', 'passwords', 'passphrase', 'passphrases', 'credential', 'credentials', 'token', 'tokens', 'seed', 'recovery', '2fa', 'one-time', 'cookie', 'cookies', '.env'];+const MODAL_ANCHORS = ['always', 'never', 'must', 'should', 'do not', "don't", 'from now on', 'going forward', 'henceforth'];++/** The detector's own patterns (written bounded; the clones are bounded by `boundQuantifiers`). */+const OWN_PATTERNS: readonly WriteGatePattern[] = [+ own('ignore-your-instructions', 'override',+ `\\b(?:ignore|disregard|forget|bypass)\\b (?:all |any )?(?:of )?(?:your|the|these|those)? ?(?:previous|prior|above|earlier|preceding|original|initial|system|safety) ${SENT}{0,20}\\b(?:instructions?|prompts?|rules|guidelines|guardrails|directives|policies|context|messages?)\\b`,+ ['ignore', 'disregard', 'forget', 'bypass']),+ own('ignore-your-rules', 'override',+ '\\b(?:ignore|disregard|bypass)\\b (?:all )?your (?:instructions?|rules|guidelines|programming|system prompt|guardrails)\\b',+ ['ignore', 'disregard', 'bypass']),+ own('conceal-from-user', 'override',+ "\\b(?:do not|don't|never)\\b (?:tell|inform|notify|alert|warn|mention (?:this |it )?to|reveal (?:this |it )?to) (?:the )?(?:user|owner|human|operator)\\b",+ ['user', 'owner', 'human', 'operator']),+ own('redacted-marker', 'override', '\\[redacted(?:-attr)?\\]', ['redacted']),+ own('from-now-on-lead', 'standing_instruction',+ `\\b${FUTURE}\\b${SENT}{0,100}\\b(?:${SPEECH}|${ACTION})\\b`,+ FUTURE_ANCHORS),+ own('from-now-on-trail', 'standing_instruction',+ `\\b${FUTURE}\\b`,+ FUTURE_ANCHORS, { preceded: `\\b(?:${SPEECH}|${ACTION})\\b${SENT}{0,100}` }),+ own('agent-vocative-note', 'standing_instruction',+ `\\b(?:(?:note|message|reminder|instructions?|attention|attn|memo) (?:to|for) (?:the |any |all |my |our |your )?(?:ai |llm )?|(?:dear|hey|hello|attention|attn) (?:the )?)${AGENT}\\b${SENT}{0,80}\\b(?:always|never|must|should|do not|don't|from now on|going forward)\\b${SENT}{0,40}\\b(?:${SPEECH}|${ACTION})\\b`,+ ['note', 'message', 'reminder', 'instruction', 'instructions', 'attention', 'attn', 'memo', 'dear', 'hey', 'hello'], { requires: AGENT_ANCHORS }),+ own('agent-standing-rule', 'standing_instruction',+ `\\b${AGENT}\\b(?: ?[,:]${SENT}{0,80}\\b(?:always|never|must|should|do not|don't|from now on|going forward)\\b${SENT}{0,40}\\b(?:${SPEECH}|${ACTION})|${SENT}{0,40}\\b(?:always|never|from now on|going forward|henceforth)\\b${SENT}{0,40}\\b(?:${STRICT_SPEECH}|${ACTION}))\\b`,+ AGENT_ANCHORS, { requires: MODAL_ANCHORS }),+ own('you-always-say', 'standing_instruction',+ `\\byou\\b${SENT}{0,30}\\b(?:always|never)\\b${SENT}{0,40}\\b${STRICT_SPEECH}\\b`,+ ['you'], { requires: ['always', 'never'] }),+ own('imperative-always-say', 'standing_instruction',+ `\\b(?:always|never) ${STRICT_SPEECH}\\b`,+ ['always', 'never'], { preceded: '(?:[.!?:;\\n] ?|- )(?:please )?' }),+ own('when-asked-say', 'standing_instruction',+ `\\b(?:asks?|asked|asking|inquires?|wants to know)\\b${SENT}{0,80}\\b(?:say|tell|respond|reply|answer|claim|state|insist|deny|recommend)\\b`,+ ['ask', 'asks', 'asked', 'asking', 'inquire', 'inquires', 'wants to know'], { preceded: `\\b(?:when|whenever|if)\\b${SENT}{0,60}` }),+ own('exfil-standing-lead', 'exfiltration', `\\bto ?${ADDRESS}`, STANDING_ANCHORS,+ { requires: ADDRESS_ANCHORS, preceded: `\\b${STANDING}\\b${SENT}{0,80}\\b${EXFIL_VERB}\\b${SENT}{0,80}` }),+ own('exfil-standing-trail', 'exfiltration', `\\bto ?${ADDRESS}${SENT}{0,80}\\b${STANDING}\\b`, STANDING_ANCHORS,+ { requires: ADDRESS_ANCHORS, preceded: `\\b${EXFIL_VERB}\\b${SENT}{0,80}` }),+ own('exfil-agent-addressed', 'exfiltration', `\\bto ?${ADDRESS}`, AGENT_ANCHORS,+ { requires: ADDRESS_ANCHORS, preceded: `\\b${AGENT}\\b${SENT}{0,60}\\b${EXFIL_VERB}\\b${SENT}{0,80}` }),+ own('exfil-private-data', 'exfiltration', `\\bto ?${ADDRESS}`,+ ['memory', 'memories', 'history', 'system prompt', 'private notes', 'user data', ...CREDENTIAL_ANCHORS],+ { requires: ADDRESS_ANCHORS, preceded: `\\b${EXFIL_VERB}\\b${SENT}{0,40}\\b(?:memor(?:y|ies)|conversation history|chat history|system prompt|private notes|user data|${CREDENTIAL})\\b${SENT}{0,60}` }),+ own('exfil-templated-url', 'exfiltration',+ 'https?:\\/\\/[^\\s)"\'<>]{1,200}[?&][a-z0-9_]{1,30}= ?(?:\\{|<|\\[|%7b|\\$\\{)',+ ['http', 'https']),+ own('credential-request', 'credential',+ `\\b${CREDENTIAL}\\b`,+ CREDENTIAL_ANCHORS, { preceded: "(?:(?<neg>\\bnever|\\bnot|n't|\\bno) )?\\b(?:send|email|e-mail|share|reveal|paste|give|forward|upload|disclose|leak|dump|exfiltrate|tell)\\b (?:me |us |them )?(?:all |any |a copy of )?(?:of )?(?:your|the|their|our|my|these|those|all|any) (?:[a-z0-9-]{1,20} )?" }),+];++/** The full detector table: bounded clones first, then the detector's own patterns. */+export const WRITE_GATE_PATTERNS: readonly WriteGatePattern[] = [+ ...INJECTION_DETECTION_PATTERNS.map(p => ({+ name: p.name, family: p.family, rx: new RegExp(boundQuantifiers(p.rx.source), p.rx.flags), anchors: CLONE_ANCHORS[p.name] ?? [],+ ...(CLONE_REQUIRES[p.name] ? { requires: CLONE_REQUIRES[p.name] } : {}),+ })),+ ...IMPERATIVE_RES.map((rx, i) => ({+ name: IMPERATIVE_META[i]!.name, family: 'override' as const, rx: new RegExp(boundQuantifiers(rx.source), rx.flags.replace('g', '')), anchors: IMPERATIVE_META[i]!.anchors,+ ...(IMPERATIVE_META[i]!.requires ? { requires: IMPERATIVE_META[i]!.requires } : {}),+ })),+ ...OWN_PATTERNS,+];diff --git a/src/core/write-gate.ts b/src/core/write-gate.tsnew file mode 100644index 0000000000..52b0a8fb6e--- /dev/null+++ b/src/core/write-gate.ts@@ -0,0 +1,426 @@+/**+ * #5575 blocking write gate: decides whether attacker-controllable text may+ * become durable memory. Separate from `guardrails.ts` (observe-only, never+ * imported here).+ *+ * Deterministic and model-free (P8 zero-LLM write contract): the detector is+ * the bounded pattern table in `write-gate-patterns.ts`, run over windows of+ * normalized text. Precision comes from routing by trust tier, not from the+ * detector: the gate never runs on `user_confirmed`, `operator_curated` or+ * `tool_observed` writes. Defaults (`write_gate.*` config, DX-13):+ * - `external_untrusted`: instruction-like -> `quarantine` (or `flag` /+ * `reject` / `off` by `write_gate.external_mode`); a detector error ->+ * `quarantine` (fail-closed).+ * - `agent_written` and `unknown`: instruction-like -> `flag` (or `off` by+ * `write_gate.agent_mode`); a detector error -> `allow` (fail-open).+ *+ * The assessment covers every attacker-controllable persisted text (ENG-9):+ * page title, body, frontmatter strings and origin fields; fact text,+ * context, value and provenance; take claim, source and evidence; timeline+ * summary, detail and source. Callers compute the tier (it is never guessed+ * here) and persist receipts and holds through `write-gate-store.ts`.+ */+import { createHash } from 'node:crypto';+import type { Action } from './agent-output.ts';+import { opError, type OperationError } from './ops/contract.ts';+import { MAX_MATCH_CHARS, MAX_PRECEDING_CHARS, WRITE_GATE_PATTERNS, WRITE_GATE_REASON_FAMILIES, type WriteGatePattern, type WriteGateReasonFamily } from './write-gate-patterns.ts';++export type { WriteGateReasonFamily } from './write-gate-patterns.ts';++/** Bumped whenever the pattern table changes meaning; stored on every receipt and hold. */+export const WRITE_GATE_DETECTOR_VERSION = 1;++/** The trust-tier vocabulary (#5575 A1), highest first. Must match `trust/tier.ts`. */+export const WRITE_GATE_TIERS = ['user_confirmed', 'operator_curated', 'tool_observed', 'agent_written', 'unknown', 'external_untrusted'] as const;+export type WriteGateTier = typeof WRITE_GATE_TIERS[number];++export type WriteGateVerdict = 'allow' | 'flag' | 'quarantine' | 'reject';+export type WriteGateExternalMode = 'quarantine' | 'flag' | 'reject' | 'off';+export type WriteGateAgentMode = 'flag' | 'off';++export interface WriteGateConfig {+ externalMode: WriteGateExternalMode;+ agentMode: WriteGateAgentMode;+}++export const DEFAULT_WRITE_GATE_CONFIG: Readonly<WriteGateConfig> = { externalMode: 'quarantine', agentMode: 'flag' };++/** Structured origin of a write (`write_origin`); every string here is scanned as data. */+export interface WriteGateOrigin {+ channel?: string | null;+ connector?: string | null;+ source_uri?: string | null;+ source_kind?: string | null;+ ingested_via?: string | null;+}++/** What a caller passes to gate one write. Absent on a write path means the gate does not run there. */+export interface WriteGateInput {+ tier: WriteGateTier;+ origin?: WriteGateOrigin | null;+ /** `persistence_requests.id` (or another request id) recorded on receipts and holds. */+ requestId?: string | null;+}++export type WriteGateField =+ | 'title' | 'body' | 'frontmatter' | 'origin'+ | 'fact' | 'context' | 'value' | 'provenance' | 'source_text'+ | 'claim' | 'source' | 'evidence'+ | 'summary' | 'detail';++export interface WriteGateHit { family: WriteGateReasonFamily; pattern: string; field: WriteGateField }++export interface WriteGateAssessment {+ verdict: WriteGateVerdict;+ tier: WriteGateTier;+ /** False when the tier or mode skips the gate (the verdict is then `allow`). */+ ran: boolean;+ families: WriteGateReasonFamily[];+ hits: WriteGateHit[];+ /** The detector threw; the verdict is the tier's fail-closed / fail-open default. */+ detectorError: boolean;+ detectorVersion: number;+ /** sha256 over the scanned fields; receipts dedupe on it. */+ contentHash: string;+}++/** DX-1: the one gate outcome shape `remember`, `put_page` and `capture` return as `gate`. */+export interface WriteGateOutcome {+ verdict: WriteGateVerdict;+ /** `h<id>` for a hold, `wgr<id>` for a receipt, null when nothing was recorded. */+ receipt_ref: string | null;+ /** Reason families only, never matched patterns (remote callers see this). */+ reason_families: WriteGateReasonFamily[];+ /** False when the content is held, rejected, or stored but not active until the owner confirms. */+ active: boolean;+ next: Action | null;+}++const VALID_EXTERNAL: ReadonlySet<string> = new Set(['quarantine', 'flag', 'reject', 'off']);+const VALID_AGENT: ReadonlySet<string> = new Set(['flag', 'off']);++/**+ * Parse `write_gate.external_mode` / `write_gate.agent_mode`. An unreadable+ * or invalid external mode falls back to `quarantine` (fail-closed), an+ * invalid agent mode to `flag`.+ */+export function parseWriteGateConfig(raw: { external_mode?: unknown; agent_mode?: unknown } = {}): WriteGateConfig {+ const ext = typeof raw.external_mode === 'string' ? raw.external_mode.trim().toLowerCase() : '';+ const agent = typeof raw.agent_mode === 'string' ? raw.agent_mode.trim().toLowerCase() : '';+ return {+ externalMode: VALID_EXTERNAL.has(ext) ? ext as WriteGateExternalMode : DEFAULT_WRITE_GATE_CONFIG.externalMode,+ agentMode: VALID_AGENT.has(agent) ? agent as WriteGateAgentMode : DEFAULT_WRITE_GATE_CONFIG.agentMode,+ };+}++export function isWriteGateTier(value: unknown): value is WriteGateTier {+ return typeof value === 'string' && (WRITE_GATE_TIERS as readonly string[]).includes(value);+}++/** True when a write at `tier` is assessed under `cfg` (owner tiers and `off` modes are not). */+export function writeGateApplies(tier: WriteGateTier, cfg: WriteGateConfig): boolean {+ if (tier === 'external_untrusted') return cfg.externalMode !== 'off';+ if (tier === 'agent_written' || tier === 'unknown') return cfg.agentMode !== 'off';+ return false;+}++// Zero-width, bidi-control, soft-hyphen and BOM characters an attacker can use to split a phrase,+// plus Unicode tag characters (U+E0020..E007E, as surrogate pairs), which mirror ASCII invisibly and+// are decoded so hidden text is scanned.+const HIDDEN_RE = /[\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u202a-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0]|\udb40[\udc20-\udc7e]/g;+const revealHidden = (ch: string) => ch.length === 2 ? String.fromCharCode(ch.charCodeAt(1) - 0xdc00) : '';++// Characters NFKC folds into ASCII letters: letterlike and enclosed forms, CJK compatibility,+// ligatures, fullwidth forms and mathematical alphanumerics. (Unicode spaces need no folding:+// the patterns' \s already matches them.)+const COMPAT_RE = /[\u2100-\u214f\u2460-\u24ff\u3300-\u33ff\ufb00-\ufb4f\uff00-\uffef]|\ud835/;++const NEEDS_NORMALIZING_RE = new RegExp(`${HIDDEN_RE.source}|${COMPAT_RE.source}`);++/**+ * The text the patterns see: Unicode tag characters decoded to the ASCII they+ * mirror, invisible characters removed, and NFKC applied when compatibility+ * forms are present (fullwidth letters fold to ASCII). Plain ASCII passes+ * through untouched. Case, spacing and line breaks are left alone: every+ * pattern is case-insensitive, matches whitespace runs (line breaks+ * included) and lets a sentence gap cross a hard-wrapped line.+ */+export function normalizeForGate(text: string): string {+ if (!/[^\x00-\x7f]/.test(text) || !NEEDS_NORMALIZING_RE.test(text)) return text;+ const revealed = text.replace(HIDDEN_RE, revealHidden);+ return COMPAT_RE.test(revealed) ? revealed.normalize('NFKC') : revealed;+}++const FENCE_OPEN = '<!--- gbrain:';++/**+ * Drop gbrain-managed facts/takes fence table rows from page text: those rows+ * get the row-level gate when they are projected. Non-row lines inside a+ * fence (free text an attacker could add) stay in the page scan. Linear: one+ * forward pass with `indexOf`, no backtracking regex.+ */+export function stripManagedFenceRows(body: string): string {+ let out = '';+ let pos = 0;+ for (;;) {+ const open = body.indexOf(FENCE_OPEN, pos);+ if (open < 0) break;+ const nameEnd = body.indexOf(':begin -->', open + FENCE_OPEN.length);+ const name = nameEnd < 0 ? '' : body.slice(open + FENCE_OPEN.length, nameEnd);+ if (!/^[a-z_-]{1,40}$/.test(name)) { out += body.slice(pos, open + FENCE_OPEN.length); pos = open + FENCE_OPEN.length; continue; }+ const closeMarker = `${FENCE_OPEN}${name}:end -->`;+ const close = body.indexOf(closeMarker, nameEnd);+ if (close < 0) break;+ out += body.slice(pos, open);+ out += body.slice(nameEnd + ':begin -->'.length, close).split('\n').filter(line => !line.trimStart().startsWith('|')).join('\n');+ pos = close + closeMarker.length;+ }+ return out + body.slice(pos);+}++/** Scan windows: wide enough to amortize the prefilter, overlapping by the longest possible match. */+export const WRITE_GATE_WINDOW_CHARS = 16384;++const NEGATED_BEFORE_RE = /\b(?:never|not|n't|no)\s{1,4}$/i;+/** Global clones for walking every match of a context-checked pattern (the table's own regexes stay stateless). */+const ITERATORS: ReadonlyMap<string, RegExp> = new Map(WRITE_GATE_PATTERNS.filter(p => p.negatable || p.preceded).map(p => [p.name, new RegExp(p.rx.source, `${p.rx.flags}g`)]));++/**+ * True when `p.rx` matches somewhere its context rules hold: not directly+ * negated, and `preceded` matching the text before it without its `neg` group. Walks every match in+ * the window (bounded by its length), so padding with rejected matches cannot+ * hide a real one.+ */+function matchesInContext(p: WriteGatePattern, window: string, atTextStart: boolean): boolean {+ const rx = ITERATORS.get(p.name)!;+ rx.lastIndex = 0;+ for (let m = rx.exec(window); m; m = rx.exec(window)) {+ const at = m.index;+ if (m[0].length === 0) rx.lastIndex++;+ if (p.negatable && NEGATED_BEFORE_RE.test(window.slice(Math.max(0, at - 10), at))) continue;+ if (!p.preceded) return true;+ // The text start counts as a line start for `preceded` (a pattern may require one).+ const before = at > MAX_PRECEDING_CHARS ? window.slice(at - MAX_PRECEDING_CHARS, at) : `${atTextStart ? '\n' : ''}${window.slice(0, at)}`;+ const context = p.preceded.exec(before);+ if (context && !context.groups?.neg) return true;+ }+ return false;+}++type Detector = (fields: ReadonlyArray<readonly [WriteGateField, string]>) => WriteGateHit[];++/** FNV-1a over a lowercased ASCII word; collisions only widen the prefilter (the regex still decides). */+function wordHash(word: string): number {+ let h = 0x811c9dc5;+ for (let i = 0; i < word.length; i++) h = Math.imul(h ^ word.charCodeAt(i), 0x01000193);+ return h >>> 0;+}++/** An anchor's prefilter key: `@`, or the hash of its longest word. */+function anchorKey(anchor: string): number | '@' {+ if (anchor === '@') return '@';+ const words = anchor.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);+ return wordHash(words.reduce((long, w) => w.length > long.length ? w : long, ''));+}++const ANCHOR_KEYS: ReadonlyMap<string, number | '@'> = new Map(+ [...new Set(WRITE_GATE_PATTERNS.flatMap(p => [...p.anchors, ...(p.requires ?? [])]))].map(a => [a, anchorKey(a)]));+const ANCHOR_HASHES: ReadonlySet<number> = new Set([...ANCHOR_KEYS.values()].filter((k): k is number => k !== '@'));++// Word characters for the anchor scan, case-folded: ASCII digits and letters map to their lowercase code, everything else to 0.+const WORD_CHAR = new Uint8Array(128);+for (let c = 48; c <= 57; c++) WORD_CHAR[c] = c;+for (let c = 97; c <= 122; c++) { WORD_CHAR[c] = c; WORD_CHAR[c - 32] = c; }++/**+ * One allocation-free pass over a window: the hashes of every anchor word it+ * contains as a whole word (ASCII letters and digits, case-folded), plus+ * whether it contains `@`.+ */+function anchorsIn(window: string): { words: Set<number>; at: boolean } {+ const words = new Set<number>();+ let at = false;+ let h = 0x811c9dc5;+ let inWord = false;+ for (let i = 0; i <= window.length; i++) {+ const code = i < window.length ? window.charCodeAt(i) : 32;+ const c = code < 128 ? WORD_CHAR[code]! : 0;+ if (c) {+ h = Math.imul(h ^ c, 0x01000193);+ inWord = true;+ continue;+ }+ if (inWord) {+ const key = h >>> 0;+ if (ANCHOR_HASHES.has(key)) words.add(key);+ h = 0x811c9dc5;+ inWord = false;+ }+ if (code === 64) at = true;+ }+ return { words, at };+}++function hasAnchor(anchors: readonly string[], present: { words: Set<number>; at: boolean }): boolean {+ return anchors.some(a => { const k = ANCHOR_KEYS.get(a)!; return k === '@' ? present.at : present.words.has(k); });+}++/** Pure detector: every (family, pattern, field) the pattern table finds in the fields. */+export function detectInstructionLike(fields: ReadonlyArray<readonly [WriteGateField, string]>): WriteGateHit[] {+ const hits: WriteGateHit[] = [];+ for (const [field, raw] of fields) {+ if (!raw) continue;+ const text = normalizeForGate(raw);+ const found = new Set<string>();+ const step = WRITE_GATE_WINDOW_CHARS - MAX_MATCH_CHARS - MAX_PRECEDING_CHARS;+ for (let start = 0; start < text.length; start += step) {+ const window = text.slice(start, start + WRITE_GATE_WINDOW_CHARS);+ const present = anchorsIn(window);+ for (const p of WRITE_GATE_PATTERNS) {+ if (found.has(p.name) || !hasAnchor(p.anchors, present) || (p.requires && !hasAnchor(p.requires, present))) continue;+ if (!(p.negatable || p.preceded ? matchesInContext(p, window, start === 0) : p.rx.test(window))) continue;+ found.add(p.name);+ hits.push({ family: p.family, pattern: p.name, field });+ }+ if (start + WRITE_GATE_WINDOW_CHARS >= text.length) break;+ }+ }+ return hits;+}++let detector: Detector = detectInstructionLike;++/** Test seam: replace the detector (e.g. with one that throws, to prove fail-closed). `null` restores it. */+export function __setWriteGateDetectorForTests(fn: Detector | null): void {+ detector = fn ?? detectInstructionLike;+}++function hashFields(fields: ReadonlyArray<readonly [WriteGateField, string]>): string {+ const h = createHash('sha256');+ for (const [field, value] of fields) h.update(`${field}\u0000${value}\u0001`);+ return h.digest('hex');+}++/** Assess raw fields for a write at `input.tier` under `cfg`. Never throws. */+export function assessWriteGate(fields: ReadonlyArray<readonly [WriteGateField, string | null | undefined]>, input: WriteGateInput, cfg: WriteGateConfig): WriteGateAssessment {+ const present = fields.filter((f): f is readonly [WriteGateField, string] => typeof f[1] === 'string' && f[1].length > 0);+ const scanned = [...present, ...originFields(input.origin)];+ const base = { tier: input.tier, detectorVersion: WRITE_GATE_DETECTOR_VERSION, contentHash: hashFields(scanned) };+ if (!writeGateApplies(input.tier, cfg)) return { ...base, verdict: 'allow', ran: false, families: [], hits: [], detectorError: false };+ const external = input.tier === 'external_untrusted';+ let hits: WriteGateHit[];+ try {+ hits = detector(scanned);+ } catch {+ return { ...base, verdict: external ? 'quarantine' : 'allow', ran: true, families: [], hits: [], detectorError: true };+ }+ const families = WRITE_GATE_REASON_FAMILIES.filter(f => hits.some(h => h.family === f));+ const verdict: WriteGateVerdict = !hits.length ? 'allow' : external ? cfg.externalMode as Exclude<WriteGateExternalMode, 'off'> : 'flag';+ return { ...base, verdict, ran: true, families, hits, detectorError: false };+}++/** Origin strings, scanned as the `origin` field (labels and origins are rendered to models as data). */+export function originFields(origin: WriteGateOrigin | null | undefined): Array<readonly [WriteGateField, string]> {+ if (!origin) return [];+ return [origin.channel, origin.connector, origin.source_uri, origin.source_kind, origin.ingested_via]+ .filter((v): v is string => typeof v === 'string' && v.length > 0)+ .map(v => ['origin', v] as const);+}++// Gate-owned and bookkeeping keys the gate itself or gbrain writes; never attacker text worth scanning.+const UNSCANNED_FRONTMATTER_KEYS: ReadonlySet<string> = new Set(['quarantine', 'content_flag', 'embed_skip', 'atoms_scan_hash', 'quarantine_override', 'title']);++/** Frontmatter string leaves (bounded depth and count) joined one per line. */+export function frontmatterText(frontmatter: Record<string, unknown> | null | undefined): string {+ if (!frontmatter) return '';+ const out: string[] = [];+ const walk = (value: unknown, depth: number): void => {+ if (out.length >= 512 || depth > 4) return;+ if (typeof value === 'string') { out.push(value); return; }+ if (Array.isArray(value)) { for (const v of value) walk(v, depth + 1); return; }+ if (value && typeof value === 'object') for (const v of Object.values(value)) walk(v, depth + 1);+ };+ for (const [key, value] of Object.entries(frontmatter)) if (!UNSCANNED_FRONTMATTER_KEYS.has(key)) walk(value, 0);+ return out.join('\n');+}++export function assessPageForGate(+ page: { title?: string | null; compiled_truth: string; timeline?: string | null; frontmatter?: Record<string, unknown> | null },+ input: WriteGateInput, cfg: WriteGateConfig,+): WriteGateAssessment {+ return assessWriteGate([+ ['title', page.title],+ ['body', stripManagedFenceRows(`${page.compiled_truth}\n\n${page.timeline ?? ''}`)],+ ['frontmatter', frontmatterText(page.frontmatter)],+ ], input, cfg);+}++/**+ * A fact row. Facts extraction rewrites strict injection hits to+ * `[redacted]` before the row exists, so pass the pre-sanitized source turn+ * as `source_text` when the caller has it; `[redacted]` itself also counts.+ */+export interface GateFactRow { fact: string; context?: string | null; value?: string | null; source?: string | null; source_text?: string | null }++export function assessFactForGate(row: GateFactRow, input: WriteGateInput, cfg: WriteGateConfig): WriteGateAssessment {+ return assessWriteGate([+ ['fact', row.fact], ['context', row.context], ['value', row.value], ['provenance', row.source], ['source_text', row.source_text],+ ], input, cfg);+}++export interface GateTakeRow { claim: string; source?: string | null; evidence?: string | null; source_text?: string | null }++export function assessTakeForGate(row: GateTakeRow, input: WriteGateInput, cfg: WriteGateConfig): WriteGateAssessment {+ return assessWriteGate([['claim', row.claim], ['source', row.source], ['evidence', row.evidence], ['source_text', row.source_text]], input, cfg);+}++export interface GateTimelineRow { summary: string; detail?: string | null; source?: string | null }++export function assessTimelineForGate(row: GateTimelineRow, input: WriteGateInput, cfg: WriteGateConfig): WriteGateAssessment {+ return assessWriteGate([['summary', row.summary], ['detail', row.detail], ['source', row.source]], input, cfg);+}++/** Human-safe one-line detail for markers and notices: families, detector version and tier, never matched text. */+export function writeGateDetail(a: WriteGateAssessment): string {+ const why = a.detectorError ? 'detector error (fail-closed)' : `instruction-like content (${a.families.join(', ')})`;+ return `write gate: ${why}; tier ${a.tier}, detector v${a.detectorVersion}`;+}++/** DX-1 outcome for a verdict. `ref` is the hold (`h<id>`) or receipt (`wgr<id>`) the caller recorded. */+export function writeGateOutcome(a: WriteGateAssessment, ref: string | null): WriteGateOutcome {+ const base = { verdict: a.verdict, receipt_ref: ref, reason_families: [...a.families] };+ if (a.verdict === 'allow') return { ...base, active: true, next: null };+ if (a.verdict === 'reject') {+ return { ...base, active: false, next: { argv: ['gbrain', 'config', 'get', 'write_gate.external_mode'], consent: [], actor: 'user', requires_exclusive: false,+ why: 'The operator set write_gate.external_mode to reject, so external instruction-like content is refused on every retry; changing that setting is the user\'s decision.' } };+ }+ const target = ref ?? '<ref>';+ if (a.verdict === 'quarantine') {+ return { ...base, active: false, next: { argv: ['gbrain', 'trust', 'release', target], consent: [], actor: 'user', requires_exclusive: false,+ user_message: `Memory from an untrusted source looked like an instruction, so it was held for your review (${target}). Run the command if you want to keep it.`,+ why: 'Releasing held content raises its trust; only the owner can do that, after reviewing it.' } };+ }+ return { ...base, active: false, next: { argv: ['gbrain', 'trust', 'confirm', target], consent: [], actor: 'user', requires_exclusive: false,+ user_message: `An agent saved something that reads like a standing instruction (${target}). It is stored but not acted on until you confirm it.`,+ why: 'Confirming makes agent-written instruction-like memory active; only the owner can confirm.' } };+}++function primaryReason(a: WriteGateAssessment): string {+ return a.detectorError ? 'detector_error' : a.families[0] ?? 'override';+}++/** Verb error for a held (quarantined) fact or take: never `inserted`, fix tells the user to review the hold. */+export function writeHeldError(a: WriteGateAssessment, holdRef: string): OperationError {+ const outcome = writeGateOutcome({ ...a, verdict: 'quarantine' }, holdRef);+ return opError('write_held', `Held for owner review as ${holdRef}: ${writeGateDetail(a)}.`,+ 'Do not retry: the same content re-opens the same hold. Tell the user it was held and relay the release command; releasing it is their decision.',+ { reason: primaryReason(a), detail: `hold ${holdRef}; reason families: ${a.families.join(', ') || 'none'}`, ...(outcome.next ? { fix: outcome.next } : {}) });+}++/** Refusal under `write_gate.external_mode=reject`. */+export function writeGateRejectedError(a: WriteGateAssessment): OperationError {+ const outcome = writeGateOutcome({ ...a, verdict: 'reject' }, null);+ return opError('write_gate_rejected', `Refused by the write gate: ${writeGateDetail(a)}.`,+ 'The operator set write_gate.external_mode to reject, so this content refuses on every retry. Tell the user; changing the setting is their decision.',+ { reason: primaryReason(a), detail: `reason families: ${a.families.join(', ') || 'none'}`, ...(outcome.next ? { fix: outcome.next } : {}) });+}diff --git a/test/fixtures/guards/check-write-gate-regex.ts/bad-long/patterns.json b/test/fixtures/guards/check-write-gate-regex.ts/bad-long/patterns.jsonnew file mode 100644index 0000000000..46b078759d--- /dev/null+++ b/test/fixtures/guards/check-write-gate-regex.ts/bad-long/patterns.json@@ -0,0 +1,9 @@+[+ {+ "name": "long",+ "source": "\\bsend[^.]{0,200}[^.]{0,200}to\\b",+ "anchors": [+ "send"+ ]+ }+]diff --git a/test/fixtures/guards/check-write-gate-regex.ts/bad-nested/patterns.json b/test/fixtures/guards/check-write-gate-regex.ts/bad-nested/patterns.jsonnew file mode 100644index 0000000000..7b7ab3d67a--- /dev/null+++ b/test/fixtures/guards/check-write-gate-regex.ts/bad-nested/patterns.json@@ -0,0 +1,9 @@+[+ {+ "name": "nested",+ "source": "\\b(?:send[a-z ]{1,10}){1,20}to",+ "anchors": [+ "send"+ ]+ }+]diff --git a/test/fixtures/guards/check-write-gate-regex.ts/bad-preceded/patterns.json b/test/fixtures/guards/check-write-gate-regex.ts/bad-preceded/patterns.jsonnew file mode 100644index 0000000000..8006130e9c--- /dev/null+++ b/test/fixtures/guards/check-write-gate-regex.ts/bad-preceded/patterns.json@@ -0,0 +1,10 @@+[+ {+ "name": "ctx",+ "source": "\\bto\\b",+ "anchors": [+ "to"+ ],+ "preceded": "\\bsend[^.]{0,80}"+ }+]diff --git a/test/fixtures/guards/check-write-gate-regex.ts/bad/patterns.json b/test/fixtures/guards/check-write-gate-regex.ts/bad/patterns.jsonnew file mode 100644index 0000000000..f7c9dacaa5--- /dev/null+++ b/test/fixtures/guards/check-write-gate-regex.ts/bad/patterns.json@@ -0,0 +1,9 @@+[+ {+ "name": "unbounded",+ "source": "\\bignore\\s+previous\\s+instructions",+ "anchors": [+ "ignore"+ ]+ }+]diff --git a/test/fixtures/guards/check-write-gate-regex.ts/good/patterns.json b/test/fixtures/guards/check-write-gate-regex.ts/good/patterns.jsonnew file mode 100644index 0000000000..6ab404da4d--- /dev/null+++ b/test/fixtures/guards/check-write-gate-regex.ts/good/patterns.json@@ -0,0 +1,17 @@+[+ {+ "name": "bounded",+ "source": "\\bignore\\s{1,4}previous\\s{1,4}instructions",+ "anchors": [+ "ignore"+ ]+ },+ {+ "name": "ctx",+ "source": "\\bto\\b",+ "anchors": [+ "to"+ ],+ "preceded": "\\bsend[^.]{0,80}$"+ }+]