dsh-subagent-dispatch-control 0.0.0-stage → 1.0.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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +225 -2
  3. package/client.js +9781 -0
  4. package/cordis.patch.yml +13 -0
  5. package/docs/BOOST-EVIDENCE.md +259 -0
  6. package/docs/CONFORMANCE.md +236 -0
  7. package/docs/FACTS-CONTRACT.md +368 -0
  8. package/docs/FLOW-COVERAGE.md +215 -0
  9. package/docs/PACKAGE-README.md +858 -0
  10. package/docs/RANGE-PLAN.md +357 -0
  11. package/docs/SECURITY-NOTES.md +110 -0
  12. package/docs/SPLIT-PLAN.md +604 -0
  13. package/docs/STAGE3-CONTRACT.md +287 -0
  14. package/docs/TIER-ROUTING.md +275 -0
  15. package/docs/badge/CONFORMANCE.md +246 -0
  16. package/docs/badge/DETAIL.md +319 -0
  17. package/docs/badge/PROJECTIONS.md +264 -0
  18. package/docs/badge/TEST-PLAN.md +252 -0
  19. package/docs/images/badge-menu.png +0 -0
  20. package/docs/images/dispatch.png +0 -0
  21. package/docs/images/header.png +0 -0
  22. package/docs/images/pair-header.png +0 -0
  23. package/docs/images/pair-panel.png +0 -0
  24. package/docs/images/panel.png +0 -0
  25. package/docs/wiki/Home.md +43 -0
  26. package/docs/wiki//344/275/277/347/224/250/346/214/207/345/215/227.md +116 -0
  27. package/docs/wiki//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +103 -0
  28. package/docs/wiki//346/225/205/351/232/234/346/216/222/346/237/245.md +94 -0
  29. package/icon.svg +12 -0
  30. package/lib/badge-policy.mjs +502 -0
  31. package/lib/badge-sync.mjs +385 -0
  32. package/lib/command.mjs +490 -0
  33. package/lib/completion.mjs +288 -0
  34. package/lib/concurrency.mjs +2555 -0
  35. package/lib/dispatch-command.mjs +181 -0
  36. package/lib/dispatch-gate.mjs +924 -0
  37. package/lib/facts-store.mjs +183 -0
  38. package/lib/gate-state.mjs +465 -0
  39. package/lib/gate.mjs +886 -0
  40. package/lib/index.js +309 -0
  41. package/lib/inject.mjs +195 -0
  42. package/lib/interrupt.mjs +376 -0
  43. package/lib/ledger.mjs +948 -0
  44. package/lib/lifecycle.mjs +274 -0
  45. package/lib/messages.mjs +532 -0
  46. package/lib/notice.mjs +769 -0
  47. package/lib/plan-gate.mjs +385 -0
  48. package/lib/projection.mjs +978 -0
  49. package/lib/report.mjs +290 -0
  50. package/lib/route.mjs +346 -0
  51. package/lib/run-registry.mjs +402 -0
  52. package/lib/services.mjs +293 -0
  53. package/lib/stuck.mjs +567 -0
  54. package/lib/tier-config.mjs +212 -0
  55. package/lib/tier-policy.mjs +167 -0
  56. package/lib/tier-state.mjs +137 -0
  57. package/lib/todo-gate.mjs +1672 -0
  58. package/lib/tools.mjs +2912 -0
  59. package/locale/en.json +9 -0
  60. package/locale/zh.json +9 -0
  61. package/package.json +58 -4
  62. package/vendor/node_modules/@deepseek-ai/cosmokit/LICENSE +21 -0
  63. package/vendor/node_modules/@deepseek-ai/cosmokit/README.md +30 -0
  64. package/vendor/node_modules/@deepseek-ai/cosmokit/lib/index.js +418 -0
  65. package/vendor/node_modules/@deepseek-ai/cosmokit/package.json +32 -0
  66. package/vendor/node_modules/@deepseek-ai/cosmokit/src/array.ts +42 -0
  67. package/vendor/node_modules/@deepseek-ai/cosmokit/src/index.ts +12 -0
  68. package/vendor/node_modules/@deepseek-ai/cosmokit/src/misc.ts +78 -0
  69. package/vendor/node_modules/@deepseek-ai/cosmokit/src/string.ts +113 -0
  70. package/vendor/node_modules/@deepseek-ai/cosmokit/src/time.ts +92 -0
  71. package/vendor/node_modules/@deepseek-ai/cosmokit/src/types.ts +168 -0
  72. package/vendor/node_modules/@deepseek-ai/cosmokit/src/volatile.ts +86 -0
  73. package/vendor/node_modules/@deepseek-ai/schemastery/LICENSE +21 -0
  74. package/vendor/node_modules/@deepseek-ai/schemastery/README.md +393 -0
  75. package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.cjs +635 -0
  76. package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.mjs +635 -0
  77. package/vendor/node_modules/@deepseek-ai/schemastery/package.json +39 -0
  78. package/vendor/node_modules/@deepseek-ai/schemastery/src/index.ts +962 -0
  79. package/vendor/node_modules/@standard-schema/spec/LICENSE +21 -0
  80. package/vendor/node_modules/@standard-schema/spec/README.md +198 -0
  81. package/vendor/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
  82. package/vendor/node_modules/@standard-schema/spec/dist/index.js +0 -0
  83. package/vendor/node_modules/@standard-schema/spec/package.json +39 -0
@@ -0,0 +1,274 @@
1
+ /**
2
+ * 数据生命周期(lifecycle)模块(W2-F-06):会话目录清理器与触发钩子(D1–D6)。
3
+ * 从 gate.mjs 的「数据生命周期」整段迁出(任务-97;语义与安全纪律逐字保留)。
4
+ *
5
+ * 依赖方向:lifecycle.mjs 只依赖 node:fs / node:path;落盘根(rootOf)与 TOCTOU 前缀
6
+ * 校验(withinRoot)、缺省清理日志名由 gate.mjs 注入 —— 不 import gate.mjs(无环)。
7
+ */
8
+ import { appendFileSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from 'node:fs'
9
+ import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
10
+
11
+ /** D1/D3/D4 生命周期缺省(毫秒)。 */
12
+ const LIFECYCLE_DEFAULTS = {
13
+ activeMs: 7 * 24 * 60 * 60 * 1000, // 7d:此内「活跃」,绝不删
14
+ staleMs: 30 * 24 * 60 * 60 * 1000, // 30d:有数据的目录超过即删
15
+ emptyMs: 7 * 24 * 60 * 60 * 1000, // 7d:空壳目录超过即删
16
+ intervalMs: 24 * 60 * 60 * 1000, // 每 24h 扫一次
17
+ startupDelayMs: 1000, // 启动后 1s 后台扫(不阻塞加载)
18
+ maxDepth: 8,
19
+ }
20
+
21
+ /** 有限非负数判定(配置规整)。 */
22
+ function lifecycleNum(value, fallback) {
23
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : fallback
24
+ }
25
+
26
+ /**
27
+ * 会话目录根:<root>/.dsh/team-preflight/sessions。root 必须是绝对路径,否则返回 null
28
+ * (与 ledgerRootOf 的 A-09 同款纪律:相对/空白根一律不认,绝不按 cwd 建怪目录)。
29
+ */
30
+ function lifecycleSessionsRoot(root) {
31
+ if (typeof root !== 'string') return null
32
+ const trimmed = root.trim()
33
+ if (trimmed === '' || !isAbsolute(trimmed)) return null
34
+ return join(trimmed, '.dsh', 'team-preflight', 'sessions')
35
+ }
36
+
37
+ /**
38
+ * 会话目录段名安全校验(路径段 + 会话键格式双校验,D5)。
39
+ * ① 非空、非 '.' / '..';
40
+ * ② 无路径分隔符 / NUL(readdir 名本就无分隔符,此处是防御性直调断言);
41
+ * ③ decodeURIComponent 可逆:encodeURIComponent(decode(name)) === name(规范编码键)。
42
+ * —— 挡住手工塞进来的怪名 / 大小写不规范的 %XX / 会逃出 sessions/ 的形态。
43
+ */
44
+ export function isLifecycleSegmentSafe(name) {
45
+ if (typeof name !== 'string' || name === '') return false
46
+ if (name === '.' || name === '..') return false
47
+ if (name.includes('/') || name.includes('\\') || name.includes('\0')) return false
48
+ let decoded
49
+ try { decoded = decodeURIComponent(name) } catch { return false }
50
+ if (decoded === '' || decoded === '.' || decoded === '..') return false
51
+ if (decoded.includes('/') || decoded.includes('\\') || decoded.includes('\0')) return false
52
+ try { if (encodeURIComponent(decoded) !== name) return false } catch { return false }
53
+ return true
54
+ }
55
+
56
+ /**
57
+ * 扫描单个会话目录的指标(不跟随符号链接;深度有上限,防病态目录树)。
58
+ * lastMtime = max(目录自身 mtime, 递归内所有 entry 的 mtime):无文件时用目录 mtime 兜底,
59
+ * 即「目录内最后动静」——比只数文件更稳(文件被删后目录 mtime 也会更新)。
60
+ */
61
+ function scanSessionDirMetrics(dir) {
62
+ // W2-F-17:只返回调用方真正消费的 totalBytes / fileCount / lastMtime
63
+ // (旧实现还累加并返回 entryCount / ledgerBytes,全文件 0 读者)。
64
+ let totalBytes = 0
65
+ let fileCount = 0
66
+ let lastMtime = 0
67
+ try { lastMtime = statSync(dir).mtimeMs } catch { /* 目录不可 stat → 保持 0 */ }
68
+ const stack = [{ p: dir, depth: 0 }]
69
+ while (stack.length > 0) {
70
+ const { p, depth } = stack.pop()
71
+ let entries
72
+ try { entries = readdirSync(p, { withFileTypes: true }) } catch { continue }
73
+ for (const ent of entries) {
74
+ const child = join(p, ent.name)
75
+ let st
76
+ try { st = lstatSync(child) } catch { continue }
77
+ if (st.mtimeMs > lastMtime) lastMtime = st.mtimeMs
78
+ if (ent.isDirectory() && !ent.isSymbolicLink()) {
79
+ if (depth + 1 <= LIFECYCLE_DEFAULTS.maxDepth) stack.push({ p: child, depth: depth + 1 })
80
+ } else if (ent.isFile()) {
81
+ fileCount += 1
82
+ totalBytes += st.size
83
+ }
84
+ // 符号链接:只算 mtime,不跟随、不计 size(避免逃逸到 sessions/ 之外)
85
+ }
86
+ }
87
+ return { totalBytes, fileCount, lastMtime }
88
+ }
89
+
90
+ /** 收集「当前会话」键集合(显式保护用;真实运行由「最近 mtime<7 天」天然覆盖)。 */
91
+ function lifecycleCurrentKeys(opts) {
92
+ const set = new Set()
93
+ if (opts && typeof opts.currentSessionKey === 'string' && opts.currentSessionKey !== '') {
94
+ set.add(opts.currentSessionKey)
95
+ }
96
+ if (opts && Array.isArray(opts.currentSessionKeys)) {
97
+ for (const key of opts.currentSessionKeys) if (typeof key === 'string' && key !== '') set.add(key)
98
+ }
99
+ return set
100
+ }
101
+
102
+ /**
103
+ * 纯规划:返回应删清单(不删任何东西)。
104
+ *
105
+ * @param {string} root 宿主 home 根(如 DSH_TP_HOME),必须是绝对路径
106
+ * @param {number} [now] 判定基准时刻(毫秒)
107
+ * @param {object} [opts] { activeMs, staleMs, emptyMs, currentSessionKey, currentSessionKeys }
108
+ * @returns {Array<{dir, name, sessionKey, kind:'empty'|'data', ageMs, lastActivity, totalBytes, fileCount}>}
109
+ * 仅含满足删除条件的目录(已排除当前会话与最近 7 天活跃目录),按 name 排序,确定性输出。
110
+ */
111
+ export function purgeStaleSessions(root, now = Date.now(), opts = {}) {
112
+ const sessionsRoot = lifecycleSessionsRoot(root)
113
+ if (sessionsRoot === null) return []
114
+ const activeMs = lifecycleNum(opts.activeMs, LIFECYCLE_DEFAULTS.activeMs)
115
+ const staleMs = lifecycleNum(opts.staleMs, LIFECYCLE_DEFAULTS.staleMs)
116
+ const emptyMs = lifecycleNum(opts.emptyMs, LIFECYCLE_DEFAULTS.emptyMs)
117
+ const currentKeys = lifecycleCurrentKeys(opts)
118
+ let entries
119
+ try { entries = readdirSync(sessionsRoot, { withFileTypes: true }) } catch { return [] }
120
+ const plan = []
121
+ for (const ent of entries) {
122
+ const name = ent.name
123
+ if (!ent.isDirectory() || ent.isSymbolicLink()) continue // 只处理真实目录
124
+ if (!isLifecycleSegmentSafe(name)) continue // 路径段 + 键格式校验
125
+ let sessionKey = name
126
+ try { sessionKey = decodeURIComponent(name) } catch { /* 已由 safe 校验兜底 */ }
127
+ if (currentKeys.has(sessionKey) || currentKeys.has(name)) continue // 当前会话绝不删
128
+ const dir = join(sessionsRoot, name)
129
+ let m
130
+ try { m = scanSessionDirMetrics(dir) } catch { continue }
131
+ const lastActivity = m.lastMtime
132
+ const ageMs = now - lastActivity
133
+ const isEmptyShell = m.totalBytes === 0
134
+ let decision
135
+ if (ageMs < activeMs) decision = 'active' // <7 天活跃,绝不删
136
+ else if (isEmptyShell) decision = ageMs > emptyMs ? 'purge' : 'retain-empty' // 空壳 7 天后删
137
+ else decision = ageMs > staleMs ? 'purge' : 'retain' // 有数据 30 天后删
138
+ if (decision === 'purge') {
139
+ plan.push({
140
+ dir, name, sessionKey,
141
+ kind: isEmptyShell ? 'empty' : 'data',
142
+ ageMs, lastActivity, totalBytes: m.totalBytes, fileCount: m.fileCount,
143
+ })
144
+ }
145
+ }
146
+ plan.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
147
+ return plan
148
+ }
149
+
150
+ /** 追加一行清理日志(目录懒建);失败返回 false,绝不抛错。 */
151
+ function appendLifecycleLog(logPath, payload) {
152
+ try {
153
+ mkdirSync(dirname(logPath), { recursive: true })
154
+ appendFileSync(logPath, JSON.stringify(payload) + '\n', 'utf8')
155
+ return true
156
+ } catch { return false }
157
+ }
158
+
159
+
160
+ /**
161
+ * 执行层:扫 + 判活跃 + 删 + 写清理日志。
162
+ *
163
+ * @param {string} [rootArg] home 根;省略时用 ledgerRootOf()(DSH_TP_HOME 优先)
164
+ * @param {number} [now]
165
+ * @param {object} [opts] 见 purgeStaleSessions;另支持 logPath(绝对路径,缺省落
166
+ * <root>/.dsh/team-preflight/cleanup-log.jsonl)
167
+ * @returns {{ok:boolean, reason?:string, scanned:number, planned:string[], deleted:string[],
168
+ * failed:Array<{dir,error}>, logPath?:string, sessionsRoot?:string}}
169
+ */
170
+ export function sweepLifecycle(rootArg, now = Date.now(), opts = {}, deps = {}) {
171
+ const root = rootArg === undefined ? deps.rootOf() : rootArg
172
+ const sessionsRoot = lifecycleSessionsRoot(root)
173
+ if (sessionsRoot === null) {
174
+ return { ok: false, reason: 'no-root', scanned: 0, planned: [], deleted: [], failed: [] }
175
+ }
176
+ let scanned = 0
177
+ try { scanned = readdirSync(sessionsRoot).length } catch { scanned = 0 }
178
+ const plan = purgeStaleSessions(root, now, opts)
179
+ const logPath = (typeof opts.logPath === 'string' && opts.logPath.trim() !== '')
180
+ ? opts.logPath
181
+ : join(root, '.dsh', 'team-preflight', deps.defaultLogFileName)
182
+ const at = new Date(now).toISOString()
183
+ const planned = plan.map((p) => p.dir)
184
+
185
+ // ── D5:**删前**写清理日志({删了哪些目录, 条数, 时间})──
186
+ if (planned.length > 0) {
187
+ appendLifecycleLog(logPath, {
188
+ at, ts: now, event: 'purge-plan', count: planned.length,
189
+ dirs: planned, kinds: plan.map((p) => p.kind),
190
+ })
191
+ }
192
+
193
+ const deleted = []
194
+ const failed = []
195
+ let sessionsReal = null
196
+ try { sessionsReal = realpathSync(sessionsRoot) } catch { sessionsReal = null }
197
+ for (const item of plan) {
198
+ // 删前再次前缀校验(防 TOCTOU / 符号链接逃逸)
199
+ if (!deps.withinRoot(item.dir, sessionsRoot, sessionsReal)) {
200
+ failed.push({ dir: item.dir, error: 'prefix-check' })
201
+ continue
202
+ }
203
+ try {
204
+ rmSync(item.dir, { recursive: true, force: true })
205
+ deleted.push(item.dir)
206
+ } catch (error) {
207
+ failed.push({ dir: item.dir, error: String(error?.message ?? error) })
208
+ }
209
+ }
210
+ if (deleted.length > 0 || failed.length > 0) {
211
+ appendLifecycleLog(logPath, {
212
+ at, ts: now, event: 'purge-result', deleted: deleted.length, failed: failed.length, dirs: deleted,
213
+ })
214
+ }
215
+ return { ok: true, scanned, planned, deleted, failed, logPath, sessionsRoot }
216
+ }
217
+
218
+ /**
219
+ * D4 触发钩子:宿主启动后(startupDelayMs,后台 setTimeout)扫一遍 + 每 intervalMs 一次。
220
+ * 只登记 unref 的定时器(不阻塞进程退出 / 不阻塞加载),返回 dispose。
221
+ * 无落盘根(测试 argv / 未重定向 / 空白或相对 DSH_TP_HOME)→ 返回 no-op,不建定时器。
222
+ *
223
+ * @param {object} ctx 宿主上下文(仅用可选 logger.warn,全部 try/catch)
224
+ * @param {object} [config] { enabled, root, now, intervalMs, startupDelayMs, activeMs, staleMs,
225
+ * emptyMs, currentSessionKey, logPath }
226
+ * @returns {() => void} dispose:清两个定时器
227
+ */
228
+ export function installLifecycleSweep(ctx, config = {}, deps = {}) {
229
+ const cfg = config || {}
230
+ if (cfg.enabled === false) return () => {}
231
+ const root = cfg.root !== undefined ? cfg.root : deps.rootOf()
232
+ if (lifecycleSessionsRoot(root) === null) return () => {} // 无落盘根 → no-op
233
+ const nowFn = typeof cfg.now === 'function' ? cfg.now : () => Date.now()
234
+ const intervalMs = Math.max(1, lifecycleNum(cfg.intervalMs, LIFECYCLE_DEFAULTS.intervalMs))
235
+ const startupDelayMs = lifecycleNum(cfg.startupDelayMs, LIFECYCLE_DEFAULTS.startupDelayMs)
236
+ const sweepOpts = {
237
+ activeMs: cfg.activeMs,
238
+ staleMs: cfg.staleMs,
239
+ emptyMs: cfg.emptyMs,
240
+ currentSessionKey: cfg.currentSessionKey,
241
+ currentSessionKeys: cfg.currentSessionKeys,
242
+ logPath: cfg.logPath,
243
+ }
244
+ let warned = false
245
+ const warnOnce = (message) => {
246
+ if (warned) return
247
+ warned = true
248
+ try { ctx?.logger?.warn?.('[team-preflight] ' + message) } catch { /* 无 logger */ }
249
+ }
250
+ const runOnce = () => {
251
+ try {
252
+ const result = sweepLifecycle(root, nowFn(), sweepOpts, deps)
253
+ if (result && Array.isArray(result.failed) && result.failed.length > 0) {
254
+ warnOnce('lifecycle sweep partial failure: ' + result.failed.length)
255
+ }
256
+ } catch (error) {
257
+ warnOnce('lifecycle sweep failed: ' + String(error?.message ?? error))
258
+ }
259
+ }
260
+ let startupTimer = null
261
+ let intervalTimer = null
262
+ try {
263
+ startupTimer = setTimeout(runOnce, startupDelayMs)
264
+ if (startupTimer && typeof startupTimer.unref === 'function') startupTimer.unref()
265
+ intervalTimer = setInterval(runOnce, intervalMs)
266
+ if (intervalTimer && typeof intervalTimer.unref === 'function') intervalTimer.unref()
267
+ } catch { /* 无定时器环境:忽略(清理器静默降级) */ }
268
+ return () => {
269
+ try { if (startupTimer) clearTimeout(startupTimer) } catch { /* 已清 */ }
270
+ try { if (intervalTimer) clearInterval(intervalTimer) } catch { /* 已清 */ }
271
+ startupTimer = null
272
+ intervalTimer = null
273
+ }
274
+ }