Skip to content

guardrails: model-backed hook runner for tool I/O inspection (per-tool matchers, catch-alls, configurable model + prompt) #27

Closed

Description

@JAORMX

Context

Untrusted external content enters the agent context through tool results: web search/fetch results (#26), and -- most broadly -- MCP tool results (GitHub issues, Slack messages, fetched docs), which today arrive completely unfenced. Textual defenses like the <<<UNTRUSTED fence are useful hygiene but are not a security boundary: models demonstrably ignore delimiter-based instructions at a material rate. The complementary defense is inspection: examine tool inputs/outputs with a quarantined model and flag, sanitize, or block them.

The loop-side seam for this already exists and needs no changes:

  • governance.HookEvent fires PreToolUse/PostToolUse for every tool (internal/governance/hookevent.go).
  • HookOutcome.Block vetoes the action; HookOutcome.Mutated rewrites the tool-call args (PreToolUse) or the tool result {"content","is_error"} (PostToolUse), with the loop guaranteeing the model's recorded history and the client stream agree on the effective result.

What's missing is a hook runner that uses a model. The only port.HookRunner adapter today is hookexec (external process, exit 0/2).

Goal

A new modelhook adapter implementing port.HookRunner that, for configured (phase, tool-matcher) pairs, drives a one-shot quarantined child model call over the tool input/output and maps its verdict onto the existing HookOutcome (block / mutate-sanitize / pass + message). Pure adapter + composition wiring; no core loop changes.

Proposed shape

Configuration (sketch -- names TBD):

guardrails:
  model: "claude-haiku-4-5"        # checker model; cheap/fast tier by default
  prompt: |                         # optional override of the shipped default prompt
    ...
  rules:
    - match: "WebSearch"            # exact tool name
      phases: [PreToolUse, PostToolUse]
      mode: enforce                 # block/sanitize on bad verdict
    - match: "WebFetch"
      phases: [PostToolUse]
      mode: advisory                # emit event/diagnostic, pass result through
    - match: "mcp__*"               # wildcard: all MCP tools
      phases: [PreToolUse, PostToolUse]
      mode: advisory
    - match: "*"                    # catch-all (off by default; available for paranoid configs)
      phases: [PostToolUse]
      mode: advisory
      prompt: "..."                 # optional per-rule prompt override
  • Matchers: exact tool names, wildcards (mcp__*, mcp__github__*), and a * catch-all. First-match or most-specific-wins -- TBD.
  • Model selection: a single checker model configured once, re-derived through the engine-factory discipline (same as buildSubagentEngineFactory) -- never clone-and-swap. Default to a cheap/fast tier; overridable per deployment.
  • Default prompt: ship a sensible built-in inspection prompt (prompt-injection indicators, secret/exfil patterns in outbound args, instruction-like content in results). Overridable globally and per-rule.
  • Verdict: structured output {safe: bool, reason: string, sanitized_content?: string} validated through session.ValidateJSON (the existing structured-output choke point). safe:false maps to Block + Message in enforce mode; sanitized_content maps to Mutated.
  • Quarantine: the checker child has no tools, one turn, no hooks (no recursion), and its prompt must itself fence the inspected content. A fooled checker degrades to "no checker" -- it cannot be escalated into actions. This is the dual-LLM quarantine pattern.
  • Both directions: PostToolUse inspects inbound results (injection); PreToolUse inspects outbound args (exfiltration -- secrets steered into a search query, an MCP message body, an issue comment).

Default policy

External-origin tools on, local tools off:

  • ON: WebSearch, WebFetch, mcp__* (advisory mode first)
  • OFF: Read/Grep/Glob (cost-prohibitive; workspace-trust is the right gate for repo content), Edit/Write/memory tools (model-authored content), Bash (matcher-available, not default)

Advisory-first lets false-positive rates be measured before any rule is trusted with vetoes.

Design questions

  • Failure posture: checker errored/timed out -> fail-open with WARN (advisory) seems right; should enforce mode be configurable fail-closed?
  • Cost controls: size thresholds (skip tiny results?), sampling, per-run checker budget? The checker adds a model call per matched tool use.
  • Chaining with exec hooks: ordering and composition when both hookexec and modelhook match the same event (a HookRunner multiplexer?).
  • Observability: advisory findings should surface somewhere visible (event vs diagnostics line -- mind the "loop emits exactly TWO lines" invariant; an event taxonomy entry seems right, like EvNoProgress).
  • Does a blocked PostToolUse result render to the model as an error tool result with the checker's reason? (It must be model-visible, not just a log line.)
  • Offline testing: checker driven via mockllm; deterministic verdict fixtures.

Security constraints

  • The checker is advisory/enforcing on content, never a substitute for the permission system: deny-dominant permissions remain the boundary for side effects.
  • The checker prompt must treat inspected content as data (fenced), and the adapter must neutralize fence-forgery in the inspected payload.
  • No recursion: the checker's own run fires no hooks and mounts no tools.
  • Verdict prompts and rules are operator config (trusted); tool content never influences which rule applies.

Acceptance criteria

  • modelhook adapter implementing port.HookRunner, wired in composition only; domain/port/agent untouched.
  • Matcher config with exact names, wildcards, catch-all; per-rule mode (advisory/enforce), phases, optional prompt override; global model + default prompt config.
  • Verdict path through session.ValidateJSON; sanitize via Mutated; block via Block+Message, model-visible.
  • Advisory findings observable (event or equivalent), enforce blocks surfaced to the model and client.
  • Offline tests only (mockllm); fixtures for safe/unsafe/sanitize/malformed-verdict/checker-failure paths.
  • Docs: a docs/design/GUARDRAILS.md covering the threat model (injection inbound, exfil outbound), the quarantine argument, and the cost model.

References

  • Hook seam: internal/governance/hookevent.go (HookOutcome.Mutated semantics for PreToolUse/PostToolUse), internal/agent/dispatch.go (firing points), internal/adapter/hookexec/ (the exec runner this sits beside).
  • Structured-output verdict machinery: session.ValidateJSON (the Subagent output_schema choke point).
  • Engine-factory discipline for the checker model: buildSubagentEngineFactory / newChildEngineForProvider in internal/app.
  • tooling: add a WebSearch tool for source discovery before WebFetch #26 (WebSearch) -- first first-party tool to enroll; the <<<UNTRUSTED fence work there is the complementary (weaker, cheaper) layer.
  • Prior art: Simon Willison's dual-LLM quarantine pattern; Microsoft Spotlighting (delimiting/datamarking); Claude Code's constrained-Haiku WebFetch digestion (the "tier 3" follow-up this enables).

Activity

  1. added
    enhancement
    on Jun 9, 2026
  2. added a commit that references this issue on Jun 13, 2026
  3. JAORMX commented on Jun 13, 2026

    @JAORMX
    ContributorAuthor

    Shipped in PR #57 (merge 5bc0780, commit a032412). A modelhook port.HookRunner drives a quarantined checker model over tool I/O (PostToolUse for injection in inbound web/MCP results, PreToolUse for secret/exfil in outbound args) → block / sanitize / advisory. Dual-LLM quarantine (tool-less, one-turn, no-recursion); default advisory set for web/MCP when a model is configured; operator-tier-only config; --guardrails-model/--guardrails=off. See docs/design/GUARDRAILS.md. Review caught + fixed sanitize-laundering bounds, the PostToolUse-Block-is-inert handling (enforce rewrites via Mutated-to-error), and a cost-skip that weakened outbound exfil detection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions