Audit, Detection, and Incident Response
Design tamper-evident audit trails, build layered detectors that survive base rates, and run incident response with kill switches and evidence preservation.
Language AI HandbookAll chapters Audit, Detection, and Incident Response
A test account's agent has unexpectedly requested an external write. The responder opens the trace and sees a tool call, but the record leaves two questions unanswered. Which identity authorized it, and did the operation finish? Those answers determine whether to inspect a single approval or temporarily suspend the tool. This chapter shows how to preserve the evidence, distinguish a lead from an incident, and test a narrow containment decision on invented events.
Preventive controls set the conditions under which an operation can proceed. Audit records provide evidence about how those conditions were applied, what the gateway observed, and which facts still need independent confirmation.
That question has three parts, and they map to the three pillars of this chapter.
Auditing designs a record of consequential decisions and outcomes. A chain with a separately protected checkpoint helps detect changes to the committed sequence. Verify coverage and factual accuracy using independent observations.
Detection is about turning those records (and the live stream of events) into signals. It is the "what looks wrong" layer. Its central artifacts are anomaly scores, threshold policies, and the alerts they raise.
Incident response is about what you do once a signal fires or a report arrives. It is the "what we do now" layer. Its central artifacts are a kill switch, an evidence-preservation procedure, a containment and recovery playbook, and a post-incident review that feeds back into detection and prevention.
A chain can verify agreement with the snapshot committed at a protected checkpoint. Investigators still need evidence that an event was recorded and that its fields accurately describe the observed operation.
It is worth pausing on why these three pillars are grouped together in a single chapter rather than treated as three separate concerns. The reason is that they form a closed feedback loop, and a loop only works if every link is engineered to the same standard. Auditing without detection produces records nobody reads. Detection without auditing produces alerts you cannot explain or investigate. Detection without incident response produces signals nobody acts on. And incident response without auditing produces investigations with no evidence to examine. The three are also ordered in a specific way: detection reads the records that auditing produces, and incident response consumes the signals that detection produces, so the quality of each downstream pillar is bounded by the quality of the one before it. A brilliant detection program running on an incomplete audit trail will miss attacks; a disciplined response team working from noisy detectors will spend its energy on false alarms. Improving the pipeline at any point lifts everything that follows, which is why we treat the record design (the first pillar) with the most care.
There is a second reason for the grouping, one that has to do with the economics of security. Preventive controls are binary in the sense that they either block an action or allow it, and once they are deployed they either work or they don't on a given input. They offer no mechanism for getting better after launch, because a filter that blocks an attack today blocks the same attack tomorrow but says nothing about the attacks it has never seen. Detection and response, by contrast, are learning mechanisms. Every incident, every near-miss, every false alarm that a human triages teaches you something about the shape of the attacks your prevention layer missed, and that knowledge can be converted into new signatures, tighter permissions, and improved tests. A defense stack that contains only prevention is a defense stack that is frozen at the moment of its last update. A defense stack that contains prevention plus audit, detection, and response is a defense stack that improves for as long as the team is willing to do the work. That asymmetry is the entire justification for treating these pillars as first-class engineering concerns rather than as an afterthought bolted on for compliance.
These three words are used loosely in practice. Here we fix them:
- Logging is emitting records. Any system logs; it is a precondition, not a property.
- Tracing relates observed operations across components using trace context and, when captured, span or dependency relationships.
- Auditing records consequential actions with enough context for investigation. It requires evidence that records are emitted and protected, and responders use corroboration to establish what happened.
Routine logs can omit records during delivery or include details that should never enter a durable audit store. An audit design defines which events to capture and tests whether each known route emits its expected records.
A trace ID can group retrieval, tool invocation, and completion records associated with the same request. To establish that the tool consumed a particular retrieval result, inspect the recorded dependency and corroborate it with the execution record.
Why audit trails for agents are hard
An agent’s tool call can reflect earlier retrieval, an intermediate summary, and the policy in force at execution. The decision and the completed effect can appear in separate records.
A model’s explanation is evidence of what it reported. Investigators also need observations from the surrounding application, including which inputs were supplied, what output was returned, and what the gateway did.
This produces four concrete difficulties that shape everything in this chapter. We treat each in turn below.
The action-to-cause gap. A tool invocation may follow a retrieval several steps earlier. Record stage-level provenance so a responder can find the relevant retrieval result, summary, and subsequent decision even when the final prompt omits the original document.
Versioned references and dependency identifiers can preserve that lineage. When investigating a specific incident requires source content, collect only the approved content under the protected retention policy. A log of the final prompt alone leaves preceding stages unobserved.
Nondeterminism and reproducibility. A replay of the same input may produce a different output. Under temperature sampling, or even greedy decoding across model versions, a replay of the recorded input may not reproduce the recorded action. This means audit records must capture not just inputs but the decoding configuration and model version if you ever want to reason about "would this happen again." We discussed decoding configuration in Nucleus Sampling and model versioning matters everywhere in Evaluation Harnesses and Reproducibility.
A replay can diverge because sampling drew a different result, the recorded input was incomplete, or a version or runtime setting changed. Compare resolved conditions before attributing the divergence. A replay gives one observation that a responder can compare with contemporaneous records.
The volume and privacy tension. A prompt can include private documents or personal data. Storing prompts verbatim creates an additional sensitive data store. Record the minimum set of approved metadata needed for routine investigation, and specify when separately protected content may be collected.
A metadata tier can carry two pieces of evidence about a request without recording its text: which policy version ran and what decision it returned. Keep even those IDs and decisions behind access controls. For investigations that need content, define a separate collection policy that specifies which data may be captured, who may read it, and when to delete it.
Adversary access. The threat we worry about most is an adversary who has already compromised a component of the system. If that adversary can edit or delete audit logs, the entire detection layer is defeated, and worse, it gives you false confidence during response. Send the records to a sink whose write, deletion, and read privileges are independent of the agent's credentials.
The "off-box" part deserves emphasis because it is the part most likely to erode under operational pressure. If the audit sink is reachable with the same credentials the agent uses for its normal work, then an adversary who compromises the agent can rewrite the audit trail using those same credentials. The sink must sit behind a separate authentication boundary, ideally one the agent has no path to at all, reached only through a one-way export that the agent cannot read back. This is an instance of the general least-privilege principle applied to the audit system itself: the audit system is a system with its own trust boundary, and its credentials must be as carefully scoped as any other.
Each of these difficulties gets its own treatment below.
Designing the audit record
An audit event should identify the observed action and give a responder a way to find supporting evidence. Record an authorization decision separately from the evidence that its operation completed.
For each event, ask which identifiers will still resolve after the original investigation window. Record how to join related events across services and how to find the policy version that applied.
Every event should carry a common envelope plus type-specific fields. The common envelope is what lets you chain, correlate, and trust the records. It contains:
event_id: a unique event identifier (for example, a UUID generated for each event) so records can be cross-referenced.trace_id: a correlation identifier for events recorded under the same request or interaction. Record dependency links separately when the investigation needs them.timestamp: an event timestamp in UTC, plus receipt time or source-clock information when useful.actor: the principal that caused the event. Critically, agents have two principals: the requesting or delegating principal and the authenticated execution identity. Record both when delegation exists, because attribution questions ("did the user ask for this, or did the agent decide it?") are exactly the ones that matter in incidents. We covered this delegation structure in Identity, Authorization, and Least Privilege.action_type: a controlled-vocabulary label (retrieval,tool_call,model_completion,policy_decision,human_approval,credential_use,data_egress).decision: an inert enum label such asallow,deny,escalate. Storing the label rather than prose is what makes the trail machine-queryable.prev_hashandrecord_hash: the chaining fields we define next.
The requester and the executing identity may differ. Their identifiers help a responder retrieve the authorization grant and compare its scope with the observed operation. The policy and execution records provide the evidence for that comparison.
The decision field being an inert enum label rather than a prose string is also deliberate. A prose string ("looks fine to me") is not queryable, not comparable, and not aggregatable. An enum label (allow, deny, escalate) is queryable and aggregatable, which is what lets detection count denials per actor per hour and lets the response layer filter to a single decision class. The vocabulary must be controlled, meaning it lives in a shared schema rather than being composed ad hoc at each call site, so that "deny" means the same thing everywhere and new decisions cannot be smuggled in under near-synonyms.
For a tool_call, record the tool name, approved argument references or scoped digests, and the authority used. For retrieval, record an approved query reference when useful, returned document IDs and available provenance. Capture query content only under the protected retention policy. A policy_decision event records the decision and the policy version that produced it. Dataset Lineage and Provenance covers how to preserve provenance across stages.
Use an allowlist for queryable fields. When equality checks on approved arguments are necessary, use a keyed digest with an explicit key scope and rotation plan. An ordinary digest of a short list of possible values can reveal the original through guessing. OWASP Logging Cheat Sheet
What counts as "consequential"
A common failure is to log everything (trillions of token-level events) and then drown. The audit trail should capture consequential actions: state changes, external effects, permission uses, data egress, and the decision points that led to them. Token-level logging is a debugging concern, not an audit concern. The design principle is: if a competent responder would need to cite this event to reconstruct who did what and why, it belongs in the audit trail; if it is only useful for tuning, it does not.
The trap is that "log everything" feels safer than "log selectively," because logging everything cannot omit something important. But the feeling is deceptive for two reasons. First, volume destroys signal: an audit trail with a million token-level events per user turn is one in which no responder can find the three consequential events that matter, and practical detection becomes impossible. Second, "log everything" silently imports the privacy and storage problems at full severity, because the full context window now dominates the log volume and the sensitive-data store grows without bound. The selective principle is harder to apply than "log everything," because it requires making a judgment about consequence, but it produces a trail that is at once more useful and more defensible.
The judgment "consequential" can be made reliably by asking a single question of each candidate event: could this event change the answer to "what did the agent do and why" in an investigation? A tool call changes the answer. A retrieval changes the answer. A decision to deny changes the answer. A token sampled inside a completion does not change the answer, because the completion's outcome is already recorded by the model_completion event; the token stream is how that outcome was produced, not what it was. When the boundary is ambiguous, the tie goes to including the event, because a slightly verbose trail is recoverable by filtering and a missing event is not recoverable at all.
Tamper-evident chaining
A hash chain commits each record to the preceding digest. Verification can detect a payload edit or a missing interior record when the subsequent links remain in the supplied log. Use a protected checkpoint at the expected end to detect a shorter but internally consistent prefix.
Let an audit record have payload and hash . Hash the previous digest followed by the serialized payload bytes. This commits each record to the preceding one in the stored sequence.
where:
- is the serialized payload of record .
- is the stored digest of the preceding record, or at the start of the chain.
- is the digest stored for record .
- : a collision-resistant hash function (SHA-256 in practice)
- : byte concatenation
- is the fixed initial digest, called the genesis value. The independently saved checkpoint is a separate reference to a later digest.
The recursion makes each record depend on all records before it: changing any for propagates forward and changes every subsequent . Each stored record contains . Verification recomputes each from the stored and stored and checks it matches the stored , and separately checks that each record's stored equals the previous record's stored .
The two checks in verification address different failures. Recompute the digest from the stored payload and previous digest to check the record. Compare each stored previous digest with the preceding record’s digest to check the link. A missing interior record breaks a surviving neighbor’s link. If records are removed from the end, no later link remains to check. Compare the result with the checkpoint for the expected prefix or snapshot.
This chain has three properties that matter, and one limitation that matters more.
Ordering. Because record commits to , records form a strict sequence. You cannot insert a record between two existing ones without recomputing all subsequent hashes, which changes the final head hash.
Tamper evidence within the middle. Modifying the payload of record changes , which no longer matches the stored value. If the stored hash is updated alone, the next record still points to the old digest. So any edit to a middle record is locally detectable.
Save a checkpoint containing the log identity, record count, and head digest in an independently protected location. An exact snapshot can be checked against the checkpoint for the same position. A log that has grown since the checkpoint can verify its prefix up to that position, while later records remain outside that checkpoint.
For example, a checkpoint written at record 100 still verifies that prefix after the log reaches record 110. If the supplied snapshot ends at record 106, the checkpoint alone cannot establish that four later records are missing.
A hash chain proves only integrity relative to history: that the records shown are the records that were committed, in that order, up to the last pinned head. It does not prove the following:
- Truthfulness. The agent or its instrumentation can commit a false record faithfully. A record saying
decision: allowfor an action that was denied, or atool_callrecord with falsified arguments, hashes perfectly. - Completeness relative to reality. If a component never emits an event, the chain has no gap inside itself; it is silent about what it never saw. Omission of an entire class of events (say, a tool that bypasses the instrumentation wrapper) leaves a perfectly valid chain that simply does not mention those actions. Completeness must be argued at the instrumentation level and tested by probing, not proven by the chain.
- Correctness of the clock. Timestamps are attacker-influenced if the clock is. Ordering is cryptographically enforced; wall-clock times are only as trustworthy as the time source.
- Whether the emitter reported an operation accurately. An independent append-only sink can protect stored records. Corroborate the record with separately collected observations from the relevant tool or gateway, because hashing the emitter’s version preserves its contents.
Chaining raises the cost of silent tampering. It does not raise the cost of lying.
A cryptographically consistent log can contain false reports or omit an operation. Keep independent permissions on the log sink and compare key records with observations from the tools or gateway. Use collection and source-clock information to distinguish an ordering guarantee from a timing estimate.
Worked example: chaining and verifying a small trail
Let us make this concrete. We build an in-process chain over a handful of invented events, verify a clean chain, then show precisely which record detects a single-field edit and what the head hash reveals about truncation.
PythonIn [3]Expand
import hashlib
import json
def h(prev_hex: str, payload: dict) -> str:
# Canonical serialization is essential: dict ordering must not affect the hash.
body = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode(
"utf-8"
)
return hashlib.sha256(bytes.fromhex(prev_hex) + body).hexdigest()
GENESIS = hashlib.sha256(b"handbook-audit-genesis").hexdigest()
def build_chain(events):
chain, prev = [], GENESIS
for ev in events:
prev_hash, rec_hash = prev, h(prev, ev)
chain.append(
{"payload": ev, "prev_hash": prev_hash, "record_hash": rec_hash}
)
prev = rec_hash
return chain
def verify_chain(chain, pinned_head=None):
prev = GENESIS
for i, rec in enumerate(chain):
if rec["prev_hash"] != prev:
return False, f"link broken before record {i}"
if h(rec["prev_hash"], rec["payload"]) != rec["record_hash"]:
return False, f"payload altered at record {i}"
prev = rec["record_hash"]
if pinned_head is not None and prev != pinned_head:
return False, "head does not match pinned head (truncation/rewrite)"
return True, "ok"The canonical serialization step inside h is worth a note. The payload is a dictionary, and dictionaries in Python preserve insertion order, so two payloads with the same key-value pairs but different insertion orders would serialize to different byte strings and hash differently. Canonical serialization (sorted keys, compact separators, UTF-8 encoding) removes this source of spurious divergence, so the same logical payload always produces the same hash regardless of how the dictionary was constructed. Without canonical serialization, the chain would be fragile against harmless refactoring and would produce false tamper alarms, which would train responders to ignore the alarm. Canonical serialization is the audit-system equivalent of pinning a dependency version: it makes the hash a function of the content, not of incidental construction details.
We now create four invented events. The labels and IDs are deliberately generic and inert.
The events below are committed in order: a retrieval, then a model_completion, then a tool_call, then a policy_decision. Each carries a decision label and type-specific fields. build_chain serializes each payload canonically (sorted keys, compact separators), prepends the previous hash, and hashes the concatenation, producing the triples described above.
PythonIn [4]Expand
events = [
{
"trace_id": "t-001",
"action_type": "retrieval",
"decision": "allow",
"doc_ids": ["d-77"],
},
{
"trace_id": "t-001",
"action_type": "model_completion",
"decision": "allow",
"model": "demo-1",
},
{
"trace_id": "t-001",
"action_type": "tool_call",
"decision": "allow",
"tool": "mock_transfer",
},
{
"trace_id": "t-001",
"action_type": "policy_decision",
"decision": "escalate",
"policy": "egress-v2",
},
]
chain = build_chain(events)
pinned_head = chain[-1]["record_hash"]The four fictional events cover the retrieval, completion, policy decision, and tool-call labels. The following checks use them to illustrate an edited middle record and a shorter prefix.
PythonIn [5]Expand
# Deliberately change the third synthetic record without recomputing its digest.
tampered = [dict(record, payload=dict(record["payload"])) for record in chain]
tampered[2]["payload"]["decision"] = "deny"ConsoleOut [6]Expand
Clean chain : (True, 'ok') Head hash : a879e6a75ddb1496 ... Edited chain: (False, 'payload altered at record 2') Truncated : (False, 'head does not match pinned head (truncation/rewrite)')
The clean chain verifies and its head is pinned. Editing a single decision label in record 2 breaks verification at that record (payload altered), so the responder knows exactly where to look. Truncating the last record leaves a perfectly self-consistent chain with no internal error, but its head no longer equals the pinned head, so the external pin catches it. This is why the pin matters: without pinned_head, the truncated chain would have verified as "ok."
Run the same verification over the three fixtures, once without the saved digest and once with it. The shorter prefix is valid on its own and fails when compared with the head of the four-record snapshot.
PythonIn [7]Expand
chain_checks = [chain, tampered, chain[:-1]]
check_labels = ["Unchanged", "Edited record", "Shorter prefix"]
internal_checks = [int(verify_chain(records)[0]) for records in chain_checks]
pinned_checks = [
int(verify_chain(records, pinned_head)[0]) for records in chain_checks
]
internal_x = [i - 0.10 for i in range(len(check_labels))]
pinned_x = [i + 0.10 for i in range(len(check_labels))]VisualizationOut [8]Expand

Scaling tamper evidence: Merkle trees and transparency logs
Checking every record of a linear chain takes one hash per record. A Merkle tree over an ordered batch lets a verifier check one entry against a trusted root using an inclusion proof. An append-only tree can also supply a consistency proof that shows the smaller tree is a prefix of a larger tree. RFC 9162, Sections 2.1.3 and 2.1.4
For a balanced binary Merkle tree, the verifier needs at most one sibling hash per level. Doubling the number of leaves adds one level to a complete tree. Recomputing a full root from every original record still requires work proportional to the size of the batch.
Detecting inconsistent views requires observers to compare what they received or rely on an independent witness. Inclusion and consistency proofs on one observer’s view validate that view against the heads it received.
Detection: turning events into signal
If the audit trail is the "what happened" layer, detection is the process of interrogating it live and at rest to find events that shouldn't be there. Detection is fundamentally a classification problem with a severe base-rate problem, and understanding the base rate is the difference between a detector that works and one that buries analysts in noise.
Batch detectors examine records after collection, for example to compare changes in granted permissions over a month. Streaming detectors consume observations shortly after they occur. A streaming alert can prompt a responder to check a permission decision quickly. Whether it can stop an action depends on when enforcement runs and what control the responder can invoke.
The base-rate trap
Suppose 1 in 100,000 actions in a fictional deployment is positive. Among 10 million actions that leaves 100 positives and 9,999,900 negatives. At a 1% false-positive rate, expect 99,999 false alerts. If the detector finds all 100 positives, precision is about 0.10%.
At 90% recall, the same detector would find 90 positives and precision would fall to about 0.090%. These are expected counts under the stated rates. A deployed alert policy also needs an estimate of the investigation workload at those rates.
The practical consequences are structural:
- Prefer high-precision signals even at low recall. A detector that fires on a narrow, structural signature (for example, an egress event whose destination was not pre-approved) may yield high precision if the narrow condition rarely occurs among benign events. Statistical anomaly detectors with high recall are used to generate leads for triage, not to page humans directly.
- Layer detectors. A cheap, high-recall anomaly scorer feeds a triage step; only triage outputs page a human. This is the "detection engineering" model from mature security operations.
- Calibrate against your own base rate. A generic benchmark of anomaly-detection AUC tells you almost nothing about precision at your prevalence. You must estimate the base rate in your deployment (even crudely) and compute the achieved precision.
Track all three quantities separately. The arrival rate sets how many alerts a team might receive, precision estimates how many flagged events are true positives, and recall estimates the share of all positive cases the system catches.
Families of detectors
There is no single "anomaly detection." Four families recur, and they trade off in characteristic ways.
Signature / rule detectors match structural patterns: "tool call to a destination not in the approved allowlist," "credential used outside business hours," "retrieval from a document whose provenance is untrusted followed by an egress tool." These are high-precision and cheap, but they only catch what you anticipated: they encode your threat model, not the unknown. They are the backbone, not the whole solution.
A narrow rule makes its trigger easy to inspect. Its precision still depends on whether benign activity can produce the same pattern and on the share of positive events in the population.
Threshold detectors on a single scalar page when some measured quantity crosses a limit: tokens of context consumed per minute (a cost/denial signal), number of external endpoints touched per session (a lateral-movement signal), count of denied policy decisions per actor per hour (a probing signal). Simple and explainable, but brittle at the boundary and blind to combinations.
A responder can compare a measured value with its cutoff. A legitimate workload can cross that cutoff, while incomplete records can leave concerning activity outside the observed population. Test thresholds on benign traffic and check which events and time windows the detector sees.
Statistical and distance anomaly detectors model "normal" and flag deviations. A classic, interpretable choice is the robust z-score using median and median-absolute-deviation (MAD), which is far less sensitive to outliers than mean and standard deviation. For multivariate behavior you use nearest-neighbor distance, isolation forests, or a learned density model. These catch the unanticipated, but their scores are hard to calibrate and they inherit the base-rate problem.
A statistical detector can flag a deviation without an existing signature for that behavior. The robust score estimates location with the median and scale with the median absolute deviation. The ordinary z-score uses the mean for location and the standard deviation for scale. A single extreme observation can move both the sample mean and sample standard deviation significantly, while the median and median absolute deviation use ranks and are less sensitive to a small number of extreme observations. Estimate the false-positive rate on benign cases, including unusual but valid activity.
Sequence / provenance detectors look for a specified order of event categories within one trace. For example, inspection can flag an external action that follows retrieval from a source labeled untrusted. The records establish the order of observed events. Additional evidence is needed to establish why the action was proposed or whether it complied with policy.
Check a rule's precision against legitimate traces, including normal workflows that produce its event sequence. Missing or inaccurate source labels also reduce what the rule can infer. The toy classifier below uses synthetic labels so we can inspect those conditions directly.
We will implement the robust-z threshold detector and a sequence/provenance detector below, because together they illustrate the two extremes: statistical breadth and structural precision.
Worked example: robust-z anomaly scoring on invented metrics
We generate a batch of invented per-session metrics (all benign, synthetic) and inject a few obvious outliers to stand in for anomalous sessions. Then we score every session with a robust z-score and apply a threshold. The point is to watch precision behave as we move the threshold, illustrating the base-rate math in code.
The choice of a robust z-score rather than a standard z-score is driven by the shape of the data. Egress volume per session is typically heavy-tailed: most sessions transfer small amounts, a few transfer large amounts legitimately, and the rare malicious session transfers an extreme amount. Under that distribution the standard z-score, which uses the mean and standard deviation, is dragged upward by the heavy tail, so the baseline is inflated and the extreme session no longer looks so extreme. The median and MAD, by contrast, are determined by the bulk of the distribution and only weakly influenced by the tail, so the extreme session stands out. Robust scoring is what makes the threshold meaningful when the data has the heavy-tailed shape that most security metrics have.
The median absolute deviation is:
where:
- : the -th observed value of the metric
- : the median of all observed values
- : the absolute deviation of each value from the median
- over those deviations: the robust estimate of spread,
A z-score built from it is:
where:
- : the robust z-score for observation
- : the -th observed value of the metric (for example, egress volume for one session)
- : the median of all observed values, a robust estimate of the typical value
- : the absolute deviation of each value from the median
- : the median of those absolute deviations, a robust estimate of spread
- : a scaling constant so that, for normally distributed data, the -based scale corresponds to the standard deviation
We do not assume normality for correctness, since MAD just gives a robust spread estimate, but the 0.6745 constant keeps magnitudes comparable to familiar z-scores. Without it, the same spread would be reported on a different scale, making threshold choices harder to reason about.
For a normal population, the median absolute deviation is about times its standard deviation. Dividing the sample MAD by , or multiplying it by approximately , gives the scale in the denominator of the example. The synthetic data are skewed, so a score of 8 means eight scaled-MAD units above the median. It carries no Gaussian tail-probability interpretation in this example.
PythonIn [9]Expand
import numpy as np
rng = np.random.default_rng(7)
# 4,000 benign sessions: mostly typical, log-ish egress volume in KB
n_benign = 4000
egress_benign = np.clip(
rng.lognormal(mean=2.0, sigma=0.5, size=n_benign), 0, None
)
# 12 anomalous sessions with far larger egress
n_anom = 12
egress_anom = rng.uniform(1500, 5000, size=n_anom)
egress = np.concatenate([egress_benign, egress_anom])
is_anom = np.concatenate([np.zeros(n_benign, bool), np.ones(n_anom, bool)])
def robust_z(x):
med = np.median(x)
mad = np.median(np.abs(x - med))
scale = 1.4826 * mad # 1/0.6745, avoid division by the constant
return (x - med) / (scale if scale > 0 else 1.0)
scores = robust_z(egress)The synthetic data mirrors the realistic shape: 4,000 benign sessions drawn from a lognormal (heavy-tailed) distribution and 12 anomalous sessions drawn from a uniform distribution far to the right. The is_anom boolean array records the ground truth, which is what lets us measure precision and recall below; in a real deployment you do not have this array, which is precisely the problem the base-rate section discusses.
ConsoleOut [10]Expand
Median egress (KB): 7.3 Anomaly score range: -1.72 to 1290.75 threshold z> 5: flagged= 43 precision= 0.28 recall= 1.00 threshold z> 8: flagged= 15 precision= 0.80 recall= 1.00 threshold z>12: flagged= 12 precision= 1.00 recall= 1.00
At a threshold of 5 the detector finds all 12 anomalies and flags 31 benign sessions. That is 12 true positives among 43 alerts, or about 28% precision. The threshold of 8 yields 12 true and three false positives. All three thresholds happened to catch every anomaly because the fixture’s positives are far above the benign bulk.
PythonIn [11]Expand
def precision_at_prevalence(tpr, fpr, prevalence):
# Bayes: P(anom | flagged) = tpr*prev / (tpr*prev + fpr*(1-prev))
denom = tpr * prevalence + fpr * (1 - prevalence)
return (tpr * prevalence / denom) if denom else float("nan")
# Use the z>8 operating point; measure its rates on our synthetic batch
thr = 8
flagged = scores > thr
tpr = (flagged & is_anom).sum() / is_anom.sum()
fpr = (flagged & ~is_anom).sum() / (~is_anom).sum()ConsoleOut [12]Expand
Measured TPR=1.000 FPR=0.0008 prevalence=1e-02: precision=0.931 prevalence=1e-03: precision=0.572 prevalence=1e-04: precision=0.118 prevalence=1e-05: precision=0.013
Holding the fixture rates fixed, precision is about 11.8% at prevalence and about 1.3% at . These are hypothetical deployments. If production traffic changes which events are flagged, estimate the conditional rates again before applying this calculation.
A single curve holds the fixture’s false-positive and true-positive rates fixed. The marker shows the fixture's own prevalence, about 0.003, and its 80% precision at the chosen threshold.
PythonIn [13]Expand
prevalence_grid = np.geomspace(1e-6, 1e-1, 100)
measured_curve = [
precision_at_prevalence(tpr, fpr, prior) for prior in prevalence_grid
]
measured_fixture_prevalence = is_anom.mean()
measured_fixture_precision = precision_at_prevalence(
tpr, fpr, measured_fixture_prevalence
)VisualizationOut [14]Expand

Use broad anomalies as leads and test which structural checks or triage steps improve alert quality on your own traffic.
The curves in the next figure hold recall constant and vary the false-positive rate. Each curve applies the same Bayes calculation to a different hypothetical deployment prevalence. The measured point belongs to the synthetic fixture.
VisualizationOut [16]Expand

The numerator in precision_at_prevalence is the true-positive rate multiplied by prevalence. The denominator also includes the contribution from false positives. In this figure, lowering the false-positive rate improves precision wherever prevalence and recall are held fixed and both positive and negative cases are present. In deployment, a stricter rule can also lower recall. Measure both rates and the prevalence of the cases evaluated.
Worked example: a provenance/sequence detector
The sequence detector flags an invented trace in which external action follows a retrieval labeled untrusted. The application can also legitimately produce that sequence. Treat a match as a lead, and check the recorded authorization and outcome before declaring an incident.
The trace identifier limits the demonstration to one run. Production investigators may also need authenticated principal, timestamps, exact execution outcomes, and links to related runs to assess whether two events belong to the same incident.
PythonIn [17]Expand
from dataclasses import dataclass, field
@dataclass
class Trace:
trace_id: str
events: list = field(default_factory=list)
def classify(trace):
# inert, invented provenance and effect labels only
got_untrusted = False
for ev in trace.events:
if (
ev["action_type"] == "retrieval"
and ev.get("provenance") == "untrusted"
):
got_untrusted = True
if (
got_untrusted
and ev["action_type"] == "tool_call"
and ev.get("side_effect") == "write"
and ev.get("dest") == "external"
):
return "flag:untrusted_to_egress"
return "clear"
# Invented traces; no payloads, just structural labels
traces = [
Trace(
"t-100",
[
{"action_type": "retrieval", "provenance": "trusted"},
{
"action_type": "tool_call",
"side_effect": "write",
"dest": "external",
},
],
),
Trace(
"t-101",
[
{"action_type": "retrieval", "provenance": "untrusted"},
{
"action_type": "tool_call",
"side_effect": "read",
"dest": "internal",
},
],
),
Trace(
"t-102",
[
{"action_type": "retrieval", "provenance": "untrusted"},
{"action_type": "model_completion"},
{
"action_type": "tool_call",
"side_effect": "write",
"dest": "external",
},
],
),
]The classify function walks the ordered fixture and tracks whether it has seen a retrieval labeled untrusted. It stops at the first matching sequence and returns a fixed category label. This return value gives neither a matching event index nor an alert time.
ConsoleOut [18]Expand
t-100: clear t-101: clear t-102: flag:untrusted_to_egress
Fixtures t-100 and t-101 each contain one part of the sequence and therefore return clear. Fixture t-102 contains both in the specified order and returns the category label. A clear result means the supplied records did not match this rule.
For a deployment test, include normal workflows with the same observed sequence and traces with incomplete provenance. A match provides a lead for investigation. Use event records and the applicable policy to determine whether the action was authorized and whether it completed.
From detectors to alert policy
Raw detector scores are not alerts. An alert policy decides when a combination of signals warrants human attention, and it must be designed for the triage workflow:
- Correlate before paging. Aggregate per trace and per actor. Twelve robust-z hit events in one trace is one alert, not twelve.
- Require corroboration for statistical signals. Test whether corroboration from another source reduces unnecessary pages at an acceptable recall. Use labeled observations to estimate the joint rates.
- Encode severity. Check the policy in force at the time and corroborate the recorded destination and execution result. A verified policy-disallowed effect merits investigation at the severity defined for that effect.
- Version the policy. Alerts must record the detector and policy version that produced them, exactly as Evaluation Harnesses and Reproducibility argues for evaluation, or you cannot later explain why a real incident produced no page.
If two detectors are conditionally independent among benign events, false-positive rates of 1% and 0.1% give a joint rate of 0.001% when both must fire. For precision, also measure the joint true-positive rate. Shared inputs can correlate the signals, so estimate both joint rates on labeled data before turning an AND rule into a page.
Recognize that "is my detector good?" is the same question as "is my benchmark good?" from Benchmark Design and Evaluation Challenges. You need labeled incident data to measure precision and recall, and that data is rare, adversarial, and distribution-shifting. Detector metrics measured on last year's incidents understate next year's attacks. Treat detector quality as a live, drifting quantity, not a one-time certification.
Incident response
NIST SP 800-61 Rev. 3 puts preparation, detection, response, and recovery within ongoing risk management. This example uses a small ordered timeline to make its response decisions visible. Live teams may carry out preservation, scoping, and containment concurrently.
The initial signal can be wrong, and the scope may be unclear. Assign ownership early so preservation, containment and investigation can start when needed. Keep a record of the evidence used and revisit the decision as the scope becomes clearer.
The lifecycle
1. Triage and declaration. Confirm the signal is real enough to act on, assign severity, and name an incident commander. The hardest call is declaring early enough to contain without crying wolf; a documented severity rubric resolves it in advance so nobody negotiates at 3 a.m.
The naming of a single incident commander is not ceremony; it is what resolves the coordination problem that otherwise paralyzes a response. Without a commander, responders each pursue their own hypothesis, edit each other's changes, and duplicate work, and the incident proceeds at the speed of the slowest conversation. With a commander, one person decides priorities and the rest execute, which is dramatically faster. The severity rubric exists so the commander's first decision (how seriously to take the signal) is made against a written standard rather than against the pressure of the moment.
2. Evidence preservation. Capture relevant evidence promptly. Record who collected it, when, where it came from, and how its integrity is checked. Keep controlled read access and preserve the originals. Copies of the current policy version, independent audit checkpoints, and tool outcomes can help reconstruct the event. OWASP Logging Cheat Sheet
Containment actions can change the state investigators need. Capture that state first when it is safe to wait. During ongoing harm, start containment immediately and preserve what you can in parallel or as soon as conditions allow.
Assign preservation and containment to different responders when both need to proceed quickly. Note any evidence that became inaccessible after containment so the investigation can account for the gap.
3. Containment. Limit blast radius without destroying the ability to investigate. The primary tool is the kill switch, which we discuss next. Containment options, roughly in order of increasing disruption: revoke a specific credential, disable a specific tool/skill, quarantine a session or actor, roll back to a known-good model/policy version, and finally suspend the whole agent system.
Choose the smallest containment action that can interrupt the harm under the evidence you have. An independently confirmed single-credential incident may call for revoking only that credential. When scope is uncertain and harm is ongoing, start containment promptly. Preserve evidence in parallel if possible and revisit the affected scope as records become available.
4. Investigation / scope determination. Now use the preserved evidence to answer the questions: what happened, on whose behalf, why (which inputs), how far did it spread (other traces, actors, resources), and is it still happening? This is where the audit trail earns its cost; if you cannot answer scope from the trail, the incident is open-ended and you treat the blast radius as "everything the agent could touch."
The phrase "treat the blast radius as everything" is the conservative default that governs an investigation with incomplete evidence. If the trail cannot bound the incident, you cannot assume it was small; the prudent course is to assume the maximum plausible scope and spend containment effort accordingly. This is expensive, which is precisely why a complete audit trail pays for itself: a trail that answers the scope question converts an expensive worst-case response into a cheap targeted one.
5. Recovery. Address the failure, restore narrow permissions first, and verify both the intended service behavior and its authorization checks. Use the original detector as one signal and check for new or unrelated failures during the canary.
6. Post-incident review and learning. A blameless retrospective that produces concrete, tracked changes: a new detector or signature, a tightened permission, a documentation fix, a test that reproduces the incident (as a defensive fixture). Detection improves in this step or it doesn't improve at all.
The blameless framing is not a courtesy; it is what makes the review useful. If the review is about assigning fault, participants will withhold information to protect themselves and the review will produce a comfortable narrative rather than an accurate one. If the review is about producing changes, participants will share what actually happened, and the output is a set of tracked changes that make the next incident less likely or less costly. The tracked-changes discipline is what distinguishes a review that improves the system from a review that merely commemorates it: a finding with no owner and no due date is a finding that will recur.
The kill switch
A kill switch is a pre-authorized control for suspending agent activity. Decide which actions it covers, who can use it, and how fast it must take effect. Test those conditions before relying on it.
- Granularity. A single global off-switch is easy to reason about but over-broad: killing everything for one bad session destroys legitimate work and trains operators to avoid using it. A tiered switch (per actor, per tool, per tenant, global) lets containment match blast radius.
- Authority and pre-authorization. Someone must be authorized in advance to throw the switch, and it must not require a change review. At 3 a.m. you cannot convene a committee. Pre-authorize a named on-call role.
- Fail-safe by default. Choose a failure policy for each class of action. For high-impact outbound writes, an unavailable authorization control can fail closed while independent read-only functions remain available. If the switch's own control plane is compromised or unreachable, the safe behavior is to halt, not to run. This is the hardest property to get right because it trades availability for safety, and it must be an explicit, documented decision.
- Tested. An untested kill switch is a hope. It must be exercised on a schedule in a drill, exactly as live evaluation exercises agent harnesses.
- Reversible with verification. Resuming is as dangerous as stopping. Resume only after recovery verification via detectors, and resume at reduced scope first.
The "train operators to avoid using it" point in the granularity bullet is the subtle one. A switch that causes unacceptable collateral damage when thrown is a switch that operators learn not to throw, so the switch fails at the moment it is most needed. Granularity is what keeps the switch usable: an operator who can halt one tool without halting the entire system will throw the switch readily, so the tiered switch is thrown more often than the global one even though it is more complex, and being thrown is what makes it effective.
Place suspension enforcement outside the model or agent process. A gateway can consult independent policy before permitting the covered operation. Test each route that can perform that operation, including retries or queued work that might have started earlier.
Recovery, rollback, and verification
When recovery includes a rollback, identify the known configuration and check that the release is compatible with it. Re-enable a bounded canary and collect authorization failures, content or action regressions, and service-health signals. A quiet canary is evidence about that selected slice and observation period.
Set a canary observation window and conditions for continuing, stopping, or narrowing the rollout. Check the original incident indicator alongside independent service and authorization checks. A short window may contain too few cases to assess a rare failure.
Code implementation: a small, end-to-end response harness
We now assemble the pieces into a compact, deterministic, in-process harness using only invented fixtures. It demonstrates the policy layer, the kill switch as an external enforced flag, and an incident timeline: the operational glue that connects detection to response. There are no payloads, credentials, or live targets; every record is synthetic and every label is inert.
The ControlPlane supplies a decision to the mock gateway. The Responder records the incident timeline. The coverage check submits only the supplied mock tool labels through that gateway.
The gateway writes a reduced event mapping with an action type, a mock tool label, a decision, and a reason. The full audit envelope above would also require event and trace identifiers, time, principals, and chain fields. This fixture exercises the decision boundary with a shared in-process object.
PythonIn [19]Expand
from dataclasses import dataclass, field
INERT_DECISIONS = {"allow", "deny", "escalate"}
@dataclass
class ControlPlane:
# In a real deployment this is external state (a gateway/sidecar config),
# not something the agent holds. Here it is a shared object for the demo.
global_halt: bool = False
halted_tools: set = field(default_factory=set)
allowed_tools: set = field(
default_factory=lambda: {"mock_read", "mock_transfer"}
)
def permit(self, tool: str):
if self.global_halt:
return "deny", "global_halt"
if tool in self.halted_tools:
return "deny", "tool_halted"
if tool not in self.allowed_tools:
return "deny", "not_authorized"
return "allow", "ok"
def gateway_action(control, tool, audit):
decision, reason = control.permit(tool)
assert decision in INERT_DECISIONS
audit.append(
{
"action_type": "tool_call",
"tool": tool,
"decision": decision,
"reason": reason,
}
)
return decisionThe permit method checks the global flag first, then the named tool’s hold, and finally the allowlist. This gives a defined reason when several checks could deny the same mock label. The assert in the gateway checks a fixture invariant. Python can omit assertions in optimized mode. Implement required runtime enforcement with explicit checks at the production authority boundary.
Next, a thin responder that ties the chained audit (reusing build_chain and verify_chain from earlier) to the control plane, and a timeline builder. The responder exposes exactly the operations the lifecycle requires: preserve, contain, investigate, and recover.
PythonIn [20]Expand
class Responder:
def __init__(self, control, audit):
self.control = control
self.audit = audit
self.pinned_head = None # frozen at preservation time
self.evidence_snapshot = None # independent local copy of the trail
self.timeline = []
def _stamp(self, step, detail=""):
self.timeline.append({"step": step, "detail": detail})
def preserve(self):
from copy import deepcopy
self.evidence_snapshot = build_chain(deepcopy(self.audit))
self.pinned_head = (
self.evidence_snapshot[-1]["record_hash"]
if self.evidence_snapshot
else GENESIS
)
self._stamp("preserve", f"head={self.pinned_head[:8]}")
def contain_global(self):
self.control.global_halt = True
self._stamp("contain", "global_halt_enabled")
def contain_tool(self, tool):
self.control.halted_tools.add(tool)
self._stamp("contain", f"tool_halted:{tool}")
def investigate(self):
ok, _ = verify_chain(self.evidence_snapshot, self.pinned_head)
if not ok:
self._stamp("investigate", "integrity_check_failed")
return False, None
denies = sum(
1
for e in self.evidence_snapshot
if e["payload"].get("decision") == "deny"
)
self._stamp("investigate", f"integrity={ok} denies={denies}")
return ok, denies
def recover(self, tool):
self.control.halted_tools.discard(tool)
self._stamp("recover", f"tool_restored:{tool}")The snapshot copies the local event dictionaries, including nested values, before it builds the chain. The saved digest is kept separately in the responder object to show the verification procedure. In a deployment the snapshot and checkpoint need independent storage and access controls. This local object has no write-once enforcement.
The example permits a mock write, saves the record, and temporarily suspends that tool. After checking the snapshot, it clears the narrow local hold and exercises the same mock action. Every operation is an in-process label.
PythonIn [21]Expand
control = ControlPlane()
audit = []
# Normal operation: an action the policy permits
gateway_action(control, "mock_transfer", audit)
gateway_action(control, "mock_read", audit)
# Detection signal -> declare incident, then respond in lifecycle order
resp = Responder(control, audit)
resp.preserve() # FIRST: freeze evidence
resp.contain_tool("mock_transfer")
# Post-containment attempt must now be denied by the gateway
post = gateway_action(control, "mock_transfer", audit)
ok, denies = resp.investigate()
if not ok:
raise RuntimeError("Preserved snapshot did not match its checkpoint.")
resp.recover("mock_transfer")
restored = gateway_action(control, "mock_transfer", audit)
assert post == "deny" and restored == "allow"ConsoleOut [22]Expand
Post-containment decision: deny After fixture recovery: allow Incident timeline: preserve head=72c0dc73 contain tool_halted:mock_transfer investigate integrity=True denies=0 recover tool_restored:mock_transfer Evidence integrity : True Denials in snapshot: 0 Preserved snapshot still verifies: True
Preservation happens before containment in this replay. The saved snapshot contains the two events already recorded when the hold is applied. The next mock request is denied and logged separately in the live list. Investigation verifies the saved snapshot against its stored head and counts denials in that snapshot.
The snapshot has zero denials because it contains only two earlier permitted events. The mock tool denial appears in the live list after that snapshot. The second integrity check confirms that the copied prefix still matches the saved digest.
Making the snapshot complete relative to reality
The chain check establishes that the preserved snapshot agrees with its pinned head. A route that never emitted an event would leave no record to check. In a drill, compare the emitted events with a route inventory maintained outside the logger.
The probe checks events emitted by the mock gateway for a specific set of supplied labels. A newly added path is exercised only when an independent route inventory includes it and the drill drives that path.
PythonIn [23]Expand
def completeness_probe(control, gateway_tools):
expected_tools = set(gateway_tools)
covered = set()
for tool in expected_tools:
events = []
decision = gateway_action(control, tool, events)
if (
len(events) == 1
and events[0]["action_type"] == "tool_call"
and events[0]["tool"] == tool
and events[0]["decision"] == decision
and (tool in control.allowed_tools or decision == "deny")
):
covered.add(tool)
return covered == expected_tools, covered
covered_ok, covered = completeness_probe(
ControlPlane(), control.allowed_tools | {"unknown_tool"}
)The probe includes "unknown_tool" to check that a denied mock label still produces one matching tool_call event. A gateway return without a matching record fails this fixture check.
ConsoleOut [24]Expand
All supplied mock labels recorded: True Recorded mock labels: ['mock_read', 'mock_transfer', 'unknown_tool']
The exercise covers each supplied mock tool label, including a denied unknown label. It says nothing about real paths beyond the modeled gateway. A production test can compare observations against an inventory of actual independent side-effect routes.
Limitations and impact
The mechanisms in this chapter substantially raise the cost of undetected compromise and dramatically shorten time-to-understanding during an incident, but their residual risks are large and must be documented, not assumed away. We have already stressed the boundary of tamper evidence: integrity, not truth; consistency, not completeness. That boundary has practical teeth. A tamper-evident trail of an agent that was already fully controlled by an adversary is a faithful record of that adversary's fabrications; chaining raises the bar for silent editing and does nothing for lying at emit time. Teams that equate "our logs are hash-chained" with "our logs are trustworthy" have mistaken a property of storage for a property of truth, and that mistake surfaces precisely when it is most expensive, during the incident.
A valid checkpoint check tells you the inspected prefix matches an independently preserved commitment. Investigate emitter accuracy and missing routes with separate tool observations or other evidence. Check source clocks before drawing conclusions about elapsed time.
Low prevalence can turn even a small false-positive rate into substantial alert volume. Use labeled results from the intended population to estimate precision and recall, and test the entire paging policy. Tightening a rule can reduce false positives and still make important cases harder to detect.
The alert-fatigue failure mode is the most insidious in the entire chapter because it is silent. A program with too many alerts does not announce its failure; it simply produces operators who have learned to dismiss alerts, and the detection layer is disabled by the humans who run it rather than by any technical fault. By the time the fatigue is visible (an incident is missed despite an alert having fired), the program has been non-functional for months. This is why the layering and corroboration discipline is not a refinement but a survival requirement: a program that pages humans too often is a program that has stopped working, and the engineering effort of gating statistical detectors behind structural ones is what keeps the program alive.
A drill can show an operational gap even when hash checks pass. Test that responders can access the snapshot, that the suspension takes effect at the intended boundary, and that restored service respects the same permissions. Record what failed and assign the next check.
Corroborated records can help establish which resources were affected. If collection did not cover a route or a time window, preserve that uncertainty in the incident report. Record the evidence and coverage gaps in the governance artifacts introduced in System Cards, Audits, and Impact Assessments and Risk Governance Across the Lifecycle.
One final framing worth carrying forward. This chapter closes the security part of the book by acknowledging that no access-control boundary, sandbox, or content filter is ever final. Audit, detection, and response are the mechanisms by which a system absorbs the failures its designers could not prevent, learns from them, and keeps operating without silently losing its integrity. In that sense they are not the last line of defense; they are the immune system that lets everything upstream be imperfect on purpose.
Summary
- Auditing designs capture and protection for consequential records. Detection turns recorded events into signals. Incident response uses those signals and corroborating evidence to limit harm and investigate what happened.
- An audit event carries a common envelope (event ID, trace ID, timestamp, both principals (the human and the agent), action type, decision, hashes) plus type-specific fields, and records consequential actions, not tokens.
- A hash chain makes edits and reorderings detectable and enforces ordering, but requires an externally pinned head to detect truncation or tail-rewrite. Merkle trees and transparency logs scale this and enable inclusion/consistency proofs.
- Chaining proves integrity, not truth, and not completeness. The chain can faithfully record a lie, and it is silent about actions that bypass instrumentation. Completeness is a tested instrumentation property, not a cryptographic one.
- Detection is a classification problem with a brutal base-rate problem: the false-positive paradox means a high-recall statistical detector run naked at realistic prevalence has disastrous precision. The durable response is layering: high-precision structural/sequence detectors gate pages, statistical detectors generate triage leads, alert policy correlates and requires corroboration.
- Detector quality is an evaluation problem: it needs labeled incidents, drifts over time, and must be versioned alongside the policy that produces alerts.
- Incident response follows an order that matters: preserve evidence promptly and contain ongoing harm; use a kill switch that is tiered, pre-authorized, fail-safe, externally enforced, and tested; roll back to pinned known-good versions; re-verify recovery via the same detectors on a canary; and run a blameless post-incident review that produces tracked, testable changes.
- Use drills to test suspension and recovery. Compare observed audit records with an independent inventory to test instrumentation coverage.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about auditing, detection, and incident response for agent systems.
Audit, Detection, and Incident Response
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!