dsh-work-summary 0.0.0-stage → 0.2.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.
package/index.js ADDED
@@ -0,0 +1,877 @@
1
+ /**
2
+ * 每日工作日报 · Host 插件
3
+ *
4
+ * 把原先「计划任务提示词 + 两个 PowerShell 脚本」的日报自动化收进一个插件:
5
+ * 采集、写盘、推看板由工具确定性地完成,模型只负责写正文。
6
+ *
7
+ * 不 import 任何 @deepseek-ai/* 包:本地目录安装是 link 而不是拷贝,
8
+ * 插件目录里没有 node_modules,裸导入会解析失败。工具定义直接按
9
+ * 注册表接受的普通对象写(name/description/parameters/output/execute)。
10
+ *
11
+ * @module dsh-work-summary
12
+ */
13
+
14
+ import { spawn } from 'node:child_process'
15
+ import { readFileSync } from 'node:fs'
16
+ import { appendFile, mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
17
+ import { homedir } from 'node:os'
18
+ import { dirname, join } from 'node:path'
19
+ import { fileURLToPath } from 'node:url'
20
+
21
+ export const name = 'dsh-work-summary'
22
+ export const inject = ['tools']
23
+
24
+ /** 插件自身目录:脚本与 PROMPT.md 随仓库走,不依赖数据目录。 */
25
+ const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
26
+
27
+ /** 插件的数据根:`~/.dsh/dsh-work-summary`,首次激活时创建。测试或多实例可用环境变量改。 */
28
+ const DATA_HOME = process.env.DSH_WORK_SUMMARY_HOME?.trim() || join(homedir(), '.dsh', 'dsh-work-summary')
29
+
30
+ /** 设置文件固定在数据根下:改了 reportDir 之后仍然读得到自己存过的值。 */
31
+ const SETTINGS_FILE = join(DATA_HOME, 'settings.json')
32
+
33
+ /** 插件配置默认值;patch 里的 config 覆盖同名键。 */
34
+ const DEFAULTS = {
35
+ /** 数据目录:日报、看板、源数据、日志都在这里;设置页可改。 */
36
+ reportDir: DATA_HOME,
37
+ /** 采集脚本扫描的工作区根(collect-day.ps1 -Workspace);默认也是数据根。 */
38
+ workspace: DATA_HOME,
39
+ /** 脚本目录:默认随插件仓库。 */
40
+ scriptDir: join(PLUGIN_DIR, 'scripts'),
41
+ /** 日报正文规则;默认随插件仓库。 */
42
+ promptPath: join(PLUGIN_DIR, 'PROMPT.md'),
43
+ /** PowerShell 可执行文件。 */
44
+ pwsh: 'pwsh',
45
+ /** 单个脚本的超时(毫秒)。 */
46
+ timeoutMs: 240000,
47
+ /** daily_report_save 默认是否顺带推看板。 */
48
+ pushOnSave: true,
49
+ /** 是否让插件托管每日计划任务。 */
50
+ scheduleEnabled: true,
51
+ /** 已有旧日报计划任务时,改写它的提示词而不是再建一个。 */
52
+ scheduleAdopt: true,
53
+ /** 插件自己创建的计划的标题。 */
54
+ scheduleTitle: '每日工作日报',
55
+ /** 计划时间 HH:mm(24 小时制)。 */
56
+ scheduleTime: '23:00',
57
+ /** 计划时区。 */
58
+ scheduleTimeZone: 'Asia/Shanghai',
59
+ /** 运行日志目录;留空表示 `<reportDir>\_日志`。设置页改的是这个键。 */
60
+ logDir: '',
61
+ }
62
+
63
+ /** 日报固定小节,顺序即写入顺序。 */
64
+ const SECTIONS = [
65
+ ['一', '今日概览'],
66
+ ['二', '做了什么'],
67
+ ['三', '结果与产出'],
68
+ ['四', '问题与风险'],
69
+ ['五', '后续建议'],
70
+ ['六', '明日开场清单'],
71
+ ]
72
+
73
+ /**
74
+ * 合并配置:只让显式给出的值覆盖默认值。
75
+ * @param {Record<string, unknown>} config - patch 里的 config。
76
+ * @returns {typeof DEFAULTS} 生效配置。
77
+ */
78
+ function resolveConfig(config) {
79
+ const merged = { ...DEFAULTS }
80
+ for (const [key, value] of Object.entries(config ?? {})) {
81
+ if (value !== undefined && value !== null) merged[key] = value
82
+ }
83
+ // 设置页保存的值优先级最高:那是用户在 UI 里的显式选择,重启后要能存活。
84
+ const saved = readSettings()
85
+ if (typeof saved.logDir === 'string' && saved.logDir.trim() !== '') merged.logDir = saved.logDir.trim()
86
+ if (typeof saved.reportDir === 'string' && saved.reportDir.trim() !== '') merged.reportDir = saved.reportDir.trim()
87
+ if (typeof saved.workspace === 'string' && saved.workspace.trim() !== '') merged.workspace = saved.workspace.trim()
88
+ return merged
89
+ }
90
+
91
+ /**
92
+ * 读取设置页保存的选项(数据根下的 settings.json)。读不到就是空对象。
93
+ * @returns {Record<string, unknown>} 已保存的键值。
94
+ */
95
+ function readSettings() {
96
+ try {
97
+ const parsed = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8'))
98
+ return parsed && typeof parsed === 'object' ? parsed : {}
99
+ } catch {
100
+ return {}
101
+ }
102
+ }
103
+
104
+ /**
105
+ * 运行日志目录:显式配置优先,否则落在数据目录下的 `_日志`。
106
+ * @param {typeof DEFAULTS} config - 生效配置。
107
+ * @returns {string} 目录路径。
108
+ */
109
+ function logDirOf(config) {
110
+ const explicit = String(config.logDir ?? '').trim()
111
+ return explicit !== '' ? explicit : join(config.reportDir, '_日志')
112
+ }
113
+
114
+ /**
115
+ * 某时区的 `HH:mm:ss`。
116
+ * @param {string} timeZone - IANA 时区。
117
+ * @returns {string} 时刻。
118
+ */
119
+ function clockInZone(timeZone) {
120
+ return new Intl.DateTimeFormat('en-GB', {
121
+ timeZone, hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
122
+ }).format(new Date())
123
+ }
124
+
125
+ /**
126
+ * 往当天的日志文件追加一行;日志写不下去只吞掉,不影响日报本身。
127
+ * @param {typeof DEFAULTS} config - 生效配置。
128
+ * @param {'info' | 'warn' | 'error'} level - 级别。
129
+ * @param {string} message - 内容。
130
+ * @returns {Promise<void>} 完成。
131
+ */
132
+ async function logLine(config, level, message) {
133
+ try {
134
+ const dir = logDirOf(config)
135
+ await mkdir(dir, { recursive: true })
136
+ const day = dateInZone(config.scheduleTimeZone)
137
+ const file = join(dir, `dsh-work-summary-${day}.log`)
138
+ await appendFile(file, `${day} ${clockInZone(config.scheduleTimeZone)} [${level}] ${message}\n`, 'utf8')
139
+ } catch {
140
+ // 目录不可写不该让日报流程失败。
141
+ }
142
+ }
143
+
144
+ /**
145
+ * 写回设置页的选项。只认已知键,避免任意字段被塞进配置文件。
146
+ * @param {{ reportDir?: string, logDir?: string, workspace?: string }} patch - 要保存的键。
147
+ * @returns {Promise<Record<string, unknown>>} 保存后的全部设置。
148
+ */
149
+ async function writeSettings(patch) {
150
+ const current = readSettings()
151
+ const next = {}
152
+ for (const key of ['reportDir', 'logDir', 'workspace']) {
153
+ const value = typeof patch[key] === 'string' ? patch[key] : current[key]
154
+ if (typeof value === 'string') next[key] = value
155
+ }
156
+ await mkdir(dirname(SETTINGS_FILE), { recursive: true })
157
+ await writeFile(SETTINGS_FILE, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
158
+ return next
159
+ }
160
+
161
+ /**
162
+ * 设置页要的完整状态:定时任务 + 日志目录。
163
+ * @param {Awaited<ReturnType<typeof scheduleState>>} state - 定时任务状态。
164
+ * @param {typeof DEFAULTS} config - 生效配置。
165
+ * @returns {Record<string, unknown>} 响应体。
166
+ */
167
+ function settingsPayload(state, config) {
168
+ return {
169
+ ...state,
170
+ reportDir: config.reportDir,
171
+ reportDirDefault: DATA_HOME,
172
+ workspace: config.workspace,
173
+ workspaceDefault: DATA_HOME,
174
+ logDir: logDirOf(config),
175
+ logDirDefault: join(config.reportDir, '_日志'),
176
+ logPattern: 'dsh-work-summary-YYYY-MM-DD.log',
177
+ }
178
+ }
179
+
180
+ /**
181
+ * 某时区的今天。
182
+ * @param {string} timeZone - IANA 时区。
183
+ * @returns {string} YYYY-MM-DD。
184
+ */
185
+ function dateInZone(timeZone) {
186
+ return new Intl.DateTimeFormat('en-CA', {
187
+ timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
188
+ }).format(new Date())
189
+ }
190
+
191
+ /**
192
+ * 某时区的当前时间戳。
193
+ * @param {string} timeZone - IANA 时区。
194
+ * @returns {string} YYYY-MM-DD HH:mm。
195
+ */
196
+ function stampInZone(timeZone) {
197
+ const parts = new Intl.DateTimeFormat('en-CA', {
198
+ timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
199
+ hour: '2-digit', minute: '2-digit', hour12: false,
200
+ }).formatToParts(new Date())
201
+ const get = type => parts.find(part => part.type === type)?.value ?? ''
202
+ return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}`
203
+ }
204
+
205
+ /**
206
+ * 列出缺失的固定小节标题。
207
+ * @param {string} text - 日报正文。
208
+ * @returns {string[]} 形如 `## 一、今日概览`。
209
+ */
210
+ function missingSections(text) {
211
+ const missing = []
212
+ for (const [num, title] of SECTIONS) {
213
+ const pattern = new RegExp(`^##\\s*${num}\\s*[、..]\\s*${title}`, 'm')
214
+ if (!pattern.test(text)) missing.push(`## ${num}、${title}`)
215
+ }
216
+ return missing
217
+ }
218
+
219
+ /**
220
+ * 日报骨架,交给模型填空。
221
+ * @param {string} date - YYYY-MM-DD。
222
+ * @returns {string} Markdown 模板。
223
+ */
224
+ function buildTemplate(date) {
225
+ return [
226
+ `# 工作日报 · ${date}`,
227
+ '',
228
+ '## 一、今日概览',
229
+ '(3–5 句:今天的主线、投入方向、一句话结论)',
230
+ '',
231
+ '## 二、做了什么',
232
+ '(按主题分组,不按时间流水账;每条写清「做了什么 → 落在哪个路径/模块」,并给证据)',
233
+ '',
234
+ '## 三、结果与产出',
235
+ '(表格:产出物 | 路径 | 状态(完成/进行中/待验证)| 说明)',
236
+ '',
237
+ '## 四、问题与风险',
238
+ '(暴露的问题、未通过的验证、遗留脏数据;每条给出影响面)',
239
+ '',
240
+ '## 五、后续建议',
241
+ '(3–6 条,按优先级;每条:建议 | 为什么现在做 | 预估工作量 | 何时做)',
242
+ '',
243
+ '## 六、明日开场清单',
244
+ '(明天 30 分钟内能动手的 3 件事,具体到文件/命令)',
245
+ ].join('\n')
246
+ }
247
+
248
+ /**
249
+ * 看板文件路径(push-to-board.ps1 的 -BoardPath)。
250
+ * @param {typeof DEFAULTS} config - 生效配置。
251
+ * @returns {string} 看板路径。
252
+ */
253
+ function boardPathOf(config) {
254
+ return join(config.reportDir, '看板.md')
255
+ }
256
+
257
+ /**
258
+ * 读看板里的未完成条目。
259
+ * @param {string} reportDir - 日报目录。
260
+ * @returns {Promise<{open: string[], text: string}>} 未完成条目与看板全文。
261
+ */
262
+ async function readBoard(reportDir) {
263
+ try {
264
+ const text = await readFile(join(reportDir, '看板.md'), 'utf8')
265
+ const open = text.split(/\r?\n/).map(line => line.trim()).filter(line => /^- \[ \]/.test(line))
266
+ return { open, text }
267
+ } catch {
268
+ return { open: [], text: '' }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * 取输出末尾若干行用于报错。
274
+ * @param {string} text - 进程输出。
275
+ * @returns {string} 截断后的输出。
276
+ */
277
+ function tail(text) {
278
+ const trimmed = String(text ?? '').trim()
279
+ return trimmed.length > 1200 ? `…${trimmed.slice(-1200)}` : trimmed
280
+ }
281
+
282
+ /**
283
+ * 允许以裸参数形式传给脚本的开关;其余参数一律当作字符串字面量。
284
+ * 注意:PowerShell 里给参数名加引号它就变成普通位置参数了(实测
285
+ * `& script '-Date' x` 会把 "-Date" 绑到第一个位置参数),所以新增开关必须补进这里。
286
+ */
287
+ const PS_SWITCHES = new Set([
288
+ '-Date', '-NoSessions', '-Report', '-BoardPath', '-Show', '-Done', '-Drop', '-DryRun',
289
+ '-Workspace', '-ReportDir', '-DshHome',
290
+ ])
291
+
292
+ /**
293
+ * 运行一次 PowerShell 脚本。
294
+ * @param {string} command - pwsh 可执行文件。
295
+ * @param {string[]} args - 参数。
296
+ * @param {AbortSignal | undefined} signal - 调用方取消信号。
297
+ * @param {number} timeoutMs - 超时。
298
+ * @returns {Promise<{code: number, stdout: string, stderr: string}>} 退出码与输出。
299
+ */
300
+ function runProcess(command, args, signal, timeoutMs) {
301
+ return new Promise((resolve) => {
302
+ const child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
303
+ let stdout = ''
304
+ let stderr = ''
305
+ let settled = false
306
+ const timer = setTimeout(() => {
307
+ if (!settled) child.kill()
308
+ }, timeoutMs)
309
+ const finish = (code, note) => {
310
+ if (settled) return
311
+ settled = true
312
+ clearTimeout(timer)
313
+ signal?.removeEventListener?.('abort', onAbort)
314
+ resolve({ code, stdout, stderr: note ? `${stderr}\n${note}` : stderr })
315
+ }
316
+ const onAbort = () => child.kill()
317
+ signal?.addEventListener?.('abort', onAbort, { once: true })
318
+ child.stdout?.setEncoding('utf8')
319
+ child.stderr?.setEncoding('utf8')
320
+ child.stdout?.on('data', (chunk) => { stdout += chunk })
321
+ child.stderr?.on('data', (chunk) => { stderr += chunk })
322
+ child.on('error', error => finish(-1, `无法启动 ${command}:${error.message}`))
323
+ child.on('close', code => finish(code ?? -1, code === null ? '进程被超时或取消终止' : ''))
324
+ })
325
+ }
326
+
327
+ /**
328
+ * 运行日报目录里的某个脚本。
329
+ * @param {typeof DEFAULTS} config - 生效配置。
330
+ * @param {string} script - 脚本文件名。
331
+ * @param {string[]} args - 脚本参数。
332
+ * @param {AbortSignal | undefined} signal - 取消信号。
333
+ * @returns {Promise<{code: number, stdout: string, stderr: string}>} 结果。
334
+ */
335
+ function runScript(config, script, args, signal) {
336
+ // 用 -Command 而不是 -File:只有进到 PowerShell 里才能先把控制台输出编码
337
+ // 设成 UTF-8(-File 模式没有插话的位置)。管道重定向下 pwsh 默认按系统
338
+ // ANSI(936)写 stdout,Node 按 utf8 解码就会得到乱码,中文解析全失效。
339
+ const command = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; '
340
+ + '$OutputEncoding = [System.Text.Encoding]::UTF8; '
341
+ + `& ${[psQuote(join(config.scriptDir, script)), ...args.map(psArg)].join(' ')}`
342
+ const started = Date.now()
343
+ return runProcess(
344
+ config.pwsh,
345
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command],
346
+ signal,
347
+ config.timeoutMs,
348
+ ).then((result) => {
349
+ const head = `${script} ${args.join(' ')} → exit ${result.code},${Date.now() - started}ms`
350
+ if (result.code === 0) {
351
+ void logLine(config, 'info', head)
352
+ } else {
353
+ void logLine(config, 'error', `${head}\n${tail(result.stderr || result.stdout, 800)}`)
354
+ }
355
+ return result
356
+ })
357
+ }
358
+
359
+ /**
360
+ * 把单个命令行参数转成 PowerShell 里的写法。
361
+ * 已知开关保持裸写(`-Date`),其余一律按单引号字面量引用,值里的 `'` 翻倍。
362
+ * @param {string} arg - 原始参数。
363
+ * @returns {string} PowerShell 写法。
364
+ */
365
+ function psArg(arg) {
366
+ return PS_SWITCHES.has(arg) ? arg : psQuote(arg)
367
+ }
368
+
369
+ /**
370
+ * 引用一个 PowerShell 单引号字符串字面量。
371
+ * @param {string} value - 原始字符串。
372
+ * @returns {string} 带引号的字面量。
373
+ */
374
+ function psQuote(value) {
375
+ return `'${String(value).replace(/'/g, "''")}'`
376
+ }
377
+
378
+ /** 文本输出的通用渲染。 */
379
+ const renderText = (_args, value) => [{ type: 'text', text: value.text }]
380
+
381
+ /** 侧边栏页面要的一份只读快照:看板全文 + 最近若干天日报正文。 */
382
+ async function readState(config) {
383
+ const board = await readBoard(config.reportDir)
384
+ const lines = board.text.split(/\r?\n/).map(line => line.trim())
385
+ let names = []
386
+ try {
387
+ names = (await readdir(config.reportDir)).filter(name => /^日报-\d{4}-\d{2}-\d{2}\.md$/.test(name))
388
+ } catch {
389
+ names = []
390
+ }
391
+ const reports = []
392
+ for (const name of names.sort().reverse().slice(0, 90)) {
393
+ try {
394
+ const content = await readFile(join(config.reportDir, name), 'utf8')
395
+ reports.push({
396
+ date: name.slice(3, 13),
397
+ file: name,
398
+ size: Buffer.byteLength(content, 'utf8'),
399
+ content,
400
+ })
401
+ } catch {
402
+ // 单篇读不了就跳过,不让整个页面失败
403
+ }
404
+ }
405
+ return {
406
+ reportDir: config.reportDir,
407
+ updatedAt: new Date().toISOString(),
408
+ board: {
409
+ text: board.text,
410
+ open: board.open.length,
411
+ done: lines.filter(line => /^- \[x\]/i.test(line)).length,
412
+ },
413
+ reports,
414
+ }
415
+ }
416
+
417
+ /** 找出插件托管的那条日报任务:标题前缀或提示词特征都算。 */
418
+ function findOwnTask(items, config) {
419
+ return items.find((task) => {
420
+ const title = String(task.title ?? '')
421
+ const prompt = String(task.prompt ?? '')
422
+ return title === config.scheduleTitle
423
+ || title.startsWith(config.scheduleTitle)
424
+ || /daily_report_collect|dsh-work-summary/.test(prompt)
425
+ }) ?? null
426
+ }
427
+
428
+ /** 从任务的 rrule 里读出小时、分钟与时区。 */
429
+ function parseRruleTime(task) {
430
+ const rrule = String(task?.rrule ?? '')
431
+ const start = /DTSTART(?:;TZID=([^:]+))?:(\d{8})T(\d{2})(\d{2})/.exec(rrule)
432
+ const byHour = /BYHOUR=(\d{1,2})/.exec(rrule)
433
+ const byMinute = /BYMINUTE=(\d{1,2})/.exec(rrule)
434
+ const hour = byHour ? Number(byHour[1]) : start ? Number(start[3]) : null
435
+ const minute = byMinute ? Number(byMinute[1]) : start ? Number(start[4]) : null
436
+ return { hour, minute, timeZone: start?.[1] ?? null }
437
+ }
438
+
439
+ /** 每天固定时刻的 rrule(与既有任务同一种写法)。 */
440
+ function dailyRrule(timeZone, time) {
441
+ const [hour, minute] = String(time).split(':').map(Number)
442
+ const today = dateInZone(timeZone).replace(/-/g, '')
443
+ const hh = String(hour).padStart(2, '0')
444
+ const mm = String(minute).padStart(2, '0')
445
+ return `DTSTART;TZID=${timeZone}:${today}T${hh}${mm}00\nRRULE:FREQ=DAILY;INTERVAL=1;BYHOUR=${hour};BYMINUTE=${minute}`
446
+ }
447
+
448
+ /** 设置页要的定时任务状态。 */
449
+ async function scheduleState(scheduleCtx, config) {
450
+ const page = await scheduleCtx.schedule.list({ limit: 200 })
451
+ const task = findOwnTask(page.items ?? [], config)
452
+ if (!task) {
453
+ return { found: false, scheduleTitle: config.scheduleTitle, timeZone: config.scheduleTimeZone, time: config.scheduleTime }
454
+ }
455
+ const parsed = parseRruleTime(task)
456
+ const hour = parsed.hour ?? Number(config.scheduleTime.split(':')[0])
457
+ const minute = parsed.minute ?? Number(config.scheduleTime.split(':')[1] ?? 0)
458
+ return {
459
+ found: true,
460
+ id: task.id,
461
+ title: task.title,
462
+ active: task.status === 'active',
463
+ time: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
464
+ timeZone: parsed.timeZone ?? config.scheduleTimeZone,
465
+ nextRunAt: task.scheduledAtLocal ?? task.scheduledAt ?? null,
466
+ target: task.target?.kind ?? null,
467
+ }
468
+ }
469
+
470
+ /**
471
+ * 注册三个工具,并按配置托管计划任务。
472
+ * @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
473
+ * @param {Record<string, unknown>} rawConfig - patch 配置。
474
+ * @returns {void}
475
+ */
476
+ export function apply(ctx, rawConfig) {
477
+ const config = resolveConfig(rawConfig)
478
+
479
+ // 装好第一次激活就把目录建出来;之后所有产物都落在它们下面。建不出来也不该拖垮插件。
480
+ void mkdir(DATA_HOME, { recursive: true }).catch(() => {})
481
+ void mkdir(config.reportDir, { recursive: true }).catch(() => {})
482
+ void mkdir(config.workspace, { recursive: true }).catch(() => {})
483
+
484
+ ctx.tools.register({
485
+ name: 'daily_report_collect',
486
+ description:
487
+ '采集某一天的工作痕迹,生成日报的源数据文件并返回它的路径、小节清单和日报模板。'
488
+ + '写日报前先调用它:结果里的 sourcePath 要读一遍,template 是必须填满的六节骨架。'
489
+ + '采集是只读的,只写 _源数据 目录。',
490
+ parameters: {
491
+ type: 'object',
492
+ additionalProperties: false,
493
+ properties: {
494
+ date: { type: 'string', description: '本地日期 YYYY-MM-DD,默认今天。补写往日日报时传。' },
495
+ sessions: { type: 'boolean', description: '是否解析 DSH 会话,默认 true;工作区文件很多时可设 false 提速。' },
496
+ },
497
+ },
498
+ output: {
499
+ schema: {
500
+ type: 'object',
501
+ additionalProperties: false,
502
+ required: ['date', 'sourcePath', 'lines', 'boardOpen', 'template'],
503
+ properties: {
504
+ date: { type: 'string' },
505
+ sourcePath: { type: 'string' },
506
+ lines: { type: 'integer' },
507
+ bytes: { type: 'integer' },
508
+ headings: { type: 'array', items: { type: 'string' } },
509
+ boardOpen: { type: 'integer' },
510
+ template: { type: 'string' },
511
+ },
512
+ },
513
+ render: (_args, value) => [{
514
+ type: 'text',
515
+ text: `已采集 ${value.date} → ${value.sourcePath}(${value.lines} 行,看板未完成 ${value.boardOpen} 条)。`
516
+ + (value.headings?.length
517
+ ? `\n\n采集到的小节:\n${value.headings.map(h => `- ${h.replace(/^##\s*/, '')}`).join('\n')}`
518
+ : '')
519
+ + `\n\n日报模板(把每节内容替换掉提示语):\n\n\`\`\`markdown\n${value.template}\n\`\`\``,
520
+ }],
521
+ },
522
+ async execute(args, exec) {
523
+ const date = args.date ?? dateInZone(config.scheduleTimeZone)
524
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error(`日期格式应为 YYYY-MM-DD,收到:${date}`)
525
+ const result = await runScript(
526
+ config,
527
+ 'collect-day.ps1',
528
+ [
529
+ '-Date', date,
530
+ '-Workspace', config.workspace,
531
+ '-ReportDir', config.reportDir,
532
+ ...(args.sessions === false ? ['-NoSessions'] : []),
533
+ ],
534
+ exec.signal,
535
+ )
536
+ if (result.code !== 0) {
537
+ throw new Error(`采集失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
538
+ }
539
+ let text
540
+ try {
541
+ text = await readFile(join(config.reportDir, '_源数据', `${date}.md`), 'utf8')
542
+ } catch (error) {
543
+ throw new Error(`采集脚本未产出 ${date} 的源数据:${tail(result.stdout) || String(error)}`)
544
+ }
545
+ const lines = text.split(/\r?\n/)
546
+ const headings = lines.filter(line => /^##\s/.test(line)).map(line => line.trim())
547
+ const board = await readBoard(config.reportDir)
548
+ return {
549
+ date,
550
+ sourcePath: join(config.reportDir, '_源数据', `${date}.md`),
551
+ lines: lines.length,
552
+ bytes: Buffer.byteLength(text, 'utf8'),
553
+ headings,
554
+ boardOpen: board.open.length,
555
+ template: buildTemplate(date),
556
+ }
557
+ },
558
+ })
559
+
560
+ ctx.tools.register({
561
+ name: 'daily_report_save',
562
+ description:
563
+ '校验并落盘当天日报,然后把它「六、明日开场清单」推进看板。'
564
+ + '正文必须包含六个固定小节(一、今日概览 … 六、明日开场清单);缺节或留占位符会直接报错且不写文件,'
565
+ + '按报错修好后重调即可。已存在同名日报会被整篇覆盖。',
566
+ parameters: {
567
+ type: 'object',
568
+ additionalProperties: false,
569
+ required: ['content'],
570
+ properties: {
571
+ content: { type: 'string', description: '完整日报 Markdown 正文,从 `# 工作日报 · 日期` 开始。' },
572
+ date: { type: 'string', description: '本地日期 YYYY-MM-DD,默认今天。' },
573
+ push: { type: 'boolean', description: '是否推送看板,默认 true。' },
574
+ },
575
+ },
576
+ output: {
577
+ schema: {
578
+ type: 'object',
579
+ additionalProperties: false,
580
+ required: ['date', 'reportPath', 'pushed', 'skipped', 'boardOpen'],
581
+ properties: {
582
+ date: { type: 'string' },
583
+ reportPath: { type: 'string' },
584
+ pushed: { type: 'integer' },
585
+ skipped: { type: 'integer' },
586
+ boardOpen: { type: 'integer' },
587
+ text: { type: 'string' },
588
+ },
589
+ },
590
+ render: (_args, value) => [{ type: 'text', text: value.text }],
591
+ },
592
+ async execute(args, exec) {
593
+ const date = args.date ?? dateInZone(config.scheduleTimeZone)
594
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error(`日期格式应为 YYYY-MM-DD,收到:${date}`)
595
+ const content = String(args.content ?? '')
596
+ const problems = []
597
+ const missing = missingSections(content)
598
+ if (missing.length > 0) problems.push(`缺少小节:${missing.join('、')}`)
599
+ const body = content.replace(/^#[^\n]*\n/m, '')
600
+ if (body.trim().length < 200) problems.push(`正文过短(${body.trim().length} 字符),确认不是只写了骨架`)
601
+ if (/\bTODO\b|待填|\{\{/.test(content)) problems.push('仍留有占位符(TODO / 待填 / {{…}})')
602
+ if (problems.length > 0) {
603
+ throw new Error(`日报未写入,先修正:\n- ${problems.join('\n- ')}`)
604
+ }
605
+
606
+ const stamp = stampInZone(config.scheduleTimeZone)
607
+ const withFooter = /数据来源:/.test(content)
608
+ ? content
609
+ : `${content.replace(/\s*$/, '')}\n\n---\n数据来源:\`_源数据\\${date}.md\` | 生成时间:${stamp}\n`
610
+ const reportPath = join(config.reportDir, `日报-${date}.md`)
611
+ await mkdir(config.reportDir, { recursive: true })
612
+ await writeFile(reportPath, withFooter, 'utf8')
613
+
614
+ const shouldPush = args.push ?? config.pushOnSave
615
+ let pushed = 0
616
+ let skipped = 0
617
+ let pushText = ''
618
+ if (shouldPush) {
619
+ const result = await runScript(config, 'push-to-board.ps1', ['-Report', reportPath, '-BoardPath', boardPathOf(config)], exec.signal)
620
+ if (result.code !== 0) {
621
+ throw new Error(`日报已写入 ${reportPath},但推送看板失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
622
+ }
623
+ pushText = result.stdout.trim()
624
+ const match = /已写入\s*(\d+)\s*条[,,]\s*跳过重复\s*(\d+)\s*条/.exec(pushText)
625
+ if (match) {
626
+ pushed = Number(match[1])
627
+ skipped = Number(match[2])
628
+ }
629
+ }
630
+ const board = await readBoard(config.reportDir)
631
+ const summary = shouldPush
632
+ ? `日报已写入 ${reportPath};看板 ${pushed ? `新增 ${pushed} 条` : '无新增条目'}${skipped ? `,跳过重复 ${skipped} 条` : ''},当前未完成 ${board.open.length} 条。`
633
+ : `日报已写入 ${reportPath};按要求未推送看板。`
634
+ return { date, reportPath, pushed, skipped, boardOpen: board.open.length, text: `${summary}\n${pushText}`.trim() }
635
+ },
636
+ })
637
+
638
+ ctx.tools.register({
639
+ name: 'daily_report_board',
640
+ description:
641
+ '查看或维护工作看板(_日报\\看板.md)。show 列出未完成待办;done 把匹配的待办移到「已完成」;'
642
+ + 'drop 把决定不做的移到「已放弃」(不是完成)。done/drop 需要 keyword,按标题子串匹配。',
643
+ parameters: {
644
+ type: 'object',
645
+ additionalProperties: false,
646
+ required: ['action'],
647
+ properties: {
648
+ action: { type: 'string', enum: ['show', 'done', 'drop'], description: 'show | done | drop。' },
649
+ keyword: { type: 'string', description: 'done/drop 必填,待办标题里的关键词。' },
650
+ },
651
+ },
652
+ output: {
653
+ schema: {
654
+ type: 'object',
655
+ additionalProperties: false,
656
+ required: ['action', 'openCount', 'text'],
657
+ properties: {
658
+ action: { type: 'string' },
659
+ openCount: { type: 'integer' },
660
+ open: { type: 'array', items: { type: 'string' } },
661
+ text: { type: 'string' },
662
+ },
663
+ },
664
+ render: (_args, value) => [{ type: 'text', text: value.text }],
665
+ },
666
+ async execute(args, exec) {
667
+ const action = args.action
668
+ if (action !== 'show' && action !== 'done' && action !== 'drop') {
669
+ throw new Error(`未知动作:${action}`)
670
+ }
671
+ if (action !== 'show') {
672
+ const keyword = String(args.keyword ?? '').trim()
673
+ if (keyword === '') throw new Error(`${action} 需要 keyword`)
674
+ const flag = action === 'done' ? '-Done' : '-Drop'
675
+ const result = await runScript(config, 'push-to-board.ps1', [flag, keyword, '-BoardPath', boardPathOf(config)], exec.signal)
676
+ if (result.code !== 0) {
677
+ throw new Error(`${action} 失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
678
+ }
679
+ const board = await readBoard(config.reportDir)
680
+ return {
681
+ action,
682
+ openCount: board.open.length,
683
+ open: board.open,
684
+ text: `${result.stdout.trim()}\n未完成 ${board.open.length} 条。`.trim(),
685
+ }
686
+ }
687
+ const result = await runScript(config, 'push-to-board.ps1', ['-Show', '-BoardPath', boardPathOf(config)], exec.signal)
688
+ if (result.code !== 0) {
689
+ throw new Error(`读取看板失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
690
+ }
691
+ const board = await readBoard(config.reportDir)
692
+ const listed = board.open.slice(0, 30).join('\n')
693
+ return {
694
+ action,
695
+ openCount: board.open.length,
696
+ open: board.open.slice(0, 50),
697
+ text: board.open.length === 0
698
+ ? '看板没有未完成待办。'
699
+ : `未完成 ${board.open.length} 条:\n${listed}`,
700
+ }
701
+ },
702
+ })
703
+
704
+ // 侧边栏「日报」页面读的数据:只读、同源、不缓存。Host 没接 Web 服务时这段自动缺席。
705
+ ctx.inject(['webServer'], (webCtx) => {
706
+ const dispose = webCtx.webServer.register({
707
+ kind: 'exact',
708
+ path: '/dsh-work-summary/state',
709
+ resource: async () => {
710
+ try {
711
+ const payload = await readState(config)
712
+ return new Response(JSON.stringify(payload), {
713
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
714
+ })
715
+ } catch (error) {
716
+ return new Response(JSON.stringify({ error: String(error?.message ?? error) }), {
717
+ status: 500,
718
+ headers: { 'content-type': 'application/json; charset=utf-8' },
719
+ })
720
+ }
721
+ },
722
+ })
723
+ return () => { if (typeof dispose === 'function') dispose() }
724
+ })
725
+
726
+ // 设置页:读/改那条日报计划任务。任务的 rrule 就是唯一真源,不另存一份配置。
727
+ ctx.inject(['webServer', 'schedule'], (sc) => {
728
+ const send = (res, status, value) => {
729
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
730
+ res.end(JSON.stringify(value))
731
+ }
732
+ const dispose = sc.webServer.register({
733
+ kind: 'exact',
734
+ path: '/dsh-work-summary/schedule',
735
+ handler: async (req, res) => {
736
+ try {
737
+ if (req.method === 'GET' || req.method === 'HEAD') {
738
+ send(res, 200, settingsPayload(await scheduleState(sc, config), config))
739
+ return
740
+ }
741
+ if (req.method !== 'POST') {
742
+ res.writeHead(405, { allow: 'GET, HEAD, POST' })
743
+ res.end()
744
+ return
745
+ }
746
+ const chunks = []
747
+ for await (const chunk of req) chunks.push(chunk)
748
+ const raw = Buffer.concat(chunks).toString('utf8')
749
+ const body = raw.trim() === '' ? {} : JSON.parse(raw)
750
+ const patch = {}
751
+ if (typeof body.time === 'string' || typeof body.active === 'boolean') {
752
+ const current = await scheduleState(sc, config)
753
+ if (!current.found) throw new Error('没找到日报计划任务;先重启一次让插件把它建出来')
754
+ if (typeof body.time === 'string') {
755
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(body.time)) throw new Error(`时间格式应为 HH:MM,收到:${body.time}`)
756
+ patch.timing = { kind: 'rrule', rrule: dailyRrule(current.timeZone, body.time) }
757
+ }
758
+ if (typeof body.active === 'boolean') patch.active = body.active
759
+ }
760
+ if (body.reportDir !== undefined) {
761
+ if (typeof body.reportDir !== 'string') throw new Error('reportDir 应为字符串')
762
+ const value = body.reportDir.trim()
763
+ if (!/^[A-Za-z]:[\\/]|^\\\\|^\//.test(value)) {
764
+ throw new Error('日报目录要写绝对路径,比如 D:\\reports')
765
+ }
766
+ await mkdir(value, { recursive: true })
767
+ await writeSettings({ reportDir: value })
768
+ config.reportDir = value
769
+ await logLine(config, 'info', `日报目录改为 ${value}(日报、看板、源数据都写到这里)`)
770
+ }
771
+ if (body.workspace !== undefined) {
772
+ if (typeof body.workspace !== 'string') throw new Error('workspace 应为字符串')
773
+ const value = body.workspace.trim()
774
+ if (!/^[A-Za-z]:[\\/]|^\\\\|^\//.test(value)) {
775
+ throw new Error('工作空间要写绝对路径,比如 D:\\projects')
776
+ }
777
+ await mkdir(value, { recursive: true })
778
+ await writeSettings({ workspace: value })
779
+ config.workspace = value
780
+ await logLine(config, 'info', `工作空间改为 ${value}(日报会扫描这里当天的改动)`)
781
+ }
782
+ if (body.logDir !== undefined) {
783
+ if (typeof body.logDir !== 'string') throw new Error('logDir 应为字符串')
784
+ const value = body.logDir.trim()
785
+ if (value !== '' && !/^[A-Za-z]:[\\/]|^\\\\|^\//.test(value)) {
786
+ throw new Error('日志目录要写绝对路径,比如 D:\\logs;留空表示用数据目录下的 _日志')
787
+ }
788
+ const target = value === '' ? join(config.reportDir, '_日志') : value
789
+ await mkdir(target, { recursive: true })
790
+ await writeSettings({ logDir: value })
791
+ config.logDir = value
792
+ await logLine(config, 'info', `日志目录改为 ${logDirOf(config)}`)
793
+ }
794
+ if (Object.keys(patch).length === 0 && body.logDir === undefined && body.reportDir === undefined && body.workspace === undefined) {
795
+ throw new Error('没有要改的字段(time / active / reportDir / workspace / logDir)')
796
+ }
797
+ if (Object.keys(patch).length > 0) {
798
+ await sc.schedule.edit({ id: (await scheduleState(sc, config)).id, action: 'update', patch })
799
+ }
800
+ send(res, 200, settingsPayload(await scheduleState(sc, config), config))
801
+ } catch (error) {
802
+ send(res, 400, { error: String(error?.message ?? error) })
803
+ }
804
+ },
805
+ })
806
+ return () => { if (typeof dispose === 'function') dispose() }
807
+ })
808
+
809
+ if (config.scheduleEnabled) installSchedule(ctx, config)
810
+ }
811
+
812
+ /**
813
+ * 插件自管的每日计划任务:已有同标题任务就同步提示词;
814
+ * 否则认领引用 collect-day.ps1 的旧任务(改写提示词),都没有才新建。
815
+ * 失败只记日志,不影响工具可用。
816
+ * @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
817
+ * @param {typeof DEFAULTS} config - 生效配置。
818
+ * @returns {void}
819
+ */
820
+ function installSchedule(ctx, config) {
821
+ const prompt = schedulePrompt(config)
822
+ ctx.inject(['schedule'], (scheduleCtx) => {
823
+ void (async () => {
824
+ const page = await scheduleCtx.schedule.list({ limit: 200 })
825
+ const items = page.items ?? []
826
+ const own = findOwnTask(items, config)
827
+ if (own) {
828
+ if (own.status === 'active' && own.prompt !== prompt) {
829
+ await scheduleCtx.schedule.edit({ id: own.id, action: 'update', patch: { prompt } })
830
+ ctx.logger?.info?.('dsh-work-summary: 已同步日报计划任务的提示词')
831
+ void logLine(config, 'info', `计划任务「${own.title}」的提示词已同步到当前版本`)
832
+ }
833
+ return
834
+ }
835
+ if (config.scheduleAdopt) {
836
+ const legacy = items.find(task => task.status === 'active' && /collect-day\.ps1|daily_report_collect/.test(String(task.prompt ?? '')))
837
+ if (legacy) {
838
+ await scheduleCtx.schedule.edit({ id: legacy.id, action: 'update', patch: { prompt } })
839
+ ctx.logger?.info?.(`dsh-work-summary: 已把旧日报计划任务「${legacy.title}」切到插件工具`)
840
+ void logLine(config, 'info', `已认领旧任务「${legacy.title}」,提示词切到插件工具`)
841
+ return
842
+ }
843
+ }
844
+ const today = dateInZone(config.scheduleTimeZone).replace(/-/g, '')
845
+ const [hour, minute] = config.scheduleTime.split(':')
846
+ const rrule = `DTSTART;TZID=${config.scheduleTimeZone}:${today}T${hour}${minute}00\nRRULE:FREQ=DAILY`
847
+ await scheduleCtx.schedule.create({
848
+ title: config.scheduleTitle,
849
+ prompt,
850
+ timing: { kind: 'rrule', rrule },
851
+ target: { kind: 'new_once' },
852
+ })
853
+ ctx.logger?.info?.(`dsh-work-summary: 已创建每日 ${config.scheduleTime} 的日报计划任务`)
854
+ void logLine(config, 'info', `已创建每日 ${config.scheduleTime} 的日报计划任务`)
855
+ })().catch((error) => {
856
+ ctx.logger?.warn?.(`dsh-work-summary: 计划任务处理失败:${error instanceof Error ? error.message : String(error)}`)
857
+ })
858
+ })
859
+ }
860
+
861
+ /**
862
+ * 交给计划任务执行的提示词:只说流程,细则留在 PROMPT.md。
863
+ * @param {typeof DEFAULTS} config - 生效配置。
864
+ * @returns {string} 提示词正文。
865
+ */
866
+ function schedulePrompt(config) {
867
+ return [
868
+ '每日工作日报时间到。用 dsh-work-summary 插件的工具完成今日日报:',
869
+ '',
870
+ '1. 调用 `daily_report_collect`(不传 date 即今天),然后读取返回的 sourcePath(源数据底稿)。',
871
+ `2. 按 \`${config.promptPath}\` 的规则写正文,结构用 collect 返回的 template 六节。`,
872
+ '3. 调用 `daily_report_save` 提交:它会校验结构、写日报文件、把「明日开场清单」推进看板。报错就按提示修正后重试。',
873
+ '4. 回复:日报路径 + 写入看板条数 + 三条最重要结论(≤5 行)。',
874
+ '',
875
+ '只写有证据支撑的内容,推断标「推断:」;采集失败或数据缺失就写明原因,不要编造。当天几乎无产出就写短版。',
876
+ ].join('\n')
877
+ }