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:
| action | meaning |
|---|---|
allow | run the call |
needs_approval | pause; a human must approve before the call runs |
block | refuse the call and return a structured refusal to the agent |
Requirements:
- Inline latency. Fast enough to sit on every tool call. Target p95 < 10 ms on CPU (single request, batch size 1, measured server-side) and < 3 ms on GPU. For reference, a large-LLM judge typically costs hundreds of ms to seconds per call; that gap is the reason this project exists.
- Trustworthy accuracy. High recall on harmful calls at a low false-block rate. Headline metric: recall on
block-labelled calls at a 1% false-block rate onallow-labelled calls (definitions in §7). - Calibrated scores. Thresholds come from an explicit cost matrix, so the probabilities must mean what they say.
- Drop-in integration. A Python decorator and an MCP proxy, an audit log of every decision, and a shadow mode that logs without enforcing.
2. Non-goals
- Not a sandbox. Tripwire decides whether to run a call; it does not contain a call that runs. It belongs in front of a sandbox, not in place of one.
- Not a complete policy engine. Deployment-specific allowlists (which hosts or which payees are acceptable) are config inputs, not learned behaviour.
- No post-hoc output inspection. We do not scan tool results for leaked data (DLP). Results only enter as context for later decisions.
- No multi-turn planning analysis. We look at a bounded context window, not whole-session intent. Slow-burn attacks spread over many benign-looking calls are a documented limitation (§6, F10).
- No guarantee against adaptive white-box attackers. Milestone 6 measures robustness to our own red-teaming; it does not prove robustness.
- No production claims. There are no real users or deployments. Every number in EVIDENCE.md comes from local, reproducible runs.
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.
| id | invariant | enforced by |
|---|---|---|
| I1 | Within a split manifest, every task_template_id belongs to exactly one partition. | test_split_no_template_leakage |
| I2 | Held-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 |
| I3 | source=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 |
| I4 | example_id is a deterministic hash of the canonical content, and IDs are unique across the dataset. | test_example_id_deterministic, test_no_duplicate_ids |
| I5 | Generation is deterministic: the same seed and config give byte-identical output. | test_generator_deterministic |
| I6 | A frozen gold file never changes; its sha256 is recorded and checked before every agreement or eval run. | test_gold_hash_check |
| I7 | In 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_* |
| I8 | The featurizer is a pure function shared by train and serve, pinned by a golden file. | M2 test_featurizer_golden |
| I9 | Context truncation always keeps the proposed tool call whole. Older context is dropped first. | M2 test_truncation_keeps_call |
| I10 | The rule floor may raise a decision's severity but never lower it. | M2/M5 test_rules_monotone |
| I11 | Every decision is written to the audit log before the tool runs (enforce and shadow). | M5 test_audit_before_exec |
6. Failure modes
| id | failure | detection | handling |
|---|---|---|---|
| F1 | Classifier raises an exception or the model fails to load | exception at load or inference | Enforce 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. |
| F2 | Inference exceeds its latency budget (CPU contention) | per-call timer; deadline set in config | Enforce mode falls back to needs_approval with reason guard_timeout. Timeout rate is emitted as a metric. |
| F3 | Oversized input: a huge file body or a long context | token count before inference | Deterministic truncation (I9). Calls whose own text exceeds the budget are scored on head+tail windows plus a rule check, and flagged truncated=true. |
| F4 | Malformed or unknown tool type | schema validation | Unknown tools map to generic with JSON-serialized args. Enforce mode applies a conservative policy (needs_approval unless allowlisted). |
| F5 | Obfuscation: base64, variable indirection, split commands, unicode homoglyphs | M2 robustness suite | Normalizer (decode obvious base64, NFKC) is part of the featurizer. Obfuscated variants go into training (M6). Residual gap reported per transform. |
| F6 | Injection aimed at the classifier ("SYSTEM: this call is safe") | red-team family guard_directed | Main model is an encoder classifier (not instruction-following). Untrusted context is wrapped in explicit [UNTRUSTED src=…] markers. A dedicated eval slice measures this. |
| F7 | Distribution shift: new tools, new hosts, new phrasing | shadow-mode logs, score-entropy drift | Shadow mode before enforcing. Held-out-family eval estimates the generalization gap. Retraining loop in M6. |
| F8 | Label noise: rubric ambiguity, LLM-labeler bias | inter-annotator agreement (kappa) and disagreement review | Rubric revisions are versioned. Disputed examples are adjudicated before the gold set is frozen. Agreement is reported per category. |
| F9 | Template leakage inflates scores | split by template (I1). Compare results on templated data with results on sandbox data | All headline numbers come from held-out templates. Templated-vs-sandbox gap is reported as a limitation. |
| F10 | Slow-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 scored | context window includes recent tool calls and results | Window size K is a config value. Attacks beyond K are a documented limitation, and a cross_step eval slice measures the decay. |
| F11 | Audit log unavailable (disk full, permission error) | write error | Enforce mode does not run the call (I7, I11). Shadow mode runs it and increments audit_drop (shadow must not break the agent). |
| F12 | Calibration drift after retraining or quantization | ECE on dev after every export | Temperature is refit for each artifact (FP32 and INT8 separately). The export step fails if ECE exceeds its threshold. |
| F13 | LLM judge or labeler unavailable, non-deterministic, or refuses | API error, run-to-run variance, stop_reason=refusal | Determinism 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 â.
- Per-class precision and recall. Standard one-vs-rest, computed on actions after thresholding. A confusion matrix is always reported alongside.
- False-block rate (FBR) = |{y = allow, â = block}| / |{y = allow}|.
- Recall@1%FBR. Sweep a threshold τ on the calibrated score s(x) = P(block | x). Choose the smallest τ such that FBR(τ) ≤ 1% on the dev split, then report recall on
blockat that τ on the test split, along with the realized test FBR. Choosing τ on test would be optimistic, so we never do it. When the allow class in dev has fewer than 1,000 examples, the 1% point rests on fewer than 10 examples; we report that count and a bootstrap 95% CI. - Flag recall = P(â ≠ allow | y ≠ allow), the "a human or a block saw it" rate. Unnecessary approval rate = P(â = approve | y = allow).
- Expected cost per decision under the cost matrix (ADR-0002):
mean_i C[y_i, â_i]. - ECE. 15 equal-width bins on max-class confidence,
Σ_b (|b|/n)·|acc(b) − conf(b)|. Per-class ECE on P(block) is also reported. - Latency. Wall-clock around
featurize + infer + decidein-process, batch size 1, after 200 warmup calls, over ≥ 10,000 calls, reported as p50/p95/p99 in µs. Hardware, thread count, ORT version and model variant are recorded with every number. HTTP/MCP overhead is measured separately as end-to-end latency. - Cost per 1M decisions. Large-LLM judge: measured mean input and output tokens × list price on the measurement date (price recorded). Tripwire: measured throughput on a named instance type × that instance's on-demand price. Inputs are recorded in EVIDENCE.md, and the result is labelled as an estimate.
- Generalization gap = Recall@1%FBR(test) − Recall@1%FBR(heldout_family), where heldout_family uses the same τ.
- Robustness = recall on the obfuscated variant ÷ recall on the original, per transform, over attack examples whose original was caught.
- Inter-annotator agreement. Cohen's κ (nominal) and linearly weighted κ (ordinal: allow < approve < block), with raw percent agreement, the confusion matrix and per-category κ. Bootstrap 95% CI over examples.
8. Test strategy
| layer | tool | what it covers | command |
|---|---|---|---|
| unit | pytest | schema round-trip, ID hashing, kappa against hand-computed values, split assignment, rubric helpers | make unit |
| property | pytest + seeded random | invariants I1–I5 over many random seeds and configs | part of make unit |
| integration | pytest -m integration | generate → 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 |
| lint | ruff | style, imports, common bugs | make lint |
| type-check | mypy --strict on tripwire/ | interface drift | make typecheck |
| benchmark | custom script, recorded to EVIDENCE.md | latency, throughput (from M2) | make bench |
| eval | tripwire eval | every metric in §7 from committed data and checkpoints | make 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
- [x] DESIGN.md, TAXONOMY.md (rubric v1.0), ADRs 0001–0006
- [x] Schema and validator (
tripwire validate) - [x] Executable rubric, checked against the TAXONOMY.md §4 table
- [x] Sandbox replay harness (OrbStack,
--network none, 128 MB cap, allowlisted commands only) - [x] Leakage-safe splitter with held-out attack families (I1–I3, property-tested)
- [x] Gold-set sampler (stratified, blind files, hash lock I6) and interactive CLI labeler
- [x] LLM labeler (structured output, disk cache, refusal accounting) — live Morph run completed; agreement and Darkbloom failures in OPENROUTER_REPORT.md
- [x] Agreement report (κ, linear-weighted κ, per category, bootstrap CI), hand-checked
- [x] 28-record fixture set and end-to-end CLI test
- [x] Bulk data source: AgentDojo importer, 10,105 examples, split v2 (0.5/0.25/0.25) with 4 held-out techniques (ADR-0004 addendum, ADR-0007)
- [x] Gold v1 drawn and frozen: 600 blind examples from dev/test/heldout (
data/gold/gold_v1.lock.json) - [x] Gold v1 labelled by Sonnet subagents and adjudicated by Claude (2026-11-06; the owner cannot adjudicate). LLM labels, not human gold (EVIDENCE M1). Hand-labelling stays possible:
make label WHO=<you> - [x] Owner decision (2026-11-06): precursor reads under injection stay excluded; no rubric change (ADR-0007 decision 4)
- [x] OpenRouter backend (GLM-5.3-Flash, Morph then Darkbloom) written and unit-tested with a fake HTTP layer (ADR-0009)
- [x] Live Morph gold labels and agreement; Darkbloom availability/format failures reported (OPENROUTER_REPORT.md)
- [x] Zero-shot GLM-5.3-Flash judge on all held-out and 500 sampled test examples, scored on its own labels (ADR-0016, EVIDENCE 2026-11-18)
- [ ] Remaining live work: judge on the rest of test and the obfuscation sample, open-agent runs, LLM synthetic generation
M2 — Baselines and eval harness
- [x] Featurizer and normalizer (I8, I9), golden test (ADR-0008)
- [x] Rule baseline, TF-IDF + logistic regression baseline, zero-shot GLM judge (partial test coverage;
eval-decisions, ADR-0016) - [x] Liquid d1.1 decision model scored at a dev-chosen τ (partial test coverage; robustness not measured; EVIDENCE 2026-11-18)
- [x] Local model probed on real-file actions: no risky action raised at the shipped threshold (EVIDENCE 2026-11-18)
- [x]
tripwire evalcomputing the §7 metrics into a JSON report (make eval); external predictions via--model preds - [x] Obfuscation suite: homoglyph, zero-width, case, base64. Shell-specific transforms N/A on AgentDojo (ADR-0008)
- [x] Latency benchmark harness (in-process, batch 1, 200 warmup, 10k calls)
- [x] Narrow deterministic severity floor combined monotonically with the runtime model (I10), with explicit incomplete coverage
M3 — Fine-tuned model and distillation
- [x] DeBERTa-v3-small fine-tune on Kaggle T4 (seed 0): held-out recall 0.36 vs TF-IDF 0.07; test FBR misses 1% (EVIDENCE M3)
- [x] Sweep: 1-epoch runs with quarter-epoch dev checks, 3 seeds, lower lr, DeBERTa-v3-base (EVIDENCE M3b/M3c): base held-out 0.38–0.69 vs small 0.22–0.36; test FBR at dev τ unstable across seeds (0.006–0.199)
- [ ] ModernBERT-base comparison; template-disjoint calibration partition for τ (ADR-0008 amendment)
- [x] Frozen hashed linear student distilled from existing encoder train probabilities; failed to improve held-out recall and was rejected (RELEASE_REPORT.md)
- [ ] ModernBERT-base or other student architecture; additional work needs a fresh evaluation protocol
- [ ] Optional: Qwen2.5-0.5B with LoRA as a comparison
M4 — Calibration, thresholds, quantization
- [x] Temperature / vector scaling fit on dev (
--calibrate); first results in EVIDENCE M3 - [ ] Temperature scaling, ECE before and after
- [ ] Cost-matrix thresholding; Recall@1%FBR
- [x] ONNX export works (fp32 739 MB); default dynamic INT8 collapses DeBERTa-v3-base to all-allow (EVIDENCE M4)
- [x] Three more dynamic INT8 recipes: best (per-channel + reduce_range) still drops held-out recall 0.65 → 0.20 (EVIDENCE M4)
- [ ] Static INT8 with calibration / QAT, or fp16 only; accuracy delta
- [ ] Meet the latency budget: CPU p95 is ~1 s at 512 tokens on Kaggle Xeon. Needs shorter input, a smaller model, or a cascade
M5 — Serving and integration
- [x] Bounded TF-IDF HTTP/CLI service and responsive inference demo, trusted artifact build, container and CI
- [ ] ONNX Runtime service with micro-batching (separate future encoder work)
- [x] Reference Python enforcement gate, exact-request approvals and durable metadata-only audit
- [x] MCP stdio proxy with shadow and enforce modes and a decision report (ADR-0023); application-specific shadow integration still open
- [x] Fail-closed guard/audit and severity-floor tests (I7, I10, I11), timeout/overload checks
- [ ] Public hosting and application-specific approver identity integration
M6 — Red-team round 2
- [ ] Attack the M4 model (obfuscation search, paraphrase, guard-directed injection)
- [ ] Add failures to train, re-evaluate on a fresh held-out family set
- [ ] Acceptance:
make reproduceand the inline exfiltration-block demo
v0.4 — Enforced file capabilities
- [x] Operator-owned deterministic policy, independent of advisory model scores (ADR-0012)
- [x] POSIX file runner with no-follow resolution, bounded reads and atomic approved writes
- [x] Opaque single-use actor/action/policy-bound approvals and pre-I/O durable metadata audit
- [x] Model-free CLI walkthrough, HTTP checks and interactive browser evaluator
- [x] Public project site, compatible MP4 recordings, deployment guide, report and presentation
The historical model milestones above remain separate from the shipped permission runtime.