dsh-seal-scripts 0.0.0-stage → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +318 -0
  3. package/README.md +342 -2
  4. package/cordis.patch.yml +6 -0
  5. package/index.js +12 -0
  6. package/lib/client.js +1465 -0
  7. package/lib/core/assembly.js +321 -0
  8. package/lib/core/catalog-snapshot.js +78 -0
  9. package/lib/core/diary.js +100 -0
  10. package/lib/core/health.js +72 -0
  11. package/lib/core/index.js +491 -0
  12. package/lib/core/inject.js +146 -0
  13. package/lib/core/lang.js +251 -0
  14. package/lib/core/locale.js +56 -0
  15. package/lib/core/memory-file.js +214 -0
  16. package/lib/core/migrate.js +97 -0
  17. package/lib/core/path-guard.js +43 -0
  18. package/lib/core/project-key.js +52 -0
  19. package/lib/core/render.js +228 -0
  20. package/lib/core/schema-runner.js +281 -0
  21. package/lib/core/schema-tools.js +794 -0
  22. package/lib/core/schema.js +493 -0
  23. package/lib/core/search.js +254 -0
  24. package/lib/core/settings.js +158 -0
  25. package/lib/core/store.js +408 -0
  26. package/lib/core/tool-transfer.js +249 -0
  27. package/lib/core/tool.js +602 -0
  28. package/lib/core/zip.js +226 -0
  29. package/lib/core/zstd-js.js +705 -0
  30. package/lib/core/zstd.js +103 -0
  31. package/lib/host/api.js +9 -0
  32. package/lib/host/capabilities.js +155 -0
  33. package/lib/host/compact-delete.js +76 -0
  34. package/lib/host/delete.js +136 -0
  35. package/lib/host/host-contract.js +73 -0
  36. package/lib/host/http-util.js +82 -0
  37. package/lib/host/lifecycle.js +66 -0
  38. package/lib/host/register.js +63 -0
  39. package/lib/host/routes/memories.js +102 -0
  40. package/lib/host/routes/options.js +46 -0
  41. package/lib/host/routes/sessions.js +194 -0
  42. package/lib/host/routes/tools.js +103 -0
  43. package/lib/host/summary.js +71 -0
  44. package/package.json +60 -4
@@ -0,0 +1,321 @@
1
+ /**
2
+ * 装配:把本工作区的回顾按自然日衰减后,拼成一段进上下文的文本。
3
+ *
4
+ * 全是同步读:systemPrompt.context() 的 text 是同步求值的(resolveContext 直接调用,
5
+ * 不 await),所以这里不能用 await。每轮求值一次、永远读最新磁盘状态,
6
+ * 于是同一个工作区的所有会话在同一时刻看到同一份回顾 —— 和 AGENTS.md 一样的保证。
7
+ */
8
+
9
+ import fs from 'node:fs'
10
+ import path from 'node:path'
11
+ import { memoryDir, readAssemblySync } from './store.js'
12
+
13
+ // diary.js 与旧测试还在用这个同步读;实现搬到 store.js(边车扫描),这里继续导出。
14
+ export { readAssemblySync }
15
+ import { parseMemory } from './memory-file.js'
16
+ import { dialogueOnly } from './render.js'
17
+ import { DEFAULT_OPTIONS, readOptionsSync } from './settings.js'
18
+ import { composeInjection } from './inject.js'
19
+ import { phrasesFor, localizeBody, isBlankDiary, isBlankKeywords, readField, LANG_ZH } from './lang.js'
20
+ import { readLocaleSync } from './locale.js'
21
+
22
+ /** 一天的毫秒数。 */
23
+ const DAY = 86400000
24
+
25
+ /**
26
+ * 自然日差(含当天算第一天)。按本地日期算,不看小时。
27
+ * @param {string} compactedAt ISO 时间
28
+ * @param {Date} now
29
+ * @returns {number} 1 表示压缩当天
30
+ */
31
+ export function dayIndex(compactedAt, now = new Date()) {
32
+ const then = new Date(compactedAt)
33
+ if (Number.isNaN(then.getTime())) return 1
34
+ const a = Date.UTC(then.getFullYear(), then.getMonth(), then.getDate())
35
+ const b = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
36
+ return Math.round((b - a) / DAY) + 1
37
+ }
38
+
39
+ /**
40
+ * 自然衰减到的深度:第 1 天 3、第 2 天 2、第 3–28 天 1、第 29 天起 0。
41
+ * @param {string} compactedAt
42
+ * @param {Date} now
43
+ * @returns {0|1|2|3}
44
+ */
45
+ export function naturalCount(compactedAt, now = new Date()) {
46
+ const day = dayIndex(compactedAt, now)
47
+ if (day <= 1) return 3
48
+ if (day === 2) return 2
49
+ if (day <= 28) return 1
50
+ return 0
51
+ }
52
+
53
+ /**
54
+ * 这一条此刻的有效深度。锁定过的回顾不再衰减;开了「停止降低」,全部停在记下的深度。
55
+ * @param {{compactedAt:string, count:number, pinned:boolean}} entry
56
+ * @param {Date} now
57
+ * @param {object} options 选项(默认值 = 现版本行为:按自然日衰减)
58
+ * @returns {0|1|2|3}
59
+ */
60
+ export function effectiveCount(entry, now = new Date(), options = DEFAULT_OPTIONS) {
61
+ const stored = typeof entry.count === 'number' ? entry.count : null
62
+ if (options !== null && typeof options === 'object' && options.stopLowering === true && stored !== null) return stored
63
+ if (entry.pinned && stored !== null) return stored
64
+ return naturalCount(entry.compactedAt, now)
65
+ }
66
+
67
+ /**
68
+ * 这一条载入时用哪一级:选了具体数字就用它,否则跟随深度。
69
+ * 只影响载入,不动载入文件里记下的 count / pinned。
70
+ * @param {object} entry
71
+ * @param {Date} now
72
+ * @param {object} options
73
+ * @returns {0|1|2|3}
74
+ */
75
+ export function loadLevel(entry, now = new Date(), options = DEFAULT_OPTIONS) {
76
+ const forced = options !== null && typeof options === 'object' ? options.loadLevel : undefined
77
+ if (Number.isInteger(forced) && forced >= 0 && forced <= 3) return forced
78
+ return effectiveCount(entry, now, options)
79
+ }
80
+
81
+ /** 载入数值选了具体数字吗(设置页据此把深度徽章标成「载入覆盖」)。 */
82
+ export function isLevelForced(options = DEFAULT_OPTIONS) {
83
+ return options !== null && typeof options === 'object' &&
84
+ Number.isInteger(options.loadLevel) && options.loadLevel >= 0 && options.loadLevel <= 3
85
+ }
86
+
87
+ /** 同步读一份回顾并解析;读不到返回 null。 */
88
+ export function readMemorySync(dir, file) {
89
+ try {
90
+ return parseMemory(fs.readFileSync(path.join(dir, file), 'utf8'))
91
+ } catch {
92
+ return null
93
+ }
94
+ }
95
+
96
+ /** `10-27 23:04` 这样的短日期 + 时分(本地时间,和用户说的「29 号」一致)。 */
97
+ function shortDate(compactedAt) {
98
+ const d = new Date(compactedAt)
99
+ if (Number.isNaN(d.getTime())) return '??-?? ??:??'
100
+ const p = (n) => String(n).padStart(2, '0')
101
+ return p(d.getMonth() + 1) + '-' + p(d.getDate()) + ' ' + p(d.getHours()) + ':' + p(d.getMinutes())
102
+ }
103
+
104
+ /**
105
+ * 一条回顾按深度取内容。
106
+ * @param {object} entry
107
+ * @param {object} parsed parseMemory 的结果
108
+ * @param {number} level 0–3
109
+ * @param {object} options fullLoad 为真时,深度 3 也保留工具行与报错
110
+ * @param {'zh'|'en'} lang 显示语言:中文标记是通配键,英文在这里换字(文件不动)
111
+ * @returns {string}
112
+ */
113
+ export function renderEntry(entry, parsed, level, options = DEFAULT_OPTIONS, lang = LANG_ZH) {
114
+ const P = phrasesFor(lang)
115
+ const head = P.reviewHead(shortDate(entry.compactedAt))
116
+ const sections = parsed.sections ?? {}
117
+ if (level >= 3) {
118
+ const body = sections.body ?? ''
119
+ const full = options !== null && typeof options === 'object' && options.fullLoad === true
120
+ if (full) return head + '\n' + (localizeBody(body, lang) || P.noBody)
121
+ const say = localizeBody(dialogueOnly(body), lang)
122
+ return head + '\n' + (say || P.noDialogue)
123
+ }
124
+ if (level === 2) {
125
+ return head + '\n' + (localizeBody(sections.sum, lang).trim() || P.noSummary)
126
+ }
127
+ if (level === 1) {
128
+ // 日记空着(文件里写的是(空))时,按 0.2.3 的约定注入(未总结)/(none)。
129
+ return head + '\n' + (isBlankDiary(sections.diary) ? P.none : sections.diary.trim())
130
+ }
131
+ // 深度 0:关键词 + 文件名一行。关键词没写就注入(未总结),文件名照旧留着。
132
+ const keywords = readField(parsed.meta, 'keywords')
133
+ const word = isBlankKeywords(keywords) ? P.none : keywords
134
+ return head + ' ' + word + ' · ' + entry.file
135
+ }
136
+
137
+ /**
138
+ * 拼出这一轮要注入的回顾文本。没有回顾就返回空串(空串会把条目整个移除)。
139
+ * 选项在调用时读:每轮重算,设置页一改,下一轮立刻按新选项装配。
140
+ * @param {string} dshHome
141
+ * @param {string} cwd 工作区
142
+ * @param {Date} now
143
+ * @param {object} options 选项(默认从磁盘读)
144
+ * @param {'zh'|'en'} lang 显示语言(默认读语言文件;文件不在就是中文)
145
+ * @returns {string}
146
+ */
147
+ export function buildMemoryContext(dshHome, cwd, now = new Date(), options = readOptionsSync(dshHome), lang = readLocaleSync(dshHome)) {
148
+ const dir = memoryDir(dshHome, cwd)
149
+ const data = readAssemblySync(dir, cwd)
150
+ if (!data || data.entries.length === 0) return ''
151
+
152
+ const ordered = [...data.entries]
153
+ .filter((e) => e && typeof e.file === 'string')
154
+ .sort((a, b) => String(a.compactedAt).localeCompare(String(b.compactedAt)))
155
+
156
+ const blocks = []
157
+ for (const entry of ordered) {
158
+ const parsed = readMemorySync(dir, entry.file)
159
+ if (!parsed) continue
160
+ blocks.push(renderEntry(entry, parsed, loadLevel(entry, now, options), options, lang))
161
+ }
162
+ if (blocks.length === 0) return ''
163
+ return phrasesFor(lang).preamble() + '\n\n' + blocks.join('\n\n')
164
+ }
165
+
166
+ /** 把一个工作区当前的载入状态读出来(设置页与测试用)。 */
167
+ export function snapshotAssembly(dshHome, cwd, now = new Date()) {
168
+ const dir = memoryDir(dshHome, cwd)
169
+ const data = readAssemblySync(dir, cwd)
170
+ if (!data) return { dir, entries: [] }
171
+ return {
172
+ dir,
173
+ entries: data.entries.map((e) => ({
174
+ ...e,
175
+ level: effectiveCount(e, now),
176
+ age: dayIndex(e.compactedAt, now)
177
+ }))
178
+ }
179
+ }
180
+
181
+ /* ────────────────────────────────────────────────────────────────
182
+ * 下面这些是后来补的:装配失败时指向「回顾过大」、以及给设置页看当前载入。
183
+ * 全部同步,因为 systemPrompt.context() 的 text 是同步求值的。
184
+ * ──────────────────────────────────────────────────────────────── */
185
+
186
+ /** 目录里每份 .md 的大小,从大到小。出错给空数组,不抛。 */
187
+ function memoryFileSizes(dir) {
188
+ const out = []
189
+ let names = []
190
+ try { names = fs.readdirSync(dir) } catch { return out }
191
+ for (const name of names) {
192
+ if (!name.endsWith('.md')) continue
193
+ try { out.push({ name, bytes: fs.statSync(path.join(dir, name)).size }) } catch { /* 跳过读不到的单份 */ }
194
+ }
195
+ return out.sort((a, b) => b.bytes - a.bytes)
196
+ }
197
+
198
+ function kb(n) { return (n / 1024).toFixed(1) + ' KB' }
199
+
200
+ /**
201
+ * 装配失败时给模型看的诊断。设计文档第十四节:报错要指向「回顾过大」。
202
+ * 不静默返回空串——空串会让这一轮看起来像「本来就没有回顾」。
203
+ */
204
+ export function oversizeDiagnostic(dshHome, cwd, error) {
205
+ const dir = memoryDir(dshHome, cwd)
206
+ const files = memoryFileSizes(dir)
207
+ const total = files.reduce((n, f) => n + f.bytes, 0)
208
+ const biggest = files[0]
209
+ const lines = [
210
+ '【回顾没有载入成功】工作区 ' + cwd + ' 的回顾装配失败,最可能是回顾过大。',
211
+ '目录:' + dir,
212
+ '现状:' + files.length + ' 份,合计 ' + kb(total) +
213
+ (biggest ? ',最大 ' + biggest.name + '(' + kb(biggest.bytes) + ')' : ''),
214
+ '处理:换到别的工作区的会话,或把上面最大的那份回顾删掉、精简后再回来。',
215
+ '原始错误:' + (error && error.message ? error.message : String(error))
216
+ ]
217
+ return lines.join('\n')
218
+ }
219
+
220
+ /** buildMemoryContext 的安全版:失败时返回诊断文本,不返回空串。 */
221
+ export function buildMemoryContextOrDiagnostic(dshHome, cwd, now = new Date(), options = readOptionsSync(dshHome)) {
222
+ try {
223
+ return buildMemoryContext(dshHome, cwd, now, options)
224
+ } catch (err) {
225
+ return oversizeDiagnostic(dshHome, cwd, err)
226
+ }
227
+ }
228
+
229
+ /**
230
+ * 设置页用:这一刻真正会被载入的文字,外加每一条用了哪一级。
231
+ * 与注入走同一个 buildMemoryContext(选项也同一份),所以框里看到的就是真的;
232
+ * 概括提醒在「上下文提醒」档要并进同一条消息,所以由调用方把提醒文本递进来,
233
+ * 这里用和注入同一个 composeInjection 拼——预览与实况字字相同。
234
+ */
235
+ export function describeLoad(dshHome, cwd, now = new Date(), options = readOptionsSync(dshHome), reminder = '', disabled = options.injectEnabled === false) {
236
+ const dir = memoryDir(dshHome, cwd)
237
+ const data = readAssemblySync(dir, cwd)
238
+ const forced = isLevelForced(options)
239
+ const entries = []
240
+ if (data) {
241
+ for (const entry of data.entries) {
242
+ if (!entry || typeof entry.file !== 'string') continue
243
+ const parsed = readMemorySync(dir, entry.file)
244
+ entries.push({
245
+ file: entry.file,
246
+ compactedAt: entry.compactedAt,
247
+ level: loadLevel(entry, now, options),
248
+ markedLevel: effectiveCount(entry, now, options),
249
+ loadForced: forced,
250
+ age: dayIndex(entry.compactedAt, now),
251
+ pinned: entry.pinned === true,
252
+ bytes: parsed ? Buffer.byteLength(JSON.stringify(parsed.sections), 'utf8') : 0,
253
+ ok: parsed !== null
254
+ })
255
+ }
256
+ entries.sort((a, b) => String(a.compactedAt).localeCompare(String(b.compactedAt)))
257
+ }
258
+ let text = ''
259
+ let error = null
260
+ // 注入总开关开着才拼文本;关着就只列条目(设置页仍然能看有哪些回顾)。
261
+ if (!disabled) {
262
+ try {
263
+ text = composeInjection(buildMemoryContext(dshHome, cwd, now, options), reminder)
264
+ } catch (err) {
265
+ error = err
266
+ text = oversizeDiagnostic(dshHome, cwd, err)
267
+ }
268
+ }
269
+ return {
270
+ cwd,
271
+ dir,
272
+ text,
273
+ chars: text.length,
274
+ entries,
275
+ loadForced: forced,
276
+ disabled,
277
+ error: error ? (error.message ? error.message : String(error)) : null
278
+ }
279
+ }
280
+
281
+ /**
282
+ * 设置页用:只看某一条回顾时,它自己会被注入成什么样子。
283
+ * 与 buildMemoryContext 里对这条走的是同一个 renderEntry(同一份选项),所以框里看到的还是真话。
284
+ * @param {string} dshHome
285
+ * @param {string} cwd
286
+ * @param {string} file
287
+ * @param {Date} now
288
+ * @param {object} options
289
+ */
290
+ export function describeEntry(dshHome, cwd, file, now = new Date(), options = readOptionsSync(dshHome)) {
291
+ const dir = memoryDir(dshHome, cwd)
292
+ const data = readAssemblySync(dir, cwd)
293
+ const name = String(file ?? '')
294
+ const entry = data && Array.isArray(data.entries)
295
+ ? data.entries.find((e) => e && e.file === name)
296
+ : null
297
+ if (!entry) {
298
+ return { file: name, text: '', chars: 0, level: null, age: null, error: '这条回顾不在载入清单里:' + name }
299
+ }
300
+ const parsed = readMemorySync(dir, entry.file)
301
+ if (!parsed) {
302
+ return { file: name, text: '', chars: 0, level: null, age: null, error: '读不出这份回顾:' + entry.file }
303
+ }
304
+ const level = loadLevel(entry, now, options)
305
+ const text = renderEntry(entry, parsed, level, options, readLocaleSync(dshHome))
306
+ return {
307
+ file: entry.file,
308
+ text,
309
+ chars: text.length,
310
+ level,
311
+ markedLevel: effectiveCount(entry, now, options),
312
+ loadForced: isLevelForced(options),
313
+ age: dayIndex(entry.compactedAt, now),
314
+ error: null
315
+ }
316
+ }
317
+
318
+ /** 对外暴露的短日期 `10-27`(日记提醒要用)。 */
319
+ export function shortDateOf(compactedAt) {
320
+ return shortDate(compactedAt)
321
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * 清单词快照(0.4.5):把「工具组」那一段系统提示词按会话冻住。
3
+ *
4
+ * 为什么要有这一层:catalogText() 每轮现算,装/删一个工具脚本,下一轮系统提示词就变,
5
+ * 而系统提示词一变,整份会话就要当未缓存输入重发一次——老会话里加一个工具,代价是
6
+ * 把几百轮的上下文重新计费送一遍。默认档「新会话开始之前」的取舍是:会话第一次装配时
7
+ * 取一次现词,之后固定——但 0.4.6 起,用户每改一次「清单词刷新时刻」,就把所有已记住的
8
+ * 会话刷新成那一刻的现词(切到实时、切回默认,两个方向都算)。
9
+ *
10
+ * 两件不冻的事(都是有意的):
11
+ * 1. 换语言:用户主动切语言时立刻重算,不然设置页刚切成英文、这里还挂着中文。
12
+ * 2. 关掉「注入工具组清单」:直接返回空串,这一段整个不注入(开关优先于快照)。
13
+ *
14
+ * 认不出会话 id 时退回现算(realtime 的行为):宁可多一次缓存未命中,也不要两次装配
15
+ * 冻成不同内容——那会让同一会话的两轮系统提示词在边界上跳一下。
16
+ *
17
+ * 记忆只在本进程里,重启就没了:重启后第一次装配等于「新会话开始之前」再取一次现词,
18
+ * 与这一档的语义一致(重启后整份缓存本来也要重建)。
19
+ */
20
+
21
+ import { catalogText } from './schema.js'
22
+
23
+ /** 最多记住多少个会话的清单,超出按插入顺序丢最旧的(Map 保序)。 */
24
+ export const MAX_SNAPSHOTS = 64
25
+
26
+ /** @type {Map<string, {text: string, lang: string}>} */
27
+ const snapshots = new Map()
28
+
29
+ /**
30
+ * 取这个会话该用的清单文本:第一次调用算并记住,之后原样返回。
31
+ * @param {string} dshHome
32
+ * @param {string} lang 显示语言;和记住的那次不同就重算并覆盖
33
+ * @param {string} sessionId 会话标识;空串表示认不出会话,退回现算
34
+ * @returns {string}
35
+ */
36
+ export function catalogTextForSession(dshHome, lang, sessionId) {
37
+ const key = typeof sessionId === 'string' ? sessionId : ''
38
+ if (key === '') return catalogText(dshHome, lang)
39
+ const hit = snapshots.get(key)
40
+ if (hit !== undefined && hit.lang === lang) return hit.text
41
+ const text = catalogText(dshHome, lang)
42
+ // 覆盖已有键时要先删再插:Map 的插入顺序决定谁先被挤出去,重算过的会话应排到队尾。
43
+ snapshots.delete(key)
44
+ snapshots.set(key, { text, lang })
45
+ while (snapshots.size > MAX_SNAPSHOTS) {
46
+ const oldest = snapshots.keys().next()
47
+ if (oldest.done) break
48
+ snapshots.delete(oldest.value)
49
+ }
50
+ return text
51
+ }
52
+
53
+ /**
54
+ * 把已经记住的每个会话都改成「此刻的现词」(0.4.6)。
55
+ *
56
+ * 触发点只有一个:用户改「清单词刷新时刻」的那一下(两个方向都算)。
57
+ * 这就是要的语义——A→B 时按磁盘现状注入,B→A 时把那一刻的现状冻住;
58
+ * 之后停在 A,装/删工具脚本都不再动提示词,直到下一次切档。
59
+ * 还没装配过的会话不建快照:它们第一次装配时自然取现词。
60
+ * @param {string} dshHome
61
+ * @param {string} lang
62
+ * @returns {{refreshed: number, text: string}}
63
+ */
64
+ export function refreshCatalogSnapshots(dshHome, lang) {
65
+ const text = catalogText(dshHome, lang)
66
+ for (const key of snapshots.keys()) snapshots.set(key, { text, lang })
67
+ return { refreshed: snapshots.size, text }
68
+ }
69
+
70
+ /** 清空全部快照(测试与「立刻重算」用)。 */
71
+ export function resetCatalogSnapshots() {
72
+ snapshots.clear()
73
+ }
74
+
75
+ /** 现在记住了哪些会话(测试用)。 */
76
+ export function catalogSnapshotKeys() {
77
+ return [...snapshots.keys()]
78
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * 该补写的回顾的提醒(0.2.3)。
3
+ *
4
+ * 判定:**载入级别 ≤ 1 的回顾,只要关键词或日记还有一项空着,就催。**
5
+ * 0 级:显示的是关键词 + 文件名,关键词空着就催;
6
+ * 1 级:显示的是日记,日记空着就催。
7
+ * 催一次就把两项一起写完(读原文 → 关键词 → 日记),所以任一为空都算「还没写全」。
8
+ * 一条提醒把本工作区所有这样的回顾一次列全,按压缩时刻从旧到新。
9
+ *
10
+ * 语言跟 DSH 设置走(lang.js 里的词条),这里只拼装。
11
+ * 这里只读文件,不写盘。
12
+ */
13
+
14
+ import { memoryDir } from './store.js'
15
+ import { readAssemblySync, readMemorySync, loadLevel, dayIndex, shortDateOf } from './assembly.js'
16
+ import { readOptionsSync } from './settings.js'
17
+ import {
18
+ phrasesFor, isBlankDiary, isBlankKeywords, readField,
19
+ MISSING_KEYWORDS, MISSING_DIARY, LANG_ZH
20
+ } from './lang.js'
21
+ import { readLocaleSync } from './locale.js'
22
+
23
+ // 老名字继续可用(测试与别处都在用)。
24
+ export { isBlankDiary }
25
+
26
+ /**
27
+ * 这一轮该催的回顾:载入级别 0 或 1,且关键词/日记至少一项空着。
28
+ * @param {string} dshHome
29
+ * @param {string} cwd
30
+ * @param {Date} now
31
+ * @param {object} options
32
+ * @returns {Array<{dir:string, entry:object, parsed:object, level:number, missing:string[]}>}
33
+ */
34
+ export function pendingDiaries(dshHome, cwd, now = new Date(), options = readOptionsSync(dshHome)) {
35
+ const dir = memoryDir(dshHome, cwd)
36
+ const data = readAssemblySync(dir)
37
+ if (!data || !Array.isArray(data.entries) || data.entries.length === 0) return []
38
+ const ordered = data.entries
39
+ .filter((e) => e && typeof e.file === 'string')
40
+ .slice()
41
+ .sort((a, b) => String(a.compactedAt).localeCompare(String(b.compactedAt)))
42
+ const out = []
43
+ for (const entry of ordered) {
44
+ // 只有「显示的就是关键词/日记」那两级才催;摘要、原文两级不催。
45
+ const level = loadLevel(entry, now, options)
46
+ if (level > 1) continue
47
+ const parsed = readMemorySync(dir, entry.file)
48
+ if (!parsed) continue
49
+ const missing = []
50
+ if (isBlankKeywords(readField(parsed.meta, 'keywords'))) missing.push(MISSING_KEYWORDS)
51
+ if (isBlankDiary(parsed.sections ? parsed.sections.diary : '')) missing.push(MISSING_DIARY)
52
+ if (missing.length === 0) continue
53
+ out.push({ dir, entry, parsed, level, missing })
54
+ }
55
+ return out
56
+ }
57
+
58
+ /**
59
+ * 拼提醒文本。纯函数:只读词条,不记账。
60
+ * @param {Array<{entry:object, missing?:string[]}>|{entry:object}} found pendingDiaries 的返回值(也收单条)
61
+ * @param {Date} now
62
+ * @param {'zh'|'en'} lang
63
+ * @returns {string}
64
+ */
65
+ export function reminderTextOf(found, now = new Date(), lang = LANG_ZH) {
66
+ const list = Array.isArray(found) ? found : [found]
67
+ const ready = list.filter((item) => item && item.entry && typeof item.entry.file === 'string')
68
+ if (ready.length === 0) return ''
69
+ const P = phrasesFor(lang)
70
+ const head = P.reminderHead(ready.length)
71
+ // 每份只列一行「哪一份、缺什么」;读与写怎么做由下面一组共用步骤说一次(0.2.7:
72
+ // 一次 writes 把全部写完,不在每块里重复三段调用)。
73
+ const blocks = ready.map((item, i) => {
74
+ const { entry } = item
75
+ const keys = Array.isArray(item.missing) && item.missing.length > 0
76
+ ? item.missing
77
+ : [MISSING_KEYWORDS, MISSING_DIARY]
78
+ const missing = keys.map((k) => (k === MISSING_KEYWORDS ? P.keywordsWord : P.diaryWord))
79
+ const tag = ready.length === 1 ? '' : '【' + (i + 1) + '/' + ready.length + '】'
80
+ return P.reminderItem(tag, entry.file, shortDateOf(entry.compactedAt), dayIndex(entry.compactedAt, now), P.missingLabel(missing))
81
+ })
82
+ // 收尾一句写死态度:全部写完再继续、不核对回读、不复述(0.2.7 起)。
83
+ return [head, ...blocks, ...P.reminderSteps(ready.map((item) => item.entry.file)), P.reminderTail()].join('\n')
84
+ }
85
+
86
+ /**
87
+ * 这一轮要注入的提醒;没有就给空串。
88
+ * 只要还有该补写的回顾就有内容,全写齐自然变成空串,提醒随之消失。
89
+ * @param {string} dshHome
90
+ * @param {string} cwd
91
+ * @param {Date} now
92
+ * @param {object} options
93
+ * @param {'zh'|'en'} lang 默认读语言文件(跟 DSH 设置走)
94
+ * @returns {string}
95
+ */
96
+ export function diaryReminder(dshHome, cwd, now = new Date(), options = readOptionsSync(dshHome), lang = readLocaleSync(dshHome)) {
97
+ const list = pendingDiaries(dshHome, cwd, now, options)
98
+ if (list.length === 0) return ''
99
+ return reminderTextOf(list, now, lang)
100
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * 回顾管道的心跳:最近一次成功/失败。
3
+ *
4
+ * 为什么单独一个文件:拆回顾失败以前只落进日志,用户在界面上看到的是
5
+ * 「一份看起来完全正常、只是不再增长的列表」——锁死了也不会有人知道。
6
+ * 这份文件按 #工作区 key# 记账,只留最近一次,不增长。
7
+ */
8
+ import fs from 'node:fs'
9
+ import fsp from 'node:fs/promises'
10
+ import path from 'node:path'
11
+ import { memoryRoot, writeFileAtomic } from './store.js'
12
+ import { projectKey } from './project-key.js'
13
+
14
+ const HEALTH_FILE = '_health.json'
15
+
16
+ export function healthPath(dshHome) {
17
+ return path.join(memoryRoot(dshHome), HEALTH_FILE)
18
+ }
19
+
20
+ /** 同步读(注入路径要同步);坏文件当空。 */
21
+ export function readHealthSync(dshHome) {
22
+ try {
23
+ const parsed = JSON.parse(fs.readFileSync(healthPath(dshHome), 'utf8'))
24
+ return parsed && typeof parsed === 'object' && parsed.workspaces && typeof parsed.workspaces === 'object'
25
+ ? parsed
26
+ : { workspaces: {} }
27
+ } catch {
28
+ return { workspaces: {} }
29
+ }
30
+ }
31
+
32
+ /**
33
+ * 记一次结果。只留最近一次,写失败不影响主流程。
34
+ * @param {string} dshHome
35
+ * @param {string} cwd
36
+ * @param {{ok:boolean, at?:number, code?:string, message?:string, file?:string}} event
37
+ */
38
+ export async function recordHealth(dshHome, cwd, event) {
39
+ try {
40
+ const data = readHealthSync(dshHome)
41
+ const key = projectKey(cwd)
42
+ data.workspaces[key] = {
43
+ workspace: cwd,
44
+ ok: event.ok === true,
45
+ at: Number(event.at) || Date.now(),
46
+ code: event.ok === true ? '' : String(event.code ?? 'unknown'),
47
+ message: event.ok === true ? '' : String(event.message ?? '').slice(0, 500),
48
+ file: event.ok === true ? String(event.file ?? '') : ''
49
+ }
50
+ await fsp.mkdir(memoryRoot(dshHome), { recursive: true })
51
+ await writeFileAtomic(healthPath(dshHome), JSON.stringify(data, null, 2) + '\n')
52
+ } catch { /* 心跳写不进去,不能连累回顾本身 */ }
53
+ }
54
+
55
+ /** 宿主自己那条心跳记在哪个键下(index.js 用 '(harness)' 当工作区记账)。 */
56
+ const HARNESS = '(harness)'
57
+
58
+ /**
59
+ * 宿主层面的最近一次失败(缺能力、卸载异常等)。
60
+ *
61
+ * 注意不能用字面量 '(harness)' 当键:记账走的是 projectKey(),
62
+ * 键实际长得像 --~0028harness~0029--。
63
+ */
64
+ export function harnessHealthOf(dshHome) {
65
+ try { return readHealthSync(dshHome).workspaces?.[projectKey(HARNESS)] ?? null } catch { return null }
66
+ }
67
+
68
+ /** 设置页用:某个工作区最近一次结果;没有就是 null。 */
69
+ export function healthOf(dshHome, cwd) {
70
+ const all = readHealthSync(dshHome).workspaces ?? {}
71
+ try { return all[projectKey(cwd)] ?? null } catch { return null }
72
+ }