clockwork-cli 0.3.0__py3-none-any.whl → 0.4.0__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
@@ -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.0"
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():
@@ -531,19 +676,35 @@ def _codex_token_event(record, payload, running, model):
531
676
  }
532
677
 
533
678
 
679
+ # Records that carry a tool's result back to the model. Counted as activity.
680
+ _CODEX_TOOL_OUTPUTS = ("function_call_output", "custom_tool_call_output")
681
+
682
+
534
683
  def _codex_scan_file(path):
535
- """Return (cwd, [timestamps], [token events]) for one rollout file.
684
+ """Return (cwd, [activity], [token events], [prompts]) for one rollout.
685
+
686
+ Activity is the prompts plus every tool result (`function_call_output`,
687
+ `custom_tool_call_output`), the same rule the Claude reader uses: a long
688
+ tool run with no human input is still work, not idle time. Prompts stay a
689
+ separate list, so tool results never count as something a person typed.
536
690
 
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.
691
+ Prompts come from the first of these sources that the file contains, so
692
+ the same input is never counted twice:
693
+
694
+ 1. `event_msg -> user_message`, the canonical record in older rollouts
695
+ 2. `event_msg -> item_completed` with a `UserMessage` item, which
696
+ replaced it in newer rollouts
697
+ 3. `response_item` user-role messages, as a last resort. These also
698
+ carry injected context (environment, AGENTS.md), so they overcount.
540
699
 
541
700
  The model is not in `session_meta` (which only names the provider) — it
542
701
  rides on `turn_context`, so each turn is attributed to the most recent one.
543
702
  """
544
703
  cwd = None
545
704
  canonical = []
705
+ items = []
546
706
  fallback = []
707
+ tool_outputs = []
547
708
  events = []
548
709
  model = None
549
710
  first_model = None
@@ -570,6 +731,12 @@ def _codex_scan_file(path):
570
731
  dt = _parse_ts(d.get("timestamp") or payload.get("timestamp"))
571
732
  if dt:
572
733
  canonical.append(dt)
734
+ elif (t == "event_msg"
735
+ and payload.get("type") == "item_completed"
736
+ and (payload.get("item") or {}).get("type") == "UserMessage"):
737
+ dt = _parse_ts(d.get("timestamp"))
738
+ if dt:
739
+ items.append(dt)
573
740
  elif t == "event_msg" and payload.get("type") == "token_count":
574
741
  event = _codex_token_event(d, payload, running, model)
575
742
  if event:
@@ -580,21 +747,21 @@ def _codex_scan_file(path):
580
747
  dt = _parse_ts(d.get("timestamp") or payload.get("timestamp"))
581
748
  if dt:
582
749
  fallback.append(dt)
750
+ elif (t == "response_item"
751
+ and payload.get("type") in _CODEX_TOOL_OUTPUTS):
752
+ dt = _parse_ts(d.get("timestamp"))
753
+ if dt:
754
+ tool_outputs.append(dt)
583
755
  except OSError:
584
- return None, [], []
756
+ return None, [], [], []
585
757
  # A few turns are logged before the first `turn_context`; credit them to
586
758
  # the model the session went on to use rather than losing them to unknown.
587
759
  if first_model:
588
760
  for event in events:
589
761
  if event["model"] is None:
590
762
  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
763
+ prompts = sorted(canonical or items or fallback)
764
+ return cwd, sorted(prompts + tool_outputs), events, prompts
598
765
 
599
766
 
600
767
  def codex_scan_single(project_path):
@@ -602,35 +769,40 @@ def codex_scan_single(project_path):
602
769
  matched = 0
603
770
  timestamps = []
604
771
  events = []
772
+ human = []
605
773
  for f in _codex_files():
606
- cwd, file_ts, file_events = _codex_scan_file(f)
774
+ cwd, file_ts, file_events, file_human = _codex_scan_file(f)
607
775
  if cwd == abs_path:
608
776
  matched += 1
609
777
  timestamps.extend(file_ts)
610
778
  events.extend(file_events)
779
+ human.extend(file_human)
611
780
  if not matched:
612
- return None, 0, [], []
613
- return abs_path, matched, sorted(timestamps), events
781
+ return None, 0, [], [], []
782
+ return abs_path, matched, sorted(timestamps), events, sorted(human)
614
783
 
615
784
 
616
785
  def codex_single(project_path):
617
- label, count, ts, _ = codex_scan_single(project_path)
618
- return label, count, ts
786
+ label, count, ts, _, human = codex_scan_single(project_path)
787
+ return label, count, ts, human
619
788
 
620
789
 
621
790
  def codex_scan():
622
791
  ts_groups = defaultdict(list)
623
792
  event_groups = defaultdict(list)
793
+ human_groups = defaultdict(list)
624
794
  for f in _codex_files():
625
- cwd, file_ts, file_events = _codex_scan_file(f)
795
+ cwd, file_ts, file_events, file_human = _codex_scan_file(f)
626
796
  if cwd and file_ts:
627
797
  ts_groups[cwd].extend(file_ts)
628
798
  event_groups[cwd].extend(file_events)
629
- return [(cwd, sorted(ts), event_groups[cwd]) for cwd, ts in ts_groups.items()]
799
+ human_groups[cwd].extend(file_human)
800
+ return [(cwd, sorted(ts), event_groups[cwd], sorted(human_groups[cwd]))
801
+ for cwd, ts in ts_groups.items()]
630
802
 
631
803
 
632
804
  def codex_all():
633
- return [(label, ts) for label, ts, _ in codex_scan()]
805
+ return [(label, ts, human) for label, ts, _, human in codex_scan()]
634
806
 
635
807
 
636
808
  def _codex_cwd_only(path):
@@ -670,38 +842,45 @@ def codex_list():
670
842
  # --------------------------------------------------------------------------- #
671
843
 
672
844
  def _merge_projects(*project_lists):
673
- """Merge [(label, timestamps)] lists, combining same-label projects."""
674
- groups = defaultdict(list)
845
+ """Merge [(label, timestamps, human)] lists, combining same-label projects."""
846
+ ts_groups = defaultdict(list)
847
+ human_groups = defaultdict(list)
675
848
  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()]
849
+ for label, ts, human in projects:
850
+ ts_groups[label].extend(ts)
851
+ human_groups[label].extend(human)
852
+ return [(label, sorted(ts), sorted(human_groups[label]))
853
+ for label, ts in ts_groups.items()]
679
854
 
680
855
 
681
856
  def _merge_scans(*scans):
682
- """Merge [(label, timestamps, events)] lists, combining same-label projects."""
857
+ """Merge [(label, timestamps, events, human)] lists, combining same-label
858
+ projects."""
683
859
  ts_groups = defaultdict(list)
684
860
  event_groups = defaultdict(list)
861
+ human_groups = defaultdict(list)
685
862
  for scan in scans:
686
- for label, ts, events in scan:
863
+ for label, ts, events, human in scan:
687
864
  ts_groups[label].extend(ts)
688
865
  event_groups[label].extend(events)
689
- return [(label, sorted(ts), event_groups[label])
866
+ human_groups[label].extend(human)
867
+ return [(label, sorted(ts), event_groups[label], sorted(human_groups[label]))
690
868
  for label, ts in ts_groups.items()]
691
869
 
692
870
 
693
871
  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)
872
+ _, c_count, c_ts, c_events, c_human = claude_scan_single(project_path)
873
+ _, x_count, x_ts, x_events, x_human = codex_scan_single(project_path)
696
874
  count = c_count + x_count
697
875
  if count == 0:
698
- return None, 0, [], []
699
- return project_path, count, sorted(c_ts + x_ts), c_events + x_events
876
+ return None, 0, [], [], []
877
+ return (project_path, count, sorted(c_ts + x_ts), c_events + x_events,
878
+ sorted(c_human + x_human))
700
879
 
701
880
 
702
881
  def both_single(project_path):
703
- label, count, ts, _ = both_scan_single(project_path)
704
- return label, count, ts
882
+ label, count, ts, _, human = both_scan_single(project_path)
883
+ return label, count, ts, human
705
884
 
706
885
 
707
886
  def both_scan():
@@ -713,7 +892,10 @@ def both_all():
713
892
 
714
893
 
715
894
  def both_list():
716
- labels = {_claude_folder_to_pretty(f) for f in _claude_list_folders()}
895
+ labels = {
896
+ _claude_folder_cwd(f, glob.glob(os.path.join(CLAUDE_DIR, f, "*.jsonl")))
897
+ for f in _claude_list_folders()
898
+ }
717
899
  labels.update(codex_list())
718
900
  return sorted(labels)
719
901
 
@@ -722,6 +904,15 @@ def both_list():
722
904
  # Provider dispatch
723
905
  # --------------------------------------------------------------------------- #
724
906
 
907
+ # Every backend returns two timestamp lists per project: activity (every
908
+ # user-role record, which drives sessions and active time) and human (the
909
+ # messages a person sent, which is what the `human_prompts` count reports).
910
+ #
911
+ # single(path) → (label, files, activity, human)
912
+ # scan_single(path) → (label, files, activity, events, human)
913
+ # all() → [(label, activity, human)]
914
+ # scan() → [(label, activity, events, human)]
915
+ #
725
916
  # `scan`/`scan_single` are the token-aware backends: same work as `all`/`single`
726
917
  # plus the usage records picked up in the same pass. `all`/`single` remain the
727
918
  # timing-only views, and are what the plain (no --tokens) commands read.
@@ -784,11 +975,48 @@ def _day_keys(daily, token_days):
784
975
  return sorted(set(daily) | set(token_days))
785
976
 
786
977
 
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."""
978
+ def _load_projects(provider, show_tokens):
979
+ """[(label, activity, events, human)] for every project of a provider.
980
+
981
+ Reads the token-aware backend only when tokens were asked for; the plain
982
+ backend is the same scan without usage, so `events` is empty.
983
+ """
984
+ if show_tokens:
985
+ return PROVIDERS[provider]["scan"]()
986
+ return [(label, ts, [], human)
987
+ for label, ts, human in PROVIDERS[provider]["all"]()]
988
+
989
+
990
+ def _per_day(timestamps):
991
+ """Count timestamps per calendar day."""
992
+ counts = defaultdict(int)
993
+ for ts in timestamps:
994
+ counts[ts.date()] += 1
995
+ return counts
996
+
997
+
998
+ def _human_per_session(sessions, human):
999
+ """Human prompts inside each (start, end, count) session, in order.
1000
+
1001
+ Every human prompt is also an activity timestamp, so each one falls inside
1002
+ exactly one session's [start, end].
1003
+ """
1004
+ return [bisect.bisect_right(human, end) - bisect.bisect_left(human, start)
1005
+ for start, end, _ in sessions]
1006
+
1007
+
1008
+ def _day_entry(day, daily, prompts_per_day, human_per_day, token_days,
1009
+ show_tokens):
1010
+ """One JSON day bucket, with tokens attached when they were collected.
1011
+
1012
+ `prompts` keeps its original meaning (every user-role record, tool results
1013
+ included) so existing consumers are unaffected; `human_prompts` is the
1014
+ count of messages a person sent.
1015
+ """
789
1016
  entry = {"date": str(day),
790
1017
  "minutes": round(daily[day], 2),
791
- "prompts": prompts_per_day[day]}
1018
+ "prompts": prompts_per_day[day],
1019
+ "human_prompts": human_per_day[day]}
792
1020
  if show_tokens:
793
1021
  entry["tokens"] = token_days.get(day) or _sealed(_new_token_rec())
794
1022
  return entry
@@ -832,18 +1060,21 @@ def _print_model_table(summary):
832
1060
  def analyze_single(provider, project_path, idle_threshold, since, until, as_json,
833
1061
  show_tokens=False):
834
1062
  if show_tokens:
835
- label, count, timestamps, events = PROVIDERS[provider]["scan_single"](project_path)
1063
+ label, count, timestamps, events, human = \
1064
+ PROVIDERS[provider]["scan_single"](project_path)
836
1065
  events = _filter_events(events, since, until)
837
1066
  else:
838
- label, count, timestamps = PROVIDERS[provider]["single"](project_path)
1067
+ label, count, timestamps, human = PROVIDERS[provider]["single"](project_path)
839
1068
  events = []
840
1069
  timestamps = _filter_timestamps(timestamps, since, until)
1070
+ human = _filter_timestamps(human, since, until)
841
1071
 
842
1072
  if count == 0:
843
1073
  if as_json:
844
1074
  _print_json({
845
1075
  "provider": provider, "project": project_path,
846
- "error": "no sessions found", "prompts": 0, "days": [],
1076
+ "error": "no sessions found", "prompts": 0,
1077
+ "human_prompts": 0, "days": [],
847
1078
  })
848
1079
  sys.exit(1)
849
1080
  print(f"❌ No {provider} sessions found for: {project_path}")
@@ -859,7 +1090,7 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
859
1090
  _print_json({
860
1091
  "provider": provider, "project": project_path, "label": label,
861
1092
  "session_files": count, "since": _iso(since), "until": _iso(until),
862
- "prompts": 0, "days": [],
1093
+ "prompts": 0, "human_prompts": 0, "days": [],
863
1094
  })
864
1095
  sys.exit(0)
865
1096
  print("No user prompts found in the selected range.")
@@ -872,9 +1103,8 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
872
1103
  last_ts = timestamps[-1]
873
1104
  span_days = (last_ts.date() - first_ts.date()).days + 1
874
1105
 
875
- prompts_per_day = defaultdict(int)
876
- for ts in timestamps:
877
- prompts_per_day[ts.date()] += 1
1106
+ prompts_per_day = _per_day(timestamps)
1107
+ human_per_day = _per_day(human)
878
1108
 
879
1109
  token_summary = summarize_tokens(events) if show_tokens else None
880
1110
  token_days = tokens_by_day(events) if show_tokens else {}
@@ -892,11 +1122,13 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
892
1122
  "last": _iso(last_ts),
893
1123
  "span_days": span_days,
894
1124
  "prompts": len(timestamps),
1125
+ "human_prompts": len(human),
895
1126
  "sessions": len(sessions),
896
1127
  "active_days": len(daily),
897
1128
  "total_minutes": round(total_minutes, 2),
898
1129
  "days": [
899
- _day_entry(day, daily, prompts_per_day, token_days, show_tokens)
1130
+ _day_entry(day, daily, prompts_per_day, human_per_day,
1131
+ token_days, show_tokens)
900
1132
  for day in _day_keys(daily, token_days)
901
1133
  ],
902
1134
  }
@@ -914,7 +1146,7 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
914
1146
  print(f" First : {first_ts.strftime('%Y-%m-%d %H:%M')}")
915
1147
  print(f" Last : {last_ts.strftime('%Y-%m-%d %H:%M')}")
916
1148
  print(f" Span : {span_days} calendar days")
917
- print(f" Prompts : {len(timestamps)} total")
1149
+ print(f" Prompts : {len(human)} total")
918
1150
  print(f" Sessions: {len(sessions)} (idle threshold: {idle_threshold} min)")
919
1151
  print(f" Active : {len(daily)} days")
920
1152
  print(f" Total : {fmt_duration(total_minutes)}")
@@ -934,13 +1166,13 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
934
1166
  cell = (f" {fmt_tokens(token_days.get(day, {}).get('total', 0)):>9}"
935
1167
  if show_tokens else "")
936
1168
  print(f" {str(day):<12} {fmt_duration(mins):<14} "
937
- f"{prompts_per_day[day]:<10}{cell} {bar}")
1169
+ f"{human_per_day[day]:<10}{cell} {bar}")
938
1170
 
939
1171
  print("-" * (52 + len(token_col)))
940
1172
  total_cell = f" {fmt_tokens(token_summary['total']):>9}" if show_tokens else ""
941
1173
  # rstrip so the plain (no --tokens) row keeps its original width.
942
1174
  print(f" {'TOTAL':<12} {fmt_duration(total_minutes):<14} "
943
- f"{len(timestamps):<10}{total_cell}".rstrip())
1175
+ f"{len(human):<10}{total_cell}".rstrip())
944
1176
  if show_tokens:
945
1177
  _print_model_table(token_summary)
946
1178
  print()
@@ -948,21 +1180,20 @@ def analyze_single(provider, project_path, idle_threshold, since, until, as_json
948
1180
 
949
1181
  def analyze_all(provider, idle_threshold, since, until, as_json,
950
1182
  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"]()]
1183
+ projects = _load_projects(provider, show_tokens)
955
1184
 
956
1185
  rows = []
957
1186
  all_events = []
958
1187
  grand_minutes = 0.0
959
1188
  grand_prompts = 0
1189
+ grand_human = 0
960
1190
  grand_sessions = 0
961
1191
 
962
- for label, timestamps, events in projects:
1192
+ for label, timestamps, events, human in projects:
963
1193
  timestamps = _filter_timestamps(timestamps, since, until)
964
1194
  if not timestamps:
965
1195
  continue
1196
+ human = _filter_timestamps(human, since, until)
966
1197
  events = _filter_events(events, since, until)
967
1198
  daily, sessions = compute_active_hours(timestamps, idle_threshold)
968
1199
  total_minutes = sum(daily.values())
@@ -970,12 +1201,14 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
970
1201
  "label": label,
971
1202
  "minutes": total_minutes,
972
1203
  "prompts": len(timestamps),
1204
+ "human_prompts": len(human),
973
1205
  "sessions": len(sessions),
974
1206
  "tokens": summarize_tokens(events) if show_tokens else None,
975
1207
  })
976
1208
  all_events.extend(events)
977
1209
  grand_minutes += total_minutes
978
1210
  grand_prompts += len(timestamps)
1211
+ grand_human += len(human)
979
1212
  grand_sessions += len(sessions)
980
1213
 
981
1214
  if not rows:
@@ -983,7 +1216,8 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
983
1216
  _print_json({
984
1217
  "provider": provider, "since": _iso(since), "until": _iso(until),
985
1218
  "projects": [],
986
- "totals": {"projects": 0, "minutes": 0, "prompts": 0, "sessions": 0},
1219
+ "totals": {"projects": 0, "minutes": 0, "prompts": 0,
1220
+ "human_prompts": 0, "sessions": 0},
987
1221
  })
988
1222
  sys.exit(1)
989
1223
  print(f"❌ No {provider} projects with activity found ({PROVIDERS[provider]['location']})")
@@ -998,6 +1232,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
998
1232
  entry = {"project": r["label"],
999
1233
  "minutes": round(r["minutes"], 2),
1000
1234
  "prompts": r["prompts"],
1235
+ "human_prompts": r["human_prompts"],
1001
1236
  "sessions": r["sessions"]}
1002
1237
  if show_tokens:
1003
1238
  entry["tokens"] = r["tokens"]
@@ -1006,6 +1241,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1006
1241
  "projects": len(rows),
1007
1242
  "minutes": round(grand_minutes, 2),
1008
1243
  "prompts": grand_prompts,
1244
+ "human_prompts": grand_human,
1009
1245
  "sessions": grand_sessions,
1010
1246
  }
1011
1247
  if show_tokens:
@@ -1027,7 +1263,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1027
1263
  print(f" CLOCKWORK — ALL {_provider_label(provider)} PROJECTS (idle threshold: {idle_threshold} min)")
1028
1264
  print("=" * width)
1029
1265
  print(f" Projects: {len(rows)} with activity")
1030
- print(f" Prompts : {grand_prompts} total")
1266
+ print(f" Prompts : {grand_human} total")
1031
1267
  print(f" Sessions: {grand_sessions} total")
1032
1268
  print(f" Total : {fmt_duration(grand_minutes)}")
1033
1269
  if show_tokens:
@@ -1049,7 +1285,7 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1049
1285
  if len(name) > 29:
1050
1286
  name = "…" + name[-28:]
1051
1287
  t = r["tokens"]
1052
- print(f" {name:<30} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} "
1288
+ print(f" {name:<30} {fmt_duration(r['minutes']):>9} {r['human_prompts']:>8} "
1053
1289
  f"{fmt_tokens(t['input']):>8} {fmt_tokens(t['output']):>8} "
1054
1290
  f"{fmt_tokens(t['cache_read'] + t['cache_write']):>9} "
1055
1291
  f"{fmt_tokens(t['total']):>9}")
@@ -1058,18 +1294,18 @@ def analyze_all(provider, idle_threshold, since, until, as_json,
1058
1294
  name = "…" + name[-38:]
1059
1295
  bar_len = int((r["minutes"] / max_mins) * 12) if max_mins else 0
1060
1296
  bar = "█" * bar_len
1061
- print(f" {name:<40} {fmt_duration(r['minutes']):>9} {r['prompts']:>8} {r['sessions']:>5} {bar}")
1297
+ print(f" {name:<40} {fmt_duration(r['minutes']):>9} {r['human_prompts']:>8} {r['sessions']:>5} {bar}")
1062
1298
 
1063
1299
  print("-" * width)
1064
1300
  if show_tokens:
1065
- print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} "
1301
+ print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} {grand_human:>8} "
1066
1302
  f"{fmt_tokens(grand_tokens['input']):>8} "
1067
1303
  f"{fmt_tokens(grand_tokens['output']):>8} "
1068
1304
  f"{fmt_tokens(grand_tokens['cache_read'] + grand_tokens['cache_write']):>9} "
1069
1305
  f"{fmt_tokens(grand_tokens['total']):>9}")
1070
1306
  _print_model_table(grand_tokens)
1071
1307
  else:
1072
- print(f" {'TOTAL':<40} {fmt_duration(grand_minutes):>9} {grand_prompts:>8} {grand_sessions:>5}")
1308
+ print(f" {'TOTAL':<40} {fmt_duration(grand_minutes):>9} {grand_human:>8} {grand_sessions:>5}")
1073
1309
  print()
1074
1310
 
1075
1311
 
@@ -1089,29 +1325,30 @@ def _period_window(period):
1089
1325
 
1090
1326
  def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False):
1091
1327
  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"]()]
1328
+ projects = _load_projects(provider, show_tokens)
1096
1329
 
1097
1330
  rows = []
1098
1331
  all_events = []
1099
1332
  combined_daily = defaultdict(float)
1100
1333
  prompts_per_day = defaultdict(int)
1334
+ human_per_day = defaultdict(int)
1101
1335
  grand_minutes = 0.0
1102
1336
  grand_prompts = 0
1337
+ grand_human = 0
1103
1338
  grand_sessions = 0
1104
1339
 
1105
- for label, timestamps, events in projects:
1340
+ for label, timestamps, events, human in projects:
1106
1341
  timestamps = _filter_timestamps(timestamps, since, until)
1107
1342
  if not timestamps:
1108
1343
  continue
1344
+ human = _filter_timestamps(human, since, until)
1109
1345
  events = _filter_events(events, since, until)
1110
1346
  daily, sessions = compute_active_hours(timestamps, idle_threshold)
1111
1347
  rows.append({
1112
1348
  "label": label,
1113
1349
  "minutes": sum(daily.values()),
1114
1350
  "prompts": len(timestamps),
1351
+ "human_prompts": len(human),
1115
1352
  "sessions": len(sessions),
1116
1353
  "tokens": summarize_tokens(events) if show_tokens else None,
1117
1354
  })
@@ -1120,8 +1357,11 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1120
1357
  combined_daily[day] += mins
1121
1358
  for ts in timestamps:
1122
1359
  prompts_per_day[ts.date()] += 1
1360
+ for ts in human:
1361
+ human_per_day[ts.date()] += 1
1123
1362
  grand_minutes += sum(daily.values())
1124
1363
  grand_prompts += len(timestamps)
1364
+ grand_human += len(human)
1125
1365
  grand_sessions += len(sessions)
1126
1366
 
1127
1367
  rows.sort(key=lambda r: r["minutes"], reverse=True)
@@ -1134,6 +1374,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1134
1374
  entry = {"project": r["label"],
1135
1375
  "minutes": round(r["minutes"], 2),
1136
1376
  "prompts": r["prompts"],
1377
+ "human_prompts": r["human_prompts"],
1137
1378
  "sessions": r["sessions"]}
1138
1379
  if show_tokens:
1139
1380
  entry["tokens"] = r["tokens"]
@@ -1142,6 +1383,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1142
1383
  "projects": len(rows),
1143
1384
  "minutes": round(grand_minutes, 2),
1144
1385
  "prompts": grand_prompts,
1386
+ "human_prompts": grand_human,
1145
1387
  "sessions": grand_sessions,
1146
1388
  }
1147
1389
  if show_tokens:
@@ -1154,7 +1396,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1154
1396
  "until": _iso(until),
1155
1397
  "projects": projects_json,
1156
1398
  "days": [
1157
- _day_entry(day, combined_daily, prompts_per_day,
1399
+ _day_entry(day, combined_daily, prompts_per_day, human_per_day,
1158
1400
  token_days, show_tokens)
1159
1401
  for day in _day_keys(combined_daily, token_days)
1160
1402
  ],
@@ -1172,7 +1414,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1172
1414
  print()
1173
1415
  return
1174
1416
  print(f" Active : {fmt_duration(grand_minutes)} across {len(rows)} project(s)")
1175
- print(f" Prompts : {grand_prompts} Sessions: {grand_sessions}")
1417
+ print(f" Prompts : {grand_human} Sessions: {grand_sessions}")
1176
1418
  if show_tokens:
1177
1419
  print(f" Tokens : {fmt_tokens(grand_tokens['total'])} across "
1178
1420
  f"{grand_tokens['responses']:,} responses")
@@ -1194,18 +1436,18 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1194
1436
  if len(name) > 29:
1195
1437
  name = "…" + name[-28:]
1196
1438
  print(f" {name:<30} {fmt_duration(r['minutes']):>9} "
1197
- f"{r['prompts']:>7} {fmt_tokens(r['tokens']['total']):>9}")
1439
+ f"{r['human_prompts']:>7} {fmt_tokens(r['tokens']['total']):>9}")
1198
1440
  else:
1199
1441
  if len(name) > 33:
1200
1442
  name = "…" + name[-32:]
1201
1443
  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}")
1444
+ print(f" {name:<34} {fmt_duration(r['minutes']):>9} {r['human_prompts']:>7} {bar}")
1203
1445
  print("-" * width)
1204
1446
  if show_tokens:
1205
1447
  print(f" {'TOTAL':<30} {fmt_duration(grand_minutes):>9} "
1206
- f"{grand_prompts:>7} {fmt_tokens(grand_tokens['total']):>9}")
1448
+ f"{grand_human:>7} {fmt_tokens(grand_tokens['total']):>9}")
1207
1449
  else:
1208
- print(f" {'TOTAL':<34} {fmt_duration(grand_minutes):>9} {grand_prompts:>7}")
1450
+ print(f" {'TOTAL':<34} {fmt_duration(grand_minutes):>9} {grand_human:>7}")
1209
1451
 
1210
1452
  if period == "week":
1211
1453
  print()
@@ -1219,7 +1461,7 @@ def analyze_summary(provider, period, idle_threshold, as_json, show_tokens=False
1219
1461
  cell = (f" {fmt_tokens(token_days.get(day, {}).get('total', 0)):>9}"
1220
1462
  if show_tokens else "")
1221
1463
  print(f" {str(day):<12} {fmt_duration(mins):>9} "
1222
- f"{prompts_per_day[day]:>7}{cell} {bar}")
1464
+ f"{human_per_day[day]:>7}{cell} {bar}")
1223
1465
  if show_tokens:
1224
1466
  _print_model_table(grand_tokens)
1225
1467
  print()
@@ -1248,38 +1490,42 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1248
1490
  With `show_tokens`, every project, day, provider and the grand totals also
1249
1491
  carry a normalized `tokens` record with a per-model breakdown. The token
1250
1492
  fields are purely additive — a v2 consumer reads a v3 bundle unchanged.
1493
+
1494
+ `prompts` counts every user-role record, tool results included, and keeps
1495
+ that meaning for existing consumers. Wherever it appears (totals, daily,
1496
+ sessions, by_provider, and the raw timestamp list) a `human_prompts`
1497
+ sibling carries the messages a person actually sent. Also additive.
1251
1498
  """
1252
1499
  out_projects = []
1253
1500
  by_provider = {}
1254
1501
  grand_minutes = 0.0
1255
1502
  grand_prompts = 0
1503
+ grand_human = 0
1256
1504
  grand_sessions = 0
1257
1505
  grand_events = []
1258
1506
  name_counter = 0
1259
1507
 
1260
1508
  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"]()]
1509
+ projects = _load_projects(prov, show_tokens)
1265
1510
  p_minutes = 0.0
1266
1511
  p_prompts = 0
1512
+ p_human = 0
1267
1513
  p_sessions = 0
1268
1514
  p_projects = 0
1269
1515
  p_events = []
1270
1516
 
1271
- for label, timestamps, events in sorted(projects, key=lambda p: p[0]):
1517
+ for label, timestamps, events, human in sorted(projects, key=lambda p: p[0]):
1272
1518
  timestamps = _filter_timestamps(timestamps, since, until)
1273
1519
  if not timestamps:
1274
1520
  continue
1521
+ human = _filter_timestamps(human, since, until)
1275
1522
  events = _filter_events(events, since, until)
1276
1523
  daily, _ = compute_active_hours(timestamps, idle_threshold)
1277
1524
  sessions = group_sessions(timestamps, idle_threshold)
1278
1525
  total_minutes = sum(daily.values())
1279
1526
 
1280
- prompts_per_day = defaultdict(int)
1281
- for ts in timestamps:
1282
- prompts_per_day[ts.date()] += 1
1527
+ prompts_per_day = _per_day(timestamps)
1528
+ human_per_day = _per_day(human)
1283
1529
 
1284
1530
  token_days = tokens_by_day(events) if show_tokens else {}
1285
1531
 
@@ -1291,13 +1537,15 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1291
1537
  "totals": {
1292
1538
  "minutes": round(total_minutes, 2),
1293
1539
  "prompts": len(timestamps),
1540
+ "human_prompts": len(human),
1294
1541
  "sessions": len(sessions),
1295
1542
  "active_days": len(daily),
1296
1543
  "first": int(timestamps[0].timestamp()),
1297
1544
  "last": int(timestamps[-1].timestamp()),
1298
1545
  },
1299
1546
  "daily": [
1300
- _day_entry(day, daily, prompts_per_day, token_days, show_tokens)
1547
+ _day_entry(day, daily, prompts_per_day, human_per_day,
1548
+ token_days, show_tokens)
1301
1549
  for day in _day_keys(daily, token_days)
1302
1550
  ],
1303
1551
  }
@@ -1310,16 +1558,20 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1310
1558
  {"start": int(s.timestamp()),
1311
1559
  "end": int(e.timestamp()),
1312
1560
  "minutes": round((e - s).total_seconds() / 60, 2),
1313
- "prompts": c}
1314
- for s, e, c in sessions
1561
+ "prompts": c,
1562
+ "human_prompts": h}
1563
+ for (s, e, c), h in zip(sessions,
1564
+ _human_per_session(sessions, human))
1315
1565
  ]
1316
1566
  if detail == "raw":
1317
1567
  proj["prompts"] = [int(ts.timestamp()) for ts in timestamps]
1568
+ proj["human_prompts"] = [int(ts.timestamp()) for ts in human]
1318
1569
 
1319
1570
  out_projects.append(proj)
1320
1571
  p_projects += 1
1321
1572
  p_minutes += total_minutes
1322
1573
  p_prompts += len(timestamps)
1574
+ p_human += len(human)
1323
1575
  p_sessions += len(sessions)
1324
1576
  p_events.extend(events)
1325
1577
 
@@ -1328,12 +1580,14 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1328
1580
  "projects": p_projects,
1329
1581
  "minutes": round(p_minutes, 2),
1330
1582
  "prompts": p_prompts,
1583
+ "human_prompts": p_human,
1331
1584
  "sessions": p_sessions,
1332
1585
  }
1333
1586
  if show_tokens:
1334
1587
  by_provider[prov]["tokens"] = summarize_tokens(p_events)
1335
1588
  grand_minutes += p_minutes
1336
1589
  grand_prompts += p_prompts
1590
+ grand_human += p_human
1337
1591
  grand_sessions += p_sessions
1338
1592
  grand_events.extend(p_events)
1339
1593
 
@@ -1349,6 +1603,7 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1349
1603
  "projects": len(out_projects),
1350
1604
  "minutes": round(grand_minutes, 2),
1351
1605
  "prompts": grand_prompts,
1606
+ "human_prompts": grand_human,
1352
1607
  "sessions": grand_sessions,
1353
1608
  "by_provider": by_provider,
1354
1609
  }
@@ -1381,7 +1636,7 @@ def export_data(provider, idle_threshold, since, until, detail, anonymize,
1381
1636
  tags.append("tokens")
1382
1637
  print(f"\n ✓ export complete → {where}", file=sys.stderr)
1383
1638
  print(f" {' · '.join(tags)}", file=sys.stderr)
1384
- print(f" {len(out_projects)} projects · {grand_prompts:,} prompts "
1639
+ print(f" {len(out_projects)} projects · {grand_human:,} prompts "
1385
1640
  f"· {grand_sessions:,} sessions · {grand_minutes / 60:.1f}h active",
1386
1641
  file=sys.stderr)
1387
1642
  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.0
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=FNZlwic6dPdVUWvhfWNiLlzkyRJKaTmRTIR6KaotdPc,67041
2
+ clockwork_cli/__main__.py,sha256=HcXz3nL5ocmXEASzCOKbjM3Sj6czPe8sqJSXglAjBw0,39
3
+ clockwork_cli-0.4.0.dist-info/licenses/LICENSE,sha256=pz4uy4Ra9e-Ks0T7UFFi8rGL86-f29m2ZOB0WgixjLY,1068
4
+ clockwork_cli-0.4.0.dist-info/METADATA,sha256=9O2honRVQao8H1Q3_zoiwxk3k_6G4-JhEVDLqmS-ZXY,18699
5
+ clockwork_cli-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ clockwork_cli-0.4.0.dist-info/entry_points.txt,sha256=wmiWdgLrHpNKK9wDwCOiX4zyLFx71_G5DzydSiu8DWs,49
7
+ clockwork_cli-0.4.0.dist-info/top_level.txt,sha256=g5lh3hqDChq8bNBmiN2Kze86weZTddLJspNABd-2ckg,14
8
+ clockwork_cli-0.4.0.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,,