Design: local action control

Tripwire targets an individual developer or small team using an MCP-capable agent on a local project. It gives the owner a portable policy for file actions and a review point for protected changes. Its boundary is the Tripwire file tools, not all tools available to an agent.

A version 1 owner profile combines a task, capability policy and fusion settings. Policy v2 defines readable roots/files, writable roots and automatic-write roots constrained to the writable set, along with byte limits. The gateway evaluates deterministic permissions, then combines the frozen local TF-IDF block probability with optional Liquid d1.1 risk. The maximum can elevate allow to approval; missing required advice also elevates to approval. Blocks remain blocks. The browser workbench evaluates scenarios and exports profiles without executing actions.

An eligible automatic action reaches the scoped runner. A review action becomes an inbox proposal. An owner authenticates to the loopback console and approves or rejects; approval is short-lived, single-use and bound to the reviewed request and profile. A retry executes through the scoped runner and produces local audit metadata. The profile is owner-controlled outside the workspace and reloads on change; stale tickets are invalidated. Patch edits use source hashes and bounded unique replacements under gateway serialization.

Implemented locally: profiles, automatic roots, model fusion, inbox, policy editing, activity, bounded patch and audit. The v0.6 implementation and real workflow have passed release checks; see EVIDENCE.md for measured results. Next work is real-task validation, shared profiles and team identity, and proxy adapters only after the local job proves valuable. See roadmap, security, and ADR-0014.


Historical design and milestone record (through v0.5)

The following preserves the original research design, invariants and milestone history. The current execution architecture is described above and in ADR-0014; original ambitions below are not all delivered capabilities.

Tripwire — Design

Status: living document. Last revised 2026-11-10 (OpenRouter backend added; M1–M3 done, M4 partly done; see §9 and docs/HANDOFF.md).

1. Problem statement

LLM agents act through tool calls: shell commands, file reads and writes, HTTP requests, database queries, emails and payments. Once a call runs, its effects can be irreversible: a deleted table, a leaked key, money sent. The agent's own judgement is not a safety boundary. It can be prompt-injected through any untrusted text it reads (web pages, emails, file contents, tool output), and it can make costly mistakes without being attacked at all.

Tripwire is a pre-execution guard. It receives a proposed tool call plus a bounded window of recent context and returns one of three actions before the call runs:

actionmeaning
allowrun the call
needs_approvalpause; a human must approve before the call runs
blockrefuse the call and return a structured refusal to the agent

Requirements:

2. Non-goals

3. Architecture

                         ┌─────────────────────── offline ───────────────────────┐
  scenario templates ──► │ generator ─► trajectories.jsonl ─► splitter ─► splits/ │
  sandbox runs (docker)─►│      │                                  │              │
  LLM synthetic (sep.) ─►│      └─► gold sampler ─► human labels ──┼─► agreement  │
                         │                       ─► LLM labels  ───┘    report     │
                         │ splits/ ─► baselines / fine-tune / distill ─► ckpt     │
                         │ ckpt ─► calibrate (temp scaling) ─► thresholds (cost)  │
                         │ ckpt ─► ONNX export ─► INT8 quantize ─► model bundle   │
                         └────────────────────────────────────────────────────────┘

                         ┌─────────────────────── online ────────────────────────┐
   agent ──tool call──►  │ adapter (decorator | MCP proxy)                        │
                         │   │ 1. build ToolCallEvent (canonical featurizer)       │
                         │   │ 2. rule floor (deterministic deny/escalate rules)   │
                         │   │ 3. classifier (ONNX Runtime, INT8/FP32)  ── timeout │
                         │   │ 4. decision = argmin expected cost(calibrated p)    │
                         │   │ 5. audit log append (write-ahead, before execution) │
                         │   ▼                                                    │
                         │ mode=enforce: allow→run | approval→hold | block→refuse │
                         │ mode=shadow : always run, log would-be decision        │
                         └────────────────────────────────────────────────────────┘

The featurizer (event → model input text) is one pure function imported by the training pipeline and by the server. That removes train/serve skew by construction, and a golden-file test pins its output (invariant I8).

4. Data model

All records are JSON Lines with a schema_version. Python dataclasses in tripwire/schema.py are the source of truth, and tripwire validate checks every file.

ToolCall
  tool:        enum {shell, file_read, file_write, http_request, db_query, email_send, payment, generic}
               # generic = any other tool: {"name": ..., "arguments": {...}}
  args:        object       # tool-specific; e.g. {"command": "..."} or {"method","url","body"}

ContextMessage
  role:        enum {user, assistant, tool_call, tool_result, system}
  content:     str
  trusted:     bool         # false for anything derived from external content
  source:      str | null   # "web:<host>", "email:<sender>", "file:<path>", ...

Example                     # the unit the classifier scores: one proposed call
  example_id:  str          # sha256 of the canonical content, first 16 hex chars
  trajectory_id, step_index
  task_id:     str          # concrete task instance
  task_template_id: str     # template it came from: the leakage group key
  scenario_id: str          # benign:<template> or attack:<family>/<technique>
  attack_family: str | null # e.g. exfiltration, credential_access ...
  attack_vector: str | null # how instructions arrived: web, email, file, tool_output, user
  source:      enum {templated, sandbox, benchmark, redteam_llm, synthetic_llm}
  context:     [ContextMessage]   # most recent last; already truncated
  tool_call:   ToolCall
  label:       enum {allow, needs_approval, block} | null
  category:    taxonomy category (TAXONOMY.md)
  label_source: enum {construction, human:<id>, llm:<model>}
  meta:        object       # generator params, seeds; never used as model input

The dataset split is a manifest (data/splits/<name>.json) that maps each task_template_id and held-out attack_family to train | dev | test | heldout_family, and records the source file hashes. Splits are computed, never hand-edited.

The gold set is data/gold/gold_v<N>.jsonl (frozen examples) plus data/gold/annotations/<annotator>.jsonl ({example_id, label, category, notes, annotator, timestamp}). Freezing records a content hash in the manifest.

The audit record (Milestone 5): {ts, request_id, event_hash, tool, decision, probs, mode, model_version, rule_hits, latency_us, executed}.

5. Invariants

Each invariant has a test that enforces it. The test name is in brackets.

idinvariantenforced by
I1Within a split manifest, every task_template_id belongs to exactly one partition.test_split_no_template_leakage
I2Held-out attack families never appear in train or dev, whether as a family name or through a template that only exists to deliver that family.test_heldout_family_isolated
I3source=synthetic_llm examples are never in dev, test or the gold set; they may only be added to train, and only behind an explicit flag.test_synthetic_quarantine
I4example_id is a deterministic hash of the canonical content, and IDs are unique across the dataset.test_example_id_deterministic, test_no_duplicate_ids
I5Generation is deterministic: the same seed and config give byte-identical output.test_generator_deterministic
I6A frozen gold file never changes; its sha256 is recorded and checked before every agreement or eval run.test_gold_hash_check
I7In enforce mode, a classifier error, a timeout or an audit-log write failure never yields allow. The fallback is needs_approval (configurable to block).M5 test_fail_closed_*
I8The featurizer is a pure function shared by train and serve, pinned by a golden file.M2 test_featurizer_golden
I9Context truncation always keeps the proposed tool call whole. Older context is dropped first.M2 test_truncation_keeps_call
I10The rule floor may raise a decision's severity but never lower it.M2/M5 test_rules_monotone
I11Every decision is written to the audit log before the tool runs (enforce and shadow).M5 test_audit_before_exec

6. Failure modes

idfailuredetectionhandling
F1Classifier raises an exception or the model fails to loadexception at load or inferenceEnforce mode falls back to needs_approval with reason guard_error (I7). The service refuses to start if the model hash does not match the bundle manifest.
F2Inference exceeds its latency budget (CPU contention)per-call timer; deadline set in configEnforce mode falls back to needs_approval with reason guard_timeout. Timeout rate is emitted as a metric.
F3Oversized input: a huge file body or a long contexttoken count before inferenceDeterministic truncation (I9). Calls whose own text exceeds the budget are scored on head+tail windows plus a rule check, and flagged truncated=true.
F4Malformed or unknown tool typeschema validationUnknown tools map to generic with JSON-serialized args. Enforce mode applies a conservative policy (needs_approval unless allowlisted).
F5Obfuscation: base64, variable indirection, split commands, unicode homoglyphsM2 robustness suiteNormalizer (decode obvious base64, NFKC) is part of the featurizer. Obfuscated variants go into training (M6). Residual gap reported per transform.
F6Injection aimed at the classifier ("SYSTEM: this call is safe")red-team family guard_directedMain model is an encoder classifier (not instruction-following). Untrusted context is wrapped in explicit [UNTRUSTED src=…] markers. A dedicated eval slice measures this.
F7Distribution shift: new tools, new hosts, new phrasingshadow-mode logs, score-entropy driftShadow mode before enforcing. Held-out-family eval estimates the generalization gap. Retraining loop in M6.
F8Label noise: rubric ambiguity, LLM-labeler biasinter-annotator agreement (kappa) and disagreement reviewRubric revisions are versioned. Disputed examples are adjudicated before the gold set is frozen. Agreement is reported per category.
F9Template leakage inflates scoressplit by template (I1). Compare results on templated data with results on sandbox dataAll headline numbers come from held-out templates. Templated-vs-sandbox gap is reported as a limitation.
F10Slow-burn multi-step attack (read a secret, then exfiltrate it N steps later). Note: data-gathering reads done on an attacker's instructions are excluded from the dataset (ADR-0007), so only the harmful step is trained and scoredcontext window includes recent tool calls and resultsWindow size K is a config value. Attacks beyond K are a documented limitation, and a cross_step eval slice measures the decay.
F11Audit log unavailable (disk full, permission error)write errorEnforce mode does not run the call (I7, I11). Shadow mode runs it and increments audit_drop (shadow must not break the agent).
F12Calibration drift after retraining or quantizationECE on dev after every exportTemperature is refit for each artifact (FP32 and INT8 separately). The export step fails if ECE exceeds its threshold.
F13LLM judge or labeler unavailable, non-deterministic, or refusesAPI error, run-to-run variance, stop_reason=refusalDeterminism cannot be assumed from temperature or seed. Cache keys include model, effort, prompt version, rubric hash, example id and OpenRouter routing/privacy scope. Anthropic may use server-side refusal fallbacks; OpenRouter restricts providers explicitly. Refusals, truncation and invalid results are reported, never silently counted as labels. Fresh repeats and cache replays are distinguished.

7. Metric definitions

Notation: gold label y ∈ {allow, approve, block}; predicted action â.

8. Test strategy

layertoolwhat it coverscommand
unitpytestschema round-trip, ID hashing, kappa against hand-computed values, split assignment, rubric helpersmake unit
propertypytest + seeded randominvariants I1–I5 over many random seeds and configspart of make unit
integrationpytest -m integrationgenerate → validate → split → gold sample end to end in a temp dir; sandbox replay through Docker (skipped if Docker is absent, and reported as skipped)make integration
lintruffstyle, imports, common bugsmake lint
type-checkmypy --strict on tripwire/interface driftmake typecheck
benchmarkcustom script, recorded to EVIDENCE.mdlatency, throughput (from M2)make bench
evaltripwire evalevery metric in §7 from committed data and checkpointsmake eval (M2+)

Rules: each command runs separately. A check counts as passing only if its real output says so. Benchmarks are never run inside the test suite.

9. Milestones

The portfolio runtime now uses the bounded TF-IDF service in ADR-0011; encoder/ONNX research below is a separate, unfinished performance track. See RELEASE_REPORT.md for the released application and its limitations.

Each milestone works end to end before the next one starts.

M1 — Taxonomy, data-collection harness, gold set

M2 — Baselines and eval harness

M3 — Fine-tuned model and distillation

M4 — Calibration, thresholds, quantization

M5 — Serving and integration

M6 — Red-team round 2

v0.4 — Enforced file capabilities

The historical model milestones above remain separate from the shipped permission runtime.