Skip to content

Logging Claude Code sessions

A Claude Code Stop hook can copy every turn of a coding session into an agent workspace's execution log: the prompts you type, what Claude says, and each tool call with its input and output. The log is append-only and tagged, so you can read back how a change was made, follow a teammate's session as it happens, or keep an audit trail of what an AI assistant did in a repository.

While the MCP server gives Claude Code memory to read from, this hook records what happened. You can use them together or independently.

How it works

Claude Code runs a Stop hook each time it finishes responding, and a SessionEnd hook when the session ends (for example, on /quit). The hook below runs on both. It reads the session transcript from where its previous run stopped and writes one step per entry with jnh agents memory add-step:

Entry Step fields kind tag
A prompt you typed (slash commands included) thought_process prompt
A text block from Claude thought_process narration
A tool call tool_used, tool_input, tool_output tool

Every step is also tagged with source=claude-code, session=<session id>, and cwd=<working directory>. Text injected by the harness, such as skill bodies and tool results arriving as user turns, is not logged as a prompt.

Steps go to one workspace per repository, named after the origin remote (for example, git@github.com:acme/payments.git logs to cc.acme.payments). Every clone and worktree of a repository shares that workspace, and the cc.* selector covers all of them. Sessions outside a git repository, or in one with no origin, are ignored. The first write to a workspace automatically creates it if it does not exist yet.

Requirements

  • jnh on the PATH Claude Code runs hooks with (see Getting started). If jnh is not found, the hook does nothing and logs the skipped turns once it is installed.
  • Python 3.
  • Credentials: your jnh login session, or an API key in JENNAH_API_KEY. An API key for this hook only needs access to the cc.* workspaces:

    jnh keys create --label claude-code-log \
      --scopes agent.agents:create,agent.agents:read,agent.memory:write \
      --agents 'cc.*' --expires-in 90d -o json
    

    Omit agent.agents:create if an administrator creates the workspaces ahead of time.

Install the hook

Save this script as ~/.claude/hooks/jennah-log.py:

#!/usr/bin/env python3
"""Claude Code Stop/SessionEnd hook: append the turn's prompts, narration, and
tool calls to a Jennah agent's execution log.

Stop logs entries written to the transcript so far. Because a turn's final
response is usually flushed after Stop returns, it is picked up by the next
hook run (the next turn's Stop, or SessionEnd on exit).

Does nothing when `jnh` is not on PATH (except with JENNAH_DRY_RUN=1).

Env:
  JENNAH_AGENT_ID   override the derived agent id
  JENNAH_DRY_RUN=1  print the commands instead of running them
"""
import json, os, re, shutil, subprocess, sys

MAX = 8000  # keep each field well under the per-argument size limit

def clip(s):
    s = s if isinstance(s, str) else json.dumps(s, ensure_ascii=False)
    if len(s) <= MAX:
        return s
    return s[:MAX] + f"\n...[truncated {len(s) - MAX} chars]"

def result_text(content):
    if isinstance(content, list):
        return "\n".join(c.get("text", "") for c in content
                         if c.get("type") == "text")
    return content or ""

def prompt_text(e):
    """The text the user typed, or "" for anything else in a "user" entry."""
    origin = (e.get("origin") or {}).get("kind", "human")
    if e.get("isMeta") or origin != "human":
        return ""
    content = e["message"].get("content")
    if isinstance(content, list):
        if any(b.get("type") == "tool_result" for b in content):
            return ""
        content = "\n".join(b.get("text", "") for b in content
                            if b.get("type") == "text")
    content = (content or "").strip()
    skip = ("<local-command-stdout>", "<local-command-caveat>")
    if content.startswith(skip):
        return ""
    return content

def agent_id(cwd):
    """cc.<owner>.<repo> from the origin remote, or None outside a repo."""
    r = subprocess.run(["git", "-C", cwd, "remote", "get-url", "origin"],
                       capture_output=True, text=True)
    url = r.stdout.strip()
    if r.returncode != 0 or not url:
        return None
    # Both https://host/owner/repo(.git) and git@host:owner/repo(.git).
    url = url.rstrip("/").removesuffix(".git").replace(":", "/")
    tail = url.split("/")[-2:]
    parts = [re.sub(r"[^a-z0-9-]+", "-", p.lower()).strip("-")
             for p in tail]
    parts = [p for p in parts if p]
    if not parts:
        return None
    return ".".join(["cc", *parts])[:128].rstrip(".-")

# jnh exit codes, see the CLI page.
EXIT_INVALID_ARGUMENT = 2
EXIT_NOT_FOUND = 5
EXIT_ALREADY_EXISTS = 7

def create_agent(agent):
    """Create the workspace; ALREADY_EXISTS counts (two sessions can race)."""
    r = subprocess.run(["jnh", "agents", "create", agent, "--wait"],
                       capture_output=True, text=True)
    if r.returncode in (0, EXIT_ALREADY_EXISTS):
        return True
    print(f"jennah: cannot create agent workspace {agent}: "
          f"{r.stderr.strip()}", file=sys.stderr)
    return False

def main():
    hook = json.load(sys.stdin)
    dry = os.environ.get("JENNAH_DRY_RUN") == "1"
    if not dry and not shutil.which("jnh"):
        # Leave the offset alone; the turn is logged once jnh is installed.
        return
    cwd = hook.get("cwd") or os.getcwd()
    agent = os.environ.get("JENNAH_AGENT_ID") or agent_id(cwd)
    if not agent:
        return
    sid, path = hook["session_id"], hook["transcript_path"]
    if not os.path.exists(path):
        # Session ended before any transcript was written: nothing to log.
        return
    state = os.path.expanduser(f"~/.claude/jennah-offsets/{sid}")
    os.makedirs(os.path.dirname(state), exist_ok=True)
    start = int(open(state).read()) if os.path.exists(state) else 0

    with open(path) as f:
        lines = f.readlines()
    entries = [json.loads(l) for l in lines[start:] if l.strip()]

    # Tool results arrive in later "user" entries; index them by tool_use_id.
    results = {}
    for e in entries:
        content = e.get("message", {}).get("content")
        if e.get("type") == "user" and isinstance(content, list):
            for b in content:
                if b.get("type") == "tool_result":
                    results[b["tool_use_id"]] = result_text(b.get("content"))

    created = False
    for e in entries:
        if e.get("type") == "user":
            text = prompt_text(e)
            blocks = [{"type": "prompt", "text": text}] if text else []
        elif e.get("type") == "assistant":
            blocks = e["message"].get("content", [])
        else:
            continue
        for i, b in enumerate(blocks):
            step = f"cc-{sid}-{e['uuid']}-{i}"
            meta = ["source=claude-code", f"session={sid}",
                    f"cwd={hook.get('cwd', '')}"]
            if b.get("type") == "prompt":
                args = ["--thought", clip(b["text"])]
                meta.append("kind=prompt")
            elif b.get("type") == "text" and b["text"].strip():
                args = ["--thought", clip(b["text"])]
                meta.append("kind=narration")
            elif b.get("type") == "tool_use":
                args = ["--tool", b["name"], "--tool-input", clip(b["input"]),
                        "--tool-output", clip(results.get(b["id"], ""))]
                meta.append("kind=tool")
            else:
                continue
            cmd = ["jnh", "agents", "memory", "add-step", agent,
                   "--step-id", step, *args]
            for m in meta:
                cmd += ["--metadata", m]
            if dry:
                print(json.dumps(cmd, ensure_ascii=False)[:300])
                continue
            r = subprocess.run(cmd, capture_output=True, text=True)
            if r.returncode == EXIT_NOT_FOUND and not created:
                # First write to a workspace that does not exist yet.
                if not create_agent(agent):
                    # Keep the offset; the turn is written once this is fixed.
                    return
                created = True
                r = subprocess.run(cmd, capture_output=True, text=True)
            if r.returncode in (0, EXIT_ALREADY_EXISTS):
                # Written now, or by an earlier run that stopped part-way.
                continue
            print(f"jennah: {step}: {r.stderr.strip()}", file=sys.stderr)
            if r.returncode == EXIT_INVALID_ARGUMENT:
                continue  # this step can never succeed; skip it
            # Not signed in, no network, ...: retry the whole turn next time.
            return

    if not dry:
        with open(state, "w") as f:
            f.write(str(len(lines)))

if __name__ == "__main__":
    main()

Then register it in ~/.claude/settings.json to log every session on the machine, or in a repository's .claude/settings.json to log only that repository:

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/jennah-log.py"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.claude/hooks/jennah-log.py"
          }
        ]
      }
    ]
  }
}

The SessionEnd hook is optional, but recommended so the final response of the last turn is logged when the session exits (see Behavior and limits).

To verify what the script will write before enabling it, pipe a hook payload into it with JENNAH_DRY_RUN=1, pointing at an existing transcript under ~/.claude/projects/:

printf '{"session_id":"dry-run","transcript_path":"%s","cwd":"%s"}' \
  ~/.claude/projects/<project>/<session>.jsonl "$PWD" \
  | JENNAH_DRY_RUN=1 python3 ~/.claude/hooks/jennah-log.py

Reading a session back

Query or inspect the log like any other workspace (see Inspecting memory):

# Follow sessions as they are written
jnh agents memory inspect cc.acme.payments --log --tail

# The 20 most recent prompts
jnh agents memory query cc.acme.payments --log-limit 20 \
  --filter kind=prompt

# One session, in order
jnh agents memory query cc.acme.payments --log-limit 200 \
  --filter session=<session id>

Behavior and limits

  • Idempotent writes. Step IDs are derived from the session ID and transcript entry UUID. Because the log rejects duplicate step IDs, re-running the hook never duplicates a step. If a run fails (for example, due to network or auth errors), the file offset is not updated and the next run retries the turn.
  • Sessions with no transcript. If a session ends before Claude Code writes any transcript (for example, you exit right after starting), the transcript file does not exist and the hook exits without logging anything or reporting an error.
  • New turns only. The hook tracks its file offset per session and only processes new entries. Turns recorded before the hook was installed are not backfilled.
  • Delayed final responses. Claude Code usually flushes a turn's final response to the transcript after the Stop hook returns, so the Stop run logs the prompt and tool calls while the final response is picked up on the next hook run (either the next turn's Stop or SessionEnd). If a session ends without SessionEnd running (for example, if the terminal is killed), that response is logged if you later resume the session with claude --resume.
  • Field truncation at 8,000 characters. Values exceeding 8,000 characters are truncated with a marker showing how many characters were omitted, keeping each step within the per-step size limit across all plans.
  • Turn completion latency. Because each step invokes jnh sequentially, turns with many tool calls take a few extra seconds to finish when the Stop hook runs.

Sensitive data in logs

Tool outputs include file contents, command output, and anything else Claude read during the session, including secrets in the repository or environment. The script does not redact them. Treat cc.* workspaces with the same sensitivity as the repositories they log, and restrict read access accordingly.