dsh-agent-soul 0.2.0 → 0.4.2

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/lib/paths.js CHANGED
@@ -1,168 +1,196 @@
1
- /**
2
- * paths.js —— 所有文件路径的唯一来源(纯 node: 内置模块)。
3
- *
4
- * 为什么单独一个文件:
5
- * 路径散落在各处时,「全局记忆写哪儿」「项目记忆的 slug 怎么算」这类问题
6
- * 会在插件、测试、设置页三处给出三个答案。集中一处,改规则只改这里。
7
- *
8
- * 目录布局(跟 dsh-agent-md 保持兼容,便于从它平滑迁移):
9
- * <DSH_HOME>/AGENT.md 全局人格(它已经在这写了,直接复用)
10
- * <DSH_HOME>/agents/persona.json 本插件配置
11
- * <DSH_HOME>/agents/projects/<slug>.md 项目人格(与 agent-md 同路径同规则)
12
- * <DSH_HOME>/agents/memory/global.json 全局记忆卡
13
- * <DSH_HOME>/agents/memory/projects/<slug>.json 项目记忆卡
14
- * <DSH_HOME>/agents/memory/archive.jsonl 遗忘档案(append-only)
15
- * <DSH_HOME>/agents/mood/<slug>.json 心情状态(按 cwd 的 slug;无 cwd 用 global)
16
- *
17
- * 为什么人格文件沿用它的路径而不是自己另起一套:
18
- * 他已经写好了 AGENT.md 和项目人格。换插件不该逼他搬家 ——
19
- * 路径一致意味着装上就能用,卸载也不丢东西。
20
- */
21
- import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, copyFileSync } from 'node:fs'
22
- import { homedir } from 'node:os'
23
- import { join, resolve } from 'node:path'
24
-
25
- /** DSH 家目录:跟随 DSH_HOME 环境变量,否则 ~/.dsh(跟 DSH 自己的约定一致)。 */
26
- export function dshHome() {
27
- const fromEnv = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
28
- return fromEnv !== '' ? resolve(fromEnv) : join(homedir(), '.dsh')
29
- }
30
-
31
- export const HOME = () => dshHome()
32
- export const agentsDir = () => join(dshHome(), 'agents')
33
- export const projectsDir = () => join(agentsDir(), 'projects')
34
- export const memoryDir = () => join(agentsDir(), 'memory')
35
- export const memoryProjectsDir = () => join(memoryDir(), 'projects')
36
- export const globalPersonaPath = () => join(dshHome(), 'AGENT.md')
37
- export const globalMemoryPath = () => join(memoryDir(), 'global.json')
38
- export const archivePath = () => join(memoryDir(), 'archive.jsonl')
39
- export const configPath = () => join(agentsDir(), 'persona.json')
40
- export const injectLogPath = () => join(agentsDir(), 'inject-log.jsonl')
41
- export const moodDir = () => join(agentsDir(), 'mood')
42
-
43
- /** 心情状态路径:按 cwd 的 slug(跟人格/记忆同 slug,便于对照排查);无 cwd 用 global。 */
44
- export function moodPath(cwd) {
45
- const key = normalizePathKey(cwd)
46
- if (key === '') return join(moodDir(), 'global.json')
47
- return join(moodDir(), `${slugFor(cwd).slug}.json`)
48
- }
49
-
50
- /** 一次建齐所有目录(幂等)。 */
51
- export function ensureDirs() {
52
- for (const dir of [agentsDir(), projectsDir(), memoryDir(), memoryProjectsDir(), moodDir()]) {
53
- try {
54
- mkdirSync(dir, { recursive: true })
55
- } catch {
56
- /* 并发创建不算错误 */
57
- }
58
- }
59
- }
60
-
61
- /**
62
- * 路径归一:小写 + 正斜杠 + 去尾斜杠 + 去盘符大小写差异。
63
- * 目的只有一个 —— 同一个工作区在 Windows 上写法很多(D:\a\b、D:/a/b、d:\A\B),
64
- * 不归一就会产生好几份「同一个项目」的人格和记忆。
65
- */
66
- export function normalizePathKey(cwd) {
67
- const raw = String(cwd ?? '').trim()
68
- if (raw === '') return ''
69
- return raw.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
70
- }
71
-
72
- /**
73
- * 8 位短哈希 —— **必须和 dsh-agent-md 的 hash8 完全一致(FNV-1a)**。
74
- *
75
- * 2026-10-28 真事故:这里原来用的是 sha1 前 8 位,看着"也能用",但算出来的
76
- * 目录标识跟 dsh-agent-md **对不上**:
77
- *
78
- * D:\DSH workspace\work
79
- * dsh-agent-md (FNV-1a) → work-ea826e02 ← 他的人格文件在这
80
- * 本插件 (sha1) → work-d8a72c47 ← 找一个不存在的文件
81
- *
82
- * 后果不是报错,是**静默认不出来**:设置页显示"项目人格:没有",
83
- * 看起来像人格被弄丢了,其实文件好端端躺在原地;再点一下保存,
84
- * 还会在那个新 slug 下建出一份空人格,从此两份并存、各生效一半。
85
- *
86
- * 哈希算法没有"兼容性"可言 —— 换算法等于换一套命名空间。
87
- * 想改这里的实现,必须同时想清楚已有文件怎么办。
88
- */
89
- export function shortHash(input) {
90
- const text = String(input ?? '')
91
- let h = 0x811c9dc5
92
- for (let i = 0; i < text.length; i += 1) {
93
- h ^= text.charCodeAt(i)
94
- h = Math.imul(h, 0x01000193) >>> 0
95
- }
96
- return h.toString(16).padStart(8, '0')
97
- }
98
-
99
- /**
100
- * cwd → slug。规则与 dsh-agent-md 完全一致(同一目录算出同一个 slug),
101
- * 这样它已经建好的项目人格文件能直接被本插件认领。
102
- */
103
- export function slugFor(cwd) {
104
- const key = normalizePathKey(cwd)
105
- if (key === '') return { key: '', slug: 'global', fileName: 'global.md', personaPath: join(projectsDir(), 'global.md') }
106
- const tail = key.replace(/\/+$/, '').split('/').filter((part) => part !== '').pop() || 'root'
107
- // 只保留 ASCII 字母数字、汉字、连字符、下划线、点;其余一律换成 '-'
108
- const safe = tail.replace(/[^0-9a-zA-Z\u4e00-\u9fa5._-]/g, '-').slice(0, 40) || 'root'
109
- const slug = `${safe}-${shortHash(key)}`
110
- return { key, slug, fileName: `${slug}.md`, personaPath: join(projectsDir(), `${slug}.md`) }
111
- }
112
-
113
- /** 项目记忆卡路径(跟人格同 slug,便于对照排查)。 */
114
- export function projectMemoryPath(cwd) {
115
- return join(memoryProjectsDir(), `${slugFor(cwd).slug}.json`)
116
- }
117
-
118
- /** 显示的目录名(设置页用)。 */
119
- export function displayNameFor(cwd) {
120
- const key = normalizePathKey(cwd)
121
- if (key === '') return '(全局)'
122
- const tail = key.split('/').filter((part) => part !== '').pop() || key
123
- return tail
124
- }
125
-
126
- /**
127
- * 原子写:先写 .tmp 再 rename。
128
- *
129
- * 为什么不能直接 writeFileSync:
130
- * 记忆卡是每回合都可能被写的文件。DSH 被杀进程 / 断电时,
131
- * 半截 JSON 会让下次启动读到坏文件 —— 那一刻丢的是**全部记忆**,不是一条。
132
- * rename 在同一分区上是原子的,最坏情况是丢掉最后一次写入,不会读到半个文件。
133
- */
134
- export function atomicWrite(file, text) {
135
- const tmp = `${file}.tmp-${process.pid}`
136
- writeFileSync(tmp, text, 'utf8')
137
- try {
138
- renameSync(tmp, file)
139
- } catch {
140
- // Windows 上目标被占用时 rename 会失败:退化成系统级拷贝覆盖(cp 不在 JS 堆里
141
- // 走一遍全量缓冲),至少不丢内容;记忆卡可达 MB 级,别再 readFileSync 读进内存。
142
- try {
143
- copyFileSync(tmp, file)
144
- unlinkSync(tmp)
145
- } catch {
146
- /* 都失败了就算了,调用方会在下次写入时再试 */
147
- }
148
- }
149
- }
150
-
151
- /** 读文本文件,不存在或读不了返回空串。 */
152
- export function readText(file) {
153
- try {
154
- if (!existsSync(file)) return ''
155
- return readFileSync(file, 'utf8')
156
- } catch {
157
- return ''
158
- }
159
- }
160
-
161
- /** 是否存在。 */
162
- export function exists(file) {
163
- try {
164
- return existsSync(file)
165
- } catch {
166
- return false
167
- }
168
- }
1
+ /**
2
+ * paths.js —— 所有文件路径的唯一来源(纯 node: 内置模块)。
3
+ *
4
+ * 为什么单独一个文件:
5
+ * 路径散落在各处时,「全局记忆写哪儿」「项目记忆的 slug 怎么算」这类问题
6
+ * 会在插件、测试、设置页三处给出三个答案。集中一处,改规则只改这里。
7
+ *
8
+ * 目录布局(跟 dsh-agent-md 保持兼容,便于从它平滑迁移):
9
+ * <DSH_HOME>/AGENT.md 全局人格(它已经在这写了,直接复用)
10
+ * <DSH_HOME>/agents/persona.json 本插件配置
11
+ * <DSH_HOME>/agents/projects/<slug>.md 项目人格(与 agent-md 同路径同规则)
12
+ * <DSH_HOME>/agents/memory/global.json 全局记忆卡
13
+ * <DSH_HOME>/agents/memory/projects/<slug>.json 项目记忆卡
14
+ * <DSH_HOME>/agents/memory/archive.jsonl 遗忘档案(append-only)
15
+ * <DSH_HOME>/agents/mood/<slug>.json 心情状态(按 cwd 的 slug;无 cwd 用 global)
16
+ *
17
+ * 为什么人格文件沿用它的路径而不是自己另起一套:
18
+ * 他已经写好了 AGENT.md 和项目人格。换插件不该逼他搬家 ——
19
+ * 路径一致意味着装上就能用,卸载也不丢东西。
20
+ */
21
+ import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, copyFileSync } from 'node:fs'
22
+ import { homedir } from 'node:os'
23
+ import { join, resolve } from 'node:path'
24
+
25
+ /** DSH 家目录:跟随 DSH_HOME 环境变量,否则 ~/.dsh(跟 DSH 自己的约定一致)。 */
26
+ export function dshHome() {
27
+ const fromEnv = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
28
+ return fromEnv !== '' ? resolve(fromEnv) : join(homedir(), '.dsh')
29
+ }
30
+
31
+ export const HOME = () => dshHome()
32
+ export const agentsDir = () => join(dshHome(), 'agents')
33
+ export const projectsDir = () => join(agentsDir(), 'projects')
34
+ export const memoryDir = () => join(agentsDir(), 'memory')
35
+ export const memoryProjectsDir = () => join(memoryDir(), 'projects')
36
+ export const globalPersonaPath = () => join(dshHome(), 'AGENT.md')
37
+ export const globalMemoryPath = () => join(memoryDir(), 'global.json')
38
+ export const archivePath = () => join(memoryDir(), 'archive.jsonl')
39
+ export const configPath = () => join(agentsDir(), 'persona.json')
40
+ export const injectLogPath = () => join(agentsDir(), 'inject-log.jsonl')
41
+ export const moodDir = () => join(agentsDir(), 'mood')
42
+
43
+ // ---- 日记目录 ----
44
+ // ~/.dsh/agents/diary/
45
+ // conversations/YYYY-MM-DD.jsonl 每天对话流水(自然日文件名,触发时按 22:00 分界裁剪)
46
+ // public/YYYY-MM-DD.md 公开日记
47
+ // private/YYYY-MM-DD.md 私密日记
48
+ export const diaryDir = () => join(agentsDir(), 'diary')
49
+ export const diaryConversationsDir = () => join(diaryDir(), 'conversations')
50
+ export const diaryPublicDir = () => join(diaryDir(), 'public')
51
+ export const diaryPrivateDir = () => join(diaryDir(), 'private')
52
+ export function diaryJsonlPath(dateKey) {
53
+ return join(diaryConversationsDir(), `${dateKey}.jsonl`)
54
+ }
55
+ export function diaryPublicPath(dateStr) {
56
+ return join(diaryPublicDir(), `${dateStr}.md`)
57
+ }
58
+ export function diaryPrivatePath(dateStr) {
59
+ return join(diaryPrivateDir(), `${dateStr}.md`)
60
+ }
61
+
62
+ /**
63
+ * 心情状态路径(2026-10-31 改:全局唯一,不再按工作区拆)。
64
+ *
65
+ * 原来按 cwd 的 slug 一个工作区一个文件。实测结果是四个互不相识的人:
66
+ * work 99.95、diary 89.16、qq 75.18、default 71
67
+ * 同一个人换个目录心情就换一份 —— 可心情是「这个人现在的状态」,
68
+ * 不是「这个文件夹的状态」。记忆和人格都是跨工作区共享的,唯独心情分裂,
69
+ * 会出现「刚在 A 里说累、切到 B 又满血」这种自相矛盾。
70
+ *
71
+ * 所以改成全局一个文件。cwd 参数保留只为兼容既有调用点,不再参与路径。
72
+ * 旧的分工作区文件保留不动(migrateMoodFiles 会把最完整的那份搬过来)。
73
+ */
74
+ export function moodPath(_cwd) {
75
+ return join(moodDir(), 'global.json')
76
+ }
77
+
78
+ /** 一次建齐所有目录(幂等)。 */
79
+ export function ensureDirs() {
80
+ for (const dir of [agentsDir(), projectsDir(), memoryDir(), memoryProjectsDir(), moodDir(), diaryDir(), diaryConversationsDir(), diaryPublicDir(), diaryPrivateDir()]) {
81
+ try {
82
+ mkdirSync(dir, { recursive: true })
83
+ } catch {
84
+ /* 并发创建不算错误 */
85
+ }
86
+ }
87
+ }
88
+
89
+ /**
90
+ * 路径归一:小写 + 正斜杠 + 去尾斜杠 + 去盘符大小写差异。
91
+ * 目的只有一个 —— 同一个工作区在 Windows 上写法很多(D:\a\b、D:/a/b、d:\A\B),
92
+ * 不归一就会产生好几份「同一个项目」的人格和记忆。
93
+ */
94
+ export function normalizePathKey(cwd) {
95
+ const raw = String(cwd ?? '').trim()
96
+ if (raw === '') return ''
97
+ return raw.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
98
+ }
99
+
100
+ /**
101
+ * 8 位短哈希 —— **必须和 dsh-agent-md 的 hash8 完全一致(FNV-1a)**。
102
+ *
103
+ * 2026-10-28 真事故:这里原来用的是 sha1 前 8 位,看着"也能用",但算出来的
104
+ * 目录标识跟 dsh-agent-md **对不上**:
105
+ *
106
+ * D:\DSH workspace\work
107
+ * dsh-agent-md (FNV-1a) → work-ea826e02 ← 他的人格文件在这
108
+ * 本插件 (sha1) → work-d8a72c47 ← 找一个不存在的文件
109
+ *
110
+ * 后果不是报错,是**静默认不出来**:设置页显示"项目人格:没有",
111
+ * 看起来像人格被弄丢了,其实文件好端端躺在原地;再点一下保存,
112
+ * 还会在那个新 slug 下建出一份空人格,从此两份并存、各生效一半。
113
+ *
114
+ * 哈希算法没有"兼容性"可言 —— 换算法等于换一套命名空间。
115
+ * 想改这里的实现,必须同时想清楚已有文件怎么办。
116
+ */
117
+ export function shortHash(input) {
118
+ const text = String(input ?? '')
119
+ let h = 0x811c9dc5
120
+ for (let i = 0; i < text.length; i += 1) {
121
+ h ^= text.charCodeAt(i)
122
+ h = Math.imul(h, 0x01000193) >>> 0
123
+ }
124
+ return h.toString(16).padStart(8, '0')
125
+ }
126
+
127
+ /**
128
+ * cwd → slug。规则与 dsh-agent-md 完全一致(同一目录算出同一个 slug),
129
+ * 这样它已经建好的项目人格文件能直接被本插件认领。
130
+ */
131
+ export function slugFor(cwd) {
132
+ const key = normalizePathKey(cwd)
133
+ if (key === '') return { key: '', slug: 'global', fileName: 'global.md', personaPath: join(projectsDir(), 'global.md') }
134
+ const tail = key.replace(/\/+$/, '').split('/').filter((part) => part !== '').pop() || 'root'
135
+ // 只保留 ASCII 字母数字、汉字、连字符、下划线、点;其余一律换成 '-'
136
+ const safe = tail.replace(/[^0-9a-zA-Z\u4e00-\u9fa5._-]/g, '-').slice(0, 40) || 'root'
137
+ const slug = `${safe}-${shortHash(key)}`
138
+ return { key, slug, fileName: `${slug}.md`, personaPath: join(projectsDir(), `${slug}.md`) }
139
+ }
140
+
141
+ /** 项目记忆卡路径(跟人格同 slug,便于对照排查)。 */
142
+ export function projectMemoryPath(cwd) {
143
+ return join(memoryProjectsDir(), `${slugFor(cwd).slug}.json`)
144
+ }
145
+
146
+ /** 显示的目录名(设置页用)。 */
147
+ export function displayNameFor(cwd) {
148
+ const key = normalizePathKey(cwd)
149
+ if (key === '') return '(全局)'
150
+ const tail = key.split('/').filter((part) => part !== '').pop() || key
151
+ return tail
152
+ }
153
+
154
+ /**
155
+ * 原子写:先写 .tmp 再 rename。
156
+ *
157
+ * 为什么不能直接 writeFileSync:
158
+ * 记忆卡是每回合都可能被写的文件。DSH 被杀进程 / 断电时,
159
+ * 半截 JSON 会让下次启动读到坏文件 —— 那一刻丢的是**全部记忆**,不是一条。
160
+ * rename 在同一分区上是原子的,最坏情况是丢掉最后一次写入,不会读到半个文件。
161
+ */
162
+ export function atomicWrite(file, text) {
163
+ const tmp = `${file}.tmp-${process.pid}`
164
+ writeFileSync(tmp, text, 'utf8')
165
+ try {
166
+ renameSync(tmp, file)
167
+ } catch {
168
+ // Windows 上目标被占用时 rename 会失败:退化成系统级拷贝覆盖(cp 不在 JS 堆里
169
+ // 走一遍全量缓冲),至少不丢内容;记忆卡可达 MB 级,别再 readFileSync 读进内存。
170
+ try {
171
+ copyFileSync(tmp, file)
172
+ unlinkSync(tmp)
173
+ } catch {
174
+ /* 都失败了就算了,调用方会在下次写入时再试 */
175
+ }
176
+ }
177
+ }
178
+
179
+ /** 读文本文件,不存在或读不了返回空串。 */
180
+ export function readText(file) {
181
+ try {
182
+ if (!existsSync(file)) return ''
183
+ return readFileSync(file, 'utf8')
184
+ } catch {
185
+ return ''
186
+ }
187
+ }
188
+
189
+ /** 是否存在。 */
190
+ export function exists(file) {
191
+ try {
192
+ return existsSync(file)
193
+ } catch {
194
+ return false
195
+ }
196
+ }
package/lib/purpose.js CHANGED
@@ -20,6 +20,8 @@
20
20
  * 一句话:本地的「主动」不是主动发消息,是**主动想起**。
21
21
  */
22
22
 
23
+ import { DIM_FULL } from './mood.js'
24
+
23
25
  export const PURPOSE_VERSION = 1
24
26
 
25
27
  /**
@@ -45,7 +47,9 @@ const HALF_LIFE_HOURS = 8
45
47
 
46
48
  /** 每个维度「什么事会推高它」—— 全是正则,不调模型。 */
47
49
  const NEED_WORDS = {
48
- curiosity: ['为什么', '怎么回事', '原理', '为什么', '是不是', '好奇', '想知', '搞不懂', '奇怪', '疑问', '?', '?'],
50
+ // 注意别把同一个词写两遍:needsFrom 是按「命中几个词」累加的,
51
+ // 重复一次等于给这个维度的权重翻倍('为什么' 曾经重复过)
52
+ curiosity: ['为什么', '怎么回事', '原理', '是不是', '好奇', '想知', '搞不懂', '奇怪', '疑问', '?', '?'],
49
53
  care: ['累', '困', '难受', '不舒服', '压力', '烦', '熬夜', '休息', '注意身体', '吃饭', '睡'],
50
54
  share: ['推荐', '安利', '你看', '给你看', '发现', '有意思', '好玩', '试试', '分享'],
51
55
  mastery: ['学会', '搞懂', '掌握', '搞定', '写完', '做完', '实现', '踩坑', '修好', '通过', '跑通']
@@ -191,6 +195,8 @@ export function createState(now = Date.now()) {
191
195
  drives: { ...BASE_DRIVES },
192
196
  drivesAt: now,
193
197
  goals: [],
198
+ // 本轮渲染出去、等着看她说没说出口的目标(settleServed 的消费对象)
199
+ served: [],
194
200
  updatedAt: new Date(now).toISOString()
195
201
  }
196
202
  }
@@ -210,9 +216,24 @@ export function normalizeState(raw, now = Date.now()) {
210
216
  .map((goal) => normalizeGoal(goal))
211
217
  .filter((goal) => goal !== null)
212
218
  state.updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : state.updatedAt
219
+ state.served = (Array.isArray(raw.served) ? raw.served : [])
220
+ .map(normalizeServed)
221
+ .filter((item) => item !== null)
222
+ .slice(-20)
213
223
  return state
214
224
  }
215
225
 
226
+ function normalizeServed(raw) {
227
+ if (raw === null || typeof raw !== 'object') return null
228
+ const id = String(raw.id ?? '').trim()
229
+ if (id === '') return null
230
+ return {
231
+ id,
232
+ text: String(raw.text ?? '').slice(0, 120),
233
+ at: Number(raw.at) || Date.now()
234
+ }
235
+ }
236
+
216
237
  function normalizeGoal(raw) {
217
238
  if (raw === null || typeof raw !== 'object') return null
218
239
  const text = String(raw.text ?? '').trim()
@@ -308,3 +329,176 @@ export function summarize(state, now = Date.now()) {
308
329
  idleHours: state?.drivesAt > 0 ? Math.round(((now - state.drivesAt) / HOUR) * 10) / 10 : 0
309
330
  }
310
331
  }
332
+
333
+ // --------------------------------------------------------------------------
334
+ // 情绪 → 驱动:七情推着她惦记
335
+ // --------------------------------------------------------------------------
336
+
337
+ /**
338
+ * 七情怎么变成「惦记」。
339
+ *
340
+ * 目的机制原来的驱动只靠两件事:素材刺激(聊到什么词)和久没说话。结果四个维度
341
+ * 常年贴在基线上 —— 因为**情绪才是惦记的真正来源**:担心你才会惦记你有没有加衣服,
342
+ * 开心才更想跟你说点什么。这一层不接,目的机制就只是个空转的衰减器。
343
+ *
344
+ * 权重是「这条情绪有多指向这个需求」,0~1。
345
+ */
346
+ export const EMOTION_AFFINITY = Object.freeze({
347
+ heartache: { care: 1 },
348
+ worry: { care: 0.9 },
349
+ sad: { care: 0.6 },
350
+ jealous: { care: 0.4, share: 0.2 },
351
+ happy: { share: 0.8, care: 0.2 },
352
+ sweet: { share: 0.6, care: 0.4 },
353
+ // 踏实是「已经满足了」—— 反而没那么急着说什么,轻微往下压
354
+ calm: { share: -0.2 }
355
+ })
356
+
357
+ /** 情绪拉满时,驱动最多能偏离基线多少。留够余量,别让担心 = 驱动直接顶到 1。 */
358
+ const EMOTION_SPAN = 0.45
359
+
360
+ /** 由当前七情推出各需求维度的目标值(0~1)。 */
361
+ export function emotionTargets(dims = {}) {
362
+ const out = { ...BASE_DRIVES }
363
+ // 满格口径跟设置页、日记共用同一个常量(mood.js 的 DIM_FULL = 20),
364
+ // 别再各写一份 —— 之前按 100 折算过一次,推出来的偏移不到 0.05,这层等于白接。
365
+ const level = (key) => clamp(Number(dims?.[key]) || 0, 0, DIM_FULL) / DIM_FULL
366
+ for (const need of NEEDS) {
367
+ let strongest = 0
368
+ for (const [emotion, weights] of Object.entries(EMOTION_AFFINITY)) {
369
+ const weight = Number(weights?.[need])
370
+ if (!Number.isFinite(weight) || weight === 0) continue
371
+ const value = level(emotion) * weight
372
+ // 取最强的一条,不是累加:心疼 + 担心 + 难过同时上来也不该把 care 直接顶满
373
+ if (Math.abs(value) > Math.abs(strongest)) strongest = value
374
+ }
375
+ out[need] = clamp(out[need] + strongest * EMOTION_SPAN, 0, 1)
376
+ }
377
+ return out
378
+ }
379
+
380
+ /**
381
+ * 让驱动向「情绪推出的目标」靠拢一步。
382
+ *
383
+ * 为什么不直接加:情绪是**持续状态**不是脉冲,每轮 +x 会在几十轮后把所有驱动顶到 1,
384
+ * 等于没有状态(deriveDrives 里用「地板」而不是累加,是同一个教训)。
385
+ * 按比例靠拢则天然有收敛点:情绪在,驱动停在较高的地方;情绪衰减回去,
386
+ * 目标也回到基线,驱动跟着落下来。
387
+ */
388
+ export function applyEmotionToDrives(drives, dims, { pull = 0.15 } = {}) {
389
+ const base = { ...BASE_DRIVES, ...(drives ?? {}) }
390
+ const target = emotionTargets(dims)
391
+ const step = clamp(Number(pull), 0, 1)
392
+ const out = {}
393
+ for (const need of NEEDS) {
394
+ const cur = clamp(Number(base[need]) || 0, 0, 1)
395
+ out[need] = clamp(cur + (target[need] - cur) * step, 0, 1)
396
+ }
397
+ return out
398
+ }
399
+
400
+ // --------------------------------------------------------------------------
401
+ // 「说出去了才算完」:接上 satisfyDrives
402
+ // --------------------------------------------------------------------------
403
+
404
+ const STRIP_RE = /[\s,。!?、;:""''「」『』()()【】\[\],.!?;:~—…]|_/g
405
+
406
+ /** 取 n 字滑动词组(用于判断两句话有没有真正说到同一件事)。 */
407
+ function grams(text, n) {
408
+ const body = String(text ?? '').replace(STRIP_RE, '')
409
+ const out = []
410
+ for (let i = 0; i + n <= body.length; i += 1) out.push(body.slice(i, i + n))
411
+ return out
412
+ }
413
+
414
+ /**
415
+ * 她回的这句话,有没有真的说到那件惦记的事。
416
+ *
417
+ * 用 3 字词组匹配而不是关键词表:目标文本是自由文本,列不出词表;而 2 字太容易
418
+ * 撞上「今天」「是不是」这类通用词。文本太短(不到 3 字)就退到 2 字,宁可宽松一点。
419
+ */
420
+ export function sharesPhrase(goalText, reply, n = 3) {
421
+ const body = String(reply ?? '')
422
+ if (body.trim() === '') return false
423
+ const size = String(goalText ?? '').replace(STRIP_RE, '').length >= n ? n : 2
424
+ const pieces = grams(goalText, size)
425
+ if (pieces.length === 0) return false
426
+ const flat = body.replace(STRIP_RE, '')
427
+ return pieces.some((piece) => flat.includes(piece))
428
+ }
429
+
430
+ /** 这句话主要指向哪个需求(说出口了,哪个需求才算被满足)。 */
431
+ export function dominantNeed(text, drives = {}) {
432
+ const affinity = needAffinity(text)
433
+ let best = NEEDS[0]
434
+ for (const need of NEEDS) {
435
+ const score = Number(affinity[need]) || 0
436
+ const bestScore = Number(affinity[best]) || 0
437
+ if (score > bestScore || (score === bestScore && Number(drives[need]) > Number(drives[best]))) best = need
438
+ }
439
+ return best
440
+ }
441
+
442
+ /** 记下本轮渲染出去的目标 —— 下一轮才有得可查。 */
443
+ export function markServed(state, goals, now = Date.now()) {
444
+ if (state === null || typeof state !== 'object') return false
445
+ const list = Array.isArray(state.served) ? state.served : []
446
+ let changed = false
447
+ for (const goal of Array.isArray(goals) ? goals : []) {
448
+ const id = String(goal?.id ?? '')
449
+ if (id === '' || list.some((item) => String(item?.id ?? '') === id)) continue
450
+ list.push({ id, text: String(goal?.text ?? '').slice(0, 120), at: now })
451
+ changed = true
452
+ }
453
+ // 上限 20 条:目标一共才 40 条上限,served 不该比它更能堆
454
+ if (list.length > 20) list.splice(0, list.length - 20)
455
+ if (changed) state.served = list
456
+ return changed
457
+ }
458
+
459
+ /**
460
+ * 消化:上一轮渲染出去的目标,她有没有说出口。
461
+ *
462
+ * ── 规则 ──
463
+ * · 不到 minAgeMs 的跳过:刚渲染完还没轮到她说话,这时候判定必然是「没说」
464
+ * · 她的话里说到了 → sent(×0.45,真放下)
465
+ * · 一直没说到,超过 giveUpMs → skipped(×0.85,慢慢淡了)
466
+ * · 两条都只判一次:判完就移出列表 —— 否则每轮都 ×0.85,驱动会被反复压到 0,
467
+ * 跟情绪牵引打架
468
+ *
469
+ * 这是 satisfyDrives 唯一的调用点:那块代码从写下来就没接过(2026-10-30 之前是死代码)。
470
+ */
471
+ export function settleServed(state, { assistantText = '', now = Date.now(), minAgeMs = 60000, giveUpMs = 6 * 3600000 } = {}) {
472
+ const empty = { sent: [], skipped: [] }
473
+ if (state === null || typeof state !== 'object') return empty
474
+ const list = Array.isArray(state.served) ? state.served : []
475
+ if (list.length === 0) return empty
476
+
477
+ const reply = String(assistantText ?? '')
478
+ const kept = []
479
+ const sent = []
480
+ const skipped = []
481
+ for (const item of list) {
482
+ const id = String(item?.id ?? '')
483
+ const age = now - (Number(item?.at) || 0)
484
+ if (id === '' || age < minAgeMs) {
485
+ if (id !== '') kept.push(item)
486
+ continue
487
+ }
488
+ const need = dominantNeed(item?.text ?? '', state.drives)
489
+ if (sharesPhrase(item?.text ?? '', reply)) {
490
+ state.drives = satisfyDrives(state.drives, need, 'sent')
491
+ sent.push(id)
492
+ continue
493
+ }
494
+ if (age < giveUpMs) {
495
+ kept.push(item)
496
+ continue
497
+ }
498
+ state.drives = satisfyDrives(state.drives, need, 'skipped')
499
+ skipped.push(id)
500
+ }
501
+ state.served = kept
502
+ state.updatedAt = new Date(now).toISOString()
503
+ return { sent, skipped }
504
+ }