@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.1
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/backfill-child.js +310 -0
- package/backfill-vectors.js +125 -0
- package/contract.js +114 -0
- package/cordis.patch.yml +7 -0
- package/cursor.js +116 -0
- package/dedupe.js +101 -0
- package/egress.js +790 -0
- package/embed-child.js +152 -0
- package/embed.js +475 -0
- package/envelope.js +368 -0
- package/extract.js +420 -0
- package/idle-interrupt.js +922 -0
- package/index.js +154 -0
- package/migrate.js +1723 -0
- package/package.json +68 -3
- package/persona.js +949 -0
- package/providers.js +786 -0
- package/query-window.js +562 -0
- package/recall-stages.js +150 -0
- package/recall-trivium.js +916 -0
- package/recall.js +129 -0
- package/remove-legacy.mjs +720 -0
- package/retention-sweep.js +124 -0
- package/serve.js +138 -0
- package/store-trivium-child.js +447 -0
- package/store-trivium.js +510 -0
- package/store.js +347 -0
- package/sweep.js +296 -0
- package/tools.js +507 -0
- package/trivium-runtime.js +1900 -0
- package/README.md +0 -3
package/persona.js
ADDED
|
@@ -0,0 +1,949 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 双核画像(P4 任务 36):**用户模型**(静态 / 动态 / 偏好)与**自我工作模型**(分寸 / 默契 / 履历)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要一个独立的 schema 表,而不是随手一个对象:
|
|
5
|
+
* 1. **每个字段必须有声明过的来源信号**。字段表 `FIELD_SCHEMA` 逐字段写死 `allowedSources`,
|
|
6
|
+
* 存储值再带一份 `source`(`kind` + `ref` + `at`);两层都过校验,`source: null` 或「来源种类
|
|
7
|
+
* 不在该字段的白名单里」一律抛错。任务 37 的 `serve.js` 在注入前调用 `validatePersona`,
|
|
8
|
+
* 因此「凭空多出来的字段」进不了提示词。
|
|
9
|
+
* 2. **字段名是闭集**。未知字段不是被忽略,而是 `KANABO_PERSONA_UNKNOWN_FIELD`——否则一个拼错的
|
|
10
|
+
* 字段会安静地永远不生效。
|
|
11
|
+
* 3. **衰减与冲突规则是数据,不是隐式行为**。每个字段声明 `decayHalfLifeMs` 与 `neutral`;
|
|
12
|
+
* 冲突规则只有一条(见 `CONFLICT_MARGIN`),静态字段与单调计数各有一条例外,全部有测试。
|
|
13
|
+
*
|
|
14
|
+
* 自我三组字段以 `hindsight-architecture.md` §3.3 的 **disposition 三标量**为词表:
|
|
15
|
+
* `skepticism` / `literalism` / `empathy`,各 1–5、中性 3([源码] Hindsight `Bank.disposition`
|
|
16
|
+
* 默认 `{3,3,3}`)。映射不是照搬:
|
|
17
|
+
* - **分寸**(`self.boundary.*`)= `skepticism`(该怀疑到什么程度)+ `literalism`(指令该照字面
|
|
18
|
+
* 执行到什么程度);
|
|
19
|
+
* - **默契**(`self.rapport.*`)= `empathy`(共情的分量)+ `directness`(同一 1–5 标尺上的语气刻度,
|
|
20
|
+
* 这一项 Hindsight 没有,是本项目自己加的);
|
|
21
|
+
* - **履历**(`self.history.*`)= `interactions`(观察到的交互次数,单调不减)+ `last_correction`
|
|
22
|
+
* (最近一次被纠正的是什么)。
|
|
23
|
+
*
|
|
24
|
+
* ## 来源信号词表(`SOURCE_KINDS`)
|
|
25
|
+
*
|
|
26
|
+
* | kind | 含义 | `ref` 指向 |
|
|
27
|
+
* | --- | --- | --- |
|
|
28
|
+
* | `declared` | 用户在某轮里明确陈述(原话) | 轮次号或信封 id |
|
|
29
|
+
* | `observed` | 从用户回合的行为观察到(没被明说) | 轮次号或信封 id |
|
|
30
|
+
* | `envelope` | 一条**已过 `validateEnvelope`** 的记忆信封,信号写在 `node_metadata.persona` | 信封 `id`,且必带 `source_type` |
|
|
31
|
+
* | `recall` | 一条召回命中显式携带的画像信号(`hit.persona`) | 命中 `id` |
|
|
32
|
+
* | `tool_result` | 显式工具结果 | 工具调用 id |
|
|
33
|
+
* | `config` | 部署配置里的默认值 | 配置键 |
|
|
34
|
+
* | `derived` | 由其它画像字段聚合而来 | 源字段路径列表 |
|
|
35
|
+
*
|
|
36
|
+
* 纯文本召回命中**不会**被猜成画像字段:本模块不做自然语言抽取(那属于上游),只有显式携带
|
|
37
|
+
* `persona` 的信封/命中才会产生信号。这条限制是刻意的——猜出来的字段没有可审计的来源。
|
|
38
|
+
*
|
|
39
|
+
* ## 衰减与冲突(全部以**注入的 `now`** 为准,模块内不读墙钟)
|
|
40
|
+
*
|
|
41
|
+
* 衰减,`age = max(0, now - updatedAt)`,`factor = 2^(-age / decayHalfLifeMs)`:
|
|
42
|
+
* - 所有字段:`confidence' = round(confidence × factor, 6)`;
|
|
43
|
+
* - `type: 'number'` 的字段另外把**值**往 `neutral` 收敛:`value' = neutral + (value - neutral) × factor`
|
|
44
|
+
* ——「沉默久了就回到中性」,这是 disposition 标尺的原意;字符串/枚举没有中间值,只有置信度衰减,
|
|
45
|
+
* 低于 `EXPIRY_FLOOR` 即视为过期、渲染时不出现在注入块里(中性 = 不说)。
|
|
46
|
+
*
|
|
47
|
+
* 冲突:
|
|
48
|
+
* - 同值 → **加强**:`c' = 1 - (1 - c_eff)(1 - c_new)`(noisy-OR,单调、有界),`updatedAt = now`;
|
|
49
|
+
* - 异值 → **强者胜**:`c_new > c_eff + CONFLICT_MARGIN` 才覆盖(被覆盖的旧值连同来源进 `divergences`,
|
|
50
|
+
* `reason: 'superseded'`);否则保留旧值、置信度不变,新观测进 `divergences`(`'weaker-evidence'`);
|
|
51
|
+
* - 静态字段(`decayHalfLifeMs === null && group === 'static'`):只有 `kind: 'declared'` 且置信度不低于
|
|
52
|
+
* 现有有效置信度才覆盖,否则 `'static-conflict'`;
|
|
53
|
+
* - 单调计数(`monotone: true`):下降一律拒绝,`'monotone-reject'`。
|
|
54
|
+
*
|
|
55
|
+
* `divergences` 保留被拒/被覆盖的值与来源,最长 `MAX_DIVERGENCES` 条——冲突不被静默吞掉。
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
import { SOURCE_TYPES } from './contract.js'
|
|
59
|
+
import { validateEnvelope } from './envelope.js'
|
|
60
|
+
|
|
61
|
+
export const PERSONA_VERSION = 1
|
|
62
|
+
|
|
63
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
64
|
+
|
|
65
|
+
/** 注入块的固定头行:serve.js 靠它识别「这一块是画像」,改文案必须同步那里。 */
|
|
66
|
+
export const PERSONA_HEADER = 'Persona (evidence-backed user model + working self-model):'
|
|
67
|
+
|
|
68
|
+
/** 每个字段都必须来自这些信号之一;新增信号必须同时补文档与测试。 */
|
|
69
|
+
export const SOURCE_KINDS = Object.freeze([
|
|
70
|
+
'declared',
|
|
71
|
+
'observed',
|
|
72
|
+
'envelope',
|
|
73
|
+
'recall',
|
|
74
|
+
'tool_result',
|
|
75
|
+
'config',
|
|
76
|
+
'derived',
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
/** 冲突被拒/被覆盖的原因,闭集(与 `divergences[].reason` 同源)。 */
|
|
80
|
+
export const DIVERGENCE_REASONS = Object.freeze([
|
|
81
|
+
'superseded',
|
|
82
|
+
'weaker-evidence',
|
|
83
|
+
'static-conflict',
|
|
84
|
+
'monotone-reject',
|
|
85
|
+
])
|
|
86
|
+
|
|
87
|
+
/** 覆盖门槛:新证据要严格强出现有**有效**置信度这么多,才允许改值。 */
|
|
88
|
+
export const CONFLICT_MARGIN = 0.05
|
|
89
|
+
/** 低于它就算过期:不参与渲染,等价于「回到中性」。 */
|
|
90
|
+
export const EXPIRY_FLOOR = 0.05
|
|
91
|
+
/** 低于它的字段不渲染(比过期更严格:弱信号不值得占注入预算)。 */
|
|
92
|
+
export const RENDER_FLOOR = 0.15
|
|
93
|
+
/** 配置默认值的置信度:能建立字段,但压不过一条真实观测。 */
|
|
94
|
+
export const CONFIG_CONFIDENCE = 0.5
|
|
95
|
+
/** 渲染预算(Unicode 码点数),比 `store.js` 的 2048 字节注入上限更保守。 */
|
|
96
|
+
export const PERSONA_BUDGET_CHARS = 1200
|
|
97
|
+
/** 单字段值的最大字符数,防止一条长文本把整个预算吃掉。 */
|
|
98
|
+
export const MAX_VALUE_CHARS = 160
|
|
99
|
+
/** 每个字段保留的冲突记录上限(新的在前)。 */
|
|
100
|
+
export const MAX_DIVERGENCES = 8
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 字段表。顺序 = 渲染顺序;`neutral` 是衰减的中性值;`allowedSources` 是该字段唯一合法的
|
|
104
|
+
* 来源信号集合。**新增字段必须在这里加一行**,否则校验器按未知字段拒绝。
|
|
105
|
+
*
|
|
106
|
+
* 为什么用户侧是 static / dynamic / preference 三组:静态事实只会被用户自己再声明一次;
|
|
107
|
+
* 动态事实随证据变化且会过期;偏好是带权重的(权重就是置信度),语气/自主度这类「多一点少一点」
|
|
108
|
+
* 的判断比事实更容易过时。
|
|
109
|
+
*
|
|
110
|
+
* 为什么自我侧是 分寸 / 默契 / 履历:「我该怎么和你相处」不是事实集合,分寸是策略刻度、
|
|
111
|
+
* 默契是共同语汇与语气、履历是已经发生过的交互与我犯过的错。
|
|
112
|
+
*/
|
|
113
|
+
export const FIELD_SCHEMA = Object.freeze([
|
|
114
|
+
// ---- 用户:静态事实(声明一次,不衰减) ----
|
|
115
|
+
{
|
|
116
|
+
path: 'user.static.preferred_name',
|
|
117
|
+
facet: 'user', group: 'static', label: 'preferred name', labelZh: '称呼',
|
|
118
|
+
type: 'string', maxChars: 40, neutral: '', decayHalfLifeMs: null,
|
|
119
|
+
allowedSources: ['declared', 'envelope', 'config'],
|
|
120
|
+
why: '只有用户自己说、或一条已校验的信封里写了,才算数;称呼不能猜。',
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
path: 'user.static.primary_language',
|
|
124
|
+
facet: 'user', group: 'static', label: 'primary language', labelZh: '主语言',
|
|
125
|
+
type: 'string', maxChars: 16, neutral: '', decayHalfLifeMs: null,
|
|
126
|
+
allowedSources: ['declared', 'envelope', 'config'],
|
|
127
|
+
why: '用户显式声明过的语言偏好(「只用中文」)。',
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
path: 'user.static.time_zone',
|
|
131
|
+
facet: 'user', group: 'static', label: 'time zone', labelZh: '时区',
|
|
132
|
+
type: 'string', maxChars: 40, neutral: '', decayHalfLifeMs: null,
|
|
133
|
+
allowedSources: ['declared', 'envelope', 'config'],
|
|
134
|
+
why: '时区影响「今天/昨晚」的解释,猜错会让相对时间全错。',
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
path: 'user.static.work_role',
|
|
138
|
+
facet: 'user', group: 'static', label: 'work role', labelZh: '角色',
|
|
139
|
+
type: 'string', maxChars: 60, neutral: '', decayHalfLifeMs: null,
|
|
140
|
+
allowedSources: ['declared', 'envelope'],
|
|
141
|
+
why: '只接受用户自己说过或信封里写明的角色,不能从命令推断。',
|
|
142
|
+
},
|
|
143
|
+
// ---- 用户:动态事实(随证据更新,会衰减) ----
|
|
144
|
+
{
|
|
145
|
+
path: 'user.dynamic.current_task',
|
|
146
|
+
facet: 'user', group: 'dynamic', label: 'current task', labelZh: '当前任务',
|
|
147
|
+
type: 'string', maxChars: 120, neutral: '', decayHalfLifeMs: 14 * DAY_MS,
|
|
148
|
+
allowedSources: ['observed', 'declared', 'envelope', 'recall', 'tool_result'],
|
|
149
|
+
why: '两周半衰期:任务换得快,两周前的「当前任务」只能算弱提示。',
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
path: 'user.dynamic.active_project',
|
|
153
|
+
facet: 'user', group: 'dynamic', label: 'active project', labelZh: '在手项目',
|
|
154
|
+
type: 'string', maxChars: 80, neutral: '', decayHalfLifeMs: 30 * DAY_MS,
|
|
155
|
+
allowedSources: ['observed', 'declared', 'envelope', 'recall'],
|
|
156
|
+
why: '项目比单次任务稳定,半衰期取 30 天。',
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
path: 'user.dynamic.current_blocker',
|
|
160
|
+
facet: 'user', group: 'dynamic', label: 'current blocker', labelZh: '当前阻塞',
|
|
161
|
+
type: 'string', maxChars: 120, neutral: '', decayHalfLifeMs: 7 * DAY_MS,
|
|
162
|
+
allowedSources: ['observed', 'declared', 'envelope'],
|
|
163
|
+
why: '阻塞是最易失的信息,一周半衰期;过期的阻塞比没有更糟。',
|
|
164
|
+
},
|
|
165
|
+
// ---- 用户:偏好(权重化) ----
|
|
166
|
+
{
|
|
167
|
+
path: 'user.preference.verbosity',
|
|
168
|
+
facet: 'user', group: 'preference', label: 'verbosity', labelZh: '详略',
|
|
169
|
+
type: 'enum', values: Object.freeze(['terse', 'normal', 'detailed']),
|
|
170
|
+
neutral: 'normal', decayHalfLifeMs: 90 * DAY_MS,
|
|
171
|
+
allowedSources: ['declared', 'observed', 'envelope', 'recall', 'config'],
|
|
172
|
+
why: '「少废话」这类偏好会随阶段变化,90 天半衰期 + 中性 normal。',
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
path: 'user.preference.autonomy',
|
|
176
|
+
facet: 'user', group: 'preference', label: 'autonomy', labelZh: '自主度',
|
|
177
|
+
type: 'enum', values: Object.freeze(['confirm-first', 'balanced', 'autonomous']),
|
|
178
|
+
neutral: 'balanced', decayHalfLifeMs: 120 * DAY_MS,
|
|
179
|
+
allowedSources: ['declared', 'observed', 'envelope', 'config'],
|
|
180
|
+
why: '「先问再做」还是「做完汇报」是长期但可变的偏好,中性取 balanced。',
|
|
181
|
+
},
|
|
182
|
+
// ---- 自我:分寸(策略刻度,1–5,中性 3) ----
|
|
183
|
+
{
|
|
184
|
+
path: 'self.boundary.skepticism',
|
|
185
|
+
facet: 'self', group: 'boundary', label: 'skepticism', labelZh: '谨慎度',
|
|
186
|
+
type: 'number', min: 1, max: 5, neutral: 3, decayHalfLifeMs: 60 * DAY_MS,
|
|
187
|
+
disposition: true,
|
|
188
|
+
allowedSources: ['observed', 'declared', 'envelope', 'recall', 'config'],
|
|
189
|
+
why: 'disposition 三标量之一:对结论该怀疑到什么程度。',
|
|
190
|
+
},
|
|
191
|
+
{
|
|
192
|
+
path: 'self.boundary.literalism',
|
|
193
|
+
facet: 'self', group: 'boundary', label: 'literalism', labelZh: '照字面程度',
|
|
194
|
+
type: 'number', min: 1, max: 5, neutral: 3, decayHalfLifeMs: 60 * DAY_MS,
|
|
195
|
+
disposition: true,
|
|
196
|
+
allowedSources: ['observed', 'declared', 'envelope', 'recall', 'config'],
|
|
197
|
+
why: 'disposition 三标量之一:照字面执行还是领会意图。',
|
|
198
|
+
},
|
|
199
|
+
// ---- 自我:默契(语气与共同语汇,1–5,中性 3) ----
|
|
200
|
+
{
|
|
201
|
+
path: 'self.rapport.empathy',
|
|
202
|
+
facet: 'self', group: 'rapport', label: 'empathy', labelZh: '共情',
|
|
203
|
+
type: 'number', min: 1, max: 5, neutral: 3, decayHalfLifeMs: 90 * DAY_MS,
|
|
204
|
+
disposition: true,
|
|
205
|
+
allowedSources: ['observed', 'declared', 'envelope', 'recall', 'config'],
|
|
206
|
+
why: 'disposition 三标量之一:安慰与共情的分量;比分寸更稳,90 天半衰期。',
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
path: 'self.rapport.directness',
|
|
210
|
+
facet: 'self', group: 'rapport', label: 'directness', labelZh: '直白程度',
|
|
211
|
+
type: 'number', min: 1, max: 5, neutral: 3, decayHalfLifeMs: 90 * DAY_MS,
|
|
212
|
+
allowedSources: ['observed', 'declared', 'envelope', 'recall', 'config'],
|
|
213
|
+
why: '与 disposition 同一 1–5 标尺,但 Hindsight 没有这一项:本项目用来记「要不要绕弯子」。',
|
|
214
|
+
},
|
|
215
|
+
// ---- 自我:履历(已发生的交互,单调不减) ----
|
|
216
|
+
{
|
|
217
|
+
path: 'self.history.interactions',
|
|
218
|
+
facet: 'self', group: 'history', label: 'interactions', labelZh: '交互次数',
|
|
219
|
+
type: 'integer', min: 0, max: Number.MAX_SAFE_INTEGER, neutral: 0,
|
|
220
|
+
decayHalfLifeMs: null, monotone: true,
|
|
221
|
+
allowedSources: ['derived', 'recall', 'tool_result'],
|
|
222
|
+
why: '履历是计数,不衰减也不许倒退;来源只能是聚合(derived)或显式记录。',
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
path: 'self.history.last_correction',
|
|
226
|
+
facet: 'self', group: 'history', label: 'last correction', labelZh: '最近被纠正',
|
|
227
|
+
type: 'string', maxChars: 120, neutral: '', decayHalfLifeMs: 45 * DAY_MS,
|
|
228
|
+
allowedSources: ['observed', 'declared', 'envelope'],
|
|
229
|
+
why: '48 天量级的记忆:我最近一次被纠正的是什么,避免重复犯同一个错。',
|
|
230
|
+
},
|
|
231
|
+
])
|
|
232
|
+
|
|
233
|
+
const SCHEMA_BY_PATH = new Map(FIELD_SCHEMA.map((row) => [row.path, row]))
|
|
234
|
+
|
|
235
|
+
/** 合法的字段路径(闭集)。serve 或测试可用它做自检。 */
|
|
236
|
+
export const FIELD_PATHS = Object.freeze(FIELD_SCHEMA.map((row) => row.path))
|
|
237
|
+
|
|
238
|
+
/** disposition 三标量在画像里的落点(§3.3 的词表复用)。 */
|
|
239
|
+
export const DISPOSITION_PATHS = Object.freeze(
|
|
240
|
+
FIELD_SCHEMA.filter((row) => row.disposition === true).map((row) => row.path))
|
|
241
|
+
|
|
242
|
+
const TOP_FIELDS = Object.freeze(['version', 'scope', 'builtAt', 'fields', 'skipped'])
|
|
243
|
+
const FIELD_KEYS = Object.freeze(['path', 'value', 'confidence', 'source', 'updatedAt', 'divergences'])
|
|
244
|
+
const SOURCE_FIELD_KEYS = Object.freeze(['kind', 'ref', 'at', 'source_type'])
|
|
245
|
+
const DIVERGENCE_KEYS = Object.freeze(['value', 'confidence', 'source', 'at', 'reason'])
|
|
246
|
+
const SKIPPED_KEYS = Object.freeze(['ref', 'code'])
|
|
247
|
+
const SIGNAL_KEYS = Object.freeze(['path', 'value', 'confidence', 'source'])
|
|
248
|
+
|
|
249
|
+
function personaError(code, message, extra) {
|
|
250
|
+
const error = new Error(message)
|
|
251
|
+
error.code = code
|
|
252
|
+
if (extra !== undefined) Object.assign(error, extra)
|
|
253
|
+
return error
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function isPlainObject(value) {
|
|
257
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
258
|
+
const proto = Object.getPrototypeOf(value)
|
|
259
|
+
return proto === Object.prototype || proto === null
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function received(value) {
|
|
263
|
+
if (value === undefined) return 'undefined'
|
|
264
|
+
if (typeof value === 'number' && !Number.isFinite(value)) return String(value)
|
|
265
|
+
try {
|
|
266
|
+
const json = JSON.stringify(value)
|
|
267
|
+
if (typeof json !== 'string') return typeof value
|
|
268
|
+
return json.length > 120 ? `${json.slice(0, 119)}…` : json
|
|
269
|
+
} catch {
|
|
270
|
+
return typeof value
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function fail(code, field, expected, value) {
|
|
275
|
+
throw personaError(code, `persona: 字段 "${field}" 非法(期望 ${expected},收到 ${received(value)})。`,
|
|
276
|
+
{ field, expected, received: received(value) })
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function assertKnownFields(object, allowed, prefix) {
|
|
280
|
+
for (const key of Object.keys(object)) {
|
|
281
|
+
if (!allowed.includes(key)) {
|
|
282
|
+
throw personaError('KANABO_PERSONA_UNKNOWN_FIELD',
|
|
283
|
+
`persona: 未知字段 "${prefix === '' ? key : `${prefix}.${key}`}";画像字段必须在 FIELD_SCHEMA 里声明,`
|
|
284
|
+
+ '扩展请先加 schema 行与来源信号。', { field: prefix === '' ? key : `${prefix}.${key}` })
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function failUnknownPath(path) {
|
|
290
|
+
throw personaError('KANABO_PERSONA_UNKNOWN_FIELD',
|
|
291
|
+
`persona: 未声明的画像字段 "${String(path)}";合法路径见 FIELD_PATHS(${FIELD_PATHS.length} 个)。`,
|
|
292
|
+
{ field: String(path) })
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export function schemaOf(path) {
|
|
296
|
+
return SCHEMA_BY_PATH.get(path)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function round(value, dp) {
|
|
300
|
+
const scale = 10 ** dp
|
|
301
|
+
return Math.round(value * scale) / scale
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** 显式 `now` 是硬要求:模块内不取墙钟,衰减结果才可复现。 */
|
|
305
|
+
function requireNow(now, where) {
|
|
306
|
+
if (!Number.isSafeInteger(now) || now < 0) {
|
|
307
|
+
throw personaError('KANABO_PERSONA_NOW',
|
|
308
|
+
`${where}: 必须显式传 now(≥ 0 的安全整数毫秒);本模块不读墙钟,否则衰减不可复现。`,
|
|
309
|
+
{ field: 'now', received: received(now) })
|
|
310
|
+
}
|
|
311
|
+
return now
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** 控制字符与换行折成空格:画像值会被拼进注入块,绝不带第二行。 */
|
|
315
|
+
export function normalizeText(text) {
|
|
316
|
+
return String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function normalizeValue(schema, value) {
|
|
320
|
+
if (schema.type === 'string') {
|
|
321
|
+
if (typeof value !== 'string') fail('KANABO_PERSONA_FIELD_TYPE', schema.path, 'string', value)
|
|
322
|
+
const text = normalizeText(value)
|
|
323
|
+
if (text.length === 0) fail('KANABO_PERSONA_FIELD_VALUE', schema.path, '非空白字符串', value)
|
|
324
|
+
if (text.length > schema.maxChars) {
|
|
325
|
+
fail('KANABO_PERSONA_FIELD_VALUE', schema.path, `≤ ${schema.maxChars} 字符(先摘句再写入)`, value)
|
|
326
|
+
}
|
|
327
|
+
return text
|
|
328
|
+
}
|
|
329
|
+
if (schema.type === 'enum') {
|
|
330
|
+
if (typeof value !== 'string' || !schema.values.includes(value)) {
|
|
331
|
+
fail('KANABO_PERSONA_FIELD_VALUE', schema.path, schema.values.join(' | '), value)
|
|
332
|
+
}
|
|
333
|
+
return value
|
|
334
|
+
}
|
|
335
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
336
|
+
fail('KANABO_PERSONA_FIELD_TYPE', schema.path, schema.type === 'integer' ? 'integer' : 'number', value)
|
|
337
|
+
}
|
|
338
|
+
if (schema.type === 'integer' && !Number.isSafeInteger(value)) {
|
|
339
|
+
fail('KANABO_PERSONA_FIELD_TYPE', schema.path, '安全整数', value)
|
|
340
|
+
}
|
|
341
|
+
if (value < schema.min || value > schema.max) {
|
|
342
|
+
fail('KANABO_PERSONA_FIELD_VALUE', schema.path, `${schema.min}..${schema.max}`, value)
|
|
343
|
+
}
|
|
344
|
+
return value
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function validateSource(source, schema, field) {
|
|
348
|
+
if (!isPlainObject(source)) {
|
|
349
|
+
throw personaError('KANABO_PERSONA_UNSOURCED',
|
|
350
|
+
`persona: 字段 "${field}" 没有来源(source 必须是对象);画像不允许无来源字段。`, { field })
|
|
351
|
+
}
|
|
352
|
+
assertKnownFields(source, SOURCE_FIELD_KEYS, `${field}.source`)
|
|
353
|
+
if (source.kind === undefined) {
|
|
354
|
+
throw personaError('KANABO_PERSONA_UNSOURCED', `persona: 字段 "${field}" 缺少 source.kind。`, { field })
|
|
355
|
+
}
|
|
356
|
+
if (typeof source.kind !== 'string' || !SOURCE_KINDS.includes(source.kind)) {
|
|
357
|
+
fail('KANABO_PERSONA_SOURCE_KIND', `${field}.source.kind`, SOURCE_KINDS.join(' | '), source.kind)
|
|
358
|
+
}
|
|
359
|
+
if (!schema.allowedSources.includes(source.kind)) {
|
|
360
|
+
throw personaError('KANABO_PERSONA_SOURCE_KIND',
|
|
361
|
+
`persona: 字段 "${field}" 不接受来源 "${source.kind}";只允许 [${schema.allowedSources.join(', ')}]。`,
|
|
362
|
+
{ field: `${field}.source.kind`, allowed: [...schema.allowedSources], received: source.kind })
|
|
363
|
+
}
|
|
364
|
+
if (typeof source.ref !== 'string' || source.ref.trim().length === 0) {
|
|
365
|
+
throw personaError('KANABO_PERSONA_UNSOURCED',
|
|
366
|
+
`persona: 字段 "${field}" 的来源缺少非空 ref(指向证据:轮次/信封 id/配置键/字段路径)。`,
|
|
367
|
+
{ field: `${field}.source.ref`, received: received(source.ref) })
|
|
368
|
+
}
|
|
369
|
+
if (!Number.isSafeInteger(source.at) || source.at < 0) {
|
|
370
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${field}.source.at`, '≥ 0 的安全整数毫秒', source.at)
|
|
371
|
+
}
|
|
372
|
+
if (source.kind === 'envelope') {
|
|
373
|
+
if (source.source_type === undefined) {
|
|
374
|
+
throw personaError('KANABO_PERSONA_UNSOURCED',
|
|
375
|
+
`persona: 字段 "${field}" 的 envelope 来源必须带 source_type(信封种类决定它能不能提供这个字段)。`,
|
|
376
|
+
{ field: `${field}.source.source_type` })
|
|
377
|
+
}
|
|
378
|
+
if (typeof source.source_type !== 'string' || !SOURCE_TYPES.includes(source.source_type)) {
|
|
379
|
+
fail('KANABO_PERSONA_SOURCE_KIND', `${field}.source.source_type`, SOURCE_TYPES.join(' | '), source.source_type)
|
|
380
|
+
}
|
|
381
|
+
} else if (source.source_type !== undefined) {
|
|
382
|
+
throw personaError('KANABO_PERSONA_UNKNOWN_FIELD',
|
|
383
|
+
`persona: 字段 "${field}" 的来源种类是 "${source.kind}",不该带 source_type。`, { field: `${field}.source.source_type` })
|
|
384
|
+
}
|
|
385
|
+
return source
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function validateDivergence(entry, schema, field, index) {
|
|
389
|
+
const at = `${field}.divergences[${index}]`
|
|
390
|
+
if (!isPlainObject(entry)) fail('KANABO_PERSONA_FIELD_TYPE', at, 'object', entry)
|
|
391
|
+
assertKnownFields(entry, DIVERGENCE_KEYS, at)
|
|
392
|
+
for (const key of DIVERGENCE_KEYS) {
|
|
393
|
+
if (entry[key] === undefined) {
|
|
394
|
+
throw personaError('KANABO_PERSONA_MISSING_FIELD', `persona: 缺少必需字段 "${at}.${key}"。`, { field: `${at}.${key}` })
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
if (typeof entry.reason !== 'string' || !DIVERGENCE_REASONS.includes(entry.reason)) {
|
|
398
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.reason`, DIVERGENCE_REASONS.join(' | '), entry.reason)
|
|
399
|
+
}
|
|
400
|
+
if (typeof entry.confidence !== 'number' || !Number.isFinite(entry.confidence)
|
|
401
|
+
|| entry.confidence < 0 || entry.confidence > 1) {
|
|
402
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.confidence`, '0..1 之间的有限数', entry.confidence)
|
|
403
|
+
}
|
|
404
|
+
if (!Number.isSafeInteger(entry.at) || entry.at < 0) {
|
|
405
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.at`, '≥ 0 的安全整数毫秒', entry.at)
|
|
406
|
+
}
|
|
407
|
+
validateSource(entry.source, schema, at)
|
|
408
|
+
normalizeValue(schema, entry.value)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function validateField(field, index) {
|
|
412
|
+
const at = `fields[${index}]`
|
|
413
|
+
if (!isPlainObject(field)) fail('KANABO_PERSONA_FIELD_TYPE', at, 'object', field)
|
|
414
|
+
assertKnownFields(field, FIELD_KEYS, at)
|
|
415
|
+
if (field.path === undefined) {
|
|
416
|
+
throw personaError('KANABO_PERSONA_MISSING_FIELD', `persona: 缺少必需字段 "${at}.path"。`, { field: `${at}.path` })
|
|
417
|
+
}
|
|
418
|
+
const schema = schemaOf(field.path)
|
|
419
|
+
if (schema === undefined) failUnknownPath(field.path)
|
|
420
|
+
for (const key of FIELD_KEYS) {
|
|
421
|
+
if (key === 'divergences') continue
|
|
422
|
+
if (field[key] === undefined) {
|
|
423
|
+
throw personaError('KANABO_PERSONA_MISSING_FIELD', `persona: 缺少必需字段 "${at}.${key}"。`, { field: `${at}.${key}` })
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
normalizeValue(schema, field.value)
|
|
427
|
+
if (typeof field.value === 'string' && normalizeText(field.value) !== field.value) {
|
|
428
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.value`, '已规范化的单行文本(控制字符/换行进块前必须去掉)', field.value)
|
|
429
|
+
}
|
|
430
|
+
if (typeof field.confidence !== 'number' || !Number.isFinite(field.confidence)
|
|
431
|
+
|| field.confidence < 0 || field.confidence > 1) {
|
|
432
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.confidence`, '0..1 之间的有限数', field.confidence)
|
|
433
|
+
}
|
|
434
|
+
if (!Number.isSafeInteger(field.updatedAt) || field.updatedAt < 0) {
|
|
435
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.updatedAt`, '≥ 0 的安全整数毫秒', field.updatedAt)
|
|
436
|
+
}
|
|
437
|
+
validateSource(field.source, schema, field.path)
|
|
438
|
+
if (!Array.isArray(field.divergences)) fail('KANABO_PERSONA_FIELD_TYPE', `${at}.divergences`, 'array', field.divergences)
|
|
439
|
+
if (field.divergences.length > MAX_DIVERGENCES) {
|
|
440
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.divergences`, `≤ ${MAX_DIVERGENCES} 条`, field.divergences.length)
|
|
441
|
+
}
|
|
442
|
+
field.divergences.forEach((entry, i) => validateDivergence(entry, schema, field.path, i))
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* 严格校验一份画像,合法时**原样返回**,非法时抛 `KANABO_PERSONA_*` 结构化错误。
|
|
447
|
+
*
|
|
448
|
+
* 拒绝的类别(全部有测试):未知顶层键、未知字段键、未声明的字段路径、重复字段路径、
|
|
449
|
+
* 类型不符、越界(置信度/取值/时间戳)、无来源(缺失、未知 kind、该字段不允许的 kind、
|
|
450
|
+
* 空 ref、envelope 缺 source_type)。
|
|
451
|
+
*/
|
|
452
|
+
export function validatePersona(persona) {
|
|
453
|
+
if (!isPlainObject(persona)) {
|
|
454
|
+
throw personaError('KANABO_PERSONA_INPUT', `persona: 入参必须是普通对象(收到 ${received(persona)})。`,
|
|
455
|
+
{ expected: 'object', received: received(persona) })
|
|
456
|
+
}
|
|
457
|
+
assertKnownFields(persona, TOP_FIELDS, '')
|
|
458
|
+
if (persona.version === undefined) {
|
|
459
|
+
throw personaError('KANABO_PERSONA_MISSING_FIELD', 'persona: 缺少必需字段 "version"。', { field: 'version' })
|
|
460
|
+
}
|
|
461
|
+
if (persona.version !== PERSONA_VERSION) {
|
|
462
|
+
fail('KANABO_PERSONA_FIELD_VALUE', 'version', String(PERSONA_VERSION), persona.version)
|
|
463
|
+
}
|
|
464
|
+
if (typeof persona.scope !== 'string' || persona.scope.length === 0) {
|
|
465
|
+
fail('KANABO_PERSONA_FIELD_VALUE', 'scope', '非空字符串(workspace 分域键)', persona.scope)
|
|
466
|
+
}
|
|
467
|
+
if (!Number.isSafeInteger(persona.builtAt) || persona.builtAt < 0) {
|
|
468
|
+
fail('KANABO_PERSONA_FIELD_VALUE', 'builtAt', '≥ 0 的安全整数毫秒', persona.builtAt)
|
|
469
|
+
}
|
|
470
|
+
if (!Array.isArray(persona.fields)) fail('KANABO_PERSONA_FIELD_TYPE', 'fields', 'array', persona.fields)
|
|
471
|
+
const seen = new Set()
|
|
472
|
+
persona.fields.forEach((field, index) => {
|
|
473
|
+
validateField(field, index)
|
|
474
|
+
if (seen.has(field.path)) {
|
|
475
|
+
throw personaError('KANABO_PERSONA_DUPLICATE_PATH',
|
|
476
|
+
`persona: 字段路径 "${field.path}" 出现多次;同一字段只能有一条记录,冲突值放 divergences。`,
|
|
477
|
+
{ field: field.path })
|
|
478
|
+
}
|
|
479
|
+
seen.add(field.path)
|
|
480
|
+
})
|
|
481
|
+
if (persona.skipped !== undefined) {
|
|
482
|
+
if (!Array.isArray(persona.skipped)) fail('KANABO_PERSONA_FIELD_TYPE', 'skipped', 'array', persona.skipped)
|
|
483
|
+
persona.skipped.forEach((entry, index) => {
|
|
484
|
+
const at = `skipped[${index}]`
|
|
485
|
+
if (!isPlainObject(entry)) fail('KANABO_PERSONA_FIELD_TYPE', at, 'object', entry)
|
|
486
|
+
assertKnownFields(entry, SKIPPED_KEYS, at)
|
|
487
|
+
if (typeof entry.ref !== 'string' || entry.ref.length === 0) {
|
|
488
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.ref`, '非空字符串', entry.ref)
|
|
489
|
+
}
|
|
490
|
+
if (typeof entry.code !== 'string' || entry.code.length === 0) {
|
|
491
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${at}.code`, '非空字符串(KANABO_PERSONA_* 错误码)', entry.code)
|
|
492
|
+
}
|
|
493
|
+
})
|
|
494
|
+
}
|
|
495
|
+
return persona
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** 空画像:`scope` 是 workspace 分域键(与 store.js 同口径),`now` 显式传入。 */
|
|
499
|
+
export function createPersona(options = {}) {
|
|
500
|
+
const scope = typeof options.scope === 'string' && options.scope.length > 0 ? options.scope : 'unknown-workspace'
|
|
501
|
+
const now = requireNow(options.now, 'createPersona')
|
|
502
|
+
return validatePersona({ version: PERSONA_VERSION, scope, builtAt: now, fields: [], skipped: [] })
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* 衰减投影(纯函数,不改入参):
|
|
507
|
+
* - `confidence` 按半衰期衰减;
|
|
508
|
+
* - `type: 'number'` 的值同时向 `neutral` 收敛(disposition 标尺「沉默久了回中性」);
|
|
509
|
+
* - `expired` 表示置信度已低于 `EXPIRY_FLOOR`(渲染时等同不存在)。
|
|
510
|
+
*/
|
|
511
|
+
export function decayed(field, now) {
|
|
512
|
+
requireNow(now, 'decayed')
|
|
513
|
+
const schema = schemaOf(field.path)
|
|
514
|
+
if (schema === undefined) failUnknownPath(field.path)
|
|
515
|
+
if (schema.decayHalfLifeMs === null) {
|
|
516
|
+
return { value: field.value, confidence: field.confidence, factor: 1, expired: false, ageMs: 0 }
|
|
517
|
+
}
|
|
518
|
+
const ageMs = Math.max(0, now - field.updatedAt)
|
|
519
|
+
const factor = 2 ** (-ageMs / schema.decayHalfLifeMs)
|
|
520
|
+
const confidence = round(field.confidence * factor, 6)
|
|
521
|
+
const value = schema.type === 'number'
|
|
522
|
+
? round(schema.neutral + (field.value - schema.neutral) * factor, 3)
|
|
523
|
+
: field.value
|
|
524
|
+
return { value, confidence, factor, expired: confidence < EXPIRY_FLOOR, ageMs }
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
export function isExpired(field, now) {
|
|
528
|
+
return decayed(field, now).expired
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function cloneField(field) {
|
|
532
|
+
return {
|
|
533
|
+
path: field.path,
|
|
534
|
+
value: field.value,
|
|
535
|
+
confidence: field.confidence,
|
|
536
|
+
source: { ...field.source },
|
|
537
|
+
updatedAt: field.updatedAt,
|
|
538
|
+
divergences: field.divergences.map((entry) => ({ ...entry, source: { ...entry.source } })),
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
function normalizeSignal(signal, now) {
|
|
543
|
+
if (!isPlainObject(signal)) {
|
|
544
|
+
throw personaError('KANABO_PERSONA_SIGNAL', `persona: 观测信号必须是普通对象(收到 ${received(signal)})。`,
|
|
545
|
+
{ expected: 'object', received: received(signal) })
|
|
546
|
+
}
|
|
547
|
+
assertKnownFields(signal, SIGNAL_KEYS, 'signal')
|
|
548
|
+
const schema = schemaOf(signal.path)
|
|
549
|
+
if (schema === undefined) failUnknownPath(signal.path)
|
|
550
|
+
if (signal.value === undefined) {
|
|
551
|
+
throw personaError('KANABO_PERSONA_MISSING_FIELD', `persona: 信号缺少 value(字段 "${signal.path}")。`,
|
|
552
|
+
{ field: `${signal.path}.value` })
|
|
553
|
+
}
|
|
554
|
+
if (signal.confidence === undefined) {
|
|
555
|
+
throw personaError('KANABO_PERSONA_MISSING_FIELD', `persona: 信号缺少 confidence(字段 "${signal.path}")。`,
|
|
556
|
+
{ field: `${signal.path}.confidence` })
|
|
557
|
+
}
|
|
558
|
+
if (typeof signal.confidence !== 'number' || !Number.isFinite(signal.confidence)
|
|
559
|
+
|| signal.confidence < 0 || signal.confidence > 1) {
|
|
560
|
+
fail('KANABO_PERSONA_FIELD_VALUE', `${signal.path}.confidence`, '0..1 之间的有限数', signal.confidence)
|
|
561
|
+
}
|
|
562
|
+
const value = normalizeValue(schema, signal.value)
|
|
563
|
+
const source = { ...(isPlainObject(signal.source) ? signal.source : {}) }
|
|
564
|
+
if (source.at === undefined) source.at = now
|
|
565
|
+
validateSource(source, schema, signal.path)
|
|
566
|
+
return { path: schema.path, value, confidence: signal.confidence, source }
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function sameValue(schema, a, b) {
|
|
570
|
+
if (schema.type === 'string' || schema.type === 'enum') return a === b
|
|
571
|
+
return Math.abs(a - b) < 1e-9
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
function pushDivergence(field, entry) {
|
|
575
|
+
field.divergences.unshift(entry)
|
|
576
|
+
if (field.divergences.length > MAX_DIVERGENCES) field.divergences.length = MAX_DIVERGENCES
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function divergenceOf(field, decayedOld) {
|
|
580
|
+
return {
|
|
581
|
+
value: decayedOld.value,
|
|
582
|
+
confidence: decayedOld.confidence,
|
|
583
|
+
source: { ...field.source },
|
|
584
|
+
at: field.updatedAt,
|
|
585
|
+
reason: 'superseded',
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* 应用一条观测信号,返回**新的**画像(不改入参)与这次更新的结论。
|
|
591
|
+
*
|
|
592
|
+
* `outcome` 闭集:
|
|
593
|
+
* - `created` 该字段第一次被写入;
|
|
594
|
+
* - `reinforced` 同值观测(noisy-OR 加强,`updatedAt` 前移);
|
|
595
|
+
* - `superseded` 异值且证据更强(旧值进 `divergences[].reason = 'superseded'`);
|
|
596
|
+
* - `rejected-weaker` 异值但证据不够强(保持原值,新值进 `divergences[].reason = 'weaker-evidence'`);
|
|
597
|
+
* - `rejected-static` 静态字段被非声明/更弱的证据试图改写(`'static-conflict'`);
|
|
598
|
+
* - `rejected-monotone` 单调计数被要求下降(`'monotone-reject'`)。
|
|
599
|
+
*/
|
|
600
|
+
export function applySignal(persona, signal, options = {}) {
|
|
601
|
+
const now = requireNow(options.now, 'applySignal')
|
|
602
|
+
const base = validatePersona(persona)
|
|
603
|
+
const incoming = normalizeSignal(signal, now)
|
|
604
|
+
const schema = schemaOf(incoming.path)
|
|
605
|
+
const fields = base.fields.map(cloneField)
|
|
606
|
+
const skipped = Array.isArray(base.skipped) ? base.skipped : []
|
|
607
|
+
const index = fields.findIndex((field) => field.path === incoming.path)
|
|
608
|
+
|
|
609
|
+
if (index === -1) {
|
|
610
|
+
const field = {
|
|
611
|
+
path: incoming.path,
|
|
612
|
+
value: incoming.value,
|
|
613
|
+
confidence: incoming.confidence,
|
|
614
|
+
source: incoming.source,
|
|
615
|
+
updatedAt: now,
|
|
616
|
+
divergences: [],
|
|
617
|
+
}
|
|
618
|
+
fields.push(field)
|
|
619
|
+
return {
|
|
620
|
+
persona: validatePersona({ ...base, fields, skipped }),
|
|
621
|
+
outcome: 'created',
|
|
622
|
+
field: cloneField(field),
|
|
623
|
+
reason: null,
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
const field = fields[index]
|
|
628
|
+
const old = decayed(field, now)
|
|
629
|
+
|
|
630
|
+
if (schema.monotone === true && Number(incoming.value) < Number(field.value)) {
|
|
631
|
+
pushDivergence(field, {
|
|
632
|
+
value: incoming.value,
|
|
633
|
+
confidence: incoming.confidence,
|
|
634
|
+
source: incoming.source,
|
|
635
|
+
at: incoming.source.at,
|
|
636
|
+
reason: 'monotone-reject',
|
|
637
|
+
})
|
|
638
|
+
return {
|
|
639
|
+
persona: validatePersona({ ...base, fields, skipped }),
|
|
640
|
+
outcome: 'rejected-monotone',
|
|
641
|
+
field: cloneField(field),
|
|
642
|
+
reason: 'monotone-reject',
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
if (sameValue(schema, field.value, incoming.value)) {
|
|
647
|
+
const merged = round(1 - (1 - old.confidence) * (1 - incoming.confidence), 6)
|
|
648
|
+
field.value = incoming.value
|
|
649
|
+
field.confidence = Math.max(field.confidence, merged)
|
|
650
|
+
field.source = incoming.source
|
|
651
|
+
field.updatedAt = now
|
|
652
|
+
return {
|
|
653
|
+
persona: validatePersona({ ...base, fields, skipped }),
|
|
654
|
+
outcome: 'reinforced',
|
|
655
|
+
field: cloneField(field),
|
|
656
|
+
reason: null,
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const isStatic = schema.decayHalfLifeMs === null && schema.group === 'static'
|
|
661
|
+
const staticRedeclared = isStatic && incoming.source.kind === 'declared'
|
|
662
|
+
&& incoming.confidence >= old.confidence
|
|
663
|
+
if (isStatic && !staticRedeclared) {
|
|
664
|
+
pushDivergence(field, {
|
|
665
|
+
value: incoming.value,
|
|
666
|
+
confidence: incoming.confidence,
|
|
667
|
+
source: incoming.source,
|
|
668
|
+
at: incoming.source.at,
|
|
669
|
+
reason: 'static-conflict',
|
|
670
|
+
})
|
|
671
|
+
return {
|
|
672
|
+
persona: validatePersona({ ...base, fields, skipped }),
|
|
673
|
+
outcome: 'rejected-static',
|
|
674
|
+
field: cloneField(field),
|
|
675
|
+
reason: 'static-conflict',
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
if (staticRedeclared || incoming.confidence > old.confidence + CONFLICT_MARGIN) {
|
|
680
|
+
pushDivergence(field, divergenceOf(field, old))
|
|
681
|
+
field.value = incoming.value
|
|
682
|
+
field.confidence = incoming.confidence
|
|
683
|
+
field.source = incoming.source
|
|
684
|
+
field.updatedAt = now
|
|
685
|
+
return {
|
|
686
|
+
persona: validatePersona({ ...base, fields, skipped }),
|
|
687
|
+
outcome: 'superseded',
|
|
688
|
+
field: cloneField(field),
|
|
689
|
+
reason: null,
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
pushDivergence(field, {
|
|
694
|
+
value: incoming.value,
|
|
695
|
+
confidence: incoming.confidence,
|
|
696
|
+
source: incoming.source,
|
|
697
|
+
at: incoming.source.at,
|
|
698
|
+
reason: 'weaker-evidence',
|
|
699
|
+
})
|
|
700
|
+
return {
|
|
701
|
+
persona: validatePersona({ ...base, fields, skipped }),
|
|
702
|
+
outcome: 'rejected-weaker',
|
|
703
|
+
field: cloneField(field),
|
|
704
|
+
reason: 'weaker-evidence',
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* 从一条**已过 `validateEnvelope`** 的记忆信封读画像信号:只认 `node_metadata.persona`
|
|
710
|
+
* (对象或数组)。没写信号的信封返回 `[]`——不猜、不从正文抽取。
|
|
711
|
+
*
|
|
712
|
+
* 信封的 `id` / `ts` / `source_type` 原样成为信号的来源指向,因此每个画像字段都能回到证据。
|
|
713
|
+
*/
|
|
714
|
+
export function signalsFromEnvelope(envelope) {
|
|
715
|
+
const valid = validateEnvelope(envelope)
|
|
716
|
+
const meta = valid.node_metadata === undefined ? undefined : valid.node_metadata.persona
|
|
717
|
+
if (meta === undefined) return []
|
|
718
|
+
const items = Array.isArray(meta) ? meta : [meta]
|
|
719
|
+
return items.map((item) => {
|
|
720
|
+
if (!isPlainObject(item)) {
|
|
721
|
+
throw personaError('KANABO_PERSONA_SIGNAL',
|
|
722
|
+
`persona: 信封 ${valid.id} 的 node_metadata.persona 必须是对象或对象数组(收到 ${received(item)})。`,
|
|
723
|
+
{ field: `${valid.id}.node_metadata.persona` })
|
|
724
|
+
}
|
|
725
|
+
assertKnownFields(item, ['path', 'value', 'confidence'], `${valid.id}.node_metadata.persona`)
|
|
726
|
+
return {
|
|
727
|
+
path: item.path,
|
|
728
|
+
value: item.value,
|
|
729
|
+
confidence: item.confidence,
|
|
730
|
+
source: { kind: 'envelope', ref: String(valid.id), at: valid.ts, source_type: valid.source_type },
|
|
731
|
+
}
|
|
732
|
+
})
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/**
|
|
736
|
+
* 从召回命中读画像信号:只认命中上显式携带的 `persona`(对象或数组)。
|
|
737
|
+
*
|
|
738
|
+
* 纯文本命中不产生任何信号:召回文本是记忆正文,不是结构化声明;从正文猜字段会让字段
|
|
739
|
+
* 失去可审计的来源。命中没有 `ts` 时 `at` 记 0——「不知道多新」按最旧处理,衰减会自然让它过期。
|
|
740
|
+
*/
|
|
741
|
+
export function signalsFromRecall(hits) {
|
|
742
|
+
const list = Array.isArray(hits) ? hits : []
|
|
743
|
+
const signals = []
|
|
744
|
+
for (const hit of list) {
|
|
745
|
+
if (!isPlainObject(hit)) continue
|
|
746
|
+
const meta = hit.persona
|
|
747
|
+
if (meta === undefined) continue
|
|
748
|
+
const ref = typeof hit.id === 'string' && hit.id.length > 0 ? hit.id : null
|
|
749
|
+
if (ref === null) {
|
|
750
|
+
throw personaError('KANABO_PERSONA_UNSOURCED',
|
|
751
|
+
'persona: 携带 persona 信号的召回命中缺少非空 id,无法指向证据。', { field: 'recall.id' })
|
|
752
|
+
}
|
|
753
|
+
const at = Number.isSafeInteger(hit.ts) && hit.ts >= 0 ? hit.ts : 0
|
|
754
|
+
const items = Array.isArray(meta) ? meta : [meta]
|
|
755
|
+
for (const item of items) {
|
|
756
|
+
if (!isPlainObject(item)) {
|
|
757
|
+
throw personaError('KANABO_PERSONA_SIGNAL',
|
|
758
|
+
`persona: 召回命中 ${ref} 的 persona 必须是对象或对象数组(收到 ${received(item)})。`,
|
|
759
|
+
{ field: `${ref}.persona` })
|
|
760
|
+
}
|
|
761
|
+
assertKnownFields(item, ['path', 'value', 'confidence'], `${ref}.persona`)
|
|
762
|
+
signals.push({
|
|
763
|
+
path: item.path,
|
|
764
|
+
value: item.value,
|
|
765
|
+
confidence: item.confidence,
|
|
766
|
+
source: { kind: 'recall', ref, at },
|
|
767
|
+
})
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
return signals
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* 从记忆构建画像(serve.js 的入口):
|
|
775
|
+
* `config` 默认值 → 按 `(ts, id)` 排序的信封 → 按 `(at, ref)` 排序的召回命中 → 显式 `signals`。
|
|
776
|
+
*
|
|
777
|
+
* 顺序固定,因此同样的输入两次构建逐字节相同(`now` 由调用方注入)。来自记忆的脏数据不会让
|
|
778
|
+
* 构建失败:该条被跳进 `skipped`(带 `KANABO_PERSONA_*` 错误码),其余照常;**调用方直接传的
|
|
779
|
+
* `signals` 例外**——那是程序错误,按异常抛出。
|
|
780
|
+
*/
|
|
781
|
+
export function buildPersonaFromMemory(options = {}) {
|
|
782
|
+
const now = requireNow(options.now, 'buildPersonaFromMemory')
|
|
783
|
+
const scope = typeof options.scope === 'string' && options.scope.length > 0 ? options.scope : 'unknown-workspace'
|
|
784
|
+
let persona = createPersona({ scope, now })
|
|
785
|
+
const skipped = []
|
|
786
|
+
const codeOf = (error) => (typeof error?.code === 'string' ? error.code : 'KANABO_PERSONA_UNKNOWN_ERROR')
|
|
787
|
+
|
|
788
|
+
const config = isPlainObject(options.config) ? options.config : {}
|
|
789
|
+
for (const key of Object.keys(config).sort()) {
|
|
790
|
+
try {
|
|
791
|
+
persona = applySignal(persona, {
|
|
792
|
+
path: key,
|
|
793
|
+
value: config[key],
|
|
794
|
+
confidence: CONFIG_CONFIDENCE,
|
|
795
|
+
source: { kind: 'config', ref: `config:${key}`, at: now },
|
|
796
|
+
}, { now }).persona
|
|
797
|
+
} catch (error) {
|
|
798
|
+
skipped.push({ ref: `config:${key}`, code: codeOf(error) })
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
const envelopes = (Array.isArray(options.envelopes) ? [...options.envelopes] : [])
|
|
803
|
+
.sort((a, b) => Number(a?.ts ?? 0) - Number(b?.ts ?? 0) || String(a?.id ?? '').localeCompare(String(b?.id ?? '')))
|
|
804
|
+
for (const envelope of envelopes) {
|
|
805
|
+
const ref = envelope !== null && typeof envelope === 'object' && envelope.id !== undefined ? String(envelope.id) : 'envelope'
|
|
806
|
+
let signals
|
|
807
|
+
try {
|
|
808
|
+
signals = signalsFromEnvelope(envelope)
|
|
809
|
+
} catch (error) {
|
|
810
|
+
skipped.push({ ref, code: codeOf(error) })
|
|
811
|
+
continue
|
|
812
|
+
}
|
|
813
|
+
for (const signal of signals) {
|
|
814
|
+
try {
|
|
815
|
+
persona = applySignal(persona, signal, { now }).persona
|
|
816
|
+
} catch (error) {
|
|
817
|
+
skipped.push({ ref: signal.source.ref, code: codeOf(error) })
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const recall = (Array.isArray(options.recall) ? [...options.recall] : [])
|
|
823
|
+
.sort((a, b) => Number(a?.ts ?? 0) - Number(b?.ts ?? 0) || String(a?.id ?? '').localeCompare(String(b?.id ?? '')))
|
|
824
|
+
try {
|
|
825
|
+
for (const signal of signalsFromRecall(recall)) {
|
|
826
|
+
try {
|
|
827
|
+
persona = applySignal(persona, signal, { now }).persona
|
|
828
|
+
} catch (error) {
|
|
829
|
+
skipped.push({ ref: signal.source.ref, code: codeOf(error) })
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
} catch (error) {
|
|
833
|
+
skipped.push({ ref: 'recall', code: codeOf(error) })
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
for (const signal of Array.isArray(options.signals) ? options.signals : []) {
|
|
837
|
+
persona = applySignal(persona, signal, { now }).persona
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
return validatePersona({ ...persona, skipped })
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
const GROUP_TITLES = Object.freeze({
|
|
844
|
+
static: 'User — static',
|
|
845
|
+
dynamic: 'User — dynamic',
|
|
846
|
+
preference: 'User — preferences',
|
|
847
|
+
boundary: 'Self — measure (分寸)',
|
|
848
|
+
rapport: 'Self — rapport (默契)',
|
|
849
|
+
history: 'Self — track record (履历)',
|
|
850
|
+
})
|
|
851
|
+
|
|
852
|
+
function formatValue(schema, value) {
|
|
853
|
+
if (schema.type === 'number') return value.toFixed(1)
|
|
854
|
+
return String(value)
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/**
|
|
858
|
+
* 渲染成可注入的一块文本:**有预算、幂等、确定性**。
|
|
859
|
+
*
|
|
860
|
+
* - 顺序恒为 `FIELD_SCHEMA` 顺序(不随插入顺序漂移),同一 `(persona, now)` 两次调用逐字节相同;
|
|
861
|
+
* - 过期(`expired`)或置信度低于 `RENDER_FLOOR` 的字段不出现——中性就是不说;
|
|
862
|
+
* - 超预算时按置信度从低到高整行丢弃,并在末尾如实标注隐藏了几个字段;
|
|
863
|
+
* - 没有任何可见字段、或预算连「头行 + 一行字段」都装不下时返回**空串**——调用方据此不注入,
|
|
864
|
+
* 而不是注入一个只有开头没有内容的壳;
|
|
865
|
+
* - 值在写入与渲染两处都已去掉控制字符,所以一块里绝不会出现第二行伪造内容。
|
|
866
|
+
*
|
|
867
|
+
* 非法画像直接抛错:宁可不注入,也不注入一份没通过 schema 的东西。
|
|
868
|
+
*/
|
|
869
|
+
export function renderPersona(persona, options = {}) {
|
|
870
|
+
const now = requireNow(options.now, 'renderPersona')
|
|
871
|
+
const budget = Number.isFinite(options.budgetChars) && options.budgetChars > 0
|
|
872
|
+
? Math.floor(options.budgetChars)
|
|
873
|
+
: PERSONA_BUDGET_CHARS
|
|
874
|
+
const valid = validatePersona(persona)
|
|
875
|
+
const byPath = new Map(valid.fields.map((field) => [field.path, field]))
|
|
876
|
+
|
|
877
|
+
const visible = []
|
|
878
|
+
let hiddenByDecay = 0
|
|
879
|
+
for (const schema of FIELD_SCHEMA) {
|
|
880
|
+
const field = byPath.get(schema.path)
|
|
881
|
+
if (field === undefined) continue
|
|
882
|
+
const projected = decayed(field, now)
|
|
883
|
+
if (projected.expired || projected.confidence < RENDER_FLOOR) {
|
|
884
|
+
hiddenByDecay += 1
|
|
885
|
+
continue
|
|
886
|
+
}
|
|
887
|
+
visible.push({ schema, value: projected.value, confidence: projected.confidence })
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const costOf = (text) => Array.from(text).length
|
|
891
|
+
const build = (rows, dropped) => {
|
|
892
|
+
const lines = [PERSONA_HEADER]
|
|
893
|
+
let group = null
|
|
894
|
+
for (const row of rows) {
|
|
895
|
+
if (row.schema.group !== group) {
|
|
896
|
+
group = row.schema.group
|
|
897
|
+
lines.push(`${GROUP_TITLES[group]}:`)
|
|
898
|
+
}
|
|
899
|
+
const conf = row.confidence.toFixed(2)
|
|
900
|
+
lines.push(`- ${row.schema.label}: ${formatValue(row.schema, row.value)} (conf ${conf})`)
|
|
901
|
+
}
|
|
902
|
+
const hidden = hiddenByDecay + dropped
|
|
903
|
+
lines.push(`(${rows.length} fields${hidden > 0 ? `, ${hidden} hidden` : ''})`)
|
|
904
|
+
return lines.join('\n')
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
let rows = visible
|
|
908
|
+
let dropped = 0
|
|
909
|
+
let text = build(rows, dropped)
|
|
910
|
+
while (costOf(text) > budget && rows.length > 0) {
|
|
911
|
+
let weakest = 0
|
|
912
|
+
for (let i = 1; i < rows.length; i += 1) {
|
|
913
|
+
if (rows[i].confidence <= rows[weakest].confidence) weakest = i
|
|
914
|
+
}
|
|
915
|
+
rows = rows.filter((_, i) => i !== weakest)
|
|
916
|
+
dropped += 1
|
|
917
|
+
text = build(rows, dropped)
|
|
918
|
+
}
|
|
919
|
+
// 没话可说(没有可见字段)或预算连一行都装不下:返回空串,调用方据此不注入。
|
|
920
|
+
if (visible.length === 0 || costOf(text) > budget) return ''
|
|
921
|
+
return text
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/** 两个画像的差异(`{added, removed, changed}`,按路径)。测试与日志用。 */
|
|
925
|
+
export function diffPersona(before, after) {
|
|
926
|
+
const left = new Map(validatePersona(before).fields.map((field) => [field.path, field]))
|
|
927
|
+
const right = new Map(validatePersona(after).fields.map((field) => [field.path, field]))
|
|
928
|
+
const added = []
|
|
929
|
+
const removed = []
|
|
930
|
+
const changed = []
|
|
931
|
+
for (const [path, field] of right) {
|
|
932
|
+
const old = left.get(path)
|
|
933
|
+
if (old === undefined) {
|
|
934
|
+
added.push({ path, value: field.value, confidence: field.confidence })
|
|
935
|
+
continue
|
|
936
|
+
}
|
|
937
|
+
if (sameValue(schemaOf(path), old.value, field.value) && old.confidence === field.confidence) continue
|
|
938
|
+
changed.push({
|
|
939
|
+
path,
|
|
940
|
+
from: { value: old.value, confidence: old.confidence },
|
|
941
|
+
to: { value: field.value, confidence: field.confidence },
|
|
942
|
+
divergences: field.divergences.length,
|
|
943
|
+
})
|
|
944
|
+
}
|
|
945
|
+
for (const path of left.keys()) if (!right.has(path)) removed.push(path)
|
|
946
|
+
return { added, removed, changed }
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
export default renderPersona
|