whale-emotion-intake 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 whale-memory contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
- # Temporary Holding Version
1
+ # whale-emotion-intake
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把一句对话拆成"情绪候选"的小模块:分句判断是谁的感受、证据与感受分账、每回合限额。
4
+
5
+ ## 装
6
+
7
+ ```sh
8
+ npm i whale-emotion-intake
9
+ ```
10
+
11
+ ## 它解决什么
12
+
13
+ 角色说"好听""房间有点闷""有点冲"时,这些是**评价**,不一定是**她感到**(评价的对象是房间/声音/菜)。
14
+ 只有"我觉得心里闷""我有点难过"这类第一人称体验才是她的感受。
15
+ 如果不分开,夸两句心情就飘,说两句难听就沉——情绪通胀。
16
+
17
+ 这个模块只做三件事:
18
+
19
+ 1. 分句;
20
+ 2. 判断每个分句的体验者是不是"她自己";
21
+ 3. 给出候选(证据 / 可写入的维度),以及每回合的写入门槛。
22
+
23
+ 它**不碰**存储、不碰模型、不发网络请求。
24
+
25
+ ## 跑一下
26
+
27
+ ```sh
28
+ npm i whale-emotion-intake
29
+ node node_modules/whale-emotion-intake/example.mjs
30
+ ```
31
+
32
+ 在仓库里则用:
33
+
34
+ ```sh
35
+ node packages/emotion-intake/example.mjs
36
+ ```
37
+
38
+ ## 用法
39
+
40
+ ```js
41
+ import { scoreTurn } from 'whale-emotion-intake'
42
+
43
+ const r = scoreTurn({
44
+ otherText: '我有点难过',
45
+ selfText: '我也有点闷',
46
+ prevAskedSelf: false
47
+ })
48
+
49
+ r.selfEvidence // ['闷']:她的表达证据
50
+ r.otherEvidence // ['难过']:对方的表达证据
51
+ r.write // { dim: 'v', value: -0.15, source: 'self_felt' } 或 null
52
+ r.moment // 是否够"值得记住的一刻"
53
+ r.sources // ['other_evidence', 'self_felt']
54
+ ```
55
+
56
+ ## 规则摘要
57
+
58
+ | 分句 | 处理 |
59
+ | --- | --- |
60
+ | 第一人称 + 体感/情绪词 | 进维度(strong) |
61
+ | 省略主语,且上一句在问她感受 | 进维度(weak) |
62
+ | 第二/三人称、听说、假设、否定、疑问 | 只进证据 |
63
+ | 评价/偏好(好听/好看/冲/快) | 只进证据 |
64
+
65
+ - 权重:他直接喜欢/不喜欢 0.10;他一般情绪词 0;她第一人称 0.15
66
+ - 每回合最多写一次,Δ≤0.15;跨来源冷却 2 回合(任何来源写入后都要等 2 回合)、3 回合≤2、每天≤6
67
+ - moment:≥2 个独立源,且至少一个是强源(`self_felt` / `other_direct` / `other_evidence`);`self_weak` + `contagion` 这组弱源组合也算够(与 `scoreTurn` 的判定一致)
68
+
69
+ ## 边界
70
+
71
+ - 词表是手写的,方言、反讽、新词会漏;
72
+ - 它只给"候选",是否写入、怎么写由宿主决定;
73
+ - 不含任何真实对话数据,测试全部是合成样本。
74
+ ## 返回契约
75
+
76
+ `write` 与 `moment` 都只是**候选**:是否写入、是否记下由宿主决定,模块本身不碰存储。
77
+ `source: 'self_felt'` 表示“候选来源是她第一人称的自感句”,不是模型真的感觉到了什么。
78
+
79
+ `scoreTurn()` 返回:
80
+
81
+ | 字段 | 类型 | 空值条件 |
82
+ | --- | --- | --- |
83
+ | `otherEvidence` | `string[]` | 该侧没有命中任何情绪/评价词时 `[]` |
84
+ | `selfEvidence` | `string[]` | 同上 |
85
+ | `transferEvidence` | `string[]` | 没有转述/引用时 `[]` |
86
+ | `write` | `{ dim:'v'|'a', value:number, source:string, a?:number }` | 没有可写候选时 `null` |
87
+ | `sources` | `string[]`(独立来源,用于 moment 判定) | 没有来源时 `[]` |
88
+ | `moment` | `boolean` | 不够 moment 时 `false` |
89
+
90
+ **注意**:证据与 `write` 相互独立。「房间有点闷」会得到 `write: null`,但 `otherEvidence: ['闷']`——宿主不要在 `write` 为空时丢弃证据。
91
+
92
+ **证据 vs 可写维度**:证据是"这句话里出现过情绪/评价词"的记录,**不会直接改情绪**,但可以作为 moment 的独立来源参与判定;`write` 才是允许改情绪的量,且每回合最多一次。
93
+
94
+ `allowWrite(state, opts)` 只读,不修改 `state`;省略 `now` 会读系统时钟,跨上海时区午夜可能得到不同的“当天”,生产建议显式传入。
95
+ `recordWrite(state, opts)` **不修改**入参,返回一个新的 state(`intakeLog` 追加一条并裁剪到 100 条);是否采用由调用方决定。`now` 必须由调用方传入;非法 state、缺 `now`、缺 `dim/value/source` 的候选均返回 `null`(不占配额)。
96
+
97
+ ## 依赖边界
98
+
99
+ - 无 `fs` / `net` / `child_process` / 定时器;
100
+ - 不读环境变量、不写全局状态;
101
+ - 纯函数:`scoreTurn` / `classifyClause` / `featureFlags` 等;`allowWrite` 只读,但省略 `now` 时会读系统时钟;
102
+ - `recordWrite` 返回**新状态**,不修改入参;
103
+ - `mergeMomentWindow` / `recordMoment` 是状态机,**会原地更新**传入的 `state`(窗口与每日记录),调用方需自备状态容器。
104
+
105
+ ## 稳定性
106
+
107
+ 版本 `0.1.x`,接口**不保证稳定**;升级可能改名或调整返回结构,届时在 CHANGELOG 注明。
108
+
109
+ ## 已知局限(首版保留)
110
+
111
+ 这是词表 + 规则的启发式模块,不做句法分析。下面几类会误判,已在测试里固定为“当前行为”,用前请知道:
112
+
113
+ - 条件句只按分句判断:「如果下雨,我会很难过」的后半句会被当作她当前的自感;
114
+ - 名词里的「的话」与条件词可能混淆(已排除「你的话」,其他名词未穷举);
115
+ - 「让我」只看是否直接支配感受词,复杂句式可能漏判;
116
+ - 评价对象词表有限,新名词(新作品、新物件)可能被当成她的体感;
117
+ - 否定、反讽、方言、新词都可能漏。
118
+
119
+ 它的定位是“候选”,不是判定器;宿主应保留采纳/拒绝的余地。
120
+ - 同伴/听者人称会误拦第一人称:「和你在一起我很开心」「我告诉她我喜欢你」当前不会产生候选(首版保留)。
121
+ - 条件「…的话」与名词「你的话」在「喜欢你的话」这类句子里会被当成名词,条件句漏判;
122
+ - 说话者在 \`otherText\` 里带同伴/听者代词(「我告诉她我喜欢你」)时,直接偏好会被误拦;\`otherText\` 里单独的「我喜欢你」仍正常。
package/example.mjs ADDED
@@ -0,0 +1,16 @@
1
+ // 十行示例:一句话进来,候选出去;写不写由宿主决定。
2
+ import { scoreTurn, recordWrite } from './index.js'
3
+
4
+ const r = scoreTurn({ otherText: '我有点累', selfText: '我也有点闷' })
5
+
6
+ console.log('证据(她):', r.selfEvidence) // ['闷']
7
+ console.log('候选(需宿主决定是否写):', r.write) // { dim:'v', value:-0.15, source:'self_felt', ... }
8
+ console.log('时刻候选(需宿主决定是否记):', r.moment) // true
9
+
10
+ if (r.write) {
11
+ const next = recordWrite({ intakeLog: [] }, { now: Date.now(), write: r.write })
12
+ console.log('写入后日志条数:', next.intakeLog.length) // 1
13
+ }
14
+
15
+ // 给自动化测试看的机器可读结果
16
+ console.log(JSON.stringify({ self: r.selfEvidence, write: r.write, moment: r.moment }))
package/index.js ADDED
@@ -0,0 +1,331 @@
1
+ // 情绪采集:分句体验者判定、证据与感受分账(公开模块)
2
+ //
3
+ // 分账:
4
+ // - 他直接喜欢/不喜欢 → C 0.10(唯一例外:即使带"不"也按极性算)
5
+ // - 他一般情绪词 → C 0(只进证据,是 moment 的"强证据源")
6
+ // - 她第一人称/让我+感受/躯体 → C 0.15(强情绪源)
7
+ // - 她无对象+程度+上轮问感受 → C 0.15(弱锚定);其余评价只进证据
8
+ // - 语气/长度/速度 → 永不单独产生 C
9
+ // 合并:每回合最多写一次,Δ≤0.15;同源冷却 2 回合;每 3 回合≤2 次;每天≤6 次。
10
+ // moment:≥2 个独立有效源且至少 1 个强源(强情绪或强证据);语气不计源;日≤3。
11
+
12
+ export const C_HIS_DIRECT = 0.10
13
+ export const C_HER_FELT = 0.15
14
+ export const C_CONTAGION = 0.10
15
+ export const TURN_CAP = 0.15
16
+ export const COOLDOWN_TURNS = 2
17
+ export const DAY_CAP = 6
18
+ export const MOMENT_DAY_CAP = 3
19
+
20
+ // 来源名归一化:旧名 → 新名;只统计认可来源,未知标签不计
21
+ const SOURCE_ALIAS = { her_felt: 'self_felt', his_direct: 'other_direct', his_evidence: 'other_evidence', her_weak: 'self_weak' }
22
+ const ALLOWED_SOURCES = new Set(['self_felt', 'other_direct', 'other_evidence', 'self_weak', 'contagion'])
23
+ const ALWAYS_STRONG = new Set(['self_felt', 'other_direct', 'other_evidence'])
24
+ function normalizeSources(sources) {
25
+ return [...new Set((Array.isArray(sources) ? sources : []).map((s) => SOURCE_ALIAS[s] || s).filter((s) => ALLOWED_SOURCES.has(s)))]
26
+ }
27
+ function isStrong(sources) {
28
+ if (sources.some((s) => ALWAYS_STRONG.has(s))) return true
29
+ // 弱源例外:必须 self_weak 与 contagion 成对,单个弱源不算
30
+ return sources.includes('self_weak') && sources.includes('contagion')
31
+ }
32
+
33
+ const FELT = ['烦', '闷', '累', '疼', '怕', '慌', '难受', '委屈', '堵', '酸', '丧', '难过', '低落', '焦虑', '孤单', '生气', '冲', '开心', '高兴', '松', '暖', '舒服', '轻松', '踏实', '爽', '安', '喜']
34
+ const FELT_POS = new Set(['开心', '高兴', '松', '暖', '舒服', '轻松', '踏实', '爽', '安', '喜'])
35
+ const FELT_RE = FELT.join('|')
36
+ const EVAL = ['好听', '好看', '不错', '喜欢', '可爱', '帅', '美', '棒', '行', '可以', '难听', '难看', '不行', '讨厌', '丑', '差', '冲', '快']
37
+ const DIRECT_POS = ['我喜欢你', '爱你', '想你', '喜欢你', '我喜欢这个']
38
+ const DIRECT_NEG = ['我讨厌你', '烦你', '不想理你', '不喜欢你', '我不喜欢这个', '不爱你', '不爱你了']
39
+ export const LEXICON_WORDS = [...new Set([...DIRECT_POS, ...DIRECT_NEG, ...FELT, ...EVAL])]
40
+
41
+ const FIRST_PERSON = /我|咱/
42
+ const HEARSAY = /(他说|她说|听说|据说|别人说|好像说)/
43
+ const QUESTION = /[??]\s*$|(吗|呢)\s*[。.!!]?\s*$|怎么样/
44
+ const NEGATION = /(不|没|别|勿)\s*\S{0,2}$/
45
+ const PREV_ASK_SELF = /(你|你自己).{0,8}(烦|闷|累|怕|难受|开心|高兴|舒服|感觉|觉得|感受)/
46
+
47
+ export function askedSelf(text) {
48
+ return PREV_ASK_SELF.test(String(text || ''))
49
+ }
50
+
51
+ /** 受限句法标记:只出布尔/粗桶,不保留原句。 */
52
+ export function wordsInText(text) {
53
+ const s = String(text || '')
54
+ return [...new Set([...hits(s, DIRECT_POS), ...hits(s, DIRECT_NEG), ...hits(s, FELT), ...hits(s, EVAL)])]
55
+ }
56
+
57
+ export function featureFlags(text) {
58
+ const s = String(text || '')
59
+ return {
60
+ first_person: FIRST_PERSON.test(s) ? 1 : 0,
61
+ degree: /(有点|有些|挺|很|太|特别|好)/.test(s) ? 'mild' : 'none',
62
+ negation: NEGATION.test(s.replace(/[,,。!!??;;]/g, '')) ? 1 : 0,
63
+ question: QUESTION.test(s) ? 1 : 0,
64
+ rhetorical: /(难道|怎么可能|你说呢|呵呵)/.test(s) ? 1 : 0,
65
+ reported: HEARSAY.test(s) ? 1 : 0,
66
+ punct_bucket: /[!!]{2,}/.test(s) ? 'excl' : /[??]/.test(s) ? 'q' : /(…{2,}|\.{3,})/.test(s) ? 'ellipsis' : 'plain'
67
+ }
68
+ }
69
+
70
+ /** 词 → 7 类粗语义;不细分原词。 */
71
+ export function categoryOf(word) {
72
+ const w = String(word || '')
73
+ if (DIRECT_POS.includes(w)) return 'direct_like'
74
+ if (DIRECT_NEG.includes(w)) return 'direct_dislike'
75
+ if (FELT.filter((x) => !FELT_POS.has(x)).includes(w)) return 'body_neg'
76
+ if (FELT_POS.has(w)) return 'body_pos'
77
+ if (EVAL.includes(w) && ['难听', '难看', '不行', '讨厌', '丑', '差'].includes(w)) return 'eval_neg'
78
+ if (EVAL.includes(w)) return 'eval_pos'
79
+ return 'neutral'
80
+ }
81
+
82
+ const splitClauses = (text) => {
83
+ const parts = String(text || '').split(/([,,。!!??;;\n])/)
84
+ const out = []
85
+ for (let i = 0; i < parts.length; i += 2) {
86
+ const s = (parts[i] + (parts[i + 1] || '')).trim()
87
+ if (s) out.push(s)
88
+ }
89
+ return out
90
+ }
91
+
92
+ const hits = (c, list) => list.filter((w) => c.includes(w))
93
+
94
+ /**
95
+ * 语气因子:0.5–1.0,只乘已放行的强信号,绝不单独产生 C。
96
+ * 夸张标点/笑声/省略号会被视为表演性语气,压低权重。
97
+ */
98
+ export function toneFactor(clause) {
99
+ const c = String(clause || '')
100
+ let f = 1
101
+ if (/[!!]{2,}/.test(c)) f -= 0.2
102
+ if (/(哈{2,}|笑死|狗头|doge)/i.test(c)) f -= 0.2
103
+ if (/(…{2,}|\.{3,})/.test(c)) f -= 0.1
104
+ return Math.max(0.5, Math.min(1, f))
105
+ }
106
+
107
+ /** 单句判定:返回 { evidence: [{word,strong}], cue }。cue = 可写入的维度。 */
108
+ export function classifyClause(clause, { speaker = 'other', prevAskedSelf = false } = {}) {
109
+ const c = String(clause || '').trim()
110
+ if (!c) return { evidence: [], cue: null }
111
+ const firstPerson = FIRST_PERSON.test(c)
112
+ const hearsay = HEARSAY.test(c)
113
+ const question = QUESTION.test(c)
114
+ const negated = NEGATION.test(c.replace(/[,,。!!??;;]/g, ''))
115
+ const directPos = hits(c, DIRECT_POS)
116
+ const directNeg = hits(c, DIRECT_NEG)
117
+ const felt = hits(c, FELT)
118
+ const evalWords = hits(c, EVAL)
119
+
120
+ // 转述/引用/疑问/否定:不归她,也不产生 C;转述保留证据(记的是"他说的")
121
+ if (hearsay) return { evidence: [], transfer: felt.map((w) => ({ word: w })), cue: null, reason: 'hearsay' }
122
+ if (question) return { evidence: [], cue: null, reason: 'question' }
123
+
124
+ // 「她不爱你了」「如果我不爱你」不是在陈述说话者自己的偏好
125
+ const thirdSubject = new RegExp(`(他|她|他们|她们|别人)[^,。!?]{0,6}(${FELT_RE}|${DIRECT_POS.join('|')}|${DIRECT_NEG.join('|')})`).test(c)
126
+ const hypotheticalEarly = /(如果|要是|假如|万一)/.test(c.replace(/主要是/g, ''))
127
+ || (/的话/.test(c) && !/你的话/.test(c))
128
+
129
+ // 他:直接喜欢/不喜欢是唯一进 C 的例外(否定短语包含肯定子串,先判否定)
130
+ if (speaker === 'other' && !thirdSubject && !hypotheticalEarly && (directPos.length || directNeg.length)) {
131
+ const sign = directNeg.length || negated ? -1 : 1
132
+ const words = directNeg.length ? directNeg : directPos
133
+ return {
134
+ evidence: words.map((w) => ({ word: w, strong: true })),
135
+ cue: { source: 'other_direct', dim: 'v', value: sign * C_HIS_DIRECT, strong: true },
136
+ reason: 'direct'
137
+ }
138
+ }
139
+
140
+ if (negated) return { evidence: [], cue: null, reason: 'negated' }
141
+
142
+ // 他:一般情绪词只进证据(强证据源)
143
+ if (speaker === 'other') {
144
+ return { evidence: felt.map((w) => ({ word: w, strong: true })), cue: null, reason: 'his-evidence' }
145
+ }
146
+
147
+ // 她:第一人称 / "让我" + 感受/躯体 → 强情绪
148
+ // 但「我觉得房间有点闷」是在评价对象,不是她的体感
149
+ const OBJECT = /(房间|屋子|天气|这个|那个|它|歌|视频|声音|音色|电影|剧|书|饭|菜|作业|题)/
150
+ const feltIdx = felt.length ? Math.min(...felt.map((w) => c.indexOf(w)).filter((i) => i >= 0)) : -1
151
+ const objIdx = c.search(OBJECT)
152
+ // 「让我」要直接支配感受词(中间只允许程度副词);「让我看看房间有多闷」不算
153
+ const letCause = new RegExp(`让我\\s*(很|有点|有些|挺|太|特别|好|真)?\\s*(${FELT_RE})`).test(c)
154
+ const aboutObject = objIdx >= 0 && feltIdx >= 0 && objIdx < feltIdx && !letCause
155
+ // 第三人称/第二人称、假设句里的感受不归她
156
+ const thirdPerson = new RegExp(`(他|她|他们|她们|别人)\\s*[^,。!?]{0,6}?(${FELT_RE})`).test(c)
157
+ const secondPerson = new RegExp(`你[^,。!?]{0,6}?(${FELT_RE})`).test(c)
158
+ const hypothetical = /(如果|要是|假如|万一)/.test(c.replace(/主要是/g, ''))
159
+ || (/的话/.test(c) && !/你的话/.test(c))
160
+ const selfFelt = (firstPerson || letCause) && felt.length && !aboutObject && !(thirdPerson && !letCause) && !(secondPerson && !letCause) && !hypothetical
161
+ if (selfFelt) {
162
+ const pos = felt.some((w) => FELT_POS.has(w))
163
+ const neg = felt.some((w) => !FELT_POS.has(w))
164
+ const sign = pos && !neg ? 1 : neg && !pos ? -1 : 0
165
+ return {
166
+ evidence: felt.map((w) => ({ word: w, strong: true })),
167
+ cue: sign ? { source: 'self_felt', dim: 'v', value: sign * C_HER_FELT, strong: true, a: sign < 0 ? 1 : 0 } : null,
168
+ reason: 'self-felt'
169
+ }
170
+ }
171
+
172
+ // 她:无对象 + 程度 + 上轮在问自己感受 → 弱锚定(问音色则不算)
173
+ const degree = /(有点|有些|挺|很|太|特别|好)/.test(c)
174
+ const noObject = !OBJECT.test(c) && !/(他|她|你)/.test(c)
175
+ if (prevAskedSelf && degree && noObject && felt.length && !thirdPerson && !hypothetical) {
176
+ const pos = felt.some((w) => FELT_POS.has(w))
177
+ const neg = felt.some((w) => !FELT_POS.has(w))
178
+ const sign = pos && !neg ? 1 : neg && !pos ? -1 : 0
179
+ return {
180
+ evidence: felt.map((w) => ({ word: w, strong: true })),
181
+ cue: sign ? { source: 'self_weak', dim: 'v', value: sign * 0.15, strong: false } : null,
182
+ reason: 'weak-anchor'
183
+ }
184
+ }
185
+
186
+ // 其余(评价/偏好/无自感)只进证据
187
+ return {
188
+ evidence: [...felt, ...evalWords].map((w) => ({ word: w, strong: felt.includes(w) })),
189
+ cue: null,
190
+ reason: evalWords.length ? 'evaluation' : 'evidence'
191
+ }
192
+ }
193
+
194
+ /** 整段(他 + 她)评估:证据分账、C 合并、moment 判定。 */
195
+ export function scoreTurn({ otherText = '', selfText = '', prevAskedSelf = false, contagion = null, tone = true } = {}) {
196
+ const hisClauses = splitClauses(otherText).map((s) => classifyClause(s, { speaker: 'other' }))
197
+ const herClauses = splitClauses(selfText).map((s) => classifyClause(s, { speaker: 'self', prevAskedSelf }))
198
+ const otherEvidence = [...new Set(hisClauses.flatMap((r) => r.evidence.map((e) => e.word)))]
199
+ const transferEvidence = [...new Set([...hisClauses, ...herClauses].flatMap((r) => (r.transfer || []).map((e) => e.word)))]
200
+ // 疑问/反问里的裸感受词是"回声",不记成她的证据(S16「难过?呵呵」)
201
+ const echo = /[??]/.test(String(selfText || ''))
202
+ const selfEvidence = [...new Set(herClauses.flatMap((r, i) => {
203
+ const raw = splitClauses(selfText)[i] || ''
204
+ if (echo && /^(烦|闷|累|疼|怕|慌|难受|委屈|堵|酸|丧|难过|低落|焦虑|孤单|生气|开心|高兴|松|暖|舒服|轻松|踏实|爽|安|喜)$/.test(raw)) return []
205
+ return r.evidence.map((e) => e.word)
206
+ }))]
207
+ const cues = [...hisClauses, ...herClauses].map((r) => r.cue).filter(Boolean)
208
+ // 情绪传染:只有她本轮没有强自感时才作为独立源进 C(0.10)
209
+ const herFeltCue = cues.some((c) => c.source === 'self_felt')
210
+ const contagionCue = herFeltCue ? null : contagionCueOf(contagion)
211
+ if (contagionCue) cues.push(contagionCue)
212
+
213
+ // 每回合只写一次:取 |value| 最大的 cue
214
+ cues.sort((a, b) => Math.abs(b.value) - Math.abs(a.value))
215
+ let write = null
216
+ if (cues.length) {
217
+ const top = cues[0]
218
+ // 分句会吃掉标点,所以整体语气在这里再乘一次(只抑制,不产生新信号)
219
+ const tf = tone ? Math.min(toneFactor(otherText), toneFactor(selfText)) : 1
220
+ write = { dim: top.dim, value: Math.sign(top.value) * Math.min(TURN_CAP, Math.abs(top.value) * tf), source: top.source, a: top.a ? 1 : 0 }
221
+ }
222
+
223
+ const strongEmotion = cues.some((c) => c.source === 'self_felt' || c.source === 'other_direct')
224
+ const strongEvidence = hisClauses.some((r) => r.reason === 'his-evidence' && r.evidence.length)
225
+ const generalHisEvidence = hisClauses.some((r) => r.reason === 'his-evidence' && r.evidence.length)
226
+ const weakAnchor = cues.some((c) => c.source === 'self_weak')
227
+ const sources = new Set()
228
+ if (cues.some((c) => c.source === 'other_direct')) sources.add('other_direct')
229
+ if (generalHisEvidence) sources.add('other_evidence')
230
+ if (cues.some((c) => c.source === 'self_felt')) sources.add('self_felt')
231
+ if (weakAnchor) sources.add('self_weak')
232
+ if (contagionCue) sources.add('contagion')
233
+ const moment = sources.size >= 2 && (strongEmotion || strongEvidence || weakAnchor)
234
+
235
+ return { otherEvidence, selfEvidence, transferEvidence, otherFeatures: featureFlags(otherText), selfFeatures: featureFlags(selfText), cues, write, moment, sources: [...sources] }
236
+ }
237
+
238
+ /** 跨回合配额:冷却 2 回合、每 3 回合≤2 次、每天≤6 次。 */
239
+ export function allowWrite(state, { turnIndex = 0, now = Date.now() } = {}) {
240
+ if (!state || typeof state !== 'object') return false;
241
+ const log = Array.isArray(state.intakeLog) ? state.intakeLog : []
242
+ const last = log[log.length - 1]
243
+ if (last && turnIndex - last.turn < COOLDOWN_TURNS) return false
244
+ const recent = log.filter((x) => turnIndex - x.turn <= 3)
245
+ if (recent.length >= 2) return false
246
+ const day = new Date(now).toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' })
247
+ if (log.filter((x) => x.day === day).length >= DAY_CAP) return false
248
+ return true
249
+ }
250
+
251
+ /**
252
+ * 追加一条写入日志,返回**新状态**;不修改传入的 state 或它的 intakeLog 数组。
253
+ * `now` 必须由调用方传入(不隐藏时钟);`write` 为空时返回 null,不占配额。
254
+ */
255
+ export function recordWrite(state, { turnIndex = 0, now, write = null } = {}) {
256
+ if (!state || typeof state !== 'object') return null;
257
+ if (!Number.isFinite(now)) return null;
258
+ if (!write || typeof write !== 'object') return null;
259
+ if (!['v', 'a'].includes(write.dim)) return null;
260
+ if (typeof write.value !== 'number' || !Number.isFinite(write.value)) return null;
261
+ if (typeof write.source !== 'string' || !write.source.trim()) return null;
262
+ const prev = Array.isArray(state.intakeLog) ? state.intakeLog.slice() : []
263
+ const day = new Date(now).toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' })
264
+ prev.push({ turn: turnIndex, day, dim: write.dim || '', value: write.value || 0, source: write.source || '' })
265
+ return { ...state, intakeLog: prev.slice(-100) }
266
+ }
267
+
268
+ /**
269
+ * moment 序列闸门:≥2 个独立源、距上次 ≥2 回合、同一对源当天只触发一次。
270
+ * 返回 true 才允许 noteCandidate。
271
+ */
272
+ export function momentDue(state, { turnIndex = 0, sources = [], now = Date.now() } = {}) {
273
+ const norm = normalizeSources(sources)
274
+ if (norm.length < 2) return false
275
+ if (Number.isFinite(state.lastMomentTurn) && turnIndex - state.lastMomentTurn < 2) return false
276
+ const day = new Date(now).toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' })
277
+ const pair = norm.sort().join('+')
278
+ const pairs = Array.isArray(state.momentPairs) ? state.momentPairs : []
279
+ if (pairs.some((p) => p.day === day && normalizeSources(String(p.pair || '').split('+')).sort().join('+') === pair)) return false
280
+ return true
281
+ }
282
+
283
+ export function recordMoment(state, { turnIndex = 0, sources = [], now = Date.now() } = {}) {
284
+ const day = new Date(now).toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' })
285
+ state.momentPairs = Array.isArray(state.momentPairs) ? state.momentPairs : []
286
+ state.momentPairs.push({ day, pair: normalizeSources(sources).sort().join('+'), turn: turnIndex })
287
+ state.momentPairs = state.momentPairs.slice(-50)
288
+ state.lastMomentTurn = turnIndex
289
+ }
290
+
291
+ /** 传染源门槛:置信度 ≥0.4 且 |push| ≥0.12,两个条件同时满足才算(宿主入口同口径)。 */
292
+ export function contagionCueOf(contagion) {
293
+ const confidence = Number(contagion?.confidence ?? 0)
294
+ const push = Number(contagion?.push ?? 0)
295
+ if (confidence < 0.4 || Math.abs(push) < 0.12) return null
296
+ return { source: 'contagion', dim: 'v', value: Math.sign(push) * C_CONTAGION, strong: false }
297
+ }
298
+
299
+ /**
300
+ * moment 跨回合窗口:3 回合内的独立源合并;按来源各自最后出现的回合淘汰。
301
+ * 旧来源名先归一化再计数;兼容旧格式窗口(只有 turn/sources,没有 last)。
302
+ */
303
+ export function mergeMomentWindow(state, { turnIndex = 0, sources = [] } = {}) {
304
+ const old = state.momentWindow
305
+ const oldTurn = old && Number.isFinite(Number(old.turn)) ? Number(old.turn) : null
306
+ const fresh = oldTurn !== null && turnIndex - oldTurn <= 3
307
+ const w = fresh ? old : { turn: turnIndex, sources: [], last: {} }
308
+ const last = {}
309
+ // 已存的 last 也要过白名单与别名:旧版本可能存过未知标签
310
+ if (w.last && typeof w.last === 'object') {
311
+ for (const [k, v] of Object.entries(w.last)) {
312
+ const name = SOURCE_ALIAS[k] || k
313
+ if (!ALLOWED_SOURCES.has(name) || !Number.isFinite(Number(v))) continue
314
+ last[name] = Math.max(Number.isFinite(last[name]) ? last[name] : -Infinity, Number(v))
315
+ }
316
+ }
317
+ // 旧格式没有 last:只有 turn 表示窗口最近一次更新,无法还原每个来源的实际出现回合,
318
+ // 迁就取这个更新回合作为上界。
319
+ if (!w.last && Array.isArray(w.sources)) {
320
+ const t = oldTurn !== null ? oldTurn : turnIndex
321
+ for (const s of normalizeSources(w.sources)) last[s] = t
322
+ }
323
+ for (const s of normalizeSources(sources)) last[s] = turnIndex
324
+ // 只保留 3 回合内出现过的来源;空回合不会给旧证据续期
325
+ const alive = Object.fromEntries(Object.entries(last).filter(([, t]) => turnIndex - t <= 3))
326
+ w.sources = Object.keys(alive)
327
+ w.last = alive
328
+ w.turn = turnIndex
329
+ state.momentWindow = w
330
+ return { due: w.sources.length >= 2 && isStrong(w.sources), sources: w.sources }
331
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "whale-emotion-intake",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Turn a message into emotion candidates: clause-level experiencer check, evidence vs felt separation, per-turn caps.",
6
+ "license": "MIT",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "example.mjs",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "keywords": [
18
+ "emotion",
19
+ "appraisal",
20
+ "companion",
21
+ "memory",
22
+ "narrative"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/firefly1office/whale-memory.git",
30
+ "directory": "packages/emotion-intake"
31
+ }
32
+ }