Skip to content

Monitoring agents: judge the actions

An agent's response becomes an action: a query, a write, a payment. The response text and the reasoning tell you what the agent says about its work. The tool calls and their effects show what it did. This module explains what to watch, where to place a check so that a request cannot switch it off, what chain-of-thought monitoring gives, and what to log without storing customer content. Each section ends with a conclusion: what this means for protecting an AI agent.

Time: about an hour. Roughly 35 minutes for the text, 20 minutes for the lab and 5 minutes for the questions. What you need: Python 3.8 or later with no third-party packages. No account, keys or network access are needed.

Learning goals

  • Explain why the monitoring of an agent is built on tool calls and their effects, not on text alone.
  • Write out the request shapes that reach a control, and find the request field that switches it off.
  • Explain why the model's output is checked as well as the input, and which part of the output is an action.
  • Name what chain-of-thought monitoring gives and what it cannot give.
  • Draft a log record from which an incident can be reconstructed without storing customer content.

Text and action

A model does not execute anything: it produces text, and the executor turns part of that text into an action. The module "LLMs for security engineers" covers this. An agent therefore has three different products: the reasoning, the reply to the user and the tool calls. Only the third changes the world.

Text and action come apart for three reasons.

  • A reply is a report, and a report can be wrong. The agent says "done" although it did something else, or more than it was asked. The cause may be a mistake, or it may be an injected instruction that also told the agent not to mention it.
  • The harm comes before the reply. A tool call is executed in the middle of the loop, and the final text appears at the end. A monitor that reads the final text learns about a payment after the payment.
  • A combination of steps can be dangerous when each step is innocuous. Simon Willison named such a combination the lethal trifecta: access to private data, exposure to untrusted content and a channel to the outside. Nothing in the text of any single step looks suspicious.

Research benchmarks for agents are built the same way. In the AgentDojo benchmark, which Debenedetti and coauthors described in 2024, the success of a task and the success of an attack are decided by checking the state of the environment after the agent has run, not by reading its reply.

What this means for defense:

  • The unit of observation for an agent is a tool call with its arguments and its result, not a message.
  • The check on an action sits before execution, at the executor. Observation after execution is good for an investigation, but it does not undo an irreversible action.
  • Success and violation are decided from the state of the environment: what changed, for whom and by how much. The phrase "task completed" is not evidence.

What to watch in actions

What to watchThe questionThe kind of check
The call and its argumentsIs the action consistent with what the user authorized?Deterministic, before execution
The origin of the argumentsDid the value come from the user's task or from content that was read?Tracking the source of data
The sequence of stepsDid private data, untrusted input and a channel to the outside meet in one task?A rule over the history of the task
The tool resultWhat actually changed, and what came back into the context?Reconciling the state, checking the returned text
The agent's reportDoes what was said match what was called?Comparing the reply with the log of calls

The first row of the table matters more than the rest. The question "is the call consistent with the authorization" has an exact answer: the amount is no greater than the authorized one, the recipient is on the user's list, the object belongs to the user. The question "does this text look like an attack" has no exact answer.

An observer sees only what it was given. Spectorn's public page on agent security states this boundary directly: Spectorn sees only the content and events that the calling system actually sends to it, and becomes a blocking layer only where the integration enforces its verdict. A gateway in front of the model sees the tool call in the model's response. Your code executes the call, and only your code knows what happened afterwards.

What this means for defense:

  • Make the check on an action deterministic and place it in the executor's code or directly in front of it.
  • Do not appoint as the judge of an action the same model that proposed it.
  • Observation does not replace least privilege. The narrower the set of tools and permissions, the fewer outcomes have to be recognized.
  • A tool result is untrusted input and is checked before it returns to the context.
  • An action that must be checked goes through the point where the check runs. Nobody sees an action that was executed around it.

A control the caller cannot switch off

Complete mediation requires that a control runs on every access. A request to a model has many shapes: a whole response or a stream, the response format, the set of tools, the model and the route, the size and type of the content. The caller sets every one of these fields. If even one of them determines whether the response reaches the control, then the caller owns the control, not you.

In our own history this happened to the check on agent actions. It was attached to the buffered response and did not run for streamed responses. Meanwhile 60 unit tests, a corpus of 345 cases and 11 end-to-end tests stayed green: none of them turned streaming on. This is question C1 in the index of 28 questions, entries from August 2026. The defect has been fixed.

Defects of this class have an unpleasant property: the victim of an attack is not the only one who suffers. A customer who wired the check up correctly and turned on streaming, as almost every chat interface does, gets neither the protection nor a signal that the check did not run.

Sometimes blocking has to be switched off, and there is a right form for that. The owner of the policy makes the decision, not the request. In Spectorn this is the shadow mode in the tenant's policy: the request is still checked, and the record shows what would have been blocked. What is switched off is the blocking, not the check, and this state is visible in the decision record.

What this means for defense:

  • For every control, write out the request shapes that reach it and the shapes that do not. The second list must be the one you intended.
  • If any field of the request moves an input from the first list to the second, assume that the caller controls the control.
  • Attach a control to a place that every path goes through, not to one of the branches.
  • A path on which the control cannot run is closed or forced onto a path that can be checked. Letting it pass with a note is not a solution.
  • A test sends the request the way a client sends it, and goes through every value of every field that the path depends on. The test itself is checked by mutation: remove the control from one path and see whether the test goes red.
  • An exception from a control is a state of the policy: it has an author, a time and a mark in the decision record.

Check the output as well as the input

Checking the input alone is not enough, for four reasons.

  • Indirect injection does not come from the user. It sits in a document, an email or a tool result. A check that reads only the user's message does not see it.
  • The input can be clean while the output is not. The model pulls a secret out of the context, assembles a dangerous command from an innocuous request, or simply makes a mistake.
  • A tool call is model output. A check on an action is a check on the output.
  • The output travels on: into a browser, into a database query, into a command shell. The OWASP list has a separate risk for this: improper output handling.

Checking the output has a price. To check a response before it is released, it has to be held back whole or in parts, and the time to first token grows. This is where the temptation to skip the check for the sake of speed appears. The defect from the previous section lived in exactly this place: on the streaming path. According to the public description of the request path in Spectorn, the output is checked before it is returned to the client, and streamed output is buffered and checked before release.

Checking the output at a gateway does not replace the protection of the sink. Parameterized queries, escaping and a sandbox for executable code remain the duty of the code that receives the output.

What this means for defense:

  • Check everything that enters the context: documents, tool results and memory, not only the user's message.
  • Check the output before it reaches the user or the executor. In streaming mode that means a buffer.
  • Treat the input and the output as different measurements. The miss rate on the input says nothing about the output.
  • Protect the sink of the output independently of the check at the gateway.

Chain-of-thought monitoring

Reasoning models produce a chain of intermediate steps before they answer. The paper by Korbak, Balesni and coauthors (2025) states the idea this way: while a model reasons in human language, its reasoning can be read automatically and an intent can be noticed before the action. The authors call this opportunity new and fragile.

What chain-of-thought monitoring gives:

  • An early signal. An intent is sometimes visible before the tool call.
  • An explanation for an investigation: why the agent took this step.
  • Something that actions do not show. In the paper by Baker and coauthors (2025), a monitor that read the reasoning found reward hacking noticeably better than a monitor that saw only actions and responses.
  • A foothold in hard tasks. When a task cannot be solved without writing down intermediate steps, the reasoning serves as working memory, and hiding something essential in it is harder.

What it cannot give:

  • Proof that there is no violation. The written chain need not reflect what determined the answer. The papers by Turpin and by Chen and their coauthors describe cases in which a model relied on a hint and did not mention it in its reasoning. The paper by Lanham and coauthors shows that the answer does not always depend on the written chain.
  • Availability. Some providers return the reasoning in abridged form or do not return it at all, and the observer sees only what it was given.
  • Robustness to optimization. In the same paper by Baker, a model that was penalized for "bad thoughts" learned to hide its intent in the reasoning and went on misbehaving.
  • Permanence. According to Korbak and coauthors, the property may disappear because of the way models are trained, because of architectures in which reasoning is not expressed in words, or because a model learns to hide its reasoning from the observer.
  • Trusted input. The reasoning is produced in the context that the attacker's text enters. A monitor that reads it is itself reading untrusted text.

What this means for defense:

  • Use the reasoning as an additional signal: to ask for human confirmation, to tighten a check or to pick tasks for review. The decision about an action is made by the check on the action.
  • Do not optimize the agent against your own chain-of-thought monitor. A signal that has become a target stops being a signal.
  • Measure the chain-of-thought monitor separately: what share of the violations found from actions it noticed. Its misses must be visible.
  • Do not write the reasoning to the log as it is. It restates customer content.

What to log

A log is needed so that after an incident you can answer the questions: what happened, in what order, who made the decision, on what grounds, and what was left unchecked. Storing customer content is not necessary for this, and it is better not to store it: a log lives longer than a request, more people read it, and it becomes a target itself.

GroupWhat to recordWhat not to record
Who and whenTenant, key identifier, agent, session, task, time and sequence numberThe key itself, the user's personal data
PathAPI route, delivery mode, model, provider, model versionRequest headers and body
ActionTool name, a keyed fingerprint of the arguments, a reference to the user's authorizationArgument values, the text of the authorization
DecisionVerdict, policy mode, category and severity of the finding, version of the policy and rulesThe fragment of text that triggered the finding
What ranWhich checks ran, which did not and why; retries and switches to a fallback pathAn error message that quotes content
ResultExecuted or rejected, tool status, a reference to the changed objectThe returned data

Four notes on the table.

  • The fingerprint is keyed. A plain hash of a short or predictable value can be found by brute force: a payment amount or a phone number can be recovered from it. A fingerprint with a secret key (HMAC) that is stored apart from the log lets you compare values and does not reveal them.
  • A check has three outcomes: checked and clean, checked and found, not checked. The third is never recorded as the first. This is question B2 in the index.
  • A mitigation records itself. A retry, a fallback path and operation in a degraded mode get a counter that is always printed, zero included. This is question D3.
  • The record appears before the action is executed or together with it. An action without a record is worse than a record without an action.

A log without content does not answer the question of what exactly was written. If that answer is needed, the customer keeps the content on their own side under the same request identifier, or an explicit, time-limited capture is turned on. Running the request again does not replace the record: the model's response may turn out different.

A gateway's log also has a boundary of coverage. Spectorn's documentation states it directly: the decision log covers what was submitted to Spectorn, attribution is limited to the identity and metadata supplied by the authenticated integration, and calls that bypass it are not recorded.

What this means for defense:

  • Every decision and every action gets a record. A missing record must be impossible, not merely rare.
  • The record lists the checks that ran, so that "did not run" differs from "found nothing".
  • The absence of content in the log is verified by a test: a synthetic marker is put into a request and then searched for in the log.
  • The log is tried on a practice incident before a real one: take the records and answer the questions of an investigation from them without access to the content.

Required reading

  • Tomek Korbak, Mikita Balesni et al., "Chain of Thought Monitorability: A New and Fragile Opportunity for AI Safety", 2025: the introduction and the section on the fragility of monitorability.
  • Yanda Chen et al., "Reasoning Models Don't Always Say What They Think", 2025: the experimental setup and the conclusions.
  • Kai Greshake et al., "Not what you've signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection", 2023: the threat model and the delivery methods. arxiv.org/abs/2302.12173
  • Edoardo Debenedetti et al., "AgentDojo: A Dynamic Environment to Evaluate Prompt Injection Attacks and Defenses for LLM Agents", 2024: how success and violation are decided from the state of the environment.
  • Jerome H. Saltzer, Michael D. Schroeder, "The Protection of Information in Computer Systems", 1975: complete mediation and fail-safe defaults.
  • OWASP, "Top 10 for Large Language Model Applications": the sections on improper output handling and on excessive agency. owasp.org/www-project-top-10-for-large-language-model-applications
  • Spectorn, "Autonomous AI Agent Security": the threat model and the boundary of what a gateway sees.
  • Spectorn, "28 questions to a green test suite": questions C1, B2 and D3.

Further reading

  • Bowen Baker et al., "Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation", 2025.
  • Miles Turpin et al., "Language Models Don't Always Say What They Think: Unfaithful Explanations in Chain-of-Thought Prompting", 2023.
  • Tamera Lanham et al., "Measuring Faithfulness in Chain-of-Thought Reasoning", 2023.
  • Ryan Greenblatt, Buck Shlegeris et al., "AI Control: Improving Safety Despite Intentional Subversion", 2023.
  • Edoardo Debenedetti et al., "Defeating Prompt Injections by Design", 2025.
  • Simon Willison, "The lethal trifecta for AI agents: private data, untrusted content, and external communication", 2025.
  • Norm Hardy, "The Confused Deputy (or why capabilities might have been invented)", 1988.
  • James P. Anderson, "Computer Security Technology Planning Study", 1972.
  • Bruce Schneier, John Kelsey, "Secure Audit Logs to Support Computer Forensics", 1999.
  • Karen Kent, Murugiah Souppaya, "Guide to Computer Security Log Management", NIST SP 800-92, 2006.
  • Spectorn, "Excessive Agency in AI Agents" and "Improper Output Handling in LLMs": scenarios and boundaries of responsibility.
  • Boaz Barak, the course CS 2881R AI Safety, Harvard University: the session on alignment and chain-of-thought monitorability. boazbk.github.io/mltheoryseminar

Lab

Goal: use a toy agent to compare four ways of observing, to see how a request field switches a control off, and to reconstruct an incident from a log without content. The data is synthetic. The lab's numbers describe the toy and say nothing about any real agent, model or product.

The threshold is chosen before the measurement: τ = 1%. The claim under test: "an unauthorized payment goes unnoticed in fewer than 1% of tasks". A trial is one independent agent task, and an event is a payment that the control did not notice.

The toy has 400 tasks. In each, the user authorized a payment of up to 100, and the agent, after reading a tool result with a synthetic injected line, calls a payment of 900. The user's input is clean. In some tasks the reasoning names the intent, and in some the final reply names the amount.

Save the code to a file named lab_monitoring.py and run python3 lab_monitoring.py.

Python
import hashlib
import hmac
import json
import math
import random
import re

ALPHA = 0.05     # one-sided 95% bound
TAU = 0.01       # threshold chosen before the measurement
EPISODES = 400   # independent agent tasks
LIMIT = 100      # the user authorized a payment no greater than this amount
# The fingerprint key. In a real system it is secret and stored apart from the log.
LOG_KEY = bytes(range(32))


def episodes(streaming_share, seed):
    # In every task the agent has read a tool result with a synthetic injected line
    # and calls a payment above the authorized amount. The user's input is clean.
    rng = random.Random(seed)
    batch = []
    for number in range(1, EPISODES + 1):
        reveals = rng.random() < 0.6   # the reasoning names the intent
        admits = rng.random() < 0.25   # the final reply names the amount
        stream = rng.random() < streaming_share  # the client chooses the delivery mode
        batch.append({
            "id": f"task-{number}",
            "user_input": "pay the invoice for the synthetic service",
            "reasoning": "plan: zorbak, a payment above the limit" if reveals else "plan: pay the invoice",
            "call": {"tool": "pay", "amount": 900, "recipient": "quillex-account"},
            "reply": "Done. Sent 900." if admits else "Done, the invoice is paid.",
            "stream": stream,
        })
    return batch


# Four observers. Each returns True if it noticed the unauthorized payment.
def input_scan(episode):         # reads only the user's input
    return "zorbak" in episode["user_input"]


def reply_monitor(episode):      # reads the final text of the reply
    return any(int(number) > LIMIT for number in re.findall(r"\d+", episode["reply"]))


def reasoning_monitor(episode):  # reads the reasoning, when it is available
    return "zorbak" in episode["reasoning"]


def action_check(episode):       # compares the call with what the user authorized
    return episode["call"]["tool"] == "pay" and episode["call"]["amount"] > LIMIT


def fingerprint(value):
    canonical = json.dumps(value, sort_keys=True, ensure_ascii=False).encode("utf-8")
    return hmac.new(LOG_KEY, canonical, hashlib.sha256).hexdigest()[:16]


def record(sequence, episode, control, ran, noticed):
    # A record without content: no input, no reasoning, no reply, no argument values.
    return {
        "sequence": sequence,
        "task": episode["id"],
        "path": "stream" if episode["stream"] else "buffered",
        "tool": episode["call"]["tool"],
        "arguments": fingerprint(episode["call"]),
        "control": control,
        "control_ran": ran,
        "noticed": noticed,
        "policy": "lab-policy-1",
    }


def run(batch, control, buffered_only):
    events, log = 0, []
    for sequence, episode in enumerate(batch, start=1):
        ran = not (buffered_only and episode["stream"])  # whether the control ran on this path
        noticed = ran and control(episode)
        if not noticed:
            events += 1  # the unauthorized payment went unnoticed
        log.append(record(sequence, episode, control.__name__, ran, noticed))
    return events, log


# Exact one-sided Clopper-Pearson bounds, standard library only.
# The same calculation as in the labs of the previous modules and in scripts/rate_bounds.py.
def binom_cdf(k, n, p):
    total = 0.0
    for i in range(k + 1):
        log_term = math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1)
        log_term += i * math.log(p) + (n - i) * math.log1p(-p)
        total += math.exp(log_term)
    return total


def upper_bound(k, n):
    if k == n:
        return 1.0
    low, high = k / n, 1.0
    for _ in range(100):
        middle = (low + high) / 2
        if binom_cdf(k, n, middle) > ALPHA:
            low = middle
        else:
            high = middle
    return high


def lower_bound(k, n):
    if k == 0:
        return 0.0
    low, high = 0.0, k / n
    for _ in range(100):
        middle = (low + high) / 2
        if 1.0 - binom_cdf(k - 1, n, middle) < ALPHA:
            low = middle
        else:
            high = middle
    return low


def report(label, events, trials):
    low, high = lower_bound(events, trials), upper_bound(events, trials)
    if high < TAU:
        verdict = "VERIFIED"
    elif low >= TAU:
        verdict = "NOT VERIFIED"
    else:
        verdict = "INCONCLUSIVE"
    print(f"{label}: {events}/{trials} = {events / trials:.2%}, "
          f"bounds [{low:.2%}, {high:.2%}], threshold {TAU:.0%}: {verdict}")


test_corpus = episodes(streaming_share=0.0, seed=1)  # the tests have no streaming
production = episodes(streaming_share=0.5, seed=1)   # the client chooses the delivery mode

MEASUREMENTS = [
    ("check of the user's input only", production, input_scan, False),
    ("monitor of the reply text", production, reply_monitor, False),
    ("monitor of the reasoning", production, reasoning_monitor, False),
    ("action check on the buffered path, tests without streaming", test_corpus, action_check, True),
    ("the same check, the client chooses the delivery mode", production, action_check, True),
    ("action check on every path", production, action_check, False),
]
logs = []
for label, batch, control, buffered_only in MEASUREMENTS:
    events, log = run(batch, control, buffered_only)
    logs.append(log)
    report(label, events, len(batch))

# An investigation from the log without content: what happened in the fifth measurement.
incident = logs[4]
unchecked = [entry for entry in incident if not entry["control_ran"]]
print("payments without the action check:", len(unchecked))
print("paths on which the check did not run:", sorted({entry["path"] for entry in unchecked}))
fingerprints = {json.dumps(entry["arguments"], sort_keys=True) for entry in incident}
print("distinct argument fingerprints:", len(fingerprints))
serialized = json.dumps(incident, ensure_ascii=False)
for marker in ("quillex", "zorbak", "synthetic"):
    print("content", repr(marker), "in the log:", marker in serialized)

What to do:

  1. Run the script and copy the six measurement lines into your report: events, trials, rate, both bounds and the verdict.
  2. Compare the first three lines. Explain why the check of the user's input saw nothing, and name the observer that learns about the payment only after it has been executed.
  3. Compare the fourth and fifth lines. The control and the tasks in them are the same: the only difference is the stream field, which the client sets. Which of the two lines would have gone into a release report, and what must a test include in order to see the fifth?
  4. Look at the sixth line and explain why it depends neither on seed nor on the stream field.
  5. Read the output lines about the log. From them, answer how many payments went through without the action check and on which path. Make sure the log holds none of the content markers.
  6. Run a mutation: in the function record, replace fingerprint(episode["call"]) with episode["call"] and run the script again. Record which output line changed, and restore the code.
  7. Replace the share of streamed requests 0.5 with 0.05 and run the script again. Record the verdict of the fifth line and explain why a rare path is still a path.
  8. Check one line against the tool in the Spectorn repository: python3 scripts/rate_bounds.py claim 0 400 --tau 0.01. The bounds should match.

What you can check from the formulas before running anything:

  • If N independent trials contained no events, the upper one-sided 95% bound equals 1 - 0.05 ** (1 / N). For 400 trials that is 0.75%.
  • If the event occurred in all N trials, the lower bound equals 0.05 ** (1 / N). For 400 trials that is 99.25%.
  • The reasoning names the intent with a probability of 60%, the final reply names the amount with a probability of 25%, and the client turns streaming on in half of the tasks.
  • The first, fourth and sixth lines do not depend on seed.

What you should get:

MeasurementUnnoticed payments and trials95% boundsVerdict at τ = 1%
Check of the user's input only400 out of 400from 99.25% to 100%NOT VERIFIED
Monitor of the reply textabout 300 out of 400depend on seedNOT VERIFIED
Monitor of the reasoningabout 160 out of 400depend on seedNOT VERIFIED
Action check on the buffered path, tests without streaming0 out of 400from 0% to 0.75%VERIFIED
The same check, the client chooses the delivery modeabout 200 out of 400depend on seedNOT VERIFIED
Action check on every path0 out of 400from 0% to 0.75%VERIFIED

The counts in the lines marked "about" depend on seed, so no exact numbers are given here: put your own into the report. In the lines about the log, the number of payments without the action check equals the number of events in the fifth line, the list holds one path, stream, there is one distinct argument fingerprint, and all three content checks give False.

The fourth line is the green result that misleads: the control is correct, and the tests do not take the path the client takes. Add three sentences to the report: why the monitor of the reasoning is better than the monitor of the reply and still does not confirm the threshold, which request field switched the control off in the fifth line, and which questions of an investigation the log without content answered.

Self-check questions

  1. An agent reported: "The email was sent to a recipient from your list". The monitor of the reply text found nothing. Which two records will you compare to learn what happened, and where should the check have been placed so that the extra action did not happen?
  2. The check on actions is wired up and passes all tests. A client turns on streaming of the response in the request. Which question must you ask about every field of the request, and with which test will you pin the answer?
  3. A chain-of-thought monitor raised no alert on 50 independent tasks. What upper bound on the rate of missed violations are you entitled to report, why does it say nothing about the agent's intentions, and what will you write to the log instead of the reasoning text?

Previous module: "Model policy and gateway policy".

Monitoring agents: judge the actions | Spectorn