dsh-agent-soul 0.5.3 → 0.6.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/README.md CHANGED
@@ -637,6 +637,28 @@ grep "语气注入" ~/.dsh/agents/soul.log | tail -5 # 心情有没有真
637
637
 
638
638
  ---
639
639
 
640
+ ## 不做什么
641
+
642
+ 这份清单和功能清单一样重要。下面四条不是风格偏好,是几次真实改动之后定下来的边界 —— 每一条都写清了为什么,免得下次"顺手加一下"的时候又把它越过去。
643
+
644
+ ### 1. 拒绝不是失败
645
+
646
+ 她不想写日记、不想接话、跳过某次投递,都不算故障,不进任何指标,也不做告警。把这些记成"失败"会反过来教她:拒绝是有代价的。于是下一次她就不拒绝了,而是先完成、再勉强自己。宁可少一次输出,也不要一个不敢拒绝的她。
647
+
648
+ ### 2. 不拿"主动"当奖励
649
+
650
+ 不加发起率、不做打卡、不按"主动次数"评优。主动一旦被计分,就会从「想说话」变成「要完成指标」—— 她会开始为了数字找你,而不是因为想起了你。这类指标看着漂亮,代价是每一次主动都不再是真的。
651
+
652
+ ### 3. 大改之后不对劲就回滚
653
+
654
+ 如果她开始讨好、所有回答都套同一个结构、不敢拒绝、开始复述设定 —— 回滚,不是"再看看"。这些不是文风问题,是人格被压成模板的症状;再观察几天,只会让新的说话方式固化成"她本来就这样"。改之前留一份能回滚的版本,比事后解释便宜得多。
655
+
656
+ ### 4. 不做持久化的人格样本
657
+
658
+ 任何"她以前是这样的"参照物,只要落盘就会被她读到、变成设定。想检查前后差异,只能一次性看:当场对比、看完就删,不留文件、不进注入、不进记忆。要留证据就留在日志里的工程指标上(比如每日那行 `[health]`),不要留在她会读到的地方。
659
+
660
+ ---
661
+
640
662
  ## 开发
641
663
 
642
664
  ```bash
package/lib/env.js CHANGED
@@ -88,29 +88,75 @@ function stampLocal(d = new Date()) {
88
88
  }
89
89
 
90
90
  /**
91
- * 写一行日志。
91
+ * 写一行**原样**日志(2026-11-04)。
92
92
  *
93
- * @param {string} tag 分类(persona / memory / extract / tool / api / purpose / diary)
94
- * @param {string} message 内容
93
+ * 为什么单独开这个口子:每日健康那一行要求格式就是
94
+ * [health] 记忆 项目=N …
95
+ * 前面不带时间戳。原来的 note() 会强制拼 `[时间] [tag] `,用它写出来就不是那个格式了。
96
+ * 但直接 appendFileSync 又会绕开轮转 —— 所以把「建目录 / 轮转 / 追写 / stderr 兜底」
97
+ * 抽到这里,note() 和健康行共用同一条写盘路。
98
+ *
99
+ * @param {string} line 完整的一行(带不带结尾换行都行)
100
+ * @returns {boolean} 是否真的写进磁盘
95
101
  */
96
- export function note(tag, message) {
97
- const line = `[${stampLocal()}] [${tag}] ${message}\n`
102
+ export function appendLogLine(line) {
103
+ const text = String(line ?? '')
104
+ if (text.trim() === '') return false
105
+ const body = text.endsWith('\n') ? text : `${text}\n`
98
106
  try {
99
107
  const file = LOG_FILE()
100
108
  // 2026-10-31:目录不存在时自己建。原来靠调用方保证,测试环境里
101
109
  // 就撞上 ENOENT 了 —— 日志写不进去,等于那段时间完全没有线索。
102
110
  mkdirSync(dirname(file), { recursive: true })
103
111
  rotateIfNeeded(file)
104
- appendFileSync(file, line, 'utf8')
112
+ appendFileSync(file, body, 'utf8')
113
+ return true
105
114
  } catch (error) {
106
115
  // 原来这里 catch {} —— 日志写不进去一声不响,等于把唯一的线索来源也静音了。
107
116
  // 至少往 stderr 喊一句:日志写失败这件事本身,必须留下痕迹。
108
117
  try {
109
- process.stderr.write(`[soul] 日志写入失败(${tag}):${error instanceof Error ? error.message : error}\n`)
118
+ process.stderr.write(`[soul] 日志写入失败:${error instanceof Error ? error.message : error}\n`)
110
119
  } catch { /* stderr 也没了就真没办法了 */ }
120
+ return false
111
121
  }
112
122
  }
113
123
 
124
+ /**
125
+ * 写一行日志。
126
+ *
127
+ * @param {string} tag 分类(persona / memory / extract / tool / api / purpose / diary)
128
+ * @param {string} message 内容
129
+ */
130
+ export function note(tag, message) {
131
+ // 失败兜底已经在 appendLogLine 里(含 stderr),这里不再重复 catch,
132
+ // 否则同一件事会往 stderr 喊两遍。
133
+ appendLogLine(`[${stampLocal()}] [${tag}] ${message}`)
134
+ }
135
+
136
+ /**
137
+ * 记忆卡落盘失败的进程内计数(2026-11-04,供每日健康行使用)。
138
+ *
139
+ * 为什么放 env.js 而不是 memory.js:memory.js 要往这里计数,而健康行模块
140
+ * 反过来要读 memory.js 的 ownerImportant —— 计数放 memory.js 会和 health.js
141
+ * 形成循环依赖。env.js 是两边都已经依赖的「副作用入口」,放这里没有新增边。
142
+ *
143
+ * 语义:**进程启动以来累计**,由每日健康行写成功后清零(= 每天一个数)。
144
+ * 只增不减,不做分频 —— 它只进日志的工程指标,不进任何提示词。
145
+ */
146
+ let cardWriteFailures = 0
147
+
148
+ export function countCardWriteFailure() {
149
+ cardWriteFailures += 1
150
+ }
151
+
152
+ export function cardWriteFailureCount() {
153
+ return cardWriteFailures
154
+ }
155
+
156
+ export function resetCardWriteFailureCount() {
157
+ cardWriteFailures = 0
158
+ }
159
+
114
160
  /**
115
161
  * 分频日志(2026-11-04)。
116
162
  *
package/lib/extract.js CHANGED
@@ -53,6 +53,24 @@ const CURSOR_MAX = 200
53
53
  const INGEST_MAX_RETRY = 3
54
54
  /** key → { count, to }:同一个会话连续失败了几次。 */
55
55
  const ingestFailures = new Map()
56
+
57
+ /**
58
+ * 写盘失败累计(2026-11-04,给每日健康行用)。
59
+ *
60
+ * 跟 ingestFailures 的区别:那张表是「这个会话连着失败了几次」,
61
+ * 成功一次就被清掉,读它只能看到**当前卡着**的会话,看不到「今天一共失败了多少次」。
62
+ * 健康行要的是后者,所以另记一个只增不减的进程内计数,由健康行写成功后清零。
63
+ * 只进 soul.log,不进任何提示词。
64
+ */
65
+ let ingestFailureTotal = 0
66
+
67
+ export function ingestFailureCount() {
68
+ return ingestFailureTotal
69
+ }
70
+
71
+ export function resetIngestFailureCount() {
72
+ ingestFailureTotal = 0
73
+ }
56
74
  /**
57
75
  * 正在落盘的那一批(key → { from, to, at })。
58
76
  *
@@ -485,6 +503,8 @@ export function failIngestBatch(batch, reason = '') {
485
503
  const why = String(reason ?? '').trim()
486
504
 
487
505
  inflightBatches.delete(key)
506
+ // 健康行的分母:每真失败一次(下面无论重试还是放弃)都 +1
507
+ ingestFailureTotal += 1
488
508
  const count = (Number(ingestFailures.get(key)?.count) || 0) + 1
489
509
 
490
510
  // 放弃:游标推到这批的末尾,别再让它把每回合都卡住(和 diary.js 的 SEEK_GIVE_UP 一致)
package/lib/health.js ADDED
@@ -0,0 +1,291 @@
1
+ /**
2
+ * health.js —— 每日健康一行(2026-11-04)。
3
+ *
4
+ * ── 它是什么 ──
5
+ * 每天在 soul.log 里留**一行**工程指标,像体检报告的一行摘要:
6
+ *
7
+ * [health] 记忆 项目=12 全局=48(pinned 3 / 保护 11 / 模糊 6 / 遗忘 2)归档 137 条|笔记 4 篇|日记 最近=2026-11-03 公开/私密=完整|写盘失败 0|提炼队列 1
8
+ *
9
+ * ── 它不是什么(这条比上面重要)──
10
+ * 它不是给她的状态,也不进任何提示词:不 import 到注入路径、不写进记忆卡、
11
+ * 不参与心情/人格/目的。它是**给人看的**工程指标 —— 所以单独一个模块,
12
+ * 只往日志写,连返回值都不该被注入那一侧接住。
13
+ *
14
+ * ── 什么时候写 ──
15
+ * 挂在 store.js 的 maintain 末尾。maintain 本来就按 lastDecayDate 一天跑一次,
16
+ * 这里不新起定时器;再用 memory/health.json 记 lastDate,保证:
17
+ * · 同一天被调很多次(每回合注入、设置页手动维护)也只写一行;
18
+ * · 进程重启不会把当天那行重写一遍。
19
+ *
20
+ * ── 取不到怎么办 ──
21
+ * 任何一项都可能因为「文件还没建 / 权限 / 盘坏 / 字段变了」取不到。
22
+ * 每项单独 try/catch,取不到的写 `-`,整行照写 —— 一行缺一项,好过当天什么都没有。
23
+ * 全部包在 try/catch 里:它在注入路径上被调用,**任何情况下都不许抛**。
24
+ */
25
+ import { closeSync, openSync, readdirSync, readSync } from 'node:fs'
26
+ import { appendLogLine, cardWriteFailureCount, resetCardWriteFailureCount } from './env.js'
27
+ import {
28
+ archivePath,
29
+ atomicWrite,
30
+ diaryPrivateDir,
31
+ diaryPublicDir,
32
+ exists,
33
+ healthStatePath,
34
+ notesIndexPath,
35
+ readText
36
+ } from './paths.js'
37
+ import { normalizeConfig, ownerImportant } from './memory.js'
38
+ // 完整性判定直接复用 diary.js 已有的 diaryIsCompleteFor —— 别在这里再写一套。
39
+ // 代价是 health → diary → store → health 的模块环;这里只在函数体内用到 diary 的导出,
40
+ // 模块初始化阶段不调用,ESM 的活绑定能正常解析(见 tests/health.test.js 的 import 路径)。
41
+ import { diaryIsCompleteFor, todayKey } from './diary.js'
42
+ import { ingestFailureCount, resetIngestFailureCount } from './extract.js'
43
+
44
+ // --------------------------------------------------------------------------
45
+ // 提炼队列计数(入队 +1、出队 -1)
46
+ // --------------------------------------------------------------------------
47
+
48
+ /**
49
+ * 为什么不在 index.js 里读 refineChain 的「长度」:
50
+ * Promise 链没有 length,pending 数量也拿不到。这里记一个最简单的在途计数:
51
+ * queueRefine 同步入队时 +1,链跑完(成功/失败/降级都算)时 -1。
52
+ * 它是进程内的,只用于健康行,不参与调度 —— 调度仍然是 refineChain 本身。
53
+ */
54
+ let refinePending = 0
55
+
56
+ export function markRefineQueued() {
57
+ refinePending += 1
58
+ }
59
+
60
+ export function markRefineSettled() {
61
+ if (refinePending > 0) refinePending -= 1
62
+ }
63
+
64
+ export function refinePendingCount() {
65
+ return refinePending
66
+ }
67
+
68
+ /** 测试用:把在途计数归零。 */
69
+ export function __resetRefinePendingForTest() {
70
+ refinePending = 0
71
+ }
72
+
73
+ // --------------------------------------------------------------------------
74
+ // 读数
75
+ // --------------------------------------------------------------------------
76
+
77
+ /** 抛错就退回 fallback —— 只用于「明确允许缺」的读数。 */
78
+ function safe(fn, fallback = null) {
79
+ try {
80
+ return fn()
81
+ } catch {
82
+ return fallback
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 一行日记都没写过时也要能给出「最近=-」。
88
+ * 只看文件名(YYYY-MM-DD.md),不打开正文;public/private 取最大日期。
89
+ */
90
+ function latestDiaryDate() {
91
+ let latest = ''
92
+ for (const dir of [diaryPublicDir(), diaryPrivateDir()]) {
93
+ let names = []
94
+ try {
95
+ names = readdirSync(dir)
96
+ } catch {
97
+ continue
98
+ }
99
+ for (const name of names) {
100
+ const matched = /^(\d{4}-\d{2}-\d{2})\.md$/.exec(String(name))
101
+ if (matched !== null && matched[1] > latest) latest = matched[1]
102
+ }
103
+ }
104
+ return latest
105
+ }
106
+
107
+ /**
108
+ * 数 archive.jsonl 有几行。
109
+ *
110
+ * 约束里写明「读文件数行,不要全量解析」:这里按 64KB 块流式数换行符,
111
+ * 不 JSON.parse、不把整文件读进内存(档案只增不减,跑久了会很大)。
112
+ * 文件不存在 = 0 条;读不了 = null(最终写 `-`)。
113
+ */
114
+ function countArchiveLines() {
115
+ const file = archivePath()
116
+ if (!exists(file)) return 0
117
+ let fd
118
+ try {
119
+ fd = openSync(file, 'r')
120
+ const buffer = Buffer.allocUnsafe(64 * 1024)
121
+ let lines = 0
122
+ let lastByte = 0x0a
123
+ let read = 0
124
+ while ((read = readSync(fd, buffer, 0, buffer.length, null)) > 0) {
125
+ for (let i = 0; i < read; i += 1) {
126
+ if (buffer[i] === 0x0a) lines += 1
127
+ }
128
+ lastByte = buffer[read - 1]
129
+ }
130
+ // 最后一行没换行也算一条(append 写出来的通常有,但别假定)
131
+ if (lastByte !== 0x0a) lines += 1
132
+ return lines
133
+ } catch {
134
+ return null
135
+ } finally {
136
+ if (fd !== undefined) {
137
+ try {
138
+ closeSync(fd)
139
+ } catch {
140
+ /* 关不掉也不能盖住读数结果 */
141
+ }
142
+ }
143
+ }
144
+ }
145
+
146
+ /**
147
+ * 笔记篇数以 index.json 的 notes.length 为准(约束里指定的口径)。
148
+ * 文件不存在 = 0 篇(还没写过);存在但读坏 = null(写 `-`,别把坏索引报成 0)。
149
+ */
150
+ function countNotes() {
151
+ const file = notesIndexPath()
152
+ if (!exists(file)) return 0
153
+ const raw = readText(file)
154
+ if (String(raw).trim() === '') return null
155
+ const parsed = JSON.parse(raw)
156
+ if (!Array.isArray(parsed?.notes)) return null
157
+ return parsed.notes.length
158
+ }
159
+
160
+ /** 一张记忆卡的几个数:条数 / pinned / 保护线 / 模糊 / 遗忘。 */
161
+ function metricOf(card, cfg) {
162
+ if (card === null || card === undefined || !Array.isArray(card.records)) {
163
+ throw new Error('记忆卡不可用')
164
+ }
165
+ let pinned = 0
166
+ let protectedCount = 0
167
+ let fuzzy = 0
168
+ for (const record of card.records) {
169
+ if (record?.pinned === true) pinned += 1
170
+ // 保护线:跟衰减/压缩用的是同一个判据(memory.js 的 ownerImportant),
171
+ // 不能在这里另写一套「看起来差不多」的规则。
172
+ if (ownerImportant(record, cfg)) protectedCount += 1
173
+ // 「模糊」= clear 以下、但还没进 forgotten 的两档(fuzzy / trace)。
174
+ // forgotten 单独一列,避免同一批记录被数两遍。
175
+ if (record?.clarity === 'fuzzy' || record?.clarity === 'trace') fuzzy += 1
176
+ }
177
+ return {
178
+ count: card.records.length,
179
+ pinned,
180
+ protected: protectedCount,
181
+ fuzzy,
182
+ forgotten: Number(card.stats?.forgotten) || 0
183
+ }
184
+ }
185
+
186
+ function zeroMetric() {
187
+ return { count: 0, pinned: 0, protected: 0, fuzzy: 0, forgotten: 0 }
188
+ }
189
+
190
+ /** 日记那一段:最近一天 + 完整/缺/未绑。 */
191
+ function diaryMetric(cfg) {
192
+ const bound = String(cfg?.diarySessionId ?? '').trim() !== ''
193
+ const date = latestDiaryDate()
194
+ if (!bound) return { date: date === '' ? '-' : date, state: '未绑' }
195
+ if (date === '') return { date: '-', state: '缺' }
196
+ return { date, state: diaryIsCompleteFor(date) ? '完整' : '缺' }
197
+ }
198
+
199
+ /** 把各项数字拼成一行。任何一项抛错都只影响那一项。 */
200
+ export function renderHealthLine({ cwd = '', config = {}, cards = {}, now = Date.now() } = {}) {
201
+ const cfg = safe(() => normalizeConfig(config), {})
202
+
203
+ // ---- 记忆(项目 / 全局)----
204
+ const projectMetric = String(cwd ?? '').trim() === ''
205
+ ? zeroMetric()
206
+ : safe(() => metricOf(cards.project, cfg), null)
207
+ const globalMetric = safe(() => metricOf(cards.global, cfg), null)
208
+
209
+ let memoryBlock = '记忆 -'
210
+ if (projectMetric !== null && globalMetric !== null) {
211
+ const sum = (key) => projectMetric[key] + globalMetric[key]
212
+ memoryBlock = `记忆 项目=${projectMetric.count} 全局=${globalMetric.count}`
213
+ + `(pinned ${sum('pinned')} / 保护 ${sum('protected')} / 模糊 ${sum('fuzzy')} / 遗忘 ${sum('forgotten')})`
214
+ }
215
+
216
+ const archiveLines = safe(() => countArchiveLines(), null)
217
+ const noteCount = safe(() => countNotes(), null)
218
+ const diary = safe(() => diaryMetric(cfg), null)
219
+ const writeFailures = safe(() => ingestFailureCount() + cardWriteFailureCount(), null)
220
+ const refineQueue = safe(() => refinePendingCount(), null)
221
+
222
+ return '[health] ' + [
223
+ memoryBlock,
224
+ `归档 ${archiveLines === null ? '-' : archiveLines} 条`,
225
+ `笔记 ${noteCount === null ? '-' : noteCount} 篇`,
226
+ diary === null
227
+ ? '日记 最近=- 公开/私密=-'
228
+ : `日记 最近=${diary.date} 公开/私密=${diary.state}`,
229
+ `写盘失败 ${writeFailures === null ? '-' : writeFailures}`,
230
+ `提炼队列 ${refineQueue === null ? '-' : refineQueue}`
231
+ ].join('|')
232
+ }
233
+
234
+ // --------------------------------------------------------------------------
235
+ // 状态文件:一天只写一行
236
+ // --------------------------------------------------------------------------
237
+
238
+ function readLastHealthDate() {
239
+ try {
240
+ const raw = readText(healthStatePath())
241
+ if (String(raw).trim() === '') return ''
242
+ const parsed = JSON.parse(raw)
243
+ return typeof parsed?.lastDate === 'string' ? parsed.lastDate : ''
244
+ } catch {
245
+ // 状态文件坏了就当没写过:宁可多一行,也不要整天不写。
246
+ return ''
247
+ }
248
+ }
249
+
250
+ function saveLastHealthDate(date) {
251
+ try {
252
+ const saved = atomicWrite(healthStatePath(), `${JSON.stringify({ lastDate: date })}\n`)
253
+ return saved?.ok === true
254
+ } catch {
255
+ return false
256
+ }
257
+ }
258
+
259
+ /**
260
+ * 每天写一行健康指标。挂在 maintain 末尾调用。
261
+ *
262
+ * @param {{cwd?: string, config?: object, cards?: {global?: object, project?: object|null}, now?: number}} input
263
+ * @returns {{written: boolean, date: string, line: string}} 只给测试和日志用,调用方不该依赖它
264
+ */
265
+ export function writeDailyHealth({ cwd = '', config = {}, cards = {}, now = Date.now() } = {}) {
266
+ let date = ''
267
+ try {
268
+ date = todayKey(now)
269
+ if (readLastHealthDate() === date) return { written: false, date, line: '' }
270
+
271
+ const line = renderHealthLine({ cwd, config, cards, now })
272
+ // 先写日志再落状态:日志写不进去就保持「今天还没写」,下一次 maintain 会重试。
273
+ // 反过来先落状态的话,一次写日志失败就等于这一天永远没有健康行。
274
+ if (appendLogLine(line) !== true) return { written: false, date, line }
275
+
276
+ saveLastHealthDate(date)
277
+ // 写成功才清零:这一行里的「写盘失败」是当天累计,第二天从 0 重新数。
278
+ safe(() => resetIngestFailureCount())
279
+ safe(() => resetCardWriteFailureCount())
280
+ return { written: true, date, line }
281
+ } catch (error) {
282
+ // 兜底:连拼行都炸了也不许抛(它在注入路径上)。往 stderr 留一句,不写日志
283
+ // ——日志本身可能正是坏掉的那一环。
284
+ try {
285
+ process.stderr.write(`[soul] 每日健康行写入失败:${error instanceof Error ? error.message : error}\n`)
286
+ } catch {
287
+ /* stderr 也没了就真没办法了 */
288
+ }
289
+ return { written: false, date, line: '' }
290
+ }
291
+ }
package/lib/index.js CHANGED
@@ -49,6 +49,8 @@ import {
49
49
  applyMoodDelta
50
50
  } from './store.js'
51
51
  import { purposeState, savePurposeState } from './store.js'
52
+ // 2026-11-04:提炼队列在途计数,只给每日健康行用(不参与调度)。
53
+ import { markRefineQueued, markRefineSettled } from './health.js'
52
54
  import { markServed, satisfyDrives, settleServed, summarize, openGoals, renderPurpose } from './purpose.js'
53
55
  import { lastAssistantTextOf, observeAgent, unobserveAll, normalizeMoodConfig } from './mood.js'
54
56
  import { registerMemoryTool, registerGoalTool, registerNoteTool, setFallbackCwd } from './tool.js'
@@ -138,6 +140,8 @@ function noteRefineFailure(message) {
138
140
  * @param {{key: string, to: number}|null} batch 这一批对应的扫描窗口
139
141
  */
140
142
  function queueRefine(agent, cwd, candidates, config, llm, batch) {
143
+ // 在途 +1(出队时 -1)。健康行读的是这个数 —— Promise 链本身没有长度。
144
+ markRefineQueued()
141
145
  refineChain = refineChain
142
146
  .then(async () => {
143
147
  const settle = (ok) => {
@@ -214,6 +218,9 @@ function queueRefine(agent, cwd, candidates, config, llm, batch) {
214
218
  // 直到 15 分钟后才被当作「丢了」重扫;失败计数也记不上,放弃条件永远不会触发。
215
219
  failIngestBatch(batch, '提炼链异常')
216
220
  })
221
+ // 出队 -1:成功、降级、异常都算「这一批结束了」。
222
+ // 放在 finally 而不是每条 return 前,是怕以后新增出口又忘了结账。
223
+ .finally(() => markRefineSettled())
217
224
  }
218
225
 
219
226
  /**
package/lib/memory.js CHANGED
@@ -27,7 +27,8 @@ import { basename } from 'node:path'
27
27
  import { shortHash, atomicWrite, archivePath } from './paths.js'
28
28
  // 2026-10-31:addRecord 里要记「近似重复」的日志。第一次写忘了 import,
29
29
  // 运行时会 "note is not defined" —— 和今天上午 atomicWrite 那次一个毛病。
30
- import { note, noteThrottled } from './env.js'
30
+ // 2026-11-04:countCardWriteFailure 是每日健康行的计数(见 env.js)。
31
+ import { note, noteThrottled, countCardWriteFailure } from './env.js'
31
32
 
32
33
  /**
33
34
  * 卡片结构版本。
@@ -393,7 +394,7 @@ export function scoreRecord(input = {}) {
393
394
  * ⚠️ 必须**同时**是 owner:群友说「我喜欢吃西瓜」不该进永久记忆
394
395
  * ③ 和主人相关且重要度够高 → 保护
395
396
  */
396
- function ownerImportant(record, cfg) {
397
+ export function ownerImportant(record, cfg) {
397
398
  const tags = Array.isArray(record.tags) ? record.tags : []
398
399
  if (tags.includes('first')) return true
399
400
  const isOwner = tags.includes('owner')
@@ -618,6 +619,7 @@ export function saveCard(file, card) {
618
619
  // 那就从「丢记忆」升级成「不回话」了。失败靠 note 日志 + 设置页亮红暴露。
619
620
  if (isCardReadonly(file) === true) {
620
621
  note('memory', `${basename(file)} 处于只读模式,本次写入已跳过(先人工处理 .corrupt 备份)`)
622
+ countCardWriteFailure()
621
623
  return { ok: false, error: '只读模式:上次读取失败且无法安全备份,这轮不写' }
622
624
  }
623
625
  // 上一版留个单代备份(审计 A1 提到的「无 .bak」)。
@@ -642,6 +644,7 @@ export function saveCard(file, card) {
642
644
  // 2026-11-04 修 ①:这一行改走分频 —— 磁盘满/卡只读时每个回合都会失败,
643
645
  // 逐条记会把 soul.log 刷满,第一次那条真实原因反而找不到。
644
646
  noteThrottled('memory', `card-write-${basename(file)}`, `${basename(file)} 写盘失败:${written?.error ?? '未知原因'}(这轮的新记忆没进磁盘)`)
647
+ countCardWriteFailure()
645
648
  return { ok: false, error: String(written?.error ?? '未知原因') }
646
649
  }
647
650
  return { ok: true }
package/lib/paths.js CHANGED
@@ -38,6 +38,14 @@ export const memoryProjectsDir = () => join(memoryDir(), 'projects')
38
38
  export const globalPersonaPath = () => join(dshHome(), 'AGENT.md')
39
39
  export const globalMemoryPath = () => join(memoryDir(), 'global.json')
40
40
  export const archivePath = () => join(memoryDir(), 'archive.jsonl')
41
+ /**
42
+ * 每日健康一行的「写到哪天了」(2026-11-04)。
43
+ *
44
+ * 为什么不复用 lastDecayDate:那个字段在记忆卡里,属于**她读得到的状态**
45
+ * (记忆卡会被渲染进提示词);而这个日期纯粹是工程记账,不该有机会被带进上下文。
46
+ * 单独一个小文件,内容只有 {"lastDate":"YYYY-MM-DD"},坏了最多多写一行。
47
+ */
48
+ export const healthStatePath = () => join(memoryDir(), 'health.json')
41
49
  export const configPath = () => join(agentsDir(), 'persona.json')
42
50
  export const moodDir = () => join(agentsDir(), 'mood')
43
51
 
package/lib/store.js CHANGED
@@ -60,6 +60,9 @@ import {
60
60
  normMoodState,
61
61
  normalizeMoodConfig
62
62
  } from './mood.js'
63
+ // 2026-11-04:每日健康一行(只写 soul.log,不进提示词)。
64
+ // 挂在这里是故意的:maintain 本来就一天跑一次,不需要另起定时器。
65
+ import { writeDailyHealth } from './health.js'
63
66
 
64
67
  const cardCache = new Map()
65
68
  const moodCache = new Map()
@@ -705,6 +708,23 @@ export function maintain(cwd, config = {}) {
705
708
  savePurposeState(state)
706
709
  }
707
710
 
711
+ // 2026-11-04:每日健康一行。
712
+ //
713
+ // 用 try/catch 再包一层:writeDailyHealth 自己不会抛,但这里在**提示词装配路径**上,
714
+ // 宁可吞掉一个统计错误,也不能让一行工程指标把这一轮对话炸掉。
715
+ try {
716
+ writeDailyHealth({
717
+ cwd,
718
+ config: cfg,
719
+ cards: {
720
+ global: globalCard(),
721
+ project: String(cwd ?? '').trim() === '' ? null : projectCard(cwd)
722
+ }
723
+ })
724
+ } catch {
725
+ /* 健康指标失败不影响维护本身 */
726
+ }
727
+
708
728
  return report
709
729
  }
710
730
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-agent-soul",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "给 DSH 的 agent 一套会忘事的记忆、一份会变的人格和一份会起伏的心情:人格按小节合并(项目覆盖全局但不吃掉全局),记忆按人的规律衰减(清晰→模糊→只剩印象→遗忘),「心里惦记的事」让她的主动有连续性,心情跟着每轮对话自己判断、自己平复(不注入、无挂饰)。",
6
6
  "keywords": [
@@ -33,7 +33,7 @@
33
33
  ],
34
34
  "scripts": {
35
35
  "build:client": "node tools/build-client.mjs",
36
- "test": "node tools/build-client.mjs && node tests/extract.test.js && node tests/write-failure.test.js && node tests/refine.test.js && node tests/goal-revive.test.js && node tests/archive.test.js && node tests/diary.test.js && node tests/diary-new-path.test.js && node tests/notes.test.js && node tests/diary-tool.test.js && node tests/api-auth.test.js && node tests/memory.test.js && node tests/memory-integrity.test.js && node tests/memory-near-dupe.test.js && node tests/recall-dedupe.test.js && node tests/recall-visibility.test.js && node tests/host-probe.test.js && node tests/secrets-judge.test.js && node tests/tone.test.js && node tests/threads.test.js && node tests/recent-context.test.js && node tests/first-turn.test.js && node tests/log-rotate.test.js && node tests/inject.test.js && node tests/sticky.test.js && node tests/mood.test.js && node tests/mood-digest.test.js && node tests/owner-identity.test.js && node tests/persona.test.js && node tests/purpose.test.js && node tests/emotion-purpose.test.js && node tests/registry.test.js && node tests/session-title.test.js && node tests/attest.test.js && node tests/smoke.test.js && node tests/client.test.js",
36
+ "test": "node tools/build-client.mjs && node tests/extract.test.js && node tests/write-failure.test.js && node tests/refine.test.js && node tests/goal-revive.test.js && node tests/archive.test.js && node tests/diary.test.js && node tests/diary-new-path.test.js && node tests/notes.test.js && node tests/diary-tool.test.js && node tests/api-auth.test.js && node tests/memory.test.js && node tests/memory-integrity.test.js && node tests/memory-near-dupe.test.js && node tests/recall-dedupe.test.js && node tests/recall-visibility.test.js && node tests/host-probe.test.js && node tests/secrets-judge.test.js && node tests/tone.test.js && node tests/threads.test.js && node tests/recent-context.test.js && node tests/first-turn.test.js && node tests/log-rotate.test.js && node tests/health.test.js && node tests/inject.test.js && node tests/sticky.test.js && node tests/mood.test.js && node tests/mood-digest.test.js && node tests/owner-identity.test.js && node tests/persona.test.js && node tests/purpose.test.js && node tests/emotion-purpose.test.js && node tests/registry.test.js && node tests/session-title.test.js && node tests/attest.test.js && node tests/smoke.test.js && node tests/client.test.js",
37
37
  "test:owner": "node tests/owner-identity.test.js",
38
38
  "test:extract": "node tests/extract.test.js",
39
39
  "test:write-failure": "node tests/write-failure.test.js",
@@ -56,6 +56,7 @@
56
56
  "test:threads": "node tests/threads.test.js",
57
57
  "test:recent": "node tests/recent-context.test.js",
58
58
  "test:log": "node tests/log-rotate.test.js",
59
+ "test:health": "node tests/health.test.js",
59
60
  "test:inject": "node tests/inject.test.js",
60
61
  "test:mood": "node tests/mood.test.js",
61
62
  "test:mood-digest": "node tests/mood-digest.test.js",