dsh-agent-soul 0.9.11 → 0.9.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,147 @@
1
+ /**
2
+ * 日记 · deliver.js(2026-11-10 KNOWN-ISSUES #26:由 scheduler.js 按职责拆出)
3
+ * 投递与回执判定:shouldAskAgain / askAgentToWrite(含 mtimeMsOf)。
4
+ * 「她写没写」的判据是目标文件在不在、mtime 是否新于本轮基线 —— 事故注释在函数体里。
5
+ * 定时器 / 双层锁 / 业务主流程仍在 scheduler.js;会话获取在 agent.js。
6
+ */
7
+ import { statSync } from 'node:fs'
8
+ import { exists } from '../paths.js'
9
+ import { waitForWrite } from './files.js'
10
+ import { note, serviceOf } from '../env.js'
11
+
12
+
13
+ /**
14
+ * 投一条消息给绑定会话,让她自己写日记,然后等文件出现(2026-11-04)。
15
+ *
16
+ * ── 回执为什么用「文件出现」而不是 followup 的返回值 ──
17
+ * 2026-10-31 就是栽在这儿:`agent.followup()` **同步返回 void**,旧判据
18
+ * 「没抛异常就算发送成功」对 void 函数恒为真 —— 日志天天报「已发送」,
19
+ * 取证的时候 335 个事件里 `source.kind='schedule'` 零命中,一个 turn 都没进。
20
+ *
21
+ * 官方 schedule 插件靠 `await sessions.flush(agent.session)` 拿回执,但那是从
22
+ * 打包好的 exe 里逆出来的接口,我在这边没法验证它一定存在。而 flush 也只能证明
23
+ * 「消息进了 turn」,证明不了「她把文章写完了」。
24
+ *
25
+ * 所以判据直接取最终事实:**目标文件在不在**。文件在就是写成了,别的一律不算。
26
+ *
27
+ * ── source.kind 为什么是 'schedule' ──
28
+ * extract.js 会跳过这个来源(不进记忆),mood.js 也跳过(不影响心情),
29
+ * 日记扫描自己也跳过(不进 JSONL)—— 否则「叫她写日记」这件事本身会被
30
+ * 记成一条对话,越滚越多。
31
+ *
32
+ * @returns {{ asked: boolean, wrote: boolean, reason: string }}
33
+ */
34
+ /**
35
+ * 文件的 mtime(毫秒)。读不到就返回 0 —— 调用方据此当成「比任何 since 都旧」,
36
+ * 也就是宁可重写一次,也不要把旧文件当成她的新产出。
37
+ */
38
+ function mtimeMsOf(file) {
39
+ try {
40
+ return statSync(file).mtimeMs
41
+ } catch {
42
+ return 0
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 决定「还要不要再找她写一次」。
48
+ *
49
+ * 2026-11-07 R05 / P1-D3:抽成纯函数,一是给测试一个确定的入口,
50
+ * 二是把这条判断从 followup 的一大段代码里拎出来单独说清楚。
51
+ *
52
+ * - force(手动重写)→ 一定重新写
53
+ * - 文件不存在 → 要写
54
+ * - 文件存在 + since=0(没有时间基线,老调用方)→ 当她已经写过(保持老行为)
55
+ * - 文件存在 + since>0 → 只有比 since 新才算「她这轮写的」,否则是旧文件,重写
56
+ *
57
+ * @param {string} file
58
+ * @param {{ force?: boolean, since?: number }} [options]
59
+ * @returns {boolean} true = 要问她/重写
60
+ */
61
+ export function shouldAskAgain(file, { force = false, since = 0 } = {}) {
62
+ if (force === true) return true
63
+ if (!exists(file)) return true
64
+ if (!(since > 0)) return false
65
+ const mtime = mtimeMsOf(file)
66
+ // mtime 读不到(被删/权限)时按「更旧」处理:宁可重写一次,也不要把旧文件当成新产出
67
+ return mtime < since
68
+ }
69
+
70
+ export async function askAgentToWrite(ctx, agent, text, file, timeoutMs, { force = false, since = 0 } = {}) {
71
+ // 已经写过了就别再投 —— 投了也只能等来一个「已存在」的文件,白打扰她一次。
72
+ //
73
+ // 这条必须排在 agent 检查**之前**:否则没绑定会话的时候,哪怕她早就写好了,
74
+ // 也会一路掉进兜底生成,把她写的日记整篇覆盖掉。
75
+ // force(手动重写某一天)时跳过这个判断 —— 那种场景就是要重新写。
76
+ //
77
+ // ── 2026-11-07 R05 / P1-D3:光看「文件在不在」会把旧文件当成她刚写的 ──
78
+ //
79
+ // 事故链:某天有一篇「写于当天最后一句话之前」的半成品(下午手动补的),
80
+ // startupWork 判它不完整 → 决定重写 → 走到这里看到文件存在 → 认为"她写好了"
81
+ // → 记「日记完成」返回 true → 文件没变 → 下一轮仍不完整 → 再走一遍……
82
+ // 结果是**看门狗每 30 分钟空转一次**,而日志里写的是「日记完成」,看起来一切正常,
83
+ // 那段内容永远补不回来。
84
+ //
85
+ // 现在多一个时间判据:`since` = 这一轮开始重写的时间。文件比它旧,就说明是上一轮
86
+ // 留下的旧文件,不能算「她这次写的」。`since` 为 0 时保持老行为(其它调用方不受影响)。
87
+ if (!shouldAskAgain(file, { force, since })) {
88
+ return { asked: false, wrote: true, reason: '' }
89
+ }
90
+ if (exists(file) && force !== true) {
91
+ // 走到这里 = 文件在、但比 since 旧 → 是上一轮留下的旧文件,这次重新问她
92
+ note('diary', `${file} 是旧文件(写于本轮之前),这次重新找她写`)
93
+ }
94
+
95
+ if (agent === undefined || agent === null || typeof agent.followup !== 'function') {
96
+ return { asked: false, wrote: false, reason: '没有可投递的会话(followup 不可用)' }
97
+ }
98
+
99
+ let message
100
+ try {
101
+ const blocks = [{ type: 'text', text }]
102
+ const llm = serviceOf(ctx, 'llm')
103
+ message = llm !== undefined && llm !== null && typeof llm.createUserMessage === 'function'
104
+ ? llm.createUserMessage({ content: blocks, source: { kind: 'schedule' } })
105
+ : {
106
+ id: `soul-diary-${Date.now()}-${Math.random().toString(16).slice(2)}`,
107
+ role: 'user',
108
+ content: blocks,
109
+ source: { kind: 'schedule' }
110
+ }
111
+ } catch (error) {
112
+ return { asked: false, wrote: false, reason: `构造消息失败:${error instanceof Error ? error.message : error}` }
113
+ }
114
+
115
+ // 记下投递前的 mtime,用来判断「是不是这次写出来的」。
116
+ // followup 有可能是**同步**写盘的(插件内部的工具调用可以在同一个 tick 里跑完),
117
+ // 所以投完要立刻看一眼 —— 不能直接交给 waitForWrite:
118
+ // waitForWrite 的语义是「等 mtime 变化」,它进去时会把当前 mtime 当成基线,
119
+ // 文件要是已经写好了,基线就等于完成后的值,于是永远等不到「变化」。
120
+ const mtimeBefore = (() => {
121
+ try {
122
+ return exists(file) ? statSync(file).mtimeMs : 0
123
+ } catch {
124
+ return 0
125
+ }
126
+ })()
127
+
128
+ try {
129
+ agent.followup(message)
130
+ } catch (error) {
131
+ return { asked: false, wrote: false, reason: `投递抛异常:${error instanceof Error ? error.message : error}` }
132
+ }
133
+
134
+ // 同步就写完的情况:这里直接认,别再去等一个永远不会来的 mtime 变化
135
+ try {
136
+ if (exists(file) && statSync(file).mtimeMs > mtimeBefore) return { asked: true, wrote: true, reason: '' }
137
+ } catch {
138
+ /* 读不到就往下走,交给异步等待 */
139
+ }
140
+
141
+ const wrote = await waitForWrite(file, timeoutMs)
142
+ return {
143
+ asked: true,
144
+ wrote,
145
+ reason: wrote ? '' : `等了 ${Math.round(timeoutMs / 1000)} 秒没见她写出文件`
146
+ }
147
+ }
@@ -2,108 +2,21 @@
2
2
  * 日记 · scheduler.js
3
3
  * 由 lib/diary.js 按职责拆出(2026-11-06 模块化重构),函数体保持原样。
4
4
  */
5
- import { composeDiarySetup } from './agent.js'
5
+ import { diaryAgent } from './agent.js'
6
6
  import { readRecentDiaries } from './history.js'
7
7
  import { composeDiaryText } from './llm.js'
8
8
  import { buildMoodBlocks, composePrivateMessage, composePublicMessage } from './compose.js'
9
9
  import { closeMentioned, expireThreads, extractThreads, loadThreads, openThread, renderThreadSection, saveThreads } from '../threads.js'
10
10
  import { diaryIsCompleteFor, todayKey, yesterdayKey } from '../diary/completion.js'
11
11
  import { diaryPrivatePath, diaryPublicPath, exists, readText } from '../paths.js'
12
- import { findMissingDay, waitForWrite, writeDiaryFile } from './files.js'
12
+ import { findMissingDay, writeDiaryFile } from './files.js'
13
+ import { askAgentToWrite } from './deliver.js'
13
14
  import { join } from 'node:path'
14
15
  import { loadConfig } from '../store.js'
15
16
  import { note, serviceOf } from '../env.js'
16
17
  import { pickConversation } from '../core/diary-pick.js'
17
18
  import { readConversationRows, readDiaryConversations } from './feed.js'
18
- import { statSync } from 'node:fs'
19
19
 
20
-
21
- export async function diaryAgent(ctx) {
22
- const config = loadConfig()
23
- const sessionId = String(config.diarySessionId ?? '').trim()
24
-
25
- if (sessionId === '') {
26
- // 没有绑定就是没有绑定。以前这里会去捞「最近活跃会话」,等于把日记写进
27
- // 用户正在聊的那个会话 —— 语义错了,私密内容还可能摆到不该看的人面前。
28
- note('diary', '没有绑定日记会话(diarySessionId 为空),跳过本次投递。去设置页「日记」里点「把当前会话指定为日记会话」')
29
- return undefined
30
- }
31
-
32
- const agents = serviceOf(ctx, 'agents')
33
- if (agents === undefined || agents === null || typeof agents.get !== 'function') {
34
- note('diary', `绑定的日记会话不可用:宿主没有 agents 服务(${sessionId})`)
35
- return undefined
36
- }
37
-
38
- const reasons = []
39
-
40
- // ① 活着的
41
- try {
42
- const live = agents.get(sessionId)
43
- if (live !== undefined && live !== null) {
44
- note('diary', `绑定的日记会话已在运行:${sessionId}`)
45
- return live
46
- }
47
- reasons.push('当前不活跃')
48
- } catch (error) {
49
- const message = error instanceof Error ? error.message : String(error)
50
- note('diary', `取活会话 ${sessionId} 失败:${message}`)
51
- reasons.push(`get 失败:${message}`)
52
- }
53
-
54
- // ② 冷启动
55
- if (typeof agents.resume !== 'function') {
56
- reasons.push('agents 服务没有 resume 方法')
57
- } else {
58
- try {
59
- // 必须带上 setup:resume 只恢复会话,不恢复 preset。
60
- // 不带的话日记会话会「活着但没有工具」,而且不报错(2026-11-03 事故)。
61
- const setup = await composeDiarySetup(ctx, sessionId)
62
-
63
- // 2026-11-05 修:还必须有 agentOptions.model。
64
- //
65
- // 文档原话:「agents[].provider / agents[].model —— 模型路由;分发前两者都必须存在」。
66
- // resume 一个持久化会话时,模型**不会**从会话里恢复(session 头里根本没这个字段),
67
- // 不显式传就得到一个没有模型的 agent。后果不是「模型选错了」,而是装配直接抛:
68
- // prompt variable "{{model}}" has no value (section "deployment:persona-prefix")
69
- // 每一轮都抛,日记一个字也写不出来 —— 而且界面只显示「本轮运行失败」,很难联想到模型。
70
- //
71
- // 路由取日记专用配置;没配就退回 diarySummarize*(也是给日记用的),
72
- // 两个都没有时明确记一行,不要静默传空。
73
- const provider = String(config.diaryAgentProvider ?? '').trim() || String(config.diarySummarizeProvider ?? '').trim()
74
- const model = String(config.diaryAgentModel ?? '').trim() || String(config.diarySummarizeModel ?? '').trim()
75
- let agentOptions
76
- if (provider !== '' && model !== '') {
77
- agentOptions = { provider, model }
78
- } else {
79
- note('diary', '没配 diaryAgentProvider/Model 也没配 diarySummarize*:冷启动的日记会话将没有模型,装配会失败')
80
- }
81
-
82
- const handle = await agents.resume({
83
- resumeSessionId: sessionId,
84
- ...(agentOptions === undefined ? {} : { agentOptions }),
85
- ...(setup === undefined ? {} : { setup })
86
- })
87
- const agent = handle?.agent
88
- if (agent !== undefined && agent !== null) {
89
- note('diary', `冷启动绑定的日记会话成功:${sessionId}`)
90
- return agent
91
- }
92
- reasons.push('resume 没有返回 agent')
93
- } catch (error) {
94
- const message = error instanceof Error ? error.message : String(error)
95
- note('diary', `冷启动绑定的日记会话 ${sessionId} 失败:${message}`)
96
- reasons.push(`resume 失败:${message}`)
97
- }
98
- }
99
-
100
- note('diary', `绑定的日记会话不可用:${reasons.join(';') || '未知原因'}(${sessionId})`)
101
- return undefined
102
- }
103
-
104
-
105
-
106
- // --------------------------------------------------------------------------
107
20
  // 启动时写(2026-10-31 改造:去掉 22:00 闹钟)
108
21
  // --------------------------------------------------------------------------
109
22
 
@@ -259,11 +172,6 @@ export function startDiaryTimer(ctx, { budgetMs = DIARY_TOTAL_BUDGET_MS } = {})
259
172
  }
260
173
  }
261
174
 
262
-
263
- // --------------------------------------------------------------------------
264
- // 主流程
265
- // --------------------------------------------------------------------------
266
-
267
175
  /**
268
176
  * 执行一次完整的日记生成流程。
269
177
  *
@@ -279,142 +187,6 @@ export function startDiaryTimer(ctx, { budgetMs = DIARY_TOTAL_BUDGET_MS } = {})
279
187
  * @param {string} [manualNote] 手动触发时的备注(追加到对话内容之后)
280
188
  * @returns {Promise<boolean>} 是否成功投递
281
189
  */
282
- /**
283
- * 投一条消息给绑定会话,让她自己写日记,然后等文件出现(2026-11-04)。
284
- *
285
- * ── 回执为什么用「文件出现」而不是 followup 的返回值 ──
286
- * 2026-10-31 就是栽在这儿:`agent.followup()` **同步返回 void**,旧判据
287
- * 「没抛异常就算发送成功」对 void 函数恒为真 —— 日志天天报「已发送」,
288
- * 取证的时候 335 个事件里 `source.kind='schedule'` 零命中,一个 turn 都没进。
289
- *
290
- * 官方 schedule 插件靠 `await sessions.flush(agent.session)` 拿回执,但那是从
291
- * 打包好的 exe 里逆出来的接口,我在这边没法验证它一定存在。而 flush 也只能证明
292
- * 「消息进了 turn」,证明不了「她把文章写完了」。
293
- *
294
- * 所以判据直接取最终事实:**目标文件在不在**。文件在就是写成了,别的一律不算。
295
- *
296
- * ── source.kind 为什么是 'schedule' ──
297
- * extract.js 会跳过这个来源(不进记忆),mood.js 也跳过(不影响心情),
298
- * 日记扫描自己也跳过(不进 JSONL)—— 否则「叫她写日记」这件事本身会被
299
- * 记成一条对话,越滚越多。
300
- *
301
- * @returns {{ asked: boolean, wrote: boolean, reason: string }}
302
- */
303
- /**
304
- * 文件的 mtime(毫秒)。读不到就返回 0 —— 调用方据此当成「比任何 since 都旧」,
305
- * 也就是宁可重写一次,也不要把旧文件当成她的新产出。
306
- */
307
- function mtimeMsOf(file) {
308
- try {
309
- return statSync(file).mtimeMs
310
- } catch {
311
- return 0
312
- }
313
- }
314
-
315
- /**
316
- * 决定「还要不要再找她写一次」。
317
- *
318
- * 2026-11-07 R05 / P1-D3:抽成纯函数,一是给测试一个确定的入口,
319
- * 二是把这条判断从 followup 的一大段代码里拎出来单独说清楚。
320
- *
321
- * - force(手动重写)→ 一定重新写
322
- * - 文件不存在 → 要写
323
- * - 文件存在 + since=0(没有时间基线,老调用方)→ 当她已经写过(保持老行为)
324
- * - 文件存在 + since>0 → 只有比 since 新才算「她这轮写的」,否则是旧文件,重写
325
- *
326
- * @param {string} file
327
- * @param {{ force?: boolean, since?: number }} [options]
328
- * @returns {boolean} true = 要问她/重写
329
- */
330
- export function shouldAskAgain(file, { force = false, since = 0 } = {}) {
331
- if (force === true) return true
332
- if (!exists(file)) return true
333
- if (!(since > 0)) return false
334
- const mtime = mtimeMsOf(file)
335
- // mtime 读不到(被删/权限)时按「更旧」处理:宁可重写一次,也不要把旧文件当成新产出
336
- return mtime < since
337
- }
338
-
339
- async function askAgentToWrite(ctx, agent, text, file, timeoutMs, { force = false, since = 0 } = {}) {
340
- // 已经写过了就别再投 —— 投了也只能等来一个「已存在」的文件,白打扰她一次。
341
- //
342
- // 这条必须排在 agent 检查**之前**:否则没绑定会话的时候,哪怕她早就写好了,
343
- // 也会一路掉进兜底生成,把她写的日记整篇覆盖掉。
344
- // force(手动重写某一天)时跳过这个判断 —— 那种场景就是要重新写。
345
- //
346
- // ── 2026-11-07 R05 / P1-D3:光看「文件在不在」会把旧文件当成她刚写的 ──
347
- //
348
- // 事故链:某天有一篇「写于当天最后一句话之前」的半成品(下午手动补的),
349
- // startupWork 判它不完整 → 决定重写 → 走到这里看到文件存在 → 认为"她写好了"
350
- // → 记「日记完成」返回 true → 文件没变 → 下一轮仍不完整 → 再走一遍……
351
- // 结果是**看门狗每 30 分钟空转一次**,而日志里写的是「日记完成」,看起来一切正常,
352
- // 那段内容永远补不回来。
353
- //
354
- // 现在多一个时间判据:`since` = 这一轮开始重写的时间。文件比它旧,就说明是上一轮
355
- // 留下的旧文件,不能算「她这次写的」。`since` 为 0 时保持老行为(其它调用方不受影响)。
356
- if (!shouldAskAgain(file, { force, since })) {
357
- return { asked: false, wrote: true, reason: '' }
358
- }
359
- if (exists(file) && force !== true) {
360
- // 走到这里 = 文件在、但比 since 旧 → 是上一轮留下的旧文件,这次重新问她
361
- note('diary', `${file} 是旧文件(写于本轮之前),这次重新找她写`)
362
- }
363
-
364
- if (agent === undefined || agent === null || typeof agent.followup !== 'function') {
365
- return { asked: false, wrote: false, reason: '没有可投递的会话(followup 不可用)' }
366
- }
367
-
368
- let message
369
- try {
370
- const blocks = [{ type: 'text', text }]
371
- const llm = serviceOf(ctx, 'llm')
372
- message = llm !== undefined && llm !== null && typeof llm.createUserMessage === 'function'
373
- ? llm.createUserMessage({ content: blocks, source: { kind: 'schedule' } })
374
- : {
375
- id: `soul-diary-${Date.now()}-${Math.random().toString(16).slice(2)}`,
376
- role: 'user',
377
- content: blocks,
378
- source: { kind: 'schedule' }
379
- }
380
- } catch (error) {
381
- return { asked: false, wrote: false, reason: `构造消息失败:${error instanceof Error ? error.message : error}` }
382
- }
383
-
384
- // 记下投递前的 mtime,用来判断「是不是这次写出来的」。
385
- // followup 有可能是**同步**写盘的(插件内部的工具调用可以在同一个 tick 里跑完),
386
- // 所以投完要立刻看一眼 —— 不能直接交给 waitForWrite:
387
- // waitForWrite 的语义是「等 mtime 变化」,它进去时会把当前 mtime 当成基线,
388
- // 文件要是已经写好了,基线就等于完成后的值,于是永远等不到「变化」。
389
- const mtimeBefore = (() => {
390
- try {
391
- return exists(file) ? statSync(file).mtimeMs : 0
392
- } catch {
393
- return 0
394
- }
395
- })()
396
-
397
- try {
398
- agent.followup(message)
399
- } catch (error) {
400
- return { asked: false, wrote: false, reason: `投递抛异常:${error instanceof Error ? error.message : error}` }
401
- }
402
-
403
- // 同步就写完的情况:这里直接认,别再去等一个永远不会来的 mtime 变化
404
- try {
405
- if (exists(file) && statSync(file).mtimeMs > mtimeBefore) return { asked: true, wrote: true, reason: '' }
406
- } catch {
407
- /* 读不到就往下走,交给异步等待 */
408
- }
409
-
410
- const wrote = await waitForWrite(file, timeoutMs)
411
- return {
412
- asked: true,
413
- wrote,
414
- reason: wrote ? '' : `等了 ${Math.round(timeoutMs / 1000)} 秒没见她写出文件`
415
- }
416
- }
417
-
418
190
 
419
191
  /**
420
192
  * 同一天同时只允许一条写日记的流程在跑(2026-11-04 修 ④)。
package/lib/diary.js CHANGED
@@ -43,5 +43,6 @@ export { composeDiaryText, summarizeConversations } from './diary/llm.js'
43
43
  export { digestDiaries, readRecentDiaries } from './diary/history.js'
44
44
  export { buildMoodBlocks, composePrivateMessage, composePublicMessage, diaryWindowOf } from './diary/compose.js'
45
45
  export { findMissingDay, waitForWrite, writeDiaryFile } from './diary/files.js'
46
- export { __resetDiaryInFlightForTest, diaryAgent, regenerateDiary, runCatchUp, runDiaryOnce, startDiaryTimer } from './diary/scheduler.js'
46
+ export { diaryAgent } from './diary/agent.js'
47
+ export { __resetDiaryInFlightForTest, regenerateDiary, runCatchUp, runDiaryOnce, startDiaryTimer } from './diary/scheduler.js'
47
48
  export { todayKey, yesterdayKey, parseDateLocal, scheduleMinutes, diaryDayBoundaries, diaryIsCompleteFor } from './diary/completion.js'
@@ -0,0 +1,168 @@
1
+ /**
2
+ * evidence.js —— 开关的「生效 / 未生效」证据(2026-11-10 R18-C)。
3
+ *
4
+ * ── 为什么要它 ──
5
+ * 语气链失效三天,日志一句错都没有,测试全绿。根因:**开关的值 ≠ 开关的效果** ——
6
+ * `moodToneInject: true` 只说明「用户没关它」,说明不了「它这一轮真的挂了语气」。
7
+ * 同类事故还有:记忆卡一次都没创建、日志里连报错都没有(extract.js:179 记过)。
8
+ *
9
+ * 本模块提供两只眼睛:
10
+ * ① mark(key, note) —— 动态证据:这个开关**上次真的发生**是什么时候、发生了几次。
11
+ * 内存 Map,不落盘(写盘会带来「统计本身就是新的失败面」)。
12
+ * ② statuses(cfg, extra) —— 静态生效性:这个配置组合下开关**可能**生效吗?
13
+ * inert(不可能生效)时必须给出**人话原因**(「心情关了」,而不是 moodEnabled=false)。
14
+ *
15
+ * ── 噪音纪律 ──
16
+ * 启动打一行(index.js)+ 每日健康行带一句(health.js),**绝不每轮打** ——
17
+ * 噪音会让人不再看日志,「哪一轮全掉了」就被淹掉了。
18
+ *
19
+ * ── 「0 次」≠「N/A」──
20
+ * report() 里区分「从未发生」(开关可能生效但还没轮到它)与
21
+ * 「未生效:原因」(配置组合下不可能发生)。两者混报是这轮要消灭的假旋钮。
22
+ */
23
+ import { exists, diaryPublicPath } from './paths.js'
24
+ import { yesterdayKey } from './diary/completion.js'
25
+
26
+ /** key → { count, lastAt, note }。全进程共享(开关证据本来就不分会话)。 */
27
+ const marks = new Map()
28
+
29
+ /**
30
+ * 记一次「真的发生了」。由各链路的**送达点**调用(不是决策点):
31
+ * · moodTone —— 语气消息真的 append 进了她的 inbox(inject.js)
32
+ * · moodJudge —— 心情判定成功写回(mood/judge.js)
33
+ * · memory —— 记忆段真的注入了非空文本(segment-memory.js)
34
+ * · memoryRefine—— 提炼结果真的被接受入库(refine.js)
35
+ * @param {string} key
36
+ * @param {string} [note] 人话备注(进 report,截 40 字)
37
+ */
38
+ export function mark(key, note = '') {
39
+ const prev = marks.get(key)
40
+ marks.set(key, {
41
+ count: (prev?.count ?? 0) + 1,
42
+ lastAt: Date.now(),
43
+ note: String(note ?? '').slice(0, 40)
44
+ })
45
+ }
46
+
47
+ /** 测试与 /state 用:只读快照。 */
48
+ export function markSnapshot() {
49
+ return [...marks.entries()].map(([key, v]) => ({ key, count: v.count, lastAt: v.lastAt, note: v.note }))
50
+ }
51
+
52
+ /** 测试用:清空(正常流程永不调)。 */
53
+ export function __resetEvidenceForTest() {
54
+ marks.clear()
55
+ }
56
+
57
+ /**
58
+ * 单个开关的动态证据怎么写。
59
+ * @returns {string} ''(没有 mark 点的开关)| '0 次' | 'N 次'
60
+ */
61
+ function evidenceOf(key) {
62
+ const m = marks.get(key)
63
+ if (m === undefined) return ''
64
+ return `${m.count} 次`
65
+ }
66
+
67
+ /**
68
+ * 全部开关的静态生效性 + 动态证据。
69
+ *
70
+ * @param {object} cfg loadConfig() 的结果
71
+ * @param {{ memoryRecords?: number, notesCount?: number }} [extra] 调用方算好的数据面
72
+ * @returns {Array<{key:string, label:string, status:'生效'|'未生效'|'暂无'|'从未发生'|'生效(N次)'|'边界', reason:string}>}
73
+ */
74
+ export function statuses(cfg, extra = {}) {
75
+ const out = []
76
+ const push = (key, label, status, reason = '') => out.push({ key, label, status, reason })
77
+ const on = (v) => v !== false
78
+ const memoryRecords = Number(extra.memoryRecords)
79
+ const notesCount = Number(extra.notesCount)
80
+
81
+ // ---- 总开关 ----
82
+ if (on(cfg.enabled)) push('enabled', '总开关', '生效')
83
+ else {
84
+ push('enabled', '总开关', '未生效', '插件总开关关了——下面的全部跟着停')
85
+ push('memoryEnabled', '记忆', '未生效', '插件总开关关了')
86
+ push('purposeEnabled', '目的', '未生效', '插件总开关关了')
87
+ push('notesEnabled', '笔记', '未生效', '插件总开关关了')
88
+ push('moodEnabled', '心情', '未生效', '插件总开关关了')
89
+ push('moodToneInject', '心情语气', '未生效', '插件总开关关了')
90
+ push('diaryEnabled', '日记', '未生效', '插件总开关关了')
91
+ push('memoryRefine', '提炼', '未生效', '插件总开关关了')
92
+ push('projectMemoryEnabled', '项目记忆', '未生效', '插件总开关关了')
93
+ push('projectPersonaEnabled', '项目人格', '未生效', '插件总开关关了')
94
+ return out
95
+ }
96
+
97
+ // ---- 记忆 ----
98
+ if (on(cfg.memoryEnabled)) {
99
+ if (Number.isFinite(memoryRecords) && memoryRecords === 0) push('memoryEnabled', '记忆', '暂无', '还没有一条记忆(聊出值得记的事才会有)')
100
+ else push('memoryEnabled', '记忆', '生效', Number.isFinite(memoryRecords) ? `${memoryRecords} 条` : '')
101
+ } else push('memoryEnabled', '记忆', '未生效', '记忆关了(素材照常收集,只是不注入不提取)')
102
+
103
+ // ---- 提炼(最贵,出过静默降级)----
104
+ if (on(cfg.memoryRefine)) {
105
+ const n = evidenceOf('memoryRefine')
106
+ if (n === '') push('memoryRefine', '提炼', '从未发生', '开关开着,但还没有一次提炼发生(等下一条入库;没配提炼模型会一直停在这)')
107
+ else push('memoryRefine', '提炼', `生效(${n})`)
108
+ } else push('memoryRefine', '提炼', '未生效', '提炼关了——记忆直存原话')
109
+
110
+ // ---- 目的 ----
111
+ push('purposeEnabled', on(cfg.purposeEnabled) ? '目的' : '目的', on(cfg.purposeEnabled) ? '生效' : '未生效', on(cfg.purposeEnabled) ? '' : '目的关了')
112
+
113
+ // ---- 笔记 ----
114
+ if (on(cfg.notesEnabled)) {
115
+ if (Number.isFinite(notesCount) && notesCount === 0) push('notesEnabled', '笔记', '暂无', '笔记目录是空的(她还没写过一篇)')
116
+ else push('notesEnabled', '笔记', '生效', Number.isFinite(notesCount) ? `${notesCount} 篇` : '')
117
+ } else push('notesEnabled', '笔记', '未生效', '笔记关了')
118
+
119
+ // ---- 心情 + 语气(出过三天静默事故的那条链)----
120
+ if (on(cfg.moodEnabled)) {
121
+ const judge = evidenceOf('moodJudge')
122
+ push('moodEnabled', '心情', judge === '' ? '从未发生' : `生效(判定 ${judge})`, judge === '' ? '开关开着,但还没有一次判定发生(等第一轮对话结束)' : '')
123
+ if (on(cfg.moodToneInject)) {
124
+ const tone = evidenceOf('moodTone')
125
+ if (tone === '') push('moodToneInject', '心情语气', '从未发生', '开关开着,但还没有一次语气真的挂出去(要等判定成功 + 轮次节流到点)')
126
+ else push('moodToneInject', '心情语气', `生效(挂 ${tone})`)
127
+ } else push('moodToneInject', '心情语气', '未生效', '语气开关关了——心情照样判,只是不往对话里挂')
128
+ } else {
129
+ push('moodEnabled', '心情', '未生效', '心情关了')
130
+ push('moodToneInject', '心情语气', '未生效', '心情关了——判定不跑,语气无从挂起')
131
+ }
132
+
133
+ // ---- 日记 ----
134
+ if (on(cfg.diaryEnabled)) {
135
+ const yesterdayWritten = exists(diaryPublicPath(yesterdayKey(Date.now())))
136
+ push('diaryEnabled', '日记', yesterdayWritten ? '生效' : '从未发生', yesterdayWritten ? '昨天的已写' : '昨天的还没写(看门狗/兜底会来补)')
137
+ } else push('diaryEnabled', '日记', '未生效', '日记关了')
138
+
139
+ // ---- 其余开关(静态,无 mark 点)----
140
+ push('projectMemoryEnabled', on(cfg.projectMemoryEnabled) ? '项目记忆' : '项目记忆', on(cfg.projectMemoryEnabled) ? '生效' : '未生效', on(cfg.projectMemoryEnabled) ? '' : '项目记忆关了(只记全局一张卡)')
141
+ push('projectPersonaEnabled', on(cfg.projectPersonaEnabled) ? '项目人格' : '项目人格', on(cfg.projectPersonaEnabled) ? '生效' : '未生效', on(cfg.projectPersonaEnabled) ? '' : '项目人格关了(只吃全局人格)')
142
+ push('includeGlobal', on(cfg.includeGlobal) ? '全局人格' : '全局人格', on(cfg.includeGlobal) ? '生效' : '未生效', on(cfg.includeGlobal) ? '' : '关了 =「纯项目制」,没有项目人格的会话将没有人格')
143
+ push('memoryRecentDiaryIncludePrivate', '最近日记含私密', on(cfg.memoryRecentDiaryIncludePrivate) ? '生效' : '未生效', on(cfg.memoryRecentDiaryIncludePrivate) ? '' : '关了 =「最近」段只带公开日记')
144
+ push('diaryCatchUp', '日记追补', on(cfg.diaryCatchUp) ? '生效' : '未生效', on(cfg.diaryCatchUp) ? '' : '关了 = 错过的日子不往前补')
145
+ push('diaryOverwrite', '日记重写', on(cfg.diaryOverwrite) ? '生效' : '未生效', on(cfg.diaryOverwrite) ? '' : '关了 = 已存在的日记不覆盖')
146
+ push('diaryAgentWrite', '先投给她写', on(cfg.diaryAgentWrite) ? '生效' : '未生效', on(cfg.diaryAgentWrite) ? '' : '关了 = 跳过「让她自己写」,直接兜底生成')
147
+ push('diaryManualNote', '手动触发带备注', on(cfg.diaryManualNote) ? '生效' : '未生效', on(cfg.diaryManualNote) ? '' : '关了 = 手动触发不接受备注')
148
+ push('apiLoopbackOnly', '仅本机访问', cfg.apiLoopbackOnly === false ? '边界' : '边界', cfg.apiLoopbackOnly === false ? '⚠ 已放宽(需启动环境 DSH_SOUL_ALLOW_REMOTE_API=1)——确认是你自己干的' : '设置页接口只允许本机回环')
149
+
150
+ return out
151
+ }
152
+
153
+ /**
154
+ * 一行人话总览(启动 + 每日健康行用)。
155
+ * @returns {string}
156
+ */
157
+ export function reportLine(cfg, extra = {}) {
158
+ const rows = statuses(cfg, extra)
159
+ const mark = (row) => row.status === '未生效' ? '✗' : row.status === '暂无' || row.status === '从未发生' ? '◐' : '✓'
160
+ const okPart = rows.filter((r) => mark(r) === '✓').map((r) => `${r.label}${r.reason !== '' && !r.label.includes('开关') ? `(${r.reason})` : ''}✓`)
161
+ const pendingPart = rows.filter((r) => mark(r) === '◐').map((r) => `${r.label}◐(${r.reason})`)
162
+ const offPart = rows.filter((r) => r.status === '未生效').map((r) => `${r.label}✗(${r.reason})`)
163
+ const parts = []
164
+ if (okPart.length > 0) parts.push(`生效:${okPart.join(' ')}`)
165
+ if (pendingPart.length > 0) parts.push(`暂未发生:${pendingPart.join(' ')}`)
166
+ if (offPart.length > 0) parts.push(`未生效:${offPart.join(' ')}`)
167
+ return `开关证据|${parts.join(' | ')}`
168
+ }
package/lib/health.js CHANGED
@@ -40,6 +40,7 @@ import { normalizeConfig, ownerImportant } from './memory.js'
40
40
  // 现在 health 只依赖不碰 store 的时间/完整性工具,环断掉,依赖图门禁会强制守住。
41
41
  import { diaryIsCompleteFor, todayKey } from './diary/completion.js'
42
42
  import { ingestFailureCount, resetIngestFailureCount } from './extract.js'
43
+ import { reportLine } from './evidence.js'
43
44
 
44
45
  // --------------------------------------------------------------------------
45
46
  // 提炼队列计数(入队 +1、出队 -1)
@@ -219,7 +220,7 @@ export function renderHealthLine({ cwd = '', config = {}, cards = {}, now = Date
219
220
  const writeFailures = safe(() => ingestFailureCount() + cardWriteFailureCount(), null)
220
221
  const refineQueue = safe(() => refinePendingCount(), null)
221
222
 
222
- return '[health] ' + [
223
+ const base = '[health] ' + [
223
224
  memoryBlock,
224
225
  `归档 ${archiveLines === null ? '-' : archiveLines} 条`,
225
226
  `笔记 ${noteCount === null ? '-' : noteCount} 篇`,
@@ -229,6 +230,15 @@ export function renderHealthLine({ cwd = '', config = {}, cards = {}, now = Date
229
230
  `写盘失败 ${writeFailures === null ? '-' : writeFailures}`,
230
231
  `提炼队列 ${refineQueue === null ? '-' : refineQueue}`
231
232
  ].join('|')
233
+
234
+ // 2026-11-10 R18-C:每日健康行带上开关证据(一天一行,噪音纪律同健康行本身)
235
+ const evidenceSuffix = safe(() => {
236
+ const memoryRecords = projectMetric !== null && globalMetric !== null
237
+ ? projectMetric.count + globalMetric.count
238
+ : undefined
239
+ return reportLine(cfg, { memoryRecords, notesCount: noteCount === null ? undefined : noteCount })
240
+ }, '')
241
+ return evidenceSuffix === '' ? base : `${base}|${evidenceSuffix}`
232
242
  }
233
243
 
234
244
  // --------------------------------------------------------------------------