csm-cli 0.1.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.
csm_cli/scanner.py ADDED
@@ -0,0 +1,999 @@
1
+ """csm_scanner — 数据层:发现 Claude Code 会话文件并提取元数据。
2
+
3
+ 数据布局(claude 2.1.277 实测):
4
+ ~/.claude/projects/<encoded-cwd>/<session-uuid>.jsonl 主会话转录,文件名即 UUID
5
+ ~/.claude/sessions/<pid>.json 活跃进程注册表
6
+ ~/.claude/history.jsonl 全局用户输入历史(回退源)
7
+
8
+ 设计要点:
9
+ - 发现阶段只 stat(不打开文件),mtime 降序
10
+ - light_scan:单次 open 读 head/tail 各 64KB,拿 标题/首输入/项目路径
11
+ - full_scan:流式全文件,补 消息数/回复数/最后时间戳,兜底 light 没拿到的字段
12
+ - 所有解析容忍坏行;永不反解目录名('-' 有歧义),项目路径取行内第一条 cwd
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import re
20
+ import threading
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ DEFAULT_HEAD_BYTES = 64 * 1024
27
+ DEFAULT_TAIL_BYTES = 64 * 1024
28
+
29
+ CONFIG_ROOT = Path(os.environ.get("CLAUDE_CONFIG_DIR", "~/.claude")).expanduser()
30
+
31
+ # 斜杠命令/系统包装行:无 origin 也非 isMeta,但不是人输入的内容(实测会混在 str 行里)
32
+ _WRAPPER_RE = re.compile(
33
+ r"^\s*<(command-name|command-message|command-args|local-command-stdout"
34
+ r"|bash-|task-|system-|warning-)"
35
+ )
36
+
37
+
38
+ @dataclass
39
+ class RunningInfo:
40
+ """活跃进程注册表里的一条记录。"""
41
+
42
+ pid: int
43
+ status: str | None # "busy" / "idle" / "waiting" 原样透传
44
+ name: str | None # 会话昵称,如 "workspace-3d"
45
+ entrypoint: str | None = None # "cli" / "sdk-cli"
46
+ kind: str | None = None # "interactive" / "bg" / ...
47
+ proc_start: str | None = None # 防 pid 复用交叉校验用
48
+ tty: str | None = None # ps 快照来
49
+
50
+
51
+ @dataclass
52
+ class SessionEntry:
53
+ """一个会话的全部已知元数据(随扫描进度逐步补全)。"""
54
+
55
+ session_id: str
56
+ file_path: str
57
+ mtime: float
58
+ size: int
59
+ project_path: str | None = None
60
+ # 最后一条 cwd(tail 窗口即得,full 全扫覆盖):会话当前工作位置。
61
+ # 与 project_path(出生地)互补——EnterWorktree/cd 后 cwd 逐行变化,
62
+ # worktree 检测优先用它。仅辅助信号,缺省时回退 project_path,无需兜底标记。
63
+ last_cwd: str | None = None
64
+ # 轻扫(head+tail 窗口)即得
65
+ title: str | None = None
66
+ first_input: str | None = None
67
+ light_scanned: bool = False
68
+ title_scanned_full: bool = False # False = tail 窗口没找到标题,全扫需兜底
69
+ input_scanned_full: bool = False # False = head 窗口没找到首输入,全扫需兜底
70
+ # registry 关联
71
+ running_status: str | None = None
72
+ session_name: str | None = None
73
+ # 分类与收藏(三期)
74
+ entrypoint: str | None = None # jsonl 行内 "cli"/"sdk-cli";registry 兜底
75
+ tty: str | None = None # registry→ps 快照
76
+ is_current: bool = False # tty == csm 进程所在 tty
77
+ star: int = 0 # 0=无 / 1=⭐ / 2=★重要
78
+ tags: list[str] = field(default_factory=list)
79
+ # worktree 感知(四期):cwd 是 git worktree 时的归属信息
80
+ wt_name: str | None = None # worktree 目录名
81
+ wt_repo: str | None = None # 主仓库目录名(gitdir 指针反解,非目录名猜测)
82
+ wt_branch: str | None = None # 分支名(worktree HEAD 的 ref)
83
+ wt_ahead: int | None = None # 未合并到 base 的提交数(subprocess,后台补)
84
+ wt_scanned: bool = False # 纯文件检测完成(含「确认非 worktree」)
85
+ wt_deep_scanned: bool = False # ahead 已尝试(含失败,防反复起子进程)
86
+ # 全扫补全
87
+ msg_count: int | None = None # 真实用户输入次数(human turns)
88
+ assistant_count: int | None = None
89
+ last_timestamp: str | None = None
90
+ full_scanned: bool = False
91
+ # 测试/诊断
92
+ bad_lines: int = field(default=0, repr=False)
93
+
94
+ @property
95
+ def display_title(self) -> str:
96
+ return self.title or self.first_input or "(无用户输入)"
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # 发现
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def discover_sessions(limit: int = 0, project_filter: str | None = None) -> list[SessionEntry]:
105
+ """glob projects/*/*.jsonl(一层,天然跳过 <uuid>/subagents 与 memory/)。
106
+
107
+ 仅 stat 不读内容;按 (mtime desc, size desc, session_id) 稳定排序。
108
+ project_filter 对目录名做大小写不敏感子串粗筛(行内 cwd 的精筛在轻扫后)。
109
+ """
110
+ projects_dir = CONFIG_ROOT / "projects"
111
+ entries: list[SessionEntry] = []
112
+ if not projects_dir.is_dir():
113
+ return entries
114
+ pf = project_filter.lower() if project_filter else None
115
+ for path in projects_dir.glob("*/*.jsonl"):
116
+ if pf and pf not in path.parent.name.lower():
117
+ continue
118
+ try:
119
+ st = path.stat()
120
+ except OSError:
121
+ continue
122
+ entries.append(
123
+ SessionEntry(
124
+ session_id=path.stem,
125
+ file_path=str(path),
126
+ mtime=st.st_mtime,
127
+ size=st.st_size,
128
+ )
129
+ )
130
+ entries.sort(key=lambda e: (-e.mtime, -e.size, e.session_id))
131
+ if limit > 0:
132
+ entries = entries[:limit]
133
+ return entries
134
+
135
+
136
+ # ---------------------------------------------------------------------------
137
+ # 行判定
138
+ # ---------------------------------------------------------------------------
139
+
140
+
141
+ def is_real_user_input(obj: dict) -> bool:
142
+ """真实人类输入 vs 工具结果/通知/命令包装行。
143
+
144
+ 实测判定表(73 文件全量):
145
+ content 是 list -> tool_result 等,False(91% 的 user 行)
146
+ isMeta -> 伴随信息/peer 消息,False
147
+ origin.kind 非 human -> peer / task-notification,False
148
+ <command-name> 等包装 -> 斜杠命令回显,False
149
+ """
150
+ if obj.get("type") != "user":
151
+ return False
152
+ if obj.get("isMeta"):
153
+ return False
154
+ msg = obj.get("message") or {}
155
+ content = msg.get("content")
156
+ if not isinstance(content, str):
157
+ return False
158
+ origin = (obj.get("origin") or {}).get("kind")
159
+ if origin not in ("human", None): # None = 旧会话缺 origin 字段
160
+ return False
161
+ if _WRAPPER_RE.match(content):
162
+ return False
163
+ if content.lstrip().startswith("/"):
164
+ return False # 斜杠命令(如 "/goal 开始"),与 history 回退口径一致
165
+ return True
166
+
167
+
168
+ def _clean_input(text: str, cap: int = 200) -> str:
169
+ """压缩空白并截断(按字符,展示层再做 CJK 宽度截断)。"""
170
+ text = re.sub(r"\s+", " ", text).strip()
171
+ return text[:cap]
172
+
173
+
174
+ # ---------------------------------------------------------------------------
175
+ # 轻扫:head + tail 各一个窗口
176
+ # ---------------------------------------------------------------------------
177
+
178
+
179
+ def light_scan(
180
+ entry: SessionEntry,
181
+ head_bytes: int = DEFAULT_HEAD_BYTES,
182
+ tail_bytes: int = DEFAULT_TAIL_BYTES,
183
+ ) -> None:
184
+ """单次 open:头部找 第一条 cwd + 首条真实用户输入;尾部倒序找最后一条 ai-title。
185
+
186
+ 窗口内找不到不报错,置 None 并清 scanned_full 标记,留给 full_scan 兜底。
187
+ """
188
+ if entry.size == 0 or not entry.file_path:
189
+ entry.light_scanned = True
190
+ entry.title_scanned_full = True # 空文件确实没有,无需兜底
191
+ entry.input_scanned_full = True
192
+ return
193
+
194
+ try:
195
+ with open(entry.file_path, "rb") as f:
196
+ head = f.read(head_bytes)
197
+ if entry.size > head_bytes:
198
+ f.seek(entry.size - min(entry.size, tail_bytes))
199
+ tail = f.read(tail_bytes)
200
+ else:
201
+ tail = b"" # 小文件:head 已覆盖全部,标题在 head 里找
202
+ except OSError:
203
+ return
204
+
205
+ _scan_head(entry, head, truncated=entry.size > head_bytes)
206
+ _scan_tail(entry, tail if tail else head,
207
+ truncated=entry.size > head_bytes and bool(tail))
208
+ entry.light_scanned = True
209
+
210
+
211
+ def _scan_head(entry: SessionEntry, blob: bytes, truncated: bool) -> None:
212
+ """头部窗口:第一条 cwd + 第一条真实用户输入(正序,命中即停)。"""
213
+ lines = blob.decode("utf-8", errors="replace").split("\n")
214
+ if truncated and lines:
215
+ lines = lines[:-1] # 末行可能被窗口截断成半个 JSON
216
+ for line in lines:
217
+ line = line.strip()
218
+ if not line:
219
+ continue
220
+ try:
221
+ obj = json.loads(line)
222
+ except (json.JSONDecodeError, ValueError):
223
+ entry.bad_lines += 1
224
+ continue
225
+ if not isinstance(obj, dict):
226
+ continue
227
+ if entry.project_path is None:
228
+ cwd = obj.get("cwd")
229
+ if isinstance(cwd, str) and cwd:
230
+ entry.project_path = cwd
231
+ if entry.entrypoint is None:
232
+ ep = obj.get("entrypoint")
233
+ if isinstance(ep, str) and ep:
234
+ entry.entrypoint = ep
235
+ if entry.first_input is None and is_real_user_input(obj):
236
+ entry.first_input = _clean_input(obj["message"]["content"])
237
+ if (entry.project_path is not None and entry.first_input is not None
238
+ and entry.entrypoint is not None):
239
+ break
240
+ entry.input_scanned_full = entry.first_input is not None
241
+
242
+
243
+ def _scan_tail(entry: SessionEntry, blob: bytes, truncated: bool) -> None:
244
+ """尾部窗口:倒序找第一条 ai-title,即全文件最后一条(实测窗口 100% 覆盖)。"""
245
+ text = blob.decode("utf-8", errors="replace")
246
+ lines = text.split("\n")
247
+ if truncated and lines:
248
+ lines = lines[1:] # 首行可能被窗口截断
249
+ for line in reversed(lines):
250
+ line = line.strip()
251
+ if not line:
252
+ continue
253
+ try:
254
+ obj = json.loads(line)
255
+ except (json.JSONDecodeError, ValueError):
256
+ continue # tail 坏行不计数(可能是窗口边界)
257
+ if not isinstance(obj, dict):
258
+ continue
259
+ if entry.last_cwd is None:
260
+ cwd = obj.get("cwd")
261
+ if isinstance(cwd, str) and cwd:
262
+ entry.last_cwd = cwd # 倒序首见 = 全文件最后一条 cwd
263
+ if obj.get("type") == "ai-title":
264
+ title = obj.get("aiTitle")
265
+ if isinstance(title, str) and title.strip():
266
+ entry.title = title.strip()
267
+ entry.title_scanned_full = True
268
+ return
269
+ # 窗口内无标题:若没扫过完整文件,留给全扫兜底
270
+ entry.title_scanned_full = not truncated and entry.title is None
271
+
272
+
273
+ # ---------------------------------------------------------------------------
274
+ # 全扫
275
+ # ---------------------------------------------------------------------------
276
+
277
+
278
+ def full_scan(entry: SessionEntry) -> None:
279
+ """流式全文件:补 msg_count / assistant_count / last_timestamp,
280
+ 并兜底 light_scan 窗口没覆盖到的 title / first_input / project_path。"""
281
+ msg_count = assistant_count = 0
282
+ last_ts: str | None = None
283
+ try:
284
+ with open(entry.file_path, "r", encoding="utf-8", errors="replace") as f:
285
+ for line in f:
286
+ line = line.strip()
287
+ if not line:
288
+ continue
289
+ try:
290
+ obj = json.loads(line)
291
+ except (json.JSONDecodeError, ValueError):
292
+ entry.bad_lines += 1
293
+ continue
294
+ if not isinstance(obj, dict):
295
+ continue
296
+ cwd = obj.get("cwd")
297
+ if isinstance(cwd, str) and cwd:
298
+ if entry.project_path is None:
299
+ entry.project_path = cwd
300
+ entry.last_cwd = cwd # 持续覆盖 → 结束时即最后一条
301
+ if entry.entrypoint is None:
302
+ ep = obj.get("entrypoint")
303
+ if isinstance(ep, str) and ep:
304
+ entry.entrypoint = ep
305
+ if is_real_user_input(obj):
306
+ msg_count += 1
307
+ if entry.first_input is None:
308
+ entry.first_input = _clean_input(obj["message"]["content"])
309
+ if obj.get("type") == "assistant":
310
+ assistant_count += 1
311
+ if obj.get("type") == "ai-title":
312
+ title = obj.get("aiTitle")
313
+ if isinstance(title, str) and title.strip():
314
+ entry.title = title.strip() # 顺次覆盖 → 结束时即最后一条
315
+ ts = obj.get("timestamp")
316
+ if isinstance(ts, str):
317
+ last_ts = ts
318
+ except OSError:
319
+ return
320
+ entry.msg_count = msg_count
321
+ entry.assistant_count = assistant_count
322
+ entry.last_timestamp = last_ts
323
+ entry.title_scanned_full = True
324
+ entry.input_scanned_full = True
325
+ entry.full_scanned = True
326
+
327
+
328
+ # ---------------------------------------------------------------------------
329
+ # worktree 感知(四期):只读识别会话所属的 git worktree
330
+ # ---------------------------------------------------------------------------
331
+
332
+
333
+ @dataclass
334
+ class WorktreeInfo:
335
+ """cwd 是 git worktree 时,从 .git 指针反解出的归属信息。"""
336
+
337
+ name: str # worktree 目录名
338
+ main_repo: str # 主仓库根目录(绝对路径)
339
+ branch: str | None # 分支名;detached HEAD 或 HEAD 不可读时 None
340
+ gitdir: str # <main>/.git/worktrees/<name>
341
+
342
+
343
+ def detect_worktree(project_path: str | None) -> WorktreeInfo | None:
344
+ """读 <path>/.git 判定是否 worktree(仅文件读,零 subprocess)。
345
+
346
+ .git 是目录 → 主仓库/普通仓库,返回 None;.git 是文件(内容
347
+ "gitdir: <main>/.git/worktrees/<name>")→ worktree。gitdir 指针为相对
348
+ 路径时按 project_path 解析(git 手册语义)。形如 submodule 的
349
+ ".git/modules/..." 指针不匹配 worktrees 段,返回 None(不猜)。
350
+ worktree 目录已删除的残留 cwd 仍可反解 name/main_repo(路径字符串
351
+ 本身在),branch 读不到为 None。
352
+ """
353
+ if not project_path:
354
+ return None
355
+ dot = Path(project_path) / ".git"
356
+ try:
357
+ if dot.is_dir():
358
+ return None
359
+ content = dot.read_text(encoding="utf-8", errors="replace").strip()
360
+ except OSError:
361
+ return None
362
+ m = re.match(r"^gitdir:\s*(.+)$", content)
363
+ if not m:
364
+ return None
365
+ gitdir = Path(m.group(1).strip())
366
+ if not gitdir.is_absolute():
367
+ gitdir = Path(project_path) / gitdir
368
+ if gitdir.parent.name != "worktrees" or gitdir.parent.parent.name != ".git":
369
+ return None # submodule 等其它 .git 文件形态
370
+ branch = None
371
+ try:
372
+ head = (gitdir / "HEAD").read_text(encoding="utf-8", errors="replace").strip()
373
+ if head.startswith("ref: refs/heads/"):
374
+ branch = head[len("ref: refs/heads/"):]
375
+ except OSError:
376
+ pass
377
+ return WorktreeInfo(name=gitdir.name, main_repo=str(gitdir.parent.parent.parent),
378
+ branch=branch or None, gitdir=str(gitdir))
379
+
380
+
381
+ def worktree_scan(entry: SessionEntry) -> None:
382
+ """纯文件检测挂到条目:工作目录是 worktree 时填 wt_name/wt_repo/wt_branch。
383
+
384
+ 优先 last_cwd(会话当前所在,EnterWorktree/cd 后逐行变化),回退
385
+ project_path(出生地)。两者皆未知时不动(等 light/full 兜底出 cwd
386
+ 后再扫);确认非 worktree 也置 wt_scanned(与 *_scanned_full 同口径:
387
+ 区分「确认没有」和「还没扫」)。
388
+ """
389
+ path = entry.last_cwd or entry.project_path
390
+ if entry.wt_scanned or path is None:
391
+ return
392
+ info = detect_worktree(path)
393
+ if info is not None:
394
+ entry.wt_name = info.name
395
+ entry.wt_repo = Path(info.main_repo).name
396
+ entry.wt_branch = info.branch
397
+ entry.wt_scanned = True
398
+
399
+
400
+ # rev-list 的 base 候选:远端默认分支优先,回退本地主干(逐个试,首个可用即止)
401
+ _WT_BASE_CANDIDATES = ("origin/main", "origin/master", "main", "master")
402
+
403
+
404
+ def worktree_ahead(entry: SessionEntry) -> None:
405
+ """git rev-list --count <base>..<branch> 填 wt_ahead(subprocess,调用方放后台)。
406
+
407
+ 失败/超时/无可用 base → None,但置 wt_deep_scanned(含失败——避免每次
408
+ 轮询都对同一个条目反复起子进程)。
409
+ """
410
+ if entry.wt_deep_scanned or not entry.wt_branch or entry.project_path is None:
411
+ return
412
+ entry.wt_deep_scanned = True
413
+ import subprocess
414
+
415
+ for base in _WT_BASE_CANDIDATES:
416
+ try:
417
+ out = subprocess.run(
418
+ ["git", "-C", entry.project_path, "rev-list", "--count",
419
+ f"{base}..{entry.wt_branch}"],
420
+ capture_output=True, text=True, timeout=2,
421
+ )
422
+ except (OSError, subprocess.TimeoutExpired):
423
+ entry.wt_ahead = None
424
+ return
425
+ if out.returncode == 0:
426
+ try:
427
+ entry.wt_ahead = int(out.stdout.strip())
428
+ except ValueError:
429
+ entry.wt_ahead = None
430
+ return
431
+ entry.wt_ahead = None
432
+
433
+
434
+ # ---------------------------------------------------------------------------
435
+ # 进程快照(ps)与终端关联
436
+ # ---------------------------------------------------------------------------
437
+
438
+
439
+ @dataclass
440
+ class PsInfo:
441
+ """ps 快照里的一行:pid -> (ppid, tty, lstart, command)。"""
442
+
443
+ ppid: int
444
+ tty: str | None # "??" 归一化为 None
445
+ lstart: str | None # "Sat Nov 21 04:47:13 2026",与 registry procStart 同格式
446
+ command: str
447
+
448
+
449
+ def ps_snapshot() -> dict[int, PsInfo]:
450
+ """单次 `ps -axo pid=,ppid=,tty=,lstart=,command=`;失败/超时返回 {}(调用方各自降级)。
451
+
452
+ 一份快照三个用途:会话 tty / command 校验防 pid 回绕 / PPID 链上溯找本终端。
453
+ """
454
+ import subprocess
455
+
456
+ try:
457
+ proc = subprocess.run(
458
+ ["ps", "-axo", "pid=,ppid=,tty=,lstart=,command="],
459
+ capture_output=True, text=True, timeout=3,
460
+ )
461
+ except (OSError, subprocess.TimeoutExpired):
462
+ return {}
463
+ table: dict[int, PsInfo] = {}
464
+ for line in proc.stdout.splitlines():
465
+ parts = line.split(None, 3) # pid ppid tty rest
466
+ if len(parts) < 4:
467
+ continue
468
+ try:
469
+ pid, ppid = int(parts[0]), int(parts[1])
470
+ except ValueError:
471
+ continue
472
+ tty = parts[2] if parts[2] != "??" else None
473
+ rest = parts[3].split(None, 5) # 星期 月 日 时间 年 [command...]
474
+ if len(rest) < 5:
475
+ table[pid] = PsInfo(ppid, tty, None, parts[3])
476
+ continue
477
+ lstart = " ".join(rest[:5])
478
+ command = rest[5] if len(rest) > 5 else ""
479
+ table[pid] = PsInfo(ppid, tty, lstart, command)
480
+ return table
481
+
482
+
483
+ def current_terminal_tty(table: dict[int, PsInfo] | None = None) -> str | None:
484
+ """当前终端 tty。
485
+
486
+ 快路径 os.ttyname(0/1/2)(用户直接在终端跑 csm 时零开销命中);
487
+ 失败(被工具嵌套调用、stdin 非 tty)则沿 PPID 链上溯 ps 快照,
488
+ 取第一个非 ?? 的 tty。全程拿不到返回 None(「本终端」过滤器降级)。
489
+ """
490
+ for fd in (0, 1, 2):
491
+ try:
492
+ return os.ttyname(fd)
493
+ except OSError:
494
+ continue
495
+ table = table if table is not None else ps_snapshot()
496
+ pid = os.getpid()
497
+ for _ in range(16): # 防环/防深链
498
+ info = table.get(pid)
499
+ if info is None:
500
+ return None
501
+ if info.tty is not None:
502
+ return info.tty # 先查 tty:祖先自身的 ppid<=1 不影响它有 tty
503
+ if info.ppid <= 1:
504
+ return None
505
+ pid = info.ppid
506
+ return None
507
+
508
+
509
+ # ---------------------------------------------------------------------------
510
+ # 活跃注册表
511
+ # ---------------------------------------------------------------------------
512
+
513
+
514
+ def _pid_alive(pid: int) -> bool:
515
+ try:
516
+ os.kill(pid, 0)
517
+ except ProcessLookupError:
518
+ return False
519
+ except PermissionError:
520
+ return True # 保守:进程存在但属于别人
521
+ except OSError:
522
+ return False
523
+ return True
524
+
525
+
526
+ def _parse_lstart(text: str) -> "float | None":
527
+ """解析 ps lstart 格式 "Sat Nov 21 11:11:41 2026"(本地时间)为 epoch。
528
+
529
+ registry 的 procStart 是同格式但 UTC 时区(实测差 8 小时),调用方按
530
+ 各自语义解析后做容差比对。空格填充差异("Nov 6"/"Nov 6")先归一化。
531
+ """
532
+ import datetime
533
+
534
+ try:
535
+ dt = datetime.datetime.strptime(" ".join(text.split()), "%a %b %d %H:%M:%S %Y")
536
+ except ValueError:
537
+ return None
538
+ return dt.timestamp() # 无 tzinfo → 按本地时区解释,正是 ps 语义
539
+
540
+
541
+ def _same_process(proc_start: str | None, lstart: str | None) -> bool:
542
+ """procStart(UTC)与 lstart(本地)解析后相差 <60s 视为同进程(防 pid 回绕)。"""
543
+ import datetime
544
+
545
+ if not proc_start or not lstart:
546
+ return True # 任一缺失不比对(有 command 校验兜底)
547
+ try:
548
+ utc = datetime.datetime.strptime(" ".join(proc_start.split()),
549
+ "%a %b %d %H:%M:%S %Y").replace(
550
+ tzinfo=datetime.timezone.utc).timestamp()
551
+ except ValueError:
552
+ return True
553
+ local = _parse_lstart(lstart)
554
+ if local is None:
555
+ return True
556
+ return abs(utc - local) < 60.0
557
+
558
+
559
+ def load_running_registry(ps_table: dict[int, PsInfo] | None = None) -> dict[str, RunningInfo]:
560
+ """读 sessions/<pid>.json(忽略 *.key),返回 {sessionId: RunningInfo}。
561
+
562
+ 判活三重校验:os.kill(pid,0) + ps command 含 "claude"(防 pid 回绕)
563
+ + procStart 与 ps lstart 时区归一后容差 60s 比对(双方都有才比;
564
+ 实测 procStart 为 UTC、lstart 为本地时间,不能直接字符串相等)。
565
+ 死 pid 的记录不进索引;只读,不清理用户的注册表文件。
566
+ ps_table 供测试注入假快照。
567
+ """
568
+ table = ps_table if ps_table is not None else ps_snapshot()
569
+ registry: dict[str, RunningInfo] = {}
570
+ sessions_dir = CONFIG_ROOT / "sessions"
571
+ if not sessions_dir.is_dir():
572
+ return registry
573
+ for path in sessions_dir.glob("*.json"):
574
+ try:
575
+ obj = json.loads(path.read_text(encoding="utf-8"))
576
+ except (OSError, json.JSONDecodeError, ValueError):
577
+ continue
578
+ if not isinstance(obj, dict):
579
+ continue
580
+ sid = obj.get("sessionId")
581
+ pid = obj.get("pid")
582
+ if not isinstance(sid, str) or not isinstance(pid, int):
583
+ continue
584
+ if not _pid_alive(pid):
585
+ continue
586
+ info = table.get(pid) if table else None
587
+ if info is not None:
588
+ if "claude" not in (info.command or ""):
589
+ continue # pid 被其他程序复用
590
+ if not _same_process(obj.get("procStart"), info.lstart):
591
+ continue # 同 pid 不同启动时间 = 复用
592
+ registry[sid] = RunningInfo(
593
+ pid=pid,
594
+ status=obj.get("status"),
595
+ name=obj.get("name"),
596
+ entrypoint=obj.get("entrypoint"),
597
+ kind=obj.get("kind"),
598
+ proc_start=obj.get("procStart"),
599
+ tty=info.tty if info else None,
600
+ )
601
+ return registry
602
+
603
+
604
+ def apply_registry(entries: list[SessionEntry], registry: dict[str, RunningInfo],
605
+ current_tty: str | None = None) -> None:
606
+ """registry 结果回写条目;无记录即清空(修复 kill -9 残留导致的 stale busy)。"""
607
+ for e in entries:
608
+ info = registry.get(e.session_id)
609
+ if info:
610
+ e.running_status = info.status
611
+ e.session_name = info.name
612
+ e.tty = info.tty
613
+ if e.entrypoint is None and info.entrypoint:
614
+ e.entrypoint = info.entrypoint
615
+ e.is_current = bool(current_tty and info.tty and info.tty == current_tty)
616
+ else:
617
+ e.running_status = None
618
+ e.session_name = None
619
+ e.tty = None
620
+ e.is_current = False
621
+
622
+
623
+ # ---------------------------------------------------------------------------
624
+ # history.jsonl 回退
625
+ # ---------------------------------------------------------------------------
626
+
627
+
628
+ def load_history_index() -> dict[str, str]:
629
+ """一次性读 history.jsonl,建 {sessionId: 最早的非斜杠命令 display}。
630
+
631
+ 只读一遍文件,之后所有回退查询都是 O(1);文件缺失/坏行静默降级为空索引。
632
+ """
633
+ index: dict[str, tuple[int, str]] = {} # sid -> (timestamp_ms, display)
634
+ history_path = CONFIG_ROOT / "history.jsonl"
635
+ if not history_path.is_file():
636
+ return {}
637
+ try:
638
+ with open(history_path, "r", encoding="utf-8", errors="replace") as f:
639
+ for line in f:
640
+ line = line.strip()
641
+ if not line:
642
+ continue
643
+ try:
644
+ obj = json.loads(line)
645
+ except (json.JSONDecodeError, ValueError):
646
+ continue
647
+ if not isinstance(obj, dict):
648
+ continue
649
+ sid = obj.get("sessionId")
650
+ display = obj.get("display")
651
+ if not isinstance(sid, str) or not isinstance(display, str):
652
+ continue
653
+ if not display.strip() or display.startswith("/"):
654
+ continue
655
+ ts = obj.get("timestamp")
656
+ ts_val = ts if isinstance(ts, (int, float)) else 0
657
+ if sid not in index or ts_val < index[sid][0]:
658
+ index[sid] = (ts_val, display)
659
+ except OSError:
660
+ pass
661
+ return {sid: _clean_input(text) for sid, (_, text) in index.items()}
662
+
663
+
664
+ def first_input_from_history(session_id: str, index: dict[str, str] | None = None) -> str | None:
665
+ """该会话在全局输入历史里最早一条 display。传 index 避免重复读文件。"""
666
+ if index is None:
667
+ index = load_history_index()
668
+ return index.get(session_id)
669
+
670
+
671
+ # ===========================================================================
672
+ # 会话消息流解析(预览用)
673
+ # ===========================================================================
674
+
675
+ INPUT_TEXT_CAP = 20_000 # 异常巨块输入(粘贴大文本)的保险丝
676
+
677
+ # 工具 input 里最有辨识度的字段(优先级来自实测频率:command/file_path/description 最高频)
678
+ _BRIEF_KEYS = ("command", "file_path", "pattern", "path", "url", "description",
679
+ "prompt", "query", "message", "summary", "content", "name", "to")
680
+
681
+ # 保留原始 input 供 diff 渲染的工具白名单(其余工具只留 brief,控 LRU 缓存内存)
682
+ _DIFF_TOOLS = frozenset({"Edit", "Write", "MultiEdit", "NotebookEdit"})
683
+
684
+
685
+ @dataclass
686
+ class Message:
687
+ """预览用的一条展示单元(一个 assistant 消息会拆成多条:text / tool_use 各一条)。"""
688
+
689
+ role: str # "user" | "assistant"
690
+ kind: str # "input" | "text" | "tool_use"
691
+ order: int # 流内序号(0 起稳定递增,分页/前端 key 用)
692
+ ts: str | None = None # 行内 timestamp(ISO-8601 原文)
693
+ text: str | None = None # input 全文 / text 块全文(缓存存全文,序列化层按 level 截断)
694
+ tool_name: str | None = None # kind=tool_use 时,如 "Bash"
695
+ tool_brief: str | None = None # 工具 input 摘述,如 "git status"
696
+ tool_input: dict | None = None # diff 类工具的原始 input(白名单工具才存,供 Web 渲染行级 diff)
697
+ tool_result_brief: str | None = None # 回填:tool_result 前 ~80 字(None = 结果未写入)
698
+ tool_error: bool = False # 回填:tool_result.is_error
699
+
700
+
701
+ _MSG_CACHE: OrderedDict[str, tuple[float, int, list[Message]]] = OrderedDict()
702
+ _MSG_CACHE_LOCK = threading.Lock()
703
+ _MSG_CACHE_MAX = 16 # 14MB 会话解析出的字符串总量 ~几MB,16 条上限内存可控
704
+
705
+
706
+ def _cache_get(sid: str, mtime: float, size: int) -> list[Message] | None:
707
+ with _MSG_CACHE_LOCK:
708
+ hit = _MSG_CACHE.get(sid)
709
+ if hit is not None and hit[0] == mtime and hit[1] == size:
710
+ _MSG_CACHE.move_to_end(sid) # LRU 提升
711
+ return hit[2]
712
+ return None
713
+
714
+
715
+ def _cache_put(sid: str, mtime: float, size: int, msgs: list[Message]) -> None:
716
+ with _MSG_CACHE_LOCK:
717
+ _MSG_CACHE[sid] = (mtime, size, msgs)
718
+ _MSG_CACHE.move_to_end(sid)
719
+ while len(_MSG_CACHE) > _MSG_CACHE_MAX:
720
+ _MSG_CACHE.popitem(last=False)
721
+
722
+
723
+ def short_tool_name(name: str) -> str:
724
+ """mcp__ns__tool → ns.tool,其余原样;供 TUI/Web 展示层用。"""
725
+ if name.startswith("mcp__"):
726
+ return name[5:].replace("__", ".", 1)
727
+ return name
728
+
729
+
730
+ def _tool_brief(name: str, inp: Any) -> str:
731
+ """从工具 input 里挑最有辨识度的一个字段压成一行简述。"""
732
+ if not isinstance(inp, dict) or not inp:
733
+ return ""
734
+ for k in _BRIEF_KEYS:
735
+ v = inp.get(k)
736
+ if isinstance(v, str) and v.strip():
737
+ return _clean_input(v, cap=80)
738
+ for v in inp.values(): # 兜底 1:任意字符串字段
739
+ if isinstance(v, str) and v.strip():
740
+ return _clean_input(v, cap=60)
741
+ return f"({len(inp)} 参数)" # 兜底 2:全非字符串
742
+
743
+
744
+ def _result_brief(content: Any) -> str:
745
+ """tool_result.content(str 或块数组)压成一行简述。"""
746
+ text = ""
747
+ if isinstance(content, str):
748
+ text = content
749
+ elif isinstance(content, list):
750
+ parts = [b.get("text") for b in content
751
+ if isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str)]
752
+ text = " ".join(parts)
753
+ return _clean_input(text, cap=80)
754
+
755
+
756
+ def _merge_blocks(prev: list[dict], new: list[dict]) -> list[dict]:
757
+ """同 message.id 跨行分段的兼容合并。
758
+
759
+ 主流模式(每行一块增量):直接拼接。
760
+ 罕见模式(前缀增长快照):new 以 prev 为前缀 → 替换(避免重复)。
761
+ """
762
+ if len(new) >= len(prev) and new[: len(prev)] == prev:
763
+ return list(new)
764
+ return prev + list(new)
765
+
766
+
767
+ def read_session_messages(path: str | Path, use_cache: bool = True) -> list[Message] | None:
768
+ """流式解析会话文件为预览消息列表。文件不可读/不存在返回 None。
769
+
770
+ 解析口径:
771
+ - user 行:is_real_user_input() 为 True → Message(kind="input", text=原文,仅保险丝截断)
772
+ - user 行 content 是 list → tool_result 块按 tool_use_id 回填到已建 Message
773
+ - assistant 行:同一 message.id 跨多行,每行 content 是该消息的一个分段;
774
+ 按 _merge_blocks 累积,message.id 变化时 flush
775
+ - thinking 块跳过;isSidechain=True 的行跳过;其余 type 全部跳过
776
+ 坏行静默跳过(与 full_scan 同口径)。
777
+ """
778
+ p = Path(path)
779
+ sid = p.stem
780
+ try:
781
+ st = p.stat()
782
+ except OSError:
783
+ return None
784
+ if use_cache:
785
+ cached = _cache_get(sid, st.st_mtime, st.st_size)
786
+ if cached is not None:
787
+ return cached
788
+
789
+ messages: list[Message] = []
790
+ pending: dict[str, Message] = {} # tool_use_id -> 待回填 result 的 Message
791
+ cur_mid: str | None = None # 当前 assistant message.id
792
+ cur_ts: str | None = None
793
+ cur_blocks: list[dict] = []
794
+
795
+ def next_order() -> int:
796
+ return len(messages)
797
+
798
+ def flush() -> None:
799
+ nonlocal cur_mid, cur_ts, cur_blocks
800
+ for blk in cur_blocks:
801
+ btype = blk.get("type")
802
+ if btype == "text":
803
+ text = blk.get("text")
804
+ if isinstance(text, str) and text.strip():
805
+ messages.append(Message("assistant", "text", order=next_order(),
806
+ ts=cur_ts, text=text))
807
+ elif btype in ("tool_use", "mcp_tool_use"): # server_tool_use 无 input,跳过
808
+ name = blk.get("name") or "?"
809
+ inp = blk.get("input")
810
+ m = Message("assistant", "tool_use", order=next_order(), ts=cur_ts,
811
+ tool_name=name, tool_brief=_tool_brief(name, inp),
812
+ tool_input=inp if (name in _DIFF_TOOLS and isinstance(inp, dict)) else None)
813
+ messages.append(m)
814
+ if isinstance(blk.get("id"), str):
815
+ pending[blk["id"]] = m
816
+ # thinking / 其他块:跳过
817
+ cur_mid, cur_ts, cur_blocks = None, None, []
818
+
819
+ try:
820
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
821
+ for line in f:
822
+ line = line.strip()
823
+ if not line:
824
+ continue
825
+ try:
826
+ obj = json.loads(line)
827
+ except (json.JSONDecodeError, ValueError):
828
+ continue
829
+ if not isinstance(obj, dict):
830
+ continue
831
+ t = obj.get("type")
832
+ ts = obj.get("timestamp") if isinstance(obj.get("timestamp"), str) else None
833
+
834
+ if t == "user":
835
+ # user 行(输入或 tool_result 载体)出现 = 上一个 assistant
836
+ # turn 已完整写出(assistant 消息以 text/tool_use 结尾),
837
+ # 先 flush 让 pending 注册与消息时序正确——否则下一个 assistant
838
+ # 行到达前累积中的消息会排在后续 user 输入之后(时序错乱)
839
+ if cur_blocks:
840
+ flush()
841
+ if is_real_user_input(obj):
842
+ content = obj["message"]["content"]
843
+ messages.append(Message("user", "input", order=next_order(),
844
+ ts=ts, text=content[:INPUT_TEXT_CAP]))
845
+ else:
846
+ content = (obj.get("message") or {}).get("content")
847
+ if isinstance(content, list): # tool_result 载体行
848
+ for blk in content:
849
+ if (isinstance(blk, dict) and blk.get("type") == "tool_result"
850
+ and isinstance(blk.get("tool_use_id"), str)):
851
+ m = pending.pop(blk["tool_use_id"], None)
852
+ if m is not None: # 孤儿 result 丢弃
853
+ m.tool_result_brief = _result_brief(blk.get("content"))
854
+ m.tool_error = bool(blk.get("is_error"))
855
+
856
+ elif t == "assistant" and not obj.get("isSidechain"):
857
+ msg = obj.get("message") or {}
858
+ mid = msg.get("id") if isinstance(msg.get("id"), str) else None
859
+ blocks = [b for b in (msg.get("content") or []) if isinstance(b, dict)]
860
+ if mid is not None and mid == cur_mid:
861
+ cur_blocks = _merge_blocks(cur_blocks, blocks)
862
+ else:
863
+ flush()
864
+ cur_mid, cur_ts, cur_blocks = mid, ts, list(blocks)
865
+ # 其余 type(last-prompt/mode/attachment/...)全部忽略
866
+ flush() # 收尾
867
+ except OSError:
868
+ return None
869
+
870
+ if use_cache:
871
+ _cache_put(sid, st.st_mtime, st.st_size, messages)
872
+ return messages
873
+
874
+
875
+ # ===========================================================================
876
+ # 收藏(favorites.json,csm 自有命名空间)
877
+ # ===========================================================================
878
+
879
+ FAVORITES_VERSION = 1
880
+ _FAV_LOCK = threading.Lock() # 进程内串行化(web 多请求线程);跨进程用旁路 flock
881
+
882
+
883
+ def favorites_path() -> Path:
884
+ return CONFIG_ROOT / "csm" / "favorites.json"
885
+
886
+
887
+ def load_favorites() -> dict[str, dict]:
888
+ """读 favorites.json;缺失/损坏/非 dict → {}(静默降级)。
889
+
890
+ 只读不锁:写方用原子 rename,读者永远看不到半截文件。
891
+ """
892
+ try:
893
+ obj = json.loads(favorites_path().read_text(encoding="utf-8"))
894
+ except (OSError, json.JSONDecodeError, ValueError):
895
+ return {}
896
+ if not isinstance(obj, dict):
897
+ return {}
898
+ sessions = obj.get("sessions")
899
+ return sessions if isinstance(sessions, dict) else {}
900
+
901
+
902
+ def update_favorite(sid: str, star: int | None = None,
903
+ tags: list[str] | None = None) -> dict:
904
+ """读-改-写 favorites.json,返回该 sid 的新状态 {"star": int, "tags": [...]}。
905
+
906
+ star 必须 0/1/2 否则 ValueError;tags 归一化:strip、去空、去重(保序)、
907
+ 每条截 24 字符、最多 8 条。star==0 且 tags 为空 → 删除该键(内联 GC)。
908
+ 首次创建写 added_at,仅改 tags 时保留原值。
909
+ 跨进程并发:旁路锁文件 flock(锁与 rename 不组合,故锁独立的 .lock 文件)。
910
+ """
911
+ if star is not None and star not in (0, 1, 2):
912
+ raise ValueError("star must be 0|1|2")
913
+ import fcntl
914
+
915
+ with _FAV_LOCK:
916
+ path = favorites_path()
917
+ path.parent.mkdir(parents=True, exist_ok=True)
918
+ with open(str(path) + ".lock", "a+b") as lockf:
919
+ fcntl.flock(lockf.fileno(), fcntl.LOCK_EX)
920
+ try:
921
+ data = load_favorites()
922
+ rec = data.get(sid) if isinstance(data.get(sid), dict) else {}
923
+ new_star = star if star is not None else int(rec.get("star", 0) or 0)
924
+ if tags is None:
925
+ new_tags = [str(t) for t in (rec.get("tags") or [])]
926
+ else:
927
+ new_tags = []
928
+ for t in tags:
929
+ t = str(t).strip()[:24]
930
+ if t and t not in new_tags:
931
+ new_tags.append(t)
932
+ new_tags = new_tags[:8]
933
+ added_at = rec.get("added_at")
934
+ if new_star == 0 and not new_tags:
935
+ data.pop(sid, None)
936
+ else:
937
+ if not added_at:
938
+ import datetime
939
+
940
+ added_at = datetime.datetime.now().isoformat(timespec="seconds")
941
+ data[sid] = {"star": new_star, "tags": new_tags, "added_at": added_at}
942
+ tmp = str(path) + f".tmp.{os.getpid()}"
943
+ with open(tmp, "w", encoding="utf-8") as f:
944
+ json.dump({"version": FAVORITES_VERSION, "sessions": data},
945
+ f, ensure_ascii=False, indent=1)
946
+ os.replace(tmp, path)
947
+ return {"star": new_star, "tags": new_tags}
948
+ finally:
949
+ fcntl.flock(lockf.fileno(), fcntl.LOCK_UN)
950
+
951
+
952
+ def apply_favorites(entries: list[SessionEntry], fav: dict[str, dict]) -> None:
953
+ """favorites 回写条目(缺省 star=0/tags=[])。"""
954
+ for e in entries:
955
+ rec = fav.get(e.session_id)
956
+ if isinstance(rec, dict):
957
+ e.star = int(rec.get("star", 0) or 0)
958
+ tags = rec.get("tags")
959
+ e.tags = [str(t) for t in tags] if isinstance(tags, list) else []
960
+ else:
961
+ e.star = 0
962
+ e.tags = []
963
+
964
+
965
+ # ===========================================================================
966
+ # 置顶排序与分类过滤(TUI/Web/测试三方共享纯函数)
967
+ # ===========================================================================
968
+
969
+ FILTER_NAMES = ("all", "running", "current", "starred", "closed", "once")
970
+
971
+
972
+ def sort_pinned(entries: list[SessionEntry]) -> None:
973
+ """收藏置顶排序:(-star, -mtime, -size, session_id)。就地稳定排序。
974
+
975
+ star 只有 3 个值,元组键与「★段→⭐段→普通段(段内 mtime 降序)」严格等价。
976
+ """
977
+ entries.sort(key=lambda e: (-e.star, -e.mtime, -e.size, e.session_id))
978
+
979
+
980
+ def match_filter(e: SessionEntry, name: str) -> bool:
981
+ """分类过滤器(TUI 数字键 / Web chips 共用)。
982
+
983
+ all: 恒真 | running: 注册表有活记录 | current: tty 等于本终端
984
+ starred: star>0 | closed: running_status 为 None(jsonl 在 + 无活记录)
985
+ once: 恰 1 条用户输入(msg_count 未知时排除,不猜)
986
+ """
987
+ if name == "all":
988
+ return True
989
+ if name == "running":
990
+ return e.running_status is not None
991
+ if name == "current":
992
+ return e.is_current
993
+ if name == "starred":
994
+ return e.star > 0
995
+ if name == "closed":
996
+ return e.running_status is None
997
+ if name == "once":
998
+ return e.msg_count == 1
999
+ return False