dsh-worktree-groups 0.0.0-stage → 0.1.1

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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/cordis.patch.yml +17 -0
  4. package/icon.svg +20 -0
  5. package/lib/activity.d.ts +78 -0
  6. package/lib/activity.d.ts.map +1 -0
  7. package/lib/activity.js +241 -0
  8. package/lib/activity.js.map +1 -0
  9. package/lib/client.d.ts +78 -0
  10. package/lib/client.d.ts.map +1 -0
  11. package/lib/client.js +4280 -0
  12. package/lib/git.d.ts +109 -0
  13. package/lib/git.d.ts.map +1 -0
  14. package/lib/git.js +317 -0
  15. package/lib/git.js.map +1 -0
  16. package/lib/icons.d.ts +148 -0
  17. package/lib/icons.d.ts.map +1 -0
  18. package/lib/icons.js +144 -0
  19. package/lib/icons.js.map +1 -0
  20. package/lib/index.d.ts +32 -0
  21. package/lib/index.d.ts.map +1 -0
  22. package/lib/index.js +47 -0
  23. package/lib/index.js.map +1 -0
  24. package/lib/ledger.d.ts +97 -0
  25. package/lib/ledger.d.ts.map +1 -0
  26. package/lib/ledger.js +276 -0
  27. package/lib/ledger.js.map +1 -0
  28. package/lib/live-merge.d.ts +44 -0
  29. package/lib/live-merge.d.ts.map +1 -0
  30. package/lib/live-merge.js +227 -0
  31. package/lib/live-merge.js.map +1 -0
  32. package/lib/live-state.d.ts +158 -0
  33. package/lib/live-state.d.ts.map +1 -0
  34. package/lib/live-state.js +281 -0
  35. package/lib/live-state.js.map +1 -0
  36. package/lib/locales.d.ts +71 -0
  37. package/lib/locales.d.ts.map +1 -0
  38. package/lib/locales.js +199 -0
  39. package/lib/locales.js.map +1 -0
  40. package/lib/projects.d.ts +88 -0
  41. package/lib/projects.d.ts.map +1 -0
  42. package/lib/projects.js +418 -0
  43. package/lib/projects.js.map +1 -0
  44. package/lib/routes.d.ts +376 -0
  45. package/lib/routes.d.ts.map +1 -0
  46. package/lib/routes.js +1875 -0
  47. package/lib/routes.js.map +1 -0
  48. package/lib/row-memo.d.ts +34 -0
  49. package/lib/row-memo.d.ts.map +1 -0
  50. package/lib/row-memo.js +46 -0
  51. package/lib/row-memo.js.map +1 -0
  52. package/lib/sidebar.d.ts +126 -0
  53. package/lib/sidebar.d.ts.map +1 -0
  54. package/lib/tree-model.d.ts +1226 -0
  55. package/lib/tree-model.d.ts.map +1 -0
  56. package/lib/tree-model.js +2143 -0
  57. package/lib/tree-model.js.map +1 -0
  58. package/lib/types.d.ts +98 -0
  59. package/lib/types.d.ts.map +1 -0
  60. package/lib/types.js +8 -0
  61. package/lib/types.js.map +1 -0
  62. package/locale/en.json +6 -0
  63. package/locale/zh.json +6 -0
  64. package/package.json +88 -4
package/lib/routes.js ADDED
@@ -0,0 +1,1875 @@
1
+ /**
2
+ * 宿主 HTTP 路由(契约见 `docs/INTERFACES.md` §1.5)。
3
+ *
4
+ * 五个路由全部挂在 `/dsh-worktree-groups/` 前缀下,用 `ctx.effect` +
5
+ * `ctx.webServer.register({ kind: 'exact', path, handler })` 注册(宿主契约
6
+ * 见 `docs/HOST-CONTRACTS.md` §A3)。全部 handler 都把异常收敛成 JSON,
7
+ * **永不**抛到 HTTP 层(宿主在 handler 抛错时只回 400 空体,客户端拿不到原因)。
8
+ *
9
+ * ## 数据组装(本文件的重头)
10
+ *
11
+ * 侧栏树的数据必须同时覆盖两个事实源,见 `docs/INTERFACES.md` §2.7 裁定 6:
12
+ *
13
+ * | 事实 | 来源 | 为什么不能用另一个 |
14
+ * |---|---|---|
15
+ * | 全量历史会话(含 cwd 已删除的孤儿) | `ctx.sessionPersistence.list()` | `sessions` 只有进程内活着的实例 |
16
+ * | 实时状态(running/blank/updatedAt/title) | `ctx.sessionController.list()` | `sessionPersistence` 只有 `createdAt`、没有 `updatedAt` |
17
+ * | 工作区(id/path/title) | `ctx.workspaceRegistry.list()` | `sessionIds` getter 会实时过滤掉死 cwd 会话(§A4.5) |
18
+ * | worktree 事实 | `scanRepo()`(按 commonDir 去重 + 30s 缓存) | — |
19
+ *
20
+ * 两侧按 `sessionId` **左连接**到全量历史之上:以全量历史为主表,实时状态只补字段。
21
+ * 孤儿会话没有 summary ⇒ `updatedAt` 必须按裁定 7 回退到 `header.createdAt`,
22
+ * 否则会得到 `undefined`(排序 NaN / 排到末尾)。
23
+ */
24
+ import { execFile } from 'node:child_process';
25
+ import { createHash } from 'node:crypto';
26
+ import { lstat, readdir, realpath, stat } from 'node:fs/promises';
27
+ import { basename, dirname, join } from 'node:path';
28
+ import { normalizePath, runGit, scanRepo } from './git.js';
29
+ import { attachLastActivityTimes, registerSessionActivityObserver, sessionActivityVersion } from './activity.js';
30
+ import { createFileLedger } from './ledger.js';
31
+ import { buildProjects, collectUngrouped } from './projects.js';
32
+ /** 全部路由的统一前缀(路由表是全局的,必须带自己的命名空间,宿主契约硬约束 17)。 */
33
+ const ROUTE_PREFIX = '/dsh-worktree-groups';
34
+ /** 本插件注册的全部路由路径(导出便于测试与客户端对齐)。 */
35
+ export const ROUTE_PATHS = {
36
+ tree: `${ROUTE_PREFIX}/tree`,
37
+ worktreeCreate: `${ROUTE_PREFIX}/worktree-create`,
38
+ worktreeRemove: `${ROUTE_PREFIX}/worktree-remove`,
39
+ reveal: `${ROUTE_PREFIX}/reveal`,
40
+ workspaceOpen: `${ROUTE_PREFIX}/workspace-open`,
41
+ };
42
+ /**
43
+ * git 扫描结果缓存时长(PRD D13:30 秒)。
44
+ *
45
+ * ⚠️ 2026-11-14 PERF3 起,正向缓存改由仓指纹校验 + {@link SCAN_CACHE_MAX_AGE_MS} 兜底,
46
+ * 本常量仅为兼容既有导出保留,不再参与判定。
47
+ */
48
+ export const SCAN_CACHE_TTL_MS = 30_000;
49
+ /**
50
+ * 从 ctx 惰性取宿主服务。
51
+ *
52
+ * `ctx.get()` 本身也可能抛(Cordis 在极端情况下会抛诊断错误),因此统一包
53
+ * try/catch —— 本插件的总原则是**缺失即降级,绝不崩**(PRD R6)。
54
+ */
55
+ function getService(ctx, name) {
56
+ try {
57
+ const value = ctx.get;
58
+ if (typeof value !== 'function')
59
+ return undefined;
60
+ const service = value.call(ctx, name);
61
+ if (service === undefined || service === null)
62
+ return undefined;
63
+ return service;
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ /**
70
+ * 模块级扫描缓存:键是「扫描入口路径」,值附带**仓指纹**。
71
+ *
72
+ * ## 2026-11-14 PERF3:TTL → 指纹校验
73
+ *
74
+ * 旧实现只靠 30 s TTL:`git worktree add/remove`、`git checkout` 之后最长 30 s(叠加客户端
75
+ * 轮询约 60 s)侧栏才更新;而且主路径的旧条目会被优先采纳,新 worktree 入口的新鲜扫描被丢弃。
76
+ * 现在复用缓存前先算一次廉价指纹(几个 `stat`,不起 git 进程):
77
+ *
78
+ * - `<commonDir>/HEAD` 的 mtime —— 主树切分支(git 以 lock + rename 写 HEAD);
79
+ * - `<commonDir>/worktrees/` 目录项及每项 `HEAD` / `gitdir` 的 mtime —— worktree 增删、切分支、移动;
80
+ * - 每个 worktree 目录是否存在 —— 被外部 `rm -rf` 后立即显示为已关闭。
81
+ *
82
+ * 指纹一致且未超过 {@link SCAN_CACHE_MAX_AGE_MS} ⇒ 复用;否则重扫。负缓存(非 git 目录)
83
+ * 的指纹是「`<path>/.git` 是否存在」,`git init` 后立即失效。
84
+ */
85
+ const scanCache = new Map();
86
+ /** 指纹一致时缓存的最长复用时间(兜底:指纹覆盖不到的罕见变化,最迟 5 分钟收敛)。 */
87
+ export const SCAN_CACHE_MAX_AGE_MS = 5 * 60_000;
88
+ /** 并行扫描的并发上限(每个扫描最多 3 个 git 子进程)。 */
89
+ const SCAN_CONCURRENCY = 6;
90
+ /** 清空全部进程内缓存(git 扫描 + 会话列举 + `/tree` 载荷)。测试用;也用于故障后强制重扫。 */
91
+ export function clearScanCache() {
92
+ scanCache.clear();
93
+ clearSessionRowsCache();
94
+ }
95
+ /** `stat` 的 mtime(毫秒);不存在 / 失败返回 `-1`。 */
96
+ async function mtimeOf(target) {
97
+ try {
98
+ return (await stat(target)).mtimeMs;
99
+ }
100
+ catch {
101
+ return -1;
102
+ }
103
+ }
104
+ /**
105
+ * 仓指纹:只用 `stat` / `readdir`,不起 git 进程(单仓典型 < 1 ms)。
106
+ * 任何 IO 失败都折算成可比较的哨兵值,绝不抛错。
107
+ */
108
+ async function repoFingerprint(repo) {
109
+ const commonDir = repo.commonDir;
110
+ const parts = [String(await mtimeOf(join(commonDir, 'HEAD')))];
111
+ let names = [];
112
+ try {
113
+ names = (await readdir(join(commonDir, 'worktrees'))).sort();
114
+ }
115
+ catch {
116
+ names = [];
117
+ }
118
+ const linked = await Promise.all(names.map(async (name) => {
119
+ const dir = join(commonDir, 'worktrees', name);
120
+ return `${name}:${await mtimeOf(join(dir, 'HEAD'))}:${await mtimeOf(join(dir, 'gitdir'))}`;
121
+ }));
122
+ parts.push(linked.join(','));
123
+ const exists = await Promise.all(repo.worktrees.map(async (entry) => ((await mtimeOf(entry.path)) >= 0 ? '1' : '0')));
124
+ parts.push(exists.join(''));
125
+ return parts.join('|');
126
+ }
127
+ /** 负缓存指纹:`<path>/.git` 是否存在(`git init` / clone 后立即失效)。 */
128
+ async function negativeFingerprint(path) {
129
+ return (await mtimeOf(join(path, '.git'))) >= 0 ? 'git' : 'none';
130
+ }
131
+ /** 缓存条目仍可信?(指纹一致且未超过最长复用时间) */
132
+ async function cacheStillValid(entry, path, now) {
133
+ if (now < entry.at || now - entry.at >= SCAN_CACHE_MAX_AGE_MS)
134
+ return false;
135
+ const current = entry.repo === null ? await negativeFingerprint(path) : await repoFingerprint(entry.repo);
136
+ return current === entry.fingerprint;
137
+ }
138
+ /**
139
+ * 扫描候选路径,按 commonDir 去重。
140
+ *
141
+ * - 先校验缓存(同一 commonDir 的指纹只算一次),失效的路径以 {@link SCAN_CONCURRENCY}
142
+ * 并发重扫;同一仓已被本轮扫到的其它入口直接共享结果,不重复跑 git;
143
+ * - 输出顺序与候选顺序一致(与并发完成顺序无关);同一仓取本轮最新的事实;
144
+ * - 任何单路径的扫描异常都被吞掉并从缓存里剔除,不影响其余路径。
145
+ */
146
+ async function scanRepos(candidates, now, signal) {
147
+ const paths = [...new Set(candidates.map((raw) => normalizePath(raw)))];
148
+ const resolved = new Map();
149
+ /** commonDir → 本轮已确认新鲜的仓事实(校验通过或刚扫完)。 */
150
+ const freshByCommonDir = new Map();
151
+ const validity = new Map();
152
+ const validate = (path, entry) => {
153
+ if (entry.repo === null)
154
+ return cacheStillValid(entry, path, now);
155
+ const key = `${entry.repo.commonDir}\u0000${entry.at}\u0000${entry.fingerprint}`;
156
+ let pending = validity.get(key);
157
+ if (pending === undefined) {
158
+ pending = cacheStillValid(entry, path, now);
159
+ validity.set(key, pending);
160
+ }
161
+ return pending;
162
+ };
163
+ const stale = [];
164
+ await Promise.all(paths.map(async (path) => {
165
+ const cached = scanCache.get(path);
166
+ if (cached !== undefined && (await validate(path, cached))) {
167
+ resolved.set(path, cached.repo);
168
+ if (cached.repo !== null && !freshByCommonDir.has(cached.repo.commonDir)) {
169
+ freshByCommonDir.set(cached.repo.commonDir, cached.repo);
170
+ }
171
+ return;
172
+ }
173
+ stale.push(path);
174
+ }));
175
+ stale.sort((a, b) => paths.indexOf(a) - paths.indexOf(b));
176
+ const coveredBy = (path) => {
177
+ for (const repo of freshByCommonDir.values()) {
178
+ if (normalizePath(repo.mainPath) === path)
179
+ return repo;
180
+ if (repo.worktrees.some((entry) => normalizePath(entry.path) === path))
181
+ return repo;
182
+ }
183
+ return undefined;
184
+ };
185
+ let cursor = 0;
186
+ const worker = async () => {
187
+ while (cursor < stale.length) {
188
+ const path = stale[cursor];
189
+ cursor += 1;
190
+ const shared = coveredBy(path);
191
+ if (shared !== undefined) {
192
+ resolved.set(path, shared);
193
+ continue;
194
+ }
195
+ let repo;
196
+ try {
197
+ repo = await scanRepo(path, signal);
198
+ }
199
+ catch {
200
+ // 扫描抛错(git 缺失、权限、被取消):剔除陈旧缓存,本次跳过该路径。
201
+ scanCache.delete(path);
202
+ continue;
203
+ }
204
+ resolved.set(path, repo);
205
+ if (repo === null) {
206
+ scanCache.set(path, { at: now, repo: null, fingerprint: await negativeFingerprint(path) });
207
+ continue;
208
+ }
209
+ freshByCommonDir.set(repo.commonDir, repo);
210
+ const entry = { at: now, repo, fingerprint: await repoFingerprint(repo) };
211
+ scanCache.set(path, entry);
212
+ // 同一仓的其它 worktree 入口共享这份**最新**事实(覆盖旧条目,避免旧事实被优先采纳)。
213
+ for (const worktree of repo.worktrees)
214
+ scanCache.set(normalizePath(worktree.path), entry);
215
+ scanCache.set(normalizePath(repo.mainPath), entry);
216
+ }
217
+ };
218
+ await Promise.all(Array.from({ length: Math.min(SCAN_CONCURRENCY, stale.length) }, () => worker()));
219
+ const repos = new Map();
220
+ const pathToCommonDir = new Map();
221
+ for (const path of paths) {
222
+ const repo = resolved.get(path);
223
+ if (repo === undefined || repo === null)
224
+ continue;
225
+ pathToCommonDir.set(path, repo.commonDir);
226
+ if (!repos.has(repo.commonDir))
227
+ repos.set(repo.commonDir, freshByCommonDir.get(repo.commonDir) ?? repo);
228
+ }
229
+ return { repos, pathToCommonDir };
230
+ }
231
+ /* ------------------------------------------------------------------ *
232
+ * 会话 / 工作区 / 台账
233
+ * ------------------------------------------------------------------ */
234
+ /** 取有限数字,否则 undefined(防止 NaN 污染排序)。 */
235
+ function finiteNumber(value) {
236
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
237
+ }
238
+ /** 取非空字符串,否则 undefined。 */
239
+ function nonEmptyString(value) {
240
+ return typeof value === 'string' && value !== '' ? value : undefined;
241
+ }
242
+ /** 从任意 summary 形状里取 sessionId。 */
243
+ function summaryId(summary) {
244
+ return nonEmptyString(summary.sessionId) ?? nonEmptyString(summary.id);
245
+ }
246
+ /** 从任意 summary 形状里取标题投影(`projections.values.title` 优先于顶层 `title`)。 */
247
+ function summaryTitle(summary) {
248
+ return nonEmptyString(summary.projections?.values?.title) ?? nonEmptyString(summary.title);
249
+ }
250
+ /**
251
+ * 收集实时会话摘要,按 `sessionId` 索引。
252
+ *
253
+ * 三级来源,逐级降级(宿主契约 §A2.2 已核实:宿主 `ctx.sessions` 是 SessionStore,
254
+ * 它的 `list()` 返回活着的 `Session` 实例,**不是** `{items, byId}` 快照;
255
+ * 真正的 `SessionSummary` 生产者是 `ctx.sessionController`):
256
+ *
257
+ * 1. `ctx.sessionController.list({})` → `{ items: SessionSummary[] }`(权威、含孤儿)
258
+ * 2. `ctx.sessions.list()`:若元素本身长得像 summary(有 `sessionId` + 数字 `updatedAt`)直接用;
259
+ * 若元素是活的 `Session`(有 `.header`)则从 header 推导最小摘要;
260
+ * 3. `ctx.sessions.list` 若是 observable 快照源(有 `getSnapshot`)则读 `items` / `byId`。
261
+ *
262
+ * 全部缺失时返回空 Map —— 组装侧仍会为每个会话回退到 `header.createdAt`。
263
+ */
264
+ export async function loadSessionSummaries(ctx, signal) {
265
+ const summaries = new Map();
266
+ const controller = getService(ctx, 'sessionController');
267
+ if (typeof controller?.list === 'function') {
268
+ try {
269
+ const value = await controller.list({}, signal);
270
+ const items = Array.isArray(value)
271
+ ? value
272
+ : Array.isArray(value?.items)
273
+ ? (value.items)
274
+ : [];
275
+ for (const item of items) {
276
+ if (typeof item !== 'object' || item === null)
277
+ continue;
278
+ const summary = item;
279
+ const id = summaryId(summary);
280
+ if (id !== undefined && !summaries.has(id))
281
+ summaries.set(id, summary);
282
+ }
283
+ }
284
+ catch {
285
+ // 快照不可用(sessions/agents 尚未就绪):降级到下一来源
286
+ }
287
+ }
288
+ if (summaries.size > 0)
289
+ return summaries;
290
+ const sessions = getService(ctx, 'sessions');
291
+ if (sessions === undefined)
292
+ return summaries;
293
+ const absorbList = (list) => {
294
+ if (!Array.isArray(list))
295
+ return;
296
+ for (const entry of list) {
297
+ if (typeof entry !== 'object' || entry === null)
298
+ continue;
299
+ const candidate = entry;
300
+ const id = summaryId(candidate);
301
+ if (id !== undefined && finiteNumber(candidate.updatedAt) !== undefined) {
302
+ if (!summaries.has(id))
303
+ summaries.set(id, candidate);
304
+ continue;
305
+ }
306
+ // 活的 Session 实例:用它的 header 推导一份最小摘要。
307
+ const header = entry.header;
308
+ const headerId = nonEmptyString(header?.id);
309
+ if (headerId !== undefined && !summaries.has(headerId)) {
310
+ summaries.set(headerId, {
311
+ sessionId: headerId,
312
+ updatedAt: finiteNumber(header?.createdAt),
313
+ running: false,
314
+ blank: entry.seq === 0,
315
+ cwd: nonEmptyString(header?.cwd),
316
+ parentSessionId: nonEmptyString(header?.parentSession),
317
+ origin: header?.origin === 'subagent' ? 'subagent' : undefined,
318
+ });
319
+ }
320
+ }
321
+ };
322
+ const rawList = sessions.list;
323
+ if (typeof rawList === 'function') {
324
+ try {
325
+ // 宿主 `SessionStore.list()` 是**无参同步**方法(`dsh-session/lib/index.js:1562`
326
+ // `list() { return [...this.store.values()].map(...) }`)—— 不能传 signal,
327
+ // 也不返回 Promise。`absorbList` 对非数组入参是 no-op,形状不符时自然降级。
328
+ absorbList(rawList.call(sessions));
329
+ }
330
+ catch {
331
+ // 忽略:降级到空摘要表
332
+ }
333
+ }
334
+ else if (typeof rawList === 'object' && rawList !== null) {
335
+ // observable 快照源(`{ getSnapshot, subscribe }`)
336
+ const source = rawList;
337
+ if (typeof source.getSnapshot === 'function') {
338
+ try {
339
+ const snapshot = source.getSnapshot();
340
+ absorbList(snapshot?.items);
341
+ if (snapshot?.byId !== undefined && typeof snapshot.byId === 'object' && snapshot.byId !== null) {
342
+ absorbList(Object.values(snapshot.byId));
343
+ }
344
+ }
345
+ catch {
346
+ // 忽略
347
+ }
348
+ }
349
+ }
350
+ return summaries;
351
+ }
352
+ /**
353
+ * 读取全量历史会话(**含 cwd 已死**的孤儿),组装成 `SessionRow[]`。
354
+ *
355
+ * 组装规则(`docs/INTERFACES.md` §2.7 裁定 7):
356
+ * `updatedAt = summary.updatedAt ?? header.createdAt ?? 0`,且必须是**有限数字**。
357
+ *
358
+ * 返回 `{ rows, summaries }`:`summaries` 供调用方复用作 summary 存在性判断。
359
+ */
360
+ export async function buildSessionRows(ctx, signal) {
361
+ const persistence = getService(ctx, 'sessionPersistence');
362
+ // 2026-11-14 PERF1:两路列举互不依赖 ⇒ 并行发起(旧实现串行,耗时相加)。
363
+ // 宿主签名是 `list(options)`(`options?.signal`),必须传对象而不是裸 signal,
364
+ // 否则取消信号在入口丢失(`docs/HOST-CONTRACTS.md` §A1.2 的宿主源码为证)。
365
+ const listPersisted = persistence?.list;
366
+ const persisted = typeof listPersisted === 'function'
367
+ ? (async () => {
368
+ try {
369
+ return (await listPersisted.call(persistence, { signal })) ?? [];
370
+ }
371
+ catch {
372
+ // 存储故障:退化为「只有实时会话」而不是整棵树失败。
373
+ return [];
374
+ }
375
+ })()
376
+ : undefined;
377
+ const summaries = await loadSessionSummaries(ctx, signal);
378
+ const rows = [];
379
+ if (persisted !== undefined) {
380
+ const snapshots = await persisted;
381
+ for (const snapshot of snapshots) {
382
+ const header = snapshot?.header;
383
+ const sessionId = nonEmptyString(header?.id);
384
+ if (sessionId === undefined)
385
+ continue;
386
+ rows.push(toSessionRow(sessionId, header, summaries.get(sessionId)));
387
+ }
388
+ }
389
+ // 实时摘要里存在、但全量历史里没有的会话(极端时序:刚创建还没落盘)。
390
+ // 必须补进来,否则「新会话」在侧栏短暂消失。
391
+ if (rows.length > 0 || summaries.size > 0) {
392
+ const seen = new Set(rows.map((row) => row.sessionId));
393
+ for (const [sessionId, summary] of summaries) {
394
+ if (seen.has(sessionId))
395
+ continue;
396
+ rows.push(toSessionRow(sessionId, undefined, summary));
397
+ }
398
+ }
399
+ // 2026-10-29 RAS2/RAS3:补「最后更新时间」。必须在全部行(含子代理)都到齐之后做,
400
+ // 才能把子代理活动沿 parentSessionId 传播到祖先主会话。
401
+ attachLastActivityTimes(rows);
402
+ return { rows, summaries };
403
+ }
404
+ /** 单条会话的投影(左连接 summary 到 header 之上)。 */
405
+ function toSessionRow(sessionId, header, summary) {
406
+ // 裁定 7:summary.updatedAt → header.createdAt → 0,且必须是有限数字。
407
+ const updatedAt = finiteNumber(summary?.updatedAt) ?? finiteNumber(header?.createdAt) ?? 0;
408
+ const cwd = nonEmptyString(summary?.cwd) ?? nonEmptyString(header?.cwd);
409
+ const parentSessionId = nonEmptyString(summary?.parentSessionId) ?? nonEmptyString(header?.parentSession);
410
+ const originValue = summary?.origin ?? header?.origin;
411
+ const title = summary === undefined ? undefined : summaryTitle(summary);
412
+ const pendingInteraction = nonEmptyString(summary?.pendingInteraction);
413
+ const completed = typeof summary?.completed === 'boolean' ? summary.completed : undefined;
414
+ const row = {
415
+ sessionId,
416
+ updatedAt,
417
+ // 2026-10-29 RAS4:先回退到 updatedAt;buildSessionRows 末尾再由活动表补
418
+ // max(updatedAt, 自身/后代活动时间)。保持「恒为有限数字」的既有契约。
419
+ lastActivityAt: updatedAt,
420
+ running: summary?.running === true,
421
+ blank: summary?.blank === true,
422
+ };
423
+ // 裁定 8:cwd 可缺失。缺失时不写该键,由 buildProjects 的 assignSession 归入未分组。
424
+ if (cwd !== undefined)
425
+ row.cwd = cwd;
426
+ if (parentSessionId !== undefined)
427
+ row.parentSessionId = parentSessionId;
428
+ if (originValue === 'subagent')
429
+ row.origin = 'subagent';
430
+ if (pendingInteraction !== undefined)
431
+ row.pendingInteraction = pendingInteraction;
432
+ if (completed !== undefined)
433
+ row.completed = completed;
434
+ if (title !== undefined)
435
+ row.title = title;
436
+ return row;
437
+ }
438
+ /** 把宿主工作区实体投影成 `WorkspaceRow`。
439
+ *
440
+ * **只投影 id/path/title/createdAt/updatedAt**。刻意**不**投影宿主的 `sessionIds`
441
+ * getter:裁定 6 禁止用它做归属判定(实时过滤 ⇒ 会丢会话),而本包没有任何消费者
442
+ * 需要它。删掉该字段后,裁定 6 从「靠注释约束」升级为「靠类型约束」。 */
443
+ function toWorkspaceRow(entity) {
444
+ const workspaceId = nonEmptyString(entity.id);
445
+ const path = nonEmptyString(entity.path);
446
+ if (workspaceId === undefined || path === undefined)
447
+ return undefined;
448
+ return {
449
+ workspaceId,
450
+ path: normalizePath(path),
451
+ title: nonEmptyString(entity.title) ?? '',
452
+ createdAt: typeof entity.createdAt === 'string' ? entity.createdAt : '',
453
+ updatedAt: typeof entity.updatedAt === 'string' ? entity.updatedAt : '',
454
+ };
455
+ }
456
+ /** 读取工作区注册表(缺失时返回空表 —— 降级不崩)。 */
457
+ export function loadWorkspaces(ctx) {
458
+ const registry = getService(ctx, 'workspaceRegistry');
459
+ const workspaces = [];
460
+ if (typeof registry?.list !== 'function')
461
+ return { workspaces, registry };
462
+ try {
463
+ for (const entity of registry.list() ?? []) {
464
+ if (typeof entity !== 'object' || entity === null)
465
+ continue;
466
+ const row = toWorkspaceRow(entity);
467
+ if (row !== undefined)
468
+ workspaces.push(row);
469
+ }
470
+ }
471
+ catch {
472
+ // 注册表顺序损坏(宿主会抛 "references missing workspace"):返回已读到的部分。
473
+ }
474
+ return { workspaces, registry };
475
+ }
476
+ /** 归档会话集合(用于从全量历史里剔除,客户端再兜一层)。 */
477
+ export function loadArchivedSessionIds(registry) {
478
+ const raw = registry?.archivedSessionIds;
479
+ if (!Array.isArray(raw))
480
+ return [];
481
+ return raw.filter((id) => typeof id === 'string');
482
+ }
483
+ /**
484
+ * **D8**:工作区表的内容签名(用于判断「注册表是否真的变了」)。
485
+ *
486
+ * 为什么不用长度:长度是代理指标。D18 清扫删 1 条 + 宿主同一轮新增 1 条 ⇒ 长度相等,
487
+ * `length !== length` 会误判为「没变」,本轮响应继续用旧表(死工作区行多渲染一轮)。
488
+ *
489
+ * 为什么不用 `updatedAt` 单个字段:宿主对 `title` 重命名与 `delete` 都会动 `updatedAt`,
490
+ * 但**成员增删**必须被检出,所以两者都纳入。签名先按 `workspaceId` 排序,因此与
491
+ * `registry.list()` 的返回顺序无关(顺序变化不应被当成内容变化)。
492
+ *
493
+ * 导出以便单测直接对「同长度不同成员」构造用例断言。
494
+ */
495
+ export function workspaceSignature(workspaces) {
496
+ return workspaces
497
+ .map((row) => `${row.workspaceId}\u0000${row.path}\u0000${row.title}\u0000${row.updatedAt}`)
498
+ .sort()
499
+ .join('\u0001');
500
+ }
501
+ /* ------------------------------------------------------------------ *
502
+ * 会话列举缓存(2026-11-14 PERF1)
503
+ * ------------------------------------------------------------------ */
504
+ /** 会话列举缓存的最长复用时间(兜底:没有任何活动信号时也最迟 30 s 重列一次)。 */
505
+ export const SESSION_ROWS_MAX_AGE_MS = 30_000;
506
+ /** 按宿主上下文隔离的会话列举缓存(测试里每个替身 ctx 互不干扰)。 */
507
+ let sessionRowsCache = new WeakMap();
508
+ /** 清空会话列举缓存与 `/tree` 载荷合并器(由 {@link clearScanCache} 一并调用)。 */
509
+ function clearSessionRowsCache() {
510
+ sessionRowsCache = new WeakMap();
511
+ treeFlightEpoch += 1;
512
+ }
513
+ /**
514
+ * 活会话 id 集合签名:`ctx.sessions.list()` 是纯内存操作(宿主 SessionStore),
515
+ * 新建 / 关闭会话会立即改变它 —— 用它作为「会话集合变了」的廉价信号。
516
+ */
517
+ function liveSessionSignature(ctx) {
518
+ const sessions = getService(ctx, 'sessions');
519
+ if (typeof sessions?.list !== 'function')
520
+ return '';
521
+ try {
522
+ const list = sessions.list.call(sessions);
523
+ if (!Array.isArray(list))
524
+ return '';
525
+ const ids = [];
526
+ for (const entry of list) {
527
+ if (typeof entry !== 'object' || entry === null)
528
+ continue;
529
+ const id = nonEmptyString(entry.id)
530
+ ?? nonEmptyString(entry.header?.id)
531
+ ?? nonEmptyString(entry.sessionId);
532
+ if (id !== undefined)
533
+ ids.push(id);
534
+ }
535
+ return ids.sort().join('\u0000');
536
+ }
537
+ catch {
538
+ return '';
539
+ }
540
+ }
541
+ /** 用宿主 `agents` 服务(纯内存)刷新缓存行的运行态;服务缺席时保持原值。 */
542
+ function refreshRunning(ctx, rows) {
543
+ const agents = getService(ctx, 'agents');
544
+ if (typeof agents?.get !== 'function')
545
+ return;
546
+ for (const row of rows) {
547
+ try {
548
+ row.running = agents.get(row.sessionId)?.status === 'running';
549
+ }
550
+ catch {
551
+ // 单条失败保持原值
552
+ }
553
+ }
554
+ }
555
+ /**
556
+ * 带缓存的 {@link buildSessionRows}。
557
+ *
558
+ * 根因(实测):`sessionController.list()` 与 `sessionPersistence.list()` 各自全量扫一遍
559
+ * 会话目录(读每个文件首行 + stat),3753 个会话时单次 `/tree` 约 0.7–1.4 s。
560
+ * 复用条件(全部满足):
561
+ * - 自上次列举以来**没有**任何宿主 `session/event`({@link sessionActivityVersion} 未变);
562
+ * - 活会话 id 集合未变(新建 / 关闭会话立即失效);
563
+ * - 未超过 {@link SESSION_ROWS_MAX_AGE_MS}。
564
+ * 复用时仍重算 `lastActivityAt` 与运行态(都只读内存)。
565
+ */
566
+ async function cachedSessionRows(ctx, now, signal) {
567
+ const version = sessionActivityVersion();
568
+ const live = liveSessionSignature(ctx);
569
+ const entry = sessionRowsCache.get(ctx);
570
+ if (entry !== undefined &&
571
+ entry.activityVersion === version &&
572
+ entry.liveSignature === live &&
573
+ now >= entry.builtAt &&
574
+ now - entry.builtAt < SESSION_ROWS_MAX_AGE_MS) {
575
+ refreshRunning(ctx, entry.rows);
576
+ attachLastActivityTimes(entry.rows);
577
+ return entry.rows;
578
+ }
579
+ const { rows } = await buildSessionRows(ctx, signal);
580
+ sessionRowsCache.set(ctx, { builtAt: now, activityVersion: version, liveSignature: live, rows });
581
+ return rows;
582
+ }
583
+ /** 默认台账存储(模块级单例;`createFileLedger()` 构造期不做任何 IO)。 */
584
+ let defaultLedger;
585
+ /** `dshHomePath` 所在的包名(宿主包,**不可静态 import**;见 §2.5 / §C14)。 */
586
+ const DSH_HOME_PATHS_MODULE = '@deepseek-ai/dsh-home-paths';
587
+ /** 台账文件名(与 `ledger.ts` 保持一致)。 */
588
+ const LEDGER_FILE_NAME = 'worktree-groups.json';
589
+ /**
590
+ * 解析台账家目录,**优先 `dshHomePath('worktree-groups.json')`**(§2.7 裁定 9)。
591
+ *
592
+ * 背景(宿主契约 §A5.1 实测):
593
+ * - `defaultDshHome()` = `homedir()/.dsh`,**不读 `$DSH_HOME`**;
594
+ * - `dshHomePath(...)` = `resolveDshHome()` + join,**会读 `$DSH_HOME``。
595
+ *
596
+ * `ledger.ts`(T2 所有,本任务不改)只查了 `defaultDshHome()`。本该由 T2 补的第一级
597
+ * 回退在这里补上:惰性动态 import(变量说明符,避免 tsc 解析),拿到 `dshHomePath`
598
+ * 就取它的目录。失败时返回 `undefined`,让 `createFileLedger()` 走它自己的
599
+ * `defaultDshHome()` → `$DSH_HOME` → `~/.dsh` 回退链 —— **两级回退都被保留**。
600
+ *
601
+ * 之所以放在这里而不是 `ledger.ts`:文件所有权(§0)规定 `ledger.ts` 属 T2,
602
+ * 本任务不得改动;`routes.ts` 是台账的**唯一组装入口**,在这里注入等价且没有写者冲突。
603
+ */
604
+ async function resolveLedgerHome() {
605
+ try {
606
+ const specifier = DSH_HOME_PATHS_MODULE;
607
+ const mod = (await import(specifier));
608
+ const fn = mod.dshHomePath;
609
+ if (typeof fn !== 'function')
610
+ return undefined;
611
+ const file = fn(LEDGER_FILE_NAME);
612
+ if (typeof file !== 'string' || file === '')
613
+ return undefined;
614
+ return dirname(file);
615
+ }
616
+ catch {
617
+ // 包不可解析 / 导出形态变化 ⇒ 返回 undefined,交给 createFileLedger() 的两级回退
618
+ return undefined;
619
+ }
620
+ }
621
+ /**
622
+ * 取默认台账存储(懒构造)。
623
+ *
624
+ * 构造期已 await(动态 import 是异步的),所以把它包成一个 Promise 单例:
625
+ * `createFileLedger()` 本身**不做任何 IO**,只是记住 home 目录,因此这里 await
626
+ * 一次模块解析不会引入任何磁盘访问。
627
+ */
628
+ let defaultLedgerPromise;
629
+ /** 取默认台账存储(惰性;首次调用解析 home,之后复用同一实例)。 */
630
+ async function ledgerStore() {
631
+ defaultLedger ??= undefined;
632
+ if (defaultLedger !== undefined)
633
+ return defaultLedger;
634
+ defaultLedgerPromise ??= (async () => {
635
+ const home = await resolveLedgerHome();
636
+ return home === undefined ? createFileLedger() : createFileLedger(home);
637
+ })();
638
+ defaultLedger = await defaultLedgerPromise;
639
+ return defaultLedger;
640
+ }
641
+ /**
642
+ * 收集一次请求需要的全部宿主事实。
643
+ *
644
+ * 全部服务都是**惰性 + 可选**:任何一个缺席都只让对应部分为空,不抛错。
645
+ */
646
+ export async function collectSnapshot(ctx, options = {}) {
647
+ const now = options.now ?? Date.now();
648
+ const signal = options.signal;
649
+ const ledger = options.ledger ?? (await ledgerStore());
650
+ const { workspaces, registry } = loadWorkspaces(ctx);
651
+ const archivedSessionIds = loadArchivedSessionIds(registry);
652
+ const sessions = options.reuseSessions === true
653
+ ? await cachedSessionRows(ctx, now, signal)
654
+ : (await buildSessionRows(ctx, signal)).rows;
655
+ let ledgerData;
656
+ try {
657
+ ledgerData = await ledger.read();
658
+ }
659
+ catch {
660
+ ledgerData = { version: 1, projects: {}, sessions: {} };
661
+ }
662
+ // 候选扫描路径:全部工作区路径 + 台账里记录过的主树路径
663
+ // (后者用于「项目还在、但它的工作区已被注销」的场景,保证 history 桶仍有归属)。
664
+ const candidateSet = new Set();
665
+ for (const workspace of workspaces)
666
+ candidateSet.add(normalizePath(workspace.path));
667
+ for (const project of Object.values(ledgerData.projects)) {
668
+ const mainPath = nonEmptyString(project?.mainPath);
669
+ if (mainPath !== undefined)
670
+ candidateSet.add(normalizePath(mainPath));
671
+ }
672
+ const { repos, pathToCommonDir } = await scanRepos([...candidateSet], now, signal);
673
+ const repoByWorkspacePath = {};
674
+ const workspaceByPath = {};
675
+ for (const workspace of workspaces) {
676
+ const path = normalizePath(workspace.path);
677
+ // 同路径多个工作区时保留先出现的(与 tree-model 的「顺序即宿主持久顺序」一致)。
678
+ if (workspaceByPath[path] === undefined)
679
+ workspaceByPath[path] = workspace.workspaceId;
680
+ const direct = pathToCommonDir.get(path);
681
+ if (direct !== undefined) {
682
+ repoByWorkspacePath[path] = direct;
683
+ continue;
684
+ }
685
+ // 兜底:工作区落在某个已扫描仓的 worktree 里(或在主树路径上)。
686
+ for (const [commonDir, repo] of repos) {
687
+ if (normalizePath(repo.mainPath) === path) {
688
+ repoByWorkspacePath[path] = commonDir;
689
+ break;
690
+ }
691
+ if (repo.worktrees.some((entry) => normalizePath(entry.path) === path)) {
692
+ repoByWorkspacePath[path] = commonDir;
693
+ break;
694
+ }
695
+ }
696
+ }
697
+ const knownWorktreePaths = new Set();
698
+ const knownRepoPaths = new Set();
699
+ const mainPathByKnownPath = new Map();
700
+ const remember = (path, mainPath, isRepoEntry) => {
701
+ if (isRepoEntry)
702
+ knownRepoPaths.add(path);
703
+ else {
704
+ knownWorktreePaths.add(path);
705
+ knownRepoPaths.add(path);
706
+ }
707
+ if (!mainPathByKnownPath.has(path))
708
+ mainPathByKnownPath.set(path, mainPath);
709
+ };
710
+ for (const [commonDir, repo] of repos) {
711
+ const mainPath = normalizePath(repo.mainPath);
712
+ knownRepoPaths.add(normalizePath(commonDir));
713
+ knownRepoPaths.add(mainPath);
714
+ mainPathByKnownPath.set(normalizePath(commonDir), mainPath);
715
+ mainPathByKnownPath.set(mainPath, mainPath);
716
+ for (const entry of repo.worktrees)
717
+ remember(normalizePath(entry.path), mainPath, false);
718
+ // git 扫描的**入口路径**也要能反查到主树:macOS 的 /var → /private/var 符号链接
719
+ // 会让入口拼法与 `worktree list` 的拼法不同,二者都必须可用。
720
+ for (const [entryPath, common] of pathToCommonDir) {
721
+ if (common === commonDir)
722
+ remember(entryPath, mainPath, false);
723
+ }
724
+ }
725
+ for (const project of Object.values(ledgerData.projects)) {
726
+ const rawMainPath = nonEmptyString(project?.mainPath);
727
+ if (rawMainPath === undefined)
728
+ continue;
729
+ const mainPath = normalizePath(rawMainPath);
730
+ knownRepoPaths.add(mainPath);
731
+ if (!mainPathByKnownPath.has(mainPath))
732
+ mainPathByKnownPath.set(mainPath, mainPath);
733
+ for (const worktreePath of Object.keys(project?.worktrees ?? {})) {
734
+ remember(normalizePath(worktreePath), mainPath, false);
735
+ }
736
+ }
737
+ for (const workspace of workspaces) {
738
+ const path = normalizePath(workspace.path);
739
+ if (!knownWorktreePaths.has(path) && !knownRepoPaths.has(path)) {
740
+ knownWorktreePaths.add(path);
741
+ knownRepoPaths.add(path);
742
+ }
743
+ const repoKey = repoByWorkspacePath[path];
744
+ const repo = repoKey === undefined ? undefined : repos.get(repoKey);
745
+ const mainPath = repo === undefined ? path : normalizePath(repo.mainPath);
746
+ if (!mainPathByKnownPath.has(path))
747
+ mainPathByKnownPath.set(path, mainPath);
748
+ }
749
+ // 工作区路径的磁盘存在性:**用 fs.stat 实测**,不靠推断。
750
+ // 这是 D18 清扫与规则 2b 共同依赖的事实(扫描结果里只有 worktree 根,子目录工作区不在其中)。
751
+ const liveWorkspacePaths = new Set();
752
+ const nonMainWorkspacePaths = new Set();
753
+ // 正面证据(1):git 扫描里的**非主** worktree 路径。
754
+ for (const repo of repos.values()) {
755
+ for (const entry of repo.worktrees) {
756
+ if (!entry.isMain)
757
+ nonMainWorkspacePaths.add(normalizePath(entry.path));
758
+ }
759
+ }
760
+ // 正面证据(2):台账记过的 worktree 路径,且不等于该项目记录的 mainPath。
761
+ for (const project of Object.values(ledgerData.projects)) {
762
+ const rawMain = nonEmptyString(project?.mainPath);
763
+ const mainPath = rawMain === undefined ? undefined : normalizePath(rawMain);
764
+ for (const worktreePath of Object.keys(project?.worktrees ?? {})) {
765
+ const path = normalizePath(worktreePath);
766
+ if (mainPath !== undefined && path === mainPath)
767
+ continue;
768
+ nonMainWorkspacePaths.add(path);
769
+ }
770
+ }
771
+ // PERF:并行 stat(旧实现逐个 await)。
772
+ const workspacePaths = [...new Set(workspaces.map((workspace) => normalizePath(workspace.path)))];
773
+ const alive = await Promise.all(workspacePaths.map((path) => pathExists(path)));
774
+ workspacePaths.forEach((path, index) => {
775
+ if (alive[index] === true)
776
+ liveWorkspacePaths.add(path);
777
+ });
778
+ return {
779
+ workspaces,
780
+ repos: Object.fromEntries(repos),
781
+ repoByWorkspacePath,
782
+ ledger: ledgerData,
783
+ sessions,
784
+ archivedSessionIds,
785
+ workspaceByPath,
786
+ knownWorktreePaths,
787
+ knownRepoPaths,
788
+ mainPathByKnownPath,
789
+ liveWorkspacePaths,
790
+ nonMainWorkspacePaths,
791
+ };
792
+ }
793
+ /**
794
+ * **D18 自动清扫**:注销「目录已死」且「不是其仓主工作树」的 dsh 工作区记录。
795
+ *
796
+ * PRD D18(用户拍板):worktree 被外部 `rm -rf` 后,不应在侧栏留下一行死工作区;
797
+ * 其会话应由 `buildProjects` 的规则 3/4 归入该项目的 history 桶。
798
+ *
799
+ * 安全边界(与 D18 原文一致):
800
+ * - **只碰注册表,不碰磁盘、不碰会话日志**(`registry.delete` 只删一条记录);
801
+ * - **主仓自己的目录被删时不动它** —— 那多半是临时不可达或用户会重建,
802
+ * 自动注销会造成「重启后工作区莫名消失」;
803
+ * - 单个失败不中断整体(收集后返回,由调用方决定是否报告)。
804
+ *
805
+ * 返回**被成功注销**的 workspaceId 列表,便于调用方/测试断言。
806
+ */
807
+ export async function sweepDeadWorkspaces(ctx, snapshot) {
808
+ const registry = getService(ctx, 'workspaceRegistry');
809
+ const removed = [];
810
+ const failed = [];
811
+ if (typeof registry?.delete !== 'function')
812
+ return { removed, failed };
813
+ for (const workspace of snapshot.workspaces) {
814
+ const path = normalizePath(workspace.path);
815
+ if (snapshot.liveWorkspacePaths.has(path))
816
+ continue;
817
+ // 主工作树(或无法判定为非主树的路径)不自动注销。
818
+ if (!snapshot.nonMainWorkspacePaths.has(path))
819
+ continue;
820
+ try {
821
+ // `delete` 对未知 id 是幂等 no-op(返回 false);两种情况都算「记录已不在注册表里」。
822
+ await registry.delete(workspace.workspaceId);
823
+ removed.push(workspace.workspaceId);
824
+ }
825
+ catch (error) {
826
+ failed.push({ workspaceId: workspace.workspaceId, message: failMessage(error) });
827
+ }
828
+ }
829
+ return { removed, failed };
830
+ }
831
+ /**
832
+ * 组装 `POST /tree` 的完整载荷(导出以便脱离 HTTP 层做端到端验证)。
833
+ *
834
+ * 顺带把本次观察到的事实写回台账(首次/最近见到 worktree、已消失时刻、会话归属)。
835
+ * 台账写失败**不影响**响应(PRD R4:台账只是辅助归属信息)。
836
+ */
837
+ export async function buildTreePayload(ctx, options = {}, precomputed) {
838
+ const snapshot = await collectSnapshot(ctx, options);
839
+ // D18:先清扫「目录已死且非主工作树」的工作区记录,**再**合成树。
840
+ // 这样死工作区不会出现在本轮响应里,其会话随即由规则 3/4 落进 history 桶。
841
+ // 清扫失败不影响本轮渲染(规则 2 的 exists 校验已保证会话不会被扣在死节点上)。
842
+ const swept = await sweepDeadWorkspaces(ctx, snapshot);
843
+ if (swept.removed.length > 0 || swept.failed.length > 0) {
844
+ // 重新读一次注册表,让本轮响应反映清扫结果。
845
+ const refreshed = loadWorkspaces(ctx);
846
+ // **D8**:用「内容签名」判断是否真的变了,**不用长度**。
847
+ // 长度是代理指标:清扫删 1 个 + 宿主同轮新增 1 个 ⇒ 长度相等,旧写法会误判
848
+ // 「没变」而拿旧表渲染一轮(死工作区行多显示一次)。签名含 id/path/updatedAt,
849
+ // 成员增删、路径改写、重命名都能检出,且排序后与 `list()` 顺序无关。
850
+ if (workspaceSignature(refreshed.workspaces) !== workspaceSignature(snapshot.workspaces)) {
851
+ snapshot.workspaces = refreshed.workspaces;
852
+ snapshot.archivedSessionIds = loadArchivedSessionIds(refreshed.registry);
853
+ }
854
+ // 被注销的 workspaceId 必须从路径索引里摘掉 —— 这一步与「注册表内容是否变」
855
+ // 无关:`registry.delete()` 已成功,索引里的旧映射就是脏数据。
856
+ if (swept.removed.length > 0) {
857
+ for (const id of swept.removed) {
858
+ for (const [path, workspaceId] of Object.entries(snapshot.workspaceByPath)) {
859
+ if (workspaceId === id)
860
+ delete snapshot.workspaceByPath[path];
861
+ }
862
+ }
863
+ }
864
+ if (swept.failed.length > 0) {
865
+ try {
866
+ ctx.logger?.warn?.(`dsh-worktree-groups: D18 清扫有 ${swept.failed.length} 个工作区注销失败:${swept.failed
867
+ .map((item) => `${item.workspaceId}(${item.message})`)
868
+ .join('; ')}`);
869
+ }
870
+ catch {
871
+ // logger 不可用:忽略
872
+ }
873
+ }
874
+ }
875
+ const input = {
876
+ workspaces: snapshot.workspaces,
877
+ repos: snapshot.repos,
878
+ repoByWorkspacePath: snapshot.repoByWorkspacePath,
879
+ ledger: snapshot.ledger,
880
+ sessions: snapshot.sessions,
881
+ archivedSessionIds: snapshot.archivedSessionIds,
882
+ liveWorkspacePaths: snapshot.liveWorkspacePaths,
883
+ };
884
+ const built = precomputed ?? buildProjects(input);
885
+ // ⚠️ WSR2:必须在过滤掉已归档工作空间**之前**用全量 `built.projects` 计算 `ungrouped`,
886
+ // 这样归属到已归档工作空间的会话已被该工作空间认领,绝不会漏进「未分组」。
887
+ const ungrouped = collectUngrouped(input, built.projects);
888
+ try {
889
+ await updateLedger(snapshot, options, built.projects);
890
+ }
891
+ catch {
892
+ // 台账写失败不阻塞渲染。
893
+ }
894
+ const archivedMap = snapshot.ledger.archivedProjects ?? {};
895
+ const activeProjects = [];
896
+ const archivedRows = [];
897
+ const seenArchivedKeys = new Set();
898
+ for (const project of built.projects) {
899
+ const entry = archivedMap[project.key];
900
+ if (entry === undefined) {
901
+ activeProjects.push(project);
902
+ continue;
903
+ }
904
+ seenArchivedKeys.add(project.key);
905
+ const fallbackPath = project.mainPath ??
906
+ project.worktrees[0]?.path ??
907
+ (project.key.startsWith('ws:')
908
+ ? snapshot.workspaces.find((w) => `ws:${w.workspaceId}` === project.key)?.path
909
+ : undefined);
910
+ const resolvedPath = entry.path ?? fallbackPath;
911
+ archivedRows.push({
912
+ key: project.key,
913
+ title: project.title !== '' ? project.title : entry.title,
914
+ ...(resolvedPath === undefined ? {} : { path: resolvedPath }),
915
+ isGit: project.isGit,
916
+ archivedAt: entry.archivedAt,
917
+ });
918
+ }
919
+ for (const [key, entry] of Object.entries(archivedMap)) {
920
+ if (seenArchivedKeys.has(key))
921
+ continue;
922
+ archivedRows.push({
923
+ key,
924
+ title: entry.title,
925
+ ...(entry.path === undefined ? {} : { path: entry.path }),
926
+ isGit: entry.isGit,
927
+ archivedAt: entry.archivedAt,
928
+ });
929
+ }
930
+ archivedRows.sort((a, b) => (b.archivedAt !== a.archivedAt ? b.archivedAt - a.archivedAt : a.key.localeCompare(b.key)));
931
+ return {
932
+ ok: true,
933
+ projects: activeProjects,
934
+ ungrouped,
935
+ archivedSessionIds: snapshot.archivedSessionIds,
936
+ workspaceByPath: snapshot.workspaceByPath,
937
+ archivedProjects: archivedRows,
938
+ };
939
+ }
940
+ /**
941
+ * 归档一个工作空间(2026-10-21 WSR1/WSR2,AC7)。
942
+ *
943
+ * 将 `projectKey` 记入台账 `archivedProjects`;保留宿主 `workspaceRegistry` 记录不销毁,
944
+ * 使恢复(设置页放出或重新添加同目录)后标题、worktree 与会话原样归位。
945
+ */
946
+ export async function archiveWorkspaceProject(ctx, projectKey, options = {}) {
947
+ const key = projectKey.trim();
948
+ if (key === '')
949
+ return { ok: false, archivedProjects: {} };
950
+ const now = options.now ?? Date.now();
951
+ const ledger = options.ledger ?? (await ledgerStore());
952
+ const snapshot = await collectSnapshot(ctx, options);
953
+ const built = buildProjects({
954
+ workspaces: snapshot.workspaces,
955
+ repos: snapshot.repos,
956
+ repoByWorkspacePath: snapshot.repoByWorkspacePath,
957
+ ledger: snapshot.ledger,
958
+ sessions: snapshot.sessions,
959
+ archivedSessionIds: snapshot.archivedSessionIds,
960
+ liveWorkspacePaths: snapshot.liveWorkspacePaths,
961
+ });
962
+ const matched = built.projects.find((p) => p.key === key);
963
+ const wsPath = key.startsWith('ws:')
964
+ ? snapshot.workspaces.find((w) => `ws:${w.workspaceId}` === key)?.path
965
+ : undefined;
966
+ const path = matched?.mainPath ?? matched?.worktrees[0]?.path ?? wsPath;
967
+ const title = matched?.title ?? (path !== undefined ? basename(path) : key);
968
+ const isGit = matched?.isGit ?? !key.startsWith('ws:');
969
+ const updated = await ledger.update((current) => {
970
+ const nextArchived = {
971
+ ...(current.archivedProjects ?? {}),
972
+ [key]: {
973
+ title,
974
+ ...(path === undefined ? {} : { path }),
975
+ isGit,
976
+ archivedAt: now,
977
+ },
978
+ };
979
+ return {
980
+ ...current,
981
+ archivedProjects: nextArchived,
982
+ };
983
+ });
984
+ return { ok: true, archivedProjects: updated.archivedProjects ?? {} };
985
+ }
986
+ /**
987
+ * 放出(取消归档)工作空间(2026-10-21 WSR2,AC7)。
988
+ *
989
+ * 支持两种匹配方式:
990
+ * 1. `target.projectKey`:设置页点击「放出」时直接按项目键解除归档;
991
+ * 2. `target.path`:用户在首页或侧栏重新添加相同目录(或同 git 仓库下的任意 worktree 目录)
992
+ * 作为工作空间时,自动识别并解除该项目的归档状态。
993
+ */
994
+ export async function unarchiveWorkspaceProject(ctx, target, options = {}) {
995
+ const ledger = options.ledger ?? (await ledgerStore());
996
+ const currentLedger = await ledger.read();
997
+ const archivedMap = currentLedger.archivedProjects ?? {};
998
+ if (Object.keys(archivedMap).length === 0) {
999
+ return { ok: true, unarchivedKeys: [] };
1000
+ }
1001
+ const keysToRemove = new Set();
1002
+ if (typeof target.projectKey === 'string' && target.projectKey.trim() !== '') {
1003
+ const directKey = target.projectKey.trim();
1004
+ if (archivedMap[directKey] !== undefined)
1005
+ keysToRemove.add(directKey);
1006
+ }
1007
+ if (typeof target.path === 'string' && target.path.trim() !== '') {
1008
+ const normPath = normalizePath(target.path.trim());
1009
+ const realNormPath = await realpath(normPath)
1010
+ .then((resolved) => normalizePath(resolved))
1011
+ .catch(() => normPath);
1012
+ const candidatePaths = new Set([normPath, realNormPath]);
1013
+ const snapshot = await collectSnapshot(ctx, options);
1014
+ // 1. 直接匹配已归档条目的 path
1015
+ for (const [key, entry] of Object.entries(archivedMap)) {
1016
+ if (entry.path !== undefined && candidatePaths.has(normalizePath(entry.path))) {
1017
+ keysToRemove.add(key);
1018
+ }
1019
+ }
1020
+ // 2. 匹配已注册工作区路径对应的 ws:<id> 或 commonDir
1021
+ for (const ws of snapshot.workspaces) {
1022
+ const wsNorm = normalizePath(ws.path);
1023
+ if (candidatePaths.has(wsNorm)) {
1024
+ const wsKey = `ws:${ws.workspaceId}`;
1025
+ if (archivedMap[wsKey] !== undefined)
1026
+ keysToRemove.add(wsKey);
1027
+ const repoKey = snapshot.repoByWorkspacePath[wsNorm];
1028
+ if (repoKey !== undefined && archivedMap[repoKey] !== undefined)
1029
+ keysToRemove.add(repoKey);
1030
+ }
1031
+ }
1032
+ // 3. 匹配已知 git 仓库的 mainPath 或任一 worktree 路径
1033
+ for (const [commonDir, repo] of Object.entries(snapshot.repos)) {
1034
+ if (archivedMap[commonDir] === undefined)
1035
+ continue;
1036
+ if (candidatePaths.has(normalizePath(repo.mainPath)) ||
1037
+ repo.worktrees.some((wt) => candidatePaths.has(normalizePath(wt.path)))) {
1038
+ keysToRemove.add(commonDir);
1039
+ }
1040
+ }
1041
+ // 4. 若该路径是尚未注册的新 worktree 目录,尝试直接跑一次 scanRepo 反查 commonDir
1042
+ if (keysToRemove.size === 0) {
1043
+ try {
1044
+ const scanned = await scanRepo(normPath, options.signal);
1045
+ if (scanned !== null && archivedMap[scanned.commonDir] !== undefined) {
1046
+ keysToRemove.add(scanned.commonDir);
1047
+ }
1048
+ }
1049
+ catch {
1050
+ // 忽略扫描异常
1051
+ }
1052
+ }
1053
+ }
1054
+ if (keysToRemove.size === 0) {
1055
+ return { ok: true, unarchivedKeys: [] };
1056
+ }
1057
+ await ledger.update((current) => {
1058
+ const prior = current.archivedProjects;
1059
+ if (prior === undefined)
1060
+ return current;
1061
+ const nextArchived = {};
1062
+ let removed = false;
1063
+ for (const [k, v] of Object.entries(prior)) {
1064
+ if (keysToRemove.has(k)) {
1065
+ removed = true;
1066
+ continue;
1067
+ }
1068
+ nextArchived[k] = v;
1069
+ }
1070
+ if (!removed)
1071
+ return current;
1072
+ const next = {
1073
+ version: 1,
1074
+ projects: current.projects,
1075
+ sessions: current.sessions,
1076
+ };
1077
+ if (Object.keys(nextArchived).length > 0) {
1078
+ next.archivedProjects = nextArchived;
1079
+ }
1080
+ return next;
1081
+ });
1082
+ return { ok: true, unarchivedKeys: [...keysToRemove] };
1083
+ }
1084
+ /**
1085
+ * 把本次观察写回台账。
1086
+ *
1087
+ * - `projects[commonDir].worktrees[path]`:首次见到填 `firstSeenAt = lastSeenAt = now`;
1088
+ * 再次见到刷新 `lastSeenAt`(并清除 `goneAt` —— 目录又被建回来了);
1089
+ * `exists === false` 时首次设置 `goneAt`。
1090
+ * - `sessions[sessionId] = { projectKey, worktreePath }`:只记录**本次确实归到某个
1091
+ * 活 worktree** 的会话;history 桶里的会话保留台账原值(否则会把历史归属覆盖成空)。
1092
+ */
1093
+ /** 台账 `lastSeenAt` 的刷新粒度(2026-11-14 PERF2):同一 worktree 至多每小时写一次。 */
1094
+ export const LEDGER_LAST_SEEN_REFRESH_MS = 60 * 60_000;
1095
+ async function updateLedger(snapshot, options, projects) {
1096
+ const ledger = options.ledger ?? (await ledgerStore());
1097
+ const now = options.now ?? Date.now();
1098
+ await ledger.update((current) => {
1099
+ let changed = false;
1100
+ const next = {
1101
+ version: 1,
1102
+ projects: { ...current.projects },
1103
+ sessions: { ...current.sessions },
1104
+ ...(current.archivedProjects === undefined
1105
+ ? {}
1106
+ : { archivedProjects: { ...current.archivedProjects } }),
1107
+ };
1108
+ for (const [commonDir, repo] of Object.entries(snapshot.repos)) {
1109
+ const existing = next.projects[commonDir];
1110
+ const worktrees = { ...(existing?.worktrees ?? {}) };
1111
+ for (const entry of repo.worktrees) {
1112
+ const path = normalizePath(entry.path);
1113
+ const prior = worktrees[path];
1114
+ if (prior === undefined) {
1115
+ worktrees[path] = {
1116
+ ...(entry.branch === undefined ? {} : { branch: entry.branch }),
1117
+ firstSeenAt: now,
1118
+ lastSeenAt: now,
1119
+ ...(entry.exists ? {} : { goneAt: now }),
1120
+ };
1121
+ changed = true;
1122
+ continue;
1123
+ }
1124
+ // PERF2:`lastSeenAt` 节流到 {@link LEDGER_LAST_SEEN_REFRESH_MS} —— 旧实现每个请求都刷成
1125
+ // `now` ⇒ `changed` 恒真 ⇒ 每次 `/tree` 都 fsync 重写整份台账(实测 352 KB)。
1126
+ const lastSeenAt = now < prior.lastSeenAt || now - prior.lastSeenAt >= LEDGER_LAST_SEEN_REFRESH_MS ? now : prior.lastSeenAt;
1127
+ const patched = { ...prior, lastSeenAt };
1128
+ if (entry.branch !== undefined)
1129
+ patched.branch = entry.branch;
1130
+ if (entry.exists)
1131
+ delete patched.goneAt;
1132
+ else
1133
+ patched.goneAt ??= now;
1134
+ if (patched.lastSeenAt !== prior.lastSeenAt ||
1135
+ patched.branch !== prior.branch ||
1136
+ patched.goneAt !== prior.goneAt) {
1137
+ worktrees[path] = patched;
1138
+ changed = true;
1139
+ }
1140
+ }
1141
+ const mainPath = normalizePath(repo.mainPath);
1142
+ if (existing === undefined || existing.mainPath !== mainPath) {
1143
+ next.projects[commonDir] = { mainPath, worktrees };
1144
+ changed = true;
1145
+ }
1146
+ else if (changed) {
1147
+ next.projects[commonDir] = { mainPath, worktrees };
1148
+ }
1149
+ }
1150
+ // 会话归属:只登记**本次确实归到某个存在的 worktree** 的会话。
1151
+ // history 桶 / 未分组的会话保留台账原值 —— 否则会把历史归属覆盖掉。
1152
+ for (const project of projects) {
1153
+ if (!project.isGit)
1154
+ continue;
1155
+ for (const node of project.worktrees) {
1156
+ if (!node.exists)
1157
+ continue;
1158
+ for (const session of node.sessions) {
1159
+ const prior = next.sessions[session.sessionId];
1160
+ if (prior !== undefined && prior.projectKey === project.key && prior.worktreePath === node.path) {
1161
+ continue;
1162
+ }
1163
+ next.sessions[session.sessionId] = { projectKey: project.key, worktreePath: node.path };
1164
+ changed = true;
1165
+ }
1166
+ }
1167
+ }
1168
+ return changed ? next : current;
1169
+ });
1170
+ }
1171
+ /* ------------------------------------------------------------------ *
1172
+ * HTTP helpers(照抄宿主契约 §A3.3 / 参考项目 panel-routes.ts 的私有 helper)
1173
+ * ------------------------------------------------------------------ */
1174
+ /** 写 JSON 响应。 */
1175
+ function json(res, status, payload) {
1176
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
1177
+ res.end(JSON.stringify(payload));
1178
+ }
1179
+ /** 读请求体 JSON;解析失败或读流出错都 resolve 空对象(绝不 reject,否则请求悬挂)。 */
1180
+ function readBody(req) {
1181
+ return new Promise((resolve) => {
1182
+ const chunks = [];
1183
+ req.on('data', (c) => chunks.push(c));
1184
+ req.on('end', () => {
1185
+ try {
1186
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
1187
+ resolve(typeof parsed === 'object' && parsed !== null ? parsed : {});
1188
+ }
1189
+ catch {
1190
+ resolve({});
1191
+ }
1192
+ });
1193
+ req.on('error', () => resolve({}));
1194
+ });
1195
+ }
1196
+ /** 把任意异常收敛成响应体。 */
1197
+ function failMessage(error) {
1198
+ return error instanceof Error ? error.message : String(error);
1199
+ }
1200
+ /** 取请求体里的字符串字段(trim 后非空才算有值)。 */
1201
+ function bodyString(body, key) {
1202
+ const value = body[key];
1203
+ if (typeof value !== 'string')
1204
+ return undefined;
1205
+ const trimmed = value.trim();
1206
+ return trimmed === '' ? undefined : trimmed;
1207
+ }
1208
+ /**
1209
+ * 白名单精确匹配(合同 §1.5 硬要求)。
1210
+ *
1211
+ * **只做精确相等**,绝不做前缀匹配:`/a/b` 通过不代表 `/a/b/../..` 或 `/a/bc` 通过
1212
+ * (前缀匹配正是越权漏洞的常见来源)。归一化用 `normalizePath`(绝对化 + POSIX + 去尾斜杠),
1213
+ * 这也是本包内所有路径比较的唯一基准。
1214
+ */
1215
+ function assertKnown(rawPath, allowed, label) {
1216
+ if (typeof rawPath !== 'string' || rawPath.trim() === '') {
1217
+ return { ok: false, message: `缺少 ${label}` };
1218
+ }
1219
+ const path = normalizePath(rawPath);
1220
+ if (!allowed.has(path)) {
1221
+ return { ok: false, message: `${label} 不在已知集合内,拒绝访问:${path}` };
1222
+ }
1223
+ return { ok: true, path };
1224
+ }
1225
+ /** 目录是否存在(`fs.stat`)。 */
1226
+ async function pathExists(target) {
1227
+ try {
1228
+ await stat(target);
1229
+ return true;
1230
+ }
1231
+ catch {
1232
+ return false;
1233
+ }
1234
+ }
1235
+ /* ------------------------------------------------------------------ *
1236
+ * worktree-create / worktree-remove 的 git 层
1237
+ * ------------------------------------------------------------------ */
1238
+ /**
1239
+ * **D-N1**:传给 git 的位置参数(分支名 / ref / 路径)的安全校验。
1240
+ *
1241
+ * 为什么需要它:这些值由调用方指定,并直接拼进 `git worktree add` 的**参数数组**。
1242
+ * 数组形式本身挡住了 shell 注入,但**挡不住 git 自己的选项解析** —— 以 `-` 开头的值
1243
+ * 会被 git 当成选项执行。实测(git 2.54.0):`baseRef: "--no-checkout"` 会让
1244
+ * `git worktree add -b noc <target> --no-checkout` **成功返回**,但 worktree 里只有
1245
+ * `.git`、没有任何检出文件,而接口仍返回 `200 {ok:true}` 并自动注册成工作区。
1246
+ *
1247
+ * 规则刻意宽松:只挡**前导 `-`** 与 NUL / 换行。分支名合法地含有 `/`(`feature/ohos`)
1248
+ * 与 `.`(`release/6.1.20`),用「只允许字母数字」之类的白名单会砍掉正常用法。
1249
+ *
1250
+ * `src/panel-git.ts` 里移植过来的 `isSafeRef` **不在本包内**(已确认:`src/` 下只有
1251
+ * `git.ts`,无 `panel-git.ts`),故此处落地一个最小实现。
1252
+ */
1253
+ export function isSafeGitArg(value) {
1254
+ return value.length > 0 && !value.startsWith('-') && !/[\0\n\r]/.test(value);
1255
+ }
1256
+ /**
1257
+ * 把分支名净化为可做目录名的片段(PRD D7:`<主仓名>-<分支名 sanitize>`)。
1258
+ */
1259
+ export function sanitizeBranchForPath(branch) {
1260
+ const sanitized = branch.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
1261
+ return sanitized === '' ? 'worktree' : sanitized;
1262
+ }
1263
+ /** 默认目标路径:`<主仓父目录>/<主仓名>-<分支名 sanitize>`。 */
1264
+ export function defaultWorktreePath(mainPath, branch) {
1265
+ const normalized = normalizePath(mainPath);
1266
+ return join(dirname(normalized), `${basename(normalized)}-${sanitizeBranchForPath(branch)}`);
1267
+ }
1268
+ /**
1269
+ * **D5**:调用方显式传入的 `targetPath` 的安全校验。
1270
+ *
1271
+ * 为什么需要它:`repoPath` 走严格白名单,而**同样由调用方指定、后果更重**的
1272
+ * `targetPath`(git 会在那里铺开整个文件树,且成功后会被 `registry.create()` 自动
1273
+ * 注册成 dsh 工作区)此前零校验 —— 一条 POST 就能把 worktree 建到 `/tmp/evil/...`
1274
+ * 或仓外任意位置。客户端当前不传该参数(纯 API 面缺口),但后端必须同源收紧。
1275
+ *
1276
+ * 约束(与 {@link defaultWorktreePath} 的落点算法同构):
1277
+ * 1. 必须是**主仓父目录的直接子目录** —— `dirname(targetPath) === dirname(mainPath)`。
1278
+ * 这同时挡住 `/tmp/...`、仓内子路径、`..` 越狱(`normalizePath` 已解析过 `..`)。
1279
+ * 2. `basename(targetPath)` 必须先以 `basename(mainPath)` 开头(与默认推导的
1280
+ * `<主仓名>-<后缀>` 形态一致),避免在用户的项目目录里凭空多出一个无关名字。
1281
+ * 3. 不得以 `.` 开头(挡住 `.git`、`.ssh` 之类隐藏目录)。
1282
+ *
1283
+ * **D-N2**:以上三条都基于 `normalizePath`(`path.resolve`,**只做词法归一、不解析
1284
+ * 符号链接**),因此「攻击者先在主仓父目录下建一个指向仓外的符号链接
1285
+ * `demo-repo-evil-link -> /仓外目录`」这条路径词法上完全合法 ⇒ 校验通过 ⇒ git 把整个
1286
+ * worktree 铺到**链接真身**(仓外),D-5 被绕过。修复方式是让调用方把**已 realpath
1287
+ * 解析的主仓父目录**通过 `parentReal` 传进来(见 {@link resolveParentReal}),并以它为准
1288
+ * 做第 1 条比较。这样:
1289
+ * - 父目录是符号链接 ⇒ 解析后的真实父目录 ≠ 主仓真实父目录 ⇒ 拒绝;
1290
+ * - 父目录不存在 / `realpath` 抛错 ⇒ 由调用方拒绝,绝不静默放行。
1291
+ *
1292
+ * `parentReal` 是**可选第三参**:缺省时退回原词法行为,既有单测的「9 类拒绝 + 放行」
1293
+ * 用例无需改签名即可继续通过。
1294
+ *
1295
+ * 不要求 `targetPath` **等于**默认推导路径:那会砍掉「同名不同后缀」的合法用法,
1296
+ * 超出本缺陷的修复范围。
1297
+ *
1298
+ * @param raw 调用方给的原始 `targetPath`(已由 `bodyString` 取成非空字符串)。
1299
+ * @param mainPath 已解析出的主工作树路径。
1300
+ * @param parentReal 可选的**已 realpath 解析**的主仓父目录(见 D-N2)。
1301
+ * @returns 归一化后的路径,或拒绝原因。
1302
+ */
1303
+ export function validateTargetPath(raw, mainPath, parentReal) {
1304
+ const main = normalizePath(mainPath);
1305
+ const parent = dirname(main);
1306
+ const target = normalizePath(raw);
1307
+ const label = 'targetPath';
1308
+ // **D-N2**:调用方解析过符号链接时(`parentReal` 给的是**真身**父目录),判据必须落在
1309
+ // realpath 空间 —— 词法比较挡不住「父目录是指向仓外的符号链接」:攻击者在主仓父目录下
1310
+ // 建一个 `demo-repo-evil-link -> /仓外目录`,词法上完全合法(同父目录 + 主仓名前缀)
1311
+ // ⇒ 校验通过 ⇒ git 把整个 worktree 铺到链接真身,D-5 被绕过。
1312
+ //
1313
+ // 目标也归一到**真身拼法**(父目录取真身、叶子名原样保留),因此返回的 `path` 可直接
1314
+ // 交给 git,且与 `git worktree list` 回的 realpath 拼法一致(回填更稳)。
1315
+ const effectiveParent = parentReal === undefined ? parent : normalizePath(parentReal);
1316
+ const effectiveTarget = parentReal === undefined ? target : join(effectiveParent, basename(target));
1317
+ if (effectiveTarget === main) {
1318
+ return { ok: false, message: `${label} 不能等于主仓路径:${effectiveTarget}` };
1319
+ }
1320
+ if (dirname(effectiveTarget) !== effectiveParent) {
1321
+ return {
1322
+ ok: false,
1323
+ message: `${label} 必须是主仓父目录的直接子目录(${effectiveParent}),拒绝:${effectiveTarget}`,
1324
+ };
1325
+ }
1326
+ const name = basename(effectiveTarget);
1327
+ if (name === '' || name.startsWith('.')) {
1328
+ return { ok: false, message: `${label} 的目录名非法(不得为空或以 . 开头):${effectiveTarget}` };
1329
+ }
1330
+ if (!name.startsWith(basename(main))) {
1331
+ return {
1332
+ ok: false,
1333
+ message: `${label} 的目录名必须以主仓名开头(${basename(main)}),拒绝:${effectiveTarget}`,
1334
+ };
1335
+ }
1336
+ return { ok: true, path: effectiveTarget };
1337
+ }
1338
+ /**
1339
+ * **D-N2**:解析「`targetPath` 的父目录」与「主仓路径」的**真实路径**(`realpath`),
1340
+ * 供 {@link validateTargetPath} 的第三参做符号链接安全的比较。
1341
+ *
1342
+ * 为什么解析**父目录**而不是目标本身:目标目录**还不存在**,`realpath(target)` 必然 ENOENT。
1343
+ *
1344
+ * 全部失败路径都返回 `{ ok: false }`,**绝不**退化成放行:
1345
+ * - 目标路径本身已存在且是**符号链接** ⇒ 拒绝(必须用 `lstat`:`stat` 会跟随链接,
1346
+ * 看不出它是链接);
1347
+ * - 目标父目录不存在 / 无权限 / `realpath` 抛错 ⇒ 拒绝;
1348
+ * - 主仓父目录 `realpath` 失败 ⇒ 拒绝;
1349
+ * - 解析后两个**真实**父目录不相等(父目录是符号链接,或路径中某一级指向别处)⇒ 拒绝。
1350
+ *
1351
+ * 通过时返回真身空间的 `mainPathReal` / `parentReal`:前者保证「等于主仓自身」这条判据
1352
+ * 也在 realpath 空间成立,后者就是允许落点。
1353
+ */
1354
+ async function resolveRealTargetParents(rawTarget, mainPath) {
1355
+ const target = normalizePath(rawTarget);
1356
+ const targetParent = dirname(target);
1357
+ // (1) 目标本身已存在且是符号链接 ⇒ 拒绝(`lstat`;`stat` 会跟随链接而看不出)。
1358
+ try {
1359
+ const info = await lstat(target);
1360
+ if (info.isSymbolicLink()) {
1361
+ return { ok: false, message: `targetPath 已存在且是符号链接,拒绝:${target}` };
1362
+ }
1363
+ }
1364
+ catch {
1365
+ // ENOENT:目标还不存在 —— 这是唯一合法的常态,继续校验它的父目录。
1366
+ }
1367
+ // (2) 父目录必须存在且可解析;`realpath` 抛错(ENOENT / 权限)⇒ 拒绝。
1368
+ let targetParentReal;
1369
+ try {
1370
+ targetParentReal = await realpath(targetParent);
1371
+ }
1372
+ catch (error) {
1373
+ return {
1374
+ ok: false,
1375
+ message: `targetPath 的父目录不可用(不存在或无权访问),拒绝:${targetParent}(${failMessage(error)})`,
1376
+ };
1377
+ }
1378
+ // (3) 主仓父目录同理;它就是「允许落点」的真身基准。
1379
+ const main = normalizePath(mainPath);
1380
+ const mainParent = dirname(main);
1381
+ let mainParentReal;
1382
+ try {
1383
+ mainParentReal = await realpath(mainParent);
1384
+ }
1385
+ catch (error) {
1386
+ return {
1387
+ ok: false,
1388
+ message: `主仓父目录不可解析,拒绝:${mainParent}(${failMessage(error)})`,
1389
+ };
1390
+ }
1391
+ // (4) 两边都解析到真身后再比较 —— 这一步才是挡住符号链接的地方。
1392
+ const parentReal = normalizePath(targetParentReal);
1393
+ const resolvedMainParent = normalizePath(mainParentReal);
1394
+ if (parentReal !== resolvedMainParent) {
1395
+ return {
1396
+ ok: false,
1397
+ message: `targetPath 的父目录经符号链接解析后不是主仓父目录(${resolvedMainParent}),拒绝:${target}`,
1398
+ };
1399
+ }
1400
+ return { ok: true, mainPathReal: join(parentReal, basename(main)), parentReal };
1401
+ }
1402
+ /**
1403
+ * 在 `repoPath` 下建 worktree,并返回 git 实际落盘的路径。
1404
+ *
1405
+ * `createBranch !== false` ⇒ `-b <branch>`(可选 `baseRef` 作起点);否则检出**已有**分支。
1406
+ *
1407
+ * **D-N1**:`branch` / `baseRef` / `targetPath` 都是调用方指定的值,写进数组前一律过
1408
+ * {@link isSafeGitArg}(挡住前导 `-`,即 git 选项注入);并在 revision 与 pathspec 之间
1409
+ * 加 `--` 分隔符,让任何仍以 `-` 开头的值被 git 当作**ref** 报 `invalid reference`,
1410
+ * 而不是当成选项执行。
1411
+ *
1412
+ * `--` 的兼容性已在 fixture 上实测(git 2.54.0):`worktree add -b <b> -- <path> [<ref>]`
1413
+ * 与 `worktree add -- <path> <branch>` 两种形态对 `HEAD` / 合法分支名(含 `/`)/ 合法 tag
1414
+ * 起点**全部正常**;而 `<path>` 之后的值不再被解析成选项
1415
+ * (`--no-checkout` ⇒ `fatal: invalid reference`,且**不创建目录**)。
1416
+ */
1417
+ async function gitWorktreeAdd(repoPath, branch, createBranch, targetPath, baseRef, signal) {
1418
+ if (!isSafeGitArg(branch)) {
1419
+ throw new Error(`branch 非法(不得为空或以 - 开头,且不得含控制字符):${JSON.stringify(branch)}`);
1420
+ }
1421
+ if (!isSafeGitArg(targetPath)) {
1422
+ throw new Error(`targetPath 非法(不得为空或以 - 开头,且不得含控制字符):${JSON.stringify(targetPath)}`);
1423
+ }
1424
+ if (baseRef !== undefined && !isSafeGitArg(baseRef)) {
1425
+ throw new Error(`baseRef 非法(不得为空或以 - 开头,且不得含控制字符):${JSON.stringify(baseRef)}`);
1426
+ }
1427
+ const args = createBranch
1428
+ ? ['worktree', 'add', '-b', branch, '--', targetPath, ...(baseRef === undefined ? [] : [baseRef])]
1429
+ : ['worktree', 'add', '--', targetPath, branch];
1430
+ await runGit(repoPath, args, signal);
1431
+ // git 会规范化路径(符号链接 / 大小写 / 相对化),以它的列表为准回填真实路径。
1432
+ try {
1433
+ const listing = await runGit(repoPath, ['worktree', 'list', '--porcelain'], signal);
1434
+ const wanted = normalizePath(targetPath);
1435
+ for (const line of listing.split('\n')) {
1436
+ if (!line.startsWith('worktree '))
1437
+ continue;
1438
+ const candidate = normalizePath(line.slice('worktree '.length));
1439
+ if (candidate === wanted)
1440
+ return candidate;
1441
+ }
1442
+ }
1443
+ catch {
1444
+ // 列表读不到:退回归一化后的目标路径(worktree 已建成,不该因此报失败)。
1445
+ }
1446
+ return normalizePath(targetPath);
1447
+ }
1448
+ /* ------------------------------------------------------------------ *
1449
+ * reveal
1450
+ * ------------------------------------------------------------------ */
1451
+ /** 当前平台标识(注入点便于测试)。 */
1452
+ function currentPlatform() {
1453
+ return process.platform;
1454
+ }
1455
+ /**
1456
+ * 在文件管理器中定位路径(macOS `open -R`;Windows `explorer /select,`;其余 `xdg-open`)。
1457
+ *
1458
+ * 全部走 `execFile` 数组参数,**不经 shell**。Linux 的 `xdg-open` 没有「选中」语义,
1459
+ * 按契约降级为打开**所在目录**(目标是文件时)。
1460
+ */
1461
+ async function revealPath(path, platform) {
1462
+ if (platform === 'darwin') {
1463
+ await execFileAsync('open', ['-R', path]);
1464
+ return;
1465
+ }
1466
+ if (platform === 'win32') {
1467
+ await execFileAsync('explorer', [`/select,${path}`]);
1468
+ return;
1469
+ }
1470
+ let target = path;
1471
+ try {
1472
+ const info = await stat(path);
1473
+ if (!info.isDirectory())
1474
+ target = dirname(path);
1475
+ }
1476
+ catch {
1477
+ target = dirname(path);
1478
+ }
1479
+ await execFileAsync('xdg-open', [target]);
1480
+ }
1481
+ /** `execFile` 的 Promise 化(数组参数,无 shell)。 */
1482
+ function execFileAsync(file, args) {
1483
+ return new Promise((resolve, reject) => {
1484
+ execFile(file, [...args], { windowsHide: true }, (error) => {
1485
+ if (error !== null)
1486
+ reject(error);
1487
+ else
1488
+ resolve();
1489
+ });
1490
+ });
1491
+ }
1492
+ /** 递增即让既有合并器丢弃在途 / 排队的旧计算(测试用 {@link clearScanCache} 触发)。 */
1493
+ let treeFlightEpoch = 0;
1494
+ /**
1495
+ * 「加入下一次」式合并器:空闲时立即开始;忙时所有新调用共享**一个**排队计算,
1496
+ * 它在当前计算结束后才开始 ⇒ 结果一定反映调用方到达之前的状态,且不会堆积。
1497
+ */
1498
+ function createTreeFlight(task) {
1499
+ let running;
1500
+ let queued;
1501
+ let epoch = treeFlightEpoch;
1502
+ const start = () => {
1503
+ const current = task();
1504
+ running = current;
1505
+ const settle = () => {
1506
+ if (running === current)
1507
+ running = undefined;
1508
+ };
1509
+ current.then(settle, settle);
1510
+ return current;
1511
+ };
1512
+ return () => {
1513
+ if (epoch !== treeFlightEpoch) {
1514
+ epoch = treeFlightEpoch;
1515
+ running = undefined;
1516
+ queued = undefined;
1517
+ }
1518
+ if (running === undefined)
1519
+ return start();
1520
+ if (queued === undefined) {
1521
+ const next = running.then(() => undefined, () => undefined).then(() => {
1522
+ if (queued === next)
1523
+ queued = undefined;
1524
+ return start();
1525
+ });
1526
+ queued = next;
1527
+ }
1528
+ return queued;
1529
+ };
1530
+ }
1531
+ /** 取请求的 `If-None-Match`(缺失返回 `undefined`)。 */
1532
+ function ifNoneMatch(req) {
1533
+ const value = req.headers?.['if-none-match'];
1534
+ return typeof value === 'string' && value !== '' ? value : undefined;
1535
+ }
1536
+ /**
1537
+ * 注册全部 HTTP 路由。前缀统一 `/dsh-worktree-groups/`(契约 §1.5)。
1538
+ *
1539
+ * 每个路由用独立的 `ctx.effect` 包裹,插件卸载时路由一并撤销(宿主契约硬约束 15)。
1540
+ * 每个 handler 内部再包一层 try/catch —— 双保险,保证任何异常都变成 JSON。
1541
+ */
1542
+ export function registerRoutes(ctx) {
1543
+ const webServer = getService(ctx, 'webServer');
1544
+ if (typeof webServer?.register !== 'function') {
1545
+ // webServer 缺席(非 web profile):静默降级,不抛错(PRD R6)。
1546
+ return;
1547
+ }
1548
+ // 2026-10-29 RAS2:监听宿主 `session/event` 记录每个会话的最后活动时间。
1549
+ // 刻意**不**用 `ctx.effect`:监听器的生命周期由 Cordis 上下文负责,返回的 disposer
1550
+ // 已足够;路由注册的 effect 数量因此仍是 5(§7 的注册契约测试逐字断言)。
1551
+ registerSessionActivityObserver(ctx);
1552
+ const register = (path, label, handler) => {
1553
+ ctx.effect(() => webServer.register?.({
1554
+ kind: 'exact',
1555
+ path,
1556
+ handler: async (req, res) => {
1557
+ try {
1558
+ await handler(req, res);
1559
+ }
1560
+ catch (error) {
1561
+ // 最后一道防线:handler 抛错时宿主只回 400 空体,客户端拿不到原因。
1562
+ if (!res.headersSent)
1563
+ json(res, 400, { ok: false, message: failMessage(error) });
1564
+ else
1565
+ res.end();
1566
+ }
1567
+ },
1568
+ }) ?? (() => undefined), `dsh-worktree-groups: ${label} route`);
1569
+ };
1570
+ // PERF1:`/tree` 计算合并器 —— 在途计算期间到达的请求共享**下一次**计算(保证看到
1571
+ // 自己到达之前的全部变更),同一时刻至多一个在途 + 一个排队。
1572
+ const treeFlight = createTreeFlight(async () => {
1573
+ const payload = await buildTreePayload(ctx, { reuseSessions: true });
1574
+ const body = JSON.stringify(payload);
1575
+ return { body, etag: `"${createHash('sha1').update(body).digest('base64url')}"` };
1576
+ });
1577
+ register(ROUTE_PATHS.tree, 'tree', async (req, res) => {
1578
+ const body = await readBody(req);
1579
+ try {
1580
+ const archiveProjectKey = bodyString(body, 'archiveProjectKey');
1581
+ const unarchiveProjectKey = bodyString(body, 'unarchiveProjectKey');
1582
+ const unarchivePath = bodyString(body, 'unarchivePath');
1583
+ if (archiveProjectKey !== undefined) {
1584
+ await archiveWorkspaceProject(ctx, archiveProjectKey);
1585
+ }
1586
+ if (unarchiveProjectKey !== undefined || unarchivePath !== undefined) {
1587
+ await unarchiveWorkspaceProject(ctx, {
1588
+ ...(unarchiveProjectKey === undefined ? {} : { projectKey: unarchiveProjectKey }),
1589
+ ...(unarchivePath === undefined ? {} : { path: unarchivePath }),
1590
+ });
1591
+ }
1592
+ const { body: text, etag } = await treeFlight();
1593
+ // PERF4:内容未变 ⇒ 304(客户端不重解析、不重渲染)。
1594
+ if (ifNoneMatch(req) === etag) {
1595
+ res.writeHead(304, { etag, 'cache-control': 'no-cache' });
1596
+ res.end();
1597
+ return;
1598
+ }
1599
+ res.writeHead(200, {
1600
+ 'content-type': 'application/json; charset=utf-8',
1601
+ etag,
1602
+ 'cache-control': 'no-cache',
1603
+ });
1604
+ res.end(text);
1605
+ }
1606
+ catch (error) {
1607
+ json(res, 400, { ok: false, message: failMessage(error) });
1608
+ }
1609
+ });
1610
+ register(ROUTE_PATHS.worktreeCreate, 'worktree-create', async (req, res) => {
1611
+ const body = await readBody(req);
1612
+ await handleWorktreeCreate(ctx, res, body);
1613
+ });
1614
+ register(ROUTE_PATHS.worktreeRemove, 'worktree-remove', async (req, res) => {
1615
+ const body = await readBody(req);
1616
+ await handleWorktreeRemove(ctx, res, body);
1617
+ });
1618
+ register(ROUTE_PATHS.reveal, 'reveal', async (req, res) => {
1619
+ const body = await readBody(req);
1620
+ await handleReveal(ctx, res, body);
1621
+ });
1622
+ register(ROUTE_PATHS.workspaceOpen, 'workspace-open', async (req, res) => {
1623
+ const body = await readBody(req);
1624
+ const path = bodyString(body, 'path');
1625
+ if (path === undefined)
1626
+ return json(res, 400, { ok: false, message: '缺少 path' });
1627
+ const registry = getService(ctx, 'workspaceRegistry');
1628
+ if (typeof registry?.create !== 'function') {
1629
+ return json(res, 400, { ok: false, message: '宿主未提供 workspaceRegistry,无法注册工作区' });
1630
+ }
1631
+ const created = await registry.create(normalizePath(path));
1632
+ const workspaceId = nonEmptyString(created?.id);
1633
+ if (workspaceId === undefined) {
1634
+ return json(res, 400, { ok: false, message: '工作区注册未返回 id' });
1635
+ }
1636
+ try {
1637
+ await unarchiveWorkspaceProject(ctx, { path });
1638
+ }
1639
+ catch {
1640
+ // 自动解除归档失败不阻塞打开工作区
1641
+ }
1642
+ json(res, 200, { ok: true, workspaceId });
1643
+ });
1644
+ }
1645
+ /** `POST /worktree-create` 的处理器(导出以便直接单测入参校验)。
1646
+ *
1647
+ * `options` 用于**测试隔离**:传入 `createFileLedger(tmpdir)` 可确保不会写真实 `~/.dsh`。 */
1648
+ export async function handleWorktreeCreate(ctx, res, body, options = {}) {
1649
+ const repoPathRaw = bodyString(body, 'repoPath');
1650
+ const branch = bodyString(body, 'branch');
1651
+ const createBranch = body['createBranch'] !== false;
1652
+ const baseRef = bodyString(body, 'baseRef');
1653
+ const targetPathRaw = bodyString(body, 'targetPath');
1654
+ if (repoPathRaw === undefined)
1655
+ return json(res, 400, { ok: false, message: '缺少 repoPath' });
1656
+ if (branch === undefined)
1657
+ return json(res, 400, { ok: false, message: '缺少 branch' });
1658
+ let snapshot;
1659
+ try {
1660
+ snapshot = await collectSnapshot(ctx, options);
1661
+ }
1662
+ catch (error) {
1663
+ return json(res, 400, { ok: false, message: failMessage(error) });
1664
+ }
1665
+ // 安全边界:repoPath 必须是「已注册工作区路径」或「已扫描出的 git 仓路径」的精确匹配。
1666
+ const verdict = assertKnown(repoPathRaw, snapshot.knownRepoPaths, 'repoPath');
1667
+ if (!verdict.ok)
1668
+ return json(res, 400, { ok: false, message: verdict.message });
1669
+ const repoPath = verdict.path;
1670
+ if (!(await pathExists(repoPath))) {
1671
+ return json(res, 400, { ok: false, message: `repoPath 不存在:${repoPath}` });
1672
+ }
1673
+ // 用与白名单同一个来源解析主树(避免拼法不一致 ⇒ 默认目标路径算错)。
1674
+ // 命中 commonDir / worktree 时 `mainPathByKnownPath` 已给出主树;直接命中的就是主树本身。
1675
+ const mainPath = snapshot.mainPathByKnownPath.get(repoPath) ?? repoPath;
1676
+ // D5:显式传入的 targetPath 必须落在主仓父目录下(否则一条 POST 就能让 git 在
1677
+ // 任意路径铺开文件树,并自动注册成工作区)。校验失败时**什么都不建**。
1678
+ // 不传 targetPath 时仍走既有默认推导,行为不变。
1679
+ //
1680
+ // D-N2:词法校验必须叠加**符号链接解析**,否则「主仓父目录下指向仓外的符号链接」
1681
+ // 会以合法拼法绕过 D-5。这里先把两边的父目录(以及目标自身是否为符号链接)解析成
1682
+ // 真身,任一失败都直接拒绝(`resolveRealTargetParents` 绝不静默放行)。
1683
+ let targetPath;
1684
+ try {
1685
+ // 不传 targetPath 时按既有规则推导默认落点(行为不变),再走同一套安全校验。
1686
+ const candidate = targetPathRaw ?? defaultWorktreePath(mainPath, branch);
1687
+ const parents = await resolveRealTargetParents(candidate, mainPath);
1688
+ if (!parents.ok)
1689
+ return json(res, 400, { ok: false, message: parents.message });
1690
+ const targetVerdict = validateTargetPath(candidate, parents.mainPathReal, parents.parentReal);
1691
+ if (!targetVerdict.ok)
1692
+ return json(res, 400, { ok: false, message: targetVerdict.message });
1693
+ targetPath = targetVerdict.path;
1694
+ }
1695
+ catch (error) {
1696
+ return json(res, 400, { ok: false, message: failMessage(error) });
1697
+ }
1698
+ let worktreePath;
1699
+ try {
1700
+ worktreePath = await gitWorktreeAdd(repoPath, branch, createBranch, targetPath, baseRef, undefined);
1701
+ }
1702
+ catch (error) {
1703
+ // 契约:**失败时不回滚已建的 worktree**(可能是 `git worktree add` 成功但列表读取失败,
1704
+ // 也可能是 add 之前就失败)。如实报告错误,让用户自行处置。
1705
+ return json(res, 400, { ok: false, message: failMessage(error) });
1706
+ }
1707
+ // 成功后注册 dsh 工作区;注册失败**不视为创建失败**(目录已在,cwd 归属仍可用)。
1708
+ //
1709
+ // **D10**:注册失败必须**对用户可见**。旧实现是裸 `catch {}`,于是「worktree 建好了
1710
+ // 但没注册工作区」⇒ 响应缺 `workspaceId` ⇒ 客户端不 `startSession` ⇒ 用户看到的是
1711
+ // 「创建成功」却**没有自动新会话,且界面上零提示**,直接违反 D7/US6 的预期。
1712
+ // 现在把失败原因带回响应(`ok` 仍为 `true`:worktree 确实建成了)。
1713
+ const registry = getService(ctx, 'workspaceRegistry');
1714
+ let workspaceId;
1715
+ let workspaceWarning;
1716
+ if (typeof registry?.create !== 'function') {
1717
+ workspaceWarning = '宿主未提供 workspaceRegistry,worktree 已创建但未注册为工作区';
1718
+ }
1719
+ else {
1720
+ try {
1721
+ const created = await registry.create(worktreePath);
1722
+ workspaceId = nonEmptyString(created?.id);
1723
+ if (workspaceId === undefined) {
1724
+ workspaceWarning = '工作区注册未返回 id,worktree 已创建但未注册为工作区';
1725
+ }
1726
+ }
1727
+ catch (error) {
1728
+ workspaceWarning = failMessage(error);
1729
+ }
1730
+ }
1731
+ // 目录已变,让下一次 /tree 立刻看到新 worktree。
1732
+ clearScanCache();
1733
+ const payload = {
1734
+ ok: true,
1735
+ worktreePath,
1736
+ };
1737
+ if (workspaceId !== undefined)
1738
+ payload.workspaceId = workspaceId;
1739
+ if (workspaceWarning !== undefined)
1740
+ payload.workspaceWarning = workspaceWarning;
1741
+ json(res, 200, payload);
1742
+ }
1743
+ /** `POST /worktree-remove` 的处理器(导出以便直接单测入参校验)。
1744
+ *
1745
+ * `options` 用于**测试隔离**:传入 `createFileLedger(tmpdir)` 可确保不会写真实 `~/.dsh`。 */
1746
+ export async function handleWorktreeRemove(ctx, res, body, options = {}) {
1747
+ const force = body['force'] === true;
1748
+ let snapshot;
1749
+ try {
1750
+ snapshot = await collectSnapshot(ctx, options);
1751
+ }
1752
+ catch (error) {
1753
+ return json(res, 400, { ok: false, message: failMessage(error) });
1754
+ }
1755
+ // 安全边界:path 必须命中「已知 worktree 集合」= git 扫描结果 ∪ 台账 ∪ 工作区路径。
1756
+ const verdict = assertKnown(body['path'], snapshot.knownWorktreePaths, 'path');
1757
+ if (!verdict.ok)
1758
+ return json(res, 400, { ok: false, message: verdict.message });
1759
+ const path = verdict.path;
1760
+ // **D6**:再加一层「必须**已注册**为 dsh 工作区」的判据。
1761
+ //
1762
+ // 白名单 `knownWorktreePaths` 刻意包含 git 扫描到的**全部** worktree(这是 US3 必需
1763
+ // 的:未注册 worktree 上的会话也要能正确归属)。但移除是**不可撤销**的目录删除,
1764
+ // 而 UI(D14)只为已注册行渲染「移除 worktree」入口 —— 后端此前没有同源收紧,
1765
+ // 形成「前端校验当后端校验用」:一条 POST 就能删掉用户手工 `git worktree add`
1766
+ // 出来、从未在 DSH 里露过面的目录。
1767
+ //
1768
+ // 裁定:**拒绝**。D8 的语义是「移除我用过的 worktree」;未注册 ⇒ 用户没在 DSH 里
1769
+ // 用过它,误删风险高于收益。(外部 `rm -rf` 后的残留由 D18 `sweepDeadWorkspaces`
1770
+ // 自动注销,不依赖本路由。)
1771
+ if (snapshot.workspaceByPath[path] === undefined) {
1772
+ return json(res, 400, {
1773
+ ok: false,
1774
+ message: `该 worktree 尚未注册为工作区,拒绝移除:${path}(请在侧栏点 + 新建会话后再操作)`,
1775
+ });
1776
+ }
1777
+ // 找一个能跑 git 的仓库入口。
1778
+ // 直接查 `mainPathByKnownPath`,不用 `repos[].worktrees[]` 反查 ——
1779
+ // 后者用的是 git 输出的拼法,与白名单命中的拼法可能不同(见该字段的注释)。
1780
+ let resolvedRepoPath = snapshot.mainPathByKnownPath.get(path);
1781
+ if (resolvedRepoPath === undefined) {
1782
+ // 工作区路径不是任何 worktree:退台账记过的项目主树。
1783
+ for (const project of Object.values(snapshot.ledger.projects)) {
1784
+ const mainPath = nonEmptyString(project?.mainPath);
1785
+ if (mainPath === undefined)
1786
+ continue;
1787
+ if (project.worktrees?.[path] === undefined)
1788
+ continue;
1789
+ resolvedRepoPath = normalizePath(mainPath);
1790
+ break;
1791
+ }
1792
+ }
1793
+ if (resolvedRepoPath === undefined || !(await pathExists(resolvedRepoPath))) {
1794
+ return json(res, 400, {
1795
+ ok: false,
1796
+ message: `找不到可用的仓库入口来移除该 worktree:${path}`,
1797
+ });
1798
+ }
1799
+ const repoPath = resolvedRepoPath;
1800
+ const runRemove = async (useForce) => {
1801
+ const args = ['worktree', 'remove', ...(useForce ? ['--force'] : []), path];
1802
+ await runGit(repoPath, args, undefined);
1803
+ };
1804
+ try {
1805
+ await runRemove(force);
1806
+ }
1807
+ catch (error) {
1808
+ const message = failMessage(error);
1809
+ if (!force) {
1810
+ // 契约:脏 worktree(或任何失败)且未强制 ⇒ 明确告知需要 force 重试。
1811
+ return json(res, 400, { ok: false, needsForce: true, message });
1812
+ }
1813
+ return json(res, 400, { ok: false, message });
1814
+ }
1815
+ // 注销对应的 dsh 工作区。**分支不删**(契约 §1.5)。
1816
+ const workspaceId = snapshot.workspaceByPath[path];
1817
+ const registry = getService(ctx, 'workspaceRegistry');
1818
+ if (workspaceId !== undefined && typeof registry?.delete === 'function') {
1819
+ try {
1820
+ await registry.delete(workspaceId);
1821
+ }
1822
+ catch {
1823
+ // 目录已删、注册注销失败:不阻塞「移除成功」的结论,客户端下次刷新会看到死工作区。
1824
+ }
1825
+ }
1826
+ clearScanCache();
1827
+ json(res, 200, { ok: true });
1828
+ }
1829
+ /** `POST /reveal` 的处理器(导出以便直接单测入参校验与白名单)。
1830
+ *
1831
+ * **D11**:`path` 必须命中「已知集合」= `knownWorktreePaths ∪ knownRepoPaths`,
1832
+ * 与 `worktree-remove` 同级。该并集已覆盖全部四类已知路径:
1833
+ * - 全部 git 扫描出的 worktree(含**未注册**的);
1834
+ * - 仓入口 / `mainPath` / `commonDir`;
1835
+ * - 台账记过的 worktree 路径;
1836
+ * - 全部**已注册 dsh 工作区**路径(`collectSnapshot` 会把它们补进 `knownWorktreePaths`)。
1837
+ *
1838
+ * 为什么收紧:本端点会执行 `open -R` / `explorer /select,` / `xdg-open`,与
1839
+ * `worktree-remove` / `worktree-create` 承担同级的「把本机路径交给外部进程」的风险。
1840
+ * 旧实现只校验「路径存在」,等价于一个「任意路径存在性探针 + 文件管理器打开器」,
1841
+ * 与另两个端点的安全姿态不一致。
1842
+ *
1843
+ * 客户端只有一个调用点(`sidebar.tsx` 的 `MENU.reveal`,worktree 行),路径直接来自
1844
+ * 同一棵树的节点数据,必定落在白名单内,因此本收紧不破坏正常功能。
1845
+ *
1846
+ * `options` 用于**测试隔离**:传入 `createFileLedger(tmpdir)` 可确保不会写真实 `~/.dsh`。
1847
+ */
1848
+ export async function handleReveal(ctx, res, body, options = {}) {
1849
+ let snapshot;
1850
+ try {
1851
+ snapshot = await collectSnapshot(ctx, options);
1852
+ }
1853
+ catch (error) {
1854
+ return json(res, 400, { ok: false, message: failMessage(error) });
1855
+ }
1856
+ // 安全边界:与 `worktree-remove` 同级的白名单**精确匹配**(绝不前缀匹配)。
1857
+ //
1858
+ // 已知集合 = `knownWorktreePaths ∪ knownRepoPaths`,它已经覆盖:
1859
+ // - 全部 git 扫描出的 worktree(含**未注册**的);
1860
+ // - 仓入口 / `mainPath` / `commonDir`;
1861
+ // - 台账记过的 worktree 路径;
1862
+ // - 全部**已注册 dsh 工作区**路径(`collectSnapshot` 的工作区循环会把它们
1863
+ // 补进 `knownWorktreePaths`,故 `workspaceByPath` 的键必然在此并集内)。
1864
+ const allowed = new Set([...snapshot.knownWorktreePaths, ...snapshot.knownRepoPaths]);
1865
+ const verdict = assertKnown(body['path'], allowed, 'path');
1866
+ if (!verdict.ok)
1867
+ return json(res, 400, { ok: false, message: verdict.message });
1868
+ const resolved = verdict.path;
1869
+ if (!(await pathExists(resolved))) {
1870
+ return json(res, 400, { ok: false, message: `路径不存在:${resolved}` });
1871
+ }
1872
+ await revealPath(resolved, currentPlatform());
1873
+ json(res, 200, { ok: true });
1874
+ }
1875
+ //# sourceMappingURL=routes.js.map