@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/store.js ADDED
@@ -0,0 +1,347 @@
1
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join, resolve } from 'node:path'
3
+ import { tmpdir } from 'node:os'
4
+
5
+ /**
6
+ * 金棒记忆的临时存储层:按 **workspace** 分域的 JSON 文档,外加一份进程内内存镜像。
7
+ *
8
+ * 两个键绝不可混用(实测,见事实文件 §I):
9
+ * - **分域键(哪些事实)** = `session.header.cwd`,所以同一项目的下一个会话能召回上一个会话存入的事实;
10
+ * - **去重键(哪个回合)** = `scope + sessionId + turn`,由条目自身携带。
11
+ * 把分域键当去重键,会让第二个会话的 turn 1 被误判为「已服务」而永久跳过召回。
12
+ *
13
+ * 单文档全量重写的成本由 `MAX_ENTRIES` 封顶;写入是「临时文件 + fsync + rename」的原子替换。
14
+ */
15
+
16
+ /** 单条条目文本的字节上限;超过的输入由调用方处理(本模块绝不静默截断)。 */
17
+ export const MAX_ENTRY_BYTES = 4096
18
+ /** 单次注入文本的字节上限(T4 召回使用)。 */
19
+ export const MAX_INJECT_BYTES = 2048
20
+ /** 每个 workspace 文档最多保留的条目数,超出按先进先出淘汰。 */
21
+ export const MAX_ENTRIES = 200
22
+ /**
23
+ * `scopeOf` 在会话拿不到 `header.cwd` 时使用的固定字面量。
24
+ * 用常量而非随机值:缺失 cwd 的会话仍应共享同一个「未知工作区」分域。
25
+ */
26
+ export const DEFAULT_SCOPE = 'unknown-workspace'
27
+
28
+ /** 存储目录:环境变量优先(测试与验收用),否则落在系统临时目录下。 */
29
+ export function storeDir() {
30
+ return process.env.KANABO_MEMORY_DIR ?? join(tmpdir(), 'dsh-kanabo-memory')
31
+ }
32
+
33
+ /** 分域键:工作目录;缺失或为空时回退到 `DEFAULT_SCOPE`。 */
34
+ export function scopeOf(session) {
35
+ const cwd = session?.header?.cwd
36
+ return typeof cwd === 'string' && cwd.length > 0 ? cwd : DEFAULT_SCOPE
37
+ }
38
+
39
+ /**
40
+ * 分域键 → 文件名。把路径里的分隔符等字符压成 `_`,因此文件名永远是 `storeDir()` 的直接子项
41
+ * (`/tmp/ws/a` → `tmp_ws_a.json`)。文件名由 workspace 派生、**不是**由 session 派生:
42
+ * 一个 JSON 文档装下该 workspace 的全部会话(实测形状见事实文件 §V3)。
43
+ */
44
+ function fileNameFor(scope) {
45
+ const name = String(scope)
46
+ .replace(/[^A-Za-z0-9._-]+/g, '_')
47
+ .replace(/^[_.]+|[_.]+$/g, '')
48
+ return name === '' || /^[.]+$/.test(name) ? 'workspace' : name
49
+ }
50
+
51
+ export function storeFile(scope) {
52
+ const dir = resolve(storeDir())
53
+ const file = resolve(dir, `${fileNameFor(scope)}.json`)
54
+ // 兜底断言:清理后不该再有分隔符,若仍越界说明清理逻辑坏了,宁可抛错也不写到目录外。
55
+ if (dirname(file) !== dir) throw storeError('KANABO_STORE_PATH', `存储路径越界:${file}`)
56
+ return file
57
+ }
58
+
59
+ /** 带稳定 `code` 的错误:后续单元据此区分「损坏」与「不可写」,不靠匹配消息文本。 */
60
+ function storeError(code, message, cause) {
61
+ const error = new Error(message, cause === undefined ? undefined : { cause })
62
+ error.code = code
63
+ return error
64
+ }
65
+
66
+ /** 空文档。`scope` 一并保存,使 `readStore` → 修改 → `writeStore` 的往返不丢信息。 */
67
+ function emptyDoc(scope) {
68
+ return { version: 1, scope, updatedAt: 0, entries: [] }
69
+ }
70
+
71
+ /**
72
+ * 读取一个分域的文档。
73
+ * - 文件不存在(`ENOENT`)→ 返回空文档,这是正常状态;
74
+ * - JSON 解析失败或形状不对 → **抛错**,绝不悄悄当成空文档(否则损坏会变成静默丢记忆)。
75
+ */
76
+ export function readStore(scope) {
77
+ const file = storeFile(scope)
78
+ let raw
79
+ try {
80
+ raw = readFileSync(file, 'utf8')
81
+ } catch (error) {
82
+ if (error?.code === 'ENOENT') return emptyDoc(scope)
83
+ throw error
84
+ }
85
+ let doc
86
+ try {
87
+ doc = JSON.parse(raw)
88
+ } catch (error) {
89
+ throw storeError('KANABO_STORE_CORRUPT', `存储文件不是合法 JSON:${file}`, error)
90
+ }
91
+ if (doc?.version !== 1 || !Array.isArray(doc.entries)) {
92
+ throw storeError('KANABO_STORE_CORRUPT', `存储文件形状不对(需要 version:1 与 entries 数组):${file}`)
93
+ }
94
+ return doc
95
+ }
96
+
97
+ /**
98
+ * 原子整文件替换:写同目录临时文件(`wx` + `0o600`)→ `fsync` → `rename` 覆盖目标。
99
+ * 协议与 `@deepseek-ai/dsh-storage-json` 的 `writeAtomic` 一致(每个文件只有一个写者,后写者胜)。
100
+ * 存储文档、游标表与扫描状态共用这一份实现,不要再就地复制。
101
+ */
102
+ export function writeAtomicFile(file, text) {
103
+ const dir = dirname(file)
104
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
105
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`
106
+ try {
107
+ const fd = openSync(tmp, 'wx', 0o600)
108
+ try {
109
+ writeFileSync(fd, text, 'utf8')
110
+ fsyncSync(fd)
111
+ } finally {
112
+ closeSync(fd)
113
+ }
114
+ renameSync(tmp, file)
115
+ } catch (error) {
116
+ try {
117
+ unlinkSync(tmp)
118
+ } catch {
119
+ // 临时文件可能根本没建出来:忽略,保留原始错误。
120
+ }
121
+ throw error
122
+ }
123
+ // 让目录项本身也落盘;Windows 不支持对目录 fsync,失败即忽略(与参考实现同策略)。
124
+ try {
125
+ const dirFd = openSync(dir, 'r')
126
+ try {
127
+ fsyncSync(dirFd)
128
+ } finally {
129
+ closeSync(dirFd)
130
+ }
131
+ } catch {
132
+ }
133
+ }
134
+
135
+ /** 存储文档的原子整文件替换(`storeFile(scope)` 内)。 */
136
+ export function writeStore(scope, doc) {
137
+ writeAtomicFile(storeFile(scope), JSON.stringify(doc))
138
+ }
139
+
140
+ /**
141
+ * 追加一条条目并做先进先出淘汰,返回**新的**文档(不修改入参)。
142
+ * 条目身份字段(`scope`/`sessionId`/`turn`/`reason`)由调用方给出;这里只补齐可安全推导的字段,
143
+ * 并把缺席的 `turn`/`reason` 记为 `null`——本模块不猜结局。
144
+ */
145
+ export function addEntry(store, entry) {
146
+ const doc = store ?? emptyDoc(DEFAULT_SCOPE)
147
+ const text = String(entry?.text ?? '')
148
+ const normalized = {
149
+ id: entry?.id ?? `mem-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
150
+ scope: entry?.scope ?? doc.scope,
151
+ sessionId: entry?.sessionId ?? null,
152
+ turn: entry?.turn ?? null,
153
+ reason: entry?.reason ?? null,
154
+ topic: entry?.topic ?? '',
155
+ text,
156
+ ts: entry?.ts ?? Date.now(),
157
+ bytes: entry?.bytes ?? Buffer.byteLength(text, 'utf8'),
158
+ }
159
+ const entries = [...(doc.entries ?? []), normalized]
160
+ return {
161
+ ...doc,
162
+ updatedAt: normalized.ts,
163
+ entries: entries.length > MAX_ENTRIES ? entries.slice(-MAX_ENTRIES) : entries,
164
+ }
165
+ }
166
+
167
+ /**
168
+ * 停用词:查询与文档两侧都剔除,避免「what」「is」这类词制造假匹配。
169
+ * 中文没有空格,整句会退化成一个词元,等于退化为子串匹配(实测会漏掉普通追问),
170
+ * 所以中日韩汉字串按二元组切分(见 `tokens`)。
171
+ */
172
+ const STOP_WORDS = new Set([
173
+ 'the', 'a', 'an', 'and', 'or', 'of', 'to', 'in', 'on', 'at', 'for', 'is', 'are', 'was', 'were', 'be',
174
+ 'what', 'who', 'which', 'how', 'why', 'when', 'where', 'did', 'do', 'does', 'it', 'this', 'that', 'these',
175
+ 'my', 'your', 'our', 'i', 'we', 'you', 'me', 'us', 'as', 'by', 'with', 'from', 'not', 'no', 'yes',
176
+ ])
177
+
178
+ /** 词元切分:拉丁词/数字整词(长度 > 1、非停用词),汉字串取二元组。 */
179
+ const TOKEN_RE = /(?:(?!\p{Script=Han})[\p{L}\p{N}])+|\p{Script=Han}+/gu
180
+
181
+ export function tokens(text) {
182
+ const out = []
183
+ for (const match of String(text ?? '').toLowerCase().matchAll(TOKEN_RE)) {
184
+ const chunk = match[0]
185
+ if (/^\p{Script=Han}+$/u.test(chunk)) {
186
+ if (chunk.length === 1) continue
187
+ for (let i = 0; i + 1 < chunk.length; i += 1) out.push(chunk.slice(i, i + 2))
188
+ continue
189
+ }
190
+ if (chunk.length > 1 && !STOP_WORDS.has(chunk)) out.push(chunk)
191
+ }
192
+ return out
193
+ }
194
+
195
+ /**
196
+ * 按词元重叠打分排序:分数 = 查询词元在条目中出现的个数;同分按时间新者优先。
197
+ * 两种「没有词元」必须分开:未提供查询(`recall` 不带 query)返回最近事实;
198
+ * 提供了查询但只剩停用词(如 `what is the`)返回**空**——零信息查询不得召回全部条目。
199
+ */
200
+ export function searchEntries(entries, query, limit = Number.POSITIVE_INFINITY) {
201
+ const list = Array.isArray(entries) ? entries : []
202
+ const asked = typeof query === 'string' && query.trim().length > 0
203
+ const want = new Set(tokens(query))
204
+ if (asked && want.size === 0) return []
205
+ const scored = []
206
+ for (const entry of list) {
207
+ if (want.size === 0) {
208
+ scored.push({ entry, score: 0 })
209
+ continue
210
+ }
211
+ const have = new Set(tokens(`${textOf(entry)} ${entry?.topic ?? ''}`))
212
+ let score = 0
213
+ for (const token of want) if (have.has(token)) score += 1
214
+ if (score > 0) scored.push({ entry, score })
215
+ }
216
+ scored.sort((a, b) => b.score - a.score || (b.entry?.ts ?? 0) - (a.entry?.ts ?? 0))
217
+ return scored.slice(0, Math.max(0, limit)).map((row) => row.entry)
218
+ }
219
+
220
+ /** 条目的可读文本:`text` 优先,空则退回 `topic`;供注入与检索共用同一份口径。 */
221
+ export function textOf(entry) {
222
+ const text = typeof entry?.text === 'string' ? entry.text.trim() : ''
223
+ if (text.length > 0) return text
224
+ return typeof entry?.topic === 'string' ? entry.topic.trim() : ''
225
+ }
226
+
227
+ /**
228
+ * 按**字节**截断,绝不切坏多字节字符:先编码再回退到 UTF-8 字符边界,
229
+ * 截断时补 `…`(正好 3 字节,计入上限)。
230
+ */
231
+ export function clip(text, maxBytes) {
232
+ const source = String(text ?? '')
233
+ const limit = Number.isFinite(maxBytes) ? Math.max(0, Math.floor(maxBytes)) : source.length
234
+ const buf = Buffer.from(source, 'utf8')
235
+ if (buf.length <= limit) return source
236
+ const ellipsis = limit >= 3 ? '…' : ''
237
+ let end = limit - Buffer.byteLength(ellipsis, 'utf8')
238
+ while (end > 0 && (buf[end] & 0xc0) === 0x80) end -= 1
239
+ return buf.subarray(0, end).toString('utf8') + ellipsis
240
+ }
241
+
242
+ /**
243
+ * 进程内内存镜像:磁盘层抛错(只读文件系统、磁盘满、权限被夺)时接管,
244
+ * 使「记住 / 召回」在**本次进程生命周期内**继续可用,而不是整个功能失效。
245
+ *
246
+ * 它只存在于进程内存:**重启即丢**,不是持久化,也不是第二份磁盘文件。
247
+ * 接口与磁盘层同名同形(`readStore`/`writeStore`/`addEntry`/`searchEntries`/`storeDir`/`scopeOf`/`storeFile`),
248
+ * 调用方可按同一个句柄使用,无需分支。
249
+ */
250
+ export function createMemoryStore() {
251
+ /** @type {Map<string, object>} 分域键 → 文档;仅本进程可见。 */
252
+ const docs = new Map()
253
+ const clone = (doc) => structuredClone(doc)
254
+
255
+ return {
256
+ scopeOf,
257
+ storeDir() {
258
+ return 'memory:'
259
+ },
260
+ storeFile(scope) {
261
+ return `memory:${fileNameFor(scope)}`
262
+ },
263
+ readStore(scope) {
264
+ const doc = docs.get(scope)
265
+ return doc === undefined ? emptyDoc(scope) : clone(doc)
266
+ },
267
+ writeStore(scope, doc) {
268
+ docs.set(scope, clone({ ...emptyDoc(scope), ...doc, scope }))
269
+ },
270
+ addEntry(store, entry) {
271
+ const next = addEntry(store, entry)
272
+ if (next?.scope !== undefined) docs.set(next.scope, clone(next))
273
+ return next
274
+ },
275
+ searchEntries,
276
+ textOf,
277
+ tokens,
278
+ clip,
279
+ }
280
+ }
281
+
282
+ /**
283
+ * 磁盘 → 进程内镜像的降级包装:模型的三个工具都经过它读写。
284
+ *
285
+ * 两条实测约束:
286
+ * - 首次降级时把**成功读到**的磁盘文档灌进镜像,且只在镜像为空时灌——否则第二次降级会用空占位
287
+ * 文档覆盖已有镜像,造成「remember(A) 成功、再 remember(B) 后 recall(A) 变空」的丢记忆。
288
+ * - 一旦某个分域降级,镜像就是本进程内该分域的权威视图:后续读写都不再碰磁盘,避免权限恢复后
289
+ * 出现「写到磁盘但读到镜像」的双权威(split authority)。
290
+ */
291
+ export function createFallbackStore() {
292
+ const mirrors = new Map()
293
+ const causes = new Map()
294
+
295
+ const mirrorFor = (scope) => {
296
+ let mirror = mirrors.get(scope)
297
+ if (mirror === undefined) {
298
+ mirror = createMemoryStore()
299
+ mirrors.set(scope, mirror)
300
+ }
301
+ return mirror
302
+ }
303
+
304
+ const seed = (handle, scope, diskDoc) => {
305
+ if (handle.readStore(scope).entries.length > 0) return
306
+ handle.writeStore(scope, diskDoc)
307
+ }
308
+
309
+ return {
310
+ /** 读:已降级的分域只读镜像;未降级时读盘,失败即返回镜像并附降级原因。 */
311
+ load(scope) {
312
+ const cause = causes.get(scope)
313
+ if (cause !== undefined) {
314
+ const handle = mirrorFor(scope)
315
+ return { doc: handle.readStore(scope), path: handle.storeFile(scope), degraded: true, cause }
316
+ }
317
+ try {
318
+ return { doc: readStore(scope), path: storeFile(scope), degraded: false }
319
+ } catch (error) {
320
+ const handle = mirrorFor(scope)
321
+ return { doc: handle.readStore(scope), path: handle.storeFile(scope), degraded: true, cause: error }
322
+ }
323
+ },
324
+ /** 追加:降级后只追加到镜像;磁盘失败时降级,并把已读到的文档灌进镜像再追加。 */
325
+ append(scope, entry) {
326
+ const cause = causes.get(scope)
327
+ if (cause !== undefined) {
328
+ const handle = mirrorFor(scope)
329
+ const doc = handle.addEntry(handle.readStore(scope), entry)
330
+ return { doc, path: handle.storeFile(scope), degraded: true, cause }
331
+ }
332
+ let diskDoc
333
+ try {
334
+ diskDoc = readStore(scope)
335
+ const doc = addEntry(diskDoc, entry)
336
+ writeStore(scope, doc)
337
+ return { doc, path: storeFile(scope), degraded: false }
338
+ } catch (error) {
339
+ causes.set(scope, error)
340
+ const handle = mirrorFor(scope)
341
+ if (diskDoc !== undefined) seed(handle, scope, diskDoc)
342
+ const doc = handle.addEntry(handle.readStore(scope), entry)
343
+ return { doc, path: handle.storeFile(scope), degraded: true, cause: error }
344
+ }
345
+ },
346
+ }
347
+ }
package/sweep.js ADDED
@@ -0,0 +1,296 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { storeDir, scopeOf, writeAtomicFile } from './store.js'
4
+ import * as defaultRuntime from './trivium-runtime.js'
5
+ import { activeRetainSession } from './extract.js'
6
+
7
+ /**
8
+ * 启动 + 周期扫描:只决定**访问哪些会话**,读取与去重全部交给 `extract.js` 的 `retainSession`。
9
+ *
10
+ * 三道闸门:间隔(只挡周期)、revision(挡未变的整个会话;`SessionRecord` 没有 revision,
11
+ * 令牌来自 `sessionPersistence.stat`,实测 §Q1)、存活。逐轮对账交给 retain,绝不因「最后一轮
12
+ * 完成」跳过整个会话(实测 §O 会永久丢失更早的轮次)。启动扫描永不被 `lastSweepAt` 挡掉——
13
+ * 它是进程重启后唯一能捞回被 `kill -9` 的轮次的路径(实测 §L)。全部 fail-open。
14
+ *
15
+ * 第三个入口是**按需补记**(`agent/inbox/claimed`):它只校验本会话、只调用同一条 retain 流水线、
16
+ * 只写存储,绝不注入或改动任何提示内容;扫描负责「访问哪些会话」,它负责「回答之前把本会话补齐」。
17
+ */
18
+
19
+ const SWEEP_STATE_FILE = 'sweep-state.json'
20
+
21
+ const DEFAULT_INTERVAL_MS = 5 * 60 * 1000
22
+
23
+ /**
24
+ * 按需补记的时间上限(毫秒):它跑在用户的关键路径上,所以默认 1.5 秒后就放弃等待并记一条警告。
25
+ * 由 `startSweeper(ctx, { onDemandTimeoutMs })` 覆盖(非有限值或 <= 0 时用默认值)。
26
+ */
27
+ const DEFAULT_ON_DEMAND_TIMEOUT_MS = 1500
28
+
29
+ /** 超时哨兵:`retainSession` 的返回值是对象,用它区分「超时」与「没有新内容」。 */
30
+ const ON_DEMAND_TIMEOUT = Symbol('on-demand-timeout')
31
+
32
+ function sweepStateFile() {
33
+ return resolve(storeDir(), SWEEP_STATE_FILE)
34
+ }
35
+
36
+ function emptyState() {
37
+ return { version: 1, lastSweepAt: 0, sessions: {} }
38
+ }
39
+
40
+ /** 状态只是闸门:缺失、损坏、形状不对一律降级成空状态,最坏多扫一遍,绝不中止扫描。 */
41
+ function readState(report) {
42
+ const file = sweepStateFile()
43
+ let raw
44
+ try {
45
+ raw = readFileSync(file, 'utf8')
46
+ } catch (error) {
47
+ if (error?.code !== 'ENOENT') report('state-read', `sweep: state unreadable (${error?.code ?? 'error'}), starting empty: ${error?.message ?? String(error)}`)
48
+ return emptyState()
49
+ }
50
+ let doc
51
+ try {
52
+ doc = JSON.parse(raw)
53
+ } catch (error) {
54
+ report('state-parse', `sweep: state is not valid JSON, starting empty: ${error?.message ?? String(error)}`)
55
+ return emptyState()
56
+ }
57
+ if (doc === null || typeof doc !== 'object') {
58
+ report('state-shape', 'sweep: state has the wrong shape, starting empty')
59
+ return emptyState()
60
+ }
61
+ const sessions = {}
62
+ if (doc.sessions !== null && typeof doc.sessions === 'object') {
63
+ for (const [id, value] of Object.entries(doc.sessions)) {
64
+ if (id === '' || value === null || typeof value !== 'object') continue
65
+ if (typeof value.revision !== 'string' || value.revision === '') continue
66
+ sessions[id] = { revision: value.revision, entries: Number.isFinite(value.entries) ? value.entries : 0 }
67
+ }
68
+ }
69
+ return { version: 1, lastSweepAt: Number.isFinite(doc.lastSweepAt) ? doc.lastSweepAt : 0, sessions }
70
+ }
71
+
72
+ export function startSweeper(ctx, deps = {}) {
73
+ const log = typeof deps?.log === 'function' ? deps.log : () => {}
74
+ const runtime = deps?.runtime ?? defaultRuntime
75
+ const say = (text) => {
76
+ try {
77
+ log(text)
78
+ } catch {
79
+ }
80
+ }
81
+ const reported = new Set()
82
+ const report = (key, text) => {
83
+ if (reported.has(key)) return
84
+ reported.add(key)
85
+ say(text)
86
+ }
87
+
88
+ const intervalMs = Number.isFinite(deps?.intervalMs) && deps.intervalMs >= 0 ? Math.floor(deps.intervalMs) : DEFAULT_INTERVAL_MS
89
+ const onDemandTimeoutMs = Number.isFinite(deps?.onDemandTimeoutMs) && deps.onDemandTimeoutMs > 0
90
+ ? Math.floor(deps.onDemandTimeoutMs)
91
+ : DEFAULT_ON_DEMAND_TIMEOUT_MS
92
+
93
+ const idOf = (record) => {
94
+ const id = record?.header?.id
95
+ return typeof id === 'string' && id.length > 0 ? id : null
96
+ }
97
+
98
+ async function sweepOnce(kind) {
99
+ const state = readState(report)
100
+ if (kind === 'periodic' && Date.now() - state.lastSweepAt < intervalMs) {
101
+ return { kind, skipped: 'interval', visited: 0 }
102
+ }
103
+
104
+ const query = ctx?.sessionQuery
105
+ if (query === undefined || typeof query.listSessions !== 'function') return { kind, skipped: 'no-session-query', visited: 0 }
106
+
107
+ const retain = activeRetainSession()
108
+ if (typeof retain !== 'function') {
109
+ report('no-retain', 'sweep: retain pipeline unavailable (extract path not loaded); skipping')
110
+ return { kind, skipped: 'no-retain', visited: 0 }
111
+ }
112
+
113
+ let records
114
+ try {
115
+ records = await query.listSessions()
116
+ } catch (error) {
117
+ report('list', `sweep: listSessions failed (${error?.message ?? String(error)}); skipping this round`)
118
+ return { kind, skipped: 'list-failed', visited: 0 }
119
+ }
120
+
121
+ const persistence = ctx?.sessionPersistence
122
+ const nextSessions = { ...state.sessions }
123
+ let visited = 0
124
+ // 账本按「本会话已保留的轮次」向 TriviumDB 现算(与 extract.js 的 `seen` 同一 classification);
125
+ // 同一趟里按 (scope,id) 缓存,写入成功后作废。读失败返回 null,由调用方当作「不知道」处理。
126
+ const ledger = new Map()
127
+ const ledgerCount = async (scope, id) => {
128
+ const key = `${scope}\u0000${id}`
129
+ if (!ledger.has(key)) {
130
+ try {
131
+ ledger.set(key, await runtime.countRetained(scope, id))
132
+ } catch (error) {
133
+ report(`ledger:${id}`, `sweep: ledger read failed for ${id} (${error?.code ?? 'error'}: ${error?.message ?? String(error)}); skipped`)
134
+ ledger.set(key, null)
135
+ }
136
+ }
137
+ return ledger.get(key)
138
+ }
139
+
140
+ for (const record of Array.isArray(records) ? records : []) {
141
+ const id = idOf(record)
142
+ if (id === null) continue
143
+ // 存活会话的日志有未闭合 turn/start,读它会被补平成半截 interrupted 轮次(实测 §P1)。
144
+ if (record.live === true) continue
145
+ const header = record.header
146
+ // 子会话的继承前缀由 retain 按 inheritedEventCount 切分;这里不访问它们(实测 §P2)。
147
+ if (header?.origin === 'subagent' || Number(header?.delegationDepth ?? 0) > 0) continue
148
+
149
+ let revision = null
150
+ if (persistence !== undefined && typeof persistence.stat === 'function') {
151
+ let snapshot
152
+ try {
153
+ snapshot = await persistence.stat(id)
154
+ } catch (error) {
155
+ report(`stat:${id}`, `sweep: stat failed for ${id} (${error?.message ?? String(error)}); skipped`)
156
+ continue
157
+ }
158
+ if (snapshot === undefined || snapshot === null) continue
159
+ revision = typeof snapshot.revision === 'string' ? snapshot.revision : String(snapshot.revision ?? '')
160
+ // revision 未变只说明日志没变;账本少了条目正是丢写(日志没被改写),所以再核对条目数。
161
+ if (revision !== '') {
162
+ const prev = state.sessions[id]
163
+ if (prev?.revision === revision) {
164
+ const have = await ledgerCount(scopeOf(record), id)
165
+ if (have === null || have >= (Number(prev.entries) || 0)) continue
166
+ }
167
+ }
168
+ }
169
+
170
+ try {
171
+ const result = await retain(id, 'sweep')
172
+ visited += 1
173
+ if (result?.ok !== false && revision !== null && revision !== '') {
174
+ // 写入后作废该 scope 的缓存,条目数必须反映本轮真实结果。
175
+ ledger.delete(`${scopeOf(record)}\u0000${id}`)
176
+ const entries = await ledgerCount(scopeOf(record), id)
177
+ nextSessions[id] = { revision, entries: entries === null ? 0 : entries }
178
+ }
179
+ } catch (error) {
180
+ report(`retain:${id}`, `sweep: retain failed for ${id} (${error?.message ?? String(error)}); skipped`)
181
+ }
182
+ }
183
+
184
+ try {
185
+ writeAtomicFile(sweepStateFile(), `${JSON.stringify({ version: 1, lastSweepAt: Date.now(), sessions: nextSessions })}\n`)
186
+ } catch (error) {
187
+ // 状态不可写时宁可丢下一轮的闸门,也不能让这一轮的记忆丢失。
188
+ report('state-write', `sweep: state not writable (${error?.code ?? 'error'}), continuing: ${error?.message ?? String(error)}`)
189
+ }
190
+ return { kind, visited }
191
+ }
192
+
193
+ let inflight = null
194
+ const fire = (kind) => {
195
+ if (inflight !== null) return inflight
196
+ const task = sweepOnce(kind)
197
+ .catch((error) => {
198
+ report('sweep-threw', `sweep: ${kind} sweep failed (${error?.message ?? String(error)}); swallowed`)
199
+ return { kind, skipped: 'threw', visited: 0 }
200
+ })
201
+ .finally(() => {
202
+ if (inflight === task) inflight = null
203
+ })
204
+ inflight = task
205
+ return task
206
+ }
207
+
208
+ const timer = setInterval(() => {
209
+ void fire('periodic')
210
+ }, intervalMs)
211
+ if (typeof timer?.unref === 'function') timer.unref()
212
+
213
+ const stop = () => {
214
+ try {
215
+ clearInterval(timer)
216
+ } catch {
217
+ }
218
+ }
219
+
220
+ if (typeof ctx?.effect === 'function') {
221
+ try {
222
+ ctx.effect(() => () => stop())
223
+ } catch (error) {
224
+ report('effect', `sweep: cannot register disposal via effect (${error?.message ?? String(error)})`)
225
+ }
226
+ }
227
+ if (reported.has('effect') || typeof ctx?.effect !== 'function') {
228
+ // 兜底:拿不到 fiber effect 时改挂 dispose 事件;再不行就留下 unref 过的定时器(不会拦住进程退出)。
229
+ try {
230
+ if (typeof ctx?.on === 'function') ctx.on('dispose', () => stop())
231
+ } catch (error) {
232
+ report('dispose', `sweep: cannot register disposal via dispose event (${error?.message ?? String(error)})`)
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 按需补记:`agent/inbox/claimed` 实测早于 `system-prompt/assemble` 与 `agent/pre-step`,且已带着
238
+ * 用户消息(事实文件 §N),所以它是「回答之前」最早能动手的挂点。它调用与扫描**同一条**
239
+ * `retainSession(id, 'on-demand')`:没有新内容时由游标与条目键把代价压成零,而**不**按「刚扫过」
240
+ * 整体跳过——那种闸门会让这条路径在真实进程里永远做不到事(评审实测)。
241
+ *
242
+ * 只校验**本**会话(别的会话是扫描的职责),只写存储、绝不注入或改动提示内容。宿主以非否决
243
+ * `emit` 分发本事件并丢弃返回值(`packages/core/agent/src/dispatch.ts` 的 `emit`),所以失败与
244
+ * 超时都绝不会抛进回合或拖住它;时间上限只决定「我们还要不要等」,到点就记一条警告继续。
245
+ */
246
+ function onUserMessageClaimed(claimed) {
247
+ try {
248
+ if (claimed?.message?.source?.kind !== 'user') return
249
+ const sessionId = claimed?.agent?.session?.id
250
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return
251
+ const retain = activeRetainSession()
252
+ if (typeof retain !== 'function') {
253
+ report('on-demand-no-retain', 'sweep: on-demand backfill skipped: the retain pipeline is not loaded')
254
+ return
255
+ }
256
+ let timer
257
+ const bound = new Promise((resolve) => {
258
+ timer = setTimeout(() => resolve(ON_DEMAND_TIMEOUT), onDemandTimeoutMs)
259
+ if (typeof timer?.unref === 'function') timer.unref()
260
+ })
261
+ const work = Promise.resolve().then(() => retain(sessionId, 'on-demand'))
262
+ void Promise.race([work, bound])
263
+ .then((outcome) => {
264
+ if (outcome === ON_DEMAND_TIMEOUT) {
265
+ report(`on-demand-slow:${sessionId}`, `sweep: on-demand backfill for ${sessionId} exceeded ${onDemandTimeoutMs} ms; the turn continues and the write finishes in the background`)
266
+ return
267
+ }
268
+ if (outcome?.written > 0) {
269
+ say(`sweep: on-demand backfill retained ${outcome.written} turn(s) for ${sessionId}`)
270
+ }
271
+ }, (error) => {
272
+ report(`on-demand:${sessionId}`, `sweep: on-demand backfill for ${sessionId} failed (${error?.message ?? String(error)}); swallowed`)
273
+ })
274
+ .finally(() => {
275
+ try {
276
+ clearTimeout(timer)
277
+ } catch {
278
+ }
279
+ })
280
+ } catch (error) {
281
+ report('on-demand-hook', `sweep: on-demand hook failed (${error?.message ?? String(error)}); swallowed`)
282
+ }
283
+ }
284
+
285
+ if (typeof ctx?.on === 'function') {
286
+ try {
287
+ ctx.on('agent/inbox/claimed', onUserMessageClaimed)
288
+ } catch (error) {
289
+ report('on-demand-listen', `sweep: cannot listen to agent/inbox/claimed (${error?.message ?? String(error)})`)
290
+ }
291
+ }
292
+
293
+ void fire('startup')
294
+
295
+ return { stop }
296
+ }