dsh-context-switch 0.0.0-stage → 1.1.0

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.
@@ -0,0 +1,407 @@
1
+ /**
2
+ * now-card.mjs —— NOW 卡的解析与会话尾巴读取。
3
+ *
4
+ * 两件事:
5
+ * 1. **parseNow**:把一套上下文里的 `NOW.md` 解析成结构化数据
6
+ * (正在做 / 未做完 / 已做完 / 黑板 / 其他)。**容错优先**——
7
+ * 格式写歪了、只有标题、整篇纯文本,都得能读出来,绝不能让面板空掉。
8
+ * 2. **readLastSessionTail**:从 DSH 的会话存储里捞出「本工作区上一次会话的最后几条」。
9
+ *
10
+ * 会话文件是 `session.v4.jsonl.zstd`,**多帧 zstd** 追加写(一个大文件几千帧)。
11
+ * 所以要**尾读**:只读最后几十 KB,从后往前找帧头(magic `28 B5 2F FD`),
12
+ * 逐帧解压、拼起来、取最后几条。全量解 12 MB 是浪费,而且会卡死主进程。
13
+ *
14
+ * @module dsh-context-switch/now-card
15
+ */
16
+ import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import { homedir } from 'node:os'
19
+ import { zstdDecompressSync } from 'node:zlib'
20
+
21
+ /** zstd 帧头 magic:`28 B5 2F FD` */
22
+ const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
23
+
24
+ /** 二级标题 → 分区名的别名表(后面比较时会去空格、转小写) */
25
+ const SECTION_ALIASES = {
26
+ doing: ['正在做', '进行中', 'doing', 'now'],
27
+ todo: ['未做完', '待办', '还没做', 'todo'],
28
+ done: ['已做完', '已完成', 'done'],
29
+ board: ['黑板', 'board', '备注'],
30
+ }
31
+
32
+ const norm = (s) => String(s ?? '').trim().replace(/[::\s]/g, '').toLowerCase()
33
+
34
+ function matchSection(title) {
35
+ const t = norm(title)
36
+ for (const [key, aliases] of Object.entries(SECTION_ALIASES)) {
37
+ if (aliases.some((a) => t === norm(a) || t.startsWith(norm(a)))) return key
38
+ }
39
+ return null
40
+ }
41
+
42
+ /**
43
+ * 把 NOW.md 的原始文本解析成结构化对象。
44
+ *
45
+ * @param {string} raw
46
+ * @returns {{ title: string, doing: string[], todo: string[], done: string[],
47
+ * board: string, others: Array<{ heading: string, body: string }>,
48
+ * parsed: boolean }}
49
+ */
50
+ export function parseNow(raw) {
51
+ const text = String(raw ?? '')
52
+ const out = { title: '', doing: [], todo: [], done: [], board: '', others: [], parsed: false }
53
+ if (!text.trim()) return out
54
+
55
+ // 按 `## ` 切块;第一个块是 `# 标题` 和 `## 之前` 的内容
56
+ const lines = text.split(/\r?\n/)
57
+ const blocks = []
58
+ let cur = { heading: null, body: [] }
59
+
60
+ for (const line of lines) {
61
+ const m = /^(#{1,3})\s+(.*)$/.exec(line)
62
+ if (m && m[1].length === 2) {
63
+ blocks.push(cur)
64
+ cur = { heading: m[2], body: [] }
65
+ } else if (m && m[1].length === 1) {
66
+ // `# 标题` —— 单独的就不当分区,只取标题名
67
+ if (!out.title) out.title = m[2].trim()
68
+ cur.body.push(line)
69
+ } else {
70
+ cur.body.push(line)
71
+ }
72
+ }
73
+ blocks.push(cur)
74
+
75
+ const isListLine = (l) => /^\s*[-*+]\s+/.test(l) || /^\s*[-*+]\s+\[[ xX]\]\s+/.test(l)
76
+ const stripMark = (l) => l.replace(/^\s*[-*+]\s+\[[ xX]\]\s+/, '').replace(/^\s*[-*+]\s+/, '').trim()
77
+ const isChecked = (l) => /^\s*[-*+]\s+\[[xX]\]\s+/.test(l)
78
+
79
+ for (const b of blocks) {
80
+ const body = b.body.join('\n').trim()
81
+ if (b.heading === null) {
82
+ // 第一个块:可能是标题行 + 没归类的正文
83
+ const rest = b.body.filter((l) => !/^#\s/.test(l)).join('\n').trim()
84
+ if (rest) out.others.push({ heading: '(开头)', body: rest })
85
+ continue
86
+ }
87
+
88
+ const key = matchSection(b.heading)
89
+ if (key === 'board') {
90
+ out.board = body
91
+ out.parsed = true
92
+ continue
93
+ }
94
+ if (key === 'doing') {
95
+ // 「正在做」通常是一句话,不是列表;列表也接
96
+ const listLines = b.body.filter(isListLine)
97
+ if (listLines.length) {
98
+ out.doing.push(...listLines.map(stripMark))
99
+ } else if (body) {
100
+ out.doing.push(body)
101
+ }
102
+ out.parsed = true
103
+ continue
104
+ }
105
+ if (key === 'todo' || key === 'done') {
106
+ // 优先认 `- [ ]` / `- [x]`;没有的话退化成普通列表
107
+ const checked = b.body.filter((l) => isListLine(l) && isChecked(l))
108
+ const plain = b.body.filter((l) => isListLine(l) && !isChecked(l))
109
+ if (key === 'done') {
110
+ const items = [...checked, ...plain].map(stripMark).filter(Boolean)
111
+ out.done.push(...items)
112
+ // done 区里混着的未勾选项,也算 done(用户写了就是做完了)
113
+ } else {
114
+ const items = [...plain, ...checked].map(stripMark).filter(Boolean)
115
+ out.todo.push(...items)
116
+ // todo 区里勾过的,挪去 done
117
+ for (const l of checked) out.done.push(stripMark(l))
118
+ out.todo = out.todo.filter((x) => !checked.map(stripMark).includes(x) || !checked.length)
119
+ out.todo = [...b.body.filter((l) => isListLine(l) && !isChecked(l)).map(stripMark)].filter(Boolean)
120
+ }
121
+ out.parsed = true
122
+ continue
123
+ }
124
+
125
+ // 不认识的标题:原样留着,不丢内容
126
+ if (body) out.others.push({ heading: b.heading, body })
127
+ }
128
+
129
+ // 兜底:完全没认出一个分区 → 整篇当「正在做」,保证面板不空
130
+ if (!out.parsed) {
131
+ const plain = text.replace(/^#\s+.*$/m, '').trim()
132
+ if (plain) out.doing.push(plain)
133
+ }
134
+
135
+ return out
136
+ }
137
+
138
+ /**
139
+ * 读一套上下文里的 NOW.md 并解析。找不到就返回 `null`(面板不显示这一块)。
140
+ *
141
+ * @param {string} contextDir
142
+ * @param {string} name 上下文名(子目录名)
143
+ * @returns {null | ReturnType<typeof parseNow> & { file: string }}
144
+ */
145
+ export function readNowCard(contextDir, name) {
146
+ if (!contextDir || !name) return null
147
+ const file = join(contextDir, name, 'NOW.md')
148
+ if (!existsSync(file)) return null
149
+ try {
150
+ return { ...parseNow(readFileSync(file, 'utf8')), file }
151
+ } catch {
152
+ return null
153
+ }
154
+ }
155
+
156
+ /** 把工作目录转成 DSH 会话存储的目录名:`E:\work` → `--E-work--` */
157
+ export function cwdToSessionDirName(cwd) {
158
+ const s = String(cwd ?? '')
159
+ if (!s) return null
160
+ const replaced = s.replace(/[:\\/]+/g, '-').replace(/^-+|-+$/g, '')
161
+ return `--${replaced}--`
162
+ }
163
+
164
+ /**
165
+ * 从会话文件尾部读出最后几帧并解压。
166
+ *
167
+ * @param {string} file
168
+ * @param {number} maxBytes 最多读文件尾部这么多字节
169
+ * @returns {string[]} 解压后的行
170
+ */
171
+ function readTailLines(file, maxBytes = 262144) {
172
+ const size = statSync(file).size
173
+ const start = Math.max(0, size - maxBytes)
174
+ const buf = (() => {
175
+ const fd = readFileSync(file) // 小文件直接全读更简单;大文件才需要尾读
176
+ return fd
177
+ })()
178
+
179
+ let slice = buf
180
+ if (size > maxBytes) {
181
+ // 尾读:从 start 往后找第一个完整帧头
182
+ const tail = buf.subarray(start)
183
+ const firstMagic = tail.indexOf(ZSTD_MAGIC, 0)
184
+ slice = firstMagic === -1 ? tail : tail.subarray(firstMagic)
185
+ }
186
+
187
+ const lines = []
188
+ let pos = 0
189
+ while (pos < slice.length) {
190
+ const next = slice.indexOf(ZSTD_MAGIC, pos + 1)
191
+ const end = next === -1 ? slice.length : next
192
+ try {
193
+ const out = zstdDecompressSync(slice.subarray(pos, end))
194
+ if (out?.length) lines.push(...out.toString('utf8').split('\n').filter(Boolean))
195
+ } catch {
196
+ // 坏帧跳过——文件末尾可能正在写
197
+ }
198
+ pos = end
199
+ }
200
+ return lines
201
+ }
202
+
203
+ /** 把可能是 JSON 富文本块(`[{type:"text",text:"…"}]`)的字段还原成纯文本 */
204
+ function flattenText(v) {
205
+ if (v == null) return ''
206
+ if (typeof v === 'string') {
207
+ const s = v.trim()
208
+ // DSH 的 data.text 常常是 JSON 字符串化的富文本块
209
+ if ((s.startsWith('[') && s.endsWith(']')) || (s.startsWith('{') && s.endsWith('}'))) {
210
+ try {
211
+ const parsed = JSON.parse(s)
212
+ const walk = (n) => {
213
+ if (n == null) return ''
214
+ if (typeof n === 'string') return n
215
+ if (Array.isArray(n)) return n.map(walk).join('')
216
+ if (typeof n === 'object') {
217
+ if (typeof n.text === 'string') return n.text
218
+ if (n.content) return walk(n.content)
219
+ }
220
+ return ''
221
+ }
222
+ const out = walk(parsed)
223
+ if (out) return out
224
+ } catch {
225
+ // 不是 JSON,就当普通字符串
226
+ }
227
+ }
228
+ return v
229
+ }
230
+ if (Array.isArray(v)) return v.map(flattenText).join('')
231
+ if (typeof v === 'object') {
232
+ if (typeof v.text === 'string') return v.text
233
+ if (v.content) return flattenText(v.content)
234
+ }
235
+ return ''
236
+ }
237
+
238
+ /** 从一行事件里取出「这是条对话消息」的正文;不是就返回 null */
239
+ function pickMessage(line) {
240
+ let ev
241
+ try {
242
+ ev = JSON.parse(line)
243
+ } catch {
244
+ return null
245
+ }
246
+ const t = String(ev?.type ?? '')
247
+
248
+ // 工具结果、系统事件一律不要 —— 尾巴只放「人说的话」和「我说的话」
249
+ if (/tool|system|job|patch|approval|hook|mcp|notice/i.test(t)) return null
250
+
251
+ const d = ev?.data ?? {}
252
+ const role = d.role ?? d.message?.role ?? null
253
+ const raw =
254
+ d.text ?? d.content ?? d.message?.content ?? (typeof d === 'string' ? d : '') ?? ''
255
+ const text = flattenText(raw)
256
+
257
+ if (!text || !text.trim()) return null
258
+
259
+ // 角色判定:只留 user / assistant
260
+ let r = role
261
+ if (!r) r = /user/i.test(t) ? 'user' : /assistant/i.test(t) ? 'assistant' : null
262
+ if (r !== 'user' && r !== 'assistant') return null
263
+
264
+ const trimmed = text.trim()
265
+
266
+ // ── 剥掉 DSH 塞在 user 消息里的运行时噪音 ────────────────
267
+ // 判定在**解开富文本之后**做——否则 `[{…}]` 会被误认成方括号开头的系统消息。
268
+ // ── 剥掉 DSH 塞在 user 消息里的运行时噪音 ────────────────
269
+ // 判定在**解开富文本之后**做——否则 `[{…}]` 会被误认成方括号开头的系统消息。
270
+ //
271
+ // 除了已知的系统短语,还有一条通用规则:**以 markdown 标题(`# `)开头的
272
+ // user 消息也算系统注入**——DSH 的注入件(SOUL / NOW / MEMORY / 运行时快照)
273
+ // 都是这个形状。真人很少一开口就打一级标题。
274
+ const SYSTEM_LEAD =
275
+ /^(#{1,6}\s|<!--|Time sampled|Browser time zone|Current runtime context|Current working directory|Current DSH file policy|Current DeepSeek Harness|Approval prompts are disabled|长期记忆(|长期记忆\(|\[SCHEDULE|\[REMINDER|\[SYSTEM|\[NOTICE)/i
276
+
277
+ if (SYSTEM_LEAD.test(trimmed)) {
278
+ // 系统块可能接在用户输入前面:按空行切段,丢掉系统段,留下剩下的
279
+ const paras = trimmed.split(/\n{2,}/)
280
+ const keep = paras.filter((p) => !SYSTEM_LEAD.test(p.trim()))
281
+ const stripped = keep.join('\n\n').trim()
282
+ if (!stripped) return null
283
+ const hasCJK = /[\u4e00-\u9fff]/.test(stripped)
284
+ // 剥完还是一整段英文长文 → 纯系统噪音,丢掉
285
+ if (!hasCJK && stripped.length > 60) return null
286
+ return { role: r, text: stripped.slice(0, 600), time: ev?.time ?? null, seq: ev?.seq ?? null }
287
+ }
288
+
289
+ if (trimmed.length < 2) return null
290
+ return { role: r, text: trimmed.slice(0, 600), time: ev?.time ?? null, seq: ev?.seq ?? null }
291
+ }
292
+
293
+ /**
294
+ * 读「本工作区上一次会话的最后几条消息」。
295
+ *
296
+ * 选法:`~/.dsh/sessions/<cwd 转义>/` 下,按 mtime 最新的 `session.v4.jsonl.zstd`,
297
+ * 且**不是当前会话**。全程容错——任何一步失败都返回 `{ messages: [], error }`,不抛。
298
+ *
299
+ * @param {object} o
300
+ * @param {string} [o.cwd] 工作目录(默认 process.cwd())
301
+ * @param {number} [o.limit=6] 取最后几条消息
302
+ * @param {number} [o.maxBytes=262144] 尾读字节数
303
+ * @param {string} [o.excludeSessionId] 排除的会话 id(当前会话)
304
+ * @param {string} [o.dshHome] 默认 `~/.dsh`
305
+ * @returns {{ messages: Array<{role:string,text:string,time:number|null,seq:number|null}>,
306
+ * sessionId: string | null, mtime: number | null, error: string | null }}
307
+ */
308
+ export function readLastSessionTail(o = {}) {
309
+ const cwd = o.cwd || process.cwd()
310
+ const limit = Number.isFinite(o.limit) && o.limit > 0 ? o.limit : 6
311
+ const maxBytes = Number.isFinite(o.maxBytes) && o.maxBytes > 0 ? o.maxBytes : 262144
312
+ const dshHome = o.dshHome || join(homedir(), '.dsh')
313
+ // 「正在写」的会话 = 当前会话。默认排除 90 秒内动过的文件,
314
+ // 这样不依赖 DSH 给不给会话 id 也能排掉自己。
315
+ const activeWindowMs = Number.isFinite(o.activeWindowMs) ? o.activeWindowMs : 90000
316
+ const empty = { messages: [], sessionId: null, mtime: null, error: null }
317
+
318
+ const dirName = cwdToSessionDirName(cwd)
319
+ if (!dirName) return { ...empty, error: '拿不到工作目录' }
320
+
321
+ const root = join(dshHome, 'sessions', dirName)
322
+ if (!existsSync(root)) return { ...empty, error: `没有会话目录:${dirName}` }
323
+
324
+ const nowMs = Date.now()
325
+ let candidates = []
326
+ try {
327
+ for (const ent of readdirSync(root, { withFileTypes: true })) {
328
+ if (!ent.isDirectory()) continue
329
+ const sid = ent.name
330
+ if (o.excludeSessionId && sid === o.excludeSessionId) continue
331
+ const f = join(root, sid, 'session.v4.jsonl.zstd')
332
+ if (!existsSync(f)) continue
333
+ try {
334
+ const mtime = statSync(f).mtimeMs
335
+ // 跳过「正在写」的那个(大概就是当前会话)
336
+ if (activeWindowMs > 0 && nowMs - mtime < activeWindowMs) continue
337
+ candidates.push({ sid, file: f, mtime })
338
+ } catch {}
339
+ }
340
+ } catch (e) {
341
+ return { ...empty, error: `读会话目录失败:${e instanceof Error ? e.message : String(e)}` }
342
+ }
343
+
344
+ if (!candidates.length) return { ...empty, error: '没有更早的会话' }
345
+ candidates.sort((a, b) => b.mtime - a.mtime)
346
+ const pick = candidates[0]
347
+
348
+ let lines
349
+ try {
350
+ lines = readTailLines(pick.file, maxBytes)
351
+ } catch (e) {
352
+ return { ...empty, sessionId: pick.sid, mtime: pick.mtime, error: `解压失败:${e instanceof Error ? e.message : String(e)}` }
353
+ }
354
+
355
+ const msgs = []
356
+ for (const l of lines) {
357
+ const m = pickMessage(l)
358
+ if (m) msgs.push(m)
359
+ }
360
+
361
+ if (!msgs.length) {
362
+ return { messages: [], sessionId: pick.sid, mtime: pick.mtime, error: '会话里没找到对话消息' }
363
+ }
364
+
365
+ // 取最后 limit 条;**但如果里面一条 user 都没有,就往前找到最近的一条 user**
366
+ // —— 否则会出现「尾巴全是 AI 自己在干活」,那对判断「上次聊到哪」毫无用处。
367
+ //
368
+ // ⚠️ 找到之后**不能把中间几十条全带上**(实测能拉到 45 条),
369
+ // 只保留「那一条 user + 最近 limit-1 条」,总数仍然受 limit 约束。
370
+ let picked = msgs.slice(-limit)
371
+ if (!picked.some((m) => m.role === 'user')) {
372
+ let userIdx = -1
373
+ for (let i = msgs.length - 1; i >= 0; i--) {
374
+ if (msgs[i].role === 'user') {
375
+ userIdx = i
376
+ break
377
+ }
378
+ }
379
+ if (userIdx >= 0) {
380
+ const lastN = msgs.slice(-(Math.max(1, limit - 1)))
381
+ picked = [msgs[userIdx], ...lastN].slice(0, Math.max(limit, 2))
382
+ }
383
+ }
384
+
385
+ return { messages: picked, sessionId: pick.sid, mtime: pick.mtime, error: null }
386
+ }
387
+
388
+ /**
389
+ * 汇总成面板要吃的对象。
390
+ *
391
+ * @param {object} o
392
+ * @returns {{ active: string|null, now: ReturnType<typeof parseNow> | null,
393
+ * tail: ReturnType<typeof readLastSessionTail> }}
394
+ */
395
+ export function buildNowCard(o = {}) {
396
+ const now = readNowCard(o.contextDir, o.active)
397
+ const tail = o.includeTail === false
398
+ ? { messages: [], sessionId: null, mtime: null, error: null }
399
+ : readLastSessionTail({
400
+ cwd: o.cwd,
401
+ limit: o.tailMessages,
402
+ maxBytes: o.sessionTailMaxBytes,
403
+ excludeSessionId: o.excludeSessionId,
404
+ dshHome: o.dshHome,
405
+ })
406
+ return { active: o.active || null, now, tail }
407
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * schedule.mjs —— 按 WHEN.md 里的时段决定「现在用哪套上下文」。
3
+ *
4
+ * 容错优先:文件缺失 / 格式写歪 → 那套不参与自动挡,绝不抛错。
5
+ *
6
+ * @module dsh-context-switch/schedule
7
+ */
8
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+
11
+ const SLOT_HEADINGS = ['时段', '时间', '生效时段', 'when', 'time']
12
+
13
+ const norm = (s) => String(s ?? '').trim().replace(/[::\s]/g, '').toLowerCase()
14
+
15
+ /** `"22:00"` → 1320(一天里的第几分钟);不合法返回 null */
16
+ function parseClock(s) {
17
+ const m = /^(\d{1,2})[::](\d{2})$/.exec(String(s ?? '').trim())
18
+ if (!m) return null
19
+ const h = Number(m[1])
20
+ const min = Number(m[2])
21
+ if (!Number.isFinite(h) || !Number.isFinite(min)) return null
22
+ if (h < 0 || h > 24 || min < 0 || min > 59) return null
23
+ if (h === 24 && min !== 0) return null
24
+ return h * 60 + min
25
+ }
26
+
27
+ /** 分钟数 → `"HH:MM"`,只用于显示 */
28
+ export function fmtClock(minutes) {
29
+ const m = Math.max(0, Number(minutes) || 0)
30
+ return `${String(Math.floor(m / 60)).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`
31
+ }
32
+
33
+ /** `"22:00-06:00"` → { start, end, text };横线 / 波浪 / 至 / 到 都认 */
34
+ function parseSlot(text) {
35
+ const s = String(text ?? '').trim()
36
+ if (!s) return null
37
+ const m = /^(.+?)\s*(?:-|~|–|—|至|到)\s*(.+)$/.exec(s)
38
+ if (!m) return null
39
+ const start = parseClock(m[1])
40
+ const end = parseClock(m[2])
41
+ if (start == null || end == null) return null
42
+ return { start, end, text: `${fmtClock(start)}-${fmtClock(end)}` }
43
+ }
44
+
45
+ /**
46
+ * 解析 WHEN.md。读 `## 时段` 那一节的正文;没有二级标题就整篇当正文。
47
+ * @returns {{ slots: Array<{start:number,end:number,text:string}>, ok: boolean }}
48
+ */
49
+ export function parseWhen(raw) {
50
+ const text = String(raw ?? '')
51
+ if (!text.trim()) return { slots: [], ok: false }
52
+
53
+ const wanted = []
54
+ let inSection = false
55
+ let sawHeading = false
56
+
57
+ for (const line of text.split(/\r?\n/)) {
58
+ const h2 = /^##\s+(.*)$/.exec(line)
59
+ if (h2) {
60
+ sawHeading = true
61
+ const title = norm(h2[1])
62
+ inSection = SLOT_HEADINGS.some((a) => title === norm(a) || title.startsWith(norm(a)))
63
+ continue
64
+ }
65
+ if (sawHeading) {
66
+ if (inSection) wanted.push(line)
67
+ } else if (!/^#\s/.test(line)) {
68
+ wanted.push(line)
69
+ }
70
+ }
71
+
72
+ const slots = []
73
+ for (const p of wanted.join('\n').split(/[,,;;\n]+/).map((x) => x.trim()).filter(Boolean)) {
74
+ const s = parseSlot(p)
75
+ if (s) slots.push(s)
76
+ }
77
+ return { slots, ok: slots.length > 0 }
78
+ }
79
+
80
+ /**
81
+ * 某个分钟数是否落在时段内。
82
+ *
83
+ * ⚠️ 跨午夜:start > end 时命中区间是 [start, 24:00) ∪ [0, end),
84
+ * 不能写成 `m >= start && m < end`(那样永远 false)。
85
+ */
86
+ export function inSlot(minutes, slot) {
87
+ const m = ((Number(minutes) % 1440) + 1440) % 1440
88
+ const { start, end } = slot
89
+ if (start === end) return false
90
+ if (start < end) return m >= start && m < end
91
+ return m >= start || m < end
92
+ }
93
+
94
+ /** 时段长度(分钟),用于「更具体优先」的比较 */
95
+ function slotLength(slot) {
96
+ const { start, end } = slot
97
+ if (start === end) return 0
98
+ return start < end ? end - start : 1440 - start + end
99
+ }
100
+
101
+ /**
102
+ * 扫 contextDir,列出每套上下文的时段声明。
103
+ * 没有 WHEN.md 的也登记(hasWhen: false),面板要显示。
104
+ */
105
+ export function listSchedule(contextDir) {
106
+ try {
107
+ if (!existsSync(contextDir)) return []
108
+ const out = []
109
+ for (const ent of readdirSync(contextDir, { withFileTypes: true })) {
110
+ if (!ent.isDirectory()) continue
111
+ const file = join(contextDir, ent.name, 'WHEN.md')
112
+ if (!existsSync(file)) {
113
+ out.push({ name: ent.name, slots: [], hasWhen: false })
114
+ continue
115
+ }
116
+ try {
117
+ const { slots } = parseWhen(readFileSync(file, 'utf8'))
118
+ out.push({ name: ent.name, slots, hasWhen: true })
119
+ } catch {
120
+ out.push({ name: ent.name, slots: [], hasWhen: true })
121
+ }
122
+ }
123
+ return out.sort((a, b) => a.name.localeCompare(b.name))
124
+ } catch {
125
+ return []
126
+ }
127
+ }
128
+
129
+ /**
130
+ * 现在该用哪套。
131
+ *
132
+ * - **一套都没命中 → name: null**,调用方必须保持现状,不要乱切
133
+ * - 多套命中 → 取时段更短的(更具体),一样长按名字
134
+ */
135
+ export function pickBySchedule(contextDir, date = new Date()) {
136
+ const all = listSchedule(contextDir)
137
+ const minutes = date.getHours() * 60 + date.getMinutes()
138
+
139
+ const hits = []
140
+ for (const entry of all) {
141
+ for (const slot of entry.slots) {
142
+ if (inSlot(minutes, slot)) hits.push({ name: entry.name, slot, len: slotLength(slot) })
143
+ }
144
+ }
145
+ if (!hits.length) return { name: null, slot: null, matched: false, all }
146
+
147
+ hits.sort((a, b) => a.len - b.len || a.name.localeCompare(b.name))
148
+ const best = hits[0]
149
+ return { name: best.name, slot: best.slot.text, matched: true, all }
150
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * switch-count.mjs —— 「换了几轮」的计数。
3
+ *
4
+ * 从 `index.js` 里搬出来的:原来这三个函数藏在 `apply` 的闭包里,
5
+ * 想测只能把整个插件跑起来。单独成文件之后可以 import 直接测,
6
+ * 行为一个字没变。
7
+ *
8
+ * 容错优先(跟 schedule.mjs 一个脾气):
9
+ * - 文件不存在 → 0
10
+ * - JSON 坏了 → 0
11
+ * - 目录不可写 → 写失败也不抛,切换本身照常进行
12
+ *
13
+ * @module dsh-context-switch/switch-count
14
+ */
15
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
16
+ import { join } from 'node:path'
17
+
18
+ /** 计数文件就放在 contexts 目录里,跟那几套上下文住一起 */
19
+ export function countStatePath(contextDir) {
20
+ return join(String(contextDir ?? ''), '.switch-count.json')
21
+ }
22
+
23
+ /**
24
+ * 读当前计数。
25
+ * @param {string} contextDir
26
+ * @returns {number} 读不到一律 0
27
+ */
28
+ export function readSwitchCount(contextDir) {
29
+ try {
30
+ const p = countStatePath(contextDir)
31
+ if (!existsSync(p)) return 0
32
+ const j = JSON.parse(readFileSync(p, 'utf8'))
33
+ return Number(j && j.count) || 0
34
+ } catch {
35
+ return 0
36
+ }
37
+ }
38
+
39
+ /**
40
+ * 写计数。写不进去就算了——不能让「记几分」这种事拖垮「切上下文」。
41
+ * @param {string} contextDir
42
+ * @param {number} n
43
+ */
44
+ export function writeSwitchCount(contextDir, n) {
45
+ try {
46
+ writeFileSync(countStatePath(contextDir), JSON.stringify({ count: n }), 'utf8')
47
+ } catch {
48
+ /* 计数写不进去不影响切换本身 */
49
+ }
50
+ }