Sub topic 17
Logging and reviewing agent actions
This chapter assumes you have read the chapters on least privilege, sandboxing, approval gates, and egress control. It also assumes you can read basic Python and JSON. The earlier defenses try to stop a bad action. Logging covers the cases where they fail. It tells you what the agent did, what it had read just before, and whether anything needs cleaning up.
Why logs matter for injection
A successful injection often leaves no visible failure. The agent finishes the task and the pull request looks fine. The only trace of the attack is an extra command, an unexpected URL, or a file read that the task did not need.
Logs serve three purposes:
- Detection. You can spot actions that don't match the task, such as a summarizing agent that runs
curl. - Investigation. You can find which input led to an action and what data may have left.
- Tuning. Repeated denials show which allowlist entries are too narrow and which agents are being fed hostile content.
Logs are not prevention. A review that happens after an action cannot undo a token that has already been sent out. Treat logging as a second layer behind the controls that limit what the agent can do.
What to record
A useful record answers four questions: who acted, what was done, why, and what happened. For each tool call, capture:
| Field | Purpose |
|---|---|
| Timestamp and run ID | Order events and group them by task |
| Agent identity and token used | Show which credentials were exposed |
| Trigger | Name the issue, PR, or file that started the run |
| Tool and exact arguments | Show the command, path, or URL |
| Decision | Record whether it was allowed, denied, or approved by a person |
| Result summary | Record exit code, output length, and a hash |
| Model input sources | List the untrusted items in context at that moment |
The last row is the one teams skip, and it is the most useful during an incident. If you know an action followed the reading of issue-1234, you can test whether that issue caused it.
What not to record
Full tool output can contain secrets: environment dumps, config files, and API responses. If you write it to a log, you create a second place for those secrets to leak from. Prefer a length and a SHA-256 hash of the output. Store full transcripts only in a store with the same access controls as the secrets themselves, and set a retention period.
A minimal action logger
This wrapper runs an allowed command, records the event as one JSON object per line, and logs denials too. A denial is often the most interesting event in the log.
import hashlib
import json
import subprocess
import time
import uuid
from pathlib import Path
LOG_PATH = Path('agent-actions.jsonl')
RUN_ID = str(uuid.uuid4())
ALLOWED = {('git', 'status'), ('git', 'diff'), ('pytest', '-q')}
def log_event(event):
event['ts'] = time.time()
event['run_id'] = RUN_ID
with LOG_PATH.open('a', encoding='utf-8') as f:
f.write(json.dumps(event, sort_keys=True) + '\n')
def logged_run(argv, trigger):
base = {'tool': 'shell', 'argv': list(argv), 'trigger': trigger}
if tuple(argv) not in ALLOWED:
log_event({**base, 'decision': 'denied'})
raise PermissionError(f'command not allowed: {argv}')
result = subprocess.run(
argv, capture_output=True, text=True, timeout=60, check=False
)
digest = hashlib.sha256(result.stdout.encode('utf-8')).hexdigest()
log_event({
**base,
'decision': 'allowed',
'exit_code': result.returncode,
'stdout_len': len(result.stdout),
'stdout_sha256': digest,
})
return resultThe log is append-only from the agent's point of view. If the agent can edit or delete agent-actions.jsonl, an injected instruction can erase its own trail. In practice, ship events to a separate system that the agent's sandbox cannot write to except by appending.
What to look for in review
Reading every line does not scale, so look for deviations from the task. These patterns are worth a rule or an alert:
- Denied actions. One denial may be a model mistake. Several in a row, or a denial right after the agent read an issue, suggest an injection attempt.
- Network requests to unlisted hosts. An egress allowlist should block these. A logged attempt shows what the agent tried to do.
- Reads of sensitive paths. Examples are
.env,~/.ssh, cloud credential files, and CI secret mounts. - Writes outside the working tree, or to files that change behavior, such as workflow files, rules files, and hook scripts.
- Commands unrelated to the task. A documentation fix should not run
pip installfrom a new index. - Unusual volume. Large reads, many files touched, or long output suggest bulk collection.
The script below applies several of these rules to the log from the previous example. It also handles events with a url field, which a network wrapper would produce.
import json
import sys
from urllib.parse import urlparse
ALLOWED_HOSTS = {'pypi.org', 'files.pythonhosted.org'}
SENSITIVE = ('.env', '.ssh', '.aws', 'credentials')
def review(path):
findings = []
with open(path, encoding='utf-8') as f:
for number, line in enumerate(f, start=1):
event = json.loads(line)
if event.get('decision') == 'denied':
findings.append((number, 'denied action', event))
url = event.get('url')
if url and urlparse(url).hostname not in ALLOWED_HOSTS:
findings.append((number, 'unlisted host', event))
text = ' '.join(event.get('argv', []))
if any(marker in text for marker in SENSITIVE):
findings.append((number, 'sensitive path', event))
return findings
if __name__ == '__main__':
for number, reason, event in review(sys.argv[1]):
print(f'line {number}: {reason}: {event.get("trigger")}')Run it as python review.py agent-actions.jsonl. Because each finding prints the trigger, you can go straight to the issue or file that was in context.
Tying actions back to inputs
Individual events are hard to interpret without context. Add the run's input sources to the first event of each run, and include the trigger on every tool call, as the logger above does. When a suspicious action appears, ask:
- Which untrusted items were in context when it happened?
- Would the task as the user described it have needed this action?
- If you replay the run with that input removed, does the action disappear?
The third question is the strongest test. It turns "this looks odd" into evidence about cause.
Limits of logging
- Latency. An alert can arrive after the data has already left. Use logs to shorten response time, and use egress control to stop the transfer.
- Alert fatigue. If every denial pages someone, people stop reading. Page on high-signal events such as secret-path reads followed by a network attempt. Send the rest to a periodic review.
- Blind spots. The wrapper sees only what passes through it. Actions taken by tools that bypass it, such as an MCP server with its own network access, will not appear.
- Log injection. Untrusted text can end up in log fields. Write structured JSON, as above, so a newline in an issue title cannot forge a fake event.
- Privacy. Logs may hold code, usernames, and file contents. Restrict access and set retention.
Exercise
An agent that triages issues logs one denied curl command with the trigger issue-88. The egress allowlist blocked it. What are two follow-up steps, and why is the denial still worth investigating?
Show answer
First, read issue-88, including hidden content such as HTML comments, and check whether it contains an instruction to send data out. Second, review the other events in the same run for reads of sensitive paths, and rotate any credential that was exposed to that run if the evidence points to it. The denial matters because it shows an injection reached the agent and changed its behavior. The block shows that the egress control worked, but the same input could succeed against an agent with a weaker boundary.
Exercise
Why does the logger above store a hash and length of stdout instead of the full output?
Show answer
Command output can contain secrets, so a full copy in the log creates another place for them to leak. The hash and length still let a reviewer detect unusual output and match it against a protected full transcript if one exists.