cc-session 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #!/usr/bin/env bash
  2. # cc-session: Analyze Claude Code session JSONL logs
  3. # Zero dependencies beyond jq (required) and standard coreutils.
  4. #
  5. # Usage:
  6. # cc-session <command> [session.jsonl] [options]
  7. # cc-session <command> --project <project-name> [options]
  8. # cc-session <command> --dir <directory-pattern> [options]
  9. #
  10. # If no file given, uses the most recent session in the current project.
  11. set -euo pipefail
  12. CLAUDE_DIR="${CLAUDE_DIR:-$HOME/.claude}"
  13. PROJECTS_DIR="$CLAUDE_DIR/projects"
  14. # --- Helpers ---
  15. die() { printf 'error: %s\n' "$1" >&2; exit 1; }
  16. usage() {
  17. cat <<'USAGE'
  18. cc-session - Claude Code session log analyzer
  19. COMMANDS:
  20. overview Entry type counts, duration, model info
  21. tools Tool usage frequency (sorted)
  22. tool-chain Sequential tool call trace with timing
  23. thinking Extract thinking/reasoning blocks
  24. thinking-summary First 200 chars of each thinking block
  25. errors Tool results containing errors
  26. conversation Reconstructed user/assistant turns
  27. files Files read, edited, or written
  28. turns Per-turn breakdown (duration, tools, tokens)
  29. agents Subagent spawns and their tool usage
  30. search <pattern> Search across sessions (user + assistant text)
  31. cost Rough token/cost estimation
  32. timeline Event timeline with gaps highlighted
  33. summary Session summaries (compaction boundaries)
  34. OPTIONS:
  35. --project, -p <name> Filter by project name (partial match)
  36. --dir, -d <pattern> Filter by directory pattern in project path
  37. --all Search all projects (with search command)
  38. --recent <n> Use nth most recent session (default: 1)
  39. --json Output as JSON instead of text
  40. EXAMPLES:
  41. cc-session overview # Current project, latest session
  42. cc-session tools # Tool frequency
  43. cc-session tools --recent 2 # Second most recent session
  44. cc-session search "auth" --all # Search all projects
  45. cc-session errors -p claude-mods # Errors in claude-mods project
  46. cc-session tool-chain # Full tool call sequence
  47. cc-session thinking | grep -i "decision" # Search reasoning
  48. cc-session turns --json | jq '.[] | select(.tools > 5)'
  49. USAGE
  50. exit 0
  51. }
  52. # Resolve project directory from current working directory
  53. resolve_project() {
  54. local project_filter="${1:-}"
  55. if [[ -n "$project_filter" ]]; then
  56. # Find by partial match
  57. local found
  58. found=$(ls "$PROJECTS_DIR" 2>/dev/null | grep -i "$project_filter" | head -1)
  59. [[ -n "$found" ]] || die "No project matching '$project_filter'"
  60. echo "$PROJECTS_DIR/$found"
  61. else
  62. # Derive from cwd
  63. local encoded
  64. encoded=$(pwd | sed 's/[:\\\/]/-/g' | sed 's/--*/-/g')
  65. local found
  66. found=$(ls "$PROJECTS_DIR" 2>/dev/null | grep -i "${encoded##*-}" | head -1)
  67. if [[ -n "$found" ]]; then
  68. echo "$PROJECTS_DIR/$found"
  69. else
  70. die "Cannot determine project from $(pwd). Use --project <name>"
  71. fi
  72. fi
  73. }
  74. # Resolve session file
  75. resolve_session() {
  76. local project_dir="$1"
  77. local recent="${2:-1}"
  78. ls -t "$project_dir"/*.jsonl 2>/dev/null | grep -v 'agent-' | sed -n "${recent}p"
  79. }
  80. # --- Commands ---
  81. cmd_overview() {
  82. local f="$1" json="${2:-}"
  83. if [[ "$json" == "json" ]]; then
  84. cat "$f" | jq -sc '{
  85. file: input_filename,
  86. entries: length,
  87. types: (group_by(.type) | map({type: .[0].type, count: length})),
  88. first_ts: (map(.timestamp | select(.) | strings) | sort | first),
  89. last_ts: (map(.timestamp | select(.) | strings) | sort | last),
  90. duration_ms: (
  91. [.[] | select(.type == "system" and .subtype == "turn_duration") | .durationMs] | add
  92. ),
  93. turns: ([.[] | select(.type == "system" and .subtype == "turn_duration")] | length),
  94. tool_calls: ([.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use")] | length),
  95. thinking_blocks: ([.[] | select(.type == "assistant") | .message.content[]? | select(.type == "thinking")] | length),
  96. user_messages: ([.[] | select(.type == "user") | .message.content[]? | select(.type == "text")] | length)
  97. }' 2>/dev/null
  98. else
  99. echo "=== Session Overview ==="
  100. echo "File: $(basename "$f")"
  101. echo ""
  102. echo "--- Entry Types ---"
  103. cat "$f" | jq -r '.type' | sort | uniq -c | sort -rn
  104. echo ""
  105. echo "--- Timing ---"
  106. cat "$f" | jq -sc '
  107. ([.[] | select(.type == "system" and .subtype == "turn_duration") | .durationMs] | add // 0) as $total |
  108. ([.[] | select(.type == "system" and .subtype == "turn_duration")] | length) as $turns |
  109. "Total time: \($total / 1000 | floor)s (\($total / 60000 | floor)m \(($total / 1000 | floor) % 60)s)\nTurns: \($turns)\nAvg turn: \(if $turns > 0 then ($total / $turns / 1000 | floor) else 0 end)s"
  110. ' 2>/dev/null
  111. echo ""
  112. echo "--- Content ---"
  113. cat "$f" | jq -sc '
  114. ([.[] | select(.type == "user") | .message.content[]? | select(.type == "text")] | length) as $user_msgs |
  115. ([.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use")] | length) as $tools |
  116. ([.[] | select(.type == "assistant") | .message.content[]? | select(.type == "thinking")] | length) as $thinking |
  117. "User messages: \($user_msgs)\nTool calls: \($tools)\nThinking blocks: \($thinking)"
  118. ' 2>/dev/null
  119. fi
  120. }
  121. cmd_tools() {
  122. local f="$1" json="${2:-}"
  123. if [[ "$json" == "json" ]]; then
  124. cat "$f" | jq -sc '[
  125. .[] | select(.type == "assistant") | .message.content[]? |
  126. select(.type == "tool_use") | .name
  127. ] | group_by(.) | map({tool: .[0], count: length}) | sort_by(-.count)' 2>/dev/null
  128. else
  129. cat "$f" | jq -r '
  130. select(.type == "assistant") | .message.content[]? |
  131. select(.type == "tool_use") | .name
  132. ' | sort | uniq -c | sort -rn
  133. fi
  134. }
  135. cmd_tool_chain() {
  136. local f="$1" json="${2:-}"
  137. if [[ "$json" == "json" ]]; then
  138. cat "$f" | jq -c '
  139. select(.type == "assistant") | .message.content[]? |
  140. select(.type == "tool_use") |
  141. {name, id, input_summary: (
  142. if .name == "Bash" then (.input.command | .[0:120])
  143. elif .name == "Read" then .input.file_path
  144. elif .name == "Write" then .input.file_path
  145. elif .name == "Edit" then .input.file_path
  146. elif .name == "Grep" then "\(.input.pattern) in \(.input.path // ".")"
  147. elif .name == "Glob" then .input.pattern
  148. elif .name == "Agent" then "\(.input.subagent_type // "general"): \(.input.description // "")"
  149. elif .name == "Skill" then .input.skill
  150. elif .name == "WebSearch" then .input.query
  151. elif .name == "WebFetch" then .input.url
  152. else (.input | tostring | .[0:100])
  153. end
  154. )}
  155. ' 2>/dev/null
  156. else
  157. cat "$f" | jq -r '
  158. select(.type == "assistant") | .message.content[]? |
  159. select(.type == "tool_use") |
  160. "\(.name | . + " " * (15 - length)) \(
  161. if .name == "Bash" then (.input.command | .[0:100])
  162. elif .name == "Read" then .input.file_path
  163. elif .name == "Write" then .input.file_path
  164. elif .name == "Edit" then .input.file_path
  165. elif .name == "Grep" then "pattern=\(.input.pattern) path=\(.input.path // ".")"
  166. elif .name == "Glob" then .input.pattern
  167. elif .name == "Agent" then "\(.input.subagent_type // "general"): \(.input.description // "")"
  168. elif .name == "Skill" then .input.skill
  169. elif .name == "WebSearch" then .input.query
  170. elif .name == "WebFetch" then .input.url
  171. else (.input | tostring | .[0:80])
  172. end
  173. )"
  174. ' 2>/dev/null
  175. fi
  176. }
  177. cmd_thinking() {
  178. local f="$1"
  179. cat "$f" | jq -r '
  180. select(.type == "assistant") | .message.content[]? |
  181. select(.type == "thinking") | .thinking
  182. ' 2>/dev/null
  183. }
  184. cmd_thinking_summary() {
  185. local f="$1" json="${2:-}"
  186. if [[ "$json" == "json" ]]; then
  187. cat "$f" | jq -sc '[
  188. .[] | select(.type == "assistant") | .message.content[]? |
  189. select(.type == "thinking") | {preview: (.thinking | .[0:200])}
  190. ]' 2>/dev/null
  191. else
  192. local n=0
  193. cat "$f" | jq -r '
  194. select(.type == "assistant") | .message.content[]? |
  195. select(.type == "thinking") | .thinking | .[0:200] | gsub("\n"; " ")
  196. ' 2>/dev/null | while read -r line; do
  197. n=$((n + 1))
  198. printf "[%d] %s...\n\n" "$n" "$line"
  199. done
  200. fi
  201. }
  202. cmd_errors() {
  203. local f="$1" json="${2:-}"
  204. if [[ "$json" == "json" ]]; then
  205. cat "$f" | jq -c '
  206. select(.type == "user") | .message.content[]? |
  207. select(.type == "tool_result") |
  208. select(.content | type == "string" and test("error|Error|ERROR|failed|Failed|FAILED")) |
  209. {tool_use_id, error: (.content | .[0:300])}
  210. ' 2>/dev/null
  211. else
  212. cat "$f" | jq -r '
  213. select(.type == "user") | .message.content[]? |
  214. select(.type == "tool_result") |
  215. select(.content | type == "string" and test("error|Error|ERROR|failed|Failed|FAILED")) |
  216. "--- tool_use_id: \(.tool_use_id) ---\n\(.content | .[0:300])\n"
  217. ' 2>/dev/null
  218. fi
  219. }
  220. cmd_conversation() {
  221. local f="$1"
  222. cat "$f" | jq -r '
  223. if .type == "user" then
  224. .message.content[]? | select(.type == "text") | "USER: \(.text)"
  225. elif .type == "assistant" then
  226. .message.content[]? | select(.type == "text") | "CLAUDE: \(.text | .[0:500])"
  227. else empty end
  228. ' 2>/dev/null
  229. }
  230. cmd_files() {
  231. local f="$1" json="${2:-}"
  232. if [[ "$json" == "json" ]]; then
  233. cat "$f" | jq -sc '{
  234. read: [.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "Read") | .input.file_path] | group_by(.) | map({file: .[0], count: length}) | sort_by(-.count),
  235. edited: [.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "Edit") | .input.file_path] | group_by(.) | map({file: .[0], count: length}) | sort_by(-.count),
  236. written: [.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "Write") | .input.file_path] | unique
  237. }' 2>/dev/null
  238. else
  239. echo "=== Files Read ==="
  240. cat "$f" | jq -r 'select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "Read") | .input.file_path' | sort | uniq -c | sort -rn
  241. echo ""
  242. echo "=== Files Edited ==="
  243. cat "$f" | jq -r 'select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "Edit") | .input.file_path' | sort | uniq -c | sort -rn
  244. echo ""
  245. echo "=== Files Written ==="
  246. cat "$f" | jq -r 'select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "Write") | .input.file_path' | sort -u
  247. fi
  248. }
  249. cmd_turns() {
  250. local f="$1" json="${2:-}"
  251. cat "$f" | jq -sc '
  252. [.[] | select(.type == "system" and .subtype == "turn_duration")] as $durations |
  253. [.[] | select(.type == "assistant")] as $assistants |
  254. [range(0; [$durations | length, $assistants | length] | min) |
  255. {
  256. turn: (. + 1),
  257. duration_s: ($durations[.].durationMs / 1000 | floor),
  258. tools: ([$assistants[.].message.content[]? | select(.type == "tool_use") | .name] | length),
  259. tool_names: ([$assistants[.].message.content[]? | select(.type == "tool_use") | .name]),
  260. has_thinking: ([$assistants[.].message.content[]? | select(.type == "thinking")] | length > 0),
  261. text_length: ([$assistants[.].message.content[]? | select(.type == "text") | .text | length] | add // 0)
  262. }
  263. ]
  264. ' 2>/dev/null | if [[ "$json" == "json" ]]; then cat; else
  265. jq -r '.[] | "Turn \(.turn): \(.duration_s)s, \(.tools) tools [\(.tool_names | join(", "))]\(if .has_thinking then " [thinking]" else "" end)"' 2>/dev/null
  266. fi
  267. }
  268. cmd_agents() {
  269. local f="$1" json="${2:-}"
  270. if [[ "$json" == "json" ]]; then
  271. cat "$f" | jq -c '
  272. select(.type == "assistant") | .message.content[]? |
  273. select(.type == "tool_use" and .name == "Agent") |
  274. {
  275. id,
  276. subagent_type: (.input.subagent_type // "general-purpose"),
  277. description: .input.description,
  278. prompt_preview: (.input.prompt | .[0:200]),
  279. background: (.input.run_in_background // false),
  280. isolation: (.input.isolation // null)
  281. }
  282. ' 2>/dev/null
  283. else
  284. cat "$f" | jq -r '
  285. select(.type == "assistant") | .message.content[]? |
  286. select(.type == "tool_use" and .name == "Agent") |
  287. "[\(.input.subagent_type // "general")] \(.input.description // "no description")\n prompt: \(.input.prompt | .[0:150] | gsub("\n"; " "))...\n"
  288. ' 2>/dev/null
  289. fi
  290. }
  291. cmd_search() {
  292. local pattern="$1"
  293. shift
  294. local search_dir="$1"
  295. rg -l "$pattern" "$search_dir"/*.jsonl 2>/dev/null | while read -r f; do
  296. local session
  297. session=$(basename "$f" .jsonl)
  298. echo "=== $session ==="
  299. cat "$f" | jq -r "
  300. if .type == \"user\" then
  301. .message.content[]? | select(.type == \"text\") | .text
  302. elif .type == \"assistant\" then
  303. .message.content[]? | select(.type == \"text\") | .text
  304. else empty end
  305. " 2>/dev/null | grep -i --color=auto -C2 "$pattern" || true
  306. echo ""
  307. done
  308. }
  309. cmd_cost() {
  310. local f="$1" json="${2:-}"
  311. cat "$f" | jq -sc '
  312. ([.[] | select(.type == "user") | .message.content[]? | select(.type == "text") | .text | length] | add // 0) as $user_chars |
  313. ([.[] | select(.type == "assistant") | .message.content[]? | select(.type == "text") | .text | length] | add // 0) as $asst_chars |
  314. ([.[] | select(.type == "assistant") | .message.content[]? | select(.type == "thinking") | .thinking | length] | add // 0) as $think_chars |
  315. ($user_chars + $asst_chars + $think_chars) as $total_chars |
  316. ($total_chars / 4 | floor) as $est_tokens |
  317. {
  318. user_chars: $user_chars,
  319. assistant_chars: $asst_chars,
  320. thinking_chars: $think_chars,
  321. total_chars: $total_chars,
  322. est_tokens: $est_tokens,
  323. est_tokens_k: (($est_tokens / 1000 * 10 | floor) / 10)
  324. }
  325. ' 2>/dev/null | if [[ "$json" == "json" ]]; then cat; else
  326. jq -r '"Token estimate: \(.est_tokens_k)k tokens\n User: \(.user_chars) chars\n Assistant: \(.assistant_chars) chars\n Thinking: \(.thinking_chars) chars"' 2>/dev/null
  327. fi
  328. }
  329. cmd_timeline() {
  330. local f="$1"
  331. cat "$f" | jq -r '
  332. select(.type == "user" or .type == "assistant") |
  333. select(.timestamp) |
  334. "\(.timestamp) \(.type | . + " " * (12 - length)) \(
  335. if .type == "user" then
  336. (.message.content[]? | select(.type == "text") | .text | .[0:80] | gsub("\n"; " ")) // "[tool_result]"
  337. else
  338. (.message.content[]? |
  339. if .type == "tool_use" then "[\(.name)] \(
  340. if .name == "Bash" then (.input.command | .[0:60])
  341. elif .name == "Read" then .input.file_path
  342. elif .name == "Edit" then .input.file_path
  343. elif .name == "Write" then .input.file_path
  344. else (.input | tostring | .[0:60])
  345. end
  346. )"
  347. elif .type == "text" then .text | .[0:80] | gsub("\n"; " ")
  348. elif .type == "thinking" then "[thinking...]"
  349. else empty
  350. end
  351. ) // ""
  352. end
  353. )"
  354. ' 2>/dev/null
  355. }
  356. cmd_summary() {
  357. local f="$1"
  358. cat "$f" | jq -r '
  359. select(.type == "summary" or (.type == "system" and .subtype == "compact_boundary")) |
  360. if .type == "summary" then
  361. "=== Summary ===\n\(.summary)\n"
  362. else
  363. "--- Compaction Boundary ---"
  364. end
  365. ' 2>/dev/null
  366. }
  367. # --- Main ---
  368. [[ $# -eq 0 ]] && usage
  369. cmd="$1"
  370. shift
  371. # Parse options
  372. session_file=""
  373. project=""
  374. recent=1
  375. output="text"
  376. search_all=false
  377. dir_pattern=""
  378. while [[ $# -gt 0 ]]; do
  379. case "$1" in
  380. --project|-p) project="$2"; shift 2 ;;
  381. --dir|-d) dir_pattern="$2"; shift 2 ;;
  382. --recent) recent="$2"; shift 2 ;;
  383. --json) output="json"; shift ;;
  384. --all) search_all=true; shift ;;
  385. --help|-h) usage ;;
  386. *)
  387. if [[ -f "$1" ]]; then
  388. session_file="$1"
  389. elif [[ "$cmd" == "search" && -z "${search_pattern:-}" ]]; then
  390. search_pattern="$1"
  391. fi
  392. shift
  393. ;;
  394. esac
  395. done
  396. # Resolve session file if not given directly
  397. if [[ -z "$session_file" ]]; then
  398. project_dir=$(resolve_project "${project}${dir_pattern:+$dir_pattern}")
  399. session_file=$(resolve_session "$project_dir" "$recent")
  400. [[ -n "$session_file" ]] || die "No session files found in $project_dir"
  401. fi
  402. # Execute command
  403. case "$cmd" in
  404. overview) cmd_overview "$session_file" "$output" ;;
  405. tools) cmd_tools "$session_file" "$output" ;;
  406. tool-chain) cmd_tool_chain "$session_file" "$output" ;;
  407. thinking) cmd_thinking "$session_file" ;;
  408. thinking-summary) cmd_thinking_summary "$session_file" "$output" ;;
  409. errors) cmd_errors "$session_file" "$output" ;;
  410. conversation) cmd_conversation "$session_file" ;;
  411. files) cmd_files "$session_file" "$output" ;;
  412. turns) cmd_turns "$session_file" "$output" ;;
  413. agents) cmd_agents "$session_file" "$output" ;;
  414. cost) cmd_cost "$session_file" "$output" ;;
  415. timeline) cmd_timeline "$session_file" ;;
  416. summary) cmd_summary "$session_file" ;;
  417. search)
  418. [[ -n "${search_pattern:-}" ]] || die "search requires a pattern"
  419. if [[ "$search_all" == true ]]; then
  420. for d in "$PROJECTS_DIR"/*/; do
  421. echo ">>> $(basename "$d")"
  422. cmd_search "$search_pattern" "$d"
  423. done
  424. else
  425. project_dir=$(resolve_project "${project}${dir_pattern:+$dir_pattern}")
  426. cmd_search "$search_pattern" "$project_dir"
  427. fi
  428. ;;
  429. *)
  430. die "Unknown command: $cmd. Run cc-session --help for usage."
  431. ;;
  432. esac