@onigeya/dsh-kanabo-memory 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/envelope.js ADDED
@@ -0,0 +1,368 @@
1
+ import {
2
+ COMMON_FIELDS,
3
+ CONVERSATION_ROLES,
4
+ EDGE_FIELDS,
5
+ EDGE_LABELS,
6
+ EVIDENCE_KINDS,
7
+ EVIDENCE_TRACE_FIELDS,
8
+ IDLE_PATHS,
9
+ OPTIONAL_COMMON_FIELDS,
10
+ REQUIRED_TYPE_FIELDS,
11
+ SESSION_FIELDS,
12
+ SOURCE_TYPES,
13
+ TURN_UNATTRIBUTED,
14
+ TYPE_FIELDS,
15
+ } from './contract.js'
16
+
17
+ /**
18
+ * 记忆信封(Memory Envelope)的唯一写契约实现:校验 + 旧 JSON 条目的映射。
19
+ *
20
+ * 字段名、枚举与版本全部来自 `./contract.js`(vision 唯一可依赖的模块),本文件只依赖它,
21
+ * 绝不 import store/extract/tools——因此「校验口径」与「跨包可见的字段名」不会漂移。
22
+ *
23
+ * `validateEnvelope` 是纯函数:不修改入参、不做 I/O,合法时原样返回该对象,非法时抛出
24
+ * `code` 为 `KANABO_ENVELOPE_*`、并带 `field`(字段路径)的结构化错误,与 store.js/tools.js
25
+ * 的 `KANABO_*` 约定一致。
26
+ */
27
+
28
+ const COMMON_ALLOWED = new Set([...COMMON_FIELDS, ...OPTIONAL_COMMON_FIELDS])
29
+ const TYPE_ALLOWED = new Map(SOURCE_TYPES.map((type) => [type, new Set(TYPE_FIELDS[type])]))
30
+
31
+ function envelopeError(code, message, extra) {
32
+ const error = new Error(message)
33
+ error.code = code
34
+ if (extra !== undefined) Object.assign(error, extra)
35
+ return error
36
+ }
37
+
38
+ function isPlainObject(value) {
39
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
40
+ const proto = Object.getPrototypeOf(value)
41
+ return proto === Object.prototype || proto === null
42
+ }
43
+
44
+ function isJsonValue(value, depth = 0) {
45
+ if (depth > 32) return false
46
+ if (value === null) return true
47
+ const kind = typeof value
48
+ if (kind === 'string' || kind === 'boolean') return true
49
+ if (kind === 'number') return Number.isFinite(value)
50
+ if (Array.isArray(value)) return value.every((item) => isJsonValue(item, depth + 1))
51
+ if (kind === 'object' && isPlainObject(value)) {
52
+ return Object.values(value).every((item) => isJsonValue(item, depth + 1))
53
+ }
54
+ return false
55
+ }
56
+
57
+ function received(value) {
58
+ if (value === undefined) return 'undefined'
59
+ if (typeof value === 'number' && !Number.isFinite(value)) return String(value)
60
+ try {
61
+ const json = JSON.stringify(value)
62
+ if (typeof json !== 'string') return typeof value
63
+ return json.length > 120 ? `${json.slice(0, 119)}…` : json
64
+ } catch {
65
+ return typeof value
66
+ }
67
+ }
68
+
69
+ function failMissing(field, type) {
70
+ const where = type === undefined ? 'envelope' : `${type} 信封`
71
+ throw envelopeError(
72
+ 'KANABO_ENVELOPE_MISSING_FIELD',
73
+ `${where}: 缺少必需字段 "${field}"。`,
74
+ { field })
75
+ }
76
+
77
+ function failType(field, expected, value) {
78
+ throw envelopeError(
79
+ 'KANABO_ENVELOPE_FIELD_TYPE',
80
+ `envelope: 字段 "${field}" 期望 ${expected},收到 ${received(value)}。`,
81
+ { field, expected, received: received(value) })
82
+ }
83
+
84
+ function failValue(field, expected, value) {
85
+ throw envelopeError(
86
+ 'KANABO_ENVELOPE_FIELD_VALUE',
87
+ `envelope: 字段 "${field}" 取值非法(期望 ${expected},收到 ${received(value)})。`,
88
+ { field, expected, received: received(value) })
89
+ }
90
+
91
+ function failUnknown(field) {
92
+ throw envelopeError(
93
+ 'KANABO_ENVELOPE_UNKNOWN_FIELD',
94
+ `envelope: 未知字段 "${field}";扩展数据请放进 node_metadata 或边 metadata,而不是新增顶层键。`,
95
+ { field })
96
+ }
97
+
98
+ function assertKnownFields(object, allowed, prefix) {
99
+ for (const key of Object.keys(object)) {
100
+ if (!allowed.has(key)) failUnknown(prefix === '' ? key : `${prefix}.${key}`)
101
+ }
102
+ }
103
+
104
+ function assertJsonObject(value, field) {
105
+ if (!isPlainObject(value)) failType(field, 'object', value)
106
+ if (!isJsonValue(value)) failValue(field, '可 JSON 序列化的对象', value)
107
+ }
108
+
109
+ function assertOptionalString(value, field) {
110
+ if (value !== undefined && typeof value !== 'string') failType(field, 'string', value)
111
+ }
112
+
113
+ function assertNonEmptyString(value, field) {
114
+ if (typeof value !== 'string') failType(field, 'string', value)
115
+ if (value.length === 0) failValue(field, '非空字符串', value)
116
+ }
117
+
118
+ function validateSession(session) {
119
+ if (!isPlainObject(session)) failType('session', 'object', session)
120
+ assertKnownFields(session, new Set(SESSION_FIELDS), 'session')
121
+ if (session.id === undefined) failMissing('session.id')
122
+ assertNonEmptyString(session.id, 'session.id')
123
+ assertOptionalString(session.scope, 'session.scope')
124
+ }
125
+
126
+ function validateEvidenceTrace(trace, field) {
127
+ if (!isPlainObject(trace)) failType(field, 'object', trace)
128
+ assertKnownFields(trace, new Set(EVIDENCE_TRACE_FIELDS), field)
129
+ if (trace.kind === undefined) failMissing(`${field}.kind`)
130
+ if (typeof trace.kind !== 'string' || !EVIDENCE_KINDS.includes(trace.kind)) {
131
+ failValue(`${field}.kind`, EVIDENCE_KINDS.join(' | '), trace.kind)
132
+ }
133
+ assertOptionalString(trace.source, `${field}.source`)
134
+ if (trace.detail !== undefined && !isJsonValue(trace.detail)) {
135
+ failValue(`${field}.detail`, '可 JSON 序列化的值', trace.detail)
136
+ }
137
+ }
138
+
139
+ function validateEdge(edge, index) {
140
+ const at = `dynamic_relations[${index}]`
141
+ if (!isPlainObject(edge)) failType(at, 'object', edge)
142
+ assertKnownFields(edge, new Set(EDGE_FIELDS), at)
143
+ if (edge.label === undefined) failMissing(`${at}.label`)
144
+ if (typeof edge.label !== 'string' || !EDGE_LABELS.includes(edge.label)) {
145
+ failValue(`${at}.label`, EDGE_LABELS.join(' | '), edge.label)
146
+ }
147
+ if (edge.target === undefined) failMissing(`${at}.target`)
148
+ assertNonEmptyString(edge.target, `${at}.target`)
149
+ if (edge.weight !== undefined) {
150
+ if (typeof edge.weight !== 'number' || !Number.isFinite(edge.weight)
151
+ || edge.weight < 0 || edge.weight > 1) {
152
+ failValue(`${at}.weight`, '0..1 之间的有限数', edge.weight)
153
+ }
154
+ }
155
+ if (edge.metadata !== undefined) assertJsonObject(edge.metadata, `${at}.metadata`)
156
+ if (edge.evidence_trace !== undefined) validateEvidenceTrace(edge.evidence_trace, `${at}.evidence_trace`)
157
+ }
158
+
159
+ function validateSpan(input) {
160
+ const pairs = [['t0', input.t0], ['t1', input.t1]]
161
+ for (const [field, value] of pairs) {
162
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
163
+ failValue(field, '≥ 0 的有限毫秒数', value)
164
+ }
165
+ }
166
+ if (!(input.t1 > input.t0)) failValue('t1', `> t0(t0=${input.t0})`, input.t1)
167
+ }
168
+
169
+ function validateTypeFields(input, type) {
170
+ if (type === 'CONVERSATION') {
171
+ if (typeof input.text !== 'string') failType('text', 'string', input.text)
172
+ if (input.text.trim().length === 0) failValue('text', '非空白字符串', input.text)
173
+ if (input.role !== undefined && !CONVERSATION_ROLES.includes(input.role)) {
174
+ failValue('role', CONVERSATION_ROLES.join(' | '), input.role)
175
+ }
176
+ assertOptionalString(input.topic, 'topic')
177
+ if (input.reason !== undefined && input.reason !== null) assertOptionalString(input.reason, 'reason')
178
+ assertOptionalString(input.origin, 'origin')
179
+ return
180
+ }
181
+
182
+ if (type === 'TOOL_TRACE') {
183
+ assertNonEmptyString(input.tool_name, 'tool_name')
184
+ assertOptionalString(input.tool_call_id, 'tool_call_id')
185
+ if (input.args !== undefined) assertJsonObject(input.args, 'args')
186
+ if (input.result !== undefined && !isJsonValue(input.result)) {
187
+ failValue('result', '可 JSON 序列化的值', input.result)
188
+ }
189
+ assertOptionalString(input.error, 'error')
190
+ if (input.duration_ms !== undefined) {
191
+ const value = input.duration_ms
192
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
193
+ failValue('duration_ms', '≥ 0 的有限数', value)
194
+ }
195
+ }
196
+ return
197
+ }
198
+
199
+ if (type === 'VIDEO_CLIP') {
200
+ assertNonEmptyString(input.video_id, 'video_id')
201
+ validateSpan(input)
202
+ for (const field of ['frame_id', 'app', 'activity', 'scene_description', 'keyframe_path']) {
203
+ assertOptionalString(input[field], field)
204
+ }
205
+ return
206
+ }
207
+
208
+ if (type === 'AUDIO_SEGMENT') {
209
+ assertNonEmptyString(input.audio_id, 'audio_id')
210
+ validateSpan(input)
211
+ for (const field of ['text', 'speaker', 'stem']) assertOptionalString(input[field], field)
212
+ return
213
+ }
214
+
215
+ if (input.incomplete !== true) {
216
+ throw envelopeError(
217
+ 'KANABO_ENVELOPE_IDLE_INCOMPLETE',
218
+ `envelope: IDLE_INTERRUPT 必须携带 incomplete: true(收到 ${received(input.incomplete)})。`,
219
+ { field: 'incomplete', expected: true, received: received(input.incomplete) })
220
+ }
221
+ if (typeof input.idlePath !== 'string' || !IDLE_PATHS.includes(input.idlePath)) {
222
+ throw envelopeError(
223
+ 'KANABO_ENVELOPE_IDLE_PATH',
224
+ `envelope: IDLE_INTERRUPT 的 idlePath 必须是 [${IDLE_PATHS.join(', ')}] 之一(收到 ${received(input.idlePath)})。`,
225
+ { field: 'idlePath', expected: IDLE_PATHS.join(' | '), received: received(input.idlePath) })
226
+ }
227
+ assertOptionalString(input.last_event, 'last_event')
228
+ if (input.pending_intent !== undefined) assertJsonObject(input.pending_intent, 'pending_intent')
229
+ if (input.snapshot !== undefined) assertJsonObject(input.snapshot, 'snapshot')
230
+ if (input.resume_cursor !== undefined) {
231
+ assertJsonObject(input.resume_cursor, 'resume_cursor')
232
+ // 恢复锚点:seq 是唯一能从日志重定位的值,错类型等于快照不可用,必须在写入前就拒绝。
233
+ if (!Number.isSafeInteger(input.resume_cursor.seq) || input.resume_cursor.seq < 0) {
234
+ failValue('resume_cursor.seq', '≥ 0 的安全整数(事件 seq)', input.resume_cursor.seq)
235
+ }
236
+ }
237
+ }
238
+
239
+ export function validateEnvelope(input) {
240
+ if (!isPlainObject(input)) {
241
+ throw envelopeError('KANABO_ENVELOPE_INPUT', `envelope: 入参必须是普通对象(收到 ${received(input)})。`,
242
+ { expected: 'object', received: received(input) })
243
+ }
244
+ const type = input.source_type
245
+ if (type === undefined) failMissing('source_type')
246
+ if (typeof type !== 'string' || !SOURCE_TYPES.includes(type)) {
247
+ failValue('source_type', SOURCE_TYPES.join(' | '), type)
248
+ }
249
+ assertKnownFields(input, new Set([...COMMON_ALLOWED, ...TYPE_ALLOWED.get(type)]), '')
250
+
251
+ for (const field of COMMON_FIELDS) {
252
+ if (input[field] === undefined) failMissing(field, type)
253
+ }
254
+ assertNonEmptyString(input.id, 'id')
255
+ if (!Number.isSafeInteger(input.turn) || input.turn < 0) {
256
+ failValue('turn', '≥ 0 的安全整数(0 = 无可归因轮次)', input.turn)
257
+ }
258
+ if (!Number.isSafeInteger(input.ts) || input.ts < 0) failValue('ts', '≥ 0 的安全整数毫秒时间戳', input.ts)
259
+ validateSession(input.session)
260
+ validateEvidenceTrace(input.evidence_trace, 'evidence_trace')
261
+ assertJsonObject(input.node_metadata, 'node_metadata')
262
+ if (!Array.isArray(input.dynamic_relations)) failType('dynamic_relations', 'array', input.dynamic_relations)
263
+ input.dynamic_relations.forEach(validateEdge)
264
+
265
+ if (input.vector_embedding !== undefined && input.vector_embedding !== null) {
266
+ const vector = input.vector_embedding
267
+ if (!Array.isArray(vector) || vector.length === 0) {
268
+ failValue('vector_embedding', '非空的有限数数组或 null', vector)
269
+ }
270
+ for (const item of vector) {
271
+ if (typeof item !== 'number' || !Number.isFinite(item)) {
272
+ failValue('vector_embedding', '全部为有限数的非空数组', item)
273
+ }
274
+ }
275
+ }
276
+
277
+ if (type !== 'IDLE_INTERRUPT') {
278
+ for (const field of REQUIRED_TYPE_FIELDS[type]) {
279
+ if (input[field] === undefined) failMissing(field, type)
280
+ }
281
+ }
282
+ validateTypeFields(input, type)
283
+ return input
284
+ }
285
+
286
+ /**
287
+ * 旧 JSON 条目 → 信封的唯一映射(任务 13 的迁移只允许调用这里,不得另写一份)。
288
+ *
289
+ * | 旧字段(store.js/addEntry 产出的形状) | 信封字段 |
290
+ * | --- | --- |
291
+ * | `id` | `id`(缺失/空串 → `KANABO_ENVELOPE_LEGACY_ID`) |
292
+ * | `sessionId` | `session.id`(缺失 → `KANABO_ENVELOPE_LEGACY_NO_SESSION`,绝不编造会话归属) |
293
+ * | `scope` | `session.scope` 与 `node_metadata.scope` |
294
+ * | `turn`(可能为 null) | `turn`(null → `TURN_UNATTRIBUTED` = 0,并在 `node_metadata.turn_attribution` 标注) |
295
+ * | `ts` / `bytes` / `topic` | `ts` / `node_metadata.bytes` / `node_metadata.topic` |
296
+ * | `text`(为空时退回 `topic`,与 store.textOf 同口径) | `CONVERSATION.text` |
297
+ * | `reason` / `origin` | 同名字段;`origin` 在场时证据为 EXTRACTED,否则 INFERRED(无法证明来自日志直读) |
298
+ * | `reasonDetail` | `evidence_trace.detail.reason_detail` |
299
+ * | `(sessionId)` | `dynamic_relations: [{ label: 'belongs_to_session', target: sessionId }]` |
300
+ *
301
+ * 纯函数:不读盘、不取当前时间;映射结果再过一遍 `validateEnvelope`,保证迁移写出的就是
302
+ * 契约接受的信封。
303
+ */
304
+ export function fromLegacyEntry(entry) {
305
+ if (!isPlainObject(entry)) {
306
+ throw envelopeError('KANABO_ENVELOPE_LEGACY_ENTRY',
307
+ `fromLegacyEntry: 入参必须是普通对象(收到 ${received(entry)})。`, { expected: 'object' })
308
+ }
309
+ const { id } = entry
310
+ if (typeof id !== 'string' || id.length === 0) {
311
+ throw envelopeError('KANABO_ENVELOPE_LEGACY_ID',
312
+ `fromLegacyEntry: 旧条目缺少非空字符串 id(收到 ${received(id)});迁移无法为它保留稳定身份。`,
313
+ { field: 'id', received: received(id) })
314
+ }
315
+ const { sessionId } = entry
316
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
317
+ throw envelopeError('KANABO_ENVELOPE_LEGACY_NO_SESSION',
318
+ `fromLegacyEntry: 旧条目 ${id} 没有 sessionId;信封不允许省略会话归属,请补齐或单独报告该条目。`,
319
+ { field: 'sessionId', entryId: id })
320
+ }
321
+ if (!Number.isSafeInteger(entry.ts) || entry.ts < 0) {
322
+ throw envelopeError('KANABO_ENVELOPE_LEGACY_TS',
323
+ `fromLegacyEntry: 旧条目 ${id} 的 ts 不是 ≥ 0 的安全整数(收到 ${received(entry.ts)})。`,
324
+ { field: 'ts', entryId: id, received: received(entry.ts) })
325
+ }
326
+ const topic = typeof entry.topic === 'string' ? entry.topic : ''
327
+ const text = typeof entry.text === 'string' && entry.text.trim().length > 0 ? entry.text : topic
328
+ if (text.trim().length === 0) {
329
+ throw envelopeError('KANABO_ENVELOPE_LEGACY_TEXT',
330
+ `fromLegacyEntry: 旧条目 ${id} 的 text 与 topic 都为空,无法生成 CONVERSATION 信封。`,
331
+ { field: 'text', entryId: id })
332
+ }
333
+
334
+ const turnAttributed = Number.isSafeInteger(entry.turn) && entry.turn >= 0
335
+ const origin = typeof entry.origin === 'string' && entry.origin.length > 0 ? entry.origin : undefined
336
+ const reason = typeof entry.reason === 'string' ? entry.reason : undefined
337
+ const reasonDetail = typeof entry.reasonDetail === 'string' ? entry.reasonDetail : null
338
+ const scope = typeof entry.scope === 'string' && entry.scope.length > 0 ? entry.scope : undefined
339
+
340
+ const envelope = {
341
+ id,
342
+ source_type: 'CONVERSATION',
343
+ session: scope === undefined ? { id: sessionId } : { id: sessionId, scope },
344
+ turn: turnAttributed ? entry.turn : TURN_UNATTRIBUTED,
345
+ ts: entry.ts,
346
+ evidence_trace: {
347
+ kind: origin === undefined ? 'INFERRED' : 'EXTRACTED',
348
+ source: 'legacy-json-v1',
349
+ detail: { reason_detail: reasonDetail },
350
+ },
351
+ node_metadata: {
352
+ topic,
353
+ scope: scope ?? null,
354
+ bytes: Number.isSafeInteger(entry.bytes) && entry.bytes >= 0 ? entry.bytes : Buffer.byteLength(text, 'utf8'),
355
+ turn_attribution: turnAttributed ? 'recorded' : 'unattributed',
356
+ },
357
+ dynamic_relations: [{
358
+ label: 'belongs_to_session',
359
+ target: sessionId,
360
+ weight: 1,
361
+ evidence_trace: { kind: 'EXTRACTED', source: 'legacy-json-v1' },
362
+ }],
363
+ }
364
+ if (reason !== undefined) envelope.reason = reason
365
+ if (origin !== undefined) envelope.origin = origin
366
+ envelope.text = text
367
+ return validateEnvelope(envelope)
368
+ }