csm-cli 0.2.0__tar.gz → 0.3.0__tar.gz
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-0.2.0 → csm_cli-0.3.0}/CHANGELOG.md +15 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/PKG-INFO +25 -5
- {csm_cli-0.2.0 → csm_cli-0.3.0}/README.md +24 -4
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/__init__.py +1 -1
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/cli.py +73 -0
- csm_cli-0.3.0/src/csm_cli/ftsearch.py +232 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/scanner.py +71 -5
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/ui.py +76 -5
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/web.html +115 -1
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/web.py +43 -1
- csm_cli-0.3.0/test_ftsearch.py +125 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/test_scanner.py +84 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/.gitignore +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/LICENSE +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/pyproject.toml +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/__main__.py +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/fmt.py +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/src/csm_cli/serve.py +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/test_csm.py +0 -0
- {csm_cli-0.2.0 → csm_cli-0.3.0}/test_fmt.py +0 -0
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0 (2026-11-22)
|
|
4
|
+
|
|
5
|
+
### 会话进度(B)
|
|
6
|
+
- 「做到哪了」一眼可见:列表徽标 `3/7`(TodoWrite 最新快照,双口径取最后一条)+ 📋(plan 文档关联)
|
|
7
|
+
- 数据双源:`TodoWrite` tool_use(标准格式,向前兼容)+ jsonl 行内 `attachment.planFilePath`(本机实测 9/9 plan 文档关联命中)
|
|
8
|
+
- 尾窗倒序三目标齐停(title/todos/plan),`*_scanned_full` 标记位控制全扫兜底——沿用既有渐进扫描模式
|
|
9
|
+
- 三端展示:TUI 徽标 + 预览待办清单;Web 徽标(hover 清单)+ 详情栏清单(completed 划线、in_progress 高亮);`--list --json` 字段输出
|
|
10
|
+
|
|
11
|
+
### 跨会话全文检索(C)
|
|
12
|
+
- 「那个讨论 X 的会话在哪」:TUI `?词1 词2` / Web 搜索框 `?` / `csm --full-text`——消息正文级搜索
|
|
13
|
+
- sqlite FTS5 trigram 增量索引(stdlib 零新依赖),存 `~/.claude/csm/index.db`;消息级文本 = 用户输入 / assistant 文本 / 工具名+摘要+结果摘要
|
|
14
|
+
- **会话级 AND**:多词可命中不同消息;子串匹配中文 2 字词可搜;≥3 字符自动走 trigram 索引
|
|
15
|
+
- 失效粒度 (mtime, size):TUI 30s 重扫 / Web 5s 空闲轮增量重建;实测 86 会话 / 208MB 全量首建 1.4s,查询 <60ms
|
|
16
|
+
- WAL 双连接(写/读分离):建索引期间搜索不阻塞;FTS5 缺失环境整体降级不影响其他功能
|
|
17
|
+
|
|
3
18
|
## 0.2.0 (2026-11-22)
|
|
4
19
|
|
|
5
20
|
- TUI `g` 跳转:定位会话所在终端并直达——tmux 按 tty 反查 pane(csm 在 tmux 内 `switch-client` 瞬移、在外 `execvp` 让位 `attach`)、iTerm2/Terminal.app AppleScript 聚焦、全 miss 降级提示(`fmt.fallback_location_hint`)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: csm-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Claude Code 会话管理器:一屏浏览/过滤/收藏全部会话,回车 resume;TUI + 本地 Web 界面
|
|
5
5
|
Project-URL: Homepage, https://github.com/cainli/csm
|
|
6
6
|
Project-URL: Issues, https://github.com/cainli/csm/issues
|
|
@@ -32,7 +32,7 @@ Description-Content-Type: text/markdown
|
|
|
32
32
|
|
|
33
33
|
终端里开了一堆 Claude 会话分不清哪个是哪个?`csm` 一屏列出**全局所有项目**的 Claude 会话——AI 生成的标题、首条输入、运行状态、所属项目、消息轮数、worktree 归属、Session ID——输入即过滤,回车直接 resume。
|
|
34
34
|
|
|
35
|
-
- **只读**:对 `~/.claude`
|
|
35
|
+
- **只读**:对 `~/.claude` 用户数据严格只读,绝不写入或清理(仅可写 csm 自有的 `~/.claude/csm/`:收藏与全文索引)
|
|
36
36
|
- **轻量**:Python ≥ 3.10;`prompt_toolkit`/`rich` 随包安装,开箱即用
|
|
37
37
|
- **发射后不管**:resume 用 `execvp` 接管进程,csm 不持有、不托管任何会话(Web 后台服务除外,见 `serve`)
|
|
38
38
|
|
|
@@ -52,6 +52,8 @@ Description-Content-Type: text/markdown
|
|
|
52
52
|
| **Edit/Write/MultiEdit 行级 diff**(红删绿增) | — | ✅ 完整级别 | — |
|
|
53
53
|
| **双开保护**(活会话在他终端 → 确认拦截) | ✅ | — | — |
|
|
54
54
|
| **跳转 `g`**(直达会话所在终端:tmux switch-client/attach · iTerm2/Terminal 聚焦) | ✅ | — | — |
|
|
55
|
+
| **会话进度**(TodoWrite `3/7` 快照 + 📋 plan 文档关联) | ✅ 徽标/预览清单 | ✅ 徽标/详情清单 | ✅ 字段 |
|
|
56
|
+
| **跨会话全文检索**(`?词1 词2` / `--full-text`;FTS5 trigram,中文 2 字可搜,会话级 AND) | ✅ footer 摘要 | ✅ 行内摘要 | ✅ 表格/JSON |
|
|
55
57
|
| 复制 resume 命令(终端/tmux/headless 三变体) | — | ✅ | — |
|
|
56
58
|
| SDK 子进程会话标记(`sdk-cli` → SDK) | ✅ | ✅ | ✅ |
|
|
57
59
|
| **Web 后台守护**(`csm serve start/stop/status`,launchd 开机自启) | — | ✅ | — |
|
|
@@ -92,6 +94,7 @@ csm --list # 终端表格;csm --list --json | jq '.[] | .title'
|
|
|
92
94
|
csm # 交互式 TUI(默认;stdout 非 tty 时自动降级 --list)
|
|
93
95
|
csm --list # 非交互表格
|
|
94
96
|
csm --list --json # JSON 输出,可配 jq
|
|
97
|
+
csm --full-text "登录超时" # 跨会话全文检索(首次自动建索引 ~2s,之后增量)
|
|
95
98
|
csm --list --full-scan # 表格带完整消息数(较慢 ~0.6s)
|
|
96
99
|
csm --project voicemouse # 按项目路径过滤(大小写不敏感)
|
|
97
100
|
csm --new [PATH] # 在 PATH(默认当前目录)起新会话,不进列表
|
|
@@ -182,10 +185,25 @@ resume 一个正在**其他终端**运行的会话时,csm 警告并要求确
|
|
|
182
185
|
|
|
183
186
|
## 收藏与标签
|
|
184
187
|
|
|
185
|
-
- 存储在 `~/.claude/csm/favorites.json`(csm
|
|
188
|
+
- 存储在 `~/.claude/csm/favorites.json`(csm 自有命名空间;原子写 + 跨进程锁)
|
|
186
189
|
- 星标两档:⭐ 普通收藏 / ★ 重要;永久置顶(★ 段前于 ⭐ 段,段内按活跃时间)
|
|
187
190
|
- 标签在 Web 详情栏添加;搜索 `#标签名` 精确筛(多标签 AND);TUI 与 Web 双向同步(≤30s)
|
|
188
191
|
|
|
192
|
+
## 全文检索
|
|
193
|
+
|
|
194
|
+
「那个讨论 SSE 重连的会话在哪?」——元数据过滤够不着消息正文时,用 `?` 前缀进入全文模式:
|
|
195
|
+
|
|
196
|
+
- **TUI**:直接输入 `?词1 词2`——结果按命中数降序,footer 显示首条命中摘要;与数字键分类过滤叠加
|
|
197
|
+
- **Web**:搜索框 `?词`——命中行内联摘要(accent 色),按命中数重排,退出 `?` 模式即恢复置顶序
|
|
198
|
+
- **CLI**:`csm --full-text "词1 词2"`(`--json` 同样适用,管道友好)
|
|
199
|
+
|
|
200
|
+
机制:sqlite **FTS5 trigram** 增量索引(stdlib,零新依赖):
|
|
201
|
+
|
|
202
|
+
- 索引存 `~/.claude/csm/index.db`(csm 自有可写区,与 favorites 同级);消息级文本 = 用户输入 / assistant 文本 / 工具名+摘要+结果摘要
|
|
203
|
+
- **会话级 AND**:多词可命中不同消息,会话须命中所有词;子串匹配,中文 2 字词可搜(trigram 表上 LIKE,≥3 字符自动走索引)
|
|
204
|
+
- 失效粒度文件 (mtime, size):TUI 30s 重扫 / Web 5s 空闲轮增量重建,实测 86 会话 / 208MB 全量首建 **1.4s**,查询 <60ms
|
|
205
|
+
- FTS5 不可用的环境整体降级(`?` 搜索返回空并提示),不影响其他功能
|
|
206
|
+
|
|
189
207
|
## 分类口径(诚实声明)
|
|
190
208
|
|
|
191
209
|
- **运行状态**:busy/idle/waiting 来自 Claude 活跃注册表,pid 三重判活(存活 + 进程名含 claude + 启动时间容差比对)防 pid 复用;已关闭 = jsonl 在而注册表无活记录
|
|
@@ -199,7 +217,9 @@ resume 一个正在**其他终端**运行的会话时,csm 警告并要求确
|
|
|
199
217
|
| `~/.claude/projects/*/*.jsonl` | 会话转录;文件名即 Session ID;标题取最后一条 `ai-title`;行内 `cwd`/`entrypoint` |
|
|
200
218
|
| `~/.claude/sessions/*.json` | 运行中会话注册表 → 状态 + tty 关联 |
|
|
201
219
|
| `~/.claude/history.jsonl` | 无标题会话的首条输入回退 |
|
|
202
|
-
| `~/.claude/csm/favorites.json` | **csm
|
|
220
|
+
| `~/.claude/csm/favorites.json` | **csm 自有**:收藏与标签(可写) |
|
|
221
|
+
| `~/.claude/csm/index.db` | **csm 自有**:全文检索 FTS5 索引(可写,自动维护) |
|
|
222
|
+
| `~/.claude/plans/*.md` | plan mode 文档;经 jsonl 行内 `attachment.planFilePath` 关联(只读) |
|
|
203
223
|
|
|
204
224
|
进程信息:单次 `ps -axo pid,ppid,tty,lstart,command` 快照三用(会话 tty / 进程名校验防 pid 回绕 / PPID 链上溯识别本终端)。
|
|
205
225
|
支持 `CLAUDE_CONFIG_DIR` 重定向配置目录(测试注入用)。
|
|
@@ -216,6 +236,6 @@ python3 -m pytest # 全部单测:离线假数据 + 真 git worktree 集成
|
|
|
216
236
|
|
|
217
237
|
- 包布局 `src/csm_cli/`:`cli.py` 入口/CLI/resume/双开保护 · `scanner.py` 数据层+消息解析(唯一文件 I/O)·
|
|
218
238
|
`ui.py` TUI · `web.py` Web 服务端 · `web.html` Web 前端(单文件,无构建,importlib.resources 读取)·
|
|
219
|
-
`serve.py` 守护进程 · `fmt.py`
|
|
239
|
+
`serve.py` 守护进程 · `fmt.py` 纯函数格式化 · `ftsearch.py` 全文检索(FTS5 索引);仓库根 `csm.py` 为兼容 shim
|
|
220
240
|
- `fmt.py` 中 `rel_time()` / `fuzzy_score()` 为故意留空的降级实现(学习场景),实装后 `test_fmt.py` 的 `skipif` 自动生效
|
|
221
241
|
- `web.html` 顶部 CSS 变量可整体换肤;打包见 `pyproject.toml`(hatchling,`csm-cli`)
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
终端里开了一堆 Claude 会话分不清哪个是哪个?`csm` 一屏列出**全局所有项目**的 Claude 会话——AI 生成的标题、首条输入、运行状态、所属项目、消息轮数、worktree 归属、Session ID——输入即过滤,回车直接 resume。
|
|
4
4
|
|
|
5
|
-
- **只读**:对 `~/.claude`
|
|
5
|
+
- **只读**:对 `~/.claude` 用户数据严格只读,绝不写入或清理(仅可写 csm 自有的 `~/.claude/csm/`:收藏与全文索引)
|
|
6
6
|
- **轻量**:Python ≥ 3.10;`prompt_toolkit`/`rich` 随包安装,开箱即用
|
|
7
7
|
- **发射后不管**:resume 用 `execvp` 接管进程,csm 不持有、不托管任何会话(Web 后台服务除外,见 `serve`)
|
|
8
8
|
|
|
@@ -22,6 +22,8 @@
|
|
|
22
22
|
| **Edit/Write/MultiEdit 行级 diff**(红删绿增) | — | ✅ 完整级别 | — |
|
|
23
23
|
| **双开保护**(活会话在他终端 → 确认拦截) | ✅ | — | — |
|
|
24
24
|
| **跳转 `g`**(直达会话所在终端:tmux switch-client/attach · iTerm2/Terminal 聚焦) | ✅ | — | — |
|
|
25
|
+
| **会话进度**(TodoWrite `3/7` 快照 + 📋 plan 文档关联) | ✅ 徽标/预览清单 | ✅ 徽标/详情清单 | ✅ 字段 |
|
|
26
|
+
| **跨会话全文检索**(`?词1 词2` / `--full-text`;FTS5 trigram,中文 2 字可搜,会话级 AND) | ✅ footer 摘要 | ✅ 行内摘要 | ✅ 表格/JSON |
|
|
25
27
|
| 复制 resume 命令(终端/tmux/headless 三变体) | — | ✅ | — |
|
|
26
28
|
| SDK 子进程会话标记(`sdk-cli` → SDK) | ✅ | ✅ | ✅ |
|
|
27
29
|
| **Web 后台守护**(`csm serve start/stop/status`,launchd 开机自启) | — | ✅ | — |
|
|
@@ -62,6 +64,7 @@ csm --list # 终端表格;csm --list --json | jq '.[] | .title'
|
|
|
62
64
|
csm # 交互式 TUI(默认;stdout 非 tty 时自动降级 --list)
|
|
63
65
|
csm --list # 非交互表格
|
|
64
66
|
csm --list --json # JSON 输出,可配 jq
|
|
67
|
+
csm --full-text "登录超时" # 跨会话全文检索(首次自动建索引 ~2s,之后增量)
|
|
65
68
|
csm --list --full-scan # 表格带完整消息数(较慢 ~0.6s)
|
|
66
69
|
csm --project voicemouse # 按项目路径过滤(大小写不敏感)
|
|
67
70
|
csm --new [PATH] # 在 PATH(默认当前目录)起新会话,不进列表
|
|
@@ -152,10 +155,25 @@ resume 一个正在**其他终端**运行的会话时,csm 警告并要求确
|
|
|
152
155
|
|
|
153
156
|
## 收藏与标签
|
|
154
157
|
|
|
155
|
-
- 存储在 `~/.claude/csm/favorites.json`(csm
|
|
158
|
+
- 存储在 `~/.claude/csm/favorites.json`(csm 自有命名空间;原子写 + 跨进程锁)
|
|
156
159
|
- 星标两档:⭐ 普通收藏 / ★ 重要;永久置顶(★ 段前于 ⭐ 段,段内按活跃时间)
|
|
157
160
|
- 标签在 Web 详情栏添加;搜索 `#标签名` 精确筛(多标签 AND);TUI 与 Web 双向同步(≤30s)
|
|
158
161
|
|
|
162
|
+
## 全文检索
|
|
163
|
+
|
|
164
|
+
「那个讨论 SSE 重连的会话在哪?」——元数据过滤够不着消息正文时,用 `?` 前缀进入全文模式:
|
|
165
|
+
|
|
166
|
+
- **TUI**:直接输入 `?词1 词2`——结果按命中数降序,footer 显示首条命中摘要;与数字键分类过滤叠加
|
|
167
|
+
- **Web**:搜索框 `?词`——命中行内联摘要(accent 色),按命中数重排,退出 `?` 模式即恢复置顶序
|
|
168
|
+
- **CLI**:`csm --full-text "词1 词2"`(`--json` 同样适用,管道友好)
|
|
169
|
+
|
|
170
|
+
机制:sqlite **FTS5 trigram** 增量索引(stdlib,零新依赖):
|
|
171
|
+
|
|
172
|
+
- 索引存 `~/.claude/csm/index.db`(csm 自有可写区,与 favorites 同级);消息级文本 = 用户输入 / assistant 文本 / 工具名+摘要+结果摘要
|
|
173
|
+
- **会话级 AND**:多词可命中不同消息,会话须命中所有词;子串匹配,中文 2 字词可搜(trigram 表上 LIKE,≥3 字符自动走索引)
|
|
174
|
+
- 失效粒度文件 (mtime, size):TUI 30s 重扫 / Web 5s 空闲轮增量重建,实测 86 会话 / 208MB 全量首建 **1.4s**,查询 <60ms
|
|
175
|
+
- FTS5 不可用的环境整体降级(`?` 搜索返回空并提示),不影响其他功能
|
|
176
|
+
|
|
159
177
|
## 分类口径(诚实声明)
|
|
160
178
|
|
|
161
179
|
- **运行状态**:busy/idle/waiting 来自 Claude 活跃注册表,pid 三重判活(存活 + 进程名含 claude + 启动时间容差比对)防 pid 复用;已关闭 = jsonl 在而注册表无活记录
|
|
@@ -169,7 +187,9 @@ resume 一个正在**其他终端**运行的会话时,csm 警告并要求确
|
|
|
169
187
|
| `~/.claude/projects/*/*.jsonl` | 会话转录;文件名即 Session ID;标题取最后一条 `ai-title`;行内 `cwd`/`entrypoint` |
|
|
170
188
|
| `~/.claude/sessions/*.json` | 运行中会话注册表 → 状态 + tty 关联 |
|
|
171
189
|
| `~/.claude/history.jsonl` | 无标题会话的首条输入回退 |
|
|
172
|
-
| `~/.claude/csm/favorites.json` | **csm
|
|
190
|
+
| `~/.claude/csm/favorites.json` | **csm 自有**:收藏与标签(可写) |
|
|
191
|
+
| `~/.claude/csm/index.db` | **csm 自有**:全文检索 FTS5 索引(可写,自动维护) |
|
|
192
|
+
| `~/.claude/plans/*.md` | plan mode 文档;经 jsonl 行内 `attachment.planFilePath` 关联(只读) |
|
|
173
193
|
|
|
174
194
|
进程信息:单次 `ps -axo pid,ppid,tty,lstart,command` 快照三用(会话 tty / 进程名校验防 pid 回绕 / PPID 链上溯识别本终端)。
|
|
175
195
|
支持 `CLAUDE_CONFIG_DIR` 重定向配置目录(测试注入用)。
|
|
@@ -186,6 +206,6 @@ python3 -m pytest # 全部单测:离线假数据 + 真 git worktree 集成
|
|
|
186
206
|
|
|
187
207
|
- 包布局 `src/csm_cli/`:`cli.py` 入口/CLI/resume/双开保护 · `scanner.py` 数据层+消息解析(唯一文件 I/O)·
|
|
188
208
|
`ui.py` TUI · `web.py` Web 服务端 · `web.html` Web 前端(单文件,无构建,importlib.resources 读取)·
|
|
189
|
-
`serve.py` 守护进程 · `fmt.py`
|
|
209
|
+
`serve.py` 守护进程 · `fmt.py` 纯函数格式化 · `ftsearch.py` 全文检索(FTS5 索引);仓库根 `csm.py` 为兼容 shim
|
|
190
210
|
- `fmt.py` 中 `rel_time()` / `fuzzy_score()` 为故意留空的降级实现(学习场景),实装后 `test_fmt.py` 的 `skipif` 自动生效
|
|
191
211
|
- `web.html` 顶部 CSS 变量可整体换肤;打包见 `pyproject.toml`(hatchling,`csm-cli`)
|
|
@@ -78,6 +78,15 @@ def cmd_list(args, entries: list[scanner.SessionEntry]) -> int:
|
|
|
78
78
|
"wt_repo": e.wt_repo,
|
|
79
79
|
"wt_branch": e.wt_branch,
|
|
80
80
|
"wt_ahead": e.wt_ahead,
|
|
81
|
+
"todos": (
|
|
82
|
+
[{"content": c, "status": st} for c, st in e.todos]
|
|
83
|
+
if e.todos is not None else None
|
|
84
|
+
),
|
|
85
|
+
"todos_done": (
|
|
86
|
+
sum(1 for _, st in e.todos if st == "completed")
|
|
87
|
+
if e.todos is not None else None
|
|
88
|
+
),
|
|
89
|
+
"plan_file": e.plan_file,
|
|
81
90
|
"size": e.size,
|
|
82
91
|
}
|
|
83
92
|
for e in entries
|
|
@@ -140,6 +149,65 @@ def cmd_list(args, entries: list[scanner.SessionEntry]) -> int:
|
|
|
140
149
|
return 0
|
|
141
150
|
|
|
142
151
|
|
|
152
|
+
def cmd_full_text(args, entries: list[scanner.SessionEntry]) -> int:
|
|
153
|
+
"""跨会话全文检索:同步增量索引 + 表格/JSON 输出(管道友好)。"""
|
|
154
|
+
from csm_cli import fmt as csm_fmt # 惰性:fmt 依赖 prompt_toolkit
|
|
155
|
+
from csm_cli import ftsearch # 惰性:sqlite 仅全文路径需要
|
|
156
|
+
|
|
157
|
+
for e in entries:
|
|
158
|
+
if not e.light_scanned:
|
|
159
|
+
scanner.light_scan(e)
|
|
160
|
+
ftsearch.ensure_index(entries)
|
|
161
|
+
hits = ftsearch.search(args.full_text)
|
|
162
|
+
by_sid = {e.session_id: e for e in entries}
|
|
163
|
+
rows = [(by_sid[h.session_id], h) for h in hits if h.session_id in by_sid]
|
|
164
|
+
|
|
165
|
+
if not ftsearch.available():
|
|
166
|
+
print(f"全文检索不可用({ftsearch.unavailable_reason()})", file=sys.stderr)
|
|
167
|
+
return 2
|
|
168
|
+
if args.json:
|
|
169
|
+
payload = [
|
|
170
|
+
{
|
|
171
|
+
"session_id": e.session_id,
|
|
172
|
+
"title": e.title,
|
|
173
|
+
"project_path": e.project_path,
|
|
174
|
+
"hits": h.count,
|
|
175
|
+
"snippets": [{"kind": k, "text": t} for k, t in h.snippets],
|
|
176
|
+
}
|
|
177
|
+
for e, h in rows
|
|
178
|
+
]
|
|
179
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
180
|
+
return 0
|
|
181
|
+
|
|
182
|
+
from rich.console import Console
|
|
183
|
+
from rich.markup import escape
|
|
184
|
+
from rich.table import Table
|
|
185
|
+
|
|
186
|
+
console = Console(no_color=args.no_color)
|
|
187
|
+
table = Table(box=None, show_header=True, header_style="bold dim", pad_edge=False)
|
|
188
|
+
table.add_column("命中", justify="right", no_wrap=True)
|
|
189
|
+
table.add_column("标题 / 首条输入", no_wrap=True)
|
|
190
|
+
table.add_column("项目", no_wrap=True)
|
|
191
|
+
table.add_column("摘要(首条命中)", no_wrap=True)
|
|
192
|
+
table.add_column("Session ID", no_wrap=True)
|
|
193
|
+
width = console.width
|
|
194
|
+
rest = max(width - 42, 30)
|
|
195
|
+
title_w = int(rest * 0.35)
|
|
196
|
+
for e, h in rows:
|
|
197
|
+
title = e.title or e.first_input or "(无用户输入)"
|
|
198
|
+
snippet = h.snippets[0][1] if h.snippets else ""
|
|
199
|
+
table.add_row(
|
|
200
|
+
str(h.count),
|
|
201
|
+
f"[dim]{escape(csm_fmt.truncate_cjk(title, title_w))}[/dim]"
|
|
202
|
+
if not e.title else escape(csm_fmt.truncate_cjk(title, title_w)),
|
|
203
|
+
escape(csm_fmt.shorten_path(e.project_path or "?", 16)),
|
|
204
|
+
escape(csm_fmt.truncate_cjk(snippet, rest - title_w - 20)),
|
|
205
|
+
e.session_id,
|
|
206
|
+
)
|
|
207
|
+
console.print(table)
|
|
208
|
+
return 0
|
|
209
|
+
|
|
210
|
+
|
|
143
211
|
def _resume_conflict(entry: scanner.SessionEntry,
|
|
144
212
|
registry: dict[str, scanner.RunningInfo],
|
|
145
213
|
current_tty: str | None) -> str | None:
|
|
@@ -255,6 +323,8 @@ def build_argparser() -> argparse.ArgumentParser:
|
|
|
255
323
|
p.add_argument("--head-bytes", type=int, default=scanner.DEFAULT_HEAD_BYTES, help=argparse.SUPPRESS)
|
|
256
324
|
p.add_argument("--tail-bytes", type=int, default=scanner.DEFAULT_TAIL_BYTES, help=argparse.SUPPRESS)
|
|
257
325
|
p.add_argument("--no-cd", action="store_true", help="resume 时不切换到原项目目录")
|
|
326
|
+
p.add_argument("--full-text", metavar="QUERY", dest="full_text",
|
|
327
|
+
help="跨会话全文检索(空格分词 AND 子串匹配;首次自动建索引 ~2s)")
|
|
258
328
|
p.add_argument("--no-color", action="store_true", help="禁用颜色")
|
|
259
329
|
p.add_argument("--version", action="version", version=f"csm {VERSION}")
|
|
260
330
|
|
|
@@ -320,6 +390,9 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
320
390
|
|
|
321
391
|
return csm_web.serve(args, entries)
|
|
322
392
|
|
|
393
|
+
if args.full_text is not None:
|
|
394
|
+
return cmd_full_text(args, entries)
|
|
395
|
+
|
|
323
396
|
if args.list or args.json or not sys.stdout.isatty():
|
|
324
397
|
# 非 TTY(管道)自动降级为 --list,便于 csm | grep
|
|
325
398
|
return cmd_list(args, entries)
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""csm_ftsearch — 跨会话全文检索:sqlite FTS5 (trigram) 增量索引,csm 自有存储。
|
|
2
|
+
|
|
3
|
+
索引建在 ~/.claude/csm/index.db(与 favorites.json 同命名空间,csm 自有可写区)。
|
|
4
|
+
索引内容为消息级文本:真实用户输入 / assistant 文本块 / 工具名+摘要+结果摘要
|
|
5
|
+
(复用 scanner.read_session_messages 的解析与 LRU 缓存,预览与索引共享一遍解析)。
|
|
6
|
+
|
|
7
|
+
失效粒度:文件 (mtime, size)。ensure_index 对比 files 表,变化的删旧插新,
|
|
8
|
+
消失的清理——30s 重扫场景下增量代价接近零。
|
|
9
|
+
|
|
10
|
+
查询:空格分词 AND、子串匹配(LIKE;trigram 表上 ≥3 字符自动走索引,短词
|
|
11
|
+
退化全表扫——保证中文 2 字词正确命中)。sqlite LIKE 对 ASCII 天然大小写不敏感。
|
|
12
|
+
|
|
13
|
+
FTS5/trigram 不可用或目录不可写的环境整体降级:ensure_index 返回 0、
|
|
14
|
+
search 返回 []、available() 为 False,调用方按「索引不可用」提示。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import sqlite3
|
|
20
|
+
import threading
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import TYPE_CHECKING
|
|
24
|
+
|
|
25
|
+
from csm_cli import scanner
|
|
26
|
+
|
|
27
|
+
if TYPE_CHECKING:
|
|
28
|
+
from csm_cli.scanner import SessionEntry
|
|
29
|
+
|
|
30
|
+
_SNIPPET_CAP = 120 # 命中摘要截断
|
|
31
|
+
_MAX_SESSIONS = 50 # search 返回的会话上限(按命中数取前 N)
|
|
32
|
+
|
|
33
|
+
_LOCK = threading.Lock() # 串行化写(后台建索引)
|
|
34
|
+
_RLOCK = threading.Lock() # 串行化读连接(search/stats 跨线程)
|
|
35
|
+
_CONN: sqlite3.Connection | None = None # 写连接(建索引)
|
|
36
|
+
_RCONN: sqlite3.Connection | None = None # 读连接(WAL 下与写并行,建索引期间可搜)
|
|
37
|
+
_INIT_ERROR: str | None = None # 一次性探测失败原因(不可用时提示用)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Hit:
|
|
42
|
+
"""一个会话的全文命中。"""
|
|
43
|
+
|
|
44
|
+
session_id: str
|
|
45
|
+
count: int # 该会话命中消息条数
|
|
46
|
+
snippets: list[tuple[str, str]] # [(kind, 摘要)],至多 per_session 条
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def index_path() -> Path:
|
|
50
|
+
"""索引文件路径(CONFIG_ROOT 可被测试 monkeypatch,运行时求值)。"""
|
|
51
|
+
return scanner.CONFIG_ROOT / "csm" / "index.db"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def available() -> bool:
|
|
55
|
+
"""FTS5/trigram 可用且连接可建立(惰性探测,失败原因见 unavailable_reason)。"""
|
|
56
|
+
return _connect() is not None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def unavailable_reason() -> str | None:
|
|
60
|
+
_connect()
|
|
61
|
+
return _INIT_ERROR
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _connect() -> sqlite3.Connection | None:
|
|
65
|
+
"""惰性建写连接 + schema;失败记入 _INIT_ERROR 并返回 None(后续调用短路)。"""
|
|
66
|
+
global _CONN, _INIT_ERROR
|
|
67
|
+
if _CONN is not None or _INIT_ERROR is not None:
|
|
68
|
+
return _CONN
|
|
69
|
+
try:
|
|
70
|
+
path = index_path()
|
|
71
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
conn = sqlite3.connect(str(path), check_same_thread=False, timeout=10)
|
|
73
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
74
|
+
conn.execute("PRAGMA synchronous=NORMAL")
|
|
75
|
+
conn.execute(
|
|
76
|
+
"CREATE VIRTUAL TABLE IF NOT EXISTS texts USING fts5("
|
|
77
|
+
"sid UNINDEXED, kind UNINDEXED, ord UNINDEXED, body, tokenize='trigram')")
|
|
78
|
+
conn.execute(
|
|
79
|
+
"CREATE TABLE IF NOT EXISTS files("
|
|
80
|
+
"sid TEXT PRIMARY KEY, mtime REAL, size INTEGER, msgs INTEGER)")
|
|
81
|
+
_CONN = conn
|
|
82
|
+
except (sqlite3.Error, OSError) as exc:
|
|
83
|
+
_INIT_ERROR = str(exc)
|
|
84
|
+
return None
|
|
85
|
+
return _CONN
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _read_conn() -> sqlite3.Connection | None:
|
|
89
|
+
"""读连接(独立于写连接;WAL 下建索引期间查询不阻塞,读已提交部分)。"""
|
|
90
|
+
global _RCONN
|
|
91
|
+
if _RCONN is not None or _connect() is None:
|
|
92
|
+
return _RCONN
|
|
93
|
+
try:
|
|
94
|
+
_RCONN = sqlite3.connect(str(index_path()), check_same_thread=False, timeout=10)
|
|
95
|
+
except sqlite3.Error:
|
|
96
|
+
return None
|
|
97
|
+
return _RCONN
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _message_text(m: "scanner.Message") -> str | None:
|
|
101
|
+
"""Message → 可索引文本(input/text 用全文;tool 用 名+摘要+结果摘要)。"""
|
|
102
|
+
if m.kind == "tool_use":
|
|
103
|
+
parts = [m.tool_name or "", m.tool_brief or ""]
|
|
104
|
+
if m.tool_result_brief:
|
|
105
|
+
parts.append(m.tool_result_brief)
|
|
106
|
+
text = " · ".join(p for p in parts if p)
|
|
107
|
+
return text or None
|
|
108
|
+
text = (m.text or "").strip()
|
|
109
|
+
return text or None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def ensure_index(entries: list["SessionEntry"]) -> int:
|
|
113
|
+
"""增量重建索引:对比 (mtime, size),变化文件删旧插新,消失文件清理。
|
|
114
|
+
|
|
115
|
+
返回本次重建的文件数(0 = 全部新鲜)。异常吞掉返回 0(索引是尽力而为)。
|
|
116
|
+
"""
|
|
117
|
+
with _LOCK:
|
|
118
|
+
conn = _connect()
|
|
119
|
+
if conn is None:
|
|
120
|
+
return 0
|
|
121
|
+
try:
|
|
122
|
+
rows = conn.execute("SELECT sid, mtime, size FROM files").fetchall()
|
|
123
|
+
except sqlite3.Error:
|
|
124
|
+
return 0
|
|
125
|
+
known = {sid: (mtime, size) for sid, mtime, size in rows}
|
|
126
|
+
rebuilt = 0
|
|
127
|
+
seen: set[str] = set()
|
|
128
|
+
for e in entries:
|
|
129
|
+
seen.add(e.session_id)
|
|
130
|
+
if known.get(e.session_id) == (e.mtime, e.size):
|
|
131
|
+
continue # 新鲜
|
|
132
|
+
if _reindex(conn, e):
|
|
133
|
+
rebuilt += 1
|
|
134
|
+
for stale in known.keys() - seen:
|
|
135
|
+
try:
|
|
136
|
+
conn.execute("DELETE FROM texts WHERE sid = ?", (stale,))
|
|
137
|
+
conn.execute("DELETE FROM files WHERE sid = ?", (stale,))
|
|
138
|
+
conn.commit()
|
|
139
|
+
except sqlite3.Error:
|
|
140
|
+
break
|
|
141
|
+
return rebuilt
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _reindex(conn: sqlite3.Connection, entry: "SessionEntry") -> bool:
|
|
145
|
+
"""单会话重建(调用方持锁)。解析失败(返回 None)也记入 files,防反复重试。"""
|
|
146
|
+
try:
|
|
147
|
+
msgs = scanner.read_session_messages(entry.file_path)
|
|
148
|
+
except Exception:
|
|
149
|
+
msgs = None
|
|
150
|
+
try:
|
|
151
|
+
conn.execute("BEGIN")
|
|
152
|
+
conn.execute("DELETE FROM texts WHERE sid = ?", (entry.session_id,))
|
|
153
|
+
conn.execute("DELETE FROM files WHERE sid = ?", (entry.session_id,))
|
|
154
|
+
if msgs:
|
|
155
|
+
for m in msgs:
|
|
156
|
+
text = _message_text(m)
|
|
157
|
+
if text:
|
|
158
|
+
conn.execute(
|
|
159
|
+
"INSERT INTO texts(sid, kind, ord, body) VALUES (?, ?, ?, ?)",
|
|
160
|
+
(entry.session_id, m.kind, m.order, text))
|
|
161
|
+
conn.execute(
|
|
162
|
+
"INSERT INTO files(sid, mtime, size, msgs) VALUES (?, ?, ?, ?)",
|
|
163
|
+
(entry.session_id, entry.mtime, entry.size, len(msgs) if msgs else 0))
|
|
164
|
+
conn.commit()
|
|
165
|
+
except sqlite3.Error:
|
|
166
|
+
conn.rollback()
|
|
167
|
+
return False
|
|
168
|
+
return True
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def search(query: str, per_session: int = 3) -> list[Hit]:
|
|
172
|
+
"""全文检索:空格分词「会话级 AND」子串匹配,按命中数降序。
|
|
173
|
+
|
|
174
|
+
会话级 AND:每个词可命中不同消息,会话须出现在所有词的命中集合中
|
|
175
|
+
(与「这个会话既提到 A 又提到 B」的直觉一致)。count 为任一词的命中
|
|
176
|
+
消息数(相关度近似)。索引未建/不可用/空查询 → [](调用方区分提示)。
|
|
177
|
+
"""
|
|
178
|
+
terms = [t for t in query.split() if t]
|
|
179
|
+
if not terms:
|
|
180
|
+
return []
|
|
181
|
+
with _RLOCK:
|
|
182
|
+
conn = _read_conn()
|
|
183
|
+
if conn is None:
|
|
184
|
+
return []
|
|
185
|
+
like_args = [f"%{t}%" for t in terms]
|
|
186
|
+
try:
|
|
187
|
+
sets: list[set[str]] = []
|
|
188
|
+
for arg in like_args:
|
|
189
|
+
rows = conn.execute(
|
|
190
|
+
"SELECT DISTINCT sid FROM texts WHERE body LIKE ?", (arg,)).fetchall()
|
|
191
|
+
sets.append({r[0] for r in rows})
|
|
192
|
+
except sqlite3.Error:
|
|
193
|
+
return []
|
|
194
|
+
common = set.intersection(*sets)
|
|
195
|
+
if not common:
|
|
196
|
+
return []
|
|
197
|
+
where_or = " OR ".join("body LIKE ?" for _ in terms)
|
|
198
|
+
ph = ",".join("?" for _ in common)
|
|
199
|
+
try:
|
|
200
|
+
grouped = conn.execute(
|
|
201
|
+
f"SELECT sid, count(*) c FROM texts WHERE sid IN ({ph}) AND ({where_or}) "
|
|
202
|
+
f"GROUP BY sid ORDER BY c DESC LIMIT {_MAX_SESSIONS}",
|
|
203
|
+
[*common, *like_args]).fetchall()
|
|
204
|
+
except sqlite3.Error:
|
|
205
|
+
return []
|
|
206
|
+
hits: list[Hit] = []
|
|
207
|
+
for sid, count in grouped:
|
|
208
|
+
snippets: list[tuple[str, str]] = []
|
|
209
|
+
try:
|
|
210
|
+
for kind, body in conn.execute(
|
|
211
|
+
f"SELECT kind, body FROM texts WHERE sid = ? AND ({where_or}) "
|
|
212
|
+
"ORDER BY ord LIMIT ?",
|
|
213
|
+
[sid, *like_args, per_session]):
|
|
214
|
+
snippets.append((kind, body[:_SNIPPET_CAP]))
|
|
215
|
+
except sqlite3.Error:
|
|
216
|
+
continue
|
|
217
|
+
hits.append(Hit(sid, count, snippets))
|
|
218
|
+
return hits
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def stats() -> tuple[int, int]:
|
|
222
|
+
"""(已索引会话数, 消息条数)——索引状态展示用;不可用 → (0, 0)。"""
|
|
223
|
+
with _RLOCK:
|
|
224
|
+
conn = _read_conn()
|
|
225
|
+
if conn is None:
|
|
226
|
+
return (0, 0)
|
|
227
|
+
try:
|
|
228
|
+
n_files = conn.execute("SELECT count(*) FROM files").fetchone()[0]
|
|
229
|
+
n_msgs = conn.execute("SELECT count(*) FROM texts").fetchone()[0]
|
|
230
|
+
return (n_files, n_msgs)
|
|
231
|
+
except sqlite3.Error:
|
|
232
|
+
return (0, 0)
|
|
@@ -83,6 +83,11 @@ class SessionEntry:
|
|
|
83
83
|
wt_ahead: int | None = None # 未合并到 base 的提交数(subprocess,后台补)
|
|
84
84
|
wt_scanned: bool = False # 纯文件检测完成(含「确认非 worktree」)
|
|
85
85
|
wt_deep_scanned: bool = False # ahead 已尝试(含失败,防反复起子进程)
|
|
86
|
+
# 会话进度(五期):TodoWrite 最新快照 + plan 文档关联
|
|
87
|
+
todos: tuple[tuple[str, str], ...] | None = None # (content, status),最后一条 TodoWrite
|
|
88
|
+
todos_scanned_full: bool = False # False = 尾窗没找到,全扫需兜底
|
|
89
|
+
plan_file: str | None = None # attachment.planFilePath(最后引用的 plan 文档)
|
|
90
|
+
plan_scanned_full: bool = False
|
|
86
91
|
# 全扫补全
|
|
87
92
|
msg_count: int | None = None # 真实用户输入次数(human turns)
|
|
88
93
|
assistant_count: int | None = None
|
|
@@ -189,6 +194,8 @@ def light_scan(
|
|
|
189
194
|
entry.light_scanned = True
|
|
190
195
|
entry.title_scanned_full = True # 空文件确实没有,无需兜底
|
|
191
196
|
entry.input_scanned_full = True
|
|
197
|
+
entry.todos_scanned_full = True
|
|
198
|
+
entry.plan_scanned_full = True
|
|
192
199
|
return
|
|
193
200
|
|
|
194
201
|
try:
|
|
@@ -208,6 +215,40 @@ def light_scan(
|
|
|
208
215
|
entry.light_scanned = True
|
|
209
216
|
|
|
210
217
|
|
|
218
|
+
def _extract_todos(content: Any) -> tuple[tuple[str, str], ...] | None:
|
|
219
|
+
"""assistant 行 content 块 → TodoWrite 的 todos((content, status) 对)。
|
|
220
|
+
|
|
221
|
+
本行无 TodoWrite → None;有但空/坏 → ()。status 非 str 按 pending。
|
|
222
|
+
「最后一条 TodoWrite」由调用方(倒序首见/顺次覆盖)保证。
|
|
223
|
+
"""
|
|
224
|
+
if not isinstance(content, list):
|
|
225
|
+
return None
|
|
226
|
+
for block in content:
|
|
227
|
+
if not (isinstance(block, dict) and block.get("type") == "tool_use"
|
|
228
|
+
and block.get("name") == "TodoWrite"):
|
|
229
|
+
continue
|
|
230
|
+
todos = (block.get("input") or {}).get("todos")
|
|
231
|
+
if not isinstance(todos, list):
|
|
232
|
+
return ()
|
|
233
|
+
pairs: list[tuple[str, str]] = []
|
|
234
|
+
for t in todos:
|
|
235
|
+
if isinstance(t, dict) and isinstance(t.get("content"), str):
|
|
236
|
+
status = t.get("status")
|
|
237
|
+
pairs.append((t["content"], status if isinstance(status, str) else "pending"))
|
|
238
|
+
return tuple(pairs)
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _extract_plan_path(obj: dict) -> str | None:
|
|
243
|
+
"""attachment.planFilePath(plan mode 文档),非字符串/缺失 → None。"""
|
|
244
|
+
att = obj.get("attachment")
|
|
245
|
+
if isinstance(att, dict):
|
|
246
|
+
path = att.get("planFilePath")
|
|
247
|
+
if isinstance(path, str) and path:
|
|
248
|
+
return path
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
|
|
211
252
|
def _scan_head(entry: SessionEntry, blob: bytes, truncated: bool) -> None:
|
|
212
253
|
"""头部窗口:第一条 cwd + 第一条真实用户输入(正序,命中即停)。"""
|
|
213
254
|
lines = blob.decode("utf-8", errors="replace").split("\n")
|
|
@@ -241,7 +282,10 @@ def _scan_head(entry: SessionEntry, blob: bytes, truncated: bool) -> None:
|
|
|
241
282
|
|
|
242
283
|
|
|
243
284
|
def _scan_tail(entry: SessionEntry, blob: bytes, truncated: bool) -> None:
|
|
244
|
-
"""
|
|
285
|
+
"""尾部窗口倒序:最后一条 ai-title / TodoWrite / planFilePath / cwd。
|
|
286
|
+
|
|
287
|
+
倒序首见即全文件最后一条;三目标齐备即停(实测标题窗口 100% 覆盖)。
|
|
288
|
+
"""
|
|
245
289
|
text = blob.decode("utf-8", errors="replace")
|
|
246
290
|
lines = text.split("\n")
|
|
247
291
|
if truncated and lines:
|
|
@@ -260,14 +304,28 @@ def _scan_tail(entry: SessionEntry, blob: bytes, truncated: bool) -> None:
|
|
|
260
304
|
cwd = obj.get("cwd")
|
|
261
305
|
if isinstance(cwd, str) and cwd:
|
|
262
306
|
entry.last_cwd = cwd # 倒序首见 = 全文件最后一条 cwd
|
|
263
|
-
if obj.get("type") == "ai-title":
|
|
307
|
+
if entry.title is None and obj.get("type") == "ai-title":
|
|
264
308
|
title = obj.get("aiTitle")
|
|
265
309
|
if isinstance(title, str) and title.strip():
|
|
266
310
|
entry.title = title.strip()
|
|
267
311
|
entry.title_scanned_full = True
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
312
|
+
if entry.todos is None:
|
|
313
|
+
todos = _extract_todos((obj.get("message") or {}).get("content"))
|
|
314
|
+
if todos is not None:
|
|
315
|
+
entry.todos = todos
|
|
316
|
+
entry.todos_scanned_full = True
|
|
317
|
+
if entry.plan_file is None:
|
|
318
|
+
plan = _extract_plan_path(obj)
|
|
319
|
+
if plan is not None:
|
|
320
|
+
entry.plan_file = plan
|
|
321
|
+
entry.plan_scanned_full = True
|
|
322
|
+
if (entry.title is not None and entry.todos is not None
|
|
323
|
+
and entry.plan_file is not None):
|
|
324
|
+
return # 三目标齐备
|
|
325
|
+
# 窗口内未齐:若没扫过完整文件,未得项留给全扫兜底
|
|
326
|
+
entry.title_scanned_full = entry.title is not None or not truncated
|
|
327
|
+
entry.todos_scanned_full = entry.todos is not None or not truncated
|
|
328
|
+
entry.plan_scanned_full = entry.plan_file is not None or not truncated
|
|
271
329
|
|
|
272
330
|
|
|
273
331
|
# ---------------------------------------------------------------------------
|
|
@@ -308,6 +366,12 @@ def full_scan(entry: SessionEntry) -> None:
|
|
|
308
366
|
entry.first_input = _clean_input(obj["message"]["content"])
|
|
309
367
|
if obj.get("type") == "assistant":
|
|
310
368
|
assistant_count += 1
|
|
369
|
+
todos = _extract_todos((obj.get("message") or {}).get("content"))
|
|
370
|
+
if todos is not None:
|
|
371
|
+
entry.todos = todos # 顺次覆盖 → 结束时即最后一条
|
|
372
|
+
plan = _extract_plan_path(obj)
|
|
373
|
+
if plan is not None:
|
|
374
|
+
entry.plan_file = plan
|
|
311
375
|
if obj.get("type") == "ai-title":
|
|
312
376
|
title = obj.get("aiTitle")
|
|
313
377
|
if isinstance(title, str) and title.strip():
|
|
@@ -322,6 +386,8 @@ def full_scan(entry: SessionEntry) -> None:
|
|
|
322
386
|
entry.last_timestamp = last_ts
|
|
323
387
|
entry.title_scanned_full = True
|
|
324
388
|
entry.input_scanned_full = True
|
|
389
|
+
entry.todos_scanned_full = True
|
|
390
|
+
entry.plan_scanned_full = True
|
|
325
391
|
entry.full_scanned = True
|
|
326
392
|
|
|
327
393
|
|
|
@@ -23,6 +23,7 @@ from prompt_toolkit.layout import BufferControl, ConditionalContainer, Formatted
|
|
|
23
23
|
from prompt_toolkit.styles import Style
|
|
24
24
|
|
|
25
25
|
from csm_cli import fmt as csm_fmt
|
|
26
|
+
from csm_cli import ftsearch
|
|
26
27
|
from csm_cli import scanner
|
|
27
28
|
from csm_cli.scanner import SessionEntry
|
|
28
29
|
|
|
@@ -104,6 +105,7 @@ class SessionPicker:
|
|
|
104
105
|
self.query = Buffer(on_text_changed=lambda _: self._refilter())
|
|
105
106
|
self._filtered_idx: list[int] = list(range(len(entries)))
|
|
106
107
|
self._match_scores: dict[int, float] = {}
|
|
108
|
+
self._ft_hits: dict[str, ftsearch.Hit] = {} # 全文模式:sid → 命中(footer 摘要用)
|
|
107
109
|
|
|
108
110
|
# ---- 分类过滤器(数字键 1-6)----
|
|
109
111
|
self.filter_name = "all"
|
|
@@ -183,8 +185,17 @@ class SessionPicker:
|
|
|
183
185
|
self._refilter()
|
|
184
186
|
|
|
185
187
|
def _refilter(self) -> None:
|
|
186
|
-
"""过滤器(数字键)AND #tags AND query;query 有值时按分数序,否则保序(=置顶序)。
|
|
187
|
-
|
|
188
|
+
"""过滤器(数字键)AND #tags AND query;query 有值时按分数序,否则保序(=置顶序)。
|
|
189
|
+
|
|
190
|
+
query 以 `?` 开头进入全文模式:剩余部分跨会话检索索引(?词1 词2 = AND 子串),
|
|
191
|
+
结果按命中数降序;与数字键/标签过滤叠加(先全文命中,再套分类口径)。
|
|
192
|
+
"""
|
|
193
|
+
raw = self.query.text
|
|
194
|
+
if raw.startswith("?"):
|
|
195
|
+
self._refilter_fulltext(raw[1:].strip())
|
|
196
|
+
return
|
|
197
|
+
self._ft_hits: dict[str, "ftsearch.Hit"] = {}
|
|
198
|
+
plain, tag_tokens = csm_fmt.parse_query(raw)
|
|
188
199
|
base = [i for i, e in enumerate(self.entries)
|
|
189
200
|
if scanner.match_filter(e, self.filter_name)]
|
|
190
201
|
if tag_tokens:
|
|
@@ -207,6 +218,28 @@ class SessionPicker:
|
|
|
207
218
|
self.offset = 0
|
|
208
219
|
self.app.invalidate()
|
|
209
220
|
|
|
221
|
+
def _refilter_fulltext(self, ftq: str) -> None:
|
|
222
|
+
"""全文模式:ftsearch 命中的会话按命中数降序,叠加分类过滤口径。"""
|
|
223
|
+
hits = ftsearch.search(ftq) if ftq else []
|
|
224
|
+
if ftq and not hits:
|
|
225
|
+
files, _ = ftsearch.stats()
|
|
226
|
+
if not ftsearch.available():
|
|
227
|
+
self._notice("全文检索不可用(sqlite FTS5 缺失)")
|
|
228
|
+
elif files == 0:
|
|
229
|
+
self._notice("索引构建中…(86 个会话约 2s,稍候重试)")
|
|
230
|
+
self._ft_hits = {h.session_id: h for h in hits}
|
|
231
|
+
count_by_sid = {h.session_id: h.count for h in hits}
|
|
232
|
+
base = [i for i, e in enumerate(self.entries)
|
|
233
|
+
if scanner.match_filter(e, self.filter_name)
|
|
234
|
+
and e.session_id in count_by_sid]
|
|
235
|
+
base.sort(key=lambda i: -count_by_sid[self.entries[i].session_id])
|
|
236
|
+
self._filtered_idx = base
|
|
237
|
+
self._match_scores = {}
|
|
238
|
+
self._scores = None
|
|
239
|
+
self.selected = 0
|
|
240
|
+
self.offset = 0
|
|
241
|
+
self.app.invalidate()
|
|
242
|
+
|
|
210
243
|
def _refilter_keep_sid(self, sid: str) -> None:
|
|
211
244
|
"""重过滤后把选择定位到 sid(找不到归 0)——星标行跳转后跟随。"""
|
|
212
245
|
self._refilter()
|
|
@@ -465,10 +498,23 @@ class SessionPicker:
|
|
|
465
498
|
frags.append(("class:error" if m.tool_error else "class:tool", f"{hhmm} {mark} "))
|
|
466
499
|
frags.append(("class:dim", csm_fmt.truncate_cjk(line, width - 12)))
|
|
467
500
|
frags.append(("", "\n"))
|
|
468
|
-
#
|
|
501
|
+
# 滚动指示(顶行)+ 进度区块(todo 快照 + plan 文档)
|
|
469
502
|
head: StyleAndTextTuples = []
|
|
470
503
|
if self.preview_offset > 0 or self._preview_total() > vr:
|
|
471
504
|
head.append(("class:dim", f" ↑ 更多 {max(self._preview_total() - self.preview_offset - vr, 0)} 条在下方 / 共 {self._preview_total()} 条(最近 {PREVIEW_N})\n"))
|
|
505
|
+
pe = next((x for x in self.entries if x.session_id == self.preview_sid), None)
|
|
506
|
+
if pe is not None and pe.todos:
|
|
507
|
+
done = sum(1 for _, st in pe.todos if st == "completed")
|
|
508
|
+
head.append(("class:title", f" ✓待办 {done}/{len(pe.todos)}\n"))
|
|
509
|
+
for content, st in pe.todos[:8]:
|
|
510
|
+
mark = {"completed": "✓", "in_progress": "▸"}.get(st, "○")
|
|
511
|
+
style = "class:dim" if st == "completed" else "class:title"
|
|
512
|
+
head.append((style, f" {mark} {csm_fmt.truncate_cjk(content, width - 8)}\n"))
|
|
513
|
+
if len(pe.todos) > 8:
|
|
514
|
+
head.append(("class:dim", f" … 共 {len(pe.todos)} 项\n"))
|
|
515
|
+
if pe is not None and pe.plan_file:
|
|
516
|
+
stem = pe.plan_file.rsplit("/", 1)[-1]
|
|
517
|
+
head.append(("class:path", f" 📋 {csm_fmt.truncate_cjk(stem, width - 6)}\n"))
|
|
472
518
|
return head + frags
|
|
473
519
|
|
|
474
520
|
# ------------------------------------------------------------------ 渲染
|
|
@@ -493,8 +539,10 @@ class SessionPicker:
|
|
|
493
539
|
f" ⭐{sum(1 for e in self.entries if e.star == 1)}"),
|
|
494
540
|
("class:dim", f" 过滤:{_FILTER_LABELS.get(self.filter_name, self.filter_name)}"),
|
|
495
541
|
("", f" {matched}/{total}"),
|
|
496
|
-
("class:dim", " 1-6过滤 s星标 g跳转 Tab预览 ^L清空 ^R重扫 esc退出"),
|
|
542
|
+
("class:dim", " 1-6过滤 s星标 g跳转 Tab预览 ?全文 ^L清空 ^R重扫 esc退出"),
|
|
497
543
|
]
|
|
544
|
+
if self.query.text.startswith("?"):
|
|
545
|
+
frags[4] = ("class:title", f" 全文 {matched}/{total}")
|
|
498
546
|
if starred == 0:
|
|
499
547
|
# 无收藏时省略星标统计
|
|
500
548
|
frags[2] = ("class:dim", "")
|
|
@@ -546,6 +594,12 @@ class SessionPicker:
|
|
|
546
594
|
title = e.title or e.first_input or "(无用户输入)"
|
|
547
595
|
if e.tags:
|
|
548
596
|
title = f"{title} {' '.join('#' + t for t in e.tags[:3])}"
|
|
597
|
+
# 进度徽标:todo done/total + 📋plan(拼入标题,随列宽截断保护)
|
|
598
|
+
if e.todos is not None:
|
|
599
|
+
done = sum(1 for _, st in e.todos if st == "completed")
|
|
600
|
+
title += f" {done}/{len(e.todos)}"
|
|
601
|
+
if e.plan_file:
|
|
602
|
+
title += " 📋"
|
|
549
603
|
tstyle = cls if sel else ("class:title" if e.title else "class:dim")
|
|
550
604
|
frags.append((tstyle, csm_fmt.pad_to_width(csm_fmt.truncate_cjk(title, title_w), title_w)))
|
|
551
605
|
frags.append(("", " "))
|
|
@@ -578,6 +632,12 @@ class SessionPicker:
|
|
|
578
632
|
star = " ★" if e.star == 2 else " ⭐" if e.star == 1 else ""
|
|
579
633
|
cur = " ◉本终端" if e.is_current else ""
|
|
580
634
|
sdk = " SDK" if e.entrypoint == "sdk-cli" else ""
|
|
635
|
+
if e.todos is not None:
|
|
636
|
+
td = sum(1 for _, st in e.todos if st == "completed")
|
|
637
|
+
todo = f" ✓{td}/{len(e.todos)}"
|
|
638
|
+
else:
|
|
639
|
+
todo = ""
|
|
640
|
+
plan = " 📋" if e.plan_file else ""
|
|
581
641
|
tags = f" {' '.join('#' + t for t in e.tags)}" if e.tags else ""
|
|
582
642
|
if e.wt_branch:
|
|
583
643
|
ahead = f"+{e.wt_ahead}" if e.wt_ahead is not None else ""
|
|
@@ -585,6 +645,10 @@ class SessionPicker:
|
|
|
585
645
|
else:
|
|
586
646
|
wt = ""
|
|
587
647
|
line3 = e.first_input or "(无用户输入)"
|
|
648
|
+
ft = self._ft_hits.get(e.session_id)
|
|
649
|
+
if ft is not None:
|
|
650
|
+
snippet = ft.snippets[0][1] if ft.snippets else ""
|
|
651
|
+
line3 = f"?全文×{ft.count} {snippet or line3}"
|
|
588
652
|
path_len = len(e.project_path or "?") + len(wt)
|
|
589
653
|
return [
|
|
590
654
|
("class:dim", "─" * min(shutil.get_terminal_size().columns, _FOOTER_MAX)),
|
|
@@ -593,7 +657,8 @@ class SessionPicker:
|
|
|
593
657
|
("class:dim", f" {turns}{running}{name}"),
|
|
594
658
|
("class:star", star),
|
|
595
659
|
("class:dim", f"{sdk}{cur}"),
|
|
596
|
-
("class:
|
|
660
|
+
("class:title", todo),
|
|
661
|
+
("class:path", f"{plan}{tags}" if plan else tags),
|
|
597
662
|
("", "\n"),
|
|
598
663
|
("class:path", e.project_path or "?"),
|
|
599
664
|
("class:tool", wt),
|
|
@@ -638,6 +703,12 @@ class SessionPicker:
|
|
|
638
703
|
if e.first_input is None:
|
|
639
704
|
e.first_input = scanner.first_input_from_history(e.session_id, history)
|
|
640
705
|
self.app.invalidate()
|
|
706
|
+
# 全文索引增量更新(复用消息解析的 LRU;首建 ~1.4s/86 会话,之后增量近零)
|
|
707
|
+
if not stop.is_set():
|
|
708
|
+
try:
|
|
709
|
+
ftsearch.ensure_index(self.entries)
|
|
710
|
+
except Exception:
|
|
711
|
+
pass # 索引是尽力而为:建不了只是 ? 搜索降级,不影响其他功能
|
|
641
712
|
|
|
642
713
|
def refresh_entries(self) -> None:
|
|
643
714
|
"""Ctrl-R:重新发现并轻扫,原地替换列表。"""
|
|
@@ -85,6 +85,14 @@ header .refreshed { color: var(--dim); font-size: 12px; margin-left: auto; }
|
|
|
85
85
|
font-size: 10px; padding: 0 5px; border-radius: 8px; flex: none;
|
|
86
86
|
border: 1px solid var(--accent); color: var(--accent);
|
|
87
87
|
}
|
|
88
|
+
.row .badge-todo {
|
|
89
|
+
font-size: 11px; padding: 1px 6px; border-radius: 8px;
|
|
90
|
+
background: color-mix(in srgb, var(--accent) 14%, transparent);
|
|
91
|
+
color: var(--accent); white-space: nowrap;
|
|
92
|
+
}
|
|
93
|
+
.row .badge-plan {
|
|
94
|
+
font-size: 11px; color: var(--dim); white-space: nowrap; cursor: help;
|
|
95
|
+
}
|
|
88
96
|
.row .badge-sdk {
|
|
89
97
|
font-size: 10px; padding: 0 5px; border-radius: 8px; flex: none;
|
|
90
98
|
border: 1px solid var(--border); color: var(--dim);
|
|
@@ -102,6 +110,7 @@ header .refreshed { color: var(--dim); font-size: 12px; margin-left: auto; }
|
|
|
102
110
|
.row .copy:hover { border-color: var(--accent); color: var(--accent); }
|
|
103
111
|
.row .copy.ok { border-color: var(--user); color: var(--user); }
|
|
104
112
|
.row .l2 { color: var(--dim); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; }
|
|
113
|
+
.row .ft { color: var(--accent); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 2px; opacity: 0.85; }
|
|
105
114
|
.row .tagchip { cursor: pointer; }
|
|
106
115
|
.row .tagchip:hover { color: var(--accent); text-decoration: underline; }
|
|
107
116
|
.dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--border); }
|
|
@@ -139,6 +148,11 @@ header .refreshed { color: var(--dim); font-size: 12px; margin-left: auto; }
|
|
|
139
148
|
}
|
|
140
149
|
#detail-head button.primary { background: var(--accent); border-color: var(--accent); color: var(--bg); }
|
|
141
150
|
#detail-head button.on { border-color: var(--accent); color: var(--accent); }
|
|
151
|
+
#detail-head .p-head { font-size: 12px; font-weight: 600; margin-top: 8px; color: var(--accent); }
|
|
152
|
+
#detail-head .p-item { font-size: 12px; line-height: 1.5; }
|
|
153
|
+
#detail-head .p-item.completed { color: var(--dim); text-decoration: line-through; }
|
|
154
|
+
#detail-head .p-item.in_progress { color: var(--accent); font-weight: 600; }
|
|
155
|
+
#detail-head .p-plan { font-size: 12px; color: var(--dim); margin-top: 6px; cursor: help; }
|
|
142
156
|
#messages { flex: 1; overflow-y: auto; padding: 12px 14px; }
|
|
143
157
|
.msg { margin-bottom: 12px; }
|
|
144
158
|
.msg .ts { color: var(--dim); font-size: 10.5px; margin-bottom: 2px; }
|
|
@@ -253,7 +267,7 @@ header .refreshed { color: var(--dim); font-size: 12px; margin-left: auto; }
|
|
|
253
267
|
</header>
|
|
254
268
|
<main class="layout">
|
|
255
269
|
<section id="list-pane">
|
|
256
|
-
<input id="search" type="search" placeholder="搜索标题 / 首输入 / 项目 / SID… #标签">
|
|
270
|
+
<input id="search" type="search" placeholder="搜索标题 / 首输入 / 项目 / SID… #标签 · ?全文">
|
|
257
271
|
<div id="chips"></div>
|
|
258
272
|
<div id="rows"></div>
|
|
259
273
|
</section>
|
|
@@ -262,6 +276,7 @@ header .refreshed { color: var(--dim); font-size: 12px; margin-left: auto; }
|
|
|
262
276
|
<button id="back-btn">← 返回列表</button>
|
|
263
277
|
<div class="t" id="d-title">点击左侧会话查看预览</div>
|
|
264
278
|
<div class="meta" id="d-meta"></div>
|
|
279
|
+
<div id="d-progress" hidden></div>
|
|
265
280
|
<div id="d-tags" hidden></div>
|
|
266
281
|
<div class="actions" id="d-actions" hidden>
|
|
267
282
|
<button class="primary" id="btn-copy">复制 resume 命令</button>
|
|
@@ -293,6 +308,7 @@ const state = {
|
|
|
293
308
|
oldestOrder: -1,
|
|
294
309
|
hasMore: false,
|
|
295
310
|
filter: "",
|
|
311
|
+
ftActive: false, // ? 全文模式(行序按命中数,退出即恢复置顶序)
|
|
296
312
|
chip: "all", // 分类过滤器(与后端 FILTER_NAMES 对应)
|
|
297
313
|
newSeenAt: new Map(), // sid -> 徽章出现时间(10 分钟后自动摘除)
|
|
298
314
|
};
|
|
@@ -345,6 +361,8 @@ function buildRow(s) {
|
|
|
345
361
|
<span class="dot"></span>
|
|
346
362
|
<span class="title"></span>
|
|
347
363
|
<span class="badge-cur" hidden>◉本终端</span>
|
|
364
|
+
<span class="badge-todo" hidden></span>
|
|
365
|
+
<span class="badge-plan" hidden>📋</span>
|
|
348
366
|
<span class="badge-sdk" hidden>SDK</span>
|
|
349
367
|
<span class="badge-new" hidden>NEW</span>
|
|
350
368
|
<button class="copy" title="复制 resume 命令">复制</button>
|
|
@@ -372,6 +390,20 @@ function updateRow(el, s) {
|
|
|
372
390
|
star.textContent = s.star === 2 ? "★" : s.star === 1 ? "⭐" : "☆";
|
|
373
391
|
star.className = "star" + (s.star === 2 ? " s2" : s.star === 1 ? " s1" : "");
|
|
374
392
|
el.querySelector(".badge-cur").hidden = !s.is_current;
|
|
393
|
+
const btodo = el.querySelector(".badge-todo");
|
|
394
|
+
if (s.todos && s.todos.length) {
|
|
395
|
+
btodo.hidden = false;
|
|
396
|
+
const done = s.todos_done ?? s.todos.filter((t) => t.status === "completed").length;
|
|
397
|
+
const allDone = done === s.todos.length;
|
|
398
|
+
btodo.textContent = allDone ? `✓${s.todos.length}` : `${done}/${s.todos.length}`;
|
|
399
|
+
btodo.title = s.todos.map((t) =>
|
|
400
|
+
({ completed: "✓", in_progress: "▸" }[t.status] || "○") + " " + t.content).join("\n");
|
|
401
|
+
} else {
|
|
402
|
+
btodo.hidden = true;
|
|
403
|
+
}
|
|
404
|
+
const bplan = el.querySelector(".badge-plan");
|
|
405
|
+
bplan.hidden = !s.plan_file;
|
|
406
|
+
bplan.title = s.plan_file || "";
|
|
375
407
|
el.querySelector(".badge-sdk").hidden = !(s.entrypoint === "sdk-cli" && !s.running_status);
|
|
376
408
|
const title = el.querySelector(".title");
|
|
377
409
|
const t = s.title || s.first_input || "(无用户输入)";
|
|
@@ -493,6 +525,11 @@ function buildChips(ttyAvailable) {
|
|
|
493
525
|
}
|
|
494
526
|
|
|
495
527
|
function applyFilter() {
|
|
528
|
+
if (state.filter.startsWith("?")) {
|
|
529
|
+
fulltextFilter(state.filter.slice(1).trim());
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
if (state.ftActive) exitFulltext();
|
|
496
533
|
const toks = state.filter.split(/\s+/).filter(Boolean);
|
|
497
534
|
const tags = toks.filter((t) => t.startsWith("#") && t.length > 1).map((t) => t.slice(1));
|
|
498
535
|
const plain = toks.filter((t) => !(t.startsWith("#") && t.length > 1));
|
|
@@ -508,6 +545,55 @@ function applyFilter() {
|
|
|
508
545
|
if (state.filter || state.chip !== "all") $("stats").textContent += ` · ${shown} 匹配`;
|
|
509
546
|
}
|
|
510
547
|
|
|
548
|
+
/* ---------- 全文检索(? 前缀,服务端 FTS) ---------- */
|
|
549
|
+
|
|
550
|
+
let ftSeq = 0;
|
|
551
|
+
async function fulltextFilter(q) {
|
|
552
|
+
const seq = ++ftSeq;
|
|
553
|
+
state.ftActive = true;
|
|
554
|
+
if (!q) return; // 空 ?:保持当前显示,等关键词
|
|
555
|
+
let data;
|
|
556
|
+
try {
|
|
557
|
+
const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`);
|
|
558
|
+
data = await res.json();
|
|
559
|
+
} catch {
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
if (seq !== ftSeq) return; // 过期响应(用户继续输入)
|
|
563
|
+
const hits = new Map(data.results.map((r) => [r.session_id, r]));
|
|
564
|
+
const order = [];
|
|
565
|
+
for (const [sid, rec] of state.sessions) {
|
|
566
|
+
const hit = hits.get(sid);
|
|
567
|
+
rec.el.style.display = hit ? "" : "none";
|
|
568
|
+
if (hit) {
|
|
569
|
+
renderFtSnippet(rec.el, hit);
|
|
570
|
+
order.push(rec.el);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
for (const el of order) $("rows").appendChild(el); // 按命中数重排(置顶序暂失效)
|
|
574
|
+
$("stats").textContent += ` · 全文 ${order.length} 会话命中`;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function renderFtSnippet(el, hit) {
|
|
578
|
+
let ft = el.querySelector(".ft");
|
|
579
|
+
if (!ft) {
|
|
580
|
+
ft = document.createElement("div");
|
|
581
|
+
ft.className = "ft";
|
|
582
|
+
el.appendChild(ft);
|
|
583
|
+
}
|
|
584
|
+
const s = hit.ft_snippets && hit.ft_snippets[0];
|
|
585
|
+
ft.textContent = s ? `? ×${hit.ft_count} ${s.text}` : `? ×${hit.ft_count}`;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function exitFulltext() {
|
|
589
|
+
state.ftActive = false;
|
|
590
|
+
for (const { el } of state.sessions.values()) {
|
|
591
|
+
const ft = el.querySelector(".ft");
|
|
592
|
+
if (ft) ft.remove();
|
|
593
|
+
}
|
|
594
|
+
reconcileOrder([...state.sessions.keys()]); // 立即恢复服务端置顶序
|
|
595
|
+
}
|
|
596
|
+
|
|
511
597
|
/* ---------- 收藏(星标循环 + 标签编辑) ---------- */
|
|
512
598
|
|
|
513
599
|
async function postFavorite(sid, body, fallback) {
|
|
@@ -656,6 +742,34 @@ function selectSession(sid) {
|
|
|
656
742
|
(s.wt_ahead != null ? ` +${s.wt_ahead}` : "") + " · " : ""}` +
|
|
657
743
|
`${shortPath(s.project_path)} · ${relTime(s.mtime)} · ${s.msg_count ?? "?"} 轮 · ${s.session_id}` +
|
|
658
744
|
(s.is_current ? " · ◉本终端" : "") + (s.entrypoint === "sdk-cli" ? " · SDK" : "");
|
|
745
|
+
const prog = $("d-progress");
|
|
746
|
+
const hasTodos = s.todos && s.todos.length;
|
|
747
|
+
if (hasTodos || s.plan_file) {
|
|
748
|
+
prog.hidden = false;
|
|
749
|
+
prog.innerHTML = "";
|
|
750
|
+
if (hasTodos) {
|
|
751
|
+
const done = s.todos_done ?? s.todos.filter((t) => t.status === "completed").length;
|
|
752
|
+
const head = document.createElement("div");
|
|
753
|
+
head.className = "p-head";
|
|
754
|
+
head.textContent = `待办 ${done}/${s.todos.length}`;
|
|
755
|
+
prog.appendChild(head);
|
|
756
|
+
for (const t of s.todos) {
|
|
757
|
+
const item = document.createElement("div");
|
|
758
|
+
item.className = "p-item " + t.status;
|
|
759
|
+
item.textContent = ({ completed: "✓", in_progress: "▸" }[t.status] || "○") + " " + t.content;
|
|
760
|
+
prog.appendChild(item);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (s.plan_file) {
|
|
764
|
+
const p = document.createElement("div");
|
|
765
|
+
p.className = "p-plan";
|
|
766
|
+
p.textContent = "📋 " + s.plan_file.split("/").pop();
|
|
767
|
+
p.title = s.plan_file;
|
|
768
|
+
prog.appendChild(p);
|
|
769
|
+
}
|
|
770
|
+
} else {
|
|
771
|
+
prog.hidden = true;
|
|
772
|
+
}
|
|
659
773
|
$("d-tags").hidden = false;
|
|
660
774
|
renderTags(s.star, s.tags);
|
|
661
775
|
loadMessages(true);
|
|
@@ -21,6 +21,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
21
21
|
from importlib.resources import files
|
|
22
22
|
from urllib.parse import parse_qs, urlparse
|
|
23
23
|
|
|
24
|
+
from csm_cli import ftsearch
|
|
24
25
|
from csm_cli import scanner
|
|
25
26
|
from csm_cli.scanner import SessionEntry
|
|
26
27
|
|
|
@@ -85,6 +86,11 @@ class SessionStore:
|
|
|
85
86
|
else:
|
|
86
87
|
todo_is_ahead = False
|
|
87
88
|
if todo is None:
|
|
89
|
+
# 空闲轮:全文索引增量更新(mtime 对比 + 变化文件重建,见 ftsearch)
|
|
90
|
+
try:
|
|
91
|
+
ftsearch.ensure_index(list(self._by_sid.values()))
|
|
92
|
+
except Exception:
|
|
93
|
+
pass # 索引尽力而为:失败只是 ? 搜索降级
|
|
88
94
|
time.sleep(5.0)
|
|
89
95
|
elif todo_is_ahead:
|
|
90
96
|
scanner.worktree_ahead(todo) # 结果经 rev(wt_ahead)推给前端
|
|
@@ -125,7 +131,18 @@ def entry_payload(e: SessionEntry) -> dict:
|
|
|
125
131
|
"wt_repo": e.wt_repo,
|
|
126
132
|
"wt_branch": e.wt_branch,
|
|
127
133
|
"wt_ahead": e.wt_ahead,
|
|
128
|
-
"
|
|
134
|
+
"todos": (
|
|
135
|
+
[{"content": c, "status": st} for c, st in e.todos]
|
|
136
|
+
if e.todos is not None else None
|
|
137
|
+
),
|
|
138
|
+
"todos_done": (
|
|
139
|
+
sum(1 for _, st in e.todos if st == "completed")
|
|
140
|
+
if e.todos is not None else None
|
|
141
|
+
),
|
|
142
|
+
"plan_file": e.plan_file,
|
|
143
|
+
"rev": (f"{e.mtime}:{e.size}:{e.star}:{','.join(e.tags)}:{e.wt_ahead}"
|
|
144
|
+
f":{len(e.todos) if e.todos is not None else ''}"
|
|
145
|
+
f":{bool(e.plan_file)}"),
|
|
129
146
|
}
|
|
130
147
|
|
|
131
148
|
|
|
@@ -228,6 +245,8 @@ class CsmRequestHandler(BaseHTTPRequestHandler):
|
|
|
228
245
|
elif path.startswith("/api/sessions/") and path.endswith("/messages"):
|
|
229
246
|
sid = path[len("/api/sessions/"):-len("/messages")]
|
|
230
247
|
self._handle_messages(sid, parse_qs(parsed.query))
|
|
248
|
+
elif path == "/api/search":
|
|
249
|
+
self._handle_search(parse_qs(parsed.query))
|
|
231
250
|
else:
|
|
232
251
|
self._json(404, {"error": "not found"})
|
|
233
252
|
except BrokenPipeError:
|
|
@@ -235,6 +254,29 @@ class CsmRequestHandler(BaseHTTPRequestHandler):
|
|
|
235
254
|
except Exception as exc: # noqa: BLE001 — handler 兜底
|
|
236
255
|
self._json(500, {"error": f"internal: {exc}"})
|
|
237
256
|
|
|
257
|
+
def _handle_search(self, qs: dict[str, list[str]]) -> None:
|
|
258
|
+
"""全文检索:?q=词1+词2(AND 子串),返回按命中数降序的会话与摘要。"""
|
|
259
|
+
query = (qs.get("q", [""])[0] or "").strip()
|
|
260
|
+
if not query:
|
|
261
|
+
self._json(400, {"error": "q required"})
|
|
262
|
+
return
|
|
263
|
+
hits = ftsearch.search(query, per_session=3)
|
|
264
|
+
by_sid = {e.session_id: e for e in self.store.refresh()}
|
|
265
|
+
rows = []
|
|
266
|
+
for h in hits:
|
|
267
|
+
e = by_sid.get(h.session_id)
|
|
268
|
+
if e is None:
|
|
269
|
+
continue
|
|
270
|
+
rows.append({
|
|
271
|
+
**entry_payload(e),
|
|
272
|
+
"ft_count": h.count,
|
|
273
|
+
"ft_snippets": [{"kind": k, "text": t} for k, t in h.snippets],
|
|
274
|
+
})
|
|
275
|
+
files, msgs = ftsearch.stats()
|
|
276
|
+
self._json(200, {"query": query, "count": len(rows),
|
|
277
|
+
"index": {"files": files, "messages": msgs},
|
|
278
|
+
"results": rows})
|
|
279
|
+
|
|
238
280
|
def _handle_messages(self, sid: str, qs: dict[str, list[str]]) -> None:
|
|
239
281
|
entry = self.store.get(sid)
|
|
240
282
|
if entry is None:
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""ftsearch 单测:索引构建 / 搜索口径 / 增量失效 / 降级(临时 CONFIG_ROOT,不碰真实 ~/.claude)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
from csm_cli import ftsearch
|
|
10
|
+
from csm_cli import scanner as s
|
|
11
|
+
from test_scanner import user_line, write_session
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture()
|
|
15
|
+
def ft_env(tmp_path, monkeypatch):
|
|
16
|
+
"""临时 CONFIG_ROOT + 重置 ftsearch 模块级连接缓存。"""
|
|
17
|
+
monkeypatch.setattr(s, "CONFIG_ROOT", tmp_path)
|
|
18
|
+
ftsearch._CONN = None
|
|
19
|
+
ftsearch._RCONN = None
|
|
20
|
+
ftsearch._INIT_ERROR = None
|
|
21
|
+
return tmp_path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _assistant_text(text):
|
|
25
|
+
return {"type": "assistant",
|
|
26
|
+
"message": {"role": "assistant", "content": [{"type": "text", "text": text}]}}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _entry_for(root, sid, lines, mtime=None):
|
|
30
|
+
f = write_session(root, sid, lines, mtime=mtime)
|
|
31
|
+
st = f.stat()
|
|
32
|
+
return s.SessionEntry(session_id=sid, file_path=str(f),
|
|
33
|
+
mtime=st.st_mtime, size=st.st_size)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- 索引与搜索
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_index_and_search(ft_env):
|
|
40
|
+
e1 = _entry_for(ft_env, "s1", [
|
|
41
|
+
user_line("修复登录超时问题"),
|
|
42
|
+
_assistant_text("好的,先看会话注册表"),
|
|
43
|
+
])
|
|
44
|
+
e2 = _entry_for(ft_env, "s2", [
|
|
45
|
+
user_line("完全无关的话题"),
|
|
46
|
+
_assistant_text("嗯嗯"),
|
|
47
|
+
])
|
|
48
|
+
assert ftsearch.ensure_index([e1, e2]) == 2
|
|
49
|
+
files, msgs = ftsearch.stats()
|
|
50
|
+
assert files == 2 and msgs == 4
|
|
51
|
+
|
|
52
|
+
hits = ftsearch.search("登录超时")
|
|
53
|
+
assert [h.session_id for h in hits] == ["s1"]
|
|
54
|
+
assert hits[0].count == 1
|
|
55
|
+
assert "登录超时" in hits[0].snippets[0][1]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_search_multi_term_and_case(ft_env):
|
|
59
|
+
e1 = _entry_for(ft_env, "s1", [
|
|
60
|
+
user_line("发布 PyPI workflow"),
|
|
61
|
+
_assistant_text("用 Trusted Publishing"),
|
|
62
|
+
_assistant_text("另一段无关文本"),
|
|
63
|
+
])
|
|
64
|
+
ftsearch.ensure_index([e1])
|
|
65
|
+
hits = ftsearch.search("pypi trusted") # 会话级 AND:两词分处不同消息也命中
|
|
66
|
+
assert len(hits) == 1 and hits[0].count == 2
|
|
67
|
+
assert ftsearch.search("不存在词") == []
|
|
68
|
+
assert ftsearch.search(" ") == [] # 空查询
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# ---------------------------------------------------------------- 增量与清理
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_incremental_skip_and_rebuild(ft_env):
|
|
75
|
+
e = _entry_for(ft_env, "s1", [user_line("第一版")])
|
|
76
|
+
assert ftsearch.ensure_index([e]) == 1
|
|
77
|
+
assert ftsearch.ensure_index([e]) == 0 # (mtime,size) 未变 → 跳过
|
|
78
|
+
|
|
79
|
+
# 文件变化(追加一行)→ 该文件重建,消息数更新
|
|
80
|
+
f = ft_env / "projects" / "-Users-x-proj" / "s1.jsonl"
|
|
81
|
+
with open(f, "a") as fh:
|
|
82
|
+
fh.write('{"type":"user","message":{"role":"user","content":"第二版"},"origin":{"kind":"human"},"cwd":"/Users/x/proj"}\n')
|
|
83
|
+
st = f.stat()
|
|
84
|
+
e2 = s.SessionEntry(session_id="s1", file_path=str(f), mtime=st.st_mtime, size=st.st_size)
|
|
85
|
+
assert ftsearch.ensure_index([e2]) == 1
|
|
86
|
+
assert ftsearch.stats() == (1, 2)
|
|
87
|
+
assert ftsearch.search("第二版")[0].session_id == "s1"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def test_stale_session_cleaned(ft_env):
|
|
91
|
+
e = _entry_for(ft_env, "s-gone", [user_line("x")])
|
|
92
|
+
ftsearch.ensure_index([e])
|
|
93
|
+
assert ftsearch.stats() == (1, 1)
|
|
94
|
+
assert ftsearch.ensure_index([]) == 0 # 会话消失 → 清理
|
|
95
|
+
assert ftsearch.stats() == (0, 0)
|
|
96
|
+
assert ftsearch.search("x") == []
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------- 工具与降级
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_tool_text_indexed(ft_env):
|
|
103
|
+
lines = [
|
|
104
|
+
user_line("跑一下测试"),
|
|
105
|
+
{"type": "assistant", "message": {"role": "assistant", "content": [
|
|
106
|
+
{"type": "tool_use", "id": "t1", "name": "Bash",
|
|
107
|
+
"input": {"command": "pytest -k light"}}]}},
|
|
108
|
+
]
|
|
109
|
+
e = _entry_for(ft_env, "s-tool", lines)
|
|
110
|
+
ftsearch.ensure_index([e])
|
|
111
|
+
hits = ftsearch.search("pytest")
|
|
112
|
+
assert hits and hits[0].session_id == "s-tool"
|
|
113
|
+
assert hits[0].snippets[0][0] == "tool_use" # kind 原样透传,命令可搜
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def test_unavailable_degrades(monkeypatch, tmp_path):
|
|
117
|
+
monkeypatch.setattr(s, "CONFIG_ROOT", tmp_path)
|
|
118
|
+
ftsearch._CONN = None
|
|
119
|
+
ftsearch._RCONN = None
|
|
120
|
+
ftsearch._INIT_ERROR = None
|
|
121
|
+
monkeypatch.setattr(ftsearch, "_connect", lambda: None)
|
|
122
|
+
assert ftsearch.available() is False
|
|
123
|
+
assert ftsearch.ensure_index([]) == 0
|
|
124
|
+
assert ftsearch.search("any") == []
|
|
125
|
+
assert ftsearch.stats() == (0, 0)
|
|
@@ -548,6 +548,90 @@ def test_is_current_fast_path_tty_match(monkeypatch):
|
|
|
548
548
|
assert e.is_current is True
|
|
549
549
|
|
|
550
550
|
|
|
551
|
+
# ---------------------------------------------------------------- 会话进度
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _todo_line(*pairs):
|
|
555
|
+
return {"type": "assistant",
|
|
556
|
+
"message": {"role": "assistant", "content": [
|
|
557
|
+
{"type": "tool_use", "name": "TodoWrite",
|
|
558
|
+
"input": {"todos": [{"content": c, "status": st} for c, st in pairs]}}]}}
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def test_extract_todos_shapes():
|
|
562
|
+
content = _todo_line(("a", "completed"), ("b", "in_progress"))["message"]["content"]
|
|
563
|
+
assert s._extract_todos(content) == (("a", "completed"), ("b", "in_progress"))
|
|
564
|
+
assert s._extract_todos([{"type": "tool_use", "name": "Edit"}]) is None
|
|
565
|
+
assert s._extract_todos([]) is None
|
|
566
|
+
assert s._extract_todos("str") is None
|
|
567
|
+
# 坏项静默跳过 + status 缺省按 pending
|
|
568
|
+
bad = [{"type": "tool_use", "name": "TodoWrite",
|
|
569
|
+
"input": {"todos": [{"content": "ok"}, {"content": 1}, "bad"]}}]
|
|
570
|
+
assert s._extract_todos(bad) == (("ok", "pending"),)
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def test_extract_plan_path():
|
|
574
|
+
assert s._extract_plan_path({"attachment": {"planFilePath": "/p/x.md"}}) == "/p/x.md"
|
|
575
|
+
assert s._extract_plan_path({"attachment": {}}) is None
|
|
576
|
+
assert s._extract_plan_path({}) is None
|
|
577
|
+
assert s._extract_plan_path({"attachment": "str"}) is None
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def test_light_scan_todos_and_plan(fake_root):
|
|
581
|
+
lines = [
|
|
582
|
+
user_line("q"),
|
|
583
|
+
_todo_line(("step1", "completed"), ("step2", "in_progress")),
|
|
584
|
+
{"type": "attachment", "attachment": {"planFilePath": "/p/plan-a.md"}},
|
|
585
|
+
{"type": "ai-title", "aiTitle": "t"},
|
|
586
|
+
]
|
|
587
|
+
write_session(fake_root, "sid-todo", lines)
|
|
588
|
+
e = s.discover_sessions()[0]
|
|
589
|
+
s.light_scan(e)
|
|
590
|
+
assert e.todos == (("step1", "completed"), ("step2", "in_progress"))
|
|
591
|
+
assert e.todos_scanned_full is True
|
|
592
|
+
assert e.plan_file == "/p/plan-a.md"
|
|
593
|
+
assert e.plan_scanned_full is True
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def test_light_scan_no_todos_small_file(fake_root):
|
|
597
|
+
"""小文件不截断 → 尾窗没找到即为「确认没有」。"""
|
|
598
|
+
write_session(fake_root, "sid-none", [{"type": "ai-title", "aiTitle": "t"}])
|
|
599
|
+
e = s.discover_sessions()[0]
|
|
600
|
+
s.light_scan(e)
|
|
601
|
+
assert e.todos is None and e.todos_scanned_full is True
|
|
602
|
+
assert e.plan_file is None and e.plan_scanned_full is True
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def test_light_scan_todos_miss_then_full_backfill(fake_root):
|
|
606
|
+
"""TodoWrite 在头部、尾窗(缩窗模拟大文件)之外 → scanned_full=False,全扫兜底。"""
|
|
607
|
+
lines = [_todo_line(("early", "pending"))]
|
|
608
|
+
lines += [{"type": "assistant", "message": {"role": "assistant", "content": []}}] * 50
|
|
609
|
+
lines.append({"type": "ai-title", "aiTitle": "t"})
|
|
610
|
+
write_session(fake_root, "sid-miss", lines)
|
|
611
|
+
e = s.discover_sessions()[0]
|
|
612
|
+
s.light_scan(e, head_bytes=64, tail_bytes=64)
|
|
613
|
+
assert e.todos is None and e.todos_scanned_full is False
|
|
614
|
+
s.full_scan(e)
|
|
615
|
+
assert e.todos == (("early", "pending"),)
|
|
616
|
+
assert e.todos_scanned_full is True
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def test_todos_take_last_snapshot(fake_root):
|
|
620
|
+
"""多条 TodoWrite → 最后一条(最新快照)胜出,light 与 full 口径一致。"""
|
|
621
|
+
lines = [
|
|
622
|
+
_todo_line(("a", "pending")),
|
|
623
|
+
_todo_line(("b", "completed"), ("c", "in_progress")),
|
|
624
|
+
{"type": "ai-title", "aiTitle": "t"},
|
|
625
|
+
]
|
|
626
|
+
write_session(fake_root, "sid-last", lines)
|
|
627
|
+
e = s.discover_sessions()[0]
|
|
628
|
+
s.light_scan(e)
|
|
629
|
+
assert e.todos == (("b", "completed"), ("c", "in_progress"))
|
|
630
|
+
e2 = s.discover_sessions()[0]
|
|
631
|
+
s.full_scan(e2)
|
|
632
|
+
assert e2.todos == (("b", "completed"), ("c", "in_progress"))
|
|
633
|
+
|
|
634
|
+
|
|
551
635
|
# ---------------------------------------------------------------- 终端定位
|
|
552
636
|
|
|
553
637
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|