Sub topic 11
Recording what the agent did
This chapter assumes you can run the hardened container from the earlier chapters. It also assumes you can read JSON and basic Python. It covers what to record about an agent run, where to store it, and how to make the record hard to alter.
Why a log matters even with a sandbox
A sandbox limits what an agent can do. It does not tell you what the agent did. After a run you will want to answer questions like these:
- Which commands ran, and which failed?
- Which files changed?
- Did the agent try to reach a host that the network policy blocked?
- Which risky actions did a human approve, and who approved them?
Without a record you can only look at the final diff and guess. With one, you can review a surprising result, debug a bad run, and show later that the controls worked.
What to record
Record the facts that let you reconstruct a run. Do not record everything.
| Event | What to capture | Where it comes from |
|---|---|---|
| Run start | Run ID, image digest, mount list, limits, user | Your wrapper |
| Command | Argument list, working directory, start time | Your wrapper |
| Result | Exit code, duration, output size, output hash, truncated output | Your wrapper |
| File changes | List of changed paths, diff | `git diff` or `docker diff` |
| Network | Allowed and denied connections, destination, bytes | Egress proxy or firewall |
| Approval | What was asked, who answered, the decision, the time | Approval layer |
| Run end | Reason: finished, timeout, killed, or error | Your wrapper |
Give every run a unique ID and put it in every event. The ID lets you join the wrapper log, the proxy log, and the container name.
Where the log must live
The log must be written by something the agent cannot control. Follow these rules:
- Write the log from the host-side wrapper, not from inside the container.
- Never mount the log directory into the sandbox. If the agent can write it, it can edit it.
- Treat anything the agent prints as untrusted data. An agent can print text that looks like a log line, or that tries to fool a person or a model reading the log later. Store output as a quoted JSON string and never replay it as instructions.
- Use one writer process per log file, so records cannot interleave.
A structured, tamper-evident log
Write one JSON object per line (JSON Lines). This format is easy to append to and easy to search with jq. To make edits detectable, add a hash chain. Each record stores the SHA-256 hash of the previous record, so changing or deleting an old record breaks every hash after it.
The following module writes and verifies such a log.
import hashlib
import json
import time
from pathlib import Path
LOG_PATH = Path("audit/agent-audit.jsonl")
GENESIS = "0" * 64
def _digest(record: dict) -> str:
payload = json.dumps(record, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def _last_hash(path: Path) -> str:
if not path.exists():
return GENESIS
last = None
with path.open("r", encoding="utf-8") as f:
for line in f:
if line.strip():
last = line
return json.loads(last)["hash"] if last else GENESIS
def append_event(run_id: str, event_type: str, data: dict, path: Path = LOG_PATH) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
record = {
"ts": time.time(),
"run_id": run_id,
"type": event_type,
"data": data,
"prev": _last_hash(path),
}
record["hash"] = _digest(record)
with path.open("a", encoding="utf-8") as f:
f.write(json.dumps(record, sort_keys=True) + "\n")
def verify_chain(path: Path = LOG_PATH):
"""Return the line number of the first bad record, or None if the chain is intact."""
prev = GENESIS
with path.open("r", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
if not line.strip():
continue
record = json.loads(line)
claimed = record.pop("hash")
if record["prev"] != prev or _digest(record) != claimed:
return number
prev = claimed
return NoneA hash chain is tamper-evident, not tamper-proof. Someone who can write the file can rebuild the whole chain with new hashes. To close that gap, copy the latest hash to a place the writer cannot change, such as a separate service, a write-once bucket, or a signed message. Then you can detect a rewritten history.
Logging each command
Extend the wrapper from the hardening chapter so that it logs before and after each command. Two details matter here.
- Name the container, so you can kill it by name. When
subprocess.runtimes out, it kills thedockerclient process. The container can keep running. - Store a hash and a truncated copy of the output. Full output can be huge and may contain secrets.
import re
import subprocess
import time
import uuid
from pathlib import Path
# audit_log is the module from the previous listing, saved as audit_log.py
from audit_log import append_event
MAX_OUTPUT = 2000
SECRET_PATTERN = re.compile(r"(ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|sk-[A-Za-z0-9]{20,})")
def redact(text: str) -> str:
return SECRET_PATTERN.sub("[REDACTED]", text)
def run_logged(project_dir: str, command: list[str], timeout: int = 60, run_id: str | None = None) -> dict:
run_id = run_id or uuid.uuid4().hex
project = Path(project_dir).resolve()
name = f"agent-{run_id[:12]}-{uuid.uuid4().hex[:6]}"
docker_cmd = [
"docker", "run", "--rm", "--name", name,
"--user", "1000:1000",
"--read-only", "--tmpfs", "/tmp",
"--cap-drop=ALL",
"--security-opt", "no-new-privileges",
"--pids-limit", "128",
"--memory", "1g",
"--network", "none",
"-v", f"{project}:/workspace",
"-w", "/workspace",
"python:3.12-slim",
*command,
]
append_event(run_id, "command_start", {"argv": command, "container": name, "timeout": timeout})
started = time.monotonic()
try:
proc = subprocess.run(docker_cmd, capture_output=True, text=True, timeout=timeout)
outcome = {"exit_code": proc.returncode, "stdout": proc.stdout, "stderr": proc.stderr}
reason = "finished"
except subprocess.TimeoutExpired as exc:
subprocess.run(["docker", "kill", name], capture_output=True)
outcome = {"exit_code": None, "stdout": exc.stdout or "", "stderr": exc.stderr or ""}
reason = "timeout"
if isinstance(outcome["stdout"], bytes):
outcome["stdout"] = outcome["stdout"].decode("utf-8", "replace")
if isinstance(outcome["stderr"], bytes):
outcome["stderr"] = outcome["stderr"].decode("utf-8", "replace")
combined = outcome["stdout"] + outcome["stderr"]
append_event(run_id, "command_end", {
"reason": reason,
"exit_code": outcome["exit_code"],
"seconds": round(time.monotonic() - started, 3),
"output_bytes": len(combined.encode("utf-8")),
"output_head": redact(combined)[:MAX_OUTPUT],
})
return outcome
if __name__ == "__main__":
result = run_logged(".", ["python", "-c", "print('hello from the sandbox')"])
print(result["stdout"])The regular expression catches only a few well-known token formats. Treat redaction as a second line of defense. The first line is keeping secrets out of the sandbox, as the secrets chapter describes.
Recording file changes
Commands tell you what the agent tried. File changes tell you what it left behind. Because the project directory is a bind mount, the simplest method is to snapshot it before the run and diff it after.
#!/usr/bin/env bash
set -euo pipefail
PROJECT="$1"
RUN_ID="$2"
OUT="audit/$RUN_ID"
mkdir -p "$OUT"
git -C "$PROJECT" stash list > "$OUT/stash-before.txt"
git -C "$PROJECT" rev-parse HEAD > "$OUT/head-before.txt"
# ... run the agent here, for example with run_logged ...
git -C "$PROJECT" status --porcelain=v1 > "$OUT/status-after.txt"
git -C "$PROJECT" diff --binary > "$OUT/changes.patch"
sha256sum "$OUT/changes.patch" > "$OUT/changes.patch.sha256"Two limits apply:
git diffdoes not show untracked files. Usegit status --porcelainto list them, or rungit add -N .first so they appear in the diff.- Ignored files, such as
node_modulesor build output, do not appear. If the agent could plant a file there, add the paths you care about to the snapshot.
For the container's own filesystem, docker diff NAME lists paths added, changed, or deleted in the writable layer. It only works while the container exists, so you cannot use it with --rm unless you copy the result before exit. With --read-only and a tmpfs, the layer is almost empty, so this is mostly a check that the hardening held.
Recording network activity
If you used --network none, there is no network traffic to record, except failed attempts that never leave the container. If you allow egress through a proxy, as the network chapter describes, the proxy is the right place to log. It sees every request and can record the destination host, the decision, and the byte counts. Include the run ID by giving each run its own proxy credential or source address. Without that, you cannot tell which run made a request.
Log denied requests as carefully as allowed ones. A burst of denials to an unfamiliar host is often the first sign that an agent followed a malicious instruction.
Approvals belong in the log
When a human approves a risky action, record the exact action that was shown, not a summary. Record who approved it, when, and what they chose. If the approved command differs from the one that ran, you want that difference to be visible.
Retention and privacy
Logs can contain source code, file names, and fragments of private data. Decide before you start:
- How long to keep logs, and who can read them.
- Whether to store full output or only hashes and short excerpts.
- Where the logs are stored, and whether that location is backed up.
Common mistakes
- Logging from inside the container, where the agent can change the file.
- Storing complete output with no limit, which fills the disk and spreads secrets into the log.
- Forgetting the timeout path, so a killed run has a start record and no end record.
- Keeping the hash chain but never running
verify_chain. - Having no shared run ID, which makes the wrapper log and proxy log impossible to join.
Exercise
A teammate proposes having the agent append its own summary of each command to a log file inside /workspace, since "the agent knows best what it did." Give two reasons this should not be your audit log, and say what you would use instead.
Show answer
First, the agent controls the file. It can omit, rewrite, or delete entries, and a compromised or confused agent can write false ones. Second, the entries are untrusted output that a human or another model may later read as if it were fact, which opens a path for prompt injection. Use a host-side wrapper that logs the argument list, exit code, timing, and output hash from outside the container, write it to a directory that is not mounted into the sandbox, and add a hash chain whose latest hash is copied to a separate location.