-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexport.py
More file actions
804 lines (701 loc) · 29.5 KB
/
export.py
File metadata and controls
804 lines (701 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
#!/usr/bin/env python3
"""CLI for exporting Claude Code chat history.
Examples:
export.py # zip of all sessions as markdown
export.py list # show projects
export.py list --project foo # show sessions in a project
export.py stats # token/cost totals
export.py stats --session UUID # single session breakdown
export.py --format json --no-zip # JSON files instead of zip
export.py --since incremental # only sessions new/changed since last run (mtime)
export.py --since last # all sessions active on latest UTC calendar day
"""
import argparse
import json
import os
import sys
import zipfile
from datetime import datetime
# Allow running from repo root or scripts/ directory
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.dirname(SCRIPT_DIR)
sys.path.insert(0, REPO_ROOT)
from utils.session_path import get_claude_projects_dir, list_projects, list_sessions
from utils.jsonl_parser import parse_session
from utils.session_stats import compute_stats, _format_duration
from utils.md_exporter import session_to_markdown
from utils.json_exporter import session_to_json
from utils.exclusion_rules import (
resolve_exclusion_rules_path,
load_rules,
is_session_excluded,
)
from utils.slugify import slugify
from utils.export_day_filter import collect_sessions_for_latest_activity_day
from utils.export_state_store import (
atomic_write_export_state,
export_state_lock,
load_export_state_from_disk,
)
STATE_DIR = os.path.join(os.path.expanduser("~"), ".claude-code-chat-browser")
STATE_FILE = os.path.join(STATE_DIR, "export_state.json")
def _project_matches(project: dict, needle: str) -> bool:
"""True if needle matches internal dir name or display_name (substring, case-insensitive)."""
if not needle:
return True
n = needle.lower()
if n in project["name"].lower():
return True
disp = project.get("display_name") or ""
return n in disp.lower()
def _zip_export_basename(
project_filter: str | None,
projects: list[dict],
date_tag: str,
*,
since: str = "all",
latest_day=None,
) -> str:
"""Zip filename (no directory): project slug and/or latest-day slug when set."""
from datetime import date
parts: list[str] = []
if project_filter:
if len(projects) == 1:
p0 = projects[0]
parts.append(
slugify(p0.get("display_name") or p0["name"], default="project")
)
else:
parts.append(
f"{slugify(project_filter, default='project')}-n{len(projects)}"
)
if since == "last" and latest_day is not None and isinstance(
latest_day, date
):
parts.append(f"last-{latest_day.strftime('%m-%d')}")
if parts:
return f"claude-code-export-{'-'.join(parts)}-{date_tag}.zip"
return f"claude-code-export-{date_tag}.zip"
def _prefixed_export_option_overrides(argv: list[str]) -> dict[str, object]:
"""Recover export flags written *before* the ``export`` subcommand.
When the same flag is registered on both the root parser and the ``export``
subparser, argparse can drop values from the segment before ``export`` and
apply the subparser defaults instead (e.g. ``--since incremental export`` becomes
``since=all``). Parse that prefix here so incremental export still works.
"""
if "export" not in argv:
return {}
pre = argv[: argv.index("export")]
opts: dict[str, object] = {}
i = 0
while i < len(pre):
a = pre[i]
if a == "--since" and i + 1 < len(pre) and pre[i + 1] in (
"all",
"last",
"incremental",
):
opts["since"] = pre[i + 1]
i += 2
continue
if a == "--out" and i + 1 < len(pre):
opts["out"] = pre[i + 1]
i += 2
continue
if a == "--no-zip":
opts["no_zip"] = True
i += 1
continue
if a in ("-e", "--exclude-rules") and i + 1 < len(pre):
opts["exclude_rules"] = pre[i + 1]
i += 2
continue
if a == "--base-dir" and i + 1 < len(pre):
opts["base_dir"] = pre[i + 1]
i += 2
continue
if a == "--project" and i + 1 < len(pre):
opts["project"] = pre[i + 1]
i += 2
continue
if a == "--format" and i + 1 < len(pre) and pre[i + 1] in ("md", "json", "both"):
opts["format"] = pre[i + 1]
i += 2
continue
if a == "--session" and i + 1 < len(pre):
opts["session"] = pre[i + 1]
i += 2
continue
i += 1
return opts
def main():
parser = build_parser()
args = parser.parse_args()
if getattr(args, "command", None) == "export":
for key, val in _prefixed_export_option_overrides(sys.argv[1:]).items():
setattr(args, key, val)
command = getattr(args, "command", None) or "export"
if command == "list":
cmd_list(args)
elif command == "stats":
cmd_stats(args)
else:
cmd_export(args)
def cmd_list(args):
"""Print a table of projects, or drill into one project's sessions."""
base_dir = getattr(args, "base_dir", None) or get_claude_projects_dir()
project_filter = getattr(args, "project", None)
if not os.path.isdir(base_dir):
_die(f"Claude Code projects directory not found: {base_dir}")
projects = list_projects(base_dir)
if project_filter:
projects = [p for p in projects if _project_matches(p, project_filter)]
if not projects:
print("No projects found.")
return
# If a specific project is selected, list its sessions
if project_filter and len(projects) == 1:
_list_sessions(projects[0])
return
# Otherwise list all projects
print(f"Projects ({len(projects)} found):\n")
print(f" {'Project':<45} {'Sessions':>8} {'Last Modified'}")
print(f" {chr(9472) * 45} {chr(9472) * 8} {chr(9472) * 19}")
for p in sorted(projects, key=lambda x: x.get("last_modified", ""), reverse=True):
name = p.get("display_name") or p["name"]
count = p.get("session_count", 0)
modified = p.get("last_modified", "")[:19].replace("T", " ")
print(f" {name:<45} {count:>8} {modified}")
def _list_sessions(project: dict):
"""Print each session in a project with title, tokens, tool count."""
sessions = list_sessions(project["path"])
name = project.get("display_name") or project["name"]
print(f"Sessions in {name} ({len(sessions)} found):\n")
print(f" {'Date':<12} {'Title':<50} {'ID':>10} {'Tokens':>10} {'Tools':>6}")
print(f" {chr(9472) * 12} {chr(9472) * 50} {chr(9472) * 10} {chr(9472) * 10} {chr(9472) * 6}")
for s in sorted(sessions, key=lambda x: x.get("modified", 0), reverse=True):
try:
parsed = parse_session(s["path"])
if parsed["title"] == "Untitled Session":
continue
meta = parsed["metadata"]
ts = (meta.get("first_timestamp") or "")[:10]
title = parsed["title"][:50]
sid = s["id"][:10]
tokens = meta["total_input_tokens"] + meta["total_output_tokens"]
tools = meta["total_tool_calls"]
print(f" {ts:<12} {title:<50} {sid:>10} {tokens:>10,} {tools:>6}")
except Exception as e:
print(f" Warning: failed to parse {s['id'][:10]}: {e}", file=sys.stderr)
continue
def cmd_stats(args):
"""Show stats -- either for one session or aggregated across all."""
base_dir = getattr(args, "base_dir", None) or get_claude_projects_dir()
project_filter = getattr(args, "project", None)
session_id = getattr(args, "session", None)
fmt = getattr(args, "format", "text") or "text"
if not os.path.isdir(base_dir):
_die(f"Claude Code projects directory not found: {base_dir}")
if session_id:
_session_stats(session_id, base_dir, fmt)
else:
_aggregate_stats(base_dir, project_filter, fmt)
def _session_stats(session_id: str, base_dir: str, fmt: str):
"""Detailed breakdown for one session: tokens, files, commands, cost."""
filepath = _find_session(session_id, base_dir)
if not filepath:
_die(f"Session not found: {session_id}")
session = parse_session(filepath)
stats = compute_stats(session)
if fmt == "json":
print(json.dumps(stats, indent=2, default=str))
return
meta = session["metadata"]
print(f"=== Session: {session_id[:12]} ===\n")
print(f" Title: {session['title']}")
if meta["first_timestamp"]:
print(f" Created: {meta['first_timestamp'][:19]}")
dur = _format_duration(meta.get("session_wall_time_seconds"))
if dur:
print(f" Duration: {dur}")
print(f" Models: {', '.join(meta['models_used']) or 'unknown'}")
inp = meta["total_input_tokens"]
out = meta["total_output_tokens"]
print(f" Tokens: {inp + out:,} (input: {inp:,} / output: {out:,})")
cache_r = meta["total_cache_read_tokens"]
cache_c = meta["total_cache_creation_tokens"]
if cache_r or cache_c:
print(f" Cache: read: {cache_r:,} / creation: {cache_c:,}")
print(f" Tool calls: {meta['total_tool_calls']}")
if meta["tool_call_counts"]:
breakdown = ", ".join(
f"{t}: {c}" for t, c in sorted(
meta["tool_call_counts"].items(), key=lambda x: -x[1]
)
)
print(f" {breakdown}")
if meta.get("stop_reasons"):
sr = ", ".join(f"{r}: {c}" for r, c in meta["stop_reasons"].items())
print(f" Stop: {sr}")
ft = stats.get("files_touched", {})
total_files = ft.get("total_unique", 0)
if total_files:
print(
f" Files: {total_files} unique "
f"({len(ft.get('read', []))} read, "
f"{len(ft.get('written', []))} edited, "
f"{len(ft.get('created', []))} created)"
)
cmds = stats.get("commands_run", [])
if cmds:
trs = stats.get("tool_result_summary", {})
ok = trs.get("bash_success", 0)
err = trs.get("bash_error", 0)
print(f" Commands: {len(cmds)} run ({ok} success, {err} error)")
if meta.get("compactions"):
print(f" Compactions: {meta['compactions']}")
if meta.get("api_errors"):
print(f" API errors: {meta['api_errors']}")
cost = stats.get("cost_estimate_usd")
if cost is not None:
print(f" Est. cost: ~${cost:.2f} USD")
def _aggregate_stats(base_dir: str, project_filter: str, fmt: str):
"""Sum up tokens, tools, cost across every session. Optionally filter
by project."""
projects = list_projects(base_dir)
if project_filter:
projects = [p for p in projects if _project_matches(p, project_filter)]
totals = {
"projects": len(projects),
"sessions": 0,
"input_tokens": 0,
"output_tokens": 0,
"cache_read_tokens": 0,
"cache_creation_tokens": 0,
"tool_calls": 0,
"tool_counts": {},
"models": set(),
"files_unique": set(),
"commands_run": 0,
"compactions": 0,
"api_errors": 0,
"total_cost": 0.0,
"has_cost": False,
}
for project in projects:
sessions = list_sessions(project["path"])
for s in sessions:
try:
session = parse_session(s["path"])
if session["title"] == "Untitled Session":
continue
meta = session["metadata"]
stats = compute_stats(session)
totals["sessions"] += 1
totals["input_tokens"] += meta["total_input_tokens"]
totals["output_tokens"] += meta["total_output_tokens"]
totals["cache_read_tokens"] += meta["total_cache_read_tokens"]
totals["cache_creation_tokens"] += meta["total_cache_creation_tokens"]
totals["tool_calls"] += meta["total_tool_calls"]
for t, c in meta["tool_call_counts"].items():
totals["tool_counts"][t] = totals["tool_counts"].get(t, 0) + c
totals["models"].update(meta["models_used"])
ft = stats.get("files_touched", {})
for category in ("read", "written", "created"):
totals["files_unique"].update(ft.get(category, []))
totals["commands_run"] += len(stats.get("commands_run", []))
totals["compactions"] += meta.get("compactions", 0)
totals["api_errors"] += meta.get("api_errors", 0)
cost = stats.get("cost_estimate_usd")
if cost is not None:
totals["total_cost"] += cost
totals["has_cost"] = True
except Exception as e:
print(f" Warning: failed to parse {s['id'][:10]} in {project['name']}: {e}", file=sys.stderr)
continue
if fmt == "json":
out = dict(totals)
out["models"] = sorted(out["models"])
out["files_unique"] = len(out["files_unique"])
print(json.dumps(out, indent=2, default=str))
return
total_tokens = totals["input_tokens"] + totals["output_tokens"]
print("=== Aggregate Stats ===\n")
print(f" Projects: {totals['projects']}")
print(f" Sessions: {totals['sessions']}")
print(f" Models: {', '.join(sorted(totals['models'])) or 'none'}")
print(f" Total tokens: {total_tokens:,} (input: {totals['input_tokens']:,} / output: {totals['output_tokens']:,})")
if totals["cache_read_tokens"]:
print(f" Cache: read: {totals['cache_read_tokens']:,} / creation: {totals['cache_creation_tokens']:,}")
print(f" Tool calls: {totals['tool_calls']:,}")
if totals["tool_counts"]:
breakdown = ", ".join(
f"{t}: {c}" for t, c in sorted(
totals["tool_counts"].items(), key=lambda x: -x[1]
)[:10]
)
print(f" {breakdown}")
print(f" Files: {len(totals['files_unique']):,} unique")
print(f" Commands: {totals['commands_run']:,}")
if totals["compactions"]:
print(f" Compactions: {totals['compactions']}")
if totals["api_errors"]:
print(f" API errors: {totals['api_errors']}")
if totals["has_cost"]:
print(f" Est. cost: ~${totals['total_cost']:.2f} USD")
def _append_export_for_session(
project: dict,
sess_info: dict,
session: dict,
fmt: str,
all_exports: list,
manifest: list,
last_export: dict,
) -> None:
"""Append markdown/json entries and manifest row; update *last_export* mtime."""
sid = sess_info["id"]
stats = compute_stats(session)
meta = session["metadata"]
ts = meta.get("first_timestamp", "")
if not ts:
from datetime import datetime as _dt
ts = _dt.fromtimestamp(sess_info["modified"]).strftime(
"%Y-%m-%dT%H:%M:%S"
)
meta["first_timestamp"] = ts
date_str = ts[:10]
ts_file = ts[:19].replace(":", "-")
title_slug = slugify(session["title"], default="session")
short_id = sid[:8]
project_slug = slugify(project["name"], default="project")
if fmt in ("md", "both"):
md = session_to_markdown(session, stats)
rel_path = os.path.join(
date_str, project_slug, f"{ts_file}__{title_slug}__{short_id}.md"
)
all_exports.append((rel_path, md))
if fmt in ("json", "both"):
js = session_to_json(session, stats)
rel_path = os.path.join(
date_str, project_slug, f"{ts_file}__{title_slug}__{short_id}.json"
)
all_exports.append((rel_path, js))
manifest.append({
"session_id": sid,
"title": session["title"],
"project": project["name"],
"updated_at": meta.get("last_timestamp", ""),
"models": meta.get("models_used", []),
"tokens": meta["total_input_tokens"] + meta["total_output_tokens"],
"tool_calls": meta["total_tool_calls"],
"files_touched": stats.get("files_touched", {}).get(
"total_unique", 0
),
"commands_run": len(stats.get("commands_run", [])),
"cost_estimate_usd": stats.get("cost_estimate_usd"),
"wall_clock_seconds": meta.get("session_wall_time_seconds"),
})
last_export[sid] = sess_info["modified"]
def cmd_export(args):
"""The main export command. Writes md/json files, optionally zipped."""
base_dir = getattr(args, "base_dir", None) or get_claude_projects_dir()
out_dir = getattr(args, "out", None) or os.getcwd()
since = getattr(args, "since", None) or "all"
no_zip = getattr(args, "no_zip", False)
project_filter = getattr(args, "project", None)
fmt = getattr(args, "format", None) or "md"
session_filter = getattr(args, "session", None)
exclusion_rules_path = getattr(args, "exclude_rules", None)
if not os.path.isdir(base_dir):
_die(f"Claude Code projects directory not found: {base_dir}")
rules = load_rules(resolve_exclusion_rules_path(exclusion_rules_path))
state = _load_state() if since == "incremental" else {}
last_export = dict(state.get("sessions", {}))
# Single session export
if session_filter:
filepath = _find_session(session_filter, base_dir)
if not filepath:
_die(f"Session not found: {session_filter}")
session = parse_session(filepath)
stats = compute_stats(session)
_export_single(session, stats, fmt, out_dir)
return
projects = list_projects(base_dir)
if project_filter:
projects = [p for p in projects if _project_matches(p, project_filter)]
if not projects:
print("No projects found.")
return
print(f"Found {len(projects)} project(s) in {base_dir}")
all_exports = [] # list of (rel_path, content)
manifest = []
total_sessions = 0
skipped = 0
skipped_mtime_unchanged = 0
latest_day = None
if since == "last":
d, rows, total_sessions = collect_sessions_for_latest_activity_day(
projects,
list_sessions=list_sessions,
parse_session=parse_session,
is_session_excluded=is_session_excluded,
rules=rules,
)
if d is None:
print("Nothing to export (no qualifying sessions in scope).")
return
latest_day = d
print(
f"Latest activity end-date (UTC): {d.isoformat()} — "
f"exporting sessions that overlap that calendar day."
)
if not rows:
print(
f"No sessions overlap {d.isoformat()} (UTC); nothing to export."
)
return
skipped = total_sessions - len(rows)
for project, sess_info, session, _st, _en in rows:
_append_export_for_session(
project,
sess_info,
session,
fmt,
all_exports,
manifest,
last_export,
)
else:
for project in projects:
sessions = list_sessions(project["path"])
for sess_info in sessions:
total_sessions += 1
sid = sess_info["id"]
if since == "incremental":
prev_mtime = last_export.get(sid, 0)
if sess_info["modified"] <= prev_mtime:
skipped += 1
skipped_mtime_unchanged += 1
continue
try:
session = parse_session(sess_info["path"])
except Exception as e:
print(f" Warning: failed to parse {sid}: {e}")
continue
if session["title"] == "Untitled Session":
skipped += 1
continue
if is_session_excluded(
rules,
session,
project.get("display_name") or project["name"],
):
skipped += 1
continue
_append_export_for_session(
project,
sess_info,
session,
fmt,
all_exports,
manifest,
last_export,
)
exported = len(all_exports)
print(
f"Exporting {exported} file(s) "
f"({skipped} skipped, {total_sessions} total)"
)
if not all_exports:
print("Nothing to export.")
if since == "incremental":
last_t = state.get("lastExportTime")
if last_t:
print(f"Last export: {last_t}")
last_dir = state.get("exportDir")
if last_dir:
print(f"Last export directory: {last_dir}")
if skipped_mtime_unchanged > 0:
print(
"All sessions on disk were already at or before the last "
"recorded export time (nothing new to write)."
)
return
os.makedirs(out_dir, exist_ok=True)
if no_zip:
for rel_path, content in all_exports:
full_path = os.path.join(out_dir, rel_path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
with open(full_path, "w", encoding="utf-8") as f:
f.write(content)
manifest_path = os.path.join(out_dir, "manifest.jsonl")
with open(manifest_path, "w", encoding="utf-8") as f:
for entry in manifest:
f.write(json.dumps(entry, default=str) + "\n")
print(f"Exported {exported} file(s) to {out_dir}")
else:
date_tag = datetime.now().strftime("%Y-%m-%d")
zip_name = _zip_export_basename(
project_filter,
projects,
date_tag,
since=since,
latest_day=latest_day,
)
zip_path = os.path.join(out_dir, zip_name)
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
for rel_path, content in all_exports:
zf.writestr(rel_path, content)
manifest_str = "\n".join(
json.dumps(e, default=str) for e in manifest
)
zf.writestr("manifest.jsonl", manifest_str)
print(f"Exported {exported} file(s) to {zip_path}")
_save_state(last_export, count=len(manifest), out_dir=out_dir)
print(f"State saved to {STATE_FILE}")
def _export_single(session: dict, stats: dict, fmt: str, out_dir: str):
"""Write one session to disk as md, json, or both."""
title_slug = slugify(session["title"], default="session")
short_id = session["session_id"][:8]
ts = session["metadata"].get("first_timestamp", "")
ts_file = ts[:19].replace(":", "-") if ts else "0000-00-00T00-00-00"
files = []
if fmt in ("md", "both"):
md = session_to_markdown(session, stats)
files.append((f"{ts_file}__{title_slug}__{short_id}.md", md))
if fmt in ("json", "both"):
js = session_to_json(session, stats)
files.append((f"{ts_file}__{title_slug}__{short_id}.json", js))
os.makedirs(out_dir, exist_ok=True)
for fname, content in files:
fpath = os.path.join(out_dir, fname)
with open(fpath, "w", encoding="utf-8") as f:
f.write(content)
print(f"Exported: {fpath}")
# ==================== Helpers ====================
# ==================== Argument Parser ====================
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Export Claude Code chat history to Markdown/JSON",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
# Global options (for backward compatibility when no subcommand)
parser.add_argument("--base-dir", default=None,
help="Override Claude Code projects directory")
parser.add_argument("--project", default=None,
help="Filter by project (substring on list display name or dir name)")
parser.add_argument("--since", choices=["all", "last", "incremental"], default=None,
help="'last' = latest UTC calendar day; 'incremental' = new since last export (mtime)")
parser.add_argument("--out", default=None,
help="Output directory (default: current dir)")
parser.add_argument("--no-zip", action="store_true", default=False,
help="Write individual files instead of zip")
parser.add_argument("--format", choices=["md", "json", "both"],
default=None, help="Export format (default: md)")
parser.add_argument("--session", default=None,
help="Export/stats for single session (UUID prefix)")
parser.add_argument(
"--exclude-rules", "-e",
default=None,
metavar="PATH",
dest="exclude_rules",
help="Path to exclusion rules file (sensitive sessions are omitted). "
"If omitted, uses ~/.claude-code-chat-browser/exclusion-rules.txt if present.",
)
subparsers = parser.add_subparsers(dest="command")
# List subcommand
list_p = subparsers.add_parser("list", help="List projects and sessions")
list_p.add_argument("--project", default=None,
help="Filter/select project (display name or dir name substring)")
list_p.add_argument("--base-dir", default=None,
help="Override Claude Code projects directory")
# Stats subcommand
stats_p = subparsers.add_parser("stats", help="Show statistics")
stats_p.add_argument("--session", default=None,
help="Stats for specific session (UUID prefix)")
stats_p.add_argument("--format", choices=["text", "json"], default="text",
help="Output format (default: text)")
stats_p.add_argument("--project", default=None,
help="Filter by project (display name or dir name substring)")
stats_p.add_argument("--base-dir", default=None,
help="Override Claude Code projects directory")
# Export subcommand (explicit)
export_p = subparsers.add_parser("export", help="Export sessions")
export_p.add_argument("--since", choices=["all", "last", "incremental"], default="all",
help="'last' = latest UTC day; 'incremental' = new since last export")
export_p.add_argument("--out", default=None,
help="Output directory (default: current dir)")
export_p.add_argument("--no-zip", action="store_true",
help="Write individual files instead of zip")
export_p.add_argument("--format", choices=["md", "json", "both"],
default="md", help="Export format (default: md)")
export_p.add_argument("--session", default=None,
help="Export single session by UUID prefix")
export_p.add_argument("--project", default=None,
help="Filter by project (display name or dir name substring)")
export_p.add_argument("--base-dir", default=None,
help="Override Claude Code projects directory")
export_p.add_argument(
"--exclude-rules", "-e",
default=None,
metavar="PATH",
dest="exclude_rules",
help="Path to exclusion rules file (sensitive sessions are omitted). "
"If omitted, uses ~/.claude-code-chat-browser/exclusion-rules.txt if present.",
)
return parser
def _find_session(session_id: str, base_dir: str) -> str | None:
"""Scan all projects for a session matching this UUID (or prefix).
Fails if the prefix matches more than one session."""
matches = []
for project in list_projects(base_dir):
for s in list_sessions(project["path"]):
if s["id"] == session_id:
return s["path"]
if s["id"].startswith(session_id):
matches.append(s)
if len(matches) == 1:
return matches[0]["path"]
if len(matches) > 1:
_die(
f"Ambiguous prefix '{session_id}' matches {len(matches)} sessions:\n"
+ "\n".join(f" {m['id']}" for m in matches)
)
return None
def _load_state() -> dict:
"""Load export state, migrating legacy flat format to the current schema.
Current schema::
{
"lastExportTime": "2026-02-25T12:00:00",
"exportedCount": 42,
"exportDir": "/path/to/out",
"sessions": {"<session-uuid>": <mtime-float>, ...}
}
Legacy schema (written by older versions)::
{"<session-uuid>": <mtime-float>, ...}
"""
with export_state_lock(STATE_FILE):
return load_export_state_from_disk(STATE_FILE)
def _save_state(sessions: dict, count: int, out_dir: str):
"""Persist export state with standardised fields matching cursor-chat-browser.
Merges ``sessions`` into any concurrent updates on disk (same lock/atomic
path as the web API).
"""
with export_state_lock(STATE_FILE):
disk = load_export_state_from_disk(STATE_FILE)
disk["lastExportTime"] = datetime.now().isoformat()
disk["exportedCount"] = count
disk["exportDir"] = out_dir
base = disk.get("sessions")
if not isinstance(base, dict):
base = {}
merged = dict(base)
merged.update(sessions)
disk["sessions"] = merged
atomic_write_export_state(disk, STATE_FILE)
def _die(msg: str):
print(f"Error: {msg}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()