Sub topic 11
Recording what the agent did
This chapter assumes you have read the earlier chapters on hardened containers, filesystem scoping, and disposable sandboxes. You should be comfortable with Python's subprocess module and with reading JSON.
Why logs matter
A sandbox limits damage. It does not tell you what happened inside it. If an agent deletes a test file, installs a package, or tries to reach a blocked host, you need a record to see it and to decide whether your limits are right.
An audit log answers four questions:
- What did the agent run?
- When did it run, and how long did it take?
- What did the command print, and how did it exit?
- Which sandbox configuration was active at the time?
What to record
Log each command as one structured record. A line of JSON is easier to search than free text.
| Field | Purpose |
|---|---|
| `run_id` | Links the record to the container name |
| `time` | UTC timestamp for ordering events |
| `command` | The exact argument list the agent asked for |
| `exit_code` | Success, failure, or `null` after a timeout |
| `duration_s` | Spots slow or looping commands |
| `stdout`, `stderr` | Truncated output for review |
Also record the image tag and the flags you passed to docker run. Without them, you cannot tell later which restrictions applied.
A logging wrapper
This extends the run_in_sandbox wrapper from earlier. It names each container, writes one JSON line per run, and kills the container on timeout.
import json
import subprocess
import time
import uuid
from datetime import datetime, timezone
from pathlib import Path
LOG_FILE = Path("agent-audit.jsonl")
MAX_OUTPUT = 2000 # characters kept per stream
def log_event(record: dict) -> None:
with LOG_FILE.open("a", encoding="utf-8") as f:
f.write(json.dumps(record) + "\n")
def run_logged(project_dir: str, command: list[str], timeout: int = 60):
run_id = uuid.uuid4().hex[:12]
project = Path(project_dir).resolve()
docker_cmd = [
"docker", "run", "--rm", "--name", f"agent-{run_id}",
"--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,
]
record = {
"run_id": run_id,
"time": datetime.now(timezone.utc).isoformat(),
"command": command,
"image": "python:3.12-slim",
"network": "none",
}
start = time.monotonic()
try:
result = subprocess.run(
docker_cmd, capture_output=True, text=True, timeout=timeout
)
record.update(
exit_code=result.returncode,
stdout=result.stdout[:MAX_OUTPUT],
stderr=result.stderr[:MAX_OUTPUT],
)
return result
except subprocess.TimeoutExpired:
subprocess.run(["docker", "kill", f"agent-{run_id}"], capture_output=True)
record.update(exit_code=None, error="timeout")
raise
finally:
record["duration_s"] = round(time.monotonic() - start, 3)
log_event(record)
run_logged(".", ["python", "-c", "print('hello from the sandbox')"])The finally block writes a record even when the command times out or the wrapper raises an error. The docker kill call matters because stopping the Docker client on timeout does not always stop the container.
Where the log should live
The log is written by the wrapper on the host, not by the agent. The log file is not inside the mounted project directory. If it were, a compromised or confused agent could edit its own history.
Common mistakes
- Logging only failures. Successful commands show what the agent changed.
- Logging from inside the container. Anything the agent can write, the agent can alter.
- Keeping logs forever by default. Set a retention period and rotate files.
- Skipping file changes. Command logs miss edits made by the agent's own tools. Pair them with a diff of the project directory, as in the review step of the disposable workflow.
Exercise
Why does the wrapper write the audit log from the host instead of letting the agent's container write it into /workspace?
Show answer
The agent can modify anything in /workspace, so it could edit or delete its own log entries. Writing from the host, outside any mounted path, keeps the record trustworthy even if the agent misbehaves.
Exercise
Name two fields you would add to each record to make a timeout easier to investigate, and say why.
Show answer
Examples: the timeout limit that was configured (to see whether the limit was too low) and the container's memory and CPU settings (to see whether resource pressure caused the stall). The image tag and the partial stdout captured before the kill are also acceptable.