-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchronicle-manager.py
More file actions
1748 lines (1461 loc) · 61.2 KB
/
chronicle-manager.py
File metadata and controls
1748 lines (1461 loc) · 61.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Session Chronicle Manager v2.0 — cross-tool session coherence.
A shared CLI for managing a rolling log of AI coding sessions.
Works with any AI tool (Claude Code, Codex CLI, Gemini CLI, Cursor, etc.)
Usage:
chronicle-manager.py briefing [--format auto|structured|chronological]
chronicle-manager.py add --project NAME --title TITLE [--bullets "- item1" ...]
chronicle-manager.py update --entry N [--add-bullet "- text"] [--set-title "title"]
chronicle-manager.py rotate [--max-entries N]
chronicle-manager.py search "query" [--project NAME] [--tag TAG] [--since DATE]
chronicle-manager.py archive [--restore N]
chronicle-manager.py export [--format json|csv|markdown] [--include-archive]
chronicle-manager.py analytics
chronicle-manager.py validate
chronicle-manager.py config [--set KEY VALUE] [--reset]
chronicle-manager.py status
chronicle-manager.py init
Global flags:
--json JSON output for any command
--quiet Suppress non-essential output
--verbose Extra debug info
--config PATH Use alternate config file
--chronicle PATH Override chronicle path
Environment:
SESSION_CHRONICLE_PATH Override default chronicle location
Default: ~/.session-coherence/chronicle.md
"""
# =============================================================================
# 1. Imports and Constants
# =============================================================================
import argparse
import csv
import io
import json
import os
import re
import sys
import time
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
VERSION = "2.0.0"
# Tag parsing for structured bullets
TAG_RE = re.compile(r"^-\s+\[(\w+)\]\s+(.+)$")
VALID_TAGS = {"change", "decision", "blocker", "status", "next", "priority"}
CHRONICLE_HEADER = "<!-- Session Chronicle — rolling log, last 20 sessions. Oldest entries auto-trimmed. -->"
ARCHIVE_HEADER = "<!-- Session Chronicle Archive — rotated entries preserved here. -->"
DEFAULT_CONFIG = {
"max_entries": 20,
"archive_enabled": True,
"briefing_format": "auto",
"briefing_max_lines": 25,
"chronicle_path": "",
"plugins_dir": "",
"json_output": False,
}
# =============================================================================
# 2. Config Management
# =============================================================================
def get_config_path(override: Optional[str] = None) -> Path:
"""Get config file path."""
if override:
return Path(override)
return Path.home() / ".session-coherence" / "config.json"
def load_config(override_path: Optional[str] = None) -> Dict[str, Any]:
"""Load config from file, falling back to defaults."""
config = dict(DEFAULT_CONFIG)
path = get_config_path(override_path)
if path.exists():
try:
with open(path, "r", encoding="utf-8") as f:
user_config = json.load(f)
for k, v in user_config.items():
if k in DEFAULT_CONFIG:
config[k] = v
except (json.JSONDecodeError, OSError):
pass
return config
def save_config(config: Dict[str, Any], override_path: Optional[str] = None) -> None:
"""Save config to file."""
path = get_config_path(override_path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(config, f, indent=2)
def get_chronicle_path(args: Optional[argparse.Namespace] = None, config: Optional[Dict] = None) -> Path:
"""Get chronicle file path from args, env, config, or default."""
# CLI flag takes highest priority
if args and getattr(args, "chronicle", None):
return Path(args.chronicle)
# Env var next
env_path = os.environ.get("SESSION_CHRONICLE_PATH")
if env_path:
return Path(env_path)
# Config next
if config and config.get("chronicle_path"):
return Path(config["chronicle_path"])
return Path.home() / ".session-coherence" / "chronicle.md"
def get_archive_path(chronicle_path: Path) -> Path:
"""Get archive file path (same directory as chronicle)."""
return chronicle_path.parent / "archive.md"
# =============================================================================
# 3. File Locking
# =============================================================================
class FileLock:
"""Cross-platform file locking context manager.
Uses fcntl on Unix and msvcrt on Windows. Falls back to no-op
if neither is available.
"""
def __init__(self, path: Path, timeout: float = 3.0):
self.path = path
self.timeout = timeout
self._lock_path = path.parent / f".{path.name}.lock"
self._fh = None
def __enter__(self) -> "FileLock":
self._lock_path.parent.mkdir(parents=True, exist_ok=True)
self._fh = open(self._lock_path, "w", encoding="utf-8")
deadline = time.monotonic() + self.timeout
attempts = 0
while True:
try:
self._lock(self._fh)
return self
except (OSError, IOError):
attempts += 1
if time.monotonic() >= deadline:
if attempts > 1:
# Retry once more after a brief pause
try:
time.sleep(0.5)
self._lock(self._fh)
return self
except (OSError, IOError):
pass
raise TimeoutError(
f"Could not acquire lock on {self.path} after {self.timeout}s"
)
time.sleep(0.1)
def __exit__(self, *exc: Any) -> None:
if self._fh:
try:
self._unlock(self._fh)
except (OSError, IOError):
pass
self._fh.close()
try:
self._lock_path.unlink(missing_ok=True)
except OSError:
pass
@staticmethod
def _lock(fh: Any) -> None:
"""Acquire exclusive lock."""
if sys.platform == "win32":
import msvcrt
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
@staticmethod
def _unlock(fh: Any) -> None:
"""Release lock."""
if sys.platform == "win32":
import msvcrt
try:
fh.seek(0)
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
except (OSError, IOError):
pass
else:
import fcntl
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
# =============================================================================
# 4. Chronicle Parsing
# =============================================================================
def parse_bullet(line: str) -> Dict[str, str]:
"""Parse a bullet line into a dict with tag, text, and raw fields.
Tagged format: '- [decision] Chose JWT over sessions'
Untagged format: '- Fixed the login bug' (defaults to tag='change')
"""
m = TAG_RE.match(line)
if m:
tag = m.group(1).lower()
if tag not in VALID_TAGS:
tag = "change"
return {"tag": tag, "text": m.group(2).strip(), "raw": line}
# Untagged bullet — strip the leading "- "
return {"tag": "change", "text": line[2:].strip(), "raw": line}
def parse_chronicle(text: str) -> List[Dict[str, Any]]:
"""Parse chronicle into list of entry dicts (file order, newest first)."""
entries: List[Dict[str, Any]] = []
current: Optional[Dict[str, Any]] = None
for line in text.splitlines():
if line.startswith("### "):
if current:
entries.append(current)
header = line[4:].strip()
parts = [p.strip() for p in header.split("|")]
current = {
"header": header,
"date": parts[0] if len(parts) > 0 else "",
"project": parts[1] if len(parts) > 1 else "",
"title": parts[2] if len(parts) > 2 else "",
"bullets": [],
"raw_lines": [line],
}
elif current:
current["raw_lines"].append(line)
if line.startswith("- "):
current["bullets"].append(parse_bullet(line))
if current:
entries.append(current)
return entries
def rebuild_chronicle(entries: List[Dict[str, Any]], header: str = CHRONICLE_HEADER) -> str:
"""Rebuild chronicle text from parsed entries."""
lines = [header, ""]
for entry in entries:
lines.extend(entry["raw_lines"])
lines.append("")
return "\n".join(lines).rstrip() + "\n"
def entry_to_dict(entry: Dict[str, Any]) -> Dict[str, Any]:
"""Convert parsed entry to a clean JSON-serializable dict."""
tags = list({b["tag"] for b in entry["bullets"]})
return {
"date": entry["date"],
"project": entry["project"],
"title": entry["title"],
"bullets": [{"tag": b["tag"], "text": b["text"]} for b in entry["bullets"]],
"tags": tags,
}
# =============================================================================
# 5. Briefing Generation
# =============================================================================
def get_active_projects(entries: List[Dict], count: int = 10) -> Dict[str, str]:
"""Derive active projects from recent entries."""
projects: Dict[str, str] = {}
for entry in entries[:count]:
proj = entry["project"]
if proj and proj not in projects:
status = ""
for b in entry["bullets"]:
if b["tag"] == "status":
status = b["text"]
break
if b["text"].lower().startswith("status:"):
status = b["text"][len("status:"):].strip()
break
projects[proj] = status or entry["title"]
return projects
def extract_sections(entries: List[Dict], max_entries: int = 10) -> Dict[str, Any]:
"""Extract semantic sections from recent chronicle entries.
Returns a dict with:
active_threads: dict of project -> most recent status/next (max 6)
blockers: list of (text, project) tuples (max 4)
decisions: list of decision texts (max 4)
recent_work: list of (date, project, title) tuples (max 3)
focus: most recent priority or next bullet, or None
"""
active_threads: Dict[str, str] = {}
blockers: List[Tuple[str, str]] = []
decisions: List[str] = []
focus: Optional[str] = None
for entry in entries[:max_entries]:
proj = entry["project"]
if proj and proj not in active_threads:
for b in entry["bullets"]:
if b["tag"] in ("status", "next"):
active_threads[proj] = b["text"]
break
if proj not in active_threads:
active_threads[proj] = entry["title"]
for b in entry["bullets"]:
if b["tag"] == "blocker" and len(blockers) < 4:
blockers.append((b["text"], proj))
elif b["tag"] == "decision" and len(decisions) < 4:
decisions.append(b["text"])
elif b["tag"] == "priority" and focus is None:
focus = b["text"]
elif b["tag"] == "next" and focus is None:
focus = b["text"]
if len(active_threads) > 6:
active_threads = dict(list(active_threads.items())[:6])
recent_work = []
for entry in entries[:3]:
short_date = entry["date"].split(" ")[0] if " " in entry["date"] else entry["date"]
recent_work.append((short_date, entry["project"], entry["title"]))
return {
"active_threads": active_threads,
"blockers": blockers,
"decisions": decisions,
"recent_work": recent_work,
"focus": focus,
}
def has_semantic_tags(entries: List[Dict], max_entries: int = 10) -> bool:
"""Check if any recent entry has non-default tags (triggers structured mode)."""
for entry in entries[:max_entries]:
for b in entry["bullets"]:
if b["tag"] != "change":
return True
return False
def format_structured_briefing(entries: List[Dict], max_lines: int = 25) -> str:
"""Format entries as a semantic structured briefing."""
sections = extract_sections(entries)
lines = ["## Session Briefing", ""]
if sections["active_threads"]:
lines.append("Active Threads:")
for proj, status in sections["active_threads"].items():
lines.append(f"- {proj}: {status}")
lines.append("")
if sections["blockers"]:
lines.append("Blockers:")
for text, proj in sections["blockers"]:
lines.append(f"- {text} ({proj})")
lines.append("")
if sections["decisions"]:
lines.append("Recent Decisions:")
for text in sections["decisions"]:
lines.append(f"- {text}")
lines.append("")
if sections["recent_work"]:
lines.append("Last 3 Sessions:")
for date, proj, title in sections["recent_work"]:
lines.append(f"- {date}: {title} ({proj})")
lines.append("")
if sections["focus"]:
lines.append(f"Focus: {sections['focus']}")
lines.append("")
if len(lines) > max_lines:
lines = lines[:max_lines]
return "\n".join(lines).rstrip()
def format_chronological_briefing(entries: List[Dict], args: argparse.Namespace) -> str:
"""Format entries as the original chronological briefing."""
lines = ["## Session Briefing", ""]
detail = getattr(args, "detail", 5)
oneliner = getattr(args, "oneliner", 10)
max_bullets = getattr(args, "max_bullets", 3)
detailed = entries[:detail]
if detailed:
lines.append("Recent work:")
for entry in detailed:
lines.append(f"- {entry['date']} | {entry['project']} | {entry['title']}")
for bullet in entry["bullets"][:max_bullets]:
lines.append(f" > {bullet['text']}")
lines.append("")
oneliners = entries[detail:detail + oneliner]
if oneliners:
parts = []
for entry in oneliners:
short = entry["date"].split(" ")[0] if " " in entry["date"] else entry["date"]
parts.append(f"{short} {entry['project']} ({entry['title']})")
lines.append("Older: " + ", ".join(parts))
lines.append("")
projects = get_active_projects(entries)
if projects:
proj_parts = [f"{name} ({status})" for name, status in projects.items()]
lines.append("Active projects: " + ", ".join(proj_parts))
lines.append("")
if len(lines) > 30:
lines = lines[:30]
return "\n".join(lines).rstrip()
# =============================================================================
# 6. Entry Management (add, update, validate)
# =============================================================================
def duplicate_check(entries: List[Dict], project: str, title: str) -> bool:
"""Check if the most recent entry is a likely duplicate."""
if not entries:
return False
latest = entries[0]
if latest["project"].lower() == project.lower():
# Simple similarity: exact title match or high overlap
if latest["title"].lower().strip() == title.lower().strip():
return True
return False
def validate_entry_bullets(bullets: List[str], quiet: bool = False) -> List[str]:
"""Validate bullet list, return warnings."""
warnings: List[str] = []
if not bullets:
return warnings
if len(bullets) < 1:
warnings.append("Entry has no bullets")
if len(bullets) > 8:
warnings.append(f"Entry has {len(bullets)} bullets (recommended: 1-8)")
for bullet in bullets:
line = bullet if bullet.startswith("- ") else f"- {bullet}"
m = TAG_RE.match(line)
if m:
tag = m.group(1).lower()
if tag not in VALID_TAGS:
warnings.append(f"Unknown tag [{tag}] in: {line}")
return warnings
def validate_all_entries(entries: List[Dict]) -> List[Dict[str, Any]]:
"""Validate all entries, return list of issues."""
issues: List[Dict[str, Any]] = []
seen_headers: List[str] = []
for i, entry in enumerate(entries):
entry_issues: List[str] = []
idx = i + 1
# Check for missing fields
if not entry["project"]:
entry_issues.append("Missing project name")
if not entry["title"]:
entry_issues.append("Missing title")
if not entry["date"]:
entry_issues.append("Missing date")
# Check bullet count
bc = len(entry["bullets"])
if bc == 0:
entry_issues.append("No bullets")
elif bc > 8:
entry_issues.append(f"{bc} bullets (recommended max: 8)")
# Check for unknown tags
for b in entry["bullets"]:
raw = b.get("raw", "")
m = TAG_RE.match(raw)
if m and m.group(1).lower() not in VALID_TAGS:
entry_issues.append(f"Unknown tag [{m.group(1)}]")
# Check for duplicate headers
key = f"{entry['project']}|{entry['title']}"
if key in seen_headers:
entry_issues.append("Duplicate of another entry (same project + title)")
seen_headers.append(key)
if entry_issues:
issues.append({
"entry": idx,
"date": entry["date"],
"project": entry["project"],
"title": entry["title"],
"issues": entry_issues,
})
return issues
# =============================================================================
# 7. Search
# =============================================================================
def search_entries(
entries: List[Dict],
query: str,
case_sensitive: bool = False,
project_filter: Optional[str] = None,
tag_filter: Optional[str] = None,
since_filter: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Search entries for query string. Returns matching entries with match info."""
results: List[Dict[str, Any]] = []
q = query if case_sensitive else query.lower()
for i, entry in enumerate(entries):
# Apply filters
if project_filter:
if entry["project"].lower() != project_filter.lower():
continue
if tag_filter:
entry_tags = {b["tag"] for b in entry["bullets"]}
if tag_filter.lower() not in entry_tags:
continue
if since_filter:
try:
since_date = datetime.strptime(since_filter, "%Y-%m-%d")
entry_date_str = entry["date"].split(" ")[0] if " " in entry["date"] else entry["date"]
try:
entry_date = datetime.strptime(entry_date_str, "%Y-%m-%d")
if entry_date < since_date:
continue
except ValueError:
pass
except ValueError:
pass
# Search in title, project, and bullet texts
matches: List[str] = []
searchable_title = entry["title"] if case_sensitive else entry["title"].lower()
searchable_project = entry["project"] if case_sensitive else entry["project"].lower()
if q in searchable_title:
matches.append("title")
if q in searchable_project:
matches.append("project")
for b in entry["bullets"]:
searchable = b["text"] if case_sensitive else b["text"].lower()
if q in searchable:
matches.append(f"bullet:{b['tag']}")
if matches:
results.append({
"index": i + 1,
"entry": entry,
"matches": matches,
})
return results
def highlight_match(text: str, query: str, case_sensitive: bool = False) -> str:
"""Highlight query matches in text with **bold** markers."""
if not query:
return text
if case_sensitive:
return text.replace(query, f"**{query}**")
# Case-insensitive highlight — preserve original case
pattern = re.compile(re.escape(query), re.IGNORECASE)
return pattern.sub(lambda m: f"**{m.group(0)}**", text)
# =============================================================================
# 8. Archive
# =============================================================================
def archive_entries(entries: List[Dict], archive_path: Path) -> int:
"""Append entries to archive file. Returns count archived."""
if not entries:
return 0
archive_path.parent.mkdir(parents=True, exist_ok=True)
if archive_path.exists():
existing = archive_path.read_text(encoding="utf-8").strip()
# Find the end of the header line
if existing.startswith("<!--"):
header_end = existing.find("-->")
if header_end >= 0:
rest = existing[header_end + 3:].strip()
else:
rest = existing
else:
rest = existing
else:
rest = ""
new_blocks = []
for entry in entries:
new_blocks.append("\n".join(entry["raw_lines"]))
new_content = "\n\n".join(new_blocks)
if rest:
content = f"{ARCHIVE_HEADER}\n\n{new_content}\n\n{rest}\n"
else:
content = f"{ARCHIVE_HEADER}\n\n{new_content}\n"
archive_path.write_text(content, encoding="utf-8")
return len(entries)
def load_archive(archive_path: Path) -> List[Dict[str, Any]]:
"""Load and parse archive entries."""
if not archive_path.exists():
return []
text = archive_path.read_text(encoding="utf-8")
return parse_chronicle(text)
# =============================================================================
# 9. Export
# =============================================================================
def export_json(entries: List[Dict]) -> str:
"""Export entries as JSON."""
data = [entry_to_dict(e) for e in entries]
return json.dumps(data, indent=2, ensure_ascii=False)
def export_csv(entries: List[Dict]) -> str:
"""Export entries as CSV."""
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["date", "project", "title", "tags", "bullets"])
for entry in entries:
tags = ", ".join(sorted({b["tag"] for b in entry["bullets"]}))
bullets = " | ".join(b["text"] for b in entry["bullets"])
writer.writerow([entry["date"], entry["project"], entry["title"], tags, bullets])
return output.getvalue()
def export_markdown(entries: List[Dict]) -> str:
"""Export entries as clean markdown."""
lines = []
for entry in entries:
lines.append(f"### {entry['date']} | {entry['project']} | {entry['title']}")
for b in entry["bullets"]:
lines.append(b["raw"])
lines.append("")
return "\n".join(lines)
# =============================================================================
# 10. Analytics
# =============================================================================
def compute_analytics(
chronicle_entries: List[Dict],
archive_entries: List[Dict],
) -> Dict[str, Any]:
"""Compute analytics across chronicle and archive entries."""
all_entries = chronicle_entries + archive_entries
total = len(all_entries)
if total == 0:
return {"total": 0, "chronicle": 0, "archive": 0}
# Entries per project
project_counts: Dict[str, int] = {}
tag_counts: Dict[str, int] = {}
total_bullets = 0
dates: List[datetime] = []
blocker_texts: List[str] = []
decision_count = 0
for entry in all_entries:
proj = entry["project"]
if proj:
project_counts[proj] = project_counts.get(proj, 0) + 1
for b in entry["bullets"]:
total_bullets += 1
tag_counts[b["tag"]] = tag_counts.get(b["tag"], 0) + 1
if b["tag"] == "blocker":
blocker_texts.append(b["text"])
if b["tag"] == "decision":
decision_count += 1
# Parse date
date_str = entry["date"].split(" ")[0] if " " in entry["date"] else entry["date"]
try:
dates.append(datetime.strptime(date_str, "%Y-%m-%d"))
except ValueError:
pass
avg_bullets = total_bullets / total if total > 0 else 0
# Session frequency
dates.sort()
longest_gap_days = 0
if len(dates) >= 2:
for i in range(1, len(dates)):
gap = (dates[i] - dates[i - 1]).days
if gap > longest_gap_days:
longest_gap_days = gap
# Entries per day/week
if len(dates) >= 2:
span_days = max((dates[-1] - dates[0]).days, 1)
entries_per_day = total / span_days
entries_per_week = entries_per_day * 7
else:
entries_per_day = 0.0
entries_per_week = 0.0
# Most active projects (last 7 and 30 days)
now = datetime.now()
recent_7: Dict[str, int] = {}
recent_30: Dict[str, int] = {}
for entry in all_entries:
date_str = entry["date"].split(" ")[0] if " " in entry["date"] else entry["date"]
try:
d = datetime.strptime(date_str, "%Y-%m-%d")
except ValueError:
continue
proj = entry["project"]
if not proj:
continue
if (now - d).days <= 7:
recent_7[proj] = recent_7.get(proj, 0) + 1
if (now - d).days <= 30:
recent_30[proj] = recent_30.get(proj, 0) + 1
return {
"total": total,
"chronicle": len(chronicle_entries),
"archive": len(archive_entries),
"project_counts": dict(sorted(project_counts.items(), key=lambda x: -x[1])),
"tag_counts": dict(sorted(tag_counts.items(), key=lambda x: -x[1])),
"avg_bullets": round(avg_bullets, 1),
"entries_per_day": round(entries_per_day, 2),
"entries_per_week": round(entries_per_week, 1),
"longest_gap_days": longest_gap_days,
"decision_count": decision_count,
"blocker_count": len(blocker_texts),
"most_active_7d": dict(sorted(recent_7.items(), key=lambda x: -x[1])),
"most_active_30d": dict(sorted(recent_30.items(), key=lambda x: -x[1])),
}
def format_ascii_bar(label: str, value: int, max_value: int, bar_width: int = 30) -> str:
"""Format a single ASCII bar chart row."""
if max_value == 0:
filled = 0
else:
filled = int((value / max_value) * bar_width)
bar = "#" * filled + "." * (bar_width - filled)
return f" {label:<20} [{bar}] {value}"
# =============================================================================
# 11. CLI Command Handlers
# =============================================================================
def output_result(data: Any, text_fn: Any, args: argparse.Namespace) -> None:
"""Output either JSON or text based on flags."""
use_json = getattr(args, "json", False)
if not use_json:
config = load_config(getattr(args, "config", None))
use_json = config.get("json_output", False)
if use_json:
if isinstance(data, str):
print(json.dumps({"output": data}, ensure_ascii=False))
else:
print(json.dumps(data, indent=2, ensure_ascii=False))
else:
result = text_fn()
if result is not None:
print(result)
def cmd_briefing(args: argparse.Namespace) -> None:
"""Generate a session briefing from the chronicle."""
config = load_config(getattr(args, "config", None))
path = get_chronicle_path(args, config)
if not path.exists():
if getattr(args, "json", False):
print(json.dumps({"briefing": None, "reason": "no chronicle file"}))
return
text = path.read_text(encoding="utf-8").strip()
if not text:
if getattr(args, "json", False):
print(json.dumps({"briefing": None, "reason": "empty chronicle"}))
return
entries = parse_chronicle(text)
if not entries:
if getattr(args, "json", False):
print(json.dumps({"briefing": None, "reason": "no entries"}))
return
fmt = getattr(args, "format", None) or config.get("briefing_format", "auto")
max_lines = config.get("briefing_max_lines", 25)
if fmt == "structured":
output = format_structured_briefing(entries, max_lines)
elif fmt == "chronological":
output = format_chronological_briefing(entries, args)
else:
if has_semantic_tags(entries):
output = format_structured_briefing(entries, max_lines)
else:
output = format_chronological_briefing(entries, args)
if getattr(args, "json", False) or config.get("json_output", False):
sections = extract_sections(entries)
data = {
"briefing": output,
"format": fmt,
"entry_count": len(entries),
"sections": {
"active_threads": sections["active_threads"],
"blockers": [{"text": t, "project": p} for t, p in sections["blockers"]],
"decisions": sections["decisions"],
"recent_work": [{"date": d, "project": p, "title": t} for d, p, t in sections["recent_work"]],
"focus": sections["focus"],
},
}
print(json.dumps(data, indent=2, ensure_ascii=False))
elif output:
print(output)
def cmd_add(args: argparse.Namespace) -> None:
"""Add a new entry to the chronicle."""
config = load_config(getattr(args, "config", None))
path = get_chronicle_path(args, config)
path.parent.mkdir(parents=True, exist_ok=True)
quiet = getattr(args, "quiet", False)
verbose = getattr(args, "verbose", False)
use_json = getattr(args, "json", False) or config.get("json_output", False)
# Validate bullets
warnings: List[str] = []
if args.bullets:
warnings = validate_entry_bullets(args.bullets, quiet)
if warnings and not quiet:
for w in warnings:
if not use_json:
print(f"Warning: {w}", file=sys.stderr)
# Duplicate check
if path.exists():
text = path.read_text(encoding="utf-8").strip()
existing_entries = parse_chronicle(text)
if duplicate_check(existing_entries, args.project, args.title):
warnings.append("Possible duplicate of most recent entry (same project + title)")
if not quiet and not use_json:
print(f"Warning: {warnings[-1]}", file=sys.stderr)
now = datetime.now().strftime("%Y-%m-%d %H:%M")
header_line = f"### {now} | {args.project} | {args.title}"
entry_lines = [header_line]
if args.bullets:
for bullet in args.bullets:
if not bullet.startswith("- "):
bullet = f"- {bullet}"
entry_lines.append(bullet)
new_entry = "\n".join(entry_lines)
max_entries = getattr(args, "max_entries", None) or config.get("max_entries", 20)
with FileLock(path):
if path.exists():
text = path.read_text(encoding="utf-8").strip()
lines = text.split("\n", 1)
file_header = lines[0] if lines[0].startswith("<!--") else ""
rest = lines[1].strip() if len(lines) > 1 else ""
if not file_header:
rest = text
file_header = CHRONICLE_HEADER
content = f"{file_header}\n\n{new_entry}\n\n{rest}\n"
else:
content = f"{CHRONICLE_HEADER}\n\n{new_entry}\n"
path.write_text(content, encoding="utf-8")
# Auto-rotate
do_rotate(path, max_entries, config, args)
if use_json:
print(json.dumps({
"action": "added",
"project": args.project,
"title": args.title,
"date": now,
"warnings": warnings,
}, ensure_ascii=False))
elif not quiet:
print(f"Added: {args.project} | {args.title}")
def cmd_update(args: argparse.Namespace) -> None:
"""Update an existing chronicle entry."""
config = load_config(getattr(args, "config", None))
path = get_chronicle_path(args, config)
use_json = getattr(args, "json", False) or config.get("json_output", False)
quiet = getattr(args, "quiet", False)
if not path.exists():
msg = "No chronicle file found."
if use_json:
print(json.dumps({"error": msg}))
else:
print(msg)
return
with FileLock(path):
text = path.read_text(encoding="utf-8")
entries = parse_chronicle(text)
idx = args.entry - 1 # Convert to 0-indexed
if idx < 0 or idx >= len(entries):
msg = f"Entry {args.entry} not found (have {len(entries)} entries)"
if use_json:
print(json.dumps({"error": msg}))
else:
print(msg)
return
entry = entries[idx]
changes: List[str] = []
# Set title
if args.set_title:
old_header_line = entry["raw_lines"][0]
parts = [p.strip() for p in old_header_line[4:].split("|")]
if len(parts) >= 3:
parts[2] = args.set_title
new_header_line = "### " + " | ".join(parts)
entry["raw_lines"][0] = new_header_line
entry["title"] = args.set_title
entry["header"] = " | ".join(parts)
changes.append(f"title -> {args.set_title}")
# Add bullet
if args.add_bullet:
bullet = args.add_bullet
if not bullet.startswith("- "):
bullet = f"- {bullet}"
entry["raw_lines"].append(bullet)
entry["bullets"].append(parse_bullet(bullet))
changes.append(f"added bullet: {bullet}")
# Add tag shorthand
if args.add_tag:
tag = args.add_tag[0]
text_val = args.add_tag[1]
if tag.lower() not in VALID_TAGS:
warn = f"Unknown tag [{tag}] (known: {', '.join(sorted(VALID_TAGS))})"
if not quiet:
if use_json:
pass # Include in output
else:
print(f"Warning: {warn}", file=sys.stderr)
bullet = f"- [{tag}] {text_val}"
entry["raw_lines"].append(bullet)
entry["bullets"].append(parse_bullet(bullet))
changes.append(f"added [{tag}] {text_val}")
if not changes: