dsh-work-summary 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/PROMPT.md +111 -0
- package/README.md +79 -2
- package/client.js +1233 -0
- package/cordis.patch.yml +12 -0
- package/docs/DETAIL.md +197 -0
- package/icon.svg +12 -0
- package/index.js +1812 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +56 -4
- package/scripts/collect-day.ps1 +365 -0
- package/scripts/collect-range.ps1 +388 -0
- package/scripts/push-to-board.ps1 +403 -0
package/index.js
ADDED
|
@@ -0,0 +1,1812 @@
|
|
|
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 { existsSync, 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
|
+
/** 是否让插件托管每周周报任务(每周一生成上一周)。 */
|
|
60
|
+
weekScheduleEnabled: true,
|
|
61
|
+
/** 周报计划时间 HH:mm;固定每周一。 */
|
|
62
|
+
weekScheduleTime: '01:00',
|
|
63
|
+
/** 周报计划任务标题;标题稳定才好认领和更新。 */
|
|
64
|
+
weekScheduleTitle: '每周工作周报',
|
|
65
|
+
/** 是否让插件托管每月月报任务(每月 1 号生成上个月)。 */
|
|
66
|
+
monthScheduleEnabled: true,
|
|
67
|
+
/** 月报计划时间 HH:mm;固定每月 1 号。 */
|
|
68
|
+
monthScheduleTime: '01:00',
|
|
69
|
+
/** 月报计划任务标题。 */
|
|
70
|
+
monthScheduleTitle: '每月工作月报',
|
|
71
|
+
/** 日报保存时的软校验;只提醒,不阻断落盘。 */
|
|
72
|
+
quality: { minEvidence: 3 },
|
|
73
|
+
/** 运行日志目录;留空表示 `<reportDir>\_日志`。设置页改的是这个键。 */
|
|
74
|
+
logDir: '',
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 日报固定小节,顺序即写入顺序。 */
|
|
78
|
+
const SECTIONS = [
|
|
79
|
+
['一', '今日概览'],
|
|
80
|
+
['二', '做了什么'],
|
|
81
|
+
['三', '结果与产出'],
|
|
82
|
+
['四', '问题与风险'],
|
|
83
|
+
['五', '后续建议'],
|
|
84
|
+
['六', '明日开场清单'],
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
/** 空话词库:只用于日报软校验提醒,不决定落盘与否。 */
|
|
88
|
+
const FILLER_WORDS = [
|
|
89
|
+
'继续推进', '加强沟通', '持续优化', '进一步提升', '稳步推进', '深入推进',
|
|
90
|
+
'扎实做好', '高度重视', '协同发力', '形成闭环', '提质增效', '落地见效',
|
|
91
|
+
]
|
|
92
|
+
|
|
93
|
+
/** 建议小节里算「可执行」的命令线索。 */
|
|
94
|
+
const COMMAND_HINT = /(?:^|[\s`((])(?:npm|pnpm|yarn|git|node|pwsh|powershell|python|pip|dotnet|cargo|docker|kubectl|rg|curl|make)\b|(?:^|[\s`((])(?:Get|Set|New|Remove|Test|Start|Stop|Invoke|Import|Export|Select|Where|ForEach)-[A-Za-z]+/m
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 路径/提交号线索。分开写是为了让 Windows 盘符、UNC、POSIX/相对路径、
|
|
98
|
+
* 带扩展名的文件名和 7–40 位十六进制提交号都能被认出来。
|
|
99
|
+
*/
|
|
100
|
+
const EVIDENCE_PATTERNS = [
|
|
101
|
+
/[A-Za-z]:[\\/][^\s`"'<>|,。;:、))]+/g,
|
|
102
|
+
/\\\\[^\s`"'<>|,。;:、))]+/g,
|
|
103
|
+
/(?<![\w])(?:\.{1,2}[\\/]|[A-Za-z_][\w.-]*[\\/])[^\s`"'<>|,。;:、))]+/g,
|
|
104
|
+
/\b[\w.-]+\.(?:md|ps1|js|mjs|cjs|json|ya?ml|toml|txt|log|ts|tsx|jsx|py|cs|go|rs|sh|bat|cmd|exe|svg|png)\b/gi,
|
|
105
|
+
/\b[0-9a-f]{7,40}\b/gi,
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 合并配置:只让显式给出的值覆盖默认值。
|
|
110
|
+
* @param {Record<string, unknown>} config - patch 里的 config。
|
|
111
|
+
* @returns {typeof DEFAULTS} 生效配置。
|
|
112
|
+
*/
|
|
113
|
+
function resolveConfig(config) {
|
|
114
|
+
const merged = { ...DEFAULTS }
|
|
115
|
+
for (const [key, value] of Object.entries(config ?? {})) {
|
|
116
|
+
if (value !== undefined && value !== null) merged[key] = value
|
|
117
|
+
}
|
|
118
|
+
// 设置页保存的值优先级最高:那是用户在 UI 里的显式选择,重启后要能存活。
|
|
119
|
+
const saved = readSettings()
|
|
120
|
+
if (typeof saved.logDir === 'string' && saved.logDir.trim() !== '') merged.logDir = saved.logDir.trim()
|
|
121
|
+
if (typeof saved.reportDir === 'string' && saved.reportDir.trim() !== '') merged.reportDir = saved.reportDir.trim()
|
|
122
|
+
if (typeof saved.workspace === 'string' && saved.workspace.trim() !== '') merged.workspace = saved.workspace.trim()
|
|
123
|
+
for (const key of ['weekScheduleTime', 'monthScheduleTime']) {
|
|
124
|
+
if (typeof saved[key] === 'string' && /^([01]\d|2[0-3]):[0-5]\d$/.test(saved[key])) merged[key] = saved[key]
|
|
125
|
+
}
|
|
126
|
+
for (const key of ['weekScheduleEnabled', 'monthScheduleEnabled']) {
|
|
127
|
+
if (typeof saved[key] === 'boolean') merged[key] = saved[key]
|
|
128
|
+
}
|
|
129
|
+
return merged
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 读取设置页保存的选项(数据根下的 settings.json)。读不到就是空对象。
|
|
134
|
+
* @returns {Record<string, unknown>} 已保存的键值。
|
|
135
|
+
*/
|
|
136
|
+
function readSettings() {
|
|
137
|
+
try {
|
|
138
|
+
const parsed = JSON.parse(readFileSync(SETTINGS_FILE, 'utf8'))
|
|
139
|
+
return parsed && typeof parsed === 'object' ? parsed : {}
|
|
140
|
+
} catch {
|
|
141
|
+
return {}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 运行日志目录:显式配置优先,否则落在数据目录下的 `_日志`。
|
|
147
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
148
|
+
* @returns {string} 目录路径。
|
|
149
|
+
*/
|
|
150
|
+
function logDirOf(config) {
|
|
151
|
+
const explicit = String(config.logDir ?? '').trim()
|
|
152
|
+
return explicit !== '' ? explicit : join(config.reportDir, '_日志')
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 某时区的 `HH:mm:ss`。
|
|
157
|
+
* @param {string} timeZone - IANA 时区。
|
|
158
|
+
* @returns {string} 时刻。
|
|
159
|
+
*/
|
|
160
|
+
function clockInZone(timeZone) {
|
|
161
|
+
return new Intl.DateTimeFormat('en-GB', {
|
|
162
|
+
timeZone, hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
|
|
163
|
+
}).format(new Date())
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 往当天的日志文件追加一行;日志写不下去只吞掉,不影响日报本身。
|
|
168
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
169
|
+
* @param {'info' | 'warn' | 'error'} level - 级别。
|
|
170
|
+
* @param {string} message - 内容。
|
|
171
|
+
* @returns {Promise<void>} 完成。
|
|
172
|
+
*/
|
|
173
|
+
async function logLine(config, level, message) {
|
|
174
|
+
try {
|
|
175
|
+
const dir = logDirOf(config)
|
|
176
|
+
await mkdir(dir, { recursive: true })
|
|
177
|
+
const day = dateInZone(config.scheduleTimeZone)
|
|
178
|
+
const file = join(dir, `dsh-work-summary-${day}.log`)
|
|
179
|
+
await appendFile(file, `${day} ${clockInZone(config.scheduleTimeZone)} [${level}] ${message}\n`, 'utf8')
|
|
180
|
+
} catch {
|
|
181
|
+
// 目录不可写不该让日报流程失败。
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* 写回设置页的选项。只认已知键,避免任意字段被塞进配置文件。
|
|
187
|
+
* @param {Record<string, string | boolean | undefined>} patch - 要保存的键。
|
|
188
|
+
* @returns {Promise<Record<string, unknown>>} 保存后的全部设置。
|
|
189
|
+
*/
|
|
190
|
+
async function writeSettings(patch) {
|
|
191
|
+
const current = readSettings()
|
|
192
|
+
const next = {}
|
|
193
|
+
for (const key of ['reportDir', 'logDir', 'workspace', 'weekScheduleTime', 'monthScheduleTime']) {
|
|
194
|
+
const value = typeof patch[key] === 'string' ? patch[key] : current[key]
|
|
195
|
+
if (typeof value === 'string') next[key] = value
|
|
196
|
+
}
|
|
197
|
+
for (const key of ['weekScheduleEnabled', 'monthScheduleEnabled']) {
|
|
198
|
+
const value = typeof patch[key] === 'boolean' ? patch[key] : current[key]
|
|
199
|
+
if (typeof value === 'boolean') next[key] = value
|
|
200
|
+
}
|
|
201
|
+
await mkdir(dirname(SETTINGS_FILE), { recursive: true })
|
|
202
|
+
await writeFile(SETTINGS_FILE, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
203
|
+
return next
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 设置页要的完整状态:日报/周报/月报三条定时任务 + 目录。
|
|
208
|
+
* @param {{ daily: Awaited<ReturnType<typeof scheduleState>>, week: Record<string, unknown>, month: Record<string, unknown> }} states - 定时任务状态。
|
|
209
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
210
|
+
* @returns {Record<string, unknown>} 响应体。
|
|
211
|
+
*/
|
|
212
|
+
function settingsPayload(states, config) {
|
|
213
|
+
return {
|
|
214
|
+
...states.daily,
|
|
215
|
+
reportDir: config.reportDir,
|
|
216
|
+
reportDirDefault: DATA_HOME,
|
|
217
|
+
workspace: config.workspace,
|
|
218
|
+
workspaceDefault: DATA_HOME,
|
|
219
|
+
logDir: logDirOf(config),
|
|
220
|
+
logDirDefault: join(config.reportDir, '_日志'),
|
|
221
|
+
logPattern: 'dsh-work-summary-YYYY-MM-DD.log',
|
|
222
|
+
week: states.week,
|
|
223
|
+
month: states.month,
|
|
224
|
+
weekTitle: config.weekScheduleTitle,
|
|
225
|
+
monthTitle: config.monthScheduleTitle,
|
|
226
|
+
weekTimeDefault: config.weekScheduleTime,
|
|
227
|
+
monthTimeDefault: config.monthScheduleTime,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* 某时区的今天。
|
|
233
|
+
* @param {string} timeZone - IANA 时区。
|
|
234
|
+
* @returns {string} YYYY-MM-DD。
|
|
235
|
+
*/
|
|
236
|
+
function dateInZone(timeZone) {
|
|
237
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
238
|
+
timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
239
|
+
}).format(new Date())
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* 某时区的当前时间戳。
|
|
244
|
+
* @param {string} timeZone - IANA 时区。
|
|
245
|
+
* @returns {string} YYYY-MM-DD HH:mm。
|
|
246
|
+
*/
|
|
247
|
+
function stampInZone(timeZone) {
|
|
248
|
+
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
249
|
+
timeZone, year: 'numeric', month: '2-digit', day: '2-digit',
|
|
250
|
+
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
251
|
+
}).formatToParts(new Date())
|
|
252
|
+
const get = type => parts.find(part => part.type === type)?.value ?? ''
|
|
253
|
+
return `${get('year')}-${get('month')}-${get('day')} ${get('hour')}:${get('minute')}`
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 列出缺失的固定小节标题。
|
|
258
|
+
* @param {string} text - 日报正文。
|
|
259
|
+
* @returns {string[]} 形如 `## 一、今日概览`。
|
|
260
|
+
*/
|
|
261
|
+
function missingSections(text) {
|
|
262
|
+
const missing = []
|
|
263
|
+
for (const [num, title] of SECTIONS) {
|
|
264
|
+
const pattern = new RegExp(`^##\\s*${num}\\s*[、..]\\s*${title}`, 'm')
|
|
265
|
+
if (!pattern.test(text)) missing.push(`## ${num}、${title}`)
|
|
266
|
+
}
|
|
267
|
+
return missing
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* 日报骨架,交给模型填空。
|
|
272
|
+
* @param {string} date - YYYY-MM-DD。
|
|
273
|
+
* @returns {string} Markdown 模板。
|
|
274
|
+
*/
|
|
275
|
+
function buildTemplate(date) {
|
|
276
|
+
return [
|
|
277
|
+
`# 工作日报 · ${date}`,
|
|
278
|
+
'',
|
|
279
|
+
'## 一、今日概览',
|
|
280
|
+
'(3–5 句:今天的主线、投入方向、一句话结论)',
|
|
281
|
+
'',
|
|
282
|
+
'## 二、做了什么',
|
|
283
|
+
'(按主题分组,不按时间流水账;每条写清「做了什么 → 落在哪个路径/模块」,并给证据)',
|
|
284
|
+
'',
|
|
285
|
+
'## 三、结果与产出',
|
|
286
|
+
'(表格:产出物 | 路径 | 状态(完成/进行中/待验证)| 说明)',
|
|
287
|
+
'',
|
|
288
|
+
'## 四、问题与风险',
|
|
289
|
+
'(暴露的问题、未通过的验证、遗留脏数据;每条给出影响面)',
|
|
290
|
+
'',
|
|
291
|
+
'## 五、后续建议',
|
|
292
|
+
'(3–6 条,按优先级;每条:建议 | 为什么现在做 | 预估工作量 | 何时做)',
|
|
293
|
+
'',
|
|
294
|
+
'## 六、明日开场清单',
|
|
295
|
+
'(明天 30 分钟内能动手的 3 件事,具体到文件/命令)',
|
|
296
|
+
].join('\n')
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* 周期报告(周报/月报)的类型表:标题前缀与首尾两节的名字随类型变。
|
|
301
|
+
* 中间两节固定为「关键产出」「未清与复发」。
|
|
302
|
+
*/
|
|
303
|
+
const PERIOD_KINDS = {
|
|
304
|
+
week: { label: '周报', title: '工作周报', first: '本周主线', last: '下周开场' },
|
|
305
|
+
month: { label: '月报', title: '工作月报', first: '本月主线', last: '下月开场' },
|
|
306
|
+
custom: { label: '周期报告', title: '周期总结', first: '本期主线', last: '下期开场' },
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* 解析 YYYY-MM-DD 为 UTC 零点毫秒数;格式或日期不存在都直接报错。
|
|
311
|
+
* @param {string} text - 日期。
|
|
312
|
+
* @returns {number} 毫秒时间戳。
|
|
313
|
+
*/
|
|
314
|
+
function parseDay(text) {
|
|
315
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) throw new Error(`日期格式应为 YYYY-MM-DD,收到:${text}`)
|
|
316
|
+
const [year, month, day] = text.split('-').map(Number)
|
|
317
|
+
const stamp = Date.UTC(year, month - 1, day)
|
|
318
|
+
const check = new Date(stamp)
|
|
319
|
+
if (check.getUTCFullYear() !== year || check.getUTCMonth() !== month - 1 || check.getUTCDate() !== day) {
|
|
320
|
+
throw new Error(`日期不存在:${text}`)
|
|
321
|
+
}
|
|
322
|
+
return stamp
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** 两个 YYYY-MM-DD 之间相差的天数(b - a)。 */
|
|
326
|
+
function daysBetween(from, to) {
|
|
327
|
+
return Math.round((parseDay(to) - parseDay(from)) / 86400000)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** 在 YYYY-MM-DD 上加若干天。 */
|
|
331
|
+
function shiftDay(date, delta) {
|
|
332
|
+
return new Date(parseDay(date) + delta * 86400000).toISOString().slice(0, 10)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** 某月的最后一天。 */
|
|
336
|
+
function lastDayOfMonth(date) {
|
|
337
|
+
const [year, month] = date.split('-').map(Number)
|
|
338
|
+
return new Date(Date.UTC(year, month, 0)).toISOString().slice(0, 10)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* 把工具入参解析成区间:类型、起止、天数、是否整月。
|
|
343
|
+
* 不传 from/to 时按 kind 取默认区间(week=本周一至今天,month=本月 1 号至今天);
|
|
344
|
+
* offset 表示往前数几个完整周期(周报=整周,月报=整月),定时任务用它生成上一周期。
|
|
345
|
+
* @param {{ from?: string, to?: string, kind?: 'week'|'month'|'custom', offset?: number }} args - 工具入参。
|
|
346
|
+
* @param {string} timeZone - 时区。
|
|
347
|
+
* @returns {{ from: string, to: string, kind: 'week'|'month'|'custom', span: number, wholeMonth: boolean }} 区间。
|
|
348
|
+
*/
|
|
349
|
+
function resolvePeriod(args, timeZone) {
|
|
350
|
+
let from = typeof args.from === 'string' ? args.from.trim() : ''
|
|
351
|
+
let to = typeof args.to === 'string' ? args.to.trim() : ''
|
|
352
|
+
let kind = args.kind
|
|
353
|
+
const offset = args.offset === undefined ? 0 : Number(args.offset)
|
|
354
|
+
|
|
355
|
+
if (!Number.isInteger(offset) || offset < 0 || offset > 60) {
|
|
356
|
+
throw new Error(`offset 应为 0–60 的整数,收到:${args.offset}`)
|
|
357
|
+
}
|
|
358
|
+
if (offset > 0 && (from || to)) throw new Error('给了 from/to 就不要再传 offset')
|
|
359
|
+
if ((from && !to) || (!from && to)) throw new Error('from 和 to 要么都传,要么都不传')
|
|
360
|
+
if (kind !== undefined && !Object.prototype.hasOwnProperty.call(PERIOD_KINDS, kind)) {
|
|
361
|
+
throw new Error(`kind 只能是 week / month / custom,收到:${kind}`)
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const today = dateInZone(timeZone)
|
|
365
|
+
if (!from) {
|
|
366
|
+
if (kind === 'custom') throw new Error('custom 周期需要同时给 from 和 to')
|
|
367
|
+
if (kind === 'month') {
|
|
368
|
+
const [year, month] = today.split('-').map(Number)
|
|
369
|
+
from = new Date(Date.UTC(year, month - 1 - offset, 1)).toISOString().slice(0, 10)
|
|
370
|
+
to = offset === 0 ? today : lastDayOfMonth(from)
|
|
371
|
+
} else {
|
|
372
|
+
kind = 'week'
|
|
373
|
+
const weekday = new Date(parseDay(today)).getUTCDay()
|
|
374
|
+
const monday = shiftDay(today, weekday === 0 ? -6 : 1 - weekday)
|
|
375
|
+
from = shiftDay(monday, -7 * offset)
|
|
376
|
+
to = offset === 0 ? today : shiftDay(from, 6)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const span = daysBetween(from, to) + 1
|
|
381
|
+
if (span < 1) throw new Error(`结束日期不能早于起始日期:${from} ~ ${to}`)
|
|
382
|
+
if (span > 400) throw new Error(`区间最长 400 天,当前 ${span} 天:${from} ~ ${to}`)
|
|
383
|
+
|
|
384
|
+
const wholeMonth = from.slice(0, 7) === to.slice(0, 7) && from.endsWith('-01') && to === lastDayOfMonth(from)
|
|
385
|
+
if (kind === undefined) {
|
|
386
|
+
kind = wholeMonth ? 'month' : span === 7 ? 'week' : 'custom'
|
|
387
|
+
}
|
|
388
|
+
return { from, to, kind, span, wholeMonth }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* 周期报告的文件名。整月月报用 `月报-YYYY-MM.md`,方便按月份排序。
|
|
393
|
+
* @param {{ from: string, to: string, kind: string, wholeMonth: boolean }} range - 区间。
|
|
394
|
+
* @returns {string} 文件名。
|
|
395
|
+
*/
|
|
396
|
+
function periodReportName(range) {
|
|
397
|
+
if (range.kind === 'week') return `周报-${range.from}_${range.to}.md`
|
|
398
|
+
if (range.kind === 'month') {
|
|
399
|
+
return range.wholeMonth ? `月报-${range.from.slice(0, 7)}.md` : `月报-${range.from}_${range.to}.md`
|
|
400
|
+
}
|
|
401
|
+
return `周期-${range.from}_${range.to}.md`
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* 周期报告的四节标题。首节接受「本周/本月/本期主线」,末节接受「下周/下月/下期开场」。
|
|
406
|
+
* @param {string} kind - week / month / custom。
|
|
407
|
+
* @returns {string[]} 四节标题。
|
|
408
|
+
*/
|
|
409
|
+
function periodSectionLabels(kind) {
|
|
410
|
+
const spec = PERIOD_KINDS[kind] ?? PERIOD_KINDS.custom
|
|
411
|
+
return [spec.first, '关键产出', '未清与复发', spec.last]
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* 列出周期报告缺少的固定小节;首尾两节兼容三种前缀。
|
|
416
|
+
* @param {string} text - 周期报告正文。
|
|
417
|
+
* @param {string} kind - week / month / custom。
|
|
418
|
+
* @returns {string[]} 形如 `## 一、本周主线`。
|
|
419
|
+
*/
|
|
420
|
+
function missingPeriodSections(text, kind) {
|
|
421
|
+
const holes = []
|
|
422
|
+
const specs = [
|
|
423
|
+
['一', '(?:本周|本月|本期)主线'],
|
|
424
|
+
['二', '关键产出'],
|
|
425
|
+
['三', '未清与复发'],
|
|
426
|
+
['四', '(?:下周|下月|下期)开场'],
|
|
427
|
+
]
|
|
428
|
+
for (const [num, label] of specs) {
|
|
429
|
+
const pattern = new RegExp(`^##\\s*(?:[一二三四五六七八九十]+\\s*[、..]\\s*)?${label}`, 'm')
|
|
430
|
+
if (!pattern.test(text)) holes.push(`## ${num}、${periodSectionLabels(kind)[['一', '二', '三', '四'].indexOf(num)]}`)
|
|
431
|
+
}
|
|
432
|
+
return holes
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* 周期报告骨架,交给模型填空;留着「待填」时校验会拒绝。
|
|
437
|
+
* @param {{ from: string, to: string, kind: string, wholeMonth: boolean }} range - 区间。
|
|
438
|
+
* @returns {string} Markdown 模板。
|
|
439
|
+
*/
|
|
440
|
+
function buildPeriodTemplate(range) {
|
|
441
|
+
const spec = PERIOD_KINDS[range.kind] ?? PERIOD_KINDS.custom
|
|
442
|
+
const heading = range.kind === 'month' && range.wholeMonth
|
|
443
|
+
? range.from.slice(0, 7)
|
|
444
|
+
: `${range.from} ~ ${range.to}`
|
|
445
|
+
const labels = periodSectionLabels(range.kind)
|
|
446
|
+
return [
|
|
447
|
+
`# ${spec.title} · ${heading}`,
|
|
448
|
+
'',
|
|
449
|
+
`> 区间:${range.from} ~ ${range.to}(${range.span} 天)`,
|
|
450
|
+
'',
|
|
451
|
+
`## 一、${labels[0]}`,
|
|
452
|
+
'(待填:这段区间真正推进的一两条主线,给证据,不要逐日流水账)',
|
|
453
|
+
'',
|
|
454
|
+
`## 二、${labels[1]}`,
|
|
455
|
+
'(待填:产出物 | 路径 | 状态 | 说明;只写区间内新增或完成的)',
|
|
456
|
+
'',
|
|
457
|
+
`## 三、${labels[2]}`,
|
|
458
|
+
'(待填:仍未清掉的事项、跨天复发的风险;写明已经挂了几天)',
|
|
459
|
+
'',
|
|
460
|
+
`## 四、${labels[3]}`,
|
|
461
|
+
`(待填:下个周期开工就能动手的 3 件事,具体到文件/命令)`,
|
|
462
|
+
].join('\n')
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* 取日报某小节里的非空行。
|
|
467
|
+
* @param {string} text - 日报正文。
|
|
468
|
+
* @param {string} number - 中文序号:一/二/…
|
|
469
|
+
* @returns {string[]} 行。
|
|
470
|
+
*/
|
|
471
|
+
function sectionLines(text, number) {
|
|
472
|
+
const lines = String(text).split(/\r?\n/)
|
|
473
|
+
const startPattern = new RegExp(`^##\\s*${number}\\s*[、..]`)
|
|
474
|
+
let start = -1
|
|
475
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
476
|
+
if (startPattern.test(lines[i])) { start = i + 1; break }
|
|
477
|
+
}
|
|
478
|
+
if (start < 0) return []
|
|
479
|
+
const out = []
|
|
480
|
+
for (let i = start; i < lines.length; i += 1) {
|
|
481
|
+
if (/^##\s/.test(lines[i])) break
|
|
482
|
+
const trimmed = lines[i].trim()
|
|
483
|
+
if (trimmed === '' || /^---+$/.test(trimmed)) continue
|
|
484
|
+
out.push(trimmed)
|
|
485
|
+
}
|
|
486
|
+
return out
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* 正文里的路径/提交号引用,按去重后的条目数计。
|
|
491
|
+
* @param {string} text - 日报正文。
|
|
492
|
+
* @returns {Set<string>} 归一化后的引用。
|
|
493
|
+
*/
|
|
494
|
+
function evidenceRefs(text) {
|
|
495
|
+
const found = new Set()
|
|
496
|
+
// 链接里的域名和路径不算「工作证据」,先去掉;行内代码保留内容,方便识别 `index.js`。
|
|
497
|
+
const clean = String(text).replace(/https?:\/\/\S+/g, ' ').replace(/`([^`]*)`/g, ' $1 ')
|
|
498
|
+
for (const pattern of EVIDENCE_PATTERNS) {
|
|
499
|
+
for (const match of clean.matchAll(pattern)) {
|
|
500
|
+
const value = match[0]
|
|
501
|
+
.replace(/^[`'"([(]+/, '')
|
|
502
|
+
.replace(/[`'")\]).,;:,。;:、]+$/, '')
|
|
503
|
+
.toLowerCase()
|
|
504
|
+
if (value.length >= 2) found.add(value)
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
// 同一个 Windows 路径会同时命中「完整路径 / 相对后缀 / 文件名」,只留最长的那条,避免虚高。
|
|
508
|
+
const refs = new Set()
|
|
509
|
+
for (const value of [...found].sort((a, b) => b.length - a.length)) {
|
|
510
|
+
if ([...refs].some(existing => existing.includes(value))) continue
|
|
511
|
+
refs.add(value)
|
|
512
|
+
}
|
|
513
|
+
return refs
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** 建议小节里是否已有路径或可执行命令。 */
|
|
517
|
+
function hasPathOrCommand(text) {
|
|
518
|
+
if (evidenceRefs(text).size > 0) return true
|
|
519
|
+
if (COMMAND_HINT.test(text)) return true
|
|
520
|
+
// 反引号里带空格的多半是命令或脚本调用,例如 `collect-day.ps1 -Date 2026-11-25`。
|
|
521
|
+
return (String(text).match(/`[^`\n]+`/g) ?? []).some(span => /\s/.test(span.trim()))
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** 读取 `quality.minEvidence`:支持嵌套对象,也兼容扁平点号键;非法值退回默认 3。 */
|
|
525
|
+
function minEvidenceOf(config) {
|
|
526
|
+
const quality = config?.quality
|
|
527
|
+
const nested = quality && typeof quality === 'object' ? quality.minEvidence : quality
|
|
528
|
+
const flat = config?.['quality.minEvidence']
|
|
529
|
+
const raw = flat ?? nested ?? DEFAULTS.quality.minEvidence
|
|
530
|
+
const value = Number(raw)
|
|
531
|
+
return Number.isInteger(value) && value > 0 ? value : DEFAULTS.quality.minEvidence
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* 日报软校验:只生成提醒,不抛错,也不阻止落盘。
|
|
536
|
+
* @param {string} content - 日报正文(未补 footer)。
|
|
537
|
+
* @param {number} minEvidence - 证据引用下限。
|
|
538
|
+
* @returns {string[]} 提醒文案。
|
|
539
|
+
*/
|
|
540
|
+
function qualityWarnings(content, minEvidence) {
|
|
541
|
+
const warnings = []
|
|
542
|
+
const refs = evidenceRefs(content)
|
|
543
|
+
if (refs.size < minEvidence) {
|
|
544
|
+
warnings.push(`证据偏少:正文只有 ${refs.size} 处路径/提交号引用(建议至少 ${minEvidence} 处)`)
|
|
545
|
+
}
|
|
546
|
+
const filler = FILLER_WORDS.filter(word => String(content).includes(word))
|
|
547
|
+
if (filler.length > 0) {
|
|
548
|
+
warnings.push(`空话词:${filler.join('、')};换成具体动作、对象或结果`)
|
|
549
|
+
}
|
|
550
|
+
const advice = sectionLines(content, '五').join('\n')
|
|
551
|
+
if (advice.trim() !== '' && !hasPathOrCommand(advice)) {
|
|
552
|
+
warnings.push('「五、后续建议」没有路径或命令,建议补上具体文件、脚本或命令')
|
|
553
|
+
}
|
|
554
|
+
return warnings
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* 逐日热力值:非空行数 + 产出条目数 × 3。
|
|
559
|
+
* 行数代表当天写了多少,产出条目代表落地的结果;权重 3 让「有产出」的一天明显亮于「写得长但没产出」。
|
|
560
|
+
* @param {string} content - 日报正文。
|
|
561
|
+
* @returns {{ lines: number, outputs: number, score: number }} 统计值。
|
|
562
|
+
*/
|
|
563
|
+
function heatStats(content) {
|
|
564
|
+
const text = String(content)
|
|
565
|
+
const lines = text.split(/\r?\n/).filter((line) => {
|
|
566
|
+
const trimmed = line.trim()
|
|
567
|
+
return trimmed !== '' && !/^---+$/.test(trimmed)
|
|
568
|
+
}).length
|
|
569
|
+
let outputs = 0
|
|
570
|
+
for (const line of sectionLines(text, '三')) {
|
|
571
|
+
const trimmed = line.trim()
|
|
572
|
+
if (/^\|[\s:|-]+\|$/.test(trimmed)) continue
|
|
573
|
+
if (/^\|/.test(trimmed)) {
|
|
574
|
+
const first = trimmed.slice(1).split('|')[0].trim()
|
|
575
|
+
if (/^(产出物|项目|条目|路径)$/.test(first)) continue
|
|
576
|
+
outputs += 1
|
|
577
|
+
continue
|
|
578
|
+
}
|
|
579
|
+
if (/^(?:[-*]|\d+[.、])\s+/.test(trimmed)) outputs += 1
|
|
580
|
+
}
|
|
581
|
+
return { lines, outputs, score: lines + outputs * 3 }
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** 去掉列表序号与加粗标记,保留正文。 */
|
|
585
|
+
function cleanItem(line) {
|
|
586
|
+
return String(line).replace(/^\s*(?:\d+[.、]|[-*])\s+/, '').replace(/\*\*/g, '').trim()
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** 表格行转成「单元格 | 单元格」;不是表格行就原样返回。 */
|
|
590
|
+
function tableCells(line) {
|
|
591
|
+
const trimmed = line.trim()
|
|
592
|
+
if (!/^\|.*\|$/.test(trimmed)) return cleanItem(trimmed)
|
|
593
|
+
return trimmed.slice(1, -1).split('|').map(cell => cell.trim()).filter(Boolean).join(' | ')
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** 看板条目的标题:`日期 | 标题 | 来源…` 取第二段。 */
|
|
597
|
+
function boardTitle(line) {
|
|
598
|
+
const parts = String(line).split('|')
|
|
599
|
+
return (parts.length >= 2 ? parts[1] : parts[0]).trim()
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/** 截断过长的一行,避免自动草稿把整段原文搬进去。 */
|
|
603
|
+
function clip(text, max) {
|
|
604
|
+
const value = String(text).replace(/\s+/g, ' ').trim()
|
|
605
|
+
return value.length > max ? `${value.slice(0, max)}…` : value
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* 不传 content 时的兜底草稿:按区间日报的六节与看板拼出四节,保证验收里「直接产出可读周报」。
|
|
610
|
+
* 只做摘录和计数,不做跨天推断;模型可以在此基础上改写后再提交。
|
|
611
|
+
* @param {{ from: string, to: string, kind: string, span: number, wholeMonth: boolean }} range - 区间。
|
|
612
|
+
* @param {string[]} days - 区间内每一天。
|
|
613
|
+
* @param {Map<string, string>} daily - 日期 → 日报正文。
|
|
614
|
+
* @param {{ open: string[] }} board - 看板未完成条目。
|
|
615
|
+
* @param {string} today - 今天 YYYY-MM-DD(用于算待办已挂天数)。
|
|
616
|
+
* @returns {string} 四节正文。
|
|
617
|
+
*/
|
|
618
|
+
function composePeriodDraft(range, days, daily, board, today) {
|
|
619
|
+
const spec = PERIOD_KINDS[range.kind] ?? PERIOD_KINDS.custom
|
|
620
|
+
const labels = periodSectionLabels(range.kind)
|
|
621
|
+
const covered = days.filter(day => daily.has(day))
|
|
622
|
+
const missing = days.filter(day => !daily.has(day))
|
|
623
|
+
const heading = range.kind === 'month' && range.wholeMonth
|
|
624
|
+
? range.from.slice(0, 7)
|
|
625
|
+
: `${range.from} ~ ${range.to}`
|
|
626
|
+
|
|
627
|
+
const out = [`# ${spec.title} · ${heading}`, '', `> 区间:${range.from} ~ ${range.to}(${range.span} 天)`, '']
|
|
628
|
+
|
|
629
|
+
out.push(`## 一、${labels[0]}`, '')
|
|
630
|
+
out.push(`本区间 ${range.from} ~ ${range.to},共 ${range.span} 天;有日报 ${covered.length} 天${missing.length ? `、缺 ${missing.length} 天(${missing.map(day => day.slice(5)).join('、')})` : ''}。`)
|
|
631
|
+
out.push('')
|
|
632
|
+
if (covered.length === 0) {
|
|
633
|
+
out.push('_区间内没有日报,无法从记录里归纳主线。_')
|
|
634
|
+
} else {
|
|
635
|
+
out.push('按天摘录日报「今日概览」里的主线,未做跨天推断:')
|
|
636
|
+
out.push('')
|
|
637
|
+
for (const day of covered) {
|
|
638
|
+
const first = sectionLines(daily.get(day), '一')[0]
|
|
639
|
+
if (first) out.push(`- **${day.slice(5)}**:${clip(cleanItem(first), 180)}`)
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
out.push('')
|
|
643
|
+
|
|
644
|
+
out.push(`## 二、${labels[1]}`, '')
|
|
645
|
+
const outputs = []
|
|
646
|
+
for (const day of covered) {
|
|
647
|
+
for (const line of sectionLines(daily.get(day), '三')) {
|
|
648
|
+
if (/^\|[\s:|-]+\|$/.test(line) || /^\|\s*(产出物|建议|项目)\s*\|/.test(line)) continue
|
|
649
|
+
outputs.push(`- ${day.slice(5)}:${clip(tableCells(line), 220)}`)
|
|
650
|
+
if (outputs.length >= 24) break
|
|
651
|
+
}
|
|
652
|
+
if (outputs.length >= 24) break
|
|
653
|
+
}
|
|
654
|
+
out.push(...(outputs.length ? outputs : ['_区间日报里没有产出记录。_']))
|
|
655
|
+
out.push('')
|
|
656
|
+
|
|
657
|
+
out.push(`## 三、${labels[2]}`, '')
|
|
658
|
+
const open = Array.isArray(board.open) ? board.open : []
|
|
659
|
+
out.push(`看板当前未完成 ${open.length} 条:`)
|
|
660
|
+
out.push('')
|
|
661
|
+
if (open.length === 0) {
|
|
662
|
+
out.push('_看板没有未完成条目。_')
|
|
663
|
+
} else {
|
|
664
|
+
for (const line of open.slice(0, 8)) {
|
|
665
|
+
const bare = line.replace(/^-\s*\[ \]\s*/, '')
|
|
666
|
+
const dateMatch = /^(\d{4}-\d{2}-\d{2})/.exec(bare)
|
|
667
|
+
let age = ''
|
|
668
|
+
if (dateMatch) {
|
|
669
|
+
const gap = daysBetween(dateMatch[1], today)
|
|
670
|
+
if (gap >= 0) age = `(已挂 ${gap} 天)`
|
|
671
|
+
}
|
|
672
|
+
out.push(`- ${boardTitle(bare)}${age}`)
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
out.push('')
|
|
676
|
+
|
|
677
|
+
const riskDays = new Map()
|
|
678
|
+
for (const day of covered) {
|
|
679
|
+
for (const line of sectionLines(daily.get(day), '四')) {
|
|
680
|
+
const item = cleanItem(line)
|
|
681
|
+
const key = item
|
|
682
|
+
.replace(/([^)]*)/g, '')
|
|
683
|
+
.replace(/\d+/g, '#')
|
|
684
|
+
.replace(/[\s,。;:、!?,.;:!?()()【】\[\]「」“”"-]/g, '')
|
|
685
|
+
.slice(0, 40)
|
|
686
|
+
if (key.length < 6) continue
|
|
687
|
+
if (!riskDays.has(key)) riskDays.set(key, { dates: [], sample: clip(item, 60) })
|
|
688
|
+
const entry = riskDays.get(key)
|
|
689
|
+
if (!entry.dates.includes(day)) entry.dates.push(day)
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
const repeated = [...riskDays.values()].filter(entry => entry.dates.length >= 2).sort((a, b) => b.dates.length - a.dates.length)
|
|
693
|
+
if (repeated.length > 0) {
|
|
694
|
+
out.push('跨天重复出现的风险:')
|
|
695
|
+
out.push('')
|
|
696
|
+
for (const entry of repeated.slice(0, 6)) {
|
|
697
|
+
out.push(`- ${entry.sample}(${entry.dates.length} 天:${entry.dates.map(day => day.slice(5)).join('、')})`)
|
|
698
|
+
}
|
|
699
|
+
out.push('')
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
out.push(`## 四、${labels[3]}`, '')
|
|
703
|
+
const lastWithList = [...covered].reverse().find(day => sectionLines(daily.get(day), '六').length > 0)
|
|
704
|
+
let actions = lastWithList
|
|
705
|
+
? sectionLines(daily.get(lastWithList), '六').map(cleanItem).filter(Boolean).slice(0, 3)
|
|
706
|
+
: []
|
|
707
|
+
if (actions.length === 0) actions = open.map(boardTitle).slice(0, 3)
|
|
708
|
+
if (actions.length === 0) actions = ['先补上区间内缺失的日报,再决定下个周期主攻方向。']
|
|
709
|
+
out.push(lastWithList
|
|
710
|
+
? `取自 ${lastWithList} 日报「明日开场清单」的末版(${actions.length} 条):`
|
|
711
|
+
: `取自看板当前未完成条目(${actions.length} 条):`)
|
|
712
|
+
out.push('')
|
|
713
|
+
actions.forEach((item, index) => out.push(`${index + 1}. ${item}`))
|
|
714
|
+
out.push('')
|
|
715
|
+
|
|
716
|
+
return out.join('\n')
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** 周期报告的统一 footer:写清正文依据的区间源数据。 */
|
|
720
|
+
function withPeriodFooter(content, range, stamp) {
|
|
721
|
+
if (/数据来源:/.test(content)) return content
|
|
722
|
+
const source = `_源数据\\周期-${range.from}_${range.to}.md`
|
|
723
|
+
return `${content.replace(/\s*$/, '')}\n\n---\n数据来源:\`${source}\` | 生成时间:${stamp}\n`
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* 看板文件路径(push-to-board.ps1 的 -BoardPath)。
|
|
728
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
729
|
+
* @returns {string} 看板路径。
|
|
730
|
+
*/
|
|
731
|
+
function boardPathOf(config) {
|
|
732
|
+
return join(config.reportDir, '看板.md')
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* 读看板里的未完成条目。
|
|
737
|
+
* @param {string} reportDir - 日报目录。
|
|
738
|
+
* @returns {Promise<{open: string[], text: string}>} 未完成条目与看板全文。
|
|
739
|
+
*/
|
|
740
|
+
async function readBoard(reportDir) {
|
|
741
|
+
try {
|
|
742
|
+
const text = await readFile(join(reportDir, '看板.md'), 'utf8')
|
|
743
|
+
const open = text.split(/\r?\n/).map(line => line.trim()).filter(line => /^- \[ \]/.test(line))
|
|
744
|
+
return { open, text }
|
|
745
|
+
} catch {
|
|
746
|
+
return { open: [], text: '' }
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* 校验并归一化看板更新参数:优先级、截止日、状态三者至少给一个。
|
|
752
|
+
* @param {{ priority?: unknown, due?: unknown, status?: unknown }} input - 原始参数。
|
|
753
|
+
* @returns {{ priority?: string, due?: string, status?: string }} 可传给脚本的参数。
|
|
754
|
+
*/
|
|
755
|
+
function boardPatch(input) {
|
|
756
|
+
const patch = {}
|
|
757
|
+
if (input.priority !== undefined) {
|
|
758
|
+
const value = String(input.priority).trim().toUpperCase()
|
|
759
|
+
if (!['P1', 'P2', 'P3', 'NONE'].includes(value)) throw new Error('priority 只能是 P1 / P2 / P3 / none')
|
|
760
|
+
patch.priority = value === 'NONE' ? 'none' : value
|
|
761
|
+
}
|
|
762
|
+
if (input.due !== undefined) {
|
|
763
|
+
const value = String(input.due).trim()
|
|
764
|
+
if (value.toLowerCase() !== 'none') parseDay(value)
|
|
765
|
+
patch.due = value.toLowerCase() === 'none' ? 'none' : value
|
|
766
|
+
}
|
|
767
|
+
if (input.status !== undefined) {
|
|
768
|
+
const value = String(input.status).trim().toLowerCase()
|
|
769
|
+
if (!['todo', 'doing', 'done', 'drop'].includes(value)) {
|
|
770
|
+
throw new Error('status 只能是 todo / doing / done / drop')
|
|
771
|
+
}
|
|
772
|
+
patch.status = value
|
|
773
|
+
}
|
|
774
|
+
if (Object.keys(patch).length === 0) throw new Error('update 至少要给 priority / due / status 之一')
|
|
775
|
+
return patch
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/**
|
|
779
|
+
* 调 push-to-board.ps1 改一条看板条目的优先级、截止日或状态。
|
|
780
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
781
|
+
* @param {string} keyword - 标题关键词或 #h 指纹。
|
|
782
|
+
* @param {{ priority?: string, due?: string, status?: string }} patch - 更新参数。
|
|
783
|
+
* @param {AbortSignal | undefined} signal - 取消信号。
|
|
784
|
+
* @returns {Promise<{ stdout: string, board: { open: string[], text: string } }>} 脚本输出与更新后的看板。
|
|
785
|
+
*/
|
|
786
|
+
async function updateBoard(config, keyword, patch, signal) {
|
|
787
|
+
const args = ['-Update', keyword, '-BoardPath', boardPathOf(config)]
|
|
788
|
+
if (patch.priority !== undefined) args.push('-Priority', patch.priority)
|
|
789
|
+
if (patch.due !== undefined) args.push('-Due', patch.due)
|
|
790
|
+
if (patch.status !== undefined) args.push('-Status', patch.status)
|
|
791
|
+
const result = await runScript(config, 'push-to-board.ps1', args, signal)
|
|
792
|
+
if (result.code !== 0) {
|
|
793
|
+
throw new Error(`更新看板失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
|
|
794
|
+
}
|
|
795
|
+
return { stdout: result.stdout.trim(), board: await readBoard(config.reportDir) }
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* 读取 POST body;空 body 当 {},非法 JSON 由调用方转成 400。
|
|
800
|
+
* @param {import('node:http').IncomingMessage} req - 请求。
|
|
801
|
+
* @returns {Promise<Record<string, unknown>>} 解析后的 body。
|
|
802
|
+
*/
|
|
803
|
+
async function readJsonBody(req) {
|
|
804
|
+
const chunks = []
|
|
805
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
806
|
+
const raw = Buffer.concat(chunks).toString('utf8')
|
|
807
|
+
if (raw.trim() === '') return {}
|
|
808
|
+
try {
|
|
809
|
+
return JSON.parse(raw)
|
|
810
|
+
} catch {
|
|
811
|
+
throw new Error('请求体不是合法 JSON')
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* 取输出末尾若干行用于报错。
|
|
817
|
+
* @param {string} text - 进程输出。
|
|
818
|
+
* @returns {string} 截断后的输出。
|
|
819
|
+
*/
|
|
820
|
+
function tail(text) {
|
|
821
|
+
const trimmed = String(text ?? '').trim()
|
|
822
|
+
return trimmed.length > 1200 ? `…${trimmed.slice(-1200)}` : trimmed
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* 允许以裸参数形式传给脚本的开关;其余参数一律当作字符串字面量。
|
|
827
|
+
* 注意:PowerShell 里给参数名加引号它就变成普通位置参数了(实测
|
|
828
|
+
* `& script '-Date' x` 会把 "-Date" 绑到第一个位置参数),所以新增开关必须补进这里。
|
|
829
|
+
*/
|
|
830
|
+
const PS_SWITCHES = new Set([
|
|
831
|
+
'-Date', '-From', '-To', '-Section', '-NoSessions', '-Report', '-BoardPath', '-Show', '-Done', '-Drop', '-DryRun',
|
|
832
|
+
'-Update', '-Priority', '-Due', '-Status',
|
|
833
|
+
'-Workspace', '-ReportDir', '-DshHome',
|
|
834
|
+
])
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* 运行一次 PowerShell 脚本。
|
|
838
|
+
* @param {string} command - pwsh 可执行文件。
|
|
839
|
+
* @param {string[]} args - 参数。
|
|
840
|
+
* @param {AbortSignal | undefined} signal - 调用方取消信号。
|
|
841
|
+
* @param {number} timeoutMs - 超时。
|
|
842
|
+
* @returns {Promise<{code: number, stdout: string, stderr: string}>} 退出码与输出。
|
|
843
|
+
*/
|
|
844
|
+
function runProcess(command, args, signal, timeoutMs) {
|
|
845
|
+
return new Promise((resolve) => {
|
|
846
|
+
const child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
847
|
+
let stdout = ''
|
|
848
|
+
let stderr = ''
|
|
849
|
+
let settled = false
|
|
850
|
+
const timer = setTimeout(() => {
|
|
851
|
+
if (!settled) child.kill()
|
|
852
|
+
}, timeoutMs)
|
|
853
|
+
const finish = (code, note) => {
|
|
854
|
+
if (settled) return
|
|
855
|
+
settled = true
|
|
856
|
+
clearTimeout(timer)
|
|
857
|
+
signal?.removeEventListener?.('abort', onAbort)
|
|
858
|
+
resolve({ code, stdout, stderr: note ? `${stderr}\n${note}` : stderr })
|
|
859
|
+
}
|
|
860
|
+
const onAbort = () => child.kill()
|
|
861
|
+
signal?.addEventListener?.('abort', onAbort, { once: true })
|
|
862
|
+
child.stdout?.setEncoding('utf8')
|
|
863
|
+
child.stderr?.setEncoding('utf8')
|
|
864
|
+
child.stdout?.on('data', (chunk) => { stdout += chunk })
|
|
865
|
+
child.stderr?.on('data', (chunk) => { stderr += chunk })
|
|
866
|
+
child.on('error', error => finish(-1, `无法启动 ${command}:${error.message}`))
|
|
867
|
+
child.on('close', code => finish(code ?? -1, code === null ? '进程被超时或取消终止' : ''))
|
|
868
|
+
})
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* 运行日报目录里的某个脚本。
|
|
873
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
874
|
+
* @param {string} script - 脚本文件名。
|
|
875
|
+
* @param {string[]} args - 脚本参数。
|
|
876
|
+
* @param {AbortSignal | undefined} signal - 取消信号。
|
|
877
|
+
* @returns {Promise<{code: number, stdout: string, stderr: string}>} 结果。
|
|
878
|
+
*/
|
|
879
|
+
function runScript(config, script, args, signal) {
|
|
880
|
+
// 用 -Command 而不是 -File:只有进到 PowerShell 里才能先把控制台输出编码
|
|
881
|
+
// 设成 UTF-8(-File 模式没有插话的位置)。管道重定向下 pwsh 默认按系统
|
|
882
|
+
// ANSI(936)写 stdout,Node 按 utf8 解码就会得到乱码,中文解析全失效。
|
|
883
|
+
const command = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; '
|
|
884
|
+
+ '$OutputEncoding = [System.Text.Encoding]::UTF8; '
|
|
885
|
+
+ `& ${[psQuote(join(config.scriptDir, script)), ...args.map(psArg)].join(' ')}`
|
|
886
|
+
const started = Date.now()
|
|
887
|
+
return runProcess(
|
|
888
|
+
config.pwsh,
|
|
889
|
+
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command],
|
|
890
|
+
signal,
|
|
891
|
+
config.timeoutMs,
|
|
892
|
+
).then((result) => {
|
|
893
|
+
const head = `${script} ${args.join(' ')} → exit ${result.code},${Date.now() - started}ms`
|
|
894
|
+
if (result.code === 0) {
|
|
895
|
+
void logLine(config, 'info', head)
|
|
896
|
+
} else {
|
|
897
|
+
void logLine(config, 'error', `${head}\n${tail(result.stderr || result.stdout, 800)}`)
|
|
898
|
+
}
|
|
899
|
+
return result
|
|
900
|
+
})
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* 把单个命令行参数转成 PowerShell 里的写法。
|
|
905
|
+
* 已知开关保持裸写(`-Date`),其余一律按单引号字面量引用,值里的 `'` 翻倍。
|
|
906
|
+
* @param {string} arg - 原始参数。
|
|
907
|
+
* @returns {string} PowerShell 写法。
|
|
908
|
+
*/
|
|
909
|
+
function psArg(arg) {
|
|
910
|
+
return PS_SWITCHES.has(arg) ? arg : psQuote(arg)
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* 引用一个 PowerShell 单引号字符串字面量。
|
|
915
|
+
* @param {string} value - 原始字符串。
|
|
916
|
+
* @returns {string} 带引号的字面量。
|
|
917
|
+
*/
|
|
918
|
+
function psQuote(value) {
|
|
919
|
+
return `'${String(value).replace(/'/g, "''")}'`
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/** 文本输出的通用渲染。 */
|
|
923
|
+
const renderText = (_args, value) => [{ type: 'text', text: value.text }]
|
|
924
|
+
|
|
925
|
+
/** 侧边栏页面要的一份只读快照:看板全文 + 最近若干天日报正文。 */
|
|
926
|
+
async function readState(config) {
|
|
927
|
+
const board = await readBoard(config.reportDir)
|
|
928
|
+
const lines = board.text.split(/\r?\n/).map(line => line.trim())
|
|
929
|
+
let names = []
|
|
930
|
+
try {
|
|
931
|
+
names = (await readdir(config.reportDir)).filter(name => /^日报-\d{4}-\d{2}-\d{2}\.md$/.test(name))
|
|
932
|
+
} catch {
|
|
933
|
+
names = []
|
|
934
|
+
}
|
|
935
|
+
const reports = []
|
|
936
|
+
for (const name of names.sort().reverse().slice(0, 91)) {
|
|
937
|
+
try {
|
|
938
|
+
const content = await readFile(join(config.reportDir, name), 'utf8')
|
|
939
|
+
const stats = heatStats(content)
|
|
940
|
+
reports.push({
|
|
941
|
+
date: name.slice(3, 13),
|
|
942
|
+
file: name,
|
|
943
|
+
size: Buffer.byteLength(content, 'utf8'),
|
|
944
|
+
lines: stats.lines,
|
|
945
|
+
outputs: stats.outputs,
|
|
946
|
+
score: stats.score,
|
|
947
|
+
content,
|
|
948
|
+
})
|
|
949
|
+
} catch {
|
|
950
|
+
// 单篇读不了就跳过,不让整个页面失败
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
const periods = []
|
|
954
|
+
let periodNames = []
|
|
955
|
+
try {
|
|
956
|
+
periodNames = (await readdir(config.reportDir)).filter(name => /^(?:周报|月报|周期)-.+\.md$/.test(name))
|
|
957
|
+
} catch {
|
|
958
|
+
periodNames = []
|
|
959
|
+
}
|
|
960
|
+
for (const name of periodNames.sort().reverse().slice(0, 40)) {
|
|
961
|
+
try {
|
|
962
|
+
const content = await readFile(join(config.reportDir, name), 'utf8')
|
|
963
|
+
const kind = name.startsWith('周报') ? 'week' : name.startsWith('月报') ? 'month' : 'custom'
|
|
964
|
+
const period = name.replace(/^(?:周报|月报|周期)-/, '').replace(/\.md$/, '').replace('_', ' ~ ')
|
|
965
|
+
periods.push({
|
|
966
|
+
file: name,
|
|
967
|
+
kind,
|
|
968
|
+
period,
|
|
969
|
+
size: Buffer.byteLength(content, 'utf8'),
|
|
970
|
+
content,
|
|
971
|
+
})
|
|
972
|
+
} catch {
|
|
973
|
+
// 同上:单篇失败不拖垮页面
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
return {
|
|
977
|
+
reportDir: config.reportDir,
|
|
978
|
+
today: dateInZone(config.scheduleTimeZone),
|
|
979
|
+
updatedAt: new Date().toISOString(),
|
|
980
|
+
board: {
|
|
981
|
+
text: board.text,
|
|
982
|
+
open: board.open.length,
|
|
983
|
+
done: lines.filter(line => /^- \[x\]/i.test(line)).length,
|
|
984
|
+
},
|
|
985
|
+
reports,
|
|
986
|
+
periods,
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** 找出插件托管的那条日报任务:标题前缀或提示词特征都算。周期任务的提示词不含日报特征。 */
|
|
991
|
+
function findOwnTask(items, config) {
|
|
992
|
+
return items.find((task) => {
|
|
993
|
+
const title = String(task.title ?? '')
|
|
994
|
+
const prompt = String(task.prompt ?? '')
|
|
995
|
+
const looksDaily = /daily_report_collect|dsh-work-summary/.test(prompt) && !/work_summary_period/.test(prompt)
|
|
996
|
+
return title === config.scheduleTitle
|
|
997
|
+
|| title.startsWith(config.scheduleTitle)
|
|
998
|
+
|| looksDaily
|
|
999
|
+
}) ?? null
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** 按标题找插件自己的任务;标题是稳定契约,不靠提示词猜。 */
|
|
1003
|
+
function findTaskByTitle(items, title) {
|
|
1004
|
+
return items.find((task) => {
|
|
1005
|
+
const current = String(task.title ?? '')
|
|
1006
|
+
return current === title || current.startsWith(title)
|
|
1007
|
+
}) ?? null
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** 从任务的 rrule 里读出小时、分钟与时区。 */
|
|
1011
|
+
function parseRruleTime(task) {
|
|
1012
|
+
const rrule = String(task?.rrule ?? '')
|
|
1013
|
+
const start = /DTSTART(?:;TZID=([^:]+))?:(\d{8})T(\d{2})(\d{2})/.exec(rrule)
|
|
1014
|
+
const byHour = /BYHOUR=(\d{1,2})/.exec(rrule)
|
|
1015
|
+
const byMinute = /BYMINUTE=(\d{1,2})/.exec(rrule)
|
|
1016
|
+
const hour = byHour ? Number(byHour[1]) : start ? Number(start[3]) : null
|
|
1017
|
+
const minute = byMinute ? Number(byMinute[1]) : start ? Number(start[4]) : null
|
|
1018
|
+
return { hour, minute, timeZone: start?.[1] ?? null }
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/** 每天固定时刻的 rrule(与既有任务同一种写法)。 */
|
|
1022
|
+
function dailyRrule(timeZone, time) {
|
|
1023
|
+
const [hour, minute] = String(time).split(':').map(Number)
|
|
1024
|
+
const today = dateInZone(timeZone).replace(/-/g, '')
|
|
1025
|
+
const hh = String(hour).padStart(2, '0')
|
|
1026
|
+
const mm = String(minute).padStart(2, '0')
|
|
1027
|
+
return `DTSTART;TZID=${timeZone}:${today}T${hh}${mm}00\nRRULE:FREQ=DAILY;INTERVAL=1;BYHOUR=${hour};BYMINUTE=${minute}`
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/** 从某天起最近的一个指定星期几(0=周日,1=周一)。 */
|
|
1031
|
+
function nextWeekday(date, weekday) {
|
|
1032
|
+
const current = new Date(parseDay(date)).getUTCDay()
|
|
1033
|
+
return shiftDay(date, (weekday - current + 7) % 7)
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/** 每周一固定时刻的 rrule:周报任务用。 */
|
|
1037
|
+
function weeklyRrule(timeZone, time) {
|
|
1038
|
+
const [hour, minute] = String(time).split(':').map(Number)
|
|
1039
|
+
const start = nextWeekday(dateInZone(timeZone), 1).replace(/-/g, '')
|
|
1040
|
+
const hh = String(hour).padStart(2, '0')
|
|
1041
|
+
const mm = String(minute).padStart(2, '0')
|
|
1042
|
+
return `DTSTART;TZID=${timeZone}:${start}T${hh}${mm}00\nRRULE:FREQ=WEEKLY;INTERVAL=1;BYDAY=MO;BYHOUR=${hour};BYMINUTE=${minute}`
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/** 每月 1 号固定时刻的 rrule:月报任务用。 */
|
|
1046
|
+
function monthlyRrule(timeZone, time) {
|
|
1047
|
+
const [hour, minute] = String(time).split(':').map(Number)
|
|
1048
|
+
const today = dateInZone(timeZone)
|
|
1049
|
+
const [year, month, day] = today.split('-').map(Number)
|
|
1050
|
+
const start = day === 1
|
|
1051
|
+
? today
|
|
1052
|
+
: `${month === 12 ? year + 1 : year}-${String(month === 12 ? 1 : month + 1).padStart(2, '0')}-01`
|
|
1053
|
+
const hh = String(hour).padStart(2, '0')
|
|
1054
|
+
const mm = String(minute).padStart(2, '0')
|
|
1055
|
+
return `DTSTART;TZID=${timeZone}:${start.replace(/-/g, '')}T${hh}${mm}00\nRRULE:FREQ=MONTHLY;INTERVAL=1;BYMONTHDAY=1;BYHOUR=${hour};BYMINUTE=${minute}`
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/** 通用任务状态:没找到时用配置里的默认时间撑住设置页。 */
|
|
1059
|
+
async function taskState(scheduleCtx, title, fallbackTime, timeZone) {
|
|
1060
|
+
const page = await scheduleCtx.schedule.list({ limit: 200 })
|
|
1061
|
+
const task = findTaskByTitle(page.items ?? [], title)
|
|
1062
|
+
if (!task) return { found: false, title, timeZone, time: fallbackTime }
|
|
1063
|
+
const parsed = parseRruleTime(task)
|
|
1064
|
+
const hour = parsed.hour ?? Number(fallbackTime.split(':')[0])
|
|
1065
|
+
const minute = parsed.minute ?? Number(fallbackTime.split(':')[1] ?? 0)
|
|
1066
|
+
return {
|
|
1067
|
+
found: true,
|
|
1068
|
+
id: task.id,
|
|
1069
|
+
title: task.title,
|
|
1070
|
+
active: task.status === 'active',
|
|
1071
|
+
time: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
|
|
1072
|
+
timeZone: parsed.timeZone ?? timeZone,
|
|
1073
|
+
nextRunAt: task.scheduledAtLocal ?? task.scheduledAt ?? null,
|
|
1074
|
+
target: task.target?.kind ?? null,
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/** 设置页要的日报任务状态。 */
|
|
1079
|
+
async function scheduleState(scheduleCtx, config) {
|
|
1080
|
+
const state = await taskState(scheduleCtx, config.scheduleTitle, config.scheduleTime, config.scheduleTimeZone)
|
|
1081
|
+
if (!state.found) {
|
|
1082
|
+
return { found: false, scheduleTitle: config.scheduleTitle, timeZone: config.scheduleTimeZone, time: config.scheduleTime }
|
|
1083
|
+
}
|
|
1084
|
+
return state
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/** 设置页要的周报/月报任务状态。 */
|
|
1088
|
+
async function periodScheduleState(scheduleCtx, config, kind) {
|
|
1089
|
+
const week = kind === 'week'
|
|
1090
|
+
return taskState(
|
|
1091
|
+
scheduleCtx,
|
|
1092
|
+
week ? config.weekScheduleTitle : config.monthScheduleTitle,
|
|
1093
|
+
week ? config.weekScheduleTime : config.monthScheduleTime,
|
|
1094
|
+
config.scheduleTimeZone,
|
|
1095
|
+
)
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* 注册三个工具,并按配置托管计划任务。
|
|
1100
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
|
|
1101
|
+
* @param {Record<string, unknown>} rawConfig - patch 配置。
|
|
1102
|
+
* @returns {void}
|
|
1103
|
+
*/
|
|
1104
|
+
export function apply(ctx, rawConfig) {
|
|
1105
|
+
const config = resolveConfig(rawConfig)
|
|
1106
|
+
|
|
1107
|
+
// 装好第一次激活就把目录建出来;之后所有产物都落在它们下面。建不出来也不该拖垮插件。
|
|
1108
|
+
void mkdir(DATA_HOME, { recursive: true }).catch(() => {})
|
|
1109
|
+
void mkdir(config.reportDir, { recursive: true }).catch(() => {})
|
|
1110
|
+
void mkdir(config.workspace, { recursive: true }).catch(() => {})
|
|
1111
|
+
|
|
1112
|
+
ctx.tools.register({
|
|
1113
|
+
name: 'daily_report_collect',
|
|
1114
|
+
description:
|
|
1115
|
+
'采集某一天的工作痕迹,生成日报的源数据文件并返回它的路径、小节清单和日报模板。'
|
|
1116
|
+
+ '写日报前先调用它:结果里的 sourcePath 要读一遍,template 是必须填满的六节骨架。'
|
|
1117
|
+
+ '采集写 _源数据;超过 60 个时自动把旧文件按季度归档到 _归档。',
|
|
1118
|
+
parameters: {
|
|
1119
|
+
type: 'object',
|
|
1120
|
+
additionalProperties: false,
|
|
1121
|
+
properties: {
|
|
1122
|
+
date: { type: 'string', description: '本地日期 YYYY-MM-DD,默认今天。补写往日日报时传。' },
|
|
1123
|
+
sessions: { type: 'boolean', description: '是否解析 DSH 会话,默认 true;工作区文件很多时可设 false 提速。' },
|
|
1124
|
+
},
|
|
1125
|
+
},
|
|
1126
|
+
output: {
|
|
1127
|
+
schema: {
|
|
1128
|
+
type: 'object',
|
|
1129
|
+
additionalProperties: false,
|
|
1130
|
+
required: ['date', 'sourcePath', 'lines', 'boardOpen', 'template'],
|
|
1131
|
+
properties: {
|
|
1132
|
+
date: { type: 'string' },
|
|
1133
|
+
sourcePath: { type: 'string' },
|
|
1134
|
+
lines: { type: 'integer' },
|
|
1135
|
+
bytes: { type: 'integer' },
|
|
1136
|
+
headings: { type: 'array', items: { type: 'string' } },
|
|
1137
|
+
boardOpen: { type: 'integer' },
|
|
1138
|
+
template: { type: 'string' },
|
|
1139
|
+
},
|
|
1140
|
+
},
|
|
1141
|
+
render: (_args, value) => [{
|
|
1142
|
+
type: 'text',
|
|
1143
|
+
text: `已采集 ${value.date} → ${value.sourcePath}(${value.lines} 行,看板未完成 ${value.boardOpen} 条)。`
|
|
1144
|
+
+ (value.headings?.length
|
|
1145
|
+
? `\n\n采集到的小节:\n${value.headings.map(h => `- ${h.replace(/^##\s*/, '')}`).join('\n')}`
|
|
1146
|
+
: '')
|
|
1147
|
+
+ `\n\n日报模板(把每节内容替换掉提示语):\n\n\`\`\`markdown\n${value.template}\n\`\`\``,
|
|
1148
|
+
}],
|
|
1149
|
+
},
|
|
1150
|
+
async execute(args, exec) {
|
|
1151
|
+
const date = args.date ?? dateInZone(config.scheduleTimeZone)
|
|
1152
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error(`日期格式应为 YYYY-MM-DD,收到:${date}`)
|
|
1153
|
+
const result = await runScript(
|
|
1154
|
+
config,
|
|
1155
|
+
'collect-day.ps1',
|
|
1156
|
+
[
|
|
1157
|
+
'-Date', date,
|
|
1158
|
+
'-Workspace', config.workspace,
|
|
1159
|
+
'-ReportDir', config.reportDir,
|
|
1160
|
+
...(args.sessions === false ? ['-NoSessions'] : []),
|
|
1161
|
+
],
|
|
1162
|
+
exec.signal,
|
|
1163
|
+
)
|
|
1164
|
+
if (result.code !== 0) {
|
|
1165
|
+
throw new Error(`采集失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
|
|
1166
|
+
}
|
|
1167
|
+
let text
|
|
1168
|
+
try {
|
|
1169
|
+
text = await readFile(join(config.reportDir, '_源数据', `${date}.md`), 'utf8')
|
|
1170
|
+
} catch (error) {
|
|
1171
|
+
throw new Error(`采集脚本未产出 ${date} 的源数据:${tail(result.stdout) || String(error)}`)
|
|
1172
|
+
}
|
|
1173
|
+
const lines = text.split(/\r?\n/)
|
|
1174
|
+
// 归档结果只出现在源数据里;这里顺手抄一行到运行日志,失败也不影响采集。
|
|
1175
|
+
for (const note of lines.filter(line => /^>\s*归档/.test(line))) {
|
|
1176
|
+
await logLine(config, note.includes('失败') ? 'warn' : 'info', note.replace(/^>\s*/, ''))
|
|
1177
|
+
}
|
|
1178
|
+
const headings = lines.filter(line => /^##\s/.test(line)).map(line => line.trim())
|
|
1179
|
+
const board = await readBoard(config.reportDir)
|
|
1180
|
+
return {
|
|
1181
|
+
date,
|
|
1182
|
+
sourcePath: join(config.reportDir, '_源数据', `${date}.md`),
|
|
1183
|
+
lines: lines.length,
|
|
1184
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
1185
|
+
headings,
|
|
1186
|
+
boardOpen: board.open.length,
|
|
1187
|
+
template: buildTemplate(date),
|
|
1188
|
+
}
|
|
1189
|
+
},
|
|
1190
|
+
})
|
|
1191
|
+
|
|
1192
|
+
ctx.tools.register({
|
|
1193
|
+
name: 'daily_report_save',
|
|
1194
|
+
description:
|
|
1195
|
+
'校验并落盘当天日报,然后把它「六、明日开场清单」推进看板。'
|
|
1196
|
+
+ '正文必须包含六个固定小节(一、今日概览 … 六、明日开场清单);缺节或留占位符会直接报错且不写文件,'
|
|
1197
|
+
+ '按报错修好后重调即可。已存在同名日报会被整篇覆盖。'
|
|
1198
|
+
+ '落盘后会做证据密度、空话词、建议可执行性的软校验,提醒放在 warnings 与 text 里,不阻断写入。',
|
|
1199
|
+
parameters: {
|
|
1200
|
+
type: 'object',
|
|
1201
|
+
additionalProperties: false,
|
|
1202
|
+
required: ['content'],
|
|
1203
|
+
properties: {
|
|
1204
|
+
content: { type: 'string', description: '完整日报 Markdown 正文,从 `# 工作日报 · 日期` 开始。' },
|
|
1205
|
+
date: { type: 'string', description: '本地日期 YYYY-MM-DD,默认今天。' },
|
|
1206
|
+
push: { type: 'boolean', description: '是否推送看板,默认 true。' },
|
|
1207
|
+
},
|
|
1208
|
+
},
|
|
1209
|
+
output: {
|
|
1210
|
+
schema: {
|
|
1211
|
+
type: 'object',
|
|
1212
|
+
additionalProperties: false,
|
|
1213
|
+
required: ['date', 'reportPath', 'pushed', 'skipped', 'boardOpen'],
|
|
1214
|
+
properties: {
|
|
1215
|
+
date: { type: 'string' },
|
|
1216
|
+
reportPath: { type: 'string' },
|
|
1217
|
+
pushed: { type: 'integer' },
|
|
1218
|
+
skipped: { type: 'integer' },
|
|
1219
|
+
boardOpen: { type: 'integer' },
|
|
1220
|
+
warnings: {
|
|
1221
|
+
type: 'array',
|
|
1222
|
+
items: { type: 'string' },
|
|
1223
|
+
description: '软校验提醒(证据密度 / 空话词 / 建议可执行性);为空表示没发现问题。',
|
|
1224
|
+
},
|
|
1225
|
+
text: { type: 'string' },
|
|
1226
|
+
},
|
|
1227
|
+
},
|
|
1228
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
1229
|
+
},
|
|
1230
|
+
async execute(args, exec) {
|
|
1231
|
+
const date = args.date ?? dateInZone(config.scheduleTimeZone)
|
|
1232
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error(`日期格式应为 YYYY-MM-DD,收到:${date}`)
|
|
1233
|
+
const content = String(args.content ?? '')
|
|
1234
|
+
const problems = []
|
|
1235
|
+
const missing = missingSections(content)
|
|
1236
|
+
if (missing.length > 0) problems.push(`缺少小节:${missing.join('、')}`)
|
|
1237
|
+
const body = content.replace(/^#[^\n]*\n/m, '')
|
|
1238
|
+
if (body.trim().length < 200) problems.push(`正文过短(${body.trim().length} 字符),确认不是只写了骨架`)
|
|
1239
|
+
if (/\bTODO\b|待填|\{\{/.test(content)) problems.push('仍留有占位符(TODO / 待填 / {{…}})')
|
|
1240
|
+
if (problems.length > 0) {
|
|
1241
|
+
throw new Error(`日报未写入,先修正:\n- ${problems.join('\n- ')}`)
|
|
1242
|
+
}
|
|
1243
|
+
// 质量检查放在硬校验之后、写盘之前:只收集提醒,不改变落盘结果。
|
|
1244
|
+
const warnings = qualityWarnings(content, minEvidenceOf(config))
|
|
1245
|
+
|
|
1246
|
+
const stamp = stampInZone(config.scheduleTimeZone)
|
|
1247
|
+
const withFooter = /数据来源:/.test(content)
|
|
1248
|
+
? content
|
|
1249
|
+
: `${content.replace(/\s*$/, '')}\n\n---\n数据来源:\`_源数据\\${date}.md\` | 生成时间:${stamp}\n`
|
|
1250
|
+
const reportPath = join(config.reportDir, `日报-${date}.md`)
|
|
1251
|
+
await mkdir(config.reportDir, { recursive: true })
|
|
1252
|
+
await writeFile(reportPath, withFooter, 'utf8')
|
|
1253
|
+
|
|
1254
|
+
const shouldPush = args.push ?? config.pushOnSave
|
|
1255
|
+
let pushed = 0
|
|
1256
|
+
let skipped = 0
|
|
1257
|
+
let pushText = ''
|
|
1258
|
+
if (shouldPush) {
|
|
1259
|
+
const result = await runScript(config, 'push-to-board.ps1', ['-Report', reportPath, '-BoardPath', boardPathOf(config)], exec.signal)
|
|
1260
|
+
if (result.code !== 0) {
|
|
1261
|
+
throw new Error(`日报已写入 ${reportPath},但推送看板失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
|
|
1262
|
+
}
|
|
1263
|
+
pushText = result.stdout.trim()
|
|
1264
|
+
const match = /已写入\s*(\d+)\s*条[,,]\s*跳过重复\s*(\d+)\s*条/.exec(pushText)
|
|
1265
|
+
if (match) {
|
|
1266
|
+
pushed = Number(match[1])
|
|
1267
|
+
skipped = Number(match[2])
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const board = await readBoard(config.reportDir)
|
|
1271
|
+
const summary = shouldPush
|
|
1272
|
+
? `日报已写入 ${reportPath};看板 ${pushed ? `新增 ${pushed} 条` : '无新增条目'}${skipped ? `,跳过重复 ${skipped} 条` : ''},当前未完成 ${board.open.length} 条。`
|
|
1273
|
+
: `日报已写入 ${reportPath};按要求未推送看板。`
|
|
1274
|
+
const warningText = warnings.length > 0
|
|
1275
|
+
? `质量提醒(不影响落盘):\n- ${warnings.join('\n- ')}`
|
|
1276
|
+
: ''
|
|
1277
|
+
return {
|
|
1278
|
+
date,
|
|
1279
|
+
reportPath,
|
|
1280
|
+
pushed,
|
|
1281
|
+
skipped,
|
|
1282
|
+
boardOpen: board.open.length,
|
|
1283
|
+
warnings,
|
|
1284
|
+
text: [summary, pushText, warningText].filter(Boolean).join('\n'),
|
|
1285
|
+
}
|
|
1286
|
+
},
|
|
1287
|
+
})
|
|
1288
|
+
|
|
1289
|
+
ctx.tools.register({
|
|
1290
|
+
name: 'work_summary_period',
|
|
1291
|
+
description:
|
|
1292
|
+
'聚合一个日期区间的周报/月报:先跑 collect-range.ps1 生成区间源数据,再写四节正文并推看板。'
|
|
1293
|
+
+ '四节固定为「主线 / 关键产出 / 未清与复发 / 开场」,缺节、正文过短或留占位符会报错且不写文件。'
|
|
1294
|
+
+ '不传 content 时按区间日报与看板自动拼一份可读草稿;传了 content 就按给定正文校验落盘。'
|
|
1295
|
+
+ 'kind 不传时自动推断:整月=month、跨度 7 天=week、其余=custom。'
|
|
1296
|
+
+ 'offset 用于定时任务生成上一完整周期:周报 offset=1 是上周一至周日,月报 offset=1 是上一个自然月。',
|
|
1297
|
+
parameters: {
|
|
1298
|
+
type: 'object',
|
|
1299
|
+
additionalProperties: false,
|
|
1300
|
+
properties: {
|
|
1301
|
+
from: { type: 'string', description: '起始日 YYYY-MM-DD;与 to 成对出现。都不传时 week=本周一至今天、month=本月 1 号至今天。' },
|
|
1302
|
+
to: { type: 'string', description: '结束日 YYYY-MM-DD(含当天)。' },
|
|
1303
|
+
kind: { type: 'string', enum: ['week', 'month', 'custom'], description: '报告类型;不传则按区间推断。' },
|
|
1304
|
+
offset: { type: 'integer', minimum: 0, maximum: 60, description: '往前数几个完整周期,默认 0;与 from/to 互斥。周报=整周,月报=整月。' },
|
|
1305
|
+
content: { type: 'string', description: '四节正文;不传则用区间日报自动聚合成草稿。' },
|
|
1306
|
+
push: { type: 'boolean', description: '是否把「开场」小节推进看板,默认 true。' },
|
|
1307
|
+
},
|
|
1308
|
+
},
|
|
1309
|
+
output: {
|
|
1310
|
+
schema: {
|
|
1311
|
+
type: 'object',
|
|
1312
|
+
additionalProperties: false,
|
|
1313
|
+
required: ['periodPath', 'reportPath', 'pushed', 'skipped', 'boardOpen', 'text'],
|
|
1314
|
+
properties: {
|
|
1315
|
+
periodPath: { type: 'string' },
|
|
1316
|
+
reportPath: { type: 'string' },
|
|
1317
|
+
pushed: { type: 'integer' },
|
|
1318
|
+
skipped: { type: 'integer' },
|
|
1319
|
+
boardOpen: { type: 'integer' },
|
|
1320
|
+
text: { type: 'string' },
|
|
1321
|
+
},
|
|
1322
|
+
},
|
|
1323
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
1324
|
+
},
|
|
1325
|
+
async execute(args, exec) {
|
|
1326
|
+
const range = resolvePeriod(args, config.scheduleTimeZone)
|
|
1327
|
+
const periodPath = join(config.reportDir, '_源数据', `周期-${range.from}_${range.to}.md`)
|
|
1328
|
+
const collected = await runScript(
|
|
1329
|
+
config,
|
|
1330
|
+
'collect-range.ps1',
|
|
1331
|
+
['-From', range.from, '-To', range.to, '-Workspace', config.workspace, '-ReportDir', config.reportDir],
|
|
1332
|
+
exec.signal,
|
|
1333
|
+
)
|
|
1334
|
+
if (collected.code !== 0) {
|
|
1335
|
+
throw new Error(`区间采集失败(退出码 ${collected.code}):\n${tail(collected.stderr || collected.stdout)}`)
|
|
1336
|
+
}
|
|
1337
|
+
if (!existsSync(periodPath)) {
|
|
1338
|
+
throw new Error(`区间采集脚本未产出 ${periodPath}:\n${tail(collected.stdout)}`)
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
const days = []
|
|
1342
|
+
for (let day = range.from; day <= range.to; day = shiftDay(day, 1)) days.push(day)
|
|
1343
|
+
const daily = new Map()
|
|
1344
|
+
for (const day of days) {
|
|
1345
|
+
try {
|
|
1346
|
+
daily.set(day, await readFile(join(config.reportDir, `日报-${day}.md`), 'utf8'))
|
|
1347
|
+
} catch {
|
|
1348
|
+
// 缺日报就跳过;缺了几天不影响整体聚合
|
|
1349
|
+
}
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
const board = await readBoard(config.reportDir)
|
|
1353
|
+
const provided = typeof args.content === 'string' && args.content.trim() !== ''
|
|
1354
|
+
let content = provided
|
|
1355
|
+
? String(args.content)
|
|
1356
|
+
: composePeriodDraft(range, days, daily, board, dateInZone(config.scheduleTimeZone))
|
|
1357
|
+
|
|
1358
|
+
const problems = []
|
|
1359
|
+
const missing = missingPeriodSections(content, range.kind)
|
|
1360
|
+
if (missing.length > 0) problems.push(`缺少小节:${missing.join('、')}`)
|
|
1361
|
+
const body = content.replace(/^#[^\n]*\n/m, '')
|
|
1362
|
+
if (body.trim().length < 200) problems.push(`正文过短(${body.trim().length} 字符),确认不是只写了骨架`)
|
|
1363
|
+
if (/\bTODO\b|待填|\{\{/.test(content)) problems.push('仍留有占位符(TODO / 待填 / {{…}})')
|
|
1364
|
+
if (problems.length > 0) {
|
|
1365
|
+
throw new Error(`周期报告未写入,先修正:\n- ${problems.join('\n- ')}`)
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
const stamp = stampInZone(config.scheduleTimeZone)
|
|
1369
|
+
const reportName = periodReportName(range)
|
|
1370
|
+
const reportPath = join(config.reportDir, reportName)
|
|
1371
|
+
await mkdir(config.reportDir, { recursive: true })
|
|
1372
|
+
await writeFile(reportPath, withPeriodFooter(content, range, stamp), 'utf8')
|
|
1373
|
+
|
|
1374
|
+
const shouldPush = args.push ?? config.pushOnSave
|
|
1375
|
+
let pushed = 0
|
|
1376
|
+
let skipped = 0
|
|
1377
|
+
let pushText = ''
|
|
1378
|
+
if (shouldPush) {
|
|
1379
|
+
const section = periodSectionLabels(range.kind)[3]
|
|
1380
|
+
const result = await runScript(
|
|
1381
|
+
config,
|
|
1382
|
+
'push-to-board.ps1',
|
|
1383
|
+
['-Report', reportPath, '-BoardPath', boardPathOf(config), '-Section', section],
|
|
1384
|
+
exec.signal,
|
|
1385
|
+
)
|
|
1386
|
+
if (result.code !== 0) {
|
|
1387
|
+
throw new Error(`周期报告已写入 ${reportPath},但推送看板失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
|
|
1388
|
+
}
|
|
1389
|
+
pushText = result.stdout.trim()
|
|
1390
|
+
const match = /已写入\s*(\d+)\s*条[,,]\s*跳过重复\s*(\d+)\s*条/.exec(pushText)
|
|
1391
|
+
if (match) {
|
|
1392
|
+
pushed = Number(match[1])
|
|
1393
|
+
skipped = Number(match[2])
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
const after = await readBoard(config.reportDir)
|
|
1398
|
+
const kindLabel = PERIOD_KINDS[range.kind]?.label ?? '周期报告'
|
|
1399
|
+
const summary = shouldPush
|
|
1400
|
+
? `${kindLabel}已写入 ${reportPath};区间源数据 ${periodPath};看板 ${pushed ? `新增 ${pushed} 条` : '无新增条目'}${skipped ? `,跳过重复 ${skipped} 条` : ''},当前未完成 ${after.open.length} 条。`
|
|
1401
|
+
: `${kindLabel}已写入 ${reportPath};区间源数据 ${periodPath};按要求未推送看板。`
|
|
1402
|
+
return {
|
|
1403
|
+
periodPath,
|
|
1404
|
+
reportPath,
|
|
1405
|
+
pushed,
|
|
1406
|
+
skipped,
|
|
1407
|
+
boardOpen: after.open.length,
|
|
1408
|
+
text: `${summary}${provided ? '' : '\n正文由区间日报自动聚合,可直接使用,也可改写后用 content 重交。'}\n${pushText}`.trim(),
|
|
1409
|
+
}
|
|
1410
|
+
},
|
|
1411
|
+
})
|
|
1412
|
+
|
|
1413
|
+
ctx.tools.register({
|
|
1414
|
+
name: 'daily_report_board',
|
|
1415
|
+
description:
|
|
1416
|
+
'查看或维护工作看板(_日报\\看板.md)。show 列出未完成待办;done 把匹配的待办移到「已完成」;'
|
|
1417
|
+
+ 'drop 把决定不做的移到「已放弃」(不是完成);update 改一条的优先级、截止日或状态。'
|
|
1418
|
+
+ 'done/drop/update 需要 keyword(标题子串,或条目里的 #h 指纹)。',
|
|
1419
|
+
parameters: {
|
|
1420
|
+
type: 'object',
|
|
1421
|
+
additionalProperties: false,
|
|
1422
|
+
required: ['action'],
|
|
1423
|
+
properties: {
|
|
1424
|
+
action: { type: 'string', enum: ['show', 'done', 'drop', 'update'], description: 'show | done | drop | update。' },
|
|
1425
|
+
keyword: { type: 'string', description: 'done/drop/update 必填,待办标题里的关键词或 #h 指纹。' },
|
|
1426
|
+
priority: { type: 'string', enum: ['P1', 'P2', 'P3', 'none'], description: 'update 可选:优先级,none 表示清空。' },
|
|
1427
|
+
due: { type: 'string', description: 'update 可选:截止日 YYYY-MM-DD,none 表示清空。' },
|
|
1428
|
+
status: { type: 'string', enum: ['todo', 'doing', 'done', 'drop'], description: 'update 可选:目标状态,省略则只改元数据。' },
|
|
1429
|
+
},
|
|
1430
|
+
},
|
|
1431
|
+
output: {
|
|
1432
|
+
schema: {
|
|
1433
|
+
type: 'object',
|
|
1434
|
+
additionalProperties: false,
|
|
1435
|
+
required: ['action', 'openCount', 'text'],
|
|
1436
|
+
properties: {
|
|
1437
|
+
action: { type: 'string' },
|
|
1438
|
+
openCount: { type: 'integer' },
|
|
1439
|
+
open: { type: 'array', items: { type: 'string' } },
|
|
1440
|
+
updated: { type: 'string' },
|
|
1441
|
+
text: { type: 'string' },
|
|
1442
|
+
},
|
|
1443
|
+
},
|
|
1444
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
1445
|
+
},
|
|
1446
|
+
async execute(args, exec) {
|
|
1447
|
+
const action = args.action
|
|
1448
|
+
if (!['show', 'done', 'drop', 'update'].includes(action)) {
|
|
1449
|
+
throw new Error(`未知动作:${action}`)
|
|
1450
|
+
}
|
|
1451
|
+
if (action === 'update') {
|
|
1452
|
+
const keyword = String(args.keyword ?? '').trim()
|
|
1453
|
+
if (keyword === '') throw new Error('update 需要 keyword')
|
|
1454
|
+
const patch = boardPatch(args)
|
|
1455
|
+
const { stdout, board } = await updateBoard(config, keyword, patch, exec.signal)
|
|
1456
|
+
return {
|
|
1457
|
+
action,
|
|
1458
|
+
openCount: board.open.length,
|
|
1459
|
+
open: board.open,
|
|
1460
|
+
updated: stdout,
|
|
1461
|
+
text: `${stdout}\n未完成 ${board.open.length} 条。`.trim(),
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (action !== 'show') {
|
|
1465
|
+
const keyword = String(args.keyword ?? '').trim()
|
|
1466
|
+
if (keyword === '') throw new Error(`${action} 需要 keyword`)
|
|
1467
|
+
const flag = action === 'done' ? '-Done' : '-Drop'
|
|
1468
|
+
const result = await runScript(config, 'push-to-board.ps1', [flag, keyword, '-BoardPath', boardPathOf(config)], exec.signal)
|
|
1469
|
+
if (result.code !== 0) {
|
|
1470
|
+
throw new Error(`${action} 失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
|
|
1471
|
+
}
|
|
1472
|
+
const board = await readBoard(config.reportDir)
|
|
1473
|
+
return {
|
|
1474
|
+
action,
|
|
1475
|
+
openCount: board.open.length,
|
|
1476
|
+
open: board.open,
|
|
1477
|
+
text: `${result.stdout.trim()}\n未完成 ${board.open.length} 条。`.trim(),
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
const result = await runScript(config, 'push-to-board.ps1', ['-Show', '-BoardPath', boardPathOf(config)], exec.signal)
|
|
1481
|
+
if (result.code !== 0) {
|
|
1482
|
+
throw new Error(`读取看板失败(退出码 ${result.code}):\n${tail(result.stderr || result.stdout)}`)
|
|
1483
|
+
}
|
|
1484
|
+
const board = await readBoard(config.reportDir)
|
|
1485
|
+
const listed = board.open.slice(0, 30).join('\n')
|
|
1486
|
+
return {
|
|
1487
|
+
action,
|
|
1488
|
+
openCount: board.open.length,
|
|
1489
|
+
open: board.open.slice(0, 50),
|
|
1490
|
+
text: board.open.length === 0
|
|
1491
|
+
? '看板没有未完成待办。'
|
|
1492
|
+
: `未完成 ${board.open.length} 条:\n${listed}`,
|
|
1493
|
+
}
|
|
1494
|
+
},
|
|
1495
|
+
})
|
|
1496
|
+
|
|
1497
|
+
// 侧边栏「日报」页面读的数据:只读、同源、不缓存。Host 没接 Web 服务时这段自动缺席。
|
|
1498
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
1499
|
+
const stateDispose = webCtx.webServer.register({
|
|
1500
|
+
kind: 'exact',
|
|
1501
|
+
path: '/dsh-work-summary/state',
|
|
1502
|
+
resource: async () => {
|
|
1503
|
+
try {
|
|
1504
|
+
const payload = await readState(config)
|
|
1505
|
+
return new Response(JSON.stringify(payload), {
|
|
1506
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
1507
|
+
})
|
|
1508
|
+
} catch (error) {
|
|
1509
|
+
return new Response(JSON.stringify({ error: String(error?.message ?? error) }), {
|
|
1510
|
+
status: 500,
|
|
1511
|
+
headers: { 'content-type': 'application/json; charset=utf-8' },
|
|
1512
|
+
})
|
|
1513
|
+
}
|
|
1514
|
+
},
|
|
1515
|
+
})
|
|
1516
|
+
|
|
1517
|
+
// 看板页是唯一允许写文件的页面入口:只改条目元数据/状态,不碰日报正文。
|
|
1518
|
+
const boardDispose = webCtx.webServer.register({
|
|
1519
|
+
kind: 'exact',
|
|
1520
|
+
path: '/dsh-work-summary/board',
|
|
1521
|
+
handler: async (req, res) => {
|
|
1522
|
+
const send = (status, value) => {
|
|
1523
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
1524
|
+
res.end(JSON.stringify(value))
|
|
1525
|
+
}
|
|
1526
|
+
try {
|
|
1527
|
+
if (req.method !== 'POST') {
|
|
1528
|
+
res.writeHead(405, { allow: 'POST' })
|
|
1529
|
+
res.end()
|
|
1530
|
+
return
|
|
1531
|
+
}
|
|
1532
|
+
const body = await readJsonBody(req)
|
|
1533
|
+
const keyword = String(body.keyword ?? '').trim()
|
|
1534
|
+
if (keyword === '') throw new Error('keyword 不能为空:写标题关键词或条目里的 #h 指纹')
|
|
1535
|
+
const patch = boardPatch(body)
|
|
1536
|
+
const { stdout, board } = await updateBoard(config, keyword, patch)
|
|
1537
|
+
send(200, { updated: stdout, openCount: board.open.length })
|
|
1538
|
+
} catch (error) {
|
|
1539
|
+
send(400, { error: String(error?.message ?? error) })
|
|
1540
|
+
}
|
|
1541
|
+
},
|
|
1542
|
+
})
|
|
1543
|
+
|
|
1544
|
+
return () => {
|
|
1545
|
+
if (typeof stateDispose === 'function') stateDispose()
|
|
1546
|
+
if (typeof boardDispose === 'function') boardDispose()
|
|
1547
|
+
}
|
|
1548
|
+
})
|
|
1549
|
+
|
|
1550
|
+
// 设置页:读/改那条日报计划任务。任务的 rrule 就是唯一真源,不另存一份配置。
|
|
1551
|
+
ctx.inject(['webServer', 'schedule'], (sc) => {
|
|
1552
|
+
const send = (res, status, value) => {
|
|
1553
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
1554
|
+
res.end(JSON.stringify(value))
|
|
1555
|
+
}
|
|
1556
|
+
const dispose = sc.webServer.register({
|
|
1557
|
+
kind: 'exact',
|
|
1558
|
+
path: '/dsh-work-summary/schedule',
|
|
1559
|
+
handler: async (req, res) => {
|
|
1560
|
+
try {
|
|
1561
|
+
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
1562
|
+
const [daily, week, month] = await Promise.all([
|
|
1563
|
+
scheduleState(sc, config),
|
|
1564
|
+
periodScheduleState(sc, config, 'week'),
|
|
1565
|
+
periodScheduleState(sc, config, 'month'),
|
|
1566
|
+
])
|
|
1567
|
+
send(res, 200, settingsPayload({ daily, week, month }, config))
|
|
1568
|
+
return
|
|
1569
|
+
}
|
|
1570
|
+
if (req.method !== 'POST') {
|
|
1571
|
+
res.writeHead(405, { allow: 'GET, HEAD, POST' })
|
|
1572
|
+
res.end()
|
|
1573
|
+
return
|
|
1574
|
+
}
|
|
1575
|
+
const chunks = []
|
|
1576
|
+
for await (const chunk of req) chunks.push(chunk)
|
|
1577
|
+
const raw = Buffer.concat(chunks).toString('utf8')
|
|
1578
|
+
const body = raw.trim() === '' ? {} : JSON.parse(raw)
|
|
1579
|
+
const patch = {}
|
|
1580
|
+
let touched = false
|
|
1581
|
+
// 周报/月报:时间与启停都先落到 settings.json,再改任务本身;任务被删了还能按保存的值重建。
|
|
1582
|
+
for (const spec of [
|
|
1583
|
+
{ kind: 'week', label: '周报', timeField: 'weekTime', activeField: 'weekActive', timeKey: 'weekScheduleTime', enabledKey: 'weekScheduleEnabled', rrule: weeklyRrule },
|
|
1584
|
+
{ kind: 'month', label: '月报', timeField: 'monthTime', activeField: 'monthActive', timeKey: 'monthScheduleTime', enabledKey: 'monthScheduleEnabled', rrule: monthlyRrule },
|
|
1585
|
+
]) {
|
|
1586
|
+
const time = body[spec.timeField]
|
|
1587
|
+
const wantActive = body[spec.activeField]
|
|
1588
|
+
if (time === undefined && wantActive === undefined) continue
|
|
1589
|
+
touched = true
|
|
1590
|
+
const current = await periodScheduleState(sc, config, spec.kind)
|
|
1591
|
+
if (!current.found) throw new Error(`没找到${spec.label}计划任务;先重启一次让插件把它建出来`)
|
|
1592
|
+
const periodPatch = {}
|
|
1593
|
+
if (time !== undefined) {
|
|
1594
|
+
if (typeof time !== 'string') throw new Error(`${spec.timeField} 应为字符串`)
|
|
1595
|
+
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(time)) throw new Error(`时间格式应为 HH:MM,收到:${time}`)
|
|
1596
|
+
periodPatch.timing = { kind: 'rrule', rrule: spec.rrule(current.timeZone, time) }
|
|
1597
|
+
await writeSettings({ [spec.timeKey]: time })
|
|
1598
|
+
config[spec.timeKey] = time
|
|
1599
|
+
}
|
|
1600
|
+
if (wantActive !== undefined) {
|
|
1601
|
+
if (typeof wantActive !== 'boolean') throw new Error(`${spec.activeField} 应为布尔值`)
|
|
1602
|
+
periodPatch.active = wantActive
|
|
1603
|
+
await writeSettings({ [spec.enabledKey]: wantActive })
|
|
1604
|
+
config[spec.enabledKey] = wantActive
|
|
1605
|
+
}
|
|
1606
|
+
if (Object.keys(periodPatch).length > 0) {
|
|
1607
|
+
await sc.schedule.edit({ id: current.id, action: 'update', patch: periodPatch })
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
if (typeof body.time === 'string' || typeof body.active === 'boolean') {
|
|
1611
|
+
touched = true
|
|
1612
|
+
const current = await scheduleState(sc, config)
|
|
1613
|
+
if (!current.found) throw new Error('没找到日报计划任务;先重启一次让插件把它建出来')
|
|
1614
|
+
if (typeof body.time === 'string') {
|
|
1615
|
+
if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(body.time)) throw new Error(`时间格式应为 HH:MM,收到:${body.time}`)
|
|
1616
|
+
patch.timing = { kind: 'rrule', rrule: dailyRrule(current.timeZone, body.time) }
|
|
1617
|
+
}
|
|
1618
|
+
if (typeof body.active === 'boolean') patch.active = body.active
|
|
1619
|
+
}
|
|
1620
|
+
if (body.reportDir !== undefined) {
|
|
1621
|
+
touched = true
|
|
1622
|
+
if (typeof body.reportDir !== 'string') throw new Error('reportDir 应为字符串')
|
|
1623
|
+
const value = body.reportDir.trim()
|
|
1624
|
+
if (!/^[A-Za-z]:[\\/]|^\\\\|^\//.test(value)) {
|
|
1625
|
+
throw new Error('日报目录要写绝对路径,比如 D:\\reports')
|
|
1626
|
+
}
|
|
1627
|
+
await mkdir(value, { recursive: true })
|
|
1628
|
+
await writeSettings({ reportDir: value })
|
|
1629
|
+
config.reportDir = value
|
|
1630
|
+
await logLine(config, 'info', `日报目录改为 ${value}(日报、看板、源数据都写到这里)`)
|
|
1631
|
+
}
|
|
1632
|
+
if (body.workspace !== undefined) {
|
|
1633
|
+
touched = true
|
|
1634
|
+
if (typeof body.workspace !== 'string') throw new Error('workspace 应为字符串')
|
|
1635
|
+
const value = body.workspace.trim()
|
|
1636
|
+
if (!/^[A-Za-z]:[\\/]|^\\\\|^\//.test(value)) {
|
|
1637
|
+
throw new Error('工作空间要写绝对路径,比如 D:\\projects')
|
|
1638
|
+
}
|
|
1639
|
+
await mkdir(value, { recursive: true })
|
|
1640
|
+
await writeSettings({ workspace: value })
|
|
1641
|
+
config.workspace = value
|
|
1642
|
+
await logLine(config, 'info', `工作空间改为 ${value}(日报会扫描这里当天的改动)`)
|
|
1643
|
+
}
|
|
1644
|
+
if (body.logDir !== undefined) {
|
|
1645
|
+
touched = true
|
|
1646
|
+
if (typeof body.logDir !== 'string') throw new Error('logDir 应为字符串')
|
|
1647
|
+
const value = body.logDir.trim()
|
|
1648
|
+
if (value !== '' && !/^[A-Za-z]:[\\/]|^\\\\|^\//.test(value)) {
|
|
1649
|
+
throw new Error('日志目录要写绝对路径,比如 D:\\logs;留空表示用数据目录下的 _日志')
|
|
1650
|
+
}
|
|
1651
|
+
const target = value === '' ? join(config.reportDir, '_日志') : value
|
|
1652
|
+
await mkdir(target, { recursive: true })
|
|
1653
|
+
await writeSettings({ logDir: value })
|
|
1654
|
+
config.logDir = value
|
|
1655
|
+
await logLine(config, 'info', `日志目录改为 ${logDirOf(config)}`)
|
|
1656
|
+
}
|
|
1657
|
+
if (!touched) {
|
|
1658
|
+
throw new Error('没有要改的字段(time / active / weekTime / weekActive / monthTime / monthActive / reportDir / workspace / logDir)')
|
|
1659
|
+
}
|
|
1660
|
+
if (Object.keys(patch).length > 0) {
|
|
1661
|
+
await sc.schedule.edit({ id: (await scheduleState(sc, config)).id, action: 'update', patch })
|
|
1662
|
+
}
|
|
1663
|
+
const [daily, week, month] = await Promise.all([
|
|
1664
|
+
scheduleState(sc, config),
|
|
1665
|
+
periodScheduleState(sc, config, 'week'),
|
|
1666
|
+
periodScheduleState(sc, config, 'month'),
|
|
1667
|
+
])
|
|
1668
|
+
send(res, 200, settingsPayload({ daily, week, month }, config))
|
|
1669
|
+
} catch (error) {
|
|
1670
|
+
send(res, 400, { error: String(error?.message ?? error) })
|
|
1671
|
+
}
|
|
1672
|
+
},
|
|
1673
|
+
})
|
|
1674
|
+
return () => { if (typeof dispose === 'function') dispose() }
|
|
1675
|
+
})
|
|
1676
|
+
|
|
1677
|
+
if (config.scheduleEnabled) installSchedule(ctx, config)
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
/**
|
|
1681
|
+
* 插件自管的计划任务:日报每天一条,周报每周一、月报每月 1 号各一条。
|
|
1682
|
+
* 已有同标题任务就同步提示词/时间/启停;日报没有则认领旧任务,周报月报没有则按开关新建。
|
|
1683
|
+
* 失败只记日志,不影响工具可用。
|
|
1684
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
|
|
1685
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
1686
|
+
* @returns {void}
|
|
1687
|
+
*/
|
|
1688
|
+
function installSchedule(ctx, config) {
|
|
1689
|
+
const prompt = schedulePrompt(config)
|
|
1690
|
+
ctx.inject(['schedule'], (scheduleCtx) => {
|
|
1691
|
+
void (async () => {
|
|
1692
|
+
const page = await scheduleCtx.schedule.list({ limit: 200 })
|
|
1693
|
+
const items = page.items ?? []
|
|
1694
|
+
const own = findOwnTask(items, config)
|
|
1695
|
+
if (own) {
|
|
1696
|
+
if (own.status === 'active' && own.prompt !== prompt) {
|
|
1697
|
+
await scheduleCtx.schedule.edit({ id: own.id, action: 'update', patch: { prompt } })
|
|
1698
|
+
ctx.logger?.info?.('dsh-work-summary: 已同步日报计划任务的提示词')
|
|
1699
|
+
void logLine(config, 'info', `计划任务「${own.title}」的提示词已同步到当前版本`)
|
|
1700
|
+
}
|
|
1701
|
+
} else {
|
|
1702
|
+
const legacy = config.scheduleAdopt
|
|
1703
|
+
? items.find(task => task.status === 'active' && /collect-day\.ps1|daily_report_collect/.test(String(task.prompt ?? '')))
|
|
1704
|
+
: null
|
|
1705
|
+
if (legacy) {
|
|
1706
|
+
await scheduleCtx.schedule.edit({ id: legacy.id, action: 'update', patch: { prompt } })
|
|
1707
|
+
ctx.logger?.info?.(`dsh-work-summary: 已把旧日报计划任务「${legacy.title}」切到插件工具`)
|
|
1708
|
+
void logLine(config, 'info', `已认领旧任务「${legacy.title}」,提示词切到插件工具`)
|
|
1709
|
+
} else {
|
|
1710
|
+
const today = dateInZone(config.scheduleTimeZone).replace(/-/g, '')
|
|
1711
|
+
const [hour, minute] = config.scheduleTime.split(':')
|
|
1712
|
+
const rrule = `DTSTART;TZID=${config.scheduleTimeZone}:${today}T${hour}${minute}00\nRRULE:FREQ=DAILY`
|
|
1713
|
+
await scheduleCtx.schedule.create({
|
|
1714
|
+
title: config.scheduleTitle,
|
|
1715
|
+
prompt,
|
|
1716
|
+
timing: { kind: 'rrule', rrule },
|
|
1717
|
+
target: { kind: 'new_once' },
|
|
1718
|
+
})
|
|
1719
|
+
ctx.logger?.info?.(`dsh-work-summary: 已创建每日 ${config.scheduleTime} 的日报计划任务`)
|
|
1720
|
+
void logLine(config, 'info', `已创建每日 ${config.scheduleTime} 的日报计划任务`)
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
await installPeriodTask(ctx, scheduleCtx, config, 'week')
|
|
1724
|
+
await installPeriodTask(ctx, scheduleCtx, config, 'month')
|
|
1725
|
+
})().catch((error) => {
|
|
1726
|
+
ctx.logger?.warn?.(`dsh-work-summary: 计划任务处理失败:${error instanceof Error ? error.message : String(error)}`)
|
|
1727
|
+
})
|
|
1728
|
+
})
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
/**
|
|
1732
|
+
* 托管一条周期任务:时间/启停以插件配置为准,标题是稳定识别键。
|
|
1733
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - 插件上下文。
|
|
1734
|
+
* @param {*} scheduleCtx - schedule 服务上下文。
|
|
1735
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
1736
|
+
* @param {'week'|'month'} kind - 周报或月报。
|
|
1737
|
+
* @returns {Promise<void>} 完成。
|
|
1738
|
+
*/
|
|
1739
|
+
async function installPeriodTask(ctx, scheduleCtx, config, kind) {
|
|
1740
|
+
const week = kind === 'week'
|
|
1741
|
+
const title = week ? config.weekScheduleTitle : config.monthScheduleTitle
|
|
1742
|
+
const time = week ? config.weekScheduleTime : config.monthScheduleTime
|
|
1743
|
+
const enabled = Boolean(week ? config.weekScheduleEnabled : config.monthScheduleEnabled)
|
|
1744
|
+
const prompt = periodPrompt(config, kind)
|
|
1745
|
+
const rrule = (week ? weeklyRrule : monthlyRrule)(config.scheduleTimeZone, time)
|
|
1746
|
+
const items = (await scheduleCtx.schedule.list({ limit: 200 })).items ?? []
|
|
1747
|
+
const task = findTaskByTitle(items, title)
|
|
1748
|
+
const label = week ? '周报' : '月报'
|
|
1749
|
+
|
|
1750
|
+
if (!task) {
|
|
1751
|
+
if (!enabled) return
|
|
1752
|
+
await scheduleCtx.schedule.create({
|
|
1753
|
+
title,
|
|
1754
|
+
prompt,
|
|
1755
|
+
timing: { kind: 'rrule', rrule },
|
|
1756
|
+
target: { kind: 'new_once' },
|
|
1757
|
+
})
|
|
1758
|
+
ctx.logger?.info?.(`dsh-work-summary: 已创建${label}计划任务(${time})`)
|
|
1759
|
+
void logLine(config, 'info', `已创建${label}计划任务「${title}」(${time})`)
|
|
1760
|
+
return
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
const patch = {}
|
|
1764
|
+
if (task.prompt !== prompt) patch.prompt = prompt
|
|
1765
|
+
const parsed = parseRruleTime(task)
|
|
1766
|
+
const [hour, minute] = time.split(':').map(Number)
|
|
1767
|
+
if (parsed.hour !== hour || parsed.minute !== minute) patch.timing = { kind: 'rrule', rrule }
|
|
1768
|
+
if ((task.status === 'active') !== enabled) patch.active = enabled
|
|
1769
|
+
if (Object.keys(patch).length === 0) return
|
|
1770
|
+
await scheduleCtx.schedule.edit({ id: task.id, action: 'update', patch })
|
|
1771
|
+
ctx.logger?.info?.(`dsh-work-summary: 已同步${label}计划任务`)
|
|
1772
|
+
void logLine(config, 'info', `${label}计划任务「${title}」已同步(${enabled ? time : '已暂停'})`)
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
/**
|
|
1776
|
+
* 交给计划任务执行的提示词:只说流程,细则留在 PROMPT.md。
|
|
1777
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
1778
|
+
* @returns {string} 提示词正文。
|
|
1779
|
+
*/
|
|
1780
|
+
function schedulePrompt(config) {
|
|
1781
|
+
return [
|
|
1782
|
+
'每日工作日报时间到。用 dsh-work-summary 插件的工具完成今日日报:',
|
|
1783
|
+
'',
|
|
1784
|
+
'1. 调用 `daily_report_collect`(不传 date 即今天),然后读取返回的 sourcePath(源数据底稿)。',
|
|
1785
|
+
`2. 按 \`${config.promptPath}\` 的规则写正文,结构用 collect 返回的 template 六节。`,
|
|
1786
|
+
'3. 调用 `daily_report_save` 提交:它会校验结构、写日报文件、把「明日开场清单」推进看板。报错就按提示修正后重试。',
|
|
1787
|
+
'4. 回复:日报路径 + 写入看板条数 + 三条最重要结论(≤5 行)。',
|
|
1788
|
+
'',
|
|
1789
|
+
'只写有证据支撑的内容,推断标「推断:」;采集失败或数据缺失就写明原因,不要编造。当天几乎无产出就写短版。',
|
|
1790
|
+
].join('\n')
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
/**
|
|
1794
|
+
* 周报/月报计划任务的提示词:固定生成上一完整周期,避免月初/周一拿到空区间。
|
|
1795
|
+
* @param {typeof DEFAULTS} config - 生效配置。
|
|
1796
|
+
* @param {'week'|'month'} kind - 周报或月报。
|
|
1797
|
+
* @returns {string} 提示词正文。
|
|
1798
|
+
*/
|
|
1799
|
+
function periodPrompt(config, kind) {
|
|
1800
|
+
const week = kind === 'week'
|
|
1801
|
+
const label = week ? '周报' : '月报'
|
|
1802
|
+
const span = week ? '上一周(周一至周日)' : '上一个自然月'
|
|
1803
|
+
return [
|
|
1804
|
+
`定时${label}时间到。用 work_summary_period 工具生成${span}的${label}:`,
|
|
1805
|
+
'',
|
|
1806
|
+
`1. 调用 \`work_summary_period\`,参数 { "kind": "${kind}", "offset": 1 };它会先采集区间源数据,再写四节正文并推看板。`,
|
|
1807
|
+
'2. 读返回的 reportPath,核对四节是否齐全,并记下哪些日期缺日报。',
|
|
1808
|
+
`3. 回复:${label}路径 + 看板新增条数 + 三条最重要结论(≤5 行);缺日报的日期一并点出。`,
|
|
1809
|
+
'',
|
|
1810
|
+
'只写有证据支撑的内容,不要编造;写入失败就说明原因,不要重复硬跑。',
|
|
1811
|
+
].join('\n')
|
|
1812
|
+
}
|