clockwork-cli 0.3.0__py3-none-any.whl → 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clockwork_cli/__init__.py CHANGED
@@ -47,7 +47,7 @@ Examples:
47
47
 
48
48
  Data sources:
49
49
  claude → ~/.claude/projects/<encoded-path>/*.jsonl
50
- codex → $CODEX_HOME/sessions/**/rollout-*.jsonl (default ~/.codex/sessions)
50
+ codex → $CODEX_HOME/sessions/**/rollout-*.jsonl[.zst] (default ~/.codex/sessions)
51
51
 
52
52
  Token usage (--tokens):
53
53
  Both tools log per-response usage, counted differently, so clockwork
@@ -55,8 +55,10 @@ Token usage (--tokens):
55
55
 
56
56
  claude → `assistant` records carry message.model + message.usage. One API
57
57
  response spans several lines (thinking, text, each tool_use), each
58
- repeating the same usage block, so responses are deduplicated on
59
- message id. Cache reads/writes sit outside input_tokens.
58
+ repeating its usage block, so responses are deduplicated on
59
+ message id, keeping the final (largest) count per field.
60
+ Subagent logs (<session>/subagents/*.jsonl) are included. Cache
61
+ reads/writes sit outside input_tokens.
60
62
  codex → `event_msg -> token_count` records carry a cumulative
61
63
  total_token_usage; per-turn cost is read as the rise in that counter
62
64
  because last_token_usage is re-emitted on aborted turns. The model
@@ -69,11 +71,12 @@ import json
69
71
  import os
70
72
  import re
71
73
  import glob
74
+ import bisect
72
75
  import hashlib
73
76
  from datetime import datetime, timedelta, timezone
74
77
  from collections import defaultdict
75
78
 
76
- __version__ = "0.3.0"
79
+ __version__ = "0.4.1"
77
80
 
78
81
 
79
82
  def _resolve_claude_dir():
@@ -350,33 +353,71 @@ def _display_name(path):
350
353
  # Claude backend (~/.claude/projects/<encoded-path>/*.jsonl)
351
354
  # --------------------------------------------------------------------------- #
352
355
 
356
+ def _claude_encode_path(path):
357
+ """Encode a path the way Claude Code names its per-project log folder.
358
+
359
+ Every character that is not an ASCII letter or digit becomes `-`, so
360
+ `/a/team-5/My Drive` and `/a/team/5/My-Drive` both encode to
361
+ `-a-team-5-My-Drive`. That makes the encoding lossy; see
362
+ `_claude_folder_cwd` for recovering the real path.
363
+ """
364
+ return re.sub(r"[^A-Za-z0-9]", "-", path)
365
+
366
+
353
367
  def path_to_claude_folder(project_path):
354
368
  abs_path = os.path.abspath(os.path.expanduser(project_path))
355
- folder_name = abs_path.replace("/", "-").replace("\\", "-").replace(":", "-")
369
+ folder_name = _claude_encode_path(abs_path)
356
370
  if folder_name.startswith("-"):
357
371
  folder_name = folder_name[1:]
358
372
  return folder_name
359
373
 
360
374
 
375
+ def _claude_session_files(folder_dir):
376
+ """Return ([session logs], [subagent logs]) for one Claude project folder.
377
+
378
+ Subagent transcripts are not part of the session log: Claude Code writes
379
+ them beside it, under `<session-id>/subagents/agent-*.jsonl`.
380
+ """
381
+ sessions = glob.glob(os.path.join(folder_dir, "*.jsonl"))
382
+ subagents = glob.glob(os.path.join(folder_dir, "*", "subagents", "*.jsonl"))
383
+ return sessions, subagents
384
+
385
+
361
386
  def _claude_resolve_files(project_path):
362
- """Return (folder_name, [files]) for a project path, or (None, [])."""
387
+ """Return (folder_name, [session logs], [subagent logs]) for a project
388
+ path, or (None, [], [])."""
363
389
  folder = path_to_claude_folder(project_path)
364
390
  # Claude Code retains the leading dash from the absolute path, so try both
365
391
  # the dash-prefixed and stripped forms to match whichever convention exists.
366
392
  for candidate in ("-" + folder, folder):
367
- files = glob.glob(os.path.join(CLAUDE_DIR, candidate, "*.jsonl"))
393
+ files, subagents = _claude_session_files(os.path.join(CLAUDE_DIR, candidate))
368
394
  if files:
369
- return candidate, files
370
- return None, []
395
+ return candidate, files, subagents
396
+ return None, [], []
397
+
398
+
399
+ _CLAUDE_USAGE_FIELDS = (
400
+ ("input", "input_tokens"),
401
+ ("output", "output_tokens"),
402
+ ("cache_read", "cache_read_input_tokens"),
403
+ ("cache_write", "cache_creation_input_tokens"),
404
+ )
371
405
 
372
406
 
373
407
  def _claude_token_event(record, dt, seen):
374
408
  """Normalize one Claude assistant record into a token event, or None.
375
409
 
376
410
  Claude Code writes one line per content block — thinking, text, and each
377
- tool_use — and every line of a single API response repeats the *identical*
378
- usage object. Counting per line inflates totals roughly 2.6x, so responses
379
- are deduplicated on the message id (falling back to the request id).
411
+ tool_use — and every line repeats the usage of the whole API response.
412
+ Counting per line inflates totals roughly 2.6x, so responses are
413
+ deduplicated on the message id (falling back to the request id).
414
+
415
+ The repeated usage is not always identical: subagent logs write the first
416
+ line while the response is still streaming (`output_tokens: 3`) and only
417
+ the last line carries the final count. So a repeat is folded into the
418
+ event already recorded, keeping the larger value per field. Main-thread
419
+ lines are identical, so for them this is the same as keeping the first.
420
+ `seen` maps each key to the event recorded for it.
380
421
  """
381
422
  message = record.get("message") or {}
382
423
  usage = message.get("usage")
@@ -385,34 +426,105 @@ def _claude_token_event(record, dt, seen):
385
426
  # they carry a zero usage block and never hit the API.
386
427
  if not usage or not model or model == "<synthetic>" or dt is None:
387
428
  return None
429
+ event = {"ts": dt, "model": model}
430
+ for field, usage_key in _CLAUDE_USAGE_FIELDS:
431
+ event[field] = usage.get(usage_key) or 0
432
+ event["reasoning"] = 0 # Claude folds thinking into output_tokens
388
433
  key = message.get("id") or record.get("requestId")
389
434
  if key is not None:
390
- if key in seen:
435
+ prior = seen.get(key)
436
+ if prior is not None:
437
+ for field, _ in _CLAUDE_USAGE_FIELDS:
438
+ prior[field] = max(prior[field], event[field])
391
439
  return None
392
- seen.add(key)
393
- return {
394
- "ts": dt,
395
- "model": model,
396
- "input": usage.get("input_tokens") or 0,
397
- "output": usage.get("output_tokens") or 0,
398
- "cache_read": usage.get("cache_read_input_tokens") or 0,
399
- "cache_write": usage.get("cache_creation_input_tokens") or 0,
400
- "reasoning": 0, # Claude folds thinking into output_tokens
401
- }
402
-
403
-
404
- def _claude_scan_files(files):
405
- """Return (prompt timestamps, token events) from Claude .jsonl files.
406
-
407
- Both come out of a single pass: the files are already read end to end for
408
- the timestamps, so picking up usage costs nothing extra. The dedup set is
409
- shared across the whole file list so a response replayed into a resumed
440
+ seen[key] = event
441
+ return event
442
+
443
+
444
+ # Leading text of user-role records that Claude Code writes on the user's
445
+ # behalf rather than from anything sent as a prompt: local slash-command
446
+ # echoes and output (/model, /clear), `!` shell input and output, background
447
+ # task notifications, and interrupt markers. Skill-style commands that do go
448
+ # to the model start with `<command-message>` instead and are kept.
449
+ _CLAUDE_NOT_TYPED_PREFIXES = (
450
+ "<command-name>",
451
+ "<local-command-stdout>",
452
+ "<local-command-stderr>",
453
+ "<local-command-caveat>",
454
+ "<bash-input>",
455
+ "<bash-stdout>",
456
+ "<bash-stderr>",
457
+ "<task-notification>",
458
+ "<system-reminder>",
459
+ "[Request interrupted by user",
460
+ )
461
+
462
+
463
+ def _claude_is_typed_text(text):
464
+ text = (text or "").lstrip()
465
+ return bool(text) and not text.startswith(_CLAUDE_NOT_TYPED_PREFIXES)
466
+
467
+
468
+ def _claude_is_human_prompt(record):
469
+ """True when a user-role record is a message a person sent.
470
+
471
+ Most user-role records are not: the API returns every tool result to the
472
+ model as a user message, and Claude Code also logs injected context and
473
+ command output under the same role. Newer logs tag real input with
474
+ `origin.kind == "human"`, and that tag is trusted wherever it is present.
475
+ Records without an `origin` (older logs, and some newer ones) are
476
+ classified by shape instead.
477
+
478
+ One shape needs care: a message typed while a tool is running is folded
479
+ into that tool's result record as an extra text block. So a tool result
480
+ alone is not a prompt, but a tool result carrying typed text is.
481
+ """
482
+ origin = record.get("origin")
483
+ if isinstance(origin, dict) and origin.get("kind"):
484
+ return origin["kind"] == "human"
485
+ if record.get("isMeta") or record.get("isCompactSummary"):
486
+ return False
487
+ content = (record.get("message") or {}).get("content")
488
+ if isinstance(content, str):
489
+ return _claude_is_typed_text(content)
490
+ if not isinstance(content, list):
491
+ return False
492
+ blocks = [b for b in content if isinstance(b, dict)]
493
+ texts = [b.get("text") for b in blocks if b.get("type") == "text"]
494
+ if any(_claude_is_typed_text(t) for t in texts):
495
+ return True
496
+ # No typed text: an image pasted on its own still counts; a bare tool
497
+ # result or a wrapper-only record does not.
498
+ has_tool_result = any(b.get("type") == "tool_result" for b in blocks)
499
+ return not texts and not has_tool_result and bool(blocks)
500
+
501
+
502
+ def _claude_scan_files(files, subagent_files=()):
503
+ """Return (activity timestamps, token events, human prompt timestamps)
504
+ from Claude .jsonl files.
505
+
506
+ Activity is every user-role record, tool results included. Those are what
507
+ show Claude working through a long autonomous run, so session grouping and
508
+ active time are built on them. Human prompts are the subset a person
509
+ actually sent (`_claude_is_human_prompt`), deduplicated on record uuid
510
+ because a resumed session replays earlier messages into its new log.
511
+
512
+ Everything comes out of a single pass. The token dedup map is shared
513
+ across the whole file list so a response replayed into a resumed
410
514
  session's log is still only counted once.
515
+
516
+ `subagent_files` contribute token events only. Their user-role records are
517
+ the parent's task prompt plus tool results, none of it typed by a person
518
+ (see ROADMAP §1, which is where subagent activity belongs).
411
519
  """
412
520
  timestamps = []
521
+ human = []
413
522
  events = []
414
- seen = set()
415
- for f in sorted(files):
523
+ seen = {}
524
+ seen_prompts = set()
525
+ sources = [(f, True) for f in sorted(files)]
526
+ sources += [(f, False) for f in sorted(subagent_files)]
527
+ for f, is_session in sources:
416
528
  with open(f, encoding="utf-8") as fh:
417
529
  for line in fh:
418
530
  line = line.strip()
@@ -425,17 +537,19 @@ def _claude_scan_files(files):
425
537
  role = d.get("role") or d.get("type", "")
426
538
  dt = _parse_ts(d.get("timestamp"))
427
539
  if dt and role in ("human", "user"):
540
+ if not is_session:
541
+ continue
428
542
  timestamps.append(dt)
543
+ if _claude_is_human_prompt(d):
544
+ uid = d.get("uuid")
545
+ if uid is None or uid not in seen_prompts:
546
+ seen_prompts.add(uid)
547
+ human.append(dt)
429
548
  elif role == "assistant":
430
549
  event = _claude_token_event(d, dt, seen)
431
550
  if event:
432
551
  events.append(event)
433
- return sorted(timestamps), events
434
-
435
-
436
- def _claude_timestamps_from_files(files):
437
- """Parse user/human turn timestamps from Claude .jsonl files."""
438
- return _claude_scan_files(files)[0]
552
+ return sorted(timestamps), events, sorted(human)
439
553
 
440
554
 
441
555
  def _claude_folder_to_pretty(folder):
@@ -445,35 +559,66 @@ def _claude_folder_to_pretty(folder):
445
559
  return "/" + folder.lstrip("-").replace("-", "/")
446
560
 
447
561
 
562
+ def _claude_folder_cwd(folder, files):
563
+ """The project's real path, read from the `cwd` its records carry.
564
+
565
+ The folder name can't be decoded reliably (`team-5` and `team/5` encode
566
+ alike), and a wrong decode both mislabels the project and stops `both`
567
+ from merging it with the Codex rollouts for the same path. Every Claude
568
+ record carries `cwd`, so take the first one that encodes back to this
569
+ folder's name. The check matters because a session that `cd`s elsewhere
570
+ records the new cwd. Falls back to the decoded name if nothing matches.
571
+ """
572
+ for f in sorted(files):
573
+ try:
574
+ with open(f, encoding="utf-8") as fh:
575
+ for line in fh:
576
+ if '"cwd"' not in line:
577
+ continue
578
+ try:
579
+ cwd = json.loads(line).get("cwd")
580
+ except (json.JSONDecodeError, AttributeError):
581
+ continue
582
+ if cwd and _claude_encode_path(cwd) == folder:
583
+ return cwd
584
+ except OSError:
585
+ continue
586
+ return _claude_folder_to_pretty(folder)
587
+
588
+
448
589
  def claude_scan_single(project_path):
449
- folder, files = _claude_resolve_files(project_path)
590
+ folder, files, subagents = _claude_resolve_files(project_path)
450
591
  if not files:
451
- return None, 0, [], []
452
- ts, events = _claude_scan_files(files)
453
- return folder, len(files), ts, events
592
+ return None, 0, [], [], []
593
+ ts, events, human = _claude_scan_files(files, subagents)
594
+ return folder, len(files), ts, events, human
454
595
 
455
596
 
456
597
  def claude_single(project_path):
457
- folder, count, ts, _ = claude_scan_single(project_path)
458
- return folder, count, ts
598
+ folder, count, ts, _, human = claude_scan_single(project_path)
599
+ return folder, count, ts, human
459
600
 
460
601
 
461
602
  def claude_scan():
462
603
  result = []
463
604
  for folder in _claude_list_folders():
464
- files = glob.glob(os.path.join(CLAUDE_DIR, folder, "*.jsonl"))
465
- ts, events = _claude_scan_files(files)
605
+ files, subagents = _claude_session_files(os.path.join(CLAUDE_DIR, folder))
606
+ ts, events, human = _claude_scan_files(files, subagents)
466
607
  if ts:
467
- result.append((_claude_folder_to_pretty(folder), ts, events))
608
+ result.append((_claude_folder_cwd(folder, files), ts, events, human))
468
609
  return result
469
610
 
470
611
 
471
612
  def claude_all():
472
- return [(label, ts) for label, ts, _ in claude_scan()]
613
+ return [(label, ts, human) for label, ts, _, human in claude_scan()]
473
614
 
474
615
 
475
616
  def _claude_list_folders():
476
- return sorted(os.listdir(CLAUDE_DIR)) if os.path.exists(CLAUDE_DIR) else []
617
+ if not os.path.exists(CLAUDE_DIR):
618
+ return []
619
+ # Skip stray files such as macOS's .DS_Store; only folders hold logs.
620
+ return sorted(name for name in os.listdir(CLAUDE_DIR)
621
+ if os.path.isdir(os.path.join(CLAUDE_DIR, name)))
477
622
 
478
623
 
479
624
  def claude_list():
@@ -481,13 +626,79 @@ def claude_list():
481
626
 
482
627
 
483
628
  # --------------------------------------------------------------------------- #
484
- # Codex backend ($CODEX_HOME/sessions/**/rollout-*.jsonl)
629
+ # Codex backend ($CODEX_HOME/sessions/**/rollout-*.jsonl[.zst])
485
630
  # --------------------------------------------------------------------------- #
486
631
 
487
632
  def _codex_files():
633
+ """Every rollout under $CODEX_HOME/sessions, plain or zstd-compressed.
634
+
635
+ Newer Codex versions save finished rollouts as `rollout-*.jsonl.zst`.
636
+ If a rollout exists in both forms, the newer file wins so it is counted
637
+ once.
638
+ """
488
639
  codex_home = os.environ.get("CODEX_HOME", os.path.expanduser("~/.codex"))
489
- pattern = os.path.join(codex_home, "sessions", "**", "rollout-*.jsonl")
490
- return glob.glob(pattern, recursive=True)
640
+ root = os.path.join(codex_home, "sessions", "**")
641
+ found = {}
642
+ for pattern in ("rollout-*.jsonl", "rollout-*.jsonl.zst"):
643
+ for f in glob.glob(os.path.join(root, pattern), recursive=True):
644
+ key = f[:-4] if f.endswith(".zst") else f
645
+ prev = found.get(key)
646
+ if prev is None or _mtime(f) > _mtime(prev):
647
+ found[key] = f
648
+ return sorted(found.values())
649
+
650
+
651
+ def _mtime(path):
652
+ try:
653
+ return os.path.getmtime(path)
654
+ except OSError:
655
+ return 0
656
+
657
+
658
+ def _zstd_decompress(data):
659
+ """Decompress zstd bytes with whatever is available.
660
+
661
+ Python 3.14 ships `compression.zstd`; otherwise try the `zstandard`
662
+ package, then the `zstd` command-line tool.
663
+ """
664
+ try:
665
+ from compression import zstd
666
+ return zstd.decompress(data)
667
+ except ImportError:
668
+ pass
669
+ try:
670
+ import zstandard
671
+ return zstandard.ZstdDecompressor().decompressobj().decompress(data)
672
+ except ImportError:
673
+ pass
674
+ import subprocess
675
+ try:
676
+ return subprocess.run(["zstd", "-dc"], input=data, stdout=subprocess.PIPE,
677
+ stderr=subprocess.DEVNULL, check=True).stdout
678
+ except (OSError, subprocess.CalledProcessError) as e:
679
+ raise OSError("cannot decompress zstd file (needs Python 3.14+, "
680
+ "the zstandard package, or the zstd tool)") from e
681
+
682
+
683
+ _zstd_warned = False
684
+
685
+
686
+ def _open_log(path):
687
+ """Open a JSONL log for text reading, decompressing `.zst` files."""
688
+ global _zstd_warned
689
+ if not path.endswith(".zst"):
690
+ return open(path, encoding="utf-8")
691
+ import io
692
+ with open(path, "rb") as fh:
693
+ raw = fh.read()
694
+ try:
695
+ data = _zstd_decompress(raw)
696
+ except OSError as e:
697
+ if not _zstd_warned:
698
+ _zstd_warned = True
699
+ print("clockwork: skipping .zst Codex logs: %s" % e, file=sys.stderr)
700
+ raise
701
+ return io.StringIO(data.decode("utf-8", errors="replace"))
491
702
 
492
703
 
493
704
  _CODEX_TOKEN_KEYS = ("input_tokens", "cached_input_tokens",
@@ -531,25 +742,41 @@ def _codex_token_event(record, payload, running, model):
531
742
  }
532
743
 
533
744
 
745
+ # Records that carry a tool's result back to the model. Counted as activity.
746
+ _CODEX_TOOL_OUTPUTS = ("function_call_output", "custom_tool_call_output")
747
+
748
+
534
749
  def _codex_scan_file(path):
535
- """Return (cwd, [timestamps], [token events]) for one rollout file.
750
+ """Return (cwd, [activity], [token events], [prompts]) for one rollout.
536
751
 
537
- Uses the canonical `event_msg -> user_message` prompt records; only falls
538
- back to `response_item` user-role messages for files that contain no
539
- canonical prompt events, to avoid double counting the same input.
752
+ Activity is the prompts plus every tool result (`function_call_output`,
753
+ `custom_tool_call_output`), the same rule the Claude reader uses: a long
754
+ tool run with no human input is still work, not idle time. Prompts stay a
755
+ separate list, so tool results never count as something a person typed.
756
+
757
+ Prompts come from the first of these sources that the file contains, so
758
+ the same input is never counted twice:
759
+
760
+ 1. `event_msg -> user_message`, the canonical record in older rollouts
761
+ 2. `event_msg -> item_completed` with a `UserMessage` item, which
762
+ replaced it in newer rollouts
763
+ 3. `response_item` user-role messages, as a last resort. These also
764
+ carry injected context (environment, AGENTS.md), so they overcount.
540
765
 
541
766
  The model is not in `session_meta` (which only names the provider) — it
542
767
  rides on `turn_context`, so each turn is attributed to the most recent one.
543
768
  """
544
769
  cwd = None
545
770
  canonical = []
771
+ items = []
546
772
  fallback = []
773
+ tool_outputs = []
547
774
  events = []
548
775
  model = None
549
776
  first_model = None
550
777
  running = {k: 0 for k in _CODEX_TOKEN_KEYS}
551
778
  try:
552
- with open(path, encoding="utf-8") as fh:
779
+ with _open_log(path) as fh:
553
780
  for line in fh:
554
781
  line = line.strip()
555
782
  if not line:
@@ -570,6 +797,12 @@ def _codex_scan_file(path):
570
797
  dt = _parse_ts(d.get("timestamp") or payload.get("timestamp"))
571
798
  if dt:
572
799
  canonical.append(dt)
800
+ elif (t == "event_msg"
801
+ and payload.get("type") == "item_completed"
802
+ and (payload.get("item") or {}).get("type") == "UserMessage"):
803
+ dt = _parse_ts(d.get("timestamp"))
804
+ if dt:
805
+ items.append(dt)
573
806
  elif t == "event_msg" and payload.get("type") == "token_count":
574
807
  event = _codex_token_event(d, payload, running, model)
575
808
  if event:
@@ -580,21 +813,21 @@ def _codex_scan_file(path):
580
813
  dt = _parse_ts(d.get("timestamp") or payload.get("timestamp"))
581
814
  if dt:
582
815
  fallback.append(dt)
816
+ elif (t == "response_item"
817
+ and payload.get("type") in _CODEX_TOOL_OUTPUTS):
818
+ dt = _parse_ts(d.get("timestamp"))
819
+ if dt:
820
+ tool_outputs.append(dt)
583
821
  except OSError:
584
- return None, [], []
822
+ return None, [], [], []
585
823
  # A few turns are logged before the first `turn_context`; credit them to
586
824
  # the model the session went on to use rather than losing them to unknown.
587
825
  if first_model:
588
826
  for event in events:
589
827
  if event["model"] is None:
590
828
  event["model"] = first_model
591
- return cwd, sorted(canonical if canonical else fallback), events
592
-
593
-
594
- def _codex_parse_file(path):
595
- """Return (cwd, [timestamps]) for one rollout file."""
596
- cwd, timestamps, _ = _codex_scan_file(path)
597
- return cwd, timestamps
829
+ prompts = sorted(canonical or items or fallback)
830
+ return cwd, sorted(prompts + tool_outputs), events, prompts
598
831
 
599
832
 
600
833
  def codex_scan_single(project_path):
@@ -602,35 +835,40 @@ def codex_scan_single(project_path):
602
835
  matched = 0
603
836
  timestamps = []
604
837
  events = []
838
+ human = []
605
839
  for f in _codex_files():
606
- cwd, file_ts, file_events = _codex_scan_file(f)
840
+ cwd, file_ts, file_events, file_human = _codex_scan_file(f)
607
841
  if cwd == abs_path:
608
842
  matched += 1
609
843
  timestamps.extend(file_ts)
610
844
  events.extend(file_events)
845
+ human.extend(file_human)
611
846
  if not matched:
612
- return None, 0, [], []
613
- return abs_path, matched, sorted(timestamps), events
847
+ return None, 0, [], [], []
848
+ return abs_path, matched, sorted(timestamps), events, sorted(human)
614
849
 
615
850
 
616
851
  def codex_single(project_path):
617
- label, count, ts, _ = codex_scan_single(project_path)
618
- return label, count, ts
852
+ label, count, ts, _, human = codex_scan_single(project_path)
853
+ return label, count, ts, human
619
854
 
620
855
 
621
856
  def codex_scan():
622
857
  ts_groups = defaultdict(list)
623
858
  event_groups = defaultdict(list)
859
+ human_groups = defaultdict(list)
624
860
  for f in _codex_files():
625
- cwd, file_ts, file_events = _codex_scan_file(f)
861
+ cwd, file_ts, file_events, file_human = _codex_scan_file(f)
626
862
  if cwd and file_ts:
627
863
  ts_groups[cwd].extend(file_ts)
628
864
  event_groups[cwd].extend(file_events)
629
- return [(cwd, sorted(ts), event_groups[cwd]) for cwd, ts in ts_groups.items()]
865
+ human_groups[cwd].extend(file_human)
866
+ return [(cwd, sorted(ts), event_groups[cwd], sorted(human_groups[cwd]))
867
+ for cwd, ts in ts_groups.items()]
630
868
 
631
869
 
632
870
  def codex_all():
633
- return [(label, ts) for label, ts, _ in codex_scan()]
871
+ return [(label, ts, human) for label, ts, _, human in codex_scan()]
634
872
 
635
873
 
636
874
  def _codex_cwd_only(path):
@@ -640,7 +878,7 @@ def _codex_cwd_only(path):
640
878
  the `session_meta` record carrying `cwd` is at the top of the rollout.
641
879
  """
642
880
  try:
643
- with open(path, encoding="utf-8") as fh:
881
+ with _open_log(path) as fh:
644
882
  for line in fh:
645
883
  line = line.strip()
646
884
  if not line:
@@ -670,38 +908,45 @@ def codex_list():
670
908
  # --------------------------------------------------------------------------- #
671
909
 
672
910
  def _merge_projects(*project_lists):
673
- """Merge [(label, timestamps)] lists, combining same-label projects."""
674
- groups = defaultdict(list)
911
+ """Merge [(label, timestamps, human)] lists, combining same-label projects."""
912
+ ts_groups = defaultdict(list)
913
+ human_groups = defaultdict(list)
675
914
  for projects in project_lists:
676
- for label, ts in projects:
677
- groups[label].extend(ts)
678
- return [(label, sorted(ts)) for label, ts in groups.items()]
915
+ for label, ts, human in projects:
916
+ ts_groups[label].extend(ts)
917
+ human_groups[label].extend(human)
918
+ return [(label, sorted(ts), sorted(human_groups[label]))
919
+ for label, ts in ts_groups.items()]
679
920
 
680
921
 
681
922
  def _merge_scans(*scans):
682
- """Merge [(label, timestamps, events)] lists, combining same-label projects."""
923
+ """Merge [(label, timestamps, events, human)] lists, combining same-label
924
+ projects."""
683
925
  ts_groups = defaultdict(list)
684
926
  event_groups = defaultdict(list)
927
+ human_groups = defaultdict(list)
685
928
  for scan in scans:
686
- for label, ts, events in scan:
929
+ for label, ts, events, human in scan:
687
930
  ts_groups[label].extend(ts)
688
931
  event_groups[label].extend(events)
689
- return [(label, sorted(ts), event_groups[label])
932
+ human_groups[label].extend(human)
933
+ return [(label, sorted(ts), event_groups[label], sorted(human_groups[label]))
690
934
  for label, ts in ts_groups.items()]
691
935
 
692
936
 
693
937
  def both_scan_single(project_path):
694
- _, c_count, c_ts, c_events = claude_scan_single(project_path)
695
- _, x_count, x_ts, x_events = codex_scan_single(project_path)
938
+ _, c_count, c_ts, c_events, c_human = claude_scan_single(project_path)
939
+ _, x_count, x_ts, x_events, x_human = codex_scan_single(project_path)
696
940
  count = c_count + x_count
697
941
  if count == 0:
698
- return None, 0, [], []
699
- return project_path, count, sorted(c_ts + x_ts), c_events + x_events
942
+ return None, 0, [], [], []
943
+ return (project_path, count, sorted(c_ts + x_ts), c_events + x_events,
944
+ sorted(c_human + x_human))
700
945
 
701
946
 
702
947
  def both_single(project_path):
703
- label, count, ts, _ = both_scan_single(project_path)
704
- return label, count, ts
948
+ label, count, ts, _, human = both_scan_single(project_path)
949
+ return label, count, ts, human
705
950
 
706
951
 
707
952
  def both_scan():
@@ -713,7 +958,10 @@ def both_all():
713
958
 
714
959
 
715
960
  def both_list():
716
- labels = {_claude_folder_to_pretty(f) for f in _claude_list_folders()}
961
+ labels = {
962
+ _claude_folder_cwd(f, glob.glob(os.path.join(CLAUDE_DIR, f, "*.jsonl")))
963
+ for f in _claude_list_folders()
964
+ }
717
965
  labels.update(codex_list())
718
966
  return sorted(labels)
719
967
 
@@ -722,6 +970,15 @@ def both_list():
722
970
  # Provider dispatch
723
971
  # --------------------------------------------------------------------------- #
724
972
 
973
+ # Every backend returns two timestamp lists per project: activity (every
974
+ # user-role record, which drives sessions and active time) and human (the
975
+ # messages a person sent, which is what the `human_prompts` count reports).
976
+ #
977
+ # single(path) → (label, files, activity, human)
978
+ # scan_single(path) → (label, files, activity, events, human)
979
+ # all() → [(label, activity, human)]
980
+ # scan() → [(label, activity, events, human)]
981
+ #
725
982
  # `scan`/`scan_single` are the token-aware backends: same work as `all`/`single`
726
983
  # plus the usage records picked up in the same pass. `all`/`single` remain the
727
984
  # timing-only views, and are what the plain (no --tokens) commands read.
@@ -784,11 +1041,48 @@ def _day_keys(daily, token_days):
784
1041
  return sorted(set(daily) | set(token_days))
785
1042
 
786
1043
 
787
- def _day_entry(day, daily, prompts_per_day, token_days, show_tokens):
788
- """One JSON day bucket, with tokens attached when they were collected."""
1044
+ def _load_projects(provider, show_tokens):
1045
+ """[(label, activity, events, human)] for every project of a provider.
1046
+
1047
+ Reads the token-aware backend only when tokens were asked for; the plain
1048
+ backend is the same scan without usage, so `events` is empty.
1049
+ """
1050
+ if show_tokens:
1051
+ return PROVIDERS[provider]["scan"]()
1052
+ return [(label, ts, [], human)
1053
+ for label, ts, human in PROVIDERS[provider]["all"]()]
1054
+
1055
+
1056
+ def _per_day(timestamps):
1057
+ """Count timestamps per calendar day."""
1058
+ counts = defaultdict(int)
1059
+ for ts in timestamps:
1060
+ counts[ts.date()] += 1
1061
+ return counts
1062
+
1063
+
1064
+ def _human_per_session(sessions, human):
1065
+ """Human prompts inside each (start, end, count) session, in order.
1066
+
1067
+ Every human prompt is also an activity timestamp, so each one falls inside
1068
+ exactly one session's [start, end].
1069
+ """
1070
+ return [bisect.bisect_right(human, end) - bisect.bisect_left(human, start)
1071
+ for start, end, _ in sessions]
1072
+
1073
+
1074
+ def _day_entry(day, daily, prompts_per_day, human_per_day, token_days,
1075
+ show_tokens):
1076
+ """One JSON day bucket, with tokens attached when they were collected.
1077
+
1078
+ `prompts` keeps its original meaning (every user-role record, tool results
1079
+ included) so existing consumers are unaffected; `human_prompts` is the
1080
+ count of messages a person sent.
1081
+ """
789
1082
  entry = {"date": str(day),
790
1083
  "minutes": round(daily[day], 2),
791
- "prompts": prompts_per_day[day]}
1084
+ "prompts": prompts_per_day[day],
1085
+ "human_prompts": human_per_day[day]}
792
1086
  if show_tokens:
793
1087
  entry["tokens"] = token_days.get(day) or _sealed(_new_token_rec())
794
1088
  return entry
@@ -832,18 +1126,21 @@ def _print_model_table(summary):
832
1126
  def analyze_single(provider, project_path, idle_threshold, since, until, as_json,
833
1127
  show_tokens=False):
834
1128
  if show_tokens:
835
- label, count, timestamps, events = PROVIDERS[provider]["scan_single"](project_path)
1129
+ label, count, timestamps, events, human = \
1130
+ PROVIDERS[provider]["scan_single"](project_path)
836
1131
  events = _filter_events(events, since, until)
837
1132
  else:
838
- label, count, timestamps = PROVIDERS[provider]["single"](project_path)
1133
+ label, count, timestamps, human = PROVIDERS[provider]["single"](project_path)
839
1134
  events = []
840
1135
  timestamps = _filter_timestamps(timestamps, since, until)
1136
+ human = _filter_timestamps(human, since, until)
841
1137
 
842
1138
  if count == 0:
843
1139
  if as_json:
844
1140
  _print_json({
845
1141
  "provider": provider, "project": project_path,
846
- "error": "no sessions found", "prompts": 0, "days": [],
1142
+ "error": "no sessions found", "prompts": 0,
1143
+ "human_prompts": 0, "days": [],
847
1144
  })
848
1145
  sys.exit(1)
849
1146
  print(f"❌ No {provider} sessions found for: {project_path}")
@@ -859,7 +1156,7 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
859
1156
  _print_json({
860
1157
  "provider": provider, "project": project_path, "label": label,
861
1158
  "session_files": count, "since": _iso(since), "until": _iso(until),
862
- "prompts": 0, "days": [],
1159
+ "prompts": 0, "human_prompts": 0, "days": [],
863
1160
  })
864
1161
  sys.exit(0)
865
1162
  print("No user prompts found in the selected range.")
@@ -872,9 +1169,8 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
872
1169
  last_ts = timestamps[-1]
873
1170
  span_days = (last_ts.date() - first_ts.date()).days + 1
874
1171
 
875
- prompts_per_day = defaultdict(int)
876
- for ts in timestamps:
877
- prompts_per_day[ts.date()] += 1
1172
+ prompts_per_day = _per_day(timestamps)
1173
+ human_per_day = _per_day(human)
878
1174
 
879
1175
  token_summary = summarize_tokens(events) if show_tokens else None
880
1176
  token_days = tokens_by_day(events) if show_tokens else {}
@@ -892,11 +1188,13 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
892
1188
  "last": _iso(last_ts),
893
1189
  "span_days": span_days,
894
1190
  "prompts": len(timestamps),
1191
+ "human_prompts": len(human),
895
1192
  "sessions": len(sessions),
896
1193
  "active_days": len(daily),
897
1194
  "total_minutes": round(total_minutes, 2),
898
1195
  "days": [
899
- _day_entry(day, daily, prompts_per_day, token_days, show_tokens)
1196
+ _day_entry(day, daily, prompts_per_day, human_per_day,
1197
+ token_days, show_tokens)
900
1198
  for day in _day_keys(daily, token_days)
901
1199
  ],
902
1200
  }
@@ -914,7 +1212,7 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
914
1212
  print(f" First : {first_ts.strftime('%Y-%m-%d %H:%M')}")
915
1213
  print(f" Last : {last_ts.strftime('%Y-%m-%d %H:%M')}")
916
1214
  print(f" Span : {span_days} calendar days")
917
- print(f" Prompts : {len(timestamps)} total")
1215
+ print(f" Prompts : {len(human)} total")
918
1216
  print(f" Sessions: {len(sessions)} (idle threshold: {idle_threshold} min)")
919
1217
  print(f" Active : {len(daily)} days")
920
1218
  print(f" Total : {fmt_duration(total_minutes)}")
@@ -934,13 +1232,13 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
934
1232
  cell = (f" {fmt_tokens(token_days.get(day, {}).get('total', 0)):>9}"
935
1233
  if show_tokens else "")
936
1234
  print(f" {str(day):<12} {fmt_duration(mins):<14} "
937
- f"{prompts_per_day[day]:<10}{cell} {bar}")
1235
+ f"{human_per_day[day]:<10}{cell} {bar}")
938
1236
 
939
1237
  print("-" * (52 + len(token_col)))
940
1238
  total_cell = f" {fmt_tokens(token_summary['total']):>9}" if show_tokens else ""
941
1239
  # rstrip so the plain (no --tokens) row keeps its original width.
942
1240
  print(f" {'TOTAL':<12} {fmt_duration(total_minutes):<14} "
943
- f"{len(timestamps):<10}{total_cell}".rstrip())
1241
+ f"{len(human):<10}{total_cell}".rstrip())
944
1242
  if show_tokens:
945
1243
  _print_model_table(token_summary)
946
1244
  print()
@@ -948,21 +1246,20 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
948
1246
 
949
1247
  def analyze_all(provider, idle_threshold, since, until, as_json,
950
1248
  show_tokens=False):
951
- if show_tokens:
952
- projects = PROVIDERS[provider]["scan"]()
953
- else:
954
- projects = [(label, ts, []) for label, ts in PROVIDERS[provider]["all"]()]
1249
+ projects = _load_projects(provider, show_tokens)
955
1250
 
956
1251
  rows = []
957
1252
  all_events = []
958
1253
  grand_minutes = 0.0
959
1254
  grand_prompts = 0
1255
+ grand_human = 0
960
1256
  grand_sessions = 0
961
1257
 
962
- for label, timestamps, events in projects:
1258
+ for label, timestamps, events, human in projects:
963
1259
  timestamps = _filter_timestamps(timestamps, since, until)
964
1260
  if not timestamps:
965
1261
  continue
1262
+ human = _filter_timestamps(human, since, until)
966
1263
  events = _filter_events(events, since, until)
967
1264
  daily, sessions = compute_active_hours(timestamps, idle_threshold)
968
1265
  total_minutes = sum(daily.values())
@@ -970,12 +1267,14 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
970
1267
  "label": label,
971
1268
  "minutes": total_minutes,
972
1269
  "prompts": len(timestamps),
1270
+ "human_prompts": len(human),
973
1271
  "sessions": len(sessions),
974
1272
  "tokens": summarize_tokens(events) if show_tokens else None,
975
1273
  })
976
1274
  all_events.extend(events)
977
1275
  grand_minutes += total_minutes
978
1276
  grand_prompts += len(timestamps)
1277
+ grand_human += len(human)
979
1278
  grand_sessions += len(sessions)
980
1279
 
981
1280
  if not rows:
@@ -983,7 +1282,8 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
983
1282
  _print_json({
984
1283
  "provider": provider, "since": _iso(since), "until": _iso(until),
985
1284
  "projects": [],
986
- "totals": {"projects": 0, "minutes": 0, "prompts": 0, "sessions": 0},
1285
+ "totals": {"projects": 0, "minutes": 0, "prompts": 0,
1286
+ "human_prompts": 0, "sessions": 0},
987
1287
  })
988
1288
  sys.exit(1)
989
1289
  print(f"❌ No {provider} projects with activity found ({PROVIDERS[provider]['location']})")
@@ -998,6 +1298,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
998
1298
  entry = {"project": r["label"],
999
1299
  "minutes": round(r["minutes"], 2),
1000
1300
  "prompts": r["prompts"],
1301
+ "human_prompts": r["human_prompts"],
1001
1302
  "sessions": r["sessions"]}
1002
1303
  if show_tokens:
1003
1304
  entry["tokens"] = r["tokens"]
@@ -1006,6 +1307,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1006
1307
  "projects": len(rows),
1007
1308
  "minutes": round(grand_minutes, 2),
1008
1309
  "prompts": grand_prompts,
1310
+ "human_prompts": grand_human,
1009
1311
  "sessions": grand_sessions,
1010
1312
  }
1011
1313
  if show_tokens:
@@ -1027,7 +1329,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1027
1329
  print(f" CLOCKWORK — ALL {_provider_label(provider)} PROJECTS (idle threshold: {idle_threshold} min)")
1028
1330
  print("=" * width)
1029
1331
  print(f" Projects: {len(rows)} with activity")
1030
- print(f" Prompts : {grand_prompts} total")
1332
+ print(f" Prompts : {grand_human} total")
1031
1333
  print(f" Sessions: {grand_sessions} total")
1032
1334
  print(f" Total : {fmt_duration(grand_minutes)}")
1033
1335
  if show_tokens:
@@ -1049,7 +1351,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1049
1351
  if len(name) > 29:
1050
1352
  name = "…" + name[-28:]
1051
1353
  t = r["tokens"]
1052
- print(f" {name:<30} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} "
1354
+ print(f" {name:<30} {fmt_duration(r['minutes']):>9} {r['human_prompts']:>8} "
1053
1355
  f"{fmt_tokens(t['input']):>8} {fmt_tokens(t['output']):>8} "
1054
1356
  f"{fmt_tokens(t['cache_read'] + t['cache_write']):>9} "
1055
1357
  f"{fmt_tokens(t['total']):>9}")
@@ -1058,18 +1360,18 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1058
1360
  name = "…" + name[-38:]
1059
1361
  bar_len = int((r["minutes"] / max_mins) * 12) if max_mins else 0
1060
1362
  bar = "█" * bar_len
1061
- print(f" {name:<40} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} {r['sessions']:>5} {bar}")
1363
+ print(f" {name:<40} {fmt_duration(r['minutes']):>9} {r['human_prompts']:>8} {r['sessions']:>5} {bar}")
1062
1364
 
1063
1365
  print("-" * width)
1064
1366
  if show_tokens:
1065
- print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} "
1367
+ print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} {grand_human:>8} "
1066
1368
  f"{fmt_tokens(grand_tokens['input']):>8} "
1067
1369
  f"{fmt_tokens(grand_tokens['output']):>8} "
1068
1370
  f"{fmt_tokens(grand_tokens['cache_read'] + grand_tokens['cache_write']):>9} "
1069
1371
  f"{fmt_tokens(grand_tokens['total']):>9}")
1070
1372
  _print_model_table(grand_tokens)
1071
1373
  else:
1072
- print(f" {'TOTAL':<40} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} {grand_sessions:>5}")
1374
+ print(f" {'TOTAL':<40} {fmt_duration(grand_minutes):>9} {grand_human:>8} {grand_sessions:>5}")
1073
1375
  print()
1074
1376
 
1075
1377
 
@@ -1089,29 +1391,30 @@ def _period_window(period):
1089
1391
 
1090
1392
  def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False):
1091
1393
  since, until, title = _period_window(period)
1092
- if show_tokens:
1093
- projects = PROVIDERS[provider]["scan"]()
1094
- else:
1095
- projects = [(label, ts, []) for label, ts in PROVIDERS[provider]["all"]()]
1394
+ projects = _load_projects(provider, show_tokens)
1096
1395
 
1097
1396
  rows = []
1098
1397
  all_events = []
1099
1398
  combined_daily = defaultdict(float)
1100
1399
  prompts_per_day = defaultdict(int)
1400
+ human_per_day = defaultdict(int)
1101
1401
  grand_minutes = 0.0
1102
1402
  grand_prompts = 0
1403
+ grand_human = 0
1103
1404
  grand_sessions = 0
1104
1405
 
1105
- for label, timestamps, events in projects:
1406
+ for label, timestamps, events, human in projects:
1106
1407
  timestamps = _filter_timestamps(timestamps, since, until)
1107
1408
  if not timestamps:
1108
1409
  continue
1410
+ human = _filter_timestamps(human, since, until)
1109
1411
  events = _filter_events(events, since, until)
1110
1412
  daily, sessions = compute_active_hours(timestamps, idle_threshold)
1111
1413
  rows.append({
1112
1414
  "label": label,
1113
1415
  "minutes": sum(daily.values()),
1114
1416
  "prompts": len(timestamps),
1417
+ "human_prompts": len(human),
1115
1418
  "sessions": len(sessions),
1116
1419
  "tokens": summarize_tokens(events) if show_tokens else None,
1117
1420
  })
@@ -1120,8 +1423,11 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1120
1423
  combined_daily[day] += mins
1121
1424
  for ts in timestamps:
1122
1425
  prompts_per_day[ts.date()] += 1
1426
+ for ts in human:
1427
+ human_per_day[ts.date()] += 1
1123
1428
  grand_minutes += sum(daily.values())
1124
1429
  grand_prompts += len(timestamps)
1430
+ grand_human += len(human)
1125
1431
  grand_sessions += len(sessions)
1126
1432
 
1127
1433
  rows.sort(key=lambda r: r["minutes"], reverse=True)
@@ -1134,6 +1440,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1134
1440
  entry = {"project": r["label"],
1135
1441
  "minutes": round(r["minutes"], 2),
1136
1442
  "prompts": r["prompts"],
1443
+ "human_prompts": r["human_prompts"],
1137
1444
  "sessions": r["sessions"]}
1138
1445
  if show_tokens:
1139
1446
  entry["tokens"] = r["tokens"]
@@ -1142,6 +1449,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1142
1449
  "projects": len(rows),
1143
1450
  "minutes": round(grand_minutes, 2),
1144
1451
  "prompts": grand_prompts,
1452
+ "human_prompts": grand_human,
1145
1453
  "sessions": grand_sessions,
1146
1454
  }
1147
1455
  if show_tokens:
@@ -1154,7 +1462,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1154
1462
  "until": _iso(until),
1155
1463
  "projects": projects_json,
1156
1464
  "days": [
1157
- _day_entry(day, combined_daily, prompts_per_day,
1465
+ _day_entry(day, combined_daily, prompts_per_day, human_per_day,
1158
1466
  token_days, show_tokens)
1159
1467
  for day in _day_keys(combined_daily, token_days)
1160
1468
  ],
@@ -1172,7 +1480,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1172
1480
  print()
1173
1481
  return
1174
1482
  print(f" Active : {fmt_duration(grand_minutes)} across {len(rows)} project(s)")
1175
- print(f" Prompts : {grand_prompts} Sessions: {grand_sessions}")
1483
+ print(f" Prompts : {grand_human} Sessions: {grand_sessions}")
1176
1484
  if show_tokens:
1177
1485
  print(f" Tokens : {fmt_tokens(grand_tokens['total'])} across "
1178
1486
  f"{grand_tokens['responses']:,} responses")
@@ -1194,18 +1502,18 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1194
1502
  if len(name) > 29:
1195
1503
  name = "…" + name[-28:]
1196
1504
  print(f" {name:<30} {fmt_duration(r['minutes']):>9} "
1197
- f"{r['prompts']:>7} {fmt_tokens(r['tokens']['total']):>9}")
1505
+ f"{r['human_prompts']:>7} {fmt_tokens(r['tokens']['total']):>9}")
1198
1506
  else:
1199
1507
  if len(name) > 33:
1200
1508
  name = "…" + name[-32:]
1201
1509
  bar = "█" * (int((r["minutes"] / max_mins) * 10) if max_mins else 0)
1202
- print(f" {name:<34} {fmt_duration(r['minutes']):>9} {r['prompts']:>7} {bar}")
1510
+ print(f" {name:<34} {fmt_duration(r['minutes']):>9} {r['human_prompts']:>7} {bar}")
1203
1511
  print("-" * width)
1204
1512
  if show_tokens:
1205
1513
  print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} "
1206
- f"{grand_prompts:>7} {fmt_tokens(grand_tokens['total']):>9}")
1514
+ f"{grand_human:>7} {fmt_tokens(grand_tokens['total']):>9}")
1207
1515
  else:
1208
- print(f" {'TOTAL':<34} {fmt_duration(grand_minutes):>9} {grand_prompts:>7}")
1516
+ print(f" {'TOTAL':<34} {fmt_duration(grand_minutes):>9} {grand_human:>7}")
1209
1517
 
1210
1518
  if period == "week":
1211
1519
  print()
@@ -1219,7 +1527,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1219
1527
  cell = (f" {fmt_tokens(token_days.get(day, {}).get('total', 0)):>9}"
1220
1528
  if show_tokens else "")
1221
1529
  print(f" {str(day):<12} {fmt_duration(mins):>9} "
1222
- f"{prompts_per_day[day]:>7}{cell} {bar}")
1530
+ f"{human_per_day[day]:>7}{cell} {bar}")
1223
1531
  if show_tokens:
1224
1532
  _print_model_table(grand_tokens)
1225
1533
  print()
@@ -1248,38 +1556,42 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1248
1556
  With `show_tokens`, every project, day, provider and the grand totals also
1249
1557
  carry a normalized `tokens` record with a per-model breakdown. The token
1250
1558
  fields are purely additive — a v2 consumer reads a v3 bundle unchanged.
1559
+
1560
+ `prompts` counts every user-role record, tool results included, and keeps
1561
+ that meaning for existing consumers. Wherever it appears (totals, daily,
1562
+ sessions, by_provider, and the raw timestamp list) a `human_prompts`
1563
+ sibling carries the messages a person actually sent. Also additive.
1251
1564
  """
1252
1565
  out_projects = []
1253
1566
  by_provider = {}
1254
1567
  grand_minutes = 0.0
1255
1568
  grand_prompts = 0
1569
+ grand_human = 0
1256
1570
  grand_sessions = 0
1257
1571
  grand_events = []
1258
1572
  name_counter = 0
1259
1573
 
1260
1574
  for prov in _export_providers(provider):
1261
- if show_tokens:
1262
- projects = PROVIDERS[prov]["scan"]()
1263
- else:
1264
- projects = [(label, ts, []) for label, ts in PROVIDERS[prov]["all"]()]
1575
+ projects = _load_projects(prov, show_tokens)
1265
1576
  p_minutes = 0.0
1266
1577
  p_prompts = 0
1578
+ p_human = 0
1267
1579
  p_sessions = 0
1268
1580
  p_projects = 0
1269
1581
  p_events = []
1270
1582
 
1271
- for label, timestamps, events in sorted(projects, key=lambda p: p[0]):
1583
+ for label, timestamps, events, human in sorted(projects, key=lambda p: p[0]):
1272
1584
  timestamps = _filter_timestamps(timestamps, since, until)
1273
1585
  if not timestamps:
1274
1586
  continue
1587
+ human = _filter_timestamps(human, since, until)
1275
1588
  events = _filter_events(events, since, until)
1276
1589
  daily, _ = compute_active_hours(timestamps, idle_threshold)
1277
1590
  sessions = group_sessions(timestamps, idle_threshold)
1278
1591
  total_minutes = sum(daily.values())
1279
1592
 
1280
- prompts_per_day = defaultdict(int)
1281
- for ts in timestamps:
1282
- prompts_per_day[ts.date()] += 1
1593
+ prompts_per_day = _per_day(timestamps)
1594
+ human_per_day = _per_day(human)
1283
1595
 
1284
1596
  token_days = tokens_by_day(events) if show_tokens else {}
1285
1597
 
@@ -1291,13 +1603,15 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1291
1603
  "totals": {
1292
1604
  "minutes": round(total_minutes, 2),
1293
1605
  "prompts": len(timestamps),
1606
+ "human_prompts": len(human),
1294
1607
  "sessions": len(sessions),
1295
1608
  "active_days": len(daily),
1296
1609
  "first": int(timestamps[0].timestamp()),
1297
1610
  "last": int(timestamps[-1].timestamp()),
1298
1611
  },
1299
1612
  "daily": [
1300
- _day_entry(day, daily, prompts_per_day, token_days, show_tokens)
1613
+ _day_entry(day, daily, prompts_per_day, human_per_day,
1614
+ token_days, show_tokens)
1301
1615
  for day in _day_keys(daily, token_days)
1302
1616
  ],
1303
1617
  }
@@ -1310,16 +1624,20 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1310
1624
  {"start": int(s.timestamp()),
1311
1625
  "end": int(e.timestamp()),
1312
1626
  "minutes": round((e - s).total_seconds() / 60, 2),
1313
- "prompts": c}
1314
- for s, e, c in sessions
1627
+ "prompts": c,
1628
+ "human_prompts": h}
1629
+ for (s, e, c), h in zip(sessions,
1630
+ _human_per_session(sessions, human))
1315
1631
  ]
1316
1632
  if detail == "raw":
1317
1633
  proj["prompts"] = [int(ts.timestamp()) for ts in timestamps]
1634
+ proj["human_prompts"] = [int(ts.timestamp()) for ts in human]
1318
1635
 
1319
1636
  out_projects.append(proj)
1320
1637
  p_projects += 1
1321
1638
  p_minutes += total_minutes
1322
1639
  p_prompts += len(timestamps)
1640
+ p_human += len(human)
1323
1641
  p_sessions += len(sessions)
1324
1642
  p_events.extend(events)
1325
1643
 
@@ -1328,12 +1646,14 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1328
1646
  "projects": p_projects,
1329
1647
  "minutes": round(p_minutes, 2),
1330
1648
  "prompts": p_prompts,
1649
+ "human_prompts": p_human,
1331
1650
  "sessions": p_sessions,
1332
1651
  }
1333
1652
  if show_tokens:
1334
1653
  by_provider[prov]["tokens"] = summarize_tokens(p_events)
1335
1654
  grand_minutes += p_minutes
1336
1655
  grand_prompts += p_prompts
1656
+ grand_human += p_human
1337
1657
  grand_sessions += p_sessions
1338
1658
  grand_events.extend(p_events)
1339
1659
 
@@ -1349,6 +1669,7 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1349
1669
  "projects": len(out_projects),
1350
1670
  "minutes": round(grand_minutes, 2),
1351
1671
  "prompts": grand_prompts,
1672
+ "human_prompts": grand_human,
1352
1673
  "sessions": grand_sessions,
1353
1674
  "by_provider": by_provider,
1354
1675
  }
@@ -1381,7 +1702,7 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1381
1702
  tags.append("tokens")
1382
1703
  print(f"\n ✓ export complete → {where}", file=sys.stderr)
1383
1704
  print(f" {' · '.join(tags)}", file=sys.stderr)
1384
- print(f" {len(out_projects)} projects · {grand_prompts:,} prompts "
1705
+ print(f" {len(out_projects)} projects · {grand_human:,} prompts "
1385
1706
  f"· {grand_sessions:,} sessions · {grand_minutes / 60:.1f}h active",
1386
1707
  file=sys.stderr)
1387
1708
  if show_tokens:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clockwork-cli
3
- Version: 0.3.0
3
+ Version: 0.4.1
4
4
  Summary: Mine your Claude Code and Codex session logs to estimate active time
5
5
  License-Expression: MIT
6
6
  Project-URL: Homepage, https://github.com/danielsich/clockwork
@@ -54,12 +54,32 @@ DATE ACTIVE TIME PROMPTS BAR
54
54
  ## How it works
55
55
 
56
56
  `clockwork` reads the JSONL transcripts each tool writes, extracts the
57
- timestamps of your **prompts** (not the assistant's replies), and groups them
57
+ timestamps of user-side activity (not the assistant's replies), and groups them
58
58
  into sessions. Any gap longer than the *idle threshold* (default 30 minutes)
59
59
  starts a new session. A session's duration is the time from its first to its
60
- last prompt, split across calendar-day boundaries so a session that crosses
60
+ last record, split across calendar-day boundaries so a session that crosses
61
61
  midnight is credited to each day it spans.
62
62
 
63
+ **Prompts vs. activity.** On Claude, most user-side records aren't things you
64
+ typed: the API sends every tool result back to the model as a user message.
65
+ Those records still count as *activity*, because they show Claude working
66
+ through a long tool run, so sessions and active time are built on all of them.
67
+ The **Prompts** column counts only messages a person sent. Claude Code tags
68
+ these with `origin.kind: "human"` in newer logs; older records are classified by
69
+ shape, so tool results, slash-command output, `!` shell output, meta records,
70
+ task notifications, and interrupt markers are left out. Text typed while a tool
71
+ was running is counted. Codex follows the same rule: its activity is your
72
+ prompts plus every tool result (`function_call_output`,
73
+ `custom_tool_call_output`), and its Prompts column is your prompts only.
74
+
75
+ In JSON output, `prompts` is the activity count (every user-side record, tool
76
+ results included) on both providers, so Claude consumers see the meaning they
77
+ always had, and `human_prompts` carries the corrected count. On Codex,
78
+ `prompts` used to count prompts only and now includes tool results too; read
79
+ `human_prompts` for the number of messages you sent. Claude Code's Insights report counts more broadly than `human_prompts`
80
+ does (it includes slash commands, shell output, and interrupts), so expect
81
+ Insights' "messages" to run higher.
82
+
63
83
  **Data sources**
64
84
 
65
85
  | Provider | Location |
@@ -74,11 +94,11 @@ midnight is credited to each day it spans.
74
94
  > reasonable estimate, not a stopwatch.
75
95
 
76
96
  > **`both` and path matching:** `both` combines Claude and Codex prompts by
77
- > project path. Single-project mode (`clockwork both ~/dev/x`) is exact,
78
- > because it encodes the path you pass. In `all` / `export` / `list`, projects
79
- > are matched by their displayed path — and Claude stores paths dash-encoded,
80
- > so one containing spaces or dashes can't always be reversed to match Codex's
81
- > real path. Such a project may appear as two rows rather than merging.
97
+ > project path. Claude's folder names are lossy (every character that isn't a
98
+ > letter or digit becomes `-`), so clockwork labels each Claude project with
99
+ > the real `cwd` recorded in its logs, which then lines up with Codex's path.
100
+ > Only a folder whose logs carry no matching `cwd` falls back to a decoded
101
+ > guess, and that guess may appear as a separate row rather than merging.
82
102
 
83
103
  ## Requirements
84
104
 
@@ -252,9 +272,11 @@ Two counting traps are handled for you, both of which inflate the numbers if
252
272
  you read the logs naively:
253
273
 
254
274
  - **Claude** writes one line per content block — thinking, text, and each tool
255
- call — and every line of a single API response repeats the *identical* usage
256
- block. Counting per line overstates usage roughly 2.6x, so responses are
257
- deduplicated on their message id.
275
+ call — and every line of a single API response repeats its usage block.
276
+ Counting per line overstates usage roughly 2.6x, so responses are
277
+ deduplicated on their message id. Subagent transcripts
278
+ (`<session>/subagents/*.jsonl`) are read too; there the first line of a
279
+ response holds a streaming partial, so the largest count per field wins.
258
280
  - **Codex** re-emits a stale `last_token_usage` on aborted and no-op turns that
259
281
  its cumulative counter never absorbs, so a turn's real cost is read as the
260
282
  rise in `total_token_usage` instead. The model name comes from the preceding
@@ -337,11 +359,15 @@ for a combined view, so nothing is lost either way.
337
359
  "name": "myproject", // basename, or "project-N" when anonymized
338
360
  "path": "/Users/you/dev/myproject", // omitted when anonymized
339
361
  "totals": {
340
- "minutes": 1234.76, "prompts": 1646, "sessions": 27,
362
+ "minutes": 1234.76,
363
+ "prompts": 1646, // every user-side record, tool results included
364
+ "human_prompts": 231, // messages a person sent
365
+ "sessions": 27,
341
366
  "active_days": 12,
342
367
  "first": 1780521570, "last": 1782130426 // epoch seconds
343
368
  },
344
- "daily": [ { "date": "2026-06-03", "minutes": 4.34, "prompts": 27 } ],
369
+ "daily": [ { "date": "2026-06-03", "minutes": 4.34, "prompts": 27,
370
+ "human_prompts": 4 } ],
345
371
  // every "tokens" block below appears only with --tokens
346
372
  "tokens": {
347
373
  "responses": 373, // API responses, deduplicated
@@ -356,23 +382,32 @@ for a combined view, so nothing is lost either way.
356
382
  ]
357
383
  },
358
384
  "sessions": [ { "start": 1780521570, "end": 1780521830,
359
- "minutes": 4.34, "prompts": 27 } ], // detail >= sessions
360
- "prompts": [ 1780521570, 1780521582 ] // detail == raw
385
+ "minutes": 4.34, "prompts": 27,
386
+ "human_prompts": 4 } ], // detail >= sessions
387
+ "prompts": [ 1780521570, 1780521582 ], // detail == raw
388
+ "human_prompts": [ 1780521570 ] // detail == raw
361
389
  }
362
390
  ],
363
391
  "totals": {
364
- "projects": 6, "minutes": 3392.97, "prompts": 4588, "sessions": 64,
392
+ "projects": 6, "minutes": 3392.97, "prompts": 4588, "human_prompts": 950,
393
+ "sessions": 64,
365
394
  "tokens": { /* same shape, summed across every project */ },
366
395
  "by_provider": {
367
- "claude": { "projects": 4, "minutes": 2500.0, "prompts": 3000, "sessions": 40,
368
- "tokens": { /* ... */ } },
369
- "codex": { "projects": 2, "minutes": 892.97, "prompts": 1588, "sessions": 24,
370
- "tokens": { /* ... */ } }
396
+ "claude": { "projects": 4, "minutes": 2500.0, "prompts": 3000,
397
+ "human_prompts": 420, "sessions": 40, "tokens": { /* ... */ } },
398
+ "codex": { "projects": 2, "minutes": 892.97, "prompts": 1588,
399
+ "human_prompts": 530, "sessions": 24, "tokens": { /* ... */ } }
371
400
  }
372
401
  }
373
402
  }
374
403
  ```
375
404
 
405
+ `human_prompts` sits beside every `prompts` field. It was added inside
406
+ `clockwork/v3` without a version bump, because nothing existing changed
407
+ meaning: a consumer that doesn't know the field reads the bundle as before. If
408
+ you display a prompt count, read `human_prompts` when it's present and fall
409
+ back to `prompts` for older bundles.
410
+
376
411
  All instants are **UTC-based epoch seconds** (`new Date(sec * 1000)` in JS), so
377
412
  the consumer picks the display timezone. The `schema` field is the version
378
413
  contract — `clockwork/v2` was a breaking bump over `v1` (provider moved to the
@@ -0,0 +1,8 @@
1
+ clockwork_cli/__init__.py,sha256=WRSKoYRZAtL1kwyJeJnzLvI0Zv-e-9SC9WfQII8mVms,69130
2
+ clockwork_cli/__main__.py,sha256=HcXz3nL5ocmXEASzCOKbjM3Sj6czPe8sqJSXglAjBw0,39
3
+ clockwork_cli-0.4.1.dist-info/licenses/LICENSE,sha256=pz4uy4Ra9e-Ks0T7UFFi8rGL86-f29m2ZOB0WgixjLY,1068
4
+ clockwork_cli-0.4.1.dist-info/METADATA,sha256=h8KkoxESMfPz3QxSBQ0hEIwXvWPc2dbma3g7KEPwfng,18699
5
+ clockwork_cli-0.4.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ clockwork_cli-0.4.1.dist-info/entry_points.txt,sha256=wmiWdgLrHpNKK9wDwCOiX4zyLFx71_G5DzydSiu8DWs,49
7
+ clockwork_cli-0.4.1.dist-info/top_level.txt,sha256=g5lh3hqDChq8bNBmiN2Kze86weZTddLJspNABd-2ckg,14
8
+ clockwork_cli-0.4.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,8 +0,0 @@
1
- clockwork_cli/__init__.py,sha256=2BOKqQApGWawT7265tK_Gz24oUkxxdjpXIC7-Xn0mYA,55700
2
- clockwork_cli/__main__.py,sha256=HcXz3nL5ocmXEASzCOKbjM3Sj6czPe8sqJSXglAjBw0,39
3
- clockwork_cli-0.3.0.dist-info/licenses/LICENSE,sha256=pz4uy4Ra9e-Ks0T7UFFi8rGL86-f29m2ZOB0WgixjLY,1068
4
- clockwork_cli-0.3.0.dist-info/METADATA,sha256=MBLUplu6eqywZQJateg9_c3GQvRWvi1f-AFTR6tSX2Y,16467
5
- clockwork_cli-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
- clockwork_cli-0.3.0.dist-info/entry_points.txt,sha256=wmiWdgLrHpNKK9wDwCOiX4zyLFx71_G5DzydSiu8DWs,49
7
- clockwork_cli-0.3.0.dist-info/top_level.txt,sha256=g5lh3hqDChq8bNBmiN2Kze86weZTddLJspNABd-2ckg,14
8
- clockwork_cli-0.3.0.dist-info/RECORD,,