@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.
@@ -0,0 +1,922 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { IDLE_PATHS } from './contract.js'
3
+ import { validateEnvelope } from './envelope.js'
4
+
5
+ /**
6
+ * idle 中断补抽轨道(平台计划 todo 45 / IS-20):把 extract.js 从「只归约已闭合轮次」扩成双轨。
7
+ *
8
+ * 轨道一(完成轮次)仍然由 `extract.js#collectBoundaries` 归约,行为与改造前逐字一致——本文件
9
+ * 一个字节都不碰它。轨道二(本文件)回答另一个问题:**这一轮没有干净结束,它留下了什么事实?**
10
+ * 输入是同一份 `readSession` 事件数组,输出是一条条 `IDLE_INTERRUPT` 信封。
11
+ *
12
+ * ## 为什么必须有第二条轨道
13
+ * 冷读(`session-query` 的 `readSession`)会给尾部未闭合的轮次**补一条内存里的
14
+ * `turn/end { reason: { kind: 'interrupted' } }`**(`packages/session-query/session-query/src/cold-read.ts`)。
15
+ * 于是「kill -9 的尾巴」在事件流里看起来像一条闭合轮次,旧代码会把它当完成轮次写进普通召回——
16
+ * 这正是要修的东西:未完成轮次绝不能伪装成完成轮次(否则普通召回被半截对话污染)。本文件的
17
+ * 判据是 `interrupted` / `forked` 两个**只由恢复路径产生**的结局标记,加上真正没有 `turn/end`
18
+ * 的尾巴,两者都不进完成轮次轨道。
19
+ *
20
+ * ## 归约为什么优先用「压紧后的视图」
21
+ * 上下文压紧会在日志里写一条 `surfaceOp: { op: 'replace', startSeq, endSeq }`:它把一段已经被
22
+ * 模型看过的节点换成一条摘要节点。按 seq 顺序硬扫会同时看到「被换掉的旧节点」和「摘要节点」,
23
+ * 于是同一条事实出现两次、顺序还错位。`deriveMessages()` 的做法是走 surface 的节点序列,而
24
+ * `sessionQuery.readSession` 只给裸事件数组(拿不到 `Session` 实例),所以这里按
25
+ * `packages/core/session/src/surface.ts` 的同一语义做一遍只读复算:append 追加节点,replace 用
26
+ * 摘要节点顶掉被替换区间,被顶掉的节点从视图里删除,摘要节点落在区间起点。复算**绝不抛错**:
27
+ * 标记畸形或区间找不到时降级为裸 seq 顺序,并把这个降级写进快照(`surface.mode = 'raw'`)。
28
+ *
29
+ * ## 为什么不给快照写正文
30
+ * 规格(`contract.js`)里 `IDLE_INTERRUPT` 没有 `text` 必填项,本文件也**故意不写 text**:
31
+ * 文本臂(TQL BM25)与向量臂只认写入时建过索引的文本/向量,图臂只从文本/向量命中扩散,
32
+ * 所以「没有正文」= 普通召回结构上不可能把它捞出来。事实全部落在结构化字段
33
+ * (`pending_intent` / `snapshot` / `resume_cursor`)里,专用读取入口是本文件的
34
+ * `readIdleSnapshots()`。这也是「两条轨道在存储里可区分」的第二重保证:第一重是
35
+ * `source_type` + `incomplete`。
36
+ *
37
+ * ## 事实只从结构化事件读
38
+ * 不存模型自报的「我已完成」:待审批动作取自 `tool/call` 与 `approval/asked`,问题规格取自
39
+ * `ask_user_question` 的 `tool/call.arguments`,目标快照取自 `goal/change`(完整 GoalSnapshot),
40
+ * 工具参数 Schema 取自最近一次 `request/header` 的 `tools`,权限旋钮取自
41
+ * `permission/preset` / `sandbox/mode` / `approval/policy`,错误取自 `turn/end.reason` /
42
+ * `tool/result.error` / `llm/retry.failure`。派生字段(风险等级、幂等键、no-progress 判定)显式
43
+ * 标注 `source: 'derived'`,其 `evidence_trace.kind` 在只有派生信号时降为 `INFERRED`。
44
+ */
45
+
46
+ export const MAX_SNAPSHOTS_PER_SCAN = 8
47
+
48
+ /**
49
+ * 同一轮出现多个信号时取哪一个 `idlePath`:越靠前越具体、越可执行。
50
+ * 顺序理由:待人回答 > 待人批准 > 已被拒 > 压紧失败 > 预算 > 死循环 > 策略阻断 > 工具崩溃 >
51
+ * 模型错误 > 主动取消 > Pod 蒸发。`pod_gone` 永远兜底,因为它是最不具体的解释。
52
+ */
53
+ export const IDLE_PRIORITY = Object.freeze([
54
+ 'question_wait',
55
+ 'approval_wait',
56
+ 'rejected',
57
+ 'compaction_failed',
58
+ 'budget',
59
+ 'no_progress',
60
+ 'guardrail',
61
+ 'tool_crash',
62
+ 'llm_error',
63
+ 'aborted',
64
+ 'pod_gone',
65
+ ])
66
+
67
+ /** 只由恢复路径产生的 `turn/end.reason.kind`:它们标记「这一轮没有干净结束」。 */
68
+ const NON_COMPLETION_REASONS = Object.freeze(['interrupted', 'forked'])
69
+
70
+ /** 预算类 LLM 失败码(账户额度/配额)——与 `packages/llm/llm/src/error.ts` 的字面量一致。 */
71
+ const BUDGET_CODES = Object.freeze(['QUOTA', 'ACCOUNT_QUOTA', 'CONTEXT_WINDOW_EXCEEDED'])
72
+
73
+ /** 策略/安全类失败码:工具被策略层拒绝派发(INVALID_ARGS 是报告 §3.2.3 的例子)。 */
74
+ const GUARDRAIL_CODES = Object.freeze(['INVALID_ARGS', 'EGRESS_DENIED', 'EGRESS_BLOCKED', 'POLICY_DENIED', 'SANDBOX_DENIED'])
75
+
76
+ const COMPACTION_CODES = Object.freeze(['MODEL_SWITCH_COMPACTION_FAILED'])
77
+
78
+ const MAX_PREVIEW_CHARS = 512
79
+ const MAX_QUESTION_CHARS = 512
80
+ const MAX_OPTIONS = 8
81
+ const MAX_OPEN_TOOLS = 8
82
+ const NO_PROGRESS_REPEATS = 3
83
+
84
+ function clipText(value, max) {
85
+ const text = typeof value === 'string' ? value : ''
86
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text
87
+ }
88
+
89
+ function sha256(text) {
90
+ return createHash('sha256').update(String(text), 'utf8').digest('hex')
91
+ }
92
+
93
+ function isObject(value) {
94
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
95
+ }
96
+
97
+ function dataOf(event) {
98
+ return isObject(event?.data) ? event.data : {}
99
+ }
100
+
101
+ function typeOf(event) {
102
+ return typeof event?.type === 'string' ? event.type : null
103
+ }
104
+
105
+ /** 事件的稳定序号:真实日志一定有 `seq`;探针/畸形日志退回数组下标(只影响排序,不影响事实)。 */
106
+ function seqOf(event, index) {
107
+ const seq = Number(event?.seq)
108
+ return Number.isSafeInteger(seq) && seq >= 0 ? seq : index
109
+ }
110
+
111
+ function timeOf(event, fallback) {
112
+ const time = Number(event?.time ?? event?.ts)
113
+ return Number.isSafeInteger(time) && time >= 0 ? time : fallback
114
+ }
115
+
116
+ function turnOf(event) {
117
+ const turn = Number(dataOf(event).turn)
118
+ return Number.isSafeInteger(turn) && turn >= 0 ? turn : null
119
+ }
120
+
121
+ /**
122
+ * surface 复算:把事件数组折成**模型可见顺序**,并删掉被压紧顶掉的节点。
123
+ *
124
+ * - `surfaceOp: 'append'`:节点按自身 seq 追加;
125
+ * - `surfaceOp: { op: 'replace', startSeq, endSeq }`:用本条顶掉节点表里 `[startSeq, endSeq]`
126
+ * 这一段,顶掉的 seq 进 `shadowed`(从视图删掉),本条取区间起点的排序键(因此它落在
127
+ * 「原来那段内容所在的位置」,而不是它自己更大的 seq 上);
128
+ * - 没有 `surfaceOp` 的事件(turn/start、tool/call、approval/* 等日志事件)只按 seq 参与排序,
129
+ * 永不被顶掉——压紧只删模型可见的消息节点,不删事实事件。
130
+ *
131
+ * 标记畸形(`op` 不是 replace、缺 startSeq/endSeq、区间起点不在节点表、start>end)一律降级:
132
+ * 不抛错、不做删除,并把整个视图退回裸 seq 顺序(`degraded: true`)。
133
+ *
134
+ * @param events - 一个会话的事件数组(已按 seq 升序)。
135
+ * @returns `{ordered, shadowed, replacements, degraded}`;`ordered` 是重排后的事件数组。
136
+ */
137
+ export function compactedView(events) {
138
+ const list = Array.isArray(events) ? events : []
139
+ const index = list.map((event, position) => ({ event, position, seq: seqOf(event, position) }))
140
+ const nodes = []
141
+ const shadowed = new Set()
142
+ const orderAt = new Map()
143
+ let replacements = 0
144
+ let degraded = false
145
+
146
+ for (const entry of index) {
147
+ const op = entry.event?.surfaceOp
148
+ if (op === undefined) continue
149
+ if (op === 'append') {
150
+ nodes.push(entry.seq)
151
+ continue
152
+ }
153
+ const startSeq = Number(op?.startSeq)
154
+ const endSeq = Number(op?.endSeq)
155
+ const startAt = nodes.indexOf(startSeq)
156
+ const endAt = nodes.indexOf(endSeq)
157
+ if (op?.op !== 'replace' || !Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq)
158
+ || startAt < 0 || endAt < startAt) {
159
+ degraded = true
160
+ continue
161
+ }
162
+ for (const seq of nodes.slice(startAt, endAt + 1)) shadowed.add(seq)
163
+ nodes.splice(startAt, endAt - startAt + 1, entry.seq)
164
+ orderAt.set(entry.position, startSeq)
165
+ replacements += 1
166
+ }
167
+
168
+ if (degraded) {
169
+ return { ordered: list.slice(), shadowed: new Set(), replacements: 0, degraded: true }
170
+ }
171
+ const kept = index.filter((entry) => !shadowed.has(entry.seq))
172
+ kept.sort((left, right) => {
173
+ const leftKey = orderAt.get(left.position) ?? left.seq
174
+ const rightKey = orderAt.get(right.position) ?? right.seq
175
+ return leftKey === rightKey ? left.position - right.position : leftKey - rightKey
176
+ })
177
+ return { ordered: kept.map((entry) => entry.event), shadowed, replacements, degraded: false }
178
+ }
179
+
180
+ /** 工具名的风险等级:没有日志字段可读,所以按名字语义推导,并明确标注 `source: 'derived'`。 */
181
+ const RISK_HIGH = new Set(['delete', 'remove', 'drop', 'destroy', 'purge', 'deploy', 'publish', 'push', 'reset', 'revert', 'kill', 'rm', 'rmdir', 'overwrite', 'truncate', 'migrate', 'charge', 'purchase', 'payment'])
182
+ const RISK_MEDIUM = new Set(['write', 'edit', 'patch', 'apply', 'move', 'rename', 'chmod', 'chown', 'exec', 'execute', 'shell', 'bash', 'spawn', 'install', 'create', 'mkdir', 'upload', 'commit'])
183
+
184
+ export function riskOfToolName(name) {
185
+ const tokens = String(name ?? '').toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 0)
186
+ const high = tokens.filter((token) => RISK_HIGH.has(token))
187
+ if (high.length > 0) return { level: 'high', basis: 'derived:tool-name-tokens', tokens: high }
188
+ const medium = tokens.filter((token) => RISK_MEDIUM.has(token))
189
+ if (medium.length > 0) return { level: 'medium', basis: 'derived:tool-name-tokens', tokens: medium }
190
+ return { level: 'low', basis: 'derived:tool-name-tokens', tokens: [] }
191
+ }
192
+
193
+ /**
194
+ * 幂等键:恢复时用它去目标系统核对「这个副作用到底做了没有」。
195
+ * 日志里没有这个字段,所以派生:同一 (会话, 轮次, callId, 工具, 参数) 永远得到同一个键。
196
+ */
197
+ export function idempotencyKeyOf({ sessionId, turn, callId, name, argsDigest }) {
198
+ return `idem-${sha256(`${sessionId}\u0000${turn}\u0000${callId ?? ''}\u0000${name ?? ''}\u0000${argsDigest ?? ''}`).slice(0, 32)}`
199
+ }
200
+
201
+ /** `tool/call.arguments` 是模型产出的原始 JSON 字符串:能解析就取结构化值,不能解析就留原文摘要。 */
202
+ function parseArguments(raw) {
203
+ if (typeof raw !== 'string' || raw.trim() === '') return { value: null, digest: sha256(''), bytes: 0 }
204
+ try {
205
+ return { value: JSON.parse(raw), digest: sha256(raw), bytes: Buffer.byteLength(raw, 'utf8') }
206
+ } catch {
207
+ return { value: null, digest: sha256(raw), bytes: Buffer.byteLength(raw, 'utf8') }
208
+ }
209
+ }
210
+
211
+ /** `ask_user_question` 的 `question_spec`:只留可回答的结构,去掉会膨胀的任意附加字段。 */
212
+ function questionSpecOf(parsed) {
213
+ const questions = Array.isArray(parsed?.value?.questions) ? parsed.value.questions : null
214
+ if (questions === null) return null
215
+ return questions.slice(0, MAX_OPTIONS).map((question) => {
216
+ if (!isObject(question)) return { question: clipText(String(question), MAX_QUESTION_CHARS) }
217
+ const spec = {
218
+ id: typeof question.id === 'string' ? clipText(question.id, 128) : null,
219
+ question: clipText(typeof question.question === 'string' ? question.question : '', MAX_QUESTION_CHARS),
220
+ }
221
+ if (typeof question.header === 'string') spec.header = clipText(question.header, 128)
222
+ if (Array.isArray(question.options)) {
223
+ spec.options = question.options.slice(0, MAX_OPTIONS).map((option) => {
224
+ if (!isObject(option)) return { label: clipText(String(option), 128) }
225
+ const normalized = { label: clipText(typeof option.label === 'string' ? option.label : '', 128) }
226
+ if (typeof option.description === 'string') normalized.description = clipText(option.description, 256)
227
+ return normalized
228
+ })
229
+ }
230
+ if (typeof question.multi_select === 'boolean') spec.multi_select = question.multi_select
231
+ return spec
232
+ })
233
+ }
234
+
235
+ /** 工具结果正文里的 spill 定位符:`Full sorted result stored at: <locator>. <hint>`。 */
236
+ function spillOf(event) {
237
+ const content = dataOf(event).message?.content
238
+ if (!Array.isArray(content)) return null
239
+ for (const block of content) {
240
+ if (block?.type !== 'text' || typeof block.text !== 'string') continue
241
+ const match = block.text.match(/(?:stored at|spilled to|spill(?:ed)? file)[:\s]+(\S+)/i)
242
+ if (match !== null) {
243
+ return {
244
+ locator: clipText(match[1].replace(/[.,;:]+$/, ''), 400),
245
+ source: 'tool-result-text',
246
+ }
247
+ }
248
+ }
249
+ return null
250
+ }
251
+
252
+ function errorOfTurn(reason) {
253
+ if (!isObject(reason)) return null
254
+ const failure = reason.kind === 'error' ? reason.error : (reason.kind === 'aborted' ? reason.failure : null)
255
+ if (!isObject(failure)) return null
256
+ return {
257
+ code: typeof failure.code === 'string' ? failure.code : 'UNKNOWN',
258
+ message: clipText(failure.message, MAX_PREVIEW_CHARS),
259
+ status: Number.isSafeInteger(failure.status) ? failure.status : null,
260
+ source: 'turn/end.reason',
261
+ stack_summary: clipText(failure.message, MAX_PREVIEW_CHARS),
262
+ stack_source: 'error-chain',
263
+ }
264
+ }
265
+
266
+ /**
267
+ * 一轮的累加器。所有字段都来自结构化事件,绝不由模型文本推断「已完成」。
268
+ * `calls` 按 callId 记未配对的 `tool/call`;`attempts` 记已配对且失败的调用(用于 no-progress)。
269
+ */
270
+ function newTurn(turn, seq, time, open) {
271
+ return {
272
+ turn,
273
+ startSeq: seq,
274
+ startedAt: time,
275
+ open,
276
+ reason: null,
277
+ endSeq: null,
278
+ endedAt: null,
279
+ lastEvent: null,
280
+ lastSeq: seq,
281
+ lastTime: time,
282
+ steps: 0,
283
+ calls: new Map(),
284
+ results: [],
285
+ attempts: [],
286
+ asks: [],
287
+ decisions: [],
288
+ compactions: new Map(),
289
+ compactionErrors: [],
290
+ retries: [],
291
+ toolErrors: [],
292
+ spill: null,
293
+ }
294
+ }
295
+
296
+ function rememberError(turnState, error) {
297
+ if (error === null) return
298
+ if (turnState.toolErrors.some((seen) => seen.code === error.code)) return
299
+ turnState.toolErrors.push(error)
300
+ }
301
+
302
+ function toolResultError(event) {
303
+ const error = dataOf(event).error
304
+ if (!isObject(error)) return null
305
+ return {
306
+ code: typeof error.code === 'string' ? error.code : 'TOOL_RESULT_ERROR',
307
+ message: clipText(typeof error.reason === 'string' ? error.reason : (typeof error.name === 'string' ? error.name : ''), MAX_PREVIEW_CHARS),
308
+ status: null,
309
+ source: 'tool/result.error',
310
+ stack_summary: clipText(typeof error.reason === 'string' ? error.reason : '', MAX_PREVIEW_CHARS),
311
+ stack_source: 'tool-receipt',
312
+ }
313
+ }
314
+
315
+ function outcomeOfDecision(event) {
316
+ const outcome = dataOf(event).outcome
317
+ return typeof outcome === 'string' ? outcome : null
318
+ }
319
+
320
+ function compactionFailed(turnState) {
321
+ return turnState.compactionErrors.length > 0 || turnState.compactions.size > 0
322
+ }
323
+
324
+ /**
325
+ * 把一轮的累加器判成 `{idlePath, signals}`(或 null = 干净结束,不该有快照)。
326
+ *
327
+ * 判据的核心是「干净结束」:只有 `reason.kind === 'completed'` **并且**没有遗留的等待类事实
328
+ * (未回答的提问、未决定/未回答的审批、未收尾的压紧)才算干净。这样「工具失败但 agent 自己
329
+ * 处理完并完成」的普通回合不会产出快照——那是最常见的噪声来源。
330
+ */
331
+ function classify(turnState) {
332
+ const reasonKind = turnState.open ? 'no-turn-end' : (turnState.reason?.kind ?? 'unknown')
333
+ const pendingQuestion = [...turnState.calls.values()].find((call) => call.name === 'ask_user_question') ?? null
334
+ const openAsks = turnState.asks.filter((ask) => ask.decided === null)
335
+ const unendedCompaction = turnState.compactions.size > 0
336
+ const clean = reasonKind === 'completed' && pendingQuestion === null && openAsks.length === 0 && !unendedCompaction
337
+ if (clean) return null
338
+ if (reasonKind === 'forked') return null
339
+
340
+ const signals = []
341
+ const push = (kind) => {
342
+ if (!signals.includes(kind)) signals.push(kind)
343
+ }
344
+ if (pendingQuestion !== null) push('question_wait')
345
+ if (openAsks.length > 0) push('approval_wait')
346
+ const rejected = turnState.decisions.filter((decision) => decision === 'rejected' || decision === 'unavailable')
347
+ if (rejected.length > 0 || (openAsks.length > 0 && turnState.approvalPolicy === 'never')) push('rejected')
348
+ if (compactionFailed(turnState) || COMPACTION_CODES.includes(turnState.reason?.error?.code)) push('compaction_failed')
349
+ if (reasonKind === 'max-tokens' || BUDGET_CODES.includes(turnState.reason?.error?.code)) push('budget')
350
+ if (hasNoProgress(turnState)) push('no_progress')
351
+ if (reasonKind === 'blocked'
352
+ || turnState.toolErrors.some((error) => GUARDRAIL_CODES.includes(error.code))) push('guardrail')
353
+ if (turnState.toolErrors.length > 0 || turnState.calls.size > 0) push('tool_crash')
354
+ if (reasonKind === 'error' || turnState.retries.some((retry) => retry.exhausted)) push('llm_error')
355
+ if (reasonKind === 'aborted') push('aborted')
356
+ if (reasonKind === 'no-turn-end' || NON_COMPLETION_REASONS.includes(reasonKind)) push('pod_gone')
357
+ if (signals.length === 0) push('pod_gone')
358
+
359
+ const idlePath = (reasonKind === 'no-turn-end'
360
+ // 真尾巴(没有 turn/end)的因果解释只能是「进程没了」;待答/待批是仍可行动的具体状态,优先。
361
+ ? ['question_wait', 'approval_wait', 'pod_gone'].find((path) => signals.includes(path))
362
+ : IDLE_PRIORITY.find((path) => signals.includes(path))) ?? 'pod_gone'
363
+ return { idlePath, signals, reasonKind }
364
+ }
365
+
366
+ /** 连续 ≥3 次「同名 + 同参数 + 都是失败」的调用 = 无进展循环(派生判据,标 derived)。 */
367
+ function hasNoProgress(turnState) {
368
+ let run = 0
369
+ let previous = null
370
+ for (const attempt of turnState.attempts) {
371
+ if (attempt.error !== true) {
372
+ run = 0
373
+ previous = null
374
+ continue
375
+ }
376
+ run = attempt.fingerprint === previous ? run + 1 : 1
377
+ previous = attempt.fingerprint
378
+ if (run >= NO_PROGRESS_REPEATS) return true
379
+ }
380
+ return false
381
+ }
382
+
383
+ /**
384
+ * 从一段事件里收集中断快照描述符(纯函数,不读盘、不取当前时间)。
385
+ *
386
+ * @param options.events - 会话事件数组(`readSession().events`,已按 seq 升序)。
387
+ * @param options.sessionId - 会话 id(写进边与会话归属)。
388
+ * @param options.notLive - 调用方**确定**这个会话当前不活着(sweep 的 `record.live !== true`):
389
+ * 只有这时才把「最后一个 turn/start 之后没有 turn/end」的尾巴当成 `pod_gone`。活着的会话
390
+ * 正在跑的回合天然没有 turn/end,把它写成中断是假事实。
391
+ * @param options.now - 快照时间的兜底值(毫秒)。
392
+ * @returns `{snapshots, turns, degraded, surface}`;`snapshots` 按轮次升序。
393
+ */
394
+ export function collectIdleSnapshots(options = {}) {
395
+ const events = Array.isArray(options.events) ? options.events : []
396
+ const sessionId = typeof options.sessionId === 'string' ? options.sessionId : ''
397
+ const notLive = options.notLive === true
398
+ const now = Number.isSafeInteger(options.now) && options.now >= 0 ? options.now : 0
399
+ const view = compactedView(events)
400
+
401
+ /** 会话级状态:目标、权限旋钮、工具 Schema(都在快照时刻取「当时生效」的值)。 */
402
+ const session = { goal: null, preset: null, sandbox: null, approvalPolicy: null, tools: new Map() }
403
+ const turns = []
404
+ let current = null
405
+ let lastSeq = events.length === 0 ? null : seqOf(events.at(-1), events.length - 1)
406
+ let lastEventType = events.length === 0 ? null : typeOf(events.at(-1))
407
+ for (let position = 0; position < view.ordered.length; position += 1) {
408
+ const event = view.ordered[position]
409
+ const type = typeOf(event)
410
+ const seq = seqOf(event, position)
411
+ const time = timeOf(event, now)
412
+ // 会话游标必须是**最大 seq** 的那条事件(压紧视图的顺序与 seq 不同)。
413
+ if (lastSeq === null || seq >= lastSeq) {
414
+ lastSeq = seq
415
+ lastEventType = type ?? lastEventType
416
+ }
417
+
418
+ if (type === 'turn/start') {
419
+ const turn = turnOf(event)
420
+ if (turn !== null) {
421
+ if (current !== null) turns.push(current) // 前一轮没有 turn/end:两个 open 段,前一段按尾巴处理
422
+ current = newTurn(turn, seq, time, true)
423
+ }
424
+ continue
425
+ }
426
+ if (type === 'turn/end') {
427
+ const turn = turnOf(event)
428
+ if (current !== null && (turn === null || current.turn === turn)) {
429
+ current.open = false
430
+ current.reason = isObject(dataOf(event).reason) ? dataOf(event).reason : { kind: 'unknown' }
431
+ current.endSeq = seq
432
+ current.endedAt = time
433
+ current.lastEvent = type
434
+ current.lastSeq = seq
435
+ current.lastTime = time
436
+ turns.push(current)
437
+ current = null
438
+ }
439
+ continue
440
+ }
441
+ if (type === 'goal/change') {
442
+ session.goal = foldGoal(dataOf(event))
443
+ if (current !== null) touch(current, type, seq, time)
444
+ continue
445
+ }
446
+ if (type === 'permission/preset') {
447
+ session.preset = typeof dataOf(event).preset === 'string' ? dataOf(event).preset : session.preset
448
+ if (current !== null) touch(current, type, seq, time)
449
+ continue
450
+ }
451
+ if (type === 'sandbox/mode') {
452
+ session.sandbox = typeof dataOf(event).mode === 'string' ? dataOf(event).mode : session.sandbox
453
+ if (current !== null) touch(current, type, seq, time)
454
+ continue
455
+ }
456
+ if (type === 'approval/policy') {
457
+ session.approvalPolicy = typeof dataOf(event).policy === 'string' ? dataOf(event).policy : session.approvalPolicy
458
+ if (current !== null) touch(current, type, seq, time)
459
+ continue
460
+ }
461
+ if (type === 'request/header') {
462
+ const tools = dataOf(event).header?.tools
463
+ if (Array.isArray(tools)) {
464
+ for (const tool of tools) {
465
+ if (typeof tool?.name === 'string' && isObject(tool.parameters)) {
466
+ session.tools.set(tool.name, tool.parameters)
467
+ }
468
+ }
469
+ }
470
+ if (current !== null) touch(current, type, seq, time)
471
+ continue
472
+ }
473
+
474
+ if (current === null) continue
475
+ touch(current, type, seq, time)
476
+ observeTurnEvent(current, event, type, seq)
477
+ }
478
+ if (current !== null) turns.push(current)
479
+
480
+ const snapshots = []
481
+ for (const turnState of turns) {
482
+ turnState.approvalPolicy = session.approvalPolicy
483
+ if (turnState.open && !notLive) continue
484
+ const verdict = classify(turnState)
485
+ if (verdict === null) continue
486
+ snapshots.push(describe(turnState, verdict, { session, sessionId, now, lastSeq, lastEventType, surface: view }))
487
+ }
488
+
489
+ return {
490
+ snapshots,
491
+ turns: turns.length,
492
+ degraded: view.degraded,
493
+ surface: { mode: view.degraded ? 'raw' : 'compacted', replacements: view.replacements, shadowed: view.shadowed.size },
494
+ }
495
+ }
496
+
497
+ function touch(turnState, type, seq, time) {
498
+ turnState.lastEvent = type
499
+ turnState.lastSeq = seq
500
+ turnState.lastTime = time
501
+ }
502
+
503
+ function observeTurnEvent(turnState, event, type, seq) {
504
+ const data = dataOf(event)
505
+ if (type === 'step/start') {
506
+ turnState.steps += 1
507
+ return
508
+ }
509
+ if (type === 'tool/call') {
510
+ const callId = typeof data.callId === 'string' ? data.callId : (typeof data.callId === 'number' ? String(data.callId) : `seq-${seq}`)
511
+ const name = typeof data.name === 'string' ? data.name : 'unknown'
512
+ const parsed = parseArguments(data.arguments)
513
+ turnState.calls.set(callId, {
514
+ callId,
515
+ name,
516
+ turn: turnOf(event) ?? turnState.turn,
517
+ step: Number.isSafeInteger(Number(data.step)) ? Number(data.step) : null,
518
+ seq,
519
+ digest: parsed.digest,
520
+ parsed,
521
+ fingerprint: `${name}\u0000${parsed.digest}`,
522
+ })
523
+ return
524
+ }
525
+ if (type === 'tool/result') {
526
+ const callId = typeof data.message?.source?.callId === 'string'
527
+ ? data.message.source.callId
528
+ : (typeof data.callId === 'string' ? data.callId : null)
529
+ const call = callId === null ? undefined : turnState.calls.get(callId)
530
+ if (callId !== null) turnState.calls.delete(callId)
531
+ const error = toolResultError(event)
532
+ turnState.results.push({ callId, error: error !== null })
533
+ if (call !== undefined) {
534
+ turnState.attempts.push({ fingerprint: call.fingerprint, error: error !== null })
535
+ }
536
+ if (error !== null) rememberError(turnState, { ...error, tool: call?.name ?? null, call_id: callId })
537
+ const spill = spillOf(event)
538
+ if (spill !== null) turnState.spill = { ...spill, tool: call?.name ?? null, call_id: callId }
539
+ return
540
+ }
541
+ if (type === 'approval/asked') {
542
+ turnState.asks.push({
543
+ id: typeof data.id === 'string' ? data.id : null,
544
+ toolName: typeof data.toolName === 'string' ? data.toolName : null,
545
+ callId: typeof data.callId === 'string' ? data.callId : null,
546
+ reason: typeof data.reason === 'string' ? clipText(data.reason, MAX_PREVIEW_CHARS) : null,
547
+ seq,
548
+ decided: null,
549
+ })
550
+ return
551
+ }
552
+ if (type === 'approval/decided') {
553
+ const id = typeof data.id === 'string' ? data.id : null
554
+ const decision = { id, outcome: outcomeOfDecision(event) }
555
+ turnState.decisions.push(decision.outcome)
556
+ const ask = turnState.asks.find((entry) => entry.id === id) ?? null
557
+ if (ask !== null) ask.decided = decision.outcome
558
+ return
559
+ }
560
+ if (type === 'compaction/start') {
561
+ const id = typeof data.compactionId === 'string' ? data.compactionId : `seq-${seq}`
562
+ turnState.compactions.set(id, seq)
563
+ return
564
+ }
565
+ if (type === 'compaction/end') {
566
+ const id = typeof data.compactionId === 'string' ? data.compactionId : `seq-${seq}`
567
+ turnState.compactions.delete(id)
568
+ if (typeof data.error === 'string' && data.error.length > 0) {
569
+ turnState.compactionErrors.push({ code: 'COMPACTION_FAILED', message: clipText(data.error, MAX_PREVIEW_CHARS), source: 'compaction/end.error' })
570
+ }
571
+ return
572
+ }
573
+ if (type === 'llm/retry') {
574
+ const retry = Number(data.retry)
575
+ const maxRetries = Number(data.maxRetries)
576
+ turnState.retries.push({
577
+ retry: Number.isSafeInteger(retry) ? retry : null,
578
+ maxRetries: Number.isSafeInteger(maxRetries) ? maxRetries : null,
579
+ exhausted: Number.isSafeInteger(retry) && Number.isSafeInteger(maxRetries) && retry >= maxRetries,
580
+ failure: isObject(data.failure) ? data.failure : null,
581
+ })
582
+ }
583
+ }
584
+
585
+ function foldGoal(meta) {
586
+ if (!isObject(meta)) return null
587
+ if (meta.operation === 'clear') {
588
+ return { cleared: true, clearedAt: Number.isSafeInteger(meta.clearedAt) ? meta.clearedAt : null }
589
+ }
590
+ const goal = isObject(meta.goal) ? meta.goal : null
591
+ if (goal === null) return null
592
+ const folded = {
593
+ id: typeof goal.id === 'string' ? goal.id : null,
594
+ revision: Number.isSafeInteger(goal.revision) ? goal.revision : null,
595
+ objective: clipText(goal.objective, MAX_PREVIEW_CHARS),
596
+ phase: typeof goal.phase === 'string' ? goal.phase : null,
597
+ maxGoalRounds: Number.isSafeInteger(goal.maxGoalRounds) ? goal.maxGoalRounds : null,
598
+ roundsStarted: Number.isSafeInteger(meta.roundsStarted) ? meta.roundsStarted : null,
599
+ updatedAt: Number.isSafeInteger(meta.updatedAt) ? meta.updatedAt : null,
600
+ }
601
+ if (isObject(goal.blockedReason)) {
602
+ folded.blockedReason = {
603
+ code: typeof goal.blockedReason.code === 'string' ? goal.blockedReason.code : null,
604
+ message: clipText(goal.blockedReason.message, MAX_PREVIEW_CHARS),
605
+ }
606
+ }
607
+ return folded
608
+ }
609
+
610
+ function describe(turnState, verdict, context) {
611
+ const { session, sessionId, now, lastSeq, lastEventType, surface } = context
612
+ const pendingCall = pickPendingCall(turnState, verdict.idlePath)
613
+ const openAsk = turnState.asks.find((ask) => ask.decided === null) ?? null
614
+ const turnError = errorOfTurn(turnState.reason)
615
+ const retryError = turnState.retries.find((retry) => retry?.failure !== null)?.failure ?? null
616
+ const error = turnState.toolErrors[0] ?? turnError ?? (isObject(retryError) ? {
617
+ code: typeof retryError.code === 'string' ? retryError.code : 'UNKNOWN',
618
+ message: clipText(retryError.message, MAX_PREVIEW_CHARS),
619
+ status: Number.isSafeInteger(retryError.status) ? retryError.status : null,
620
+ source: 'llm/retry.failure',
621
+ stack_summary: clipText(retryError.message, MAX_PREVIEW_CHARS),
622
+ stack_source: 'error-chain',
623
+ } : turnState.compactionErrors[0] ?? null)
624
+
625
+ const reason = isObject(turnState.reason) ? turnState.reason : null
626
+ const snapshot = {
627
+ idle_path: verdict.idlePath,
628
+ signals: verdict.signals,
629
+ reason: reason === null ? (turnState.open ? { kind: 'no-turn-end' } : null) : {
630
+ kind: typeof reason.kind === 'string' ? reason.kind : 'unknown',
631
+ ...(isObject(reason.reason) && typeof reason.reason.kind === 'string' ? { cancel_cause: reason.reason.kind } : {}),
632
+ },
633
+ goal: session.goal,
634
+ spill: turnState.spill,
635
+ error,
636
+ permission_presets: {
637
+ preset: session.preset,
638
+ sandbox: session.sandbox,
639
+ approval_policy: session.approvalPolicy,
640
+ },
641
+ turn: {
642
+ steps: turnState.steps,
643
+ started_at: turnState.startedAt,
644
+ ended_at: turnState.endedAt,
645
+ open: turnState.open,
646
+ last_event: turnState.lastEvent,
647
+ },
648
+ open_tools: [...turnState.calls.values()].slice(0, MAX_OPEN_TOOLS).map((call) => ({
649
+ name: call.name,
650
+ call_id: call.callId,
651
+ turn: call.turn,
652
+ step: call.step,
653
+ args_digest: call.digest,
654
+ })),
655
+ compaction: { unended: turnState.compactions.size, failed: turnState.compactionErrors.length },
656
+ surface: { mode: surface.degraded ? 'raw' : 'compacted', replacements: surface.replacements },
657
+ session_cursor: { seq: lastSeq, event_type: lastEventType },
658
+ }
659
+
660
+ const pendingIntent = describePendingIntent({ turnState, verdict, pendingCall, openAsk, session, sessionId })
661
+ const triggerSeq = Number.isSafeInteger(pendingCall?.seq)
662
+ ? pendingCall.seq
663
+ : (Number.isSafeInteger(openAsk?.seq) ? openAsk.seq : (turnState.lastSeq ?? 0))
664
+ const trigger = {
665
+ event_type: pendingCall !== null ? 'tool/call' : (openAsk !== null ? 'approval/asked' : (turnState.lastEvent ?? 'turn/start')),
666
+ event_ref: `${sessionId}#${triggerSeq}`,
667
+ seq: triggerSeq,
668
+ }
669
+
670
+ const derived = verdict.signals.every((signal) => signal === 'no_progress')
671
+ return {
672
+ turn: turnState.turn,
673
+ idlePath: verdict.idlePath,
674
+ signals: verdict.signals,
675
+ last_event: turnState.lastEvent ?? (turnState.open ? 'turn/start' : null),
676
+ pending_intent: pendingIntent,
677
+ snapshot,
678
+ resume_cursor: {
679
+ seq: turnState.lastSeq ?? 0,
680
+ turn: turnState.turn,
681
+ event_type: turnState.lastEvent ?? 'turn/start',
682
+ ts: turnState.lastTime ?? now,
683
+ },
684
+ trigger,
685
+ evidence_kind: derived ? 'INFERRED' : 'EXTRACTED',
686
+ evidence_detail: {
687
+ signals: verdict.signals,
688
+ steps: turnState.steps,
689
+ reason_kind: verdict.reasonKind,
690
+ ...(derived ? { derived: ['no_progress'] } : {}),
691
+ },
692
+ }
693
+ }
694
+
695
+ /** 该写进 `pending_intent` 的那个待办动作:提问 > 审批 > 其它未完成的调用。 */
696
+ function pickPendingCall(turnState, idlePath) {
697
+ const calls = [...turnState.calls.values()]
698
+ if (idlePath === 'question_wait') return calls.find((call) => call.name === 'ask_user_question') ?? null
699
+ if (idlePath === 'approval_wait' || idlePath === 'rejected' || idlePath === 'guardrail') {
700
+ const asked = turnState.asks.at(-1)
701
+ if (asked?.callId !== null && asked?.callId !== undefined) {
702
+ const match = calls.find((call) => call.callId === asked.callId)
703
+ if (match !== undefined) return match
704
+ }
705
+ return calls[0] ?? null
706
+ }
707
+ return calls[0] ?? null
708
+ }
709
+
710
+ function describePendingIntent({ turnState, verdict, pendingCall, openAsk, session, sessionId }) {
711
+ const base = pendingCall === null ? null : {
712
+ name: pendingCall.name,
713
+ call_id: pendingCall.callId,
714
+ turn: pendingCall.turn,
715
+ step: pendingCall.step,
716
+ args_digest: pendingCall.digest,
717
+ args_bytes: pendingCall.parsed.bytes,
718
+ args_schema: session.tools.get(pendingCall.name) ?? null,
719
+ risk: riskOfToolName(pendingCall.name),
720
+ idempotency_key: idempotencyKeyOf({
721
+ sessionId,
722
+ turn: pendingCall.turn,
723
+ callId: pendingCall.callId,
724
+ name: pendingCall.name,
725
+ argsDigest: pendingCall.digest,
726
+ }),
727
+ }
728
+
729
+ if (verdict.idlePath === 'question_wait') {
730
+ return {
731
+ kind: 'question',
732
+ tool: base,
733
+ question_spec: questionSpecOf(pendingCall?.parsed ?? null),
734
+ }
735
+ }
736
+ if (verdict.idlePath === 'approval_wait' || verdict.idlePath === 'rejected') {
737
+ return {
738
+ kind: verdict.idlePath === 'approval_wait' ? 'approval' : 'rejected',
739
+ tool: base,
740
+ ...(openAsk !== null ? {
741
+ approval: {
742
+ id: openAsk.id,
743
+ tool_name: openAsk.toolName,
744
+ call_id: openAsk.callId,
745
+ reason: openAsk.reason,
746
+ decided: openAsk.decided,
747
+ decision: turnState.decisions.at(-1) ?? null,
748
+ },
749
+ } : {}),
750
+ }
751
+ }
752
+ if (base === null) return undefined
753
+ return { kind: verdict.idlePath, tool: base }
754
+ }
755
+
756
+ /** 去重键:同一会话、同一轮、同一 idlePath 只写一次(跨进程重扫幂等)。 */
757
+ export function idleDedupeKey(snapshot) {
758
+ return `${snapshot?.sessionId ?? ''}\u0000${snapshot?.turn ?? ''}\u0000${snapshot?.idlePath ?? ''}`
759
+ }
760
+
761
+ export function envelopeDedupeKey(envelope) {
762
+ return idleDedupeKey({
763
+ sessionId: envelope?.session?.id,
764
+ turn: envelope?.turn,
765
+ idlePath: envelope?.idlePath,
766
+ })
767
+ }
768
+
769
+ /**
770
+ * 描述符 → 校验过的 `IDLE_INTERRUPT` 信封。
771
+ *
772
+ * `successor` 是 `followed_by` 的预留入口:调用方知道「中断之后接着发生的那次恢复/下一轮」
773
+ * 时传进来,边才会出现;本文件不猜(没有后继就留空,而不是编一个目标)。
774
+ */
775
+ export function buildIdleEnvelope(descriptor, options = {}) {
776
+ const id = options.id
777
+ const scope = options.scope
778
+ const sessionId = options.sessionId
779
+ const ts = Number.isSafeInteger(options.ts) && options.ts >= 0 ? options.ts : 0
780
+ if (typeof id !== 'string' || id.length === 0 || typeof sessionId !== 'string' || sessionId.length === 0) {
781
+ throw new Error('buildIdleEnvelope 需要非空的 id 与 sessionId')
782
+ }
783
+ if (!IDLE_PATHS.includes(descriptor.idlePath)) {
784
+ throw new Error(`buildIdleEnvelope: 未知 idlePath ${String(descriptor.idlePath)}`)
785
+ }
786
+ const relations = [{
787
+ label: 'belongs_to_session',
788
+ target: sessionId,
789
+ weight: 1,
790
+ evidence_trace: { kind: 'EXTRACTED', source: 'session-log' },
791
+ }, {
792
+ label: 'triggered_by',
793
+ target: `${sessionId}#${descriptor.trigger?.seq ?? 0}`,
794
+ weight: 1,
795
+ metadata: { event_type: descriptor.trigger?.event_type ?? null },
796
+ evidence_trace: { kind: 'EXTRACTED', source: 'session-log' },
797
+ }]
798
+ if (typeof options.successor === 'string' && options.successor.length > 0) {
799
+ relations.push({
800
+ label: 'followed_by',
801
+ target: options.successor,
802
+ weight: 1,
803
+ evidence_trace: { kind: 'INFERRED', source: 'idle-resume' },
804
+ })
805
+ }
806
+
807
+ const envelope = {
808
+ id,
809
+ source_type: 'IDLE_INTERRUPT',
810
+ session: scope === undefined ? { id: sessionId } : { id: sessionId, scope },
811
+ turn: descriptor.turn,
812
+ ts,
813
+ evidence_trace: {
814
+ kind: descriptor.evidence_kind ?? 'EXTRACTED',
815
+ source: 'session-log',
816
+ detail: descriptor.evidence_detail ?? {},
817
+ },
818
+ node_metadata: {
819
+ topic: '',
820
+ scope: scope ?? null,
821
+ bytes: 0,
822
+ incomplete: true,
823
+ idle_path: descriptor.idlePath,
824
+ signals: descriptor.signals,
825
+ },
826
+ dynamic_relations: relations,
827
+ incomplete: true,
828
+ idlePath: descriptor.idlePath,
829
+ resume_cursor: descriptor.resume_cursor,
830
+ snapshot: descriptor.snapshot,
831
+ }
832
+ if (typeof descriptor.last_event === 'string') envelope.last_event = descriptor.last_event
833
+ if (descriptor.pending_intent !== undefined) envelope.pending_intent = descriptor.pending_intent
834
+ return validateEnvelope(envelope)
835
+ }
836
+
837
+ /**
838
+ * 写快照:按去重键过滤 → 配额检查 → 一次 batch。返回 `{written, skipped, why}`,绝不抛。
839
+ *
840
+ * 去重键取自**库里已有的** IDLE_INTERRUPT 信封(不是进程内记忆),所以进程重启后重扫同一份
841
+ * 日志不会写出第二条;写入失败(配额/存储错误)只让本轮快照缺席,绝不让回合失败。
842
+ */
843
+ export async function writeIdleSnapshots(options = {}) {
844
+ const runtime = options.runtime
845
+ const scope = options.scope
846
+ const sessionId = options.sessionId
847
+ const descriptors = Array.isArray(options.snapshots) ? options.snapshots : []
848
+ const max = Number.isSafeInteger(options.max) && options.max > 0 ? options.max : MAX_SNAPSHOTS_PER_SCAN
849
+ const now = Number.isSafeInteger(options.now) && options.now >= 0 ? options.now : 0
850
+ if (descriptors.length === 0) return { written: 0, skipped: 0, why: 'nothing-to-write' }
851
+ if (runtime === undefined || typeof runtime.scanWorkspace !== 'function') {
852
+ return { written: 0, skipped: descriptors.length, why: 'no-runtime' }
853
+ }
854
+ try {
855
+ return await runtime.withLock(scope, async () => {
856
+ const scan = await runtime.scanWorkspace(scope)
857
+ const seen = new Set(
858
+ scan.rows
859
+ .map((row) => row?.payload?.envelope)
860
+ .filter((envelope) => envelope?.source_type === 'IDLE_INTERRUPT')
861
+ .map((envelope) => envelopeDedupeKey(envelope)),
862
+ )
863
+ const fresh = descriptors
864
+ .filter((descriptor) => !seen.has(idleDedupeKey({ sessionId, turn: descriptor.turn, idlePath: descriptor.idlePath })))
865
+ .slice(-max)
866
+ if (fresh.length === 0) return { written: 0, skipped: descriptors.length, why: 'already-recorded' }
867
+ const envelopes = fresh.map((descriptor) => buildIdleEnvelope(descriptor, {
868
+ id: runtime.entryId(),
869
+ scope,
870
+ sessionId,
871
+ ts: now,
872
+ successor: options.successor,
873
+ }))
874
+ runtime.assertQuota({ count: scan.count, bytes: scan.bytes }, { entries: envelopes.length, bytes: 0 })
875
+ await runtime.appendEnvelopes(scope, envelopes)
876
+ return { written: envelopes.length, skipped: descriptors.length - fresh.length, why: 'written' }
877
+ })
878
+ } catch (error) {
879
+ return {
880
+ written: 0,
881
+ skipped: descriptors.length,
882
+ why: typeof error?.code === 'string' && error.code.startsWith('KANABO_MEMORY_QUOTA') ? 'quota' : 'write-failed',
883
+ code: typeof error?.code === 'string' ? error.code : null,
884
+ message: error?.message ?? String(error),
885
+ }
886
+ }
887
+ }
888
+
889
+ /**
890
+ * 专用读取入口:按会话(可选)读 IDLE_INTERRUPT 快照,返回结构化字段。
891
+ * 普通召回读不到它们(没有正文、没有向量、没有入边),只有显式来问才看得到。
892
+ */
893
+ export async function readIdleSnapshots(options = {}) {
894
+ const runtime = options.runtime
895
+ const scope = options.scope
896
+ const sessionId = typeof options.sessionId === 'string' && options.sessionId.length > 0 ? options.sessionId : null
897
+ const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : 50
898
+ if (runtime === undefined || typeof runtime.scanWorkspace !== 'function') return []
899
+ const scan = await runtime.scanWorkspace(scope)
900
+ const snapshots = []
901
+ for (const row of scan.rows) {
902
+ const envelope = row?.payload?.envelope
903
+ if (envelope?.source_type !== 'IDLE_INTERRUPT') continue
904
+ if (sessionId !== null && envelope?.session?.id !== sessionId) continue
905
+ snapshots.push({
906
+ nodeId: row.nodeId,
907
+ id: envelope.id,
908
+ turn: envelope.turn,
909
+ idlePath: envelope.idlePath,
910
+ incomplete: envelope.incomplete === true,
911
+ ts: envelope.ts,
912
+ last_event: envelope.last_event ?? null,
913
+ pending_intent: envelope.pending_intent ?? null,
914
+ resume_cursor: envelope.resume_cursor ?? null,
915
+ snapshot: envelope.snapshot ?? null,
916
+ relations: envelope.dynamic_relations,
917
+ evidence_trace: envelope.evidence_trace,
918
+ })
919
+ if (snapshots.length >= limit) break
920
+ }
921
+ return snapshots
922
+ }