Part 04›
✎

05. Runtime Monitoring and Detection#

Level: Professional · Reading time: 20 min · Exercise: 60 min Prerequisites: Defenses: Guardrails, Detection and Secure Design

In one sentence: After this chapter you can place runtime monitoring in an agent's architecture, decide for each check whether it sits on the path or beside it, and state its cost, latency, and false-positive trade-offs in numbers.

Why this matters#

You built the policy gate from the previous chapter. The user asks the agent to forward today's email to a colleague. The agent forwards 40,000 messages, one call at a time, all to a known address. Every single call was allowed by the policy for "forward email". The gate saw nothing wrong.

A gate judges one action at a time. Some attacks are only visible in the shape of many actions. The question of this chapter: what should watch a running agent, and what is watching worth?

The core idea#

Runtime protection is any check that happens while the agent runs. Dawn Song lists five kinds: input guards, output guards, information flow control and taint tracking, monitoring, and a human in the loop (84:00, Fall 2025).

Three definitions sort them.

Song places the layers in a fixed order (Spring 2025): input sanitization, model-level defense, policy enforcement on actions, and last monitoring and anomaly detection, so that even if everything before fails, something still watches the run (78:00). Her slide on monitoring and detection asks for two things: proper monitoring and log auditing, and anomaly detection applied in real time or for log analysis. That gives the main design choice: where a check sits. The three positions below organize the mechanisms she names. The labels are this repository's.

The analogy is a building. The turnstile at the door is inline. The cameras are out of band. The person who reviews the footage is the human check. The analogy breaks in one place. A camera cannot be lied to by what it films. A detector built on a language model reads the same untrusted text as the agent, so it can be deceived by the same text.

Figure 1. The three positions a check can take, and how a finding from the audit trail comes back as a rule.

flowchart LR
    U["User request"] --> G["Input guard: inline"]
    G --> M["Model"]
    M --> E["Policy gate: inline"]
    E -->|"sensitive action"| H["Human approval"]
    E --> T["Tool call"]
    H -->|"approved"| T
    M --> L["Audit trail"]
    T --> L
    L --> A["Anomaly detector: out of band"]
    A -->|"finding"| P["Alert a person"]
    P -->|"new rule"| E

Only the checks on the top path can stop an action before it happens. The out-of-band detector acts afterwards, by turning what it saw into a new rule.

How it works, step by step#

1. Define the event#

Everything else depends on the audit trail. One record per event, with at least:

Provenance is the part teams skip. The model does not receive it. Your log is the only place where it survives, and it is what turns an incident into a diagnosis. The trail has a price. Song names the large volume of input and generated text as the reason auditability has to be balanced against storage cost (106:00). So record actions and provenance first, and decide separately how much raw text to keep.

2. Keep the hard checks inline#

An input guard runs before the model. Policy enforcement runs before each tool call. Song describes Progent's enforcement component as a component that monitors the agent's actions from its outputs and enforces the policies on them (88:00). In Spring 2025 she described the loop (94:00, 96:00):

  1. The user's query arrives. A human-written baseline policy is already loaded.
  2. A model generates task-specific policies that extend the baseline.
  3. The agent plans and calls tools.
  4. The enforcement point observes each tool call, allows it, or blocks it and gives a reason.
  5. The results from the environment update the policies again.

Her banking example shows why step 5 matters. The default policy allowed the tool send money. After the query and one lookup, the updated policy allowed sending only to one account, Apple's. A transaction description then carried an injected instruction to send money to the attacker's account. The enforcement point blocked that call and allowed the payment to Apple (88:00, 90:00, 92:00). Her reading: the original policy was too loose, and the update made it strict and accurate.

Each decision, with its reason, lands in the audit trail. She describes the enforcement as efficient and real time, and as giving deterministic guarantees over the properties written in the policies (94:00, 96:00).

3. Track untrusted data#

Information flow control, or taint tracking, labels data that came from an untrusted source and follows it through the system. Song gives it two jobs: untrusted data must not influence control-critical behavior, and sensitive data must not leak to untrusted entities (92:00). She names two problems: over-tainting, when too much is labeled, and runtime overhead. Her Spring 2025 slide adds three open questions: how to keep the tracking across tool boundaries such as a plugin or API, how to write policies that evolve with the conversation, and how to test a system for leaks with adversarial tests (108:00).

4. Run anomaly detection out of band#

Anomaly detection flags behavior that differs from the normal pattern. A runtime monitor can watch the agent's behavior and the execution of the whole system, to find anomalies and unsafe actions (92:00). Her example of a learned detector is DataSentinel, a fine-tuned detector for prompt injection (IEEE Security and Privacy 2025). She expects other detectors for other attacks and for suspicious behavior, and her open question is how to make anomaly detection work in many different settings (106:00, 108:00). Four families of signal, which are this repository's:

Signal Example
Counts Tool calls, steps, or tokens in one run
Rates Calls per minute to one tool
Shapes An argument that does not fit the task, such as a new recipient domain
Sequences A read-then-export pattern, or a goal that differs from the first request

5. Send findings to a person#

A human in the loop validates critical and high-impact actions (94:00). A finding from an out-of-band monitor usually arrives too late to block. Its value is in stopping the run, alerting a person, and adding a case to the test suite.

6. Feed the findings back#

Every confirmed finding becomes a rule, a policy, or a test. The test belongs in the regression suite of Red-Teaming and Safety Evaluation.

What a monitor can and cannot see#

This table is engineering judgment, not lecture content.

A monitor can see A monitor cannot see
Every tool call with its arguments What the model intended
Which text from which source preceded an action, if provenance is logged Whether a correct-looking action came from an injection or from a bad request
Counts, rates, and costs An attack that stays under every threshold
Every policy decision Anything inside a hosted model
What your own code does Channels you do not log

Cost, latency, and false positives#

These trade-offs are engineering judgment, except where a bullet cites the lecture.

Long runs make false positives worse than they look. With a per-step false-positive rate p, a run of n steps raises at least one false alert with a probability of 1 − (1 − p)ⁿ. At p = 0.1%, a run of 200 steps has an 18% chance of a false alert. At p = 1%, it has an 87% chance. A rate that sounds small becomes a noisy monitor on a long task. So block automatically only for actions that are both rare and impossible to undo, and flag everything else.

A second model as a monitor#

The lectures do not present a monitoring agent. This paragraph is this repository's own suggestion. Where a rule cannot express the constraint, a second language model can read the user's request and the proposed action and judge whether the action serves the request. Keep it inline, keep its output to allow, block, or escalate, and give it structured events rather than raw pages. Evaluate it as you would any judge (see LLM as a Judge and Rubrics), and never as the only control. The capstone of this course builds a monitoring agent for prompt injection: capstone.

Worked example#

An out-of-band monitor over an audit trail, in plain Python and without a model. Save it as monitor_demo.py, put the two trail lines below in audit.jsonl beside it, and run python monitor_demo.py.

# monitor_demo.py: checks over one run's audit trail, in audit.jsonl.
import json

LIMITS = {"tool_calls": 12, "reads_per_send": 50}
KNOWN_DOMAINS = {"example.com"}

def findings(path: str) -> list:
    calls = reads = sends = 0
    odd = []
    with open(path) as trail:
        for line in trail:                      # one JSON object per event
            event = json.loads(line)
            if event["type"] != "tool_call":
                continue
            calls += 1
            reads += event["tool"] == "read_email"
            sends += event["tool"] == "send_email"
            if event["tool"] == "send_email":
                domain = event["args"]["to"].split("@")[-1]
                if domain not in KNOWN_DOMAINS:
                    odd.append(f"send to a new recipient domain: {event['args']['to']}")
    out = []
    if calls > LIMITS["tool_calls"]:
        out.append(f"{calls} tool calls (limit {LIMITS['tool_calls']})")
    if sends and reads / sends > LIMITS["reads_per_send"]:
        out.append(f"{reads} reads for {sends} sends: possible mass export")
    return out + odd

if __name__ == "__main__":
    print("\n".join(findings("audit.jsonl")) or "no findings")

A small trail of the same kind, with the reads shortened to one line:

{"type": "tool_call", "tool": "read_email", "args": {}}
{"type": "tool_call", "tool": "send_email", "args": {"to": "eve@evil.example"}}

What to observe:

What the practitioners say#

Dawn Song treats monitoring as one mechanism among several, in both lectures.

Neither lecture describes a monitor built on a second agent. The positions, the signals, and the trade-offs in this chapter are this repository's own engineering judgment, built on the mechanisms she names.

Pitfalls#

Try it#

Add an audit trail and an out-of-band monitor to an agent you control.

  1. Emit one event per step with the fields of step 1.
  2. Write three rules: one on counts, one on shapes, one on sequences.
  3. Run twenty benign tasks and your injection suite through the agent.
  4. Measure storage per run, false alerts per 1,000 steps on the benign tasks, and attacks caught in the suite.

You are done when you have those three numbers in writing, each rule has a documented false-positive story, and every finding names the run and the step. Stretch goal: add an inline goal-consistency check with a second model, and measure the latency it adds per step and its false-positive rate.

Key takeaways#

Self-check#

  1. A check can block an action but adds latency to every step. Which position is it in, and which two mechanisms from the lecture sit there?
  2. Why does the audit trail need provenance when the model does not receive it?
  3. A rule has a 0.1% false-positive rate per step. What is the chance of at least one false alert in a 200-step run, and what follows for blocking policy?
  4. Why does a detector built on a language model need more care than a rule on counts?
  5. What happens to a confirmed finding so that the same attack stops working?
Show answers 1. Inline. Input guards and policy enforcement on tool calls. 2. Because the model cannot see where text came from. The log is the only place that records it, and it distinguishes an injection from a bad request. 3. About 18% (1 − 0.999²⁰⁰). Block automatically only for rare and irreversible actions, and flag the rest. 4. It reads the same untrusted text as the agent, so it can be deceived by the same text, and it is a probabilistic judge rather than a fixed rule. 5. It becomes a policy, a rule, or a test in the regression suite.

Sources#

Next#

→ Red-Teaming and Safety Evaluation, for how to measure whether all these layers hold.