@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/extract.js ADDED
@@ -0,0 +1,420 @@
1
+ import { MAX_ENTRY_BYTES, clip, scopeOf } from './store.js'
2
+ import { fromLegacyEntry } from './envelope.js'
3
+ import * as defaultRuntime from './trivium-runtime.js'
4
+ import { createBackfillScheduler, DEFAULT_BACKFILL_EVERY } from './backfill-vectors.js'
5
+ import { openCursors } from './cursor.js'
6
+ import { collectIdleSnapshots, writeIdleSnapshots } from './idle-interrupt.js'
7
+
8
+ /**
9
+ * 唯一的 retain 流水线:`retainSession(sessionId, trigger)`。
10
+ *
11
+ * 两条实时触发,职责不同:
12
+ * 1. 覆盖:`session/event` 的 `turn/end`——实测对每个实时结局(completed / max-tokens / aborted /
13
+ * blocked / error)都触发且携带 `reason`,因此它是唯一能拿到结局的实时钩子。
14
+ * 2. 排空:`agent/disposed`——不负责覆盖(`turn/end` 先触发),只把仍在飞的写入排到队尾并等待。
15
+ * 不用 `agent/turn-stopping`:实测它跑在 `turn/end` 之前,`readSession` 只看到未闭合的轮次。
16
+ *
17
+ * 游标是快速路径,条目键 `(scope, sessionId, turn)` 是正确性来源;候选集按条目键比对,
18
+ * 而不是按游标预筛——游标已越过、但条目从存储里消失的轮次必须能补回。
19
+ * 写入是「同一库路径的读-合并-插入」:门面把写串行化,`withLock` 把「读去重键 → 插入」也包成原子,
20
+ * 数据库由 `trivium-runtime.js` 的进程级注册表提供(一个库路径一个门面、一个子进程)。
21
+ * 任何路径都不抛错,绝不做 `session.append`/`steer`/`inject`。
22
+ */
23
+
24
+ let activeRetain = null
25
+ /** 排空入口:进程卸载前先等已在飞的保留写完(关闭门面之前必须调用)。 */
26
+ let drainAll = async () => undefined
27
+
28
+ /**
29
+ * 保留流水线的墙钟上限(任务 45 第 6 条):读会话日志与写两条轨道都在这个期限内,超时就放弃
30
+ * 等待并让回合继续。它不取消底层读取(`readSession` 没有 signal),只是让调用方与同一会话的
31
+ * 写入链不等一个挂住的 Promise:下一条触发会重读同一批,游标没动,重复写由条目键挡住。
32
+ */
33
+ const DEFAULT_RETAIN_TIMEOUT_MS = 5000
34
+
35
+ /** 只由恢复路径产生的结局:它们不是「完成轮次」,写进普通召回就是脏数据(任务 45 第 5 条)。 */
36
+ const UNFINISHED_REASONS = new Set(['interrupted', 'forked'])
37
+
38
+ export function activeRetainSession() {
39
+ return activeRetain
40
+ }
41
+
42
+ /** 等**已在飞**的保留(含 sweep 的按需补记)写完;不发起新的读取。 */
43
+ export async function drainRetainChain() {
44
+ return await drainAll()
45
+ }
46
+
47
+ function textOfContent(content) {
48
+ if (!Array.isArray(content)) return ''
49
+ const parts = []
50
+ for (const block of content) {
51
+ if (block?.type === 'text' && typeof block.text === 'string' && block.text.length > 0) parts.push(block.text)
52
+ }
53
+ return parts.join('\n')
54
+ }
55
+
56
+ function reasonKind(reason) {
57
+ if (typeof reason === 'string') return reason
58
+ if (reason !== null && typeof reason === 'object' && typeof reason.kind === 'string') return reason.kind
59
+ return null
60
+ }
61
+
62
+ function reasonDetail(reason) {
63
+ if (reason === null || typeof reason !== 'object') return null
64
+ try {
65
+ const json = JSON.stringify(reason)
66
+ return json.length > 256 ? `${json.slice(0, 255)}…` : json
67
+ } catch {
68
+ return null
69
+ }
70
+ }
71
+
72
+ /**
73
+ * 归约成**已闭合**的回合边界:没有配对 `turn/end` 的 `turn/start` 不产生边界,所以 `kill -9`
74
+ * 中途不会写出半截轮次。人类文本只认 `source.kind === 'user'`——插件注入的召回文本与
75
+ * runtime-context 不是人类说的话(IS-7)。
76
+ *
77
+ * blocked 回合的人类文本不在 `user/message` 里:它在 turn 开始**之前**以 `agent/inbox/spliced`
78
+ * 进入 `next-turn`,回合被拒后又被一次 `removedCount` splice 取走(实测日志顺序:spliced,
79
+ * turn/start, spliced{removedCount}, turn/end{blocked})。所以收件箱必须按其折叠语义跟随,
80
+ * 并在 `turn/start` 处拍下「这次 claim 会取走的文本」——`claim('next-turn')` 取全部 next-step
81
+ * 加 next-turn 的第一条。
82
+ */
83
+ function collectBoundaries(events) {
84
+ const boundaries = []
85
+ const pending = { 'next-turn': [], 'next-step': [] }
86
+ let open = null
87
+ for (const event of events) {
88
+ const type = event?.type
89
+ if (type === 'agent/inbox/spliced') {
90
+ const data = event.data
91
+ const target = data?.target === 'next-step' ? 'next-step' : 'next-turn'
92
+ const list = pending[target]
93
+ const start = Number.isSafeInteger(data?.start) ? Math.min(Math.max(0, data.start), list.length) : list.length
94
+ const removed = Number.isSafeInteger(data?.removedCount) ? Math.max(0, data.removedCount) : 0
95
+ pending[target] = list.toSpliced(start, removed, ...(Array.isArray(data?.inserted) ? data.inserted : []))
96
+ continue
97
+ }
98
+ if (type === 'turn/start') {
99
+ const claimed = [...pending['next-step'], ...pending['next-turn'].slice(0, 1)]
100
+ open = { turn: Number(event.data?.turn), texts: [], claimed }
101
+ continue
102
+ }
103
+ if (type === 'user/message') {
104
+ if (open !== null && event.data?.source?.kind === 'user') {
105
+ const text = textOfContent(event.data?.content)
106
+ if (text.length > 0) open.texts.push(text)
107
+ }
108
+ continue
109
+ }
110
+ if (type === 'turn/end') {
111
+ const turn = Number(event.data?.turn)
112
+ const same = open !== null && open.turn === turn
113
+ const human = same ? open.claimed.filter((message) => message?.source?.kind === 'user').map((message) => textOfContent(message?.content)).filter((text) => text.length > 0) : []
114
+ const reason = event.data?.reason
115
+ boundaries.push({
116
+ turn,
117
+ reason: reasonKind(reason),
118
+ detail: reasonDetail(reason),
119
+ texts: same && open.texts.length > 0 ? open.texts : human,
120
+ })
121
+ open = null
122
+ }
123
+ }
124
+ return boundaries
125
+ }
126
+
127
+ /**
128
+ * @param ctx - DSH 插件上下文;只读 `ctx.sessionQuery.readSession` 与 `ctx.on`。
129
+ * @param deps - `{ log?, runtime?, cursors? }`;runtime/cursors 仅供自足探针注入。
130
+ * @returns `{ retainSession }`
131
+ */
132
+ export async function registerExtract(ctx, deps = {}) {
133
+ const log = typeof deps?.log === 'function' ? deps.log : () => {}
134
+ const say = (text) => {
135
+ try {
136
+ log(text)
137
+ } catch {
138
+ }
139
+ }
140
+
141
+ const runtime = deps?.runtime ?? defaultRuntime
142
+ const cursors = deps?.cursors ?? openCursors({ log: say })
143
+ const reported = new Set()
144
+ const reportOnce = (key, text) => {
145
+ if (reported.has(key)) return
146
+ reported.add(key)
147
+ say(text)
148
+ }
149
+
150
+ const chains = new Map()
151
+
152
+ const idleTrackEnabled = deps?.idleTrack !== false
153
+
154
+ /**
155
+ * 向量回填的机会式调度(任务 50 第 2/3 条):只在回合写完、或在 `agent/disposed` 之后挂一个
156
+ * unref 定时器;真正的回填是独立 Promise + 短命子进程,回合请求一到就被抢占。
157
+ * `deps.backfill` 可整体替换(探针用),`deps.backfillEvery` 覆盖 `KANABO_MEMORY_BACKFILL_EVERY`。
158
+ */
159
+ const backfillEveryEnv = Number(process.env.KANABO_MEMORY_BACKFILL_EVERY)
160
+ const backfillEvery = Number.isFinite(deps?.backfillEvery)
161
+ ? Math.max(0, Math.floor(deps.backfillEvery))
162
+ : (Number.isFinite(backfillEveryEnv) ? Math.max(0, Math.floor(backfillEveryEnv)) : DEFAULT_BACKFILL_EVERY)
163
+ const backfill = deps?.backfill ?? createBackfillScheduler({ log: say, every: backfillEvery, run: deps?.backfillRun })
164
+ const retainTimeoutMs = Number.isFinite(deps?.retainTimeoutMs) && deps.retainTimeoutMs > 0
165
+ ? Math.floor(deps.retainTimeoutMs)
166
+ : DEFAULT_RETAIN_TIMEOUT_MS
167
+
168
+ /**
169
+ * 中断快照轨道(任务 45 第 2 条):与完成轮次轨道读同一份事件、写不同的信封。
170
+ * `trigger === 'sweep'` 才会把「没有 turn/end 的尾巴」当成 pod_gone——sweep 只访问非存活会话,
171
+ * 而 live/on-demand 触发时正在跑的回合天然没有 turn/end,写成中断就是假事实。
172
+ * 任何失败都只让本轮快照缺席,不影响完成轮次轨道、更不影响回合。
173
+ */
174
+ async function retainIdle({ id, scope, events, trigger }) {
175
+ if (!idleTrackEnabled) return { written: 0, skipped: 0, why: 'disabled' }
176
+ let collected
177
+ try {
178
+ collected = collectIdleSnapshots({ events, sessionId: id, notLive: trigger === 'sweep', now: Date.now() })
179
+ } catch (error) {
180
+ reportOnce(`idle-collect:${id}`, `extract: idle snapshot reduction failed for ${id} (${error?.message ?? String(error)}); swallowed`)
181
+ return { written: 0, skipped: 0, why: 'collect-failed' }
182
+ }
183
+ if (collected.snapshots.length === 0) return { written: 0, skipped: 0, why: 'no-interrupt' }
184
+ const result = await writeIdleSnapshots({
185
+ runtime,
186
+ scope,
187
+ sessionId: id,
188
+ snapshots: collected.snapshots,
189
+ now: Date.now(),
190
+ })
191
+ if (result.written > 0) {
192
+ say(`extract: recorded ${result.written} idle-interrupt snapshot(s) for ${id} (${collected.degraded ? 'surface degraded' : 'surface compacted'})`)
193
+ } else if (result.why !== 'already-recorded' && result.why !== 'nothing-to-write') {
194
+ reportOnce(`idle-write:${id}`, `extract: idle-interrupt snapshot not recorded for ${id} (${result.why}${result.code === null || result.code === undefined ? '' : `: ${result.code}`}); the turn continues`)
195
+ }
196
+ return result
197
+ }
198
+
199
+ async function retainInner(sessionId, trigger) {
200
+ const id = String(sessionId)
201
+ try {
202
+ const query = ctx?.sessionQuery
203
+ if (query === undefined || typeof query.readSession !== 'function') return { ok: false, written: 0, why: 'no-session-query' }
204
+
205
+ let snapshot
206
+ try {
207
+ snapshot = await query.readSession(id)
208
+ } catch (error) {
209
+ // 读失败时游标一格不动:下次触发会重试同一批次;绝不从这里抛出(IS-5)。
210
+ reportOnce(`read:${id}`, `extract: readSession failed for ${id} (${error?.message ?? String(error)}); cursor unchanged`)
211
+ return { ok: false, written: 0, why: 'read-failed' }
212
+ }
213
+
214
+ const header = snapshot?.session
215
+ if (header?.origin === 'subagent' || Number(header?.delegationDepth ?? 0) > 0) return { ok: true, written: 0, why: 'subagent' }
216
+
217
+ const all = Array.isArray(snapshot?.events) ? snapshot.events : []
218
+ // seeded(fork)子会话在 inheritedEventCount 之前是父会话的事件,绝不重复归约。
219
+ const events = all.slice(Number(snapshot?.inheritedEventCount ?? 0))
220
+ const scope = scopeOf({ header })
221
+ const boundaries = collectBoundaries(events)
222
+ // 中断快照先写:尾巴没有 turn/end 时 boundaries 为空,早退会把它整个漏掉。
223
+ const idle = events.length === 0 ? { written: 0, skipped: 0, why: 'empty' } : await retainIdle({ id, scope, events, trigger })
224
+ if (boundaries.length === 0) return { ok: true, written: 0, why: 'no-closed-turn', idle }
225
+
226
+ const cursor = cursors.get(id)
227
+ const turnCursor = boundaries.reduce((max, b) => (Number.isFinite(b.turn) ? Math.max(max, b.turn) : max), cursor.turnCursor)
228
+ // 候选集由**条目键**决定,游标不再是跳过判据:游标已越过、但条目因并发丢写或崩溃而从存储里
229
+ // 消失的轮次必须能补回(IS-16)。是否已保留由 `seen` 按 `(sessionId, turn)` 判定。
230
+ // 未完成结局(interrupted / forked)不进完成轮次轨道:它们的事实由 idle 快照承载。
231
+ const candidates = boundaries.filter((b) => Number.isFinite(b.turn) && b.texts.length > 0 && !UNFINISHED_REASONS.has(b.reason))
232
+
233
+ let written = 0
234
+ let backed = 'trivium'
235
+ let quota = null
236
+ if (candidates.length > 0) {
237
+ /** 一次尝试:读到当前账本 → 按条目键去重 → 配额检查 → 一次 batch 插入。重试即重读,天然幂等。 */
238
+ const merge = async () => {
239
+ const scan = await runtime.scanWorkspace(scope)
240
+ // 只有 retainSession 写下的轮次记录才占用 (sessionId, turn) 键:它们一定带 origin
241
+ // (live / sweep / on-demand)。工具写入的条目(reason:'remember'、无 origin)带着当前
242
+ // turn 只为身份与排错,不是「该轮已保留」的证据;若把它们也算进来,任何调用过 remember
243
+ // 的回合都会被视为已保留,人类原文永远进不了存储(F2 B1 实测的丢记忆)。
244
+ const seen = new Set(
245
+ scan.entries
246
+ .filter((entry) => typeof entry.origin === 'string' && entry.origin.length > 0)
247
+ .map((entry) => `${entry.sessionId}\u0000${entry.turn}`),
248
+ )
249
+ const pending = []
250
+ let incomingBytes = 0
251
+ for (const boundary of candidates) {
252
+ const key = `${id}\u0000${boundary.turn}`
253
+ if (seen.has(key)) continue
254
+ const text = clip(boundary.texts.join('\n').trim(), MAX_ENTRY_BYTES)
255
+ if (text.length === 0) continue
256
+ seen.add(key)
257
+ pending.push(fromLegacyEntry({
258
+ id: runtime.entryId(),
259
+ sessionId: id,
260
+ scope,
261
+ turn: boundary.turn,
262
+ reason: boundary.reason ?? undefined,
263
+ topic: '',
264
+ text,
265
+ ts: Date.now(),
266
+ bytes: Buffer.byteLength(text, 'utf8'),
267
+ origin: trigger,
268
+ reasonDetail: boundary.detail ?? undefined,
269
+ }))
270
+ incomingBytes += Buffer.byteLength(text, 'utf8')
271
+ }
272
+ if (pending.length === 0) return 0
273
+ runtime.assertQuota({ count: scan.count, bytes: scan.bytes }, { entries: pending.length, bytes: incomingBytes })
274
+ const appended = await runtime.appendEnvelopes(scope, pending)
275
+ if (appended?.edges?.error !== undefined) {
276
+ // 节点已经落盘,边写失败只让图臂暂时缺这条关系;下一次同会话写入会 upsert 回来。
277
+ reportOnce(`edges:${id}`, `extract: session edge write failed for ${id} (${appended.edges.error.code}); entries kept, edges retried on the next write`)
278
+ }
279
+ return pending.length
280
+ }
281
+ for (let attempt = 0; attempt < 2; attempt += 1) {
282
+ try {
283
+ written = await runtime.withLock(scope, merge)
284
+ quota = null
285
+ break
286
+ } catch (error) {
287
+ if (typeof error?.code === 'string' && error.code.startsWith('KANABO_MEMORY_QUOTA')) {
288
+ // 配额是准入控制:本轮记忆没写进去,但回合与进程都照常;不重试(重试必然同样超限)。
289
+ quota = error
290
+ break
291
+ }
292
+ if (attempt === 0) {
293
+ say(`extract: write attempt failed for ${id} (${error?.code ?? 'error'}: ${error?.message ?? String(error)}); retrying once`)
294
+ continue
295
+ }
296
+ reportOnce(`write:${id}`, `extract: write failed for ${id} (${error?.message ?? String(error)}); cursor unchanged`)
297
+ return { ok: false, written: 0, why: 'write-failed', code: error?.code ?? null }
298
+ }
299
+ }
300
+ if (quota !== null) {
301
+ reportOnce(`quota:${id}`, `extract: ${quota.code} for ${id}; the turn continues and ${candidates.length} turn(s) were not retained`)
302
+ return { ok: false, written: 0, why: 'quota', code: quota.code, details: quota.details ?? null }
303
+ }
304
+ }
305
+
306
+ // 回填只在写完、且不在本回合的临界路径里被「安排」:noteWrite 只累加计数并挂 unref 定时器。
307
+ const writtenNow = written + Number(idle?.written ?? 0)
308
+ if (writtenNow > 0) backfill.noteWrite(scope, writtenNow)
309
+
310
+ // 条目没落盘时游标也不能落盘:否则下一个进程会永久跳过这些轮次。
311
+ if (scope !== cursor.scope || turnCursor > cursor.turnCursor || all.length > cursor.seqCursor) {
312
+ cursors.advance(id, { scope, turnCursor, seqCursor: all.length, lastRetainAt: Date.now() }, { persist: true })
313
+ }
314
+ return { ok: true, written, backed, why: written > 0 ? `retained-${backed}` : 'up-to-date', idle }
315
+ } catch (error) {
316
+ reportOnce(`retain:${id}`, `extract: retain failed for ${id} (${error?.message ?? String(error)}); swallowed`)
317
+ return { ok: false, written: 0, why: 'threw' }
318
+ }
319
+ }
320
+
321
+ /** 墙钟上限:超时只放弃等待,返回结构化结局;底层 Promise 自己 settle,不会变成未处理拒绝。 */
322
+ function bounded(work, sessionId) {
323
+ if (!(retainTimeoutMs > 0)) return work
324
+ let timer
325
+ const expiry = new Promise((resolveBound) => {
326
+ timer = setTimeout(() => {
327
+ reportOnce(`timeout:${sessionId}`, `extract: retain for ${sessionId} exceeded ${retainTimeoutMs} ms; abandoned without blocking the turn (the next trigger retries)`)
328
+ resolveBound({ ok: false, written: 0, why: 'timeout' })
329
+ }, retainTimeoutMs)
330
+ if (typeof timer?.unref === 'function') timer.unref()
331
+ })
332
+ return Promise.race([work, expiry]).finally(() => {
333
+ try {
334
+ clearTimeout(timer)
335
+ } catch {
336
+ }
337
+ })
338
+ }
339
+
340
+ async function retainOnce(sessionId, trigger) {
341
+ const id = String(sessionId)
342
+ return await bounded(retainInner(id, trigger), id)
343
+ }
344
+
345
+ function enqueue(sessionId, trigger) {
346
+ const id = String(sessionId)
347
+ const previous = chains.get(id) ?? Promise.resolve()
348
+ const next = previous.then(() => retainOnce(id, trigger), () => retainOnce(id, trigger))
349
+ chains.set(id, next)
350
+ const settle = () => {
351
+ if (chains.get(id) === next) chains.delete(id)
352
+ }
353
+ next.then(settle, settle)
354
+ return next
355
+ }
356
+
357
+ const retainSession = (sessionId, trigger = 'live') => enqueue(sessionId, trigger)
358
+
359
+ /**
360
+ * 排空:只等**已在进行**的写入,不发起新的读取。`agent/disposed` 运行时 agent scope 正在拆除,
361
+ * 此刻 `readSession` 会抛 `cannot get required service "sessions" in inactive context`(实测);
362
+ * 覆盖已经由先触发的 `turn/end` 完成,这里再读一遍只会多一条无意义的警告。
363
+ */
364
+ const drain = async (sessionId) => {
365
+ for (let round = 0; round < 8; round += 1) {
366
+ const inFlight = chains.get(String(sessionId))
367
+ if (inFlight === undefined) return
368
+ await inFlight.then(() => undefined, () => undefined)
369
+ if (chains.get(String(sessionId)) === undefined) return
370
+ }
371
+ }
372
+
373
+ if (typeof ctx?.on === 'function') {
374
+ try {
375
+ ctx.on('session/event', (session, event) => {
376
+ try {
377
+ if (event?.type !== 'turn/end') return
378
+ const id = session?.id
379
+ if (typeof id !== 'string' || id.length === 0) return
380
+ void retainSession(id, 'live').catch(() => {})
381
+ } catch (error) {
382
+ say(`extract: turn/end handler failed (${error?.message ?? String(error)}); swallowed`)
383
+ }
384
+ })
385
+ } catch (error) {
386
+ say(`extract: cannot listen to session/event (${error?.message ?? String(error)})`)
387
+ }
388
+ try {
389
+ ctx.on('agent/disposed', (payload) => {
390
+ try {
391
+ const id = payload?.agent?.session?.id
392
+ if (typeof id !== 'string' || id.length === 0) return undefined
393
+ return drain(id).then(() => {
394
+ try {
395
+ backfill.noteIdle(scopeOf(payload?.agent?.session))
396
+ } catch {
397
+ }
398
+ })
399
+ } catch (error) {
400
+ say(`extract: agent/disposed handler failed (${error?.message ?? String(error)}); swallowed`)
401
+ return undefined
402
+ }
403
+ })
404
+ } catch (error) {
405
+ say(`extract: cannot listen to agent/disposed (${error?.message ?? String(error)})`)
406
+ }
407
+ }
408
+
409
+ activeRetain = retainSession
410
+ drainAll = async () => {
411
+ // 关闭前先停调度:已在跑的回填由 runtime.close() 抢占(它不该拖慢卸载)。
412
+ backfill.stop()
413
+ for (let round = 0; round < 16; round += 1) {
414
+ const pending = [...chains.values()]
415
+ if (pending.length === 0) return
416
+ await Promise.all(pending.map((task) => task.then(() => undefined, () => undefined)))
417
+ }
418
+ }
419
+ return { retainSession, backfill }
420
+ }