-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestore_terminals.py
More file actions
executable file
·1870 lines (1676 loc) · 70.9 KB
/
Copy pathrestore_terminals.py
File metadata and controls
executable file
·1870 lines (1676 loc) · 70.9 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
"""
restore_terminals.py — recover and relaunch AI coding sessions.
Scans Claude Code and Codex session history on disk, figures out which
sessions look like 'real terminals you were working in', and prints the
commands needed to reopen them as either Terminator windows or tmux/byobu
panes.
Deterministic core. Optional `--summarize` calls `claude -p` (CLI) to
summarize the last hour of each candidate session.
The default mode is a dry run. Add --execute to launch the selected sessions.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
HOME = Path.home()
CLAUDE_ROOT = HOME / ".claude" / "projects"
CODEX_ROOT = HOME / ".codex" / "sessions"
DEFAULT_CACHE = HOME / ".ai" / "sessions.jsonl"
SNAPSHOTS_DIR = HOME / ".ai" / "snapshots"
SLUG_MAX_LEN = 25
# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------
@dataclass
class Session:
tool: str # "claude" | "codex"
session_id: str
path: Path
cwd: str | None
first_ts: datetime | None
last_ts: datetime | None
message_count: int = 0
user_message_count: int = 0
first_user_prompt: str | None = None
last_user_prompt: str | None = None
last_role: str | None = None
interrupted: bool = False # last turn is assistant/tool — user wasn't replied to OR agent was mid-task
closed_with_clear: bool = False # last user action was /clear — session was abandoned, not paused
last_hour_transcript: str = "" # populated lazily for summarization
topic: str | None = None # short label from AI (used as window title)
slug: str | None = None # short kebab-case slug from AI (used for tmux window/pane names)
abstract: str | None = None # 1-2 sentence summary from AI
summary_error: str | None = None
search_matches: list[dict] = field(default_factory=list) # [{timestamp, role, snippet}]
git_remote: str | None = None
git_branch: str | None = None
pr_number: int | None = None
pr_title: str | None = None
pr_url: str | None = None
pr_state: str | None = None # "open" | "merged" | "closed"
pr_fetched_at: datetime | None = None
workspace: str | None = None # i3 workspace name (e.g. " 1 ")
window_title: str | None = None # terminal window title at snapshot time
@property
def span_minutes(self) -> float:
if not self.first_ts or not self.last_ts:
return 0.0
return (self.last_ts - self.first_ts).total_seconds() / 60.0
@property
def age_days(self) -> float:
if not self.last_ts:
return float("inf")
return (datetime.now(timezone.utc) - self.last_ts).total_seconds() / 86400.0
# ---------------------------------------------------------------------------
# Parsers
# ---------------------------------------------------------------------------
def _parse_ts(s: str | None) -> datetime | None:
if not s:
return None
try:
# Handle both "...Z" and "+00:00" forms
return datetime.fromisoformat(s.replace("Z", "+00:00"))
except ValueError:
return None
def _truncate(s: str | None, n: int = 120) -> str:
if not s:
return ""
s = " ".join(s.split())
return s if len(s) <= n else s[: n - 1] + "…"
def _claude_user_text(msg: dict) -> str | None:
"""Extract plain text from a Claude user message payload."""
content = msg.get("content")
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for p in content:
if isinstance(p, dict) and p.get("type") == "text":
t = p.get("text")
if t:
parts.append(t)
return "\n".join(parts) if parts else None
return None
def parse_claude(path: Path) -> Session | None:
"""Parse a Claude Code .jsonl into a Session summary."""
s = Session(tool="claude", session_id=path.stem, path=path, cwd=None,
first_ts=None, last_ts=None)
last_user_ts: datetime | None = None
last_assistant_ts: datetime | None = None
recent_lines: list[tuple[datetime, str, str]] = [] # (ts, role, text)
try:
with path.open() as f:
for line in f:
line = line.strip()
if not line:
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
if s.session_id is None and d.get("sessionId"):
s.session_id = d["sessionId"]
if s.cwd is None and d.get("cwd"):
s.cwd = d["cwd"]
ts = _parse_ts(d.get("timestamp"))
if ts:
if s.first_ts is None:
s.first_ts = ts
s.last_ts = ts
t = d.get("type")
msg = d.get("message") if isinstance(d.get("message"), dict) else None
role = (msg or {}).get("role") if msg else None
if t == "user" and role == "user":
text = _claude_user_text(msg) or ""
# skip pure tool_result payloads (Claude also uses role=user for those)
if text.strip():
s.user_message_count += 1
if s.first_user_prompt is None:
s.first_user_prompt = text
s.last_user_prompt = text
if ts:
last_user_ts = ts
recent_lines.append((ts, "user", text))
s.message_count += 1
s.last_role = "user" if text.strip() else s.last_role
elif t == "assistant" and role == "assistant":
s.message_count += 1
s.last_role = "assistant"
if ts:
last_assistant_ts = ts
text = _claude_user_text(msg) or ""
if text.strip():
recent_lines.append((ts, "assistant", text))
except OSError:
return None
if not s.last_ts or not s.cwd:
return None
# interrupted: last meaningful turn is assistant (agent was mid-reply when killed)
if last_assistant_ts and last_user_ts and last_assistant_ts > last_user_ts:
s.interrupted = True
# closed_with_clear: user's last action was /clear — session was deliberately abandoned
if s.last_user_prompt and "<command-name>/clear</command-name>" in s.last_user_prompt:
s.closed_with_clear = True
# last-hour transcript (for optional summarization)
if s.last_ts:
cutoff = s.last_ts - timedelta(hours=1)
kept = [(ts, r, t) for ts, r, t in recent_lines if ts >= cutoff]
s.last_hour_transcript = "\n\n".join(
f"[{r}] {_truncate(t, 800)}" for _, r, t in kept[-40:]
)
return s
def parse_codex(path: Path) -> Session | None:
"""Parse a Codex rollout .jsonl into a Session summary."""
s = Session(tool="codex", session_id=path.stem, path=path, cwd=None,
first_ts=None, last_ts=None)
last_user_ts: datetime | None = None
last_agent_ts: datetime | None = None
recent_lines: list[tuple[datetime, str, str]] = []
try:
with path.open() as f:
for line in f:
line = line.strip()
if not line:
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
ts = _parse_ts(d.get("timestamp"))
if ts:
if s.first_ts is None:
s.first_ts = ts
s.last_ts = ts
t = d.get("type")
p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
if t == "session_meta":
s.cwd = p.get("cwd") or s.cwd
s.session_id = p.get("id") or s.session_id
elif t == "event_msg" and p.get("type") == "user_message":
text = p.get("message") or p.get("text") or ""
if text.strip():
s.user_message_count += 1
if s.first_user_prompt is None:
s.first_user_prompt = text
s.last_user_prompt = text
s.last_role = "user"
if ts:
last_user_ts = ts
recent_lines.append((ts, "user", text))
s.message_count += 1
elif t == "event_msg" and p.get("type") == "agent_message":
s.last_role = "assistant"
s.message_count += 1
if ts:
last_agent_ts = ts
text = p.get("message") or ""
if text.strip():
recent_lines.append((ts, "assistant", text))
except OSError:
return None
if not s.last_ts or not s.cwd:
return None
if last_agent_ts and last_user_ts and last_agent_ts > last_user_ts:
s.interrupted = True
if s.last_ts:
cutoff = s.last_ts - timedelta(hours=1)
kept = [(ts, r, t) for ts, r, t in recent_lines if ts >= cutoff]
s.last_hour_transcript = "\n\n".join(
f"[{r}] {_truncate(t, 800)}" for _, r, t in kept[-40:]
)
return s
# ---------------------------------------------------------------------------
# Discovery + filter
# ---------------------------------------------------------------------------
def discover(tools: set[str], only_paths: set[Path] | None = None) -> list[Session]:
"""Parse session JSONLs into Session objects.
If `only_paths` is given, skip files not in that set — used by `--find`
after rg has narrowed the candidate set."""
out: list[Session] = []
if "claude" in tools and CLAUDE_ROOT.exists():
for proj in CLAUDE_ROOT.iterdir():
if not proj.is_dir():
continue
for f in proj.glob("*.jsonl"):
# skip sub-agent transcripts under */subagents/*
if "subagents" in f.parts:
continue
if only_paths is not None and f not in only_paths:
continue
parsed = parse_claude(f)
if parsed:
out.append(parsed)
if "codex" in tools and CODEX_ROOT.exists():
for f in CODEX_ROOT.rglob("rollout-*.jsonl"):
if only_paths is not None and f not in only_paths:
continue
parsed = parse_codex(f)
if parsed:
out.append(parsed)
return out
def apply_filters(
sessions: list[Session],
*,
days: int,
min_user_msgs: int,
min_span_minutes: float,
project_glob: str | None,
include_cleared: bool = False,
) -> list[Session]:
import fnmatch
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
kept: list[Session] = []
for s in sessions:
if not s.last_ts or s.last_ts < cutoff:
continue
if s.user_message_count < min_user_msgs:
continue
if s.span_minutes < min_span_minutes:
continue
if not s.cwd or not Path(s.cwd).exists():
continue
if project_glob and not fnmatch.fnmatch(s.cwd, project_glob):
continue
if s.closed_with_clear and not include_cleared:
continue
kept.append(s)
return kept
def rank(sessions: list[Session]) -> list[Session]:
"""Sort sessions by last activity (most recent first). No dedupe — multiple
sessions in the same cwd are legitimate (different topics, pre-worktree)."""
return sorted(
sessions,
key=lambda x: x.last_ts or datetime.min.replace(tzinfo=timezone.utc),
reverse=True,
)
# ---------------------------------------------------------------------------
# Summarization (optional — calls `claude -p`)
# ---------------------------------------------------------------------------
# Files that identify "what this project is". Scanned in the session's cwd
# (and, if cwd looks like a git worktree, also the repo root — best effort).
PROJECT_CONTEXT_FILES = [
"README.md", "README", "README.rst", "README.txt",
"CLAUDE.md", "AGENTS.md", "GEMINI.md", ".cursorrules",
"package.json", "pyproject.toml", "Cargo.toml", "go.mod",
]
PER_FILE_BUDGET = 4096 # bytes per project-context file
PROJECT_CONTEXT_BUDGET = 16384 # total bytes of project context
TRANSCRIPT_BUDGET = 12000 # bytes of last-hour transcript
def _repo_root(cwd: Path) -> Path | None:
"""Walk up until we see a .git dir/file (worktree); stop at $HOME."""
home = Path.home().resolve()
p = cwd.resolve()
while p != p.parent and str(p).startswith(str(home)):
if (p / ".git").exists():
return p
p = p.parent
return None
def gather_project_context(cwd_str: str | None) -> str:
"""Read project-identity files from cwd (and repo root if different)."""
if not cwd_str:
return ""
cwd = Path(cwd_str)
if not cwd.is_dir():
return ""
roots: list[Path] = [cwd]
rr = _repo_root(cwd)
if rr and rr != cwd:
roots.append(rr)
chunks: list[str] = []
used = 0
seen: set[Path] = set()
for root in roots:
for name in PROJECT_CONTEXT_FILES:
f = root / name
try:
if not f.is_file():
continue
real = f.resolve()
if real in seen:
continue
seen.add(real)
data = f.read_text(errors="replace")[:PER_FILE_BUDGET]
except OSError:
continue
header = f"==== {f.relative_to(root.anchor) if root == cwd else name} ({root}) ===="
chunk = f"{header}\n{data.strip()}\n"
if used + len(chunk) > PROJECT_CONTEXT_BUDGET:
break
chunks.append(chunk)
used += len(chunk)
if used >= PROJECT_CONTEXT_BUDGET:
break
return "\n".join(chunks)
SUMMARY_PROMPT = """\
You classify a coding-agent session. Produce a concrete, scannable summary —
the goal is for someone scanning a list of 30 sessions to immediately know
which one this is.
Given:
1. PROJECT CONTEXT — identity docs from the working directory
2. GIT CONTEXT — branch and remote (often encodes a ticket ID or feature)
3. LAST-HOUR TRANSCRIPT — the tail of the session right before it ended
Produce a STRICT JSON object, and nothing else:
{{"topic": "<concrete short label, 3-8 words, Title Case, no trailing punctuation>",
"slug": "<short kebab-case identifier, max 25 chars, lowercase letters/digits/hyphens only>",
"abstract": "<2 sentences, <=50 words. Sentence 1: what was being worked on — name the concrete subject (component, file, feature, ticket ID). Sentence 2: the immediate next step or where the session was left off>"}}
The topic MUST name the subject, not just the verb.
Bad: "Session Exit", "Bug Fix", "Code Review", "Documentation Pass"
Good: "Drop Cadence Iframe Config", "Fix S3 Multipart Retry", "ISO 25010 Doc Pass"
If the branch encodes a ticket (e.g. PROJ-1234), include it. If the subject is
genuinely unclear after reading both project context and transcript, prefer
"Misc <repo-name> Cleanup" over a generic verb phrase.
No preface. No markdown fences. No trailing text. Just the JSON object.
==== PROJECT CONTEXT (cwd: {cwd}) ====
{project_ctx}
==== GIT CONTEXT ====
branch: {branch}
remote: {remote}
==== LAST-HOUR TRANSCRIPT (tool: {tool}) ====
{transcript}
"""
def _extract_json(text: str) -> dict | None:
"""Best-effort JSON object extraction from LLM output."""
if not text:
return None
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1 or end < start:
return None
try:
obj = json.loads(text[start : end + 1])
return obj if isinstance(obj, dict) else None
except json.JSONDecodeError:
return None
def summarize(session: Session, timeout: int = 90) -> None:
"""Populate session.topic / session.abstract via `claude -p`. Mutates in place."""
if not session.last_hour_transcript.strip():
session.summary_error = "no last-hour transcript"
return
project_ctx = gather_project_context(session.cwd) or "(no README/CLAUDE.md/etc. found)"
prompt = SUMMARY_PROMPT.format(
cwd=session.cwd or "?",
tool=session.tool,
branch=session.git_branch or "(none)",
remote=session.git_remote or "(none)",
project_ctx=project_ctx[:PROJECT_CONTEXT_BUDGET],
transcript=session.last_hour_transcript[:TRANSCRIPT_BUDGET],
)
try:
result = subprocess.run(
["claude", "-p", prompt],
capture_output=True, text=True, timeout=timeout,
)
except FileNotFoundError:
session.summary_error = "claude CLI not found"
return
except subprocess.TimeoutExpired:
session.summary_error = "timed out"
return
if result.returncode != 0:
session.summary_error = f"claude -p exited {result.returncode}: {result.stderr.strip()[:200]}"
return
obj = _extract_json(result.stdout)
if not obj:
session.summary_error = "could not parse JSON from claude output"
session.abstract = result.stdout.strip()[:200] or None
return
topic = (obj.get("topic") or "").strip().rstrip(".!?") or None
raw_slug = (obj.get("slug") or "").strip() or None
slug = _slugify(raw_slug) or _slugify(topic)
abstract = (obj.get("abstract") or "").strip() or None
session.topic = topic
session.slug = slug
session.abstract = abstract
# ---------------------------------------------------------------------------
# Git helpers
# ---------------------------------------------------------------------------
_git_cache: dict[str, dict] = {}
def _git_info(cwd: str | None) -> dict:
if not cwd:
return {}
if cwd in _git_cache:
return _git_cache[cwd]
info: dict = {}
if not Path(cwd).is_dir():
_git_cache[cwd] = info
return info
try:
r = subprocess.run(["git", "-C", cwd, "remote", "get-url", "origin"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
info["remote"] = r.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
try:
r = subprocess.run(["git", "-C", cwd, "branch", "--show-current"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0 and r.stdout.strip():
info["branch"] = r.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
_git_cache[cwd] = info
return info
def hydrate_git_info(sessions: list[Session]) -> None:
"""Populate git_branch and git_remote for each session, in parallel."""
from concurrent.futures import ThreadPoolExecutor
def fill(s: Session) -> None:
if not s.cwd:
return
gi = _git_info(s.cwd)
s.git_branch = gi.get("branch") or s.git_branch
s.git_remote = gi.get("remote") or s.git_remote
with ThreadPoolExecutor(max_workers=8) as ex:
list(ex.map(fill, sessions))
def fetch_pr_info(session: Session, timeout: int = 10) -> None:
"""Populate session.pr_* via `gh pr list`. Mutates in place. Silent on
failure (no gh, no auth, no remote, no PR for this branch — all map to
'no PR info' which is fine)."""
if not session.git_branch:
return
if not session.cwd or not Path(session.cwd).is_dir():
return
if session.git_remote and "github" not in session.git_remote:
return
try:
r = subprocess.run(
["gh", "pr", "list",
"--head", session.git_branch,
"--state", "all",
"--json", "number,title,url,state",
"--limit", "1"],
cwd=session.cwd,
capture_output=True, text=True, timeout=timeout,
)
except (FileNotFoundError, subprocess.TimeoutExpired):
return
if r.returncode != 0:
# don't mark fetched_at — let it retry next run (likely auth/remote issue)
return
session.pr_fetched_at = datetime.now(timezone.utc)
try:
prs = json.loads(r.stdout)
except json.JSONDecodeError:
return
if not isinstance(prs, list) or not prs:
# successful query, no PR for this branch — clear any stale cached data
session.pr_number = None
session.pr_title = None
session.pr_url = None
session.pr_state = None
return
pr = prs[0]
session.pr_number = pr.get("number")
session.pr_title = pr.get("title")
session.pr_url = pr.get("url")
state = pr.get("state")
session.pr_state = state.lower() if isinstance(state, str) else None
# ---------------------------------------------------------------------------
# Content search (--find)
# ---------------------------------------------------------------------------
def _snippet_around(text: str, pattern: re.Pattern, ctx: int = 80) -> str:
m = pattern.search(text)
if not m:
return _truncate(text, 160)
start = max(0, m.start() - ctx)
end = min(len(text), m.end() + ctx)
snip = text[start:end]
if start > 0:
snip = "…" + snip
if end < len(text):
snip = snip + "…"
return " ".join(snip.split())
def _extract_all_text_claude(d: dict) -> tuple[str, str, str]:
"""(timestamp, role, all_text) from a Claude JSONL line."""
ts = d.get("timestamp") or ""
t = d.get("type") or ""
msg = d.get("message") if isinstance(d.get("message"), dict) else None
role = (msg or {}).get("role") or t
content = (msg or {}).get("content") if msg else None
text = ""
if isinstance(content, str):
text = content
elif isinstance(content, list):
parts = []
for p in content:
if isinstance(p, dict):
for key in ("text", "content", "output", "input"):
v = p.get(key)
if isinstance(v, str):
parts.append(v)
text = "\n".join(parts)
return ts, role, text
def _extract_all_text_codex(d: dict) -> tuple[str, str, str]:
"""(timestamp, role, all_text) from a Codex JSONL line."""
ts = d.get("timestamp") or ""
t = d.get("type") or ""
p = d.get("payload") if isinstance(d.get("payload"), dict) else {}
subt = p.get("type") or "" if isinstance(p, dict) else ""
role = subt or t
text = ""
for key in ("message", "text", "content", "output", "command"):
v = p.get(key) if isinstance(p, dict) else None
if isinstance(v, str) and v.strip():
text += v + "\n"
content = p.get("content") if isinstance(p, dict) else None
if isinstance(content, list):
for c in content:
if isinstance(c, dict):
for key in ("text", "content"):
v = c.get(key)
if isinstance(v, str):
text += v + "\n"
return ts, role, text
def _rg_candidate_paths(pattern_str: str, tools: set[str]) -> set[Path] | None:
"""Pre-filter session files with ripgrep. Returns the set of JSONL paths
that contain at least one line matching `pattern_str`, or None if rg
isn't available or rejects the pattern (caller should fall back to a
full scan). Searches Claude and Codex roots as configured by `tools`."""
from shutil import which
if not which("rg"):
return None
paths: set[Path] = set()
targets: list[tuple[Path, list[str]]] = []
if "claude" in tools and CLAUDE_ROOT.exists():
targets.append((CLAUDE_ROOT,
["--glob", "*.jsonl", "--glob", "!**/subagents/**"]))
if "codex" in tools and CODEX_ROOT.exists():
targets.append((CODEX_ROOT, ["--glob", "rollout-*.jsonl"]))
for root, globs in targets:
try:
r = subprocess.run(
["rg", "--files-with-matches", "--ignore-case",
*globs, "-e", pattern_str, str(root)],
capture_output=True, text=True, timeout=30,
)
except (FileNotFoundError, subprocess.TimeoutExpired):
return None
# rg exit codes: 0 = matches, 1 = no matches, 2 = error (bad regex etc.)
if r.returncode == 2:
return None
if r.returncode not in (0, 1):
return None
for line in r.stdout.splitlines():
line = line.strip()
if line:
paths.add(Path(line))
return paths
def search_session(session: Session, pattern: re.Pattern,
max_matches: int = 10) -> bool:
"""Search a session's JSONL for pattern. Populates session.search_matches
and git info. Returns True if any match found."""
extractor = (_extract_all_text_claude if session.tool == "claude"
else _extract_all_text_codex)
matches: list[dict] = []
try:
with session.path.open() as f:
for line in f:
line = line.strip()
if not line:
continue
# fast reject: raw line doesn't contain pattern → skip parse
if not pattern.search(line):
continue
try:
d = json.loads(line)
except json.JSONDecodeError:
continue
ts, role, text = extractor(d)
if text and pattern.search(text) and len(matches) < max_matches:
matches.append({
"timestamp": ts,
"role": role,
"snippet": _snippet_around(text, pattern),
})
except OSError:
return False
# also check cwd and git metadata
gi = _git_info(session.cwd) if session.cwd else {}
session.git_remote = gi.get("remote")
session.git_branch = gi.get("branch")
cwd_match = bool(session.cwd and pattern.search(session.cwd))
remote_match = bool(session.git_remote and pattern.search(session.git_remote))
branch_match = bool(session.git_branch and pattern.search(session.git_branch))
if not matches and not cwd_match and not remote_match and not branch_match:
return False
session.search_matches = matches
return True
def search_relevance(s: Session) -> float:
"""Higher = more relevant. Factors: match count, recency, user-msg ratio."""
score = len(s.search_matches) * 10.0
# weight user/assistant matches higher than tool output
for m in s.search_matches:
if m["role"] in ("user", "user_message"):
score += 5.0
elif m["role"] in ("assistant", "agent_message"):
score += 2.0
# recency bonus: sessions from today score +20, 7d ago → +0
if s.last_ts:
days = s.age_days
score += max(0.0, 20.0 - days * (20.0 / 7.0))
# branch/remote exact match bonus
if s.git_branch and s.search_matches:
score += 15.0
return score
# ---------------------------------------------------------------------------
# Terminator command rendering
# ---------------------------------------------------------------------------
def resume_cmd(s: Session) -> str:
if s.tool == "claude":
return f"claude --resume {s.session_id}"
# codex: resume accepts the rollout path
return f"codex resume {shlex.quote(str(s.path))}"
def terminator_argv(s: Session, title: str) -> list[str]:
"""The exact argv that would open a new Terminator window for this session."""
inner = f"{resume_cmd(s)}; exec $SHELL"
return [
"terminator",
"-u", # --no-dbus: own process, own window (i3-friendly)
"--working-directory", s.cwd or str(HOME),
"--title", title,
"-x", "bash", "-lc", inner,
]
def launch(sessions: list[Session]) -> int:
"""Spawn one detached Terminator window per session. Returns count launched."""
import time
launched = 0
procs: list[tuple[Session, subprocess.Popen, str]] = [] # (session, proc, title)
for s in sessions:
title = _truncate(s.topic or s.first_user_prompt or "(empty)", 60)
argv = terminator_argv(s, title)
try:
p = subprocess.Popen(
argv,
stdin=subprocess.DEVNULL,
start_new_session=True,
close_fds=True,
)
ws_label = f" → ws={s.workspace!r}" if s.workspace and s.workspace != "?" else ""
procs.append((s, p, title))
launched += 1
print(f" ✓ spawned pid={p.pid}: {short_cwd(s.cwd)} — {title}{ws_label}")
except FileNotFoundError:
print(f" ✗ terminator not found in PATH — aborting", file=sys.stderr)
return launched
except OSError as e:
print(f" ✗ failed for {short_cwd(s.cwd)}: {e}", file=sys.stderr)
time.sleep(0.2)
# wait for windows to appear, then move to saved workspaces
time.sleep(1.0)
for s, p, title in procs:
rc = p.poll()
if rc is not None and rc != 0:
print(f" [!] pid={p.pid} exited rc={rc} ({short_cwd(s.cwd)}) — "
f"see Terminator output above.", file=sys.stderr)
continue
if s.workspace and s.workspace != "?":
# find the window by PID via wmctrl and move it
try:
wm = subprocess.run(["wmctrl", "-lp"], capture_output=True, text=True, timeout=3)
for line in wm.stdout.strip().splitlines():
parts = line.split(None, 4)
if len(parts) >= 3 and int(parts[2]) == p.pid:
wid = parts[0]
subprocess.run(
["i3-msg", f'[id={wid}] move to workspace {s.workspace}'],
capture_output=True, timeout=3,
)
print(f" → moved to workspace {s.workspace!r}")
break
except (subprocess.TimeoutExpired, ValueError):
pass
return launched
# ---------------------------------------------------------------------------
# Byobu / tmux backend
# ---------------------------------------------------------------------------
def _have(cmd: str) -> bool:
from shutil import which
return which(cmd) is not None
def _pane_title(s: Session) -> str:
return s.slug or _slugify(s.topic) or s.session_id[:8]
def _window_name(group: list[Session], idx: int) -> str:
first = group[0]
base = first.slug or _slugify(first.topic) or f"win-{idx + 1}"
if len(group) > 1:
return f"{base}+{len(group) - 1}"
return base
def _byobu_groups(sessions: list[Session], layout: str, max_splits: int) -> list[list[Session]]:
if layout == "windows":
per = 1
elif layout == "splits":
per = max(1, len(sessions))
else: # hybrid
per = max(1, max_splits)
return [sessions[i:i + per] for i in range(0, len(sessions), per)]
def launch_byobu(
sessions: list[Session],
*,
layout: str,
max_splits: int,
split_direction: str,
session_name: str,
) -> int:
"""Build a tmux/byobu session with the picked sessions as panes/windows.
Returns the count of panes successfully placed. Does not attach — prints
the attach command at the end (or a switch-client hint if already in tmux).
"""
if not _have("tmux"):
print(" ✗ tmux not found in PATH (install byobu / tmux first)", file=sys.stderr)
return 0
if not sessions:
return 0
groups = _byobu_groups(sessions, layout, max_splits)
split_flag = "-h" if split_direction == "h" else "-v"
has_session = subprocess.run(
["tmux", "has-session", "-t", session_name],
capture_output=True,
).returncode == 0
def inner(s: Session) -> str:
return f"{resume_cmd(s)}; exec $SHELL"
placed = 0
for gi, group in enumerate(groups):
wname = _window_name(group, gi)
first = group[0]
first_inner = inner(first)
if gi == 0 and not has_session:
argv = ["tmux", "new-session", "-d",
"-s", session_name,
"-n", wname,
"-c", first.cwd or str(HOME),
first_inner]
else:
argv = ["tmux", "new-window",
"-t", f"{session_name}:",
"-n", wname,
"-c", first.cwd or str(HOME),
first_inner]
rc = subprocess.run(argv, capture_output=True, text=True)
if rc.returncode != 0:
print(f" ✗ tmux failed creating window {wname!r}: "
f"{rc.stderr.strip()}", file=sys.stderr)
return placed
subprocess.run(
["tmux", "select-pane", "-t", f"{session_name}:{wname}.0",
"-T", _pane_title(first)],
capture_output=True,
)
placed += 1
print(f" ✓ {wname}.0 {short_cwd(first.cwd)} — {_pane_title(first)}")
for s in group[1:]:
argv = ["tmux", "split-window", split_flag,
"-t", f"{session_name}:{wname}",
"-c", s.cwd or str(HOME),
inner(s)]
rc = subprocess.run(argv, capture_output=True, text=True)
if rc.returncode != 0:
print(f" ✗ split failed in {wname!r}: {rc.stderr.strip()}",
file=sys.stderr)
continue
subprocess.run(
["tmux", "select-pane", "-t", f"{session_name}:{wname}",
"-T", _pane_title(s)],
capture_output=True,
)
placed += 1
print(f" ✓ {wname}.+ {short_cwd(s.cwd)} — {_pane_title(s)}")
if len(group) > 1:
if len(group) > 4:
tmux_layout = "tiled"
else:
tmux_layout = "even-horizontal" if split_direction == "h" else "even-vertical"
subprocess.run(
["tmux", "select-layout", "-t", f"{session_name}:{wname}", tmux_layout],
capture_output=True,
)
# show pane titles in the border so slugs are visible
subprocess.run(
["tmux", "set-option", "-t", session_name, "pane-border-status", "top"],
capture_output=True,
)
subprocess.run(
["tmux", "set-option", "-t", session_name, "pane-border-format", " #T "],
capture_output=True,
)
in_tmux = bool(os.environ.get("TMUX"))
print()
if in_tmux:
print(f" built tmux session {session_name!r}. you're already in tmux — "
f"switch with: tmux switch-client -t {session_name}")
else:
print(f" built tmux session {session_name!r}. attach with: "
f"byobu attach -t {session_name} (or: tmux attach -t {session_name})")
return placed
# ---------------------------------------------------------------------------
# Output
# ---------------------------------------------------------------------------
def fmt_dt(dt: datetime | None) -> str:
if not dt:
return "?"
return dt.astimezone().strftime("%Y-%m-%d %H:%M")
def short_cwd(cwd: str | None) -> str:
if not cwd:
return "?"
home = str(HOME)
if cwd.startswith(home):
return "~" + cwd[len(home):]
return cwd
def _slugify(text: str | None, max_len: int = SLUG_MAX_LEN) -> str | None:
if not text:
return None
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
if not s:
return None
return s[:max_len].rstrip("-") or None
def print_plan(sessions: list[Session], use_summary: bool, target: str = "terminator") -> None:
if not sessions:
print("No sessions matched the filters. Try --days 30 or lower --min-messages.")
return
if target == "byobu":
head = f"\n Would place {len(sessions)} pane(s) into a byobu/tmux session (--dry-run):\n"
else:
head = (f"\n Would open {len(sessions)} Terminator window(s) "
f"(--dry-run; i3 will tile them):\n")
print(head)
for i, s in enumerate(sessions, 1):
flag = " [INTERRUPTED]" if s.interrupted else ""
title = _truncate(s.topic or s.first_user_prompt or "(empty)", 60)
print(f" ── window {i}/{len(sessions)}{flag} ──")