Short answer

Claude Code keeps every message, tool call and tool result of a session in a plaintext JSONL file under ~/.claude/projects, deleted after 30 days by default. Read it after a long session to list the shell commands that ran, the iOS files that affect signing and review, any secret files the agent read, and the files git says changed that the agent never edited with its own tools, since /rewind may not restore those. Count tokens once per response, not once per line, and treat every flagged command as a line to read, not proof.

You asked a coding agent to fix a crash in your SwiftUI app. It came back with "Done, tests pass." The diff is 40 files. Somewhere in there is a build setting you didn't ask for, a new entitlement, or a shell command that ran on your Mac while you were making coffee. Reading the final diff tells you where the code ended up. It won't tell you how it got there.

The record of how it got there is already on your disk. Claude Code writes every message, tool call and tool result to a plain JSONL file. This post shows how to read that file for the three things an iOS developer needs to know after a long session: what ran, what changed, and which of those changes never appeared in the agent's own edit log. There is a working script below, a small hook for keeping a running log, and notes on the replay tools that already exist if you would prefer a viewer.

Where the record is, and how long you have

Anthropic's documentation for the .claude directory lists the transcript at ~/.claude/projects/<project>/<session>.jsonl and describes it as the "full conversation transcript: every message, tool call, and tool result." Subagents get their own files under <session>/subagents/, which matters because a subagent can edit your project and the parent session's file won't show each step.

Three details from those docs change how you should treat these files:

  • They expire. Claude Code deletes files in that tree once they are older than cleanupPeriodDays, which defaults to 30 days. If you want to audit a release candidate after the fact, copy the transcript somewhere first.
  • They are plaintext. The docs say transcripts are not encrypted at rest and that OS file permissions are the only protection. If a tool reads a .env file or a command prints a credential, that value lands in the JSONL.
  • They can lag. The hooks reference says the transcript file "is written asynchronously and may lag the in-memory conversation," so a script reading it mid-turn may miss the latest messages. Audit after the session ends.

Treat the field layout with some caution as well. The official pages used for this post describe where the file lives and what it contains, but none of them publishes a field-by-field schema. The third-party claude-devtools project, which parses these files, warns that the exact type values change with Claude Code versions. Anything you build on this format can break after an update, so make your script fail loudly and check it against a fresh session now and then.

Find the session you care about

The project folder name is your working directory with the path separators turned into dashes. The newest file there is usually the session you just finished:

ls -t ~/.claude/projects/-Users-you-Code-MyApp/*.jsonl | head -3

Each line is one JSON object. For an audit, you only need two kinds. An assistant line holds the model's response, and its message.content array contains tool_use blocks with a tool name and its input. A user line holds the matching tool_result, and an is_error flag tells you when a tool failed. Token counts sit in message.usage on the assistant lines.

One trap is worth knowing before you add anything up. A single API response is split across several lines in the file, and each of those lines repeats the same usage numbers. In the real transcript used to test the script in this post, 14 responses took up 70 lines, and all the lines of each response carried identical usage figures. Summing every line reported about five times the real token count. Group by message.id and count each response once. AI Coding Costs: Why Your Agent Bill Is Mostly Re-Reading (and 7 Ways to Cut It) explains where those tokens usually go.

The audit script

This is a single Python file with no dependencies. Give it a transcript and, optionally, the repo the session worked on. It prints tool counts, failures, token totals, edits to files that affect how your iOS app is signed or reviewed, any secret-looking files the agent read, and shell lines worth a second look. With --repo, it compares the agent's edit log against git.

#!/usr/bin/env python3
"""Audit one Claude Code session: what it ran, what it edited, what git says changed.

Usage: python3 agent_audit.py SESSION.jsonl [--repo /path/to/repo] [--base main]
"""
import argparse, json, os, re, subprocess, sys
from collections import Counter
from pathlib import Path

SENSITIVE_FILES = re.compile(
    r"(project\.pbxproj|\.entitlements|Info\.plist|PrivacyInfo\.xcprivacy"
    r"|\.xcconfig|ExportOptions\.plist|\.xcscheme|\.storekit"
    r"|Package\.resolved|Podfile(\.lock)?|\.github/workflows/|fastlane/)")
SECRET_FILES = re.compile(r"(\.env\b|AuthKey_\w+\.p8|\.p12$|\.mobileprovision$|\.ssh/|\.netrc)")
RISKY_COMMANDS = {
    "pushes or rewrites git": r"git\s+(push|reset\s+--hard|clean\s+-\w*f|rebase)",
    "deletes recursively": r"\brm\s+-\w*r",
    "uploads to Apple": r"(altool|notarytool|fastlane\s+\w*(pilot|deliver|upload)|xcrun\s+.*upload)",
    "touches the keychain": r"\bsecurity\s+(find|import|delete|unlock|add)",
    "changes Xcode selection": r"xcode-select\s+-s|sudo\s+xcode-select",
    "runs as root": r"\bsudo\b",
    "pipes the network to a shell": r"curl[^|]*\|\s*(ba|z)?sh",
    "edits files through the shell": r"\bsed\s+-i|\bperl\s+-\w*i|PlistBuddy|\bplutil\s+-(insert|replace|remove)|>\s*\S+\.(swift|plist|pbxproj|entitlements)",
}


def records(path):
    with open(path, encoding="utf-8") as handle:
        for line in handle:
            try:
                yield json.loads(line)
            except json.JSONDecodeError:
                continue


def session_files(path):
    path = Path(path)
    yield path
    yield from sorted(path.with_suffix("").glob("subagents/*.jsonl"))


def audit(paths):
    usage, seen = {}, set()
    tools, commands, edited, read_files, failures = Counter(), [], [], [], 0
    for path in paths:
        for rec in records(path):
            msg = rec.get("message") or {}
            content = msg.get("content")
            if rec.get("type") == "assistant":
                # One API response can span several lines, so count its usage once.
                key = msg.get("id") or rec.get("uuid")
                if key not in seen and msg.get("usage"):
                    seen.add(key)
                    for name, value in msg["usage"].items():
                        if isinstance(value, int):
                            usage[name] = usage.get(name, 0) + value
                for block in content if isinstance(content, list) else []:
                    if block.get("type") != "tool_use":
                        continue
                    name, args = block.get("name", "?"), block.get("input") or {}
                    tools[name] += 1
                    if name == "Bash":
                        commands.append(args.get("command", ""))
                    elif name in ("Edit", "Write", "MultiEdit", "NotebookEdit"):
                        edited.append(args.get("file_path") or args.get("notebook_path", ""))
                    elif name == "Read":
                        read_files.append(args.get("file_path", ""))
            elif rec.get("type") == "user" and isinstance(content, list):
                failures += sum(1 for b in content
                                if b.get("type") == "tool_result" and b.get("is_error"))
    return usage, tools, commands, edited, read_files, failures


def git_changes(repo, base):
    # Pathspec-free so renames, deletes and untracked files are all listed.
    diff = ["git", "-C", repo, "diff", "--name-only", "-z", base]
    new = ["git", "-C", repo, "ls-files", "--others", "--exclude-standard", "-z"]
    names = set()
    for cmd in (diff, new):
        names.update(subprocess.check_output(cmd, text=True).split("\0"))
    names.discard("")
    return names


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("session")
    parser.add_argument("--repo")
    parser.add_argument("--base", default="HEAD")
    opts = parser.parse_args()

    files = list(session_files(opts.session))
    usage, tools, commands, edited, read_files, failures = audit(files)

    print(f"Transcript files: {len(files)}")
    print("Tool calls: " + ", ".join(f"{k} {v}" for k, v in tools.most_common()))
    print(f"Failed tool calls: {failures}")
    print("Tokens: " + ", ".join(f"{k}={v:,}" for k, v in sorted(usage.items())))

    print("\nSensitive files edited:")
    hits = sorted({f for f in edited if SENSITIVE_FILES.search(f)})
    print("\n".join(f"  {f}" for f in hits) or "  none")

    print("\nSecret-looking files read:")
    hits = sorted({f for f in read_files if SECRET_FILES.search(f)})
    print("\n".join(f"  {f}" for f in hits) or "  none")

    print("\nCommands worth reading:")
    found = 0
    for label, pattern in RISKY_COMMANDS.items():
        for cmd in commands:
            for line in cmd.splitlines():
                if re.search(pattern, line):
                    print(f"  [{label}] {line.strip()[:110]}")
                    found += 1
    if not found:
        print("  none")

    if opts.repo:
        root = subprocess.check_output(
            ["git", "-C", opts.repo, "rev-parse", "--show-toplevel"], text=True).strip()
        logged = {os.path.relpath(os.path.realpath(f), os.path.realpath(root))
                  for f in edited if f}
        changed = git_changes(root, opts.base)
        print(f"\nChanged in git since {opts.base}: {len(changed)}")
        print("Changed but never edited through Edit or Write:")
        extra = sorted(changed - logged)
        print("\n".join(f"  {f}" for f in extra) or "  none")
        print("Logged as edited but no change in git now:")
        gone = sorted(f for f in logged - changed if not f.startswith(".."))
        print("\n".join(f"  {f}" for f in gone) or "  none")


if __name__ == "__main__":
    sys.exit(main())

Run it on the session, pointing --base at the commit you started from if the agent made commits along the way:

python3 agent_audit.py ~/.claude/projects/-Users-you-Code-MyApp/SESSION.jsonl \
  --repo ~/Code/MyApp --base a1b2c3d

Without --base, the script compares against HEAD, so it only sees uncommitted work. Any change the agent committed itself would vanish from the comparison.

What it was tested on, and what it wasn't

The script was run two ways. The first run used a real Claude Code session transcript on Linux, which confirmed the record shapes, the tool counts and the usage grouping. That session did no Xcode work, so it says nothing about what a real iOS session looks like. The second run used a hand-built transcript and a small git repo with a fake Xcode project in it: a tracked file edited through the Edit tool, a project.pbxproj changed by sed, a new privacy manifest created by the shell, a read of an AuthKey file and a git push --force. It flagged each one correctly. A third run, on a Mac against a real Xcode project, is described below. Expect to adjust the patterns for your repo all the same.

The real run also turned up the script's main weakness. It flagged several lines that were harmless, because they were lines of a test fixture and a heredoc that merely contained text like git push --force. The patterns match text, and a command that writes those words into a file looks the same as a command that runs them. Treat the output as a list of lines to read, and don't treat a flag as proof that anything happened.

A run on a Mac with a real Xcode project

The third run was on macOS 26.0.1 with Xcode 26.2 and the Python 3.9 that ships with macOS. The repo held a real iOS project generated with XcodeGen: two SwiftUI files, a third named Café View.swift, and the project's own Info.plist and project.pbxproj. After a baseline commit, the changes a session might make were applied for real: two Swift edits, a sed that raised the deployment target from iOS 16 to 17 followed by a commit, a camera usage description added to Info.plist with Apple's PlistBuddy tool, and a new entitlements file. A hand-built transcript recorded those steps as Edit, Bash and Write calls, plus a read of an AuthKey file and a keychain command, neither of which ran. Each response was split over two lines with the same usage, as in the real format.

Two things went wrong. Git prints file names with accented letters in quotes and octal escapes, so Café View.swift came back as "App/Caf\303\251 View.swift" and showed up in both comparison lists at once, as changed but never edited and as edited but unchanged. Plenty of real projects have non-English file names, and the fix is to ask git for raw, NUL-separated names with -z. And the PlistBuddy edit was missing from "Commands worth reading", because the shell-edit pattern only knew sed, perl and redirects. PlistBuddy and plutil are the usual way to change a plist from Terminal on a Mac, so an agent is likely to use them. The script above now has both fixes, and in a second pass a plutil -replace step on the same file was flagged too. With them, and with the folder path shortened, it printed:

Transcript files: 1
Tool calls: Bash 5, Read 2, Edit 2, Write 1
Failed tool calls: 1
Tokens: cache_read_input_tokens=50,000, input_tokens=10,000, output_tokens=2,000

Sensitive files edited:
  .../AuditDemo/App/AuditDemo.entitlements

Secret-looking files read:
  /Users/you/Downloads/AuthKey_ABC123XYZ.p8

Commands worth reading:
  [touches the keychain] security find-generic-password -s demo-api -w
  [edits files through the shell] sed -i '' 's/IPHONEOS_DEPLOYMENT_TARGET = 16.0/IPHONEOS_DEPLOYMENT_TARGET = 17.0/' AuditDemo.xcodeproj/project
  [edits files through the shell] /usr/libexec/PlistBuddy -c "Add :NSCameraUsageDescription string Scan receipts" App/Info.plist

Changed in git since f976b49: 5
Changed but never edited through Edit or Write:
  App/Info.plist
  AuditDemo.xcodeproj/project.pbxproj
Logged as edited but no change in git now:
  none

Everything else held. Tokens were counted once per response, not once per line. The sed on the project file and the PlistBuddy edit both appear among the commands and among the files changed outside Edit and Write. The entitlements file appears as a sensitive edit, the AuthKey read and the keychain command are flagged, and the failed keychain call is counted. Without --base, the same run listed only 2 changed files, because the deployment target change had been committed, which is the trap described above.

One more check was made on the format itself. A current transcript from Claude Code 2.1.325 on the same Mac was parsed without errors, and its responses were still split across several lines with identical usage on each. Its output isn't shown, because it is a private working session. That file also holds record types the script ignores, such as api-request-blob lines, which contain tool_use blocks of their own. The script only counts assistant lines, so they don't inflate its numbers, but a quick script that counts every tool_use block in the file would count far more calls than were made.

The comparison that catches the most

The most useful output is the list headed "Changed but never edited through Edit or Write." Those are files git says changed that the agent never touched with its file editing tools. They usually got changed by a shell command, a code generator, a package resolver or a formatter. Some of that is expected. Package.resolved changes when a dependency resolves. An xcodegen run rewrites the project file.

It's the unexpected entries you are hunting for, and this list also matters for undo. Anthropic's checkpointing docs say a file that only Bash commands changed isn't tracked, so /rewind leaves it as it is. Edits made by most subagents aren't restored either, unless Claude had already edited the same file in your conversation. So a file on this list is one that /rewind may not bring back, and git is your only way to revert it. If you let an agent work on a dirty tree, you have no clean point to return to, so commit or stash before you start.

The opposite list, "Logged as edited but no change in git now," is mostly harmless. It shows files the agent edited and later reverted, or files outside the repo. If the agent told you it fixed something in a file that appears here, though, the fix isn't in your tree. Go and look.

Git has a blind spot of its own: git diff and ls-files --exclude-standard skip ignored files. Local config, build output and anything else in .gitignore can change without appearing in either list. The "commands worth reading" section is your only clue there.

What to do about each flagged iOS file

The sensitive file list is short on purpose. Each entry can change what ships, how it is signed, or what you have to declare to Apple. Here is what to check when one appears:

  • .entitlements: a new key means the app now claims a capability it didn't claim before. Check that you meant to add it and that it matches the capability enabled for your App ID.
  • project.pbxproj and .xcconfig: look for changes to the bundle identifier, signing style, team, deployment target and any build setting that turns off a warning or check. Agents sometimes reach for a build setting to make an error go away.
  • Info.plist: a new usage description means the app is now asking for something new. Your App Store Connect privacy answers should still match what the app does.
  • PrivacyInfo.xcprivacy: check that each declared reason is the true reason the code uses that API. An agent can pick a reason that makes the build pass and is wrong.
  • Package.resolved and Podfile.lock: a dependency version moved. Read which one and why, and check that the bump didn't come along for the ride.
  • ExportOptions.plist, fastlane/ and .github/workflows/: these control how the app gets built and uploaded, so review them line by line.

A flagged secret read needs a different response. If the agent read an AuthKey file or a .env, the contents are now in the transcript in plaintext, and they went to the model provider as part of the conversation. Decide whether that key should be rotated, and consider a permission rule that denies reads of those paths from now on. Anthropic's docs suggest exactly that, along with lowering cleanupPeriodDays. Claude Code's "Don't Ask Again" Can Save Your Passwords. Find Them in Your iOS Repo and Clean Up covers another place secrets collect.

Keep a running log with a hook

A transcript audit happens after the fact. If you want a compact line per tool call while the agent works, a PostToolUse hook can append to a log. Hooks receive JSON on stdin with session_id, tool_name and tool_input, so a few lines of jq are enough:

#!/bin/bash
# Appends one line per tool call to a log outside the repo.
log="$HOME/.claude/agent-audit.log"
jq -c '{t: (now | todate), session: .session_id, tool: .tool_name,
        cmd: .tool_input.command, file: .tool_input.file_path}' >> "$log"

Save it, make it executable, and register it in your settings:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash|Edit|Write",
        "hooks": [{ "type": "command", "command": "~/.claude/hooks/log-tool.sh" }]
      }
    ]
  }
}

The log script was tested by piping sample hook JSON through it on Linux, and again on a Mac with the jq 1.7.1 that ships with macOS, where it logged a Bash call and an Edit to a file with an accented name correctly. It was not registered as a hook in a live Claude Code session for this post. It needs jq installed. A log like this will hold every command the agent ran, so it needs the same care as the transcript, and it shouldn't go in your repo.

For a team, the sturdier route is Claude Code's OpenTelemetry export. Set CLAUDE_CODE_ENABLE_TELEMETRY=1 and choose an exporter, and you get metrics such as claude_code.cost.usage and claude_code.token.usage and events such as claude_code.tool_result, with the tool name, success flag and duration. Command text is left out by default. To include it you set OTEL_LOG_TOOL_DETAILS=1, and the docs recommend leaving these opt-in content settings unset unless your pipeline is approved to store that data.

If you want to watch it instead of reading it

Three existing options cover most of what the script doesn't.

The built-in option is /usage, which shows the current session's token use. Anthropic is clear that the dollar figure is an estimate at list price and isn't relevant to billing if you are on a subscription. /insights goes further: it analyzes recent sessions on your machine and writes an HTML report on what you work on and where things went wrong, with the tokens counting against your plan.

claude-replay is an MIT-licensed tool that turns a session log into one self-contained HTML page you can step through. It handles Claude Code, Cursor, Codex CLI and several others, and the format is detected automatically:

npx claude-replay ~/.claude/projects/-Users-you-Code-MyApp/SESSION.jsonl -o replay.html

Its README says secret redaction is on by default and also warns that pattern-based redaction cannot catch every format. Read the page yourself before sending it to anyone.

ccusage reports token use and cost from local data. npx ccusage@latest session groups usage by conversation, and it supports Codex and a long list of other agents. It answers "which session burned the most" better than a hand-written script will, and it doesn't try to answer "what did that session do to my repo."

If you use Codex, OpenAI's docs confirm codex resume for returning to saved sessions, but the pages checked for this post don't say where the files are kept. A third-party guide places them at ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl. The format is different from Claude Code's, so the script above won't parse them. The approach carries over: list the commands, list the file changes, compare against git.

A routine that takes five minutes

After any session that touched more than a few files, and always before you archive a build:

  1. Commit or stash before the session starts, and note the starting commit.
  2. When the agent finishes, run the audit with --repo and --base set to that commit.
  3. Read every line in "Commands worth reading," and throw out the ones that are only text.
  4. Open each file in "Changed but never edited through Edit or Write" and decide whether you expected it.
  5. Review every entry in the sensitive list against the checks above.
  6. If a secret-looking file was read, decide on rotation before you do anything else.
  7. Save the transcript with the build if you may need it in more than 30 days.

The audit won't tell you whether the code is correct. It tells you what happened during the session, which is the part you weren't there to see, and it gives you a short list of places to spend your review time on a 40-file diff.

If you also hand work between sessions or tools, Repo Context & Handoff may be useful. It is a $39 local Node.js CLI that packs the files, decisions and constraints of a task into a Markdown, JSON or HTML packet, then checks whether those files have changed before you resume. It doesn't audit what an agent did, and it doesn't plug into an agent automatically. It covers the step after this one: making sure the context you carry into the next session still matches your repo.

Sources