Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(guardrails): implement tool-lane predicates + rule engine (phase 1)
Andy Pavia64533e113dac
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 365674759..1b2cdbea5 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.232",+ "version": "0.1.233","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.232",+ "version": "0.1.233","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 92d6ef984..ec5770fb2 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.232",+ "version": "0.1.233","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/guardrails/tool/__tests__/predicates.test.ts b/mcp-host/src/core/guardrails/tool/__tests__/predicates.test.tsnew file mode 100644index 000000000..534041fc5--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/__tests__/predicates.test.ts@@ -0,0 +1,112 @@+/**+ * Typed predicate tests (spec §6.1). Covers the four predicate types + the+ * documented bypass concerns (command shell-wrapper, path prefix trick, url+ * canonicalization, credentials-in-URL).+ */+import { describe, expect, it } from 'vitest'+import { type ArgumentPredicate, evaluatePredicate, resolvePointer } from '../predicates'++const P = (+ p: Partial<ArgumentPredicate> & Pick<ArgumentPredicate, 'type' | 'pointer' | 'op'>+): ArgumentPredicate => ({ value: undefined, ...p })++describe('resolvePointer (RFC-6901, constrained)', () => {+ it('resolves nested pointers and returns undefined for missing', () => {+ const args = { a: { b: [10, 20] }, 'x/y': 1 }+ expect(resolvePointer(args, '/a/b/1')).toBe(20)+ expect(resolvePointer(args, '/a/missing')).toBeUndefined()+ expect(resolvePointer(args, '/x~1y')).toBe(1) // ~1 → "/"+ expect(resolvePointer(args, '')).toBe(args)+ })+ it('throws on a malformed pointer', () => {+ expect(() => resolvePointer({}, 'no-slash')).toThrow()+ })+})++describe('path predicate', () => {+ it('outside: /etc/passwd is outside /workspace; a workspace path is not', () => {+ const outside = P({ type: 'path', pointer: '/path', op: 'outside', value: '/workspace' })+ expect(evaluatePredicate({ path: '/etc/passwd' }, outside)).toBe(true)+ expect(evaluatePredicate({ path: '/workspace/notes.txt' }, outside)).toBe(false)+ })+ it('under is boundary-safe — no prefix trick', () => {+ const under = P({ type: 'path', pointer: '/path', op: 'under', value: '/workspace' })+ expect(evaluatePredicate({ path: '/workspace/a' }, under)).toBe(true)+ expect(evaluatePredicate({ path: '/workspace-evil/a' }, under)).toBe(false)+ })+ it('resolves .. before containment', () => {+ const under = P({ type: 'path', pointer: '/path', op: 'under', value: '/workspace' })+ expect(evaluatePredicate({ path: '/workspace/../etc/passwd' }, under)).toBe(false)+ })+})++describe('url predicate', () => {+ const scheme = P({ type: 'url', pointer: '/url', op: 'scheme_in', value: ['https'] })+ const host = P({ type: 'url', pointer: '/url', op: 'host_in', value: ['api.github.com'] })+ const port = P({ type: 'url', pointer: '/url', op: 'port_in', value: [443] })++ it('matches scheme/host/port with canonicalization', () => {+ // Uppercase host + trailing dot canonicalize to the allowlisted host.+ expect(evaluatePredicate({ url: 'https://API.GitHub.com./x' }, host)).toBe(true)+ expect(evaluatePredicate({ url: 'https://api.github.com/x' }, scheme)).toBe(true)+ expect(evaluatePredicate({ url: 'https://api.github.com/x' }, port)).toBe(true) // default 443+ })+ it('rejects credentials-in-URL', () => {+ expect(evaluatePredicate({ url: 'https://user:[email protected]/x' }, host)).toBe(false)+ })+ it('non-matching host', () => {+ expect(evaluatePredicate({ url: 'https://evil.example/x' }, host)).toBe(false)+ })+})++describe('command predicate (shell-wrapper caveat)', () => {+ const exeRm = P({ type: 'command', pointer: '/command', op: 'executable_is', value: 'rm' })+ const rf = P({ type: 'command', pointer: '/command', op: 'argv_prefix', value: ['-rf'] })++ it('matches structured rm -rf; basename match for /bin/rm', () => {+ expect(evaluatePredicate({ command: ['rm', '-rf', '/tmp/x'] }, exeRm)).toBe(true)+ expect(evaluatePredicate({ command: ['/bin/rm', '-rf', '/'] }, exeRm)).toBe(true)+ expect(evaluatePredicate({ command: ['rm', '-rf', '/tmp/x'] }, rf)).toBe(true)+ expect(evaluatePredicate({ command: ['rm', '-v', 'file'] }, rf)).toBe(false)+ })+ it('a shell string never matches executable_is (the documented bypass)', () => {+ // `sh -c "rm -rf /"` — argv[0] is sh, so an rm rule does not fire (spec §6.1/§12.3).+ expect(evaluatePredicate({ command: ['sh', '-c', 'rm -rf /'] }, exeRm)).toBe(false)+ })+ it('accepts the {executable, args} shape too', () => {+ expect(evaluatePredicate({ command: { executable: 'rm', args: ['-rf', '/'] } }, exeRm)).toBe(+ true+ )+ })+})++describe('json predicate', () => {+ it('one_of / equals with canonical key order; exists; contains', () => {+ const oneOf = P({+ type: 'json',+ pointer: '/repository',+ op: 'one_of',+ value: ['octo/prod', 'octo/infra'],+ })+ expect(evaluatePredicate({ repository: 'octo/prod' }, oneOf)).toBe(true)+ expect(evaluatePredicate({ repository: 'octo/app' }, oneOf)).toBe(false)++ const eq = P({ type: 'json', pointer: '/o', op: 'equals', value: { a: 1, b: 2 } })+ expect(evaluatePredicate({ o: { b: 2, a: 1 } }, eq)).toBe(true) // key order canonicalized++ const exists = P({ type: 'json', pointer: '/maybe', op: 'exists' })+ expect(evaluatePredicate({ maybe: null }, exists)).toBe(true)+ expect(evaluatePredicate({}, exists)).toBe(false)++ const contains = P({ type: 'json', pointer: '/tags', op: 'contains', value: 'prod' })+ expect(evaluatePredicate({ tags: ['dev', 'prod'] }, contains)).toBe(true)+ })+})++describe('malformed predicate fails closed (throws)', () => {+ it('unknown op throws', () => {+ expect(() =>+ evaluatePredicate({ path: '/x' }, P({ type: 'path', pointer: '/path', op: 'nope' }))+ ).toThrow()+ })+})diff --git a/mcp-host/src/core/guardrails/tool/__tests__/rules.test.ts b/mcp-host/src/core/guardrails/tool/__tests__/rules.test.tsnew file mode 100644index 000000000..6c3be324c--- /dev/null+++ b/mcp-host/src/core/guardrails/tool/__tests__/rules.test.ts@@ -0,0 +1,111 @@+/**+ * Permission-rule engine tests (spec §6.1): compilation/admission validation and+ * matching (provenance + predicates, all-match AND, wildcard names).+ */+import { describe, expect, it } from 'vitest'+import type { GuardrailRule } from '../../config'+import type { ToolIdentity } from '../provenance'+import { compileRules, evaluateRules } from '../rules'++const nativeTool = (name: string): ToolIdentity => ({ provenance: 'native', name })+const mcpTool = (server: string, name: string): ToolIdentity => ({+ provenance: 'mcp',+ server,+ name,+})++const denyWritesOutsideWorkspace: GuardrailRule = {+ id: 'deny-writes-outside-workspace',+ action: 'deny',+ reasonCode: 'path_out_of_bounds',+ match: {+ tool: { provenance: 'native', name: 'file_write' },+ arguments: [{ type: 'path', pointer: '/path', op: 'outside', value: '/workspace' }],+ },+}++describe('compileRules (admission)', () => {+ it('accepts a valid set and reports hasRules', () => {+ const c = compileRules([denyWritesOutsideWorkspace])+ expect(c.hasRules).toBe(true)+ expect(c.rules).toHaveLength(1)+ })+ it('absent/empty → hasRules false (no-config compatibility)', () => {+ expect(compileRules(undefined).hasRules).toBe(false)+ expect(compileRules([]).hasRules).toBe(false)+ })+ it('rejects duplicate ids, bad action, missing provenance, over-limit', () => {+ expect(() => compileRules([denyWritesOutsideWorkspace, denyWritesOutsideWorkspace])).toThrow(+ /duplicate/+ )+ expect(() =>+ compileRules([{ ...denyWritesOutsideWorkspace, id: 'x', action: 'nope' as never }])+ ).toThrow(/invalid rule action/)+ expect(() => compileRules([denyWritesOutsideWorkspace], 0)).toThrow(/too many/)+ })+})++describe('evaluateRules (matching)', () => {+ const compiled = compileRules([denyWritesOutsideWorkspace])++ it('emits a host_rule deny when tool + predicate match', () => {+ const out = evaluateRules(compiled, nativeTool('file_write'), { path: '/etc/passwd' })+ expect(out).toHaveLength(1)+ expect(out[0]).toMatchObject({+ source: 'host_rule',+ decision: 'deny',+ sourceId: 'deny-writes-outside-workspace',+ })+ })++ it('no contribution when the predicate does not match (in-workspace write)', () => {+ expect(+ evaluateRules(compiled, nativeTool('file_write'), { path: '/workspace/n.txt' })+ ).toHaveLength(0)+ })++ it('no contribution when the tool name differs', () => {+ expect(evaluateRules(compiled, nativeTool('file_read'), { path: '/etc/passwd' })).toHaveLength(+ 0+ )+ })++ it('provenance must match (native rule does not fire on an mcp tool)', () => {+ expect(+ evaluateRules(compiled, mcpTool('github', 'file_write'), { path: '/etc/passwd' })+ ).toHaveLength(0)+ })++ it('all predicates must match (AND)', () => {+ const rule: GuardrailRule = {+ id: 'deny-rm-rf',+ action: 'deny',+ match: {+ tool: { provenance: 'native', name: 'run_command' },+ arguments: [+ { type: 'command', pointer: '/command', op: 'executable_is', value: 'rm' },+ { type: 'command', pointer: '/command', op: 'argv_prefix', value: ['-rf'] },+ ],+ },+ }+ const c = compileRules([rule])+ expect(+ evaluateRules(c, nativeTool('run_command'), { command: ['rm', '-rf', '/tmp/x'] })+ ).toHaveLength(1)+ expect(+ evaluateRules(c, nativeTool('run_command'), { command: ['rm', '-v', 'f'] })+ ).toHaveLength(0)+ })++ it('matches mcp server + wildcard name', () => {+ const rule: GuardrailRule = {+ id: 'ask-gh-writes',+ action: 'ask',+ match: { tool: { provenance: 'mcp', server: 'github', name: 'create_*' } },+ }+ const c = compileRules([rule])+ expect(evaluateRules(c, mcpTool('github', 'create_issue'), {})).toHaveLength(1)+ expect(evaluateRules(c, mcpTool('github', 'get_issue'), {})).toHaveLength(0)+ expect(evaluateRules(c, mcpTool('gitlab', 'create_issue'), {})).toHaveLength(0)+ })+})diff --git a/mcp-host/src/core/guardrails/tool/predicates.ts b/mcp-host/src/core/guardrails/tool/predicates.tsindex 97485fb7c..784edde7c 100644--- a/mcp-host/src/core/guardrails/tool/predicates.ts+++ b/mcp-host/src/core/guardrails/tool/predicates.ts@@ -4,11 +4,14 @@* Each predicate names a constrained RFC-6901 JSON Pointer into the tool* arguments and a typed operator. Predicates are DEFENSE-IN-DEPTH, not a sandbox* (spec §6.1/§12.3): a `command` predicate sees only `argv[0]`, and `path`/`url`- * are not TOCTOU-safe — authoritative containment is the hard-validator layer.+ * are lexical (not TOCTOU-safe) — authoritative containment is the hard-validator+ * / sandbox layer, which a guardrail `allow` never bypasses (spec §6.6).*- * TODO(phase1): implement each `evaluate` with the admission-time constraints- * (constrained pointers, bounded wildcards `*`/`?` only, canonicalization).+ * Malformed predicates/pointers throw here; the boundary treats a throw as+ * fail-closed. Admission-time validation (compileRules, spec §5) should reject+ * them earlier so this is a backstop, not the primary gate.*/+import { posix as pathPosix } from 'path'export type PredicateType = 'path' | 'url' | 'command' | 'json'@@ -21,25 +24,251 @@ export interface ArgumentPredicate {value?: unknown}-/** Resolve a constrained JSON Pointer against the tool arguments. TODO(phase1). */-export function resolvePointer(_args: Record<string, unknown>, _pointer: string): unknown {- // TODO(phase1): constrained RFC-6901 resolution; reject invalid/over-depth pointers at admission.- throw new Error('resolvePointer not yet implemented (Phase 1 scaffold)')+/** Bounds (spec §6.1: size/depth-bounded, excess depth/count rejected). */+const MAX_POINTER_DEPTH = 16+const MAX_JSON_COMPARE_DEPTH = 32++// ---------------------------------------------------------------------------+// RFC-6901 JSON Pointer (constrained)+// ---------------------------------------------------------------------------++/**+ * Resolve a constrained RFC-6901 JSON Pointer against the tool arguments.+ * Returns `undefined` when the path does not exist; throws on a malformed or+ * over-depth pointer (fail-closed).+ */+export function resolvePointer(args: Record<string, unknown>, pointer: string): unknown {+ if (pointer === '') return args+ if (!pointer.startsWith('/'))+ throw new Error(`invalid JSON Pointer (must start with "/"): ${pointer}`)+ const tokens = pointer+ .slice(1)+ .split('/')+ // RFC-6901 unescape: ~1 → "/", then ~0 → "~" (order matters).+ .map(t => t.replace(/~1/g, '/').replace(/~0/g, '~'))+ if (tokens.length > MAX_POINTER_DEPTH) throw new Error(`JSON Pointer too deep: ${pointer}`)++ let cur: unknown = args+ for (const tok of tokens) {+ if (cur === null || typeof cur !== 'object') return undefined+ if (Array.isArray(cur)) {+ const idx = Number(tok)+ if (!Number.isInteger(idx) || idx < 0 || idx >= cur.length) return undefined+ cur = cur[idx]+ } else {+ if (!Object.prototype.hasOwnProperty.call(cur, tok)) return undefined+ cur = (cur as Record<string, unknown>)[tok]+ }+ }+ return cur+}++// ---------------------------------------------------------------------------+// path — equals | under | outside (lexical, boundary-safe; prefixes forbidden)+// ---------------------------------------------------------------------------++function normalizePath(p: string): string {+ // Resolve "." / ".." and collapse slashes lexically; strip a trailing slash+ // (except root). Symlink/TOCTOU safety is the sandbox's job (§6.6/§12.3).+ let n = pathPosix.normalize(p)+ if (n.length > 1 && n.endsWith('/')) n = n.slice(0, -1)+ return n+}++/** Boundary-safe containment: `child` is `base` or strictly within it (no prefix trick). */+function isUnder(child: string, base: string): boolean {+ const c = normalizePath(child)+ const b = normalizePath(base)+ if (c === b) return true+ return c.startsWith(b === '/' ? '/' : b + '/')+}++function evalPath(value: unknown, op: string, target: unknown): boolean {+ if (typeof value !== 'string') return false // arg is not a path string ⇒ no match+ if (typeof target !== 'string') throw new Error(`path predicate value must be a string`)+ switch (op) {+ case 'equals':+ return normalizePath(value) === normalizePath(target)+ case 'under':+ return isUnder(value, target)+ case 'outside':+ return !isUnder(value, target)+ default:+ throw new Error(`unknown path op: ${op}`)+ }+}++// ---------------------------------------------------------------------------+// url — scheme_in | host_in | port_in | path_under (parsed + canonicalized)+// ---------------------------------------------------------------------------++const DEFAULT_PORTS: Record<string, number> = {+ 'http:': 80,+ 'https:': 443,+ 'ws:': 80,+ 'wss:': 443,+ 'ftp:': 21,+}++function canonicalHost(u: URL): string {+ // WHATWG URL already lowercases + punycodes the host; strip a trailing dot.+ const h = u.hostname+ return h.endsWith('.') ? h.slice(0, -1) : h+}++function effectivePort(u: URL): number | undefined {+ if (u.port) return Number(u.port)+ return DEFAULT_PORTS[u.protocol]}+function evalUrl(value: unknown, op: string, target: unknown): boolean {+ if (typeof value !== 'string') return false+ let u: URL+ try {+ u = new URL(value)+ } catch {+ return false // unparseable ⇒ no match+ }+ // Credentials-in-URL are rejected outright (spec §6.1).+ if (u.username || u.password) return false++ switch (op) {+ case 'scheme_in': {+ if (!Array.isArray(target)) throw new Error('url scheme_in value must be an array')+ const scheme = u.protocol.replace(/:$/, '')+ return target.some(s => String(s).toLowerCase() === scheme)+ }+ case 'host_in': {+ if (!Array.isArray(target)) throw new Error('url host_in value must be an array')+ const host = canonicalHost(u)+ return target.some(h => String(h).toLowerCase().replace(/\.$/, '') === host)+ }+ case 'port_in': {+ if (!Array.isArray(target)) throw new Error('url port_in value must be an array')+ const port = effectivePort(u)+ return port !== undefined && target.some(p => Number(p) === port)+ }+ case 'path_under': {+ if (typeof target !== 'string') throw new Error('url path_under value must be a string')+ return isUnder(u.pathname, target)+ }+ default:+ throw new Error(`unknown url op: ${op}`)+ }+}++// ---------------------------------------------------------------------------+// command — executable_is | argv_prefix (structured executable + argv)+// ---------------------------------------------------------------------------++interface StructuredCommand {+ executable: string+ args: string[]+}++/** Accept either `[exe, ...args]` or `{ executable, args }`; never a shell string. */+function asStructuredCommand(v: unknown): StructuredCommand | null {+ if (Array.isArray(v) && v.every(x => typeof x === 'string') && v.length > 0) {+ return { executable: v[0] as string, args: (v as string[]).slice(1) }+ }+ if (v && typeof v === 'object') {+ const o = v as Record<string, unknown>+ if (+ typeof o.executable === 'string' &&+ Array.isArray(o.args) &&+ o.args.every(x => typeof x === 'string')+ ) {+ return { executable: o.executable, args: o.args as string[] }+ }+ }+ return null+}++function evalCommand(value: unknown, op: string, target: unknown): boolean {+ const cmd = asStructuredCommand(value)+ if (!cmd) return false // not a structured command ⇒ no match (a shell string never matches)+ switch (op) {+ case 'executable_is': {+ if (typeof target !== 'string')+ throw new Error('command executable_is value must be a string')+ // Match the exact executable or its basename (so `rm` matches `/bin/rm`).+ return cmd.executable === target || pathPosix.basename(cmd.executable) === target+ }+ case 'argv_prefix': {+ if (!Array.isArray(target) || !target.every(x => typeof x === 'string')) {+ throw new Error('command argv_prefix value must be a string[]')+ }+ const prefix = target as string[]+ return prefix.every((tok, i) => cmd.args[i] === tok)+ }+ default:+ throw new Error(`unknown command op: ${op}`)+ }+}++// ---------------------------------------------------------------------------+// json — exists | equals | one_of | contains (bounded, canonical key order)+// ---------------------------------------------------------------------------++/** Stable stringify with sorted object keys, depth-bounded (spec §6.1). */+function canonicalize(v: unknown, depth = 0): string {+ if (depth > MAX_JSON_COMPARE_DEPTH) throw new Error('json value too deep')+ if (v === null || typeof v !== 'object') return JSON.stringify(v) ?? 'null'+ if (Array.isArray(v)) return `[${v.map(x => canonicalize(x, depth + 1)).join(',')}]`+ const o = v as Record<string, unknown>+ const keys = Object.keys(o).sort()+ return `{${keys.map(k => `${JSON.stringify(k)}:${canonicalize(o[k], depth + 1)}`).join(',')}}`+}++function jsonEquals(a: unknown, b: unknown): boolean {+ return canonicalize(a) === canonicalize(b)+}++function evalJson(value: unknown, op: string, target: unknown): boolean {+ switch (op) {+ case 'exists':+ return value !== undefined+ case 'equals':+ return value !== undefined && jsonEquals(value, target)+ case 'one_of': {+ if (!Array.isArray(target)) throw new Error('json one_of value must be an array')+ return value !== undefined && target.some(t => jsonEquals(value, t))+ }+ case 'contains': {+ if (typeof value === 'string') return typeof target === 'string' && value.includes(target)+ if (Array.isArray(value)) return value.some(el => jsonEquals(el, target))+ return false+ }+ default:+ throw new Error(`unknown json op: ${op}`)+ }+}++// ---------------------------------------------------------------------------+// Dispatch+// ---------------------------------------------------------------------------+/**- * Evaluate one predicate against the tool arguments.- *- * - path — equals | under | outside; normalized, symlink-aware, boundary-safe; prefixes forbidden.- * - url — scheme_in | host_in | port_in | path_under; parsed + canonicalized (lowercase host,- * IDN→punycode, trailing-dot stripped); credentials-in-URL rejected (spec §12.4 / F12).- * - command — executable_is | argv_prefix; structured executable + argv, not a parsed shell string.- * - json — exists | equals | one_of | contains; size/depth-bounded; key order canonicalized.+ * Evaluate one predicate against the tool arguments. Returns whether it matches.+ * Throws on a malformed predicate/pointer (the boundary treats a throw as+ * fail-closed).*/export function evaluatePredicate(- _args: Record<string, unknown>,- _predicate: ArgumentPredicate+ args: Record<string, unknown>,+ predicate: ArgumentPredicate): boolean {- // TODO(phase1): dispatch on `predicate.type`/`op`; see the per-type notes above.- throw new Error('evaluatePredicate not yet implemented (Phase 1 scaffold)')+ const target = predicate.value+ const resolved = resolvePointer(args, predicate.pointer)+ switch (predicate.type) {+ case 'path':+ return evalPath(resolved, predicate.op, target)+ case 'url':+ return evalUrl(resolved, predicate.op, target)+ case 'command':+ return evalCommand(resolved, predicate.op, target)+ case 'json':+ return evalJson(resolved, predicate.op, target)+ default:+ throw new Error(`unknown predicate type: ${(predicate as ArgumentPredicate).type}`)+ }}diff --git a/mcp-host/src/core/guardrails/tool/rules.ts b/mcp-host/src/core/guardrails/tool/rules.tsindex 39f88a270..3ba2b3d64 100644--- a/mcp-host/src/core/guardrails/tool/rules.ts+++ b/mcp-host/src/core/guardrails/tool/rules.ts@@ -8,14 +8,15 @@** NOTE (spec §6.1): an `allow` is an affirmative grant over the WHOLE call — a* rule that pins only some arguments still permits arbitrary values in the rest.- *- * TODO(phase1): implement matching (provenance + predicates) + admission checks.*/import type { GuardrailRule } from '../config'import type { Contributor } from '../types'-import { evaluatePredicate } from './predicates'+import { type ArgumentPredicate, evaluatePredicate } from './predicates'import type { ToolIdentity } from './provenance'+const DEFAULT_MAX_RULES = 100+const MAX_WILDCARD_LEN = 256+/** A rule set compiled + validated at admission (spec §5 limits, §6.1 predicates). */export interface CompiledRules {readonly rules: readonly GuardrailRule[]@@ -23,27 +24,98 @@ export interface CompiledRules {}/**- * Compile + validate the raw rules (bounded count/depth, valid pointers, bounded- * wildcards). Malformed input fails closed at admission (spec §3).- *- * TODO(phase1): validation.+ * Compile + validate the raw rules. Malformed input fails closed at admission+ * (spec §3): this throws, and the caller must reject the config rather than run+ * a partially-valid rule set (spec §5: a malformed policy never replaces the+ * last valid one).*/-export function compileRules(rules: readonly GuardrailRule[] | undefined): CompiledRules {- return { rules: rules ?? [], hasRules: (rules?.length ?? 0) > 0 }+export function compileRules(+ rules: readonly GuardrailRule[] | undefined,+ maxRules = DEFAULT_MAX_RULES+): CompiledRules {+ const list = rules ?? []+ if (list.length > maxRules)+ throw new Error(`too many guardrail rules: ${list.length} > ${maxRules}`)+ const ids = new Set<string>()+ for (const r of list) {+ if (!r.id) throw new Error('guardrail rule missing id')+ if (ids.has(r.id)) throw new Error(`duplicate guardrail rule id: ${r.id}`)+ ids.add(r.id)+ if (r.action !== 'allow' && r.action !== 'ask' && r.action !== 'deny') {+ throw new Error(`invalid rule action for ${r.id}: ${String(r.action)}`)+ }+ if (!r.match?.tool?.provenance) throw new Error(`rule ${r.id} missing match.tool.provenance`)+ if (r.match.tool.provenance !== 'native' && r.match.tool.provenance !== 'mcp') {+ throw new Error(`rule ${r.id} invalid provenance: ${r.match.tool.provenance}`)+ }+ for (const a of r.match.arguments ?? []) validateArgumentShape(r.id, a)+ }+ return { rules: list, hasRules: list.length > 0 }+}++function validateArgumentShape(+ ruleId: string,+ a: NonNullable<GuardrailRule['match']['arguments']>[number]+): void {+ if (!a || typeof a !== 'object')+ throw new Error(`rule ${ruleId} has a malformed argument predicate`)+ if (!['path', 'url', 'command', 'json'].includes(a.type)) {+ throw new Error(`rule ${ruleId} invalid predicate type: ${a.type}`)+ }+ if (typeof a.pointer !== 'string' || (a.pointer !== '' && !a.pointer.startsWith('/'))) {+ throw new Error(`rule ${ruleId} invalid JSON Pointer: ${String(a.pointer)}`)+ }+ if (typeof a.op !== 'string' || !a.op) throw new Error(`rule ${ruleId} missing predicate op`)+}++/** Anchored wildcard match: only `*` (any run) and `?` (one char) — no regex (spec §6.1). */+function matchWildcard(pattern: string, value: string): boolean {+ if (pattern.length > MAX_WILDCARD_LEN) return false+ if (!pattern.includes('*') && !pattern.includes('?')) return pattern === value+ const re = new RegExp(+ '^' ++ pattern+ .replace(/[.+^${}()|[\]\\]/g, '\\$&') // escape regex metachars (keep * and ?)+ .replace(/\*/g, '.*')+ .replace(/\?/g, '.') ++ '$'+ )+ return re.test(value)+}++/** Does a rule's tool matcher apply to this resolved identity? */+function toolMatches(rule: GuardrailRule, identity: ToolIdentity): boolean {+ const m = rule.match.tool+ if (m.provenance !== identity.provenance) return false+ if (m.server !== undefined && !matchWildcard(m.server, identity.server ?? '')) return false+ if (m.name !== undefined && !matchWildcard(m.name, identity.name)) return false+ return true}/*** Evaluate the compiled rules against a resolved call, returning one `pre`- * contributor per matching rule.- *- * TODO(phase1): match provenance (identity) + all argument predicates; emit- * `host_rule` contributors with the rule's `action`/`reasonCode`.+ * `host_rule` contributor per matching rule. All predicates on a rule must match+ * (AND). A predicate that throws (malformed) propagates → the boundary+ * fail-closes.*/export function evaluateRules(- _compiled: CompiledRules,- _identity: ToolIdentity,- _args: Record<string, unknown>+ compiled: CompiledRules,+ identity: ToolIdentity,+ args: Record<string, unknown>): Array<Contributor<Record<string, unknown>, string>> {- void evaluatePredicate- throw new Error('evaluateRules not yet implemented (Phase 1 scaffold)')+ const out: Array<Contributor<Record<string, unknown>, string>> = []+ for (const rule of compiled.rules) {+ if (!toolMatches(rule, identity)) continue+ const predicates = (rule.match.arguments ?? []) as ArgumentPredicate[]+ const allMatch = predicates.every(p => evaluatePredicate(args, p))+ if (!allMatch) continue+ out.push({+ phase: 'pre',+ source: 'host_rule',+ sourceId: rule.id,+ decision: rule.action,+ reasonCode: rule.reasonCode ?? `rule:${rule.id}`,+ })+ }+ return out}