@asd2233996/dsh-auto-context 0.0.0-stage → 1.15.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/LICENSE +21 -0
- package/README.en.md +113 -0
- package/README.md +250 -2
- package/cordis.patch.yml +23 -0
- package/docs/product-introduction.md +282 -0
- package/docs/structured-kb-notes.md +179 -0
- package/lib/actions.js +2758 -0
- package/lib/extract.js +1647 -0
- package/lib/graph.js +1628 -0
- package/lib/groups.js +307 -0
- package/lib/impl.js +170 -0
- package/lib/index.js +43 -0
- package/lib/kb-tools.js +384 -0
- package/lib/kb.js +254 -0
- package/lib/kg-archive.js +1042 -0
- package/lib/kg-store.js +1427 -0
- package/lib/recall.js +62 -0
- package/lib/scan.js +2537 -0
- package/lib/segments.js +660 -0
- package/lib/store.js +365 -0
- package/lib/util.js +64 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
|
@@ -0,0 +1,1042 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context-manager — 信息库归档(P1 surface 接管)纯函数模块。
|
|
3
|
+
*
|
|
4
|
+
* 目标(用户需求):除最近一轮外,旧轮次不再以 raw 形式进入模型上下文,
|
|
5
|
+
* 只能通过信息库工具检索。实现方式沿用 DSH 官方 surface 协议:
|
|
6
|
+
* `compaction/prune`(影子价格)+ 紧跟一条 `user/message` 替换整个旧前缀,
|
|
7
|
+
* 把旧历史折叠成一条**常量级归档标记**(`<context-archived …/>`)。
|
|
8
|
+
* 原始事件一个都不删,人类对话记录/导出/fork 均不受影响。
|
|
9
|
+
*
|
|
10
|
+
* 本模块**不做任何 append**,只提供可测试的纯函数:
|
|
11
|
+
* - `collectTurnBoundaries(events)`:从 snapshotEvents 形态的事件数组解析轮次边界;
|
|
12
|
+
* - `selectArchiveRange({events,surface,keepCompletedTurns,archivedThroughTurn})`:
|
|
13
|
+
* 选择要替换的 surface 区间(保留最近 N 个已完成轮、保护 node0、折叠旧 marker);
|
|
14
|
+
* - `validateArchivePlan({events,surface,plan,turnStatuses})`:六项覆盖证明;
|
|
15
|
+
* - `buildArchiveMarkerText/buildArchiveMarkerMessage`:常量结构标记(可带 pinned 摘要);
|
|
16
|
+
* - `isArchiveMarker/archiveMarkerInfo`:标记识别与解析。
|
|
17
|
+
*
|
|
18
|
+
* 约定:
|
|
19
|
+
* - 只把 `user/message` 且 `source.kind === 'user'` 视为"真实用户轮次起点";
|
|
20
|
+
* context-manager 自己的占位(stub)/归档 marker/notice 的 source.kind 不是 'user',
|
|
21
|
+
* 因此不会污染轮次判定。
|
|
22
|
+
* - surface 是 `session.surface.nodes`(模型可见顺序的 seq 列表);事件数组是
|
|
23
|
+
* `session.snapshotEvents()`(不可变日志,seq 连续)。
|
|
24
|
+
* - 归档标记固定使用 `source.kind = 'context-manager'`、`form = 'notice'`,
|
|
25
|
+
* 与现有丢弃占位区分开;版本/预算常量见本文件顶部。
|
|
26
|
+
* @module context-manager/kg-archive
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** 归档标记的 XML 标签(模型可见;识别与折叠都依赖它)。 */
|
|
30
|
+
export const ARCHIVE_TAG = 'context-archived'
|
|
31
|
+
/** 归档标记的 message.source.kind(与 context-manager 其它注入一致)。 */
|
|
32
|
+
export const ARCHIVE_SOURCE_KIND = 'context-manager'
|
|
33
|
+
/** 归档标记的 message.source.form。 */
|
|
34
|
+
export const ARCHIVE_NOTICE_FORM = 'notice'
|
|
35
|
+
/** 默认保留的"已完成轮次"数量(用户目标=1;集成层可用配置覆盖)。 */
|
|
36
|
+
export const DEFAULT_KEEP_COMPLETED_TURNS = 1
|
|
37
|
+
/** marker 文本 token 预算(按宿主 token-meter 固定密度估算:4 字符/token + 8 开销)。 */
|
|
38
|
+
export const MARKER_TOKEN_BUDGET = 120
|
|
39
|
+
/** marker 基础文本(不含 pinned 摘要)的字符上限,= 预算换算并留出余量。 */
|
|
40
|
+
export const MARKER_MAX_CHARS = 448
|
|
41
|
+
/** pinned 摘要块的字符上限(单独预算,避免常驻信息把 marker 撑成第二段历史)。 */
|
|
42
|
+
export const PINNED_MAX_CHARS = 600
|
|
43
|
+
/** pinned 摘要单行字符上限。 */
|
|
44
|
+
export const PINNED_LINE_MAX_CHARS = 120
|
|
45
|
+
|
|
46
|
+
/** 覆盖证明/失败原因的结构化 code(供日志与工具返回区分失败原因)。 */
|
|
47
|
+
export const ARCHIVE_FAILURE = Object.freeze({
|
|
48
|
+
/** plan/events/surface 形状非法(缺字段、非数组、索引非法)。 */
|
|
49
|
+
PLAN_INVALID: 'ARCHIVE_PLAN_INVALID',
|
|
50
|
+
/** 替换区间不是当前 surface 的连续切片(或 shadowedSeqs 与区间不一致)。 */
|
|
51
|
+
NOT_CONTIGUOUS: 'ARCHIVE_NOT_CONTIGUOUS',
|
|
52
|
+
/** shadowedSeqs 覆盖不完整/含重复/含日志中不存在的事件 seq。 */
|
|
53
|
+
COVERAGE: 'ARCHIVE_COVERAGE',
|
|
54
|
+
/** 范围内某轮尚未抽取完成(missing / pending / failed;只接受 done|skipped)。 */
|
|
55
|
+
TURN_NOT_INDEXED: 'TURN_NOT_INDEXED',
|
|
56
|
+
/** 替换区间起点或终点切断了 tool-call/tool-result 配对。 */
|
|
57
|
+
TOOL_PAIRING: 'TOOL_PAIRING',
|
|
58
|
+
/** 试图替换 surface 节点 0 的 system prompt。 */
|
|
59
|
+
NODE0: 'NODE0',
|
|
60
|
+
/** 会话日志里有未闭合的 compaction/start(内置压缩正在进行)。 */
|
|
61
|
+
COMPACTION_LOCK: 'COMPACTION_LOCK',
|
|
62
|
+
/** 旧归档 marker 未被折叠进本次替换(会造成 marker 堆积)。 */
|
|
63
|
+
MARKER_FOLD: 'MARKER_FOLD'
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
/** `selectArchiveRange` 不可替换时的结构化原因。 */
|
|
67
|
+
export const ARCHIVE_SKIP_REASON = Object.freeze({
|
|
68
|
+
INVALID_INPUT: 'INVALID_INPUT',
|
|
69
|
+
NO_TURNS: 'NO_TURNS',
|
|
70
|
+
NO_NEW_TURNS: 'NO_NEW_TURNS',
|
|
71
|
+
NOTHING_TO_ARCHIVE: 'NOTHING_TO_ARCHIVE',
|
|
72
|
+
MARKER_IN_KEPT_RANGE: 'MARKER_IN_KEPT_RANGE',
|
|
73
|
+
KEPT_TURN_NOT_ON_SURFACE: 'KEPT_TURN_NOT_ON_SURFACE'
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
/* -------------------------------------------------------------------------- */
|
|
77
|
+
/* 通用小工具 */
|
|
78
|
+
/* -------------------------------------------------------------------------- */
|
|
79
|
+
|
|
80
|
+
/** 是不是普通对象(排除数组/null)。 */
|
|
81
|
+
function isRecord(value) {
|
|
82
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 读取非负整数;非法/缺失返回 null。 */
|
|
86
|
+
function readNonNegativeInt(value) {
|
|
87
|
+
let number = NaN
|
|
88
|
+
if (typeof value === 'number') number = value
|
|
89
|
+
else if (typeof value === 'string' && value.trim() !== '') number = Number(value)
|
|
90
|
+
if (!Number.isFinite(number) || number < 0) return null
|
|
91
|
+
return Math.round(number)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 读取整数(允许 0/负数,用于索引);非法返回 null。 */
|
|
95
|
+
function readInteger(value) {
|
|
96
|
+
let number = NaN
|
|
97
|
+
if (typeof value === 'number') number = value
|
|
98
|
+
else if (typeof value === 'string' && value.trim() !== '') number = Number(value)
|
|
99
|
+
if (!Number.isFinite(number)) return null
|
|
100
|
+
return Math.trunc(number)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 折叠空白并 trim。 */
|
|
104
|
+
function cleanInline(value) {
|
|
105
|
+
if (typeof value !== 'string') return ''
|
|
106
|
+
return value.replace(/\s+/gu, ' ').trim()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** 按 code point 截断(不加省略号)。 */
|
|
110
|
+
function truncateCodePoints(text, maxChars) {
|
|
111
|
+
if (typeof text !== 'string' || text === '') return ''
|
|
112
|
+
if (!Number.isFinite(maxChars) || maxChars <= 0) return ''
|
|
113
|
+
const points = Array.from(text)
|
|
114
|
+
return points.length <= maxChars ? text : points.slice(0, maxChars).join('')
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 事件 seq(安全整数才算)。 */
|
|
118
|
+
function seqOf(event) {
|
|
119
|
+
return isRecord(event) && Number.isSafeInteger(event.seq) && event.seq >= 0 ? event.seq : null
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 事件类型(非字符串按空串)。 */
|
|
123
|
+
function typeOf(event) {
|
|
124
|
+
return isRecord(event) && typeof event.type === 'string' ? event.type : ''
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 读取消息内容块数组(user/message 直接在 data;assistant/tool 在 data.message)。 */
|
|
128
|
+
function contentBlocksOf(event) {
|
|
129
|
+
if (!isRecord(event)) return []
|
|
130
|
+
if (event.type === 'user/message') {
|
|
131
|
+
return Array.isArray(event.data?.content) ? event.data.content : []
|
|
132
|
+
}
|
|
133
|
+
if (event.type === 'assistant/message' || event.type === 'tool/result') {
|
|
134
|
+
return Array.isArray(event.data?.message?.content) ? event.data.message.content : []
|
|
135
|
+
}
|
|
136
|
+
return []
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 一条消息里是否含非空文本块(用于判断轮次是否值得抽取/覆盖)。 */
|
|
140
|
+
function hasVisibleText(event) {
|
|
141
|
+
const blocks = contentBlocksOf(event)
|
|
142
|
+
for (const block of blocks) {
|
|
143
|
+
if (!isRecord(block) || block.type !== 'text') continue
|
|
144
|
+
if (typeof block.text === 'string' && block.text.trim() !== '') return true
|
|
145
|
+
}
|
|
146
|
+
return false
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** 一条 assistant 消息里有几个 tool-call 块。 */
|
|
150
|
+
function countToolCalls(event) {
|
|
151
|
+
if (!isRecord(event) || event.type !== 'assistant/message') return 0
|
|
152
|
+
let count = 0
|
|
153
|
+
for (const block of contentBlocksOf(event)) {
|
|
154
|
+
if (isRecord(block) && block.type === 'tool-call') count += 1
|
|
155
|
+
}
|
|
156
|
+
return count
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 事件对应的 turn 号(turn/start / turn/end 的 data.turn)。 */
|
|
160
|
+
function turnOfEvent(event) {
|
|
161
|
+
if (!isRecord(event)) return null
|
|
162
|
+
if (event.type !== 'turn/start' && event.type !== 'turn/end') return null
|
|
163
|
+
return readNonNegativeInt(event.data?.turn)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/* -------------------------------------------------------------------------- */
|
|
167
|
+
/* 1) 轮次边界 */
|
|
168
|
+
/* -------------------------------------------------------------------------- */
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 从会话事件数组解析 turn/start..turn/end 边界。
|
|
172
|
+
*
|
|
173
|
+
* 只把 `user/message` 且 `source.kind === 'user'` 记为真实用户消息(userSeqs),
|
|
174
|
+
* 因此 context-manager 的占位/归档 marker/tool-result 注入不会误判为轮次起点。
|
|
175
|
+
* 未闭合的轮次(进程中断/正在生成)以 `completed=false` 返回,调用方必须保留它们
|
|
176
|
+
* 的 raw 上下文(不得归档)。
|
|
177
|
+
*
|
|
178
|
+
* @param {readonly object[]} events - `session.snapshotEvents()`(或测试等价数组)。
|
|
179
|
+
* @returns {object[]} 轮次边界数组(按日志顺序):
|
|
180
|
+
* `{turn,startIndex,endIndex,startSeq,endSeq,seqs,userSeqs,userIndexes,userCount,
|
|
181
|
+
* hasUser,hasAssistant,hasText,hasToolCalls,toolCallCount,hasToolResults,
|
|
182
|
+
* hasSystemMessage,completed,endReason}`。
|
|
183
|
+
*/
|
|
184
|
+
export function collectTurnBoundaries(events) {
|
|
185
|
+
const turns = []
|
|
186
|
+
if (!Array.isArray(events)) return turns
|
|
187
|
+
|
|
188
|
+
let open = null
|
|
189
|
+
/** 收尾当前打开的轮次并推入结果。 */
|
|
190
|
+
const finalize = (endIndex, completed, endReason) => {
|
|
191
|
+
if (open === null) return
|
|
192
|
+
const turn = open
|
|
193
|
+
open = null
|
|
194
|
+
const lastIndex = Number.isFinite(endIndex) ? Math.max(turn.startIndex, Math.trunc(endIndex)) : events.length - 1
|
|
195
|
+
const seqs = []
|
|
196
|
+
for (let index = turn.startIndex; index <= lastIndex; index += 1) {
|
|
197
|
+
const seq = seqOf(events[index])
|
|
198
|
+
if (seq !== null) seqs.push(seq)
|
|
199
|
+
}
|
|
200
|
+
const startSeq = seqs.length > 0 ? seqs[0] : null
|
|
201
|
+
const endSeq = seqs.length > 0 ? seqs[seqs.length - 1] : null
|
|
202
|
+
turns.push({
|
|
203
|
+
turn: turn.turn,
|
|
204
|
+
startIndex: turn.startIndex,
|
|
205
|
+
endIndex: lastIndex,
|
|
206
|
+
startSeq,
|
|
207
|
+
endSeq,
|
|
208
|
+
seqs,
|
|
209
|
+
userSeqs: [...turn.userSeqs],
|
|
210
|
+
userIndexes: [...turn.userIndexes],
|
|
211
|
+
userCount: turn.userSeqs.length,
|
|
212
|
+
hasUser: turn.userSeqs.length > 0,
|
|
213
|
+
hasAssistant: turn.hasAssistant,
|
|
214
|
+
hasText: turn.hasText,
|
|
215
|
+
hasToolCalls: turn.hasToolCalls,
|
|
216
|
+
toolCallCount: turn.toolCallCount,
|
|
217
|
+
hasToolResults: turn.hasToolResults,
|
|
218
|
+
hasSystemMessage: turn.hasSystemMessage,
|
|
219
|
+
completed: completed === true,
|
|
220
|
+
endReason: endReason ?? null
|
|
221
|
+
})
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
for (let index = 0; index < events.length; index += 1) {
|
|
225
|
+
const event = events[index]
|
|
226
|
+
if (!isRecord(event)) continue
|
|
227
|
+
const type = typeOf(event)
|
|
228
|
+
|
|
229
|
+
if (type === 'turn/start') {
|
|
230
|
+
// 上一个轮次没有 turn/end(中断/损坏):按未完成轮次保留,不参与归档。
|
|
231
|
+
if (open !== null) finalize(index - 1, false, 'missing-turn-end')
|
|
232
|
+
open = {
|
|
233
|
+
turn: turnOfEvent(event) ?? 0,
|
|
234
|
+
startIndex: index,
|
|
235
|
+
userSeqs: [],
|
|
236
|
+
userIndexes: [],
|
|
237
|
+
hasAssistant: false,
|
|
238
|
+
hasText: false,
|
|
239
|
+
hasToolCalls: false,
|
|
240
|
+
toolCallCount: 0,
|
|
241
|
+
hasToolResults: false,
|
|
242
|
+
hasSystemMessage: false
|
|
243
|
+
}
|
|
244
|
+
continue
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
if (type === 'turn/end') {
|
|
248
|
+
const endTurn = turnOfEvent(event)
|
|
249
|
+
if (open !== null && (endTurn === null || endTurn === open.turn)) {
|
|
250
|
+
finalize(index, true, event.data?.reason ?? null)
|
|
251
|
+
continue
|
|
252
|
+
}
|
|
253
|
+
if (open !== null) finalize(index - 1, false, 'missing-turn-end')
|
|
254
|
+
// 孤立的 turn/end(没有匹配的 turn/start):忽略。
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (open === null) continue
|
|
259
|
+
const seq = seqOf(event)
|
|
260
|
+
|
|
261
|
+
if (type === 'user/message') {
|
|
262
|
+
const kind = event.data?.source?.kind
|
|
263
|
+
if (kind === 'user') {
|
|
264
|
+
open.hasUser = true
|
|
265
|
+
if (seq !== null) open.userSeqs.push(seq)
|
|
266
|
+
open.userIndexes.push(index)
|
|
267
|
+
}
|
|
268
|
+
if (hasVisibleText(event)) open.hasText = true
|
|
269
|
+
continue
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (type === 'assistant/message') {
|
|
273
|
+
open.hasAssistant = true
|
|
274
|
+
const calls = countToolCalls(event)
|
|
275
|
+
if (calls > 0) {
|
|
276
|
+
open.hasToolCalls = true
|
|
277
|
+
open.toolCallCount += calls
|
|
278
|
+
}
|
|
279
|
+
if (hasVisibleText(event)) open.hasText = true
|
|
280
|
+
continue
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (type === 'tool/result') {
|
|
284
|
+
open.hasToolResults = true
|
|
285
|
+
continue
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (type === 'system/message') {
|
|
289
|
+
open.hasSystemMessage = true
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// 日志末尾仍未闭合的轮次:保留 raw,不参与归档。
|
|
294
|
+
if (open !== null) finalize(events.length - 1, false, 'missing-turn-end')
|
|
295
|
+
return turns
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/* -------------------------------------------------------------------------- */
|
|
299
|
+
/* 2) 归档标记识别/构建 */
|
|
300
|
+
/* -------------------------------------------------------------------------- */
|
|
301
|
+
|
|
302
|
+
/** 解析 XML 风格属性串(只认固定属性名,值内不含引号)。 */
|
|
303
|
+
function parseAttributes(raw) {
|
|
304
|
+
const attributes = {}
|
|
305
|
+
const pattern = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/gu
|
|
306
|
+
let match
|
|
307
|
+
while ((match = pattern.exec(raw)) !== null) attributes[match[1]] = match[2]
|
|
308
|
+
return attributes
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** 把属性值解析成整数(容忍 "turn 1" 这类前缀)。 */
|
|
312
|
+
function attributeInt(attributes, name) {
|
|
313
|
+
const raw = attributes[name]
|
|
314
|
+
if (typeof raw !== 'string' || raw.trim() === '') return null
|
|
315
|
+
const direct = Number(raw)
|
|
316
|
+
if (Number.isFinite(direct)) return Math.round(direct)
|
|
317
|
+
const digits = raw.replace(/[^0-9-]+/gu, '')
|
|
318
|
+
if (digits === '' || digits === '-') return null
|
|
319
|
+
const parsed = Number(digits)
|
|
320
|
+
return Number.isFinite(parsed) ? Math.round(parsed) : null
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* 一条事件是否是本插件的归档 marker。
|
|
325
|
+
*
|
|
326
|
+
* 严格三重判定(避免普通用户消息正文里恰好引用标签造成误判):
|
|
327
|
+
* 1) `user/message`;2) `source.kind === 'context-manager'`;3) 第一个 text block
|
|
328
|
+
* 以 `<context-archived` 开头。
|
|
329
|
+
*
|
|
330
|
+
* @param {object} event - 会话事件。
|
|
331
|
+
* @returns {boolean} 是否归档 marker。
|
|
332
|
+
*/
|
|
333
|
+
export function isArchiveMarker(event) {
|
|
334
|
+
if (!isRecord(event) || event.type !== 'user/message') return false
|
|
335
|
+
const message = event.data
|
|
336
|
+
if (!isRecord(message)) return false
|
|
337
|
+
const source = message.source
|
|
338
|
+
if (!isRecord(source) || source.kind !== ARCHIVE_SOURCE_KIND) return false
|
|
339
|
+
const blocks = Array.isArray(message.content) ? message.content : []
|
|
340
|
+
const first = blocks[0]
|
|
341
|
+
if (!isRecord(first) || first.type !== 'text' || typeof first.text !== 'string') return false
|
|
342
|
+
return first.text.trimStart().startsWith(`<${ARCHIVE_TAG}`)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 解析归档 marker 的属性/文本;非 marker 返回 null。
|
|
347
|
+
*
|
|
348
|
+
* @param {object} event - 会话事件。
|
|
349
|
+
* @returns {{fromTurn:number|null,throughTurn:number|null,facts:number|null,
|
|
350
|
+
* scopes:number|null,tokens:number|null,text:string}|null} 标记信息。
|
|
351
|
+
*/
|
|
352
|
+
export function archiveMarkerInfo(event) {
|
|
353
|
+
if (!isArchiveMarker(event)) return null
|
|
354
|
+
const blocks = Array.isArray(event.data?.content) ? event.data.content : []
|
|
355
|
+
const first = blocks[0]
|
|
356
|
+
const text = typeof first?.text === 'string' ? first.text : ''
|
|
357
|
+
const match = new RegExp(`<${ARCHIVE_TAG}\\s+([^>]*?)\\/?>`).exec(text)
|
|
358
|
+
const attributes = match === null ? {} : parseAttributes(match[1])
|
|
359
|
+
return {
|
|
360
|
+
fromTurn: attributeInt(attributes, 'from'),
|
|
361
|
+
throughTurn: attributeInt(attributes, 'through'),
|
|
362
|
+
facts: attributeInt(attributes, 'facts'),
|
|
363
|
+
scopes: attributeInt(attributes, 'scopes'),
|
|
364
|
+
tokens: attributeInt(attributes, 'tokens'),
|
|
365
|
+
text
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* 当前 surface 上的全部归档 marker。
|
|
371
|
+
*
|
|
372
|
+
* @param {readonly object[]} events - 完整事件日志。
|
|
373
|
+
* @param {readonly number[]} surface - `session.surface.nodes`。
|
|
374
|
+
* @returns {{seq:number,surfaceIndex:number,info:object}[]} 按 surface 顺序。
|
|
375
|
+
*/
|
|
376
|
+
export function findArchiveMarkers(events, surface) {
|
|
377
|
+
const markers = []
|
|
378
|
+
if (!Array.isArray(events) || !Array.isArray(surface)) return markers
|
|
379
|
+
const eventBySeq = new Map()
|
|
380
|
+
for (const event of events) {
|
|
381
|
+
const seq = seqOf(event)
|
|
382
|
+
if (seq !== null && !eventBySeq.has(seq)) eventBySeq.set(seq, event)
|
|
383
|
+
}
|
|
384
|
+
for (let index = 0; index < surface.length; index += 1) {
|
|
385
|
+
const seq = surface[index]
|
|
386
|
+
const event = eventBySeq.get(seq)
|
|
387
|
+
if (event === undefined) continue
|
|
388
|
+
const info = archiveMarkerInfo(event)
|
|
389
|
+
if (info === null) continue
|
|
390
|
+
markers.push({ seq, surfaceIndex: index, info })
|
|
391
|
+
}
|
|
392
|
+
return markers
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* 把 pinned 摘要归一化成 marker 内的文本块(去重/截断/总长上限)。
|
|
397
|
+
*
|
|
398
|
+
* @param {unknown} input - 字符串、字符串数组,或 `{text|snippet|line}` 数组。
|
|
399
|
+
* @returns {string} 形如 `- 行1\n- 行2`(空串表示无摘要)。
|
|
400
|
+
*/
|
|
401
|
+
function normalizePinnedDigest(input) {
|
|
402
|
+
const lines = []
|
|
403
|
+
const seen = new Set()
|
|
404
|
+
const pushLine = (value) => {
|
|
405
|
+
const text = cleanInline(value)
|
|
406
|
+
if (text === '') return
|
|
407
|
+
const key = text.toLowerCase()
|
|
408
|
+
if (seen.has(key)) return
|
|
409
|
+
seen.add(key)
|
|
410
|
+
lines.push(`- ${truncateCodePoints(text, PINNED_LINE_MAX_CHARS)}`)
|
|
411
|
+
}
|
|
412
|
+
if (typeof input === 'string') {
|
|
413
|
+
for (const line of input.split('\n')) pushLine(line.replace(/^[-*•]\s*/u, ''))
|
|
414
|
+
} else if (Array.isArray(input)) {
|
|
415
|
+
for (const item of input) {
|
|
416
|
+
if (typeof item === 'string') pushLine(item)
|
|
417
|
+
else if (isRecord(item) && typeof item.text === 'string') pushLine(item.text)
|
|
418
|
+
else if (isRecord(item) && typeof item.snippet === 'string') pushLine(item.snippet)
|
|
419
|
+
else if (isRecord(item) && typeof item.line === 'string') pushLine(item.line)
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (lines.length === 0) return ''
|
|
423
|
+
let text = lines.slice(0, 12).join('\n')
|
|
424
|
+
if (text.length > PINNED_MAX_CHARS) text = `${truncateCodePoints(text, PINNED_MAX_CHARS - 1)}…`
|
|
425
|
+
return text
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* 构建归档 marker 的模型可见文本(常量结构,仅数字变化)。
|
|
430
|
+
*
|
|
431
|
+
* 基础部分只含:属性(from/through/facts/tokens)+ 3 行固定指引,
|
|
432
|
+
* 确保每次归档只改变数字,避免 marker 文本抖动带来的无谓 cache 失效。
|
|
433
|
+
* 可选 pinned 摘要追加在 marker 之后(单独字符预算)。
|
|
434
|
+
*
|
|
435
|
+
* @param {object} [options] - 归档统计。
|
|
436
|
+
* @param {number} [options.fromTurn] - 归档起始轮次(含)。
|
|
437
|
+
* @param {number} [options.throughTurn] - 归档结束轮次(含)。
|
|
438
|
+
* @param {number} [options.facts] - 已入图事实数。
|
|
439
|
+
* @param {number} [options.archivedTokens] - 本次替换省下的 token 数。
|
|
440
|
+
* @param {unknown} [options.pinnedDigest] - 可选的常驻/重要信息摘要(字符串或行数组)。
|
|
441
|
+
* @returns {string} marker 文本(≤ MARKER_TOKEN_BUDGET 的固定结构;pinned 另算)。
|
|
442
|
+
*/
|
|
443
|
+
export function buildArchiveMarkerText(options = {}) {
|
|
444
|
+
const source = isRecord(options) ? options : {}
|
|
445
|
+
const fromTurn = readNonNegativeInt(source.fromTurn) ?? 0
|
|
446
|
+
const throughTurn = Math.max(fromTurn, readNonNegativeInt(source.throughTurn) ?? fromTurn)
|
|
447
|
+
const facts = readNonNegativeInt(source.facts) ?? 0
|
|
448
|
+
const archivedTokens = readNonNegativeInt(source.archivedTokens) ?? 0
|
|
449
|
+
const rounds = throughTurn - fromTurn + 1
|
|
450
|
+
const base = [
|
|
451
|
+
`<${ARCHIVE_TAG} from="${fromTurn}" through="${throughTurn}" facts="${facts}" tokens="${archivedTokens}">`,
|
|
452
|
+
`更早的 ${rounds} 轮对话已归档为结构化信息库,原文仍在会话日志中,但不再放入本次上下文。`,
|
|
453
|
+
'需要旧信息时按序调用:knowledge_index 看信息库目录 → knowledge_digest(scope) 看分节摘要 → knowledge_search 检索条目 → knowledge_evidence(ids) 取原文摘录。查过一次后复用结果,不要重复调用 knowledge_index。',
|
|
454
|
+
'不要假定归档内容已在上下文中,也不要重复询问用户已提供过的信息。',
|
|
455
|
+
`</${ARCHIVE_TAG}>`
|
|
456
|
+
].join('\n')
|
|
457
|
+
const pinned = normalizePinnedDigest(source.pinnedDigest)
|
|
458
|
+
if (pinned === '') return base
|
|
459
|
+
return `${base}\n<context-pinned>\n${pinned}\n</context-pinned>`
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* 生成宿主可校验的 message id。
|
|
464
|
+
*
|
|
465
|
+
* 2026-12-03 修复:`user/message` 的 message 必须带 `id`,否则宿主读取日志时
|
|
466
|
+
* `assertMessageEventShape` 抛 `session event at seq N lacks an identified message`,
|
|
467
|
+
* 整条会话被判 corrupt(宿主的会话读取/上下文加载会失败)。
|
|
468
|
+
*
|
|
469
|
+
* @returns {string} UUID(缺失 crypto 时退化为时间戳随机串)。
|
|
470
|
+
*/
|
|
471
|
+
function newMessageId() {
|
|
472
|
+
const uuid = globalThis.crypto?.randomUUID
|
|
473
|
+
if (typeof uuid === 'function') return uuid.call(globalThis.crypto)
|
|
474
|
+
return `cm-marker-${Date.now().toString(36)}-${Math.random().toString(16).slice(2, 10)}`
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* 构建归档 marker 的 `user/message` 载荷(供 `session.append` 直接使用)。
|
|
479
|
+
*
|
|
480
|
+
* @param {object} [options] - 同 {@link buildArchiveMarkerText}。
|
|
481
|
+
* @returns {{id:string,role:'user',content:{type:'text',text:string}[],source:object}} 消息载荷。
|
|
482
|
+
*/
|
|
483
|
+
export function buildArchiveMarkerMessage(options = {}) {
|
|
484
|
+
const source = isRecord(options) ? options : {}
|
|
485
|
+
const fromTurn = readNonNegativeInt(source.fromTurn) ?? 0
|
|
486
|
+
const throughTurn = Math.max(fromTurn, readNonNegativeInt(source.throughTurn) ?? fromTurn)
|
|
487
|
+
return {
|
|
488
|
+
id: newMessageId(),
|
|
489
|
+
role: 'user',
|
|
490
|
+
content: [{ type: 'text', text: buildArchiveMarkerText(source) }],
|
|
491
|
+
source: {
|
|
492
|
+
kind: ARCHIVE_SOURCE_KIND,
|
|
493
|
+
form: ARCHIVE_NOTICE_FORM,
|
|
494
|
+
summary: `已归档第 ${fromTurn}~${throughTurn} 轮上下文(信息库)`
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* 按宿主 token-meter 的固定密度估算 marker 的启发式 token 数
|
|
501
|
+
* (文本 4 字符/token + 一个 text block 4 + role 4)。
|
|
502
|
+
*
|
|
503
|
+
* @param {string} text - marker 文本。
|
|
504
|
+
* @returns {number} 估算 token 数。
|
|
505
|
+
*/
|
|
506
|
+
export function estimateArchiveMarkerTokens(text) {
|
|
507
|
+
if (typeof text !== 'string' || text === '') return 0
|
|
508
|
+
return Math.ceil(text.length / 4) + 8
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/* -------------------------------------------------------------------------- */
|
|
512
|
+
/* 3) 归档范围选择 */
|
|
513
|
+
/* -------------------------------------------------------------------------- */
|
|
514
|
+
|
|
515
|
+
/** 把 keepCompletedTurns 钳制到合法范围(0~20;非法用默认 1)。 */
|
|
516
|
+
function resolveKeepCompletedTurns(value) {
|
|
517
|
+
if (value === undefined || value === null) return DEFAULT_KEEP_COMPLETED_TURNS
|
|
518
|
+
const number = readNonNegativeInt(value)
|
|
519
|
+
if (number === null) return DEFAULT_KEEP_COMPLETED_TURNS
|
|
520
|
+
return Math.min(20, number)
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** 构造不可替换时的统一返回(字段齐全,便于调用方直接透传)。 */
|
|
524
|
+
function skipResult(reason, partial) {
|
|
525
|
+
const base = {
|
|
526
|
+
replaceable: false,
|
|
527
|
+
reason,
|
|
528
|
+
fromIndex: null,
|
|
529
|
+
toIndex: null,
|
|
530
|
+
fromSeq: null,
|
|
531
|
+
endSeq: null,
|
|
532
|
+
shadowedSeqs: [],
|
|
533
|
+
foldedMarkerSeqs: [],
|
|
534
|
+
fromTurn: null,
|
|
535
|
+
throughTurn: null,
|
|
536
|
+
archivedTurns: [],
|
|
537
|
+
requiredTurns: [],
|
|
538
|
+
keptTurns: [],
|
|
539
|
+
keepFromIndex: null,
|
|
540
|
+
protectedHead: 0,
|
|
541
|
+
surfaceNodeCount: 0,
|
|
542
|
+
previousMarkers: [],
|
|
543
|
+
newTurns: []
|
|
544
|
+
}
|
|
545
|
+
return { ...base, ...(isRecord(partial) ? partial : {}) }
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* 选择需要归档的 surface 区间。
|
|
550
|
+
*
|
|
551
|
+
* 规则:
|
|
552
|
+
* - 只归档**已完成**的轮次(未闭合轮次必须保留 raw);
|
|
553
|
+
* - 保留最近 `keepCompletedTurns` 个已完成轮次(默认 1 = 用户目标"最近一轮");
|
|
554
|
+
* - `archivedThroughTurn` 之前的轮次不会重复参与(已归档内容已不在 surface,
|
|
555
|
+
* 但其日志事件仍在;用该水位过滤避免重复计数);
|
|
556
|
+
* - 保护 surface 节点 0 的 system prompt(替换从节点 0 之后开始;节点 0 若
|
|
557
|
+
* 不是 system/message 则从 0 开始也合法);
|
|
558
|
+
* - 上次归档 marker 若落在本次替换区间内会被一并替换(折叠,避免 marker 堆积);
|
|
559
|
+
* - 若 marker 落在"保留区"(会越过本次替换保留下来)或没有新轮次可归档,
|
|
560
|
+
* 返回 `replaceable:false` + 结构化 reason,调用方不得写 surface。
|
|
561
|
+
*
|
|
562
|
+
* @param {object} options - 输入。
|
|
563
|
+
* @param {readonly object[]} options.events - `session.snapshotEvents()`。
|
|
564
|
+
* @param {readonly number[]} options.surface - `session.surface.nodes`。
|
|
565
|
+
* @param {number} [options.keepCompletedTurns=1] - 保留的最近已完成轮数。
|
|
566
|
+
* @param {number|null} [options.archivedThroughTurn=null] - 已归档水位(轮次号)。
|
|
567
|
+
* @returns {object} 归档计划:
|
|
568
|
+
* `{replaceable,reason,fromIndex,toIndex,fromSeq,endSeq,shadowedSeqs,
|
|
569
|
+
* foldedMarkerSeqs,fromTurn,throughTurn,archivedTurns,requiredTurns,
|
|
570
|
+
* keptTurns,keepFromIndex,protectedHead,surfaceNodeCount,previousMarkers,newTurns}`。
|
|
571
|
+
*/
|
|
572
|
+
export function selectArchiveRange(options = {}) {
|
|
573
|
+
const source = isRecord(options) ? options : {}
|
|
574
|
+
const events = Array.isArray(source.events) ? source.events : []
|
|
575
|
+
const rawSurface = Array.isArray(source.surface) ? source.surface : []
|
|
576
|
+
const surface = []
|
|
577
|
+
for (const seq of rawSurface) {
|
|
578
|
+
if (Number.isSafeInteger(seq) && seq >= 0) surface.push(seq)
|
|
579
|
+
}
|
|
580
|
+
const keepCompletedTurns = resolveKeepCompletedTurns(source.keepCompletedTurns)
|
|
581
|
+
const archivedThroughTurn = readNonNegativeInt(source.archivedThroughTurn)
|
|
582
|
+
|
|
583
|
+
if (events.length === 0 || surface.length === 0) {
|
|
584
|
+
return skipResult(ARCHIVE_SKIP_REASON.NO_TURNS, { surfaceNodeCount: surface.length })
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const eventBySeq = new Map()
|
|
588
|
+
for (const event of events) {
|
|
589
|
+
const seq = seqOf(event)
|
|
590
|
+
if (seq !== null && !eventBySeq.has(seq)) eventBySeq.set(seq, event)
|
|
591
|
+
}
|
|
592
|
+
const eventAt = (seq) => eventBySeq.get(seq)
|
|
593
|
+
const protectedHead = typeOf(eventAt(surface[0])) === 'system/message' ? 1 : 0
|
|
594
|
+
const surfaceIndexOf = new Map()
|
|
595
|
+
for (let index = 0; index < surface.length; index += 1) surfaceIndexOf.set(surface[index], index)
|
|
596
|
+
|
|
597
|
+
const boundaries = collectTurnBoundaries(events)
|
|
598
|
+
const completedTurns = boundaries.filter(turn => turn.completed)
|
|
599
|
+
const completedUserTurns = completedTurns.filter(turn => turn.hasUser)
|
|
600
|
+
const markers = findArchiveMarkers(events, surface)
|
|
601
|
+
const previousMarkers = markers.map(marker => ({
|
|
602
|
+
seq: marker.seq,
|
|
603
|
+
surfaceIndex: marker.surfaceIndex,
|
|
604
|
+
fromTurn: marker.info.fromTurn,
|
|
605
|
+
throughTurn: marker.info.throughTurn
|
|
606
|
+
}))
|
|
607
|
+
|
|
608
|
+
// 只考虑"尚未归档"的轮次;旧水位之前的轮次已不在 surface 上。
|
|
609
|
+
const candidates = completedUserTurns
|
|
610
|
+
.filter(turn => archivedThroughTurn === null || turn.turn > archivedThroughTurn)
|
|
611
|
+
.sort((left, right) => left.turn - right.turn)
|
|
612
|
+
if (candidates.length === 0) {
|
|
613
|
+
const reason = archivedThroughTurn === null
|
|
614
|
+
? ARCHIVE_SKIP_REASON.NO_TURNS
|
|
615
|
+
: ARCHIVE_SKIP_REASON.NO_NEW_TURNS
|
|
616
|
+
return skipResult(reason, {
|
|
617
|
+
protectedHead,
|
|
618
|
+
surfaceNodeCount: surface.length,
|
|
619
|
+
previousMarkers,
|
|
620
|
+
keptTurns: completedUserTurns.map(turn => turn.turn)
|
|
621
|
+
})
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// 保留最近的 N 个已完成轮次;其余进入归档候选。
|
|
625
|
+
const keptCount = Math.min(keepCompletedTurns, candidates.length)
|
|
626
|
+
const keptBoundaries = keptCount > 0 ? candidates.slice(candidates.length - keptCount) : []
|
|
627
|
+
const keptTurns = new Set(keptBoundaries.map(turn => turn.turn))
|
|
628
|
+
const archiveCandidates = candidates.filter(turn => !keptTurns.has(turn.turn))
|
|
629
|
+
|
|
630
|
+
/** 某轮在 surface 上最早出现的下标(没有 surface 内容返回 null)。 */
|
|
631
|
+
const firstSurfaceIndex = (turn) => {
|
|
632
|
+
let best = null
|
|
633
|
+
for (const seq of turn.seqs) {
|
|
634
|
+
const index = surfaceIndexOf.get(seq)
|
|
635
|
+
if (index !== undefined && (best === null || index < best)) best = index
|
|
636
|
+
}
|
|
637
|
+
return best
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// 保留区起点:最近 N 个已完成轮次中最早出现的 surface 位置;未闭合轮次一律保留。
|
|
641
|
+
let keepFromIndex = surface.length
|
|
642
|
+
for (const turn of keptBoundaries) {
|
|
643
|
+
const index = firstSurfaceIndex(turn)
|
|
644
|
+
if (index === null) continue
|
|
645
|
+
if (index < keepFromIndex) keepFromIndex = index
|
|
646
|
+
}
|
|
647
|
+
for (const turn of boundaries) {
|
|
648
|
+
if (turn.completed) continue
|
|
649
|
+
const index = firstSurfaceIndex(turn)
|
|
650
|
+
if (index !== null && index < keepFromIndex) keepFromIndex = index
|
|
651
|
+
}
|
|
652
|
+
if (keepFromIndex > surface.length) keepFromIndex = surface.length
|
|
653
|
+
|
|
654
|
+
// marker 在保留区里(不会被本次替换收走)→ 无法安全追加新 marker。
|
|
655
|
+
const markerInKeptRange = markers.filter(marker => marker.surfaceIndex >= keepFromIndex)
|
|
656
|
+
if (markerInKeptRange.length > 0) {
|
|
657
|
+
return skipResult(ARCHIVE_SKIP_REASON.MARKER_IN_KEPT_RANGE, {
|
|
658
|
+
protectedHead,
|
|
659
|
+
surfaceNodeCount: surface.length,
|
|
660
|
+
previousMarkers,
|
|
661
|
+
keepFromIndex,
|
|
662
|
+
keptTurns: keptBoundaries.map(turn => turn.turn)
|
|
663
|
+
})
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
if (archiveCandidates.length === 0) {
|
|
667
|
+
return skipResult(ARCHIVE_SKIP_REASON.NO_NEW_TURNS, {
|
|
668
|
+
protectedHead,
|
|
669
|
+
surfaceNodeCount: surface.length,
|
|
670
|
+
previousMarkers,
|
|
671
|
+
keepFromIndex,
|
|
672
|
+
keptTurns: keptBoundaries.map(turn => turn.turn)
|
|
673
|
+
})
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const fromIndex = protectedHead
|
|
677
|
+
const toIndex = keepFromIndex - 1
|
|
678
|
+
if (toIndex < fromIndex) {
|
|
679
|
+
return skipResult(ARCHIVE_SKIP_REASON.NOTHING_TO_ARCHIVE, {
|
|
680
|
+
protectedHead,
|
|
681
|
+
surfaceNodeCount: surface.length,
|
|
682
|
+
previousMarkers,
|
|
683
|
+
keepFromIndex,
|
|
684
|
+
keptTurns: keptBoundaries.map(turn => turn.turn)
|
|
685
|
+
})
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
const shadowedSeqs = surface.slice(fromIndex, toIndex + 1)
|
|
689
|
+
if (shadowedSeqs.length === 0) {
|
|
690
|
+
return skipResult(ARCHIVE_SKIP_REASON.NOTHING_TO_ARCHIVE, {
|
|
691
|
+
protectedHead,
|
|
692
|
+
surfaceNodeCount: surface.length,
|
|
693
|
+
previousMarkers,
|
|
694
|
+
keepFromIndex,
|
|
695
|
+
keptTurns: keptBoundaries.map(turn => turn.turn)
|
|
696
|
+
})
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
const shadowedSet = new Set(shadowedSeqs)
|
|
700
|
+
const rangeTurns = completedTurns
|
|
701
|
+
.filter(turn => turn.seqs.some(seq => shadowedSet.has(seq)))
|
|
702
|
+
.sort((left, right) => left.turn - right.turn)
|
|
703
|
+
const archivedTurns = rangeTurns.map(turn => turn.turn)
|
|
704
|
+
// 覆盖证明只要求"含可抽取文本"的轮次(与 extract 的输入口径一致);
|
|
705
|
+
// 纯工具/空文本轮次没有可抽取内容,不需要图谱覆盖。
|
|
706
|
+
const requiredTurns = rangeTurns.filter(turn => turn.hasText && turn.hasUser).map(turn => turn.turn)
|
|
707
|
+
const foldedMarkers = markers.filter(marker => marker.surfaceIndex >= fromIndex && marker.surfaceIndex <= toIndex)
|
|
708
|
+
const foldedMarkerSeqs = foldedMarkers.map(marker => marker.seq)
|
|
709
|
+
const previous = foldedMarkers.length > 0
|
|
710
|
+
? foldedMarkers.reduce((best, marker) => {
|
|
711
|
+
if (best === null) return marker
|
|
712
|
+
const bestThrough = best.info.throughTurn ?? -1
|
|
713
|
+
const markerThrough = marker.info.throughTurn ?? -1
|
|
714
|
+
return markerThrough >= bestThrough ? marker : best
|
|
715
|
+
}, null)
|
|
716
|
+
: null
|
|
717
|
+
const firstArchivedTurn = rangeTurns.find(turn => turn.hasUser)?.turn ?? archiveCandidates[0]?.turn ?? null
|
|
718
|
+
const fromTurn = readNonNegativeInt(previous?.info?.fromTurn) ?? firstArchivedTurn
|
|
719
|
+
const throughCandidates = [
|
|
720
|
+
rangeTurns.length > 0 ? Math.max(...rangeTurns.map(turn => turn.turn)) : null,
|
|
721
|
+
archiveCandidates.length > 0 ? Math.max(...archiveCandidates.map(turn => turn.turn)) : null,
|
|
722
|
+
readNonNegativeInt(previous?.info?.throughTurn)
|
|
723
|
+
].filter(value => value !== null)
|
|
724
|
+
const throughTurn = throughCandidates.length > 0 ? Math.max(...throughCandidates) : null
|
|
725
|
+
|
|
726
|
+
return {
|
|
727
|
+
replaceable: true,
|
|
728
|
+
reason: null,
|
|
729
|
+
fromIndex,
|
|
730
|
+
toIndex,
|
|
731
|
+
fromSeq: shadowedSeqs[0],
|
|
732
|
+
endSeq: shadowedSeqs[shadowedSeqs.length - 1],
|
|
733
|
+
shadowedSeqs,
|
|
734
|
+
foldedMarkerSeqs,
|
|
735
|
+
fromTurn,
|
|
736
|
+
throughTurn,
|
|
737
|
+
archivedTurns,
|
|
738
|
+
requiredTurns,
|
|
739
|
+
keptTurns: keptBoundaries.map(turn => turn.turn),
|
|
740
|
+
keepFromIndex,
|
|
741
|
+
protectedHead,
|
|
742
|
+
surfaceNodeCount: surface.length,
|
|
743
|
+
previousMarkers,
|
|
744
|
+
newTurns: archiveCandidates.map(turn => turn.turn)
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/* -------------------------------------------------------------------------- */
|
|
749
|
+
/* 4) 覆盖证明 */
|
|
750
|
+
/* -------------------------------------------------------------------------- */
|
|
751
|
+
|
|
752
|
+
/** 把 turnStatuses(对象/Map/数组)归一化成 `(turn)=>status|null`。 */
|
|
753
|
+
function statusResolver(turnStatuses) {
|
|
754
|
+
const map = new Map()
|
|
755
|
+
if (turnStatuses instanceof Map) {
|
|
756
|
+
for (const [key, value] of turnStatuses.entries()) {
|
|
757
|
+
const turn = readNonNegativeInt(key)
|
|
758
|
+
if (turn !== null) map.set(turn, value)
|
|
759
|
+
}
|
|
760
|
+
} else if (Array.isArray(turnStatuses)) {
|
|
761
|
+
for (const item of turnStatuses) {
|
|
762
|
+
if (!isRecord(item)) continue
|
|
763
|
+
const turn = readNonNegativeInt(item.turn)
|
|
764
|
+
if (turn !== null) map.set(turn, item.status ?? item)
|
|
765
|
+
}
|
|
766
|
+
} else if (isRecord(turnStatuses)) {
|
|
767
|
+
for (const [key, value] of Object.entries(turnStatuses)) {
|
|
768
|
+
const turn = readNonNegativeInt(key)
|
|
769
|
+
if (turn !== null) map.set(turn, value)
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
return (turn) => {
|
|
773
|
+
const value = map.get(turn)
|
|
774
|
+
if (typeof value === 'string') return value
|
|
775
|
+
if (isRecord(value) && typeof value.status === 'string') return value.status
|
|
776
|
+
return null
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** 计划要求的轮次列表(对象/数组/数字都接住)。 */
|
|
781
|
+
function normalizeTurnList(value) {
|
|
782
|
+
const turns = []
|
|
783
|
+
if (!Array.isArray(value)) return turns
|
|
784
|
+
for (const item of value) {
|
|
785
|
+
const turn = isRecord(item) ? readNonNegativeInt(item.turn) : readNonNegativeInt(item)
|
|
786
|
+
if (turn !== null && !turns.includes(turn)) turns.push(turn)
|
|
787
|
+
}
|
|
788
|
+
return turns.sort((left, right) => left - right)
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* 计算当前 surface 的 tool-call/result 配对平衡(每个切点是否平衡)。
|
|
793
|
+
*
|
|
794
|
+
* @param {readonly object[]} events - 事件日志。
|
|
795
|
+
* @param {readonly number[]} surface - surface seq 列表。
|
|
796
|
+
* @returns {{cutBalanced:boolean[],corrupt:boolean,finalBalanced:boolean}} 平衡信息。
|
|
797
|
+
*/
|
|
798
|
+
function surfaceToolPairing(events, surface) {
|
|
799
|
+
const eventBySeq = new Map()
|
|
800
|
+
for (const event of events) {
|
|
801
|
+
const seq = seqOf(event)
|
|
802
|
+
if (seq !== null && !eventBySeq.has(seq)) eventBySeq.set(seq, event)
|
|
803
|
+
}
|
|
804
|
+
const cutBalanced = new Array(surface.length + 1).fill(false)
|
|
805
|
+
let open = 0
|
|
806
|
+
cutBalanced[0] = true
|
|
807
|
+
let corrupt = false
|
|
808
|
+
for (let index = 0; index < surface.length; index += 1) {
|
|
809
|
+
const event = eventBySeq.get(surface[index])
|
|
810
|
+
if (event !== undefined) {
|
|
811
|
+
open += countToolCalls(event)
|
|
812
|
+
if (typeOf(event) === 'tool/result') open -= 1
|
|
813
|
+
if (open < 0) {
|
|
814
|
+
corrupt = true
|
|
815
|
+
open = 0
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
cutBalanced[index + 1] = open === 0
|
|
819
|
+
}
|
|
820
|
+
return { cutBalanced, corrupt, finalBalanced: open === 0 }
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** 未闭合的 compaction 事务(compaction/start 没有配对 compaction/end)。 */
|
|
824
|
+
function openCompactionLocks(events) {
|
|
825
|
+
const open = new Set()
|
|
826
|
+
for (const event of events) {
|
|
827
|
+
if (!isRecord(event)) continue
|
|
828
|
+
if (event.type === 'compaction/start') {
|
|
829
|
+
const id = typeof event.data?.compactionId === 'string'
|
|
830
|
+
? event.data.compactionId
|
|
831
|
+
: typeof event.data?.compactionId === 'number'
|
|
832
|
+
? String(event.data.compactionId)
|
|
833
|
+
: `anonymous-${open.size}`
|
|
834
|
+
open.add(id)
|
|
835
|
+
} else if (event.type === 'compaction/end') {
|
|
836
|
+
const id = typeof event.data?.compactionId === 'string'
|
|
837
|
+
? event.data.compactionId
|
|
838
|
+
: typeof event.data?.compactionId === 'number'
|
|
839
|
+
? String(event.data.compactionId)
|
|
840
|
+
: null
|
|
841
|
+
if (id !== null) open.delete(id)
|
|
842
|
+
else if (open.size > 0) {
|
|
843
|
+
// 无 id 的 end:按最近一个 start 关闭(容错)。
|
|
844
|
+
const last = [...open].pop()
|
|
845
|
+
if (last !== undefined) open.delete(last)
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return [...open]
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* 六项覆盖证明:该归档计划是否安全可写。
|
|
854
|
+
*
|
|
855
|
+
* 校验项(每项失败给出结构化 code,见 {@link ARCHIVE_FAILURE}):
|
|
856
|
+
* 1) 连续 surface 区间(`ARCHIVE_NOT_CONTIGUOUS`);
|
|
857
|
+
* 2) shadowedSeqs 完整覆盖区间且都能在日志中找到(`ARCHIVE_COVERAGE`);
|
|
858
|
+
* 3) 范围内每个需覆盖轮次状态为 done/skipped(`TURN_NOT_INDEXED`);
|
|
859
|
+
* 4) 不替换 surface 节点 0 的 system prompt(`NODE0`);
|
|
860
|
+
* 5) 起点/终点的 tool-call/result 配对平衡(`TOOL_PAIRING`);
|
|
861
|
+
* 6) 无未闭合 compaction 锁(`COMPACTION_LOCK`)且旧 marker 被正确折叠(`MARKER_FOLD`)。
|
|
862
|
+
*
|
|
863
|
+
* @param {object} options - 输入。
|
|
864
|
+
* @param {readonly object[]} options.events - 事件日志。
|
|
865
|
+
* @param {readonly number[]} options.surface - surface seq 列表。
|
|
866
|
+
* @param {object} options.plan - {@link selectArchiveRange} 的返回(或等价手写计划)。
|
|
867
|
+
* @param {object|Map|Array} [options.turnStatuses] - turn → status(done/skipped/...)。
|
|
868
|
+
* @returns {{ok:boolean,failures:{code:string,message:string}[],details:object}} 校验结果。
|
|
869
|
+
*/
|
|
870
|
+
export function validateArchivePlan(options = {}) {
|
|
871
|
+
const source = isRecord(options) ? options : {}
|
|
872
|
+
const events = Array.isArray(source.events) ? source.events : null
|
|
873
|
+
const rawSurface = Array.isArray(source.surface) ? source.surface : null
|
|
874
|
+
const plan = isRecord(source.plan) ? source.plan : null
|
|
875
|
+
const failures = []
|
|
876
|
+
/** 推入一条结构化失败。 */
|
|
877
|
+
const fail = (code, message, extra) => {
|
|
878
|
+
failures.push({ code, message, ...(isRecord(extra) ? extra : {}) })
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
if (events === null || rawSurface === null || plan === null) {
|
|
882
|
+
fail(ARCHIVE_FAILURE.PLAN_INVALID, '归档计划缺少 events/surface/plan,无法校验')
|
|
883
|
+
return { ok: false, failures, details: {} }
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
const surface = []
|
|
887
|
+
for (const seq of rawSurface) {
|
|
888
|
+
if (Number.isSafeInteger(seq) && seq >= 0) surface.push(seq)
|
|
889
|
+
}
|
|
890
|
+
if (surface.length === 0) {
|
|
891
|
+
fail(ARCHIVE_FAILURE.PLAN_INVALID, 'surface 为空,没有可归档的历史')
|
|
892
|
+
return { ok: false, failures, details: { surfaceNodeCount: 0 } }
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
const eventBySeq = new Map()
|
|
896
|
+
for (const event of events) {
|
|
897
|
+
const seq = seqOf(event)
|
|
898
|
+
if (seq !== null && !eventBySeq.has(seq)) eventBySeq.set(seq, event)
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const fromIndex = readInteger(plan.fromIndex)
|
|
902
|
+
const toIndex = readInteger(plan.toIndex)
|
|
903
|
+
const shadowedSeqs = []
|
|
904
|
+
if (Array.isArray(plan.shadowedSeqs)) {
|
|
905
|
+
for (const seq of plan.shadowedSeqs) {
|
|
906
|
+
if (Number.isSafeInteger(seq) && seq >= 0) shadowedSeqs.push(seq)
|
|
907
|
+
else fail(ARCHIVE_FAILURE.COVERAGE, `shadowedSeqs 含非法 seq:${String(seq)}`)
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
if (fromIndex === null || toIndex === null || shadowedSeqs.length === 0) {
|
|
911
|
+
fail(ARCHIVE_FAILURE.PLAN_INVALID, '计划缺少 fromIndex/toIndex/shadowedSeqs')
|
|
912
|
+
return { ok: false, failures, details: { surfaceNodeCount: surface.length } }
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// 4) node0 保护(先判,错误最直接)。
|
|
916
|
+
const headEvent = eventBySeq.get(surface[0])
|
|
917
|
+
const headIsSystem = typeOf(headEvent) === 'system/message'
|
|
918
|
+
if (headIsSystem && (fromIndex <= 0 || shadowedSeqs.includes(surface[0]))) {
|
|
919
|
+
fail(ARCHIVE_FAILURE.NODE0, '替换区间包含 surface 节点 0 的 system prompt(只允许从节点 0 之后开始)')
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// 1) 连续区间。
|
|
923
|
+
let contiguousOk = true
|
|
924
|
+
if (fromIndex < 0 || toIndex < 0 || fromIndex >= surface.length || toIndex >= surface.length || fromIndex > toIndex) {
|
|
925
|
+
contiguousOk = false
|
|
926
|
+
fail(ARCHIVE_FAILURE.NOT_CONTIGUOUS, `替换区间 [${fromIndex}, ${toIndex}] 越界或起止颠倒(surface 长度 ${surface.length})`)
|
|
927
|
+
} else {
|
|
928
|
+
const slice = surface.slice(fromIndex, toIndex + 1)
|
|
929
|
+
if (slice.length !== shadowedSeqs.length) {
|
|
930
|
+
contiguousOk = false
|
|
931
|
+
fail(ARCHIVE_FAILURE.NOT_CONTIGUOUS, `shadowedSeqs 长度 ${shadowedSeqs.length} 与 surface 区间长度 ${slice.length} 不一致`)
|
|
932
|
+
} else {
|
|
933
|
+
for (let index = 0; index < slice.length; index += 1) {
|
|
934
|
+
if (slice[index] !== shadowedSeqs[index]) {
|
|
935
|
+
contiguousOk = false
|
|
936
|
+
fail(ARCHIVE_FAILURE.NOT_CONTIGUOUS, `替换区间不是当前 surface 的连续切片(第 ${index} 项 ${slice[index]} ≠ ${shadowedSeqs[index]})`)
|
|
937
|
+
break
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// 2) 覆盖完整性:每个 shadowed seq 必须是日志中真实存在的事件、且不重复。
|
|
944
|
+
const seen = new Set()
|
|
945
|
+
for (const seq of shadowedSeqs) {
|
|
946
|
+
if (seen.has(seq)) {
|
|
947
|
+
fail(ARCHIVE_FAILURE.COVERAGE, `shadowedSeqs 含重复 seq ${seq}`)
|
|
948
|
+
continue
|
|
949
|
+
}
|
|
950
|
+
seen.add(seq)
|
|
951
|
+
if (!eventBySeq.has(seq)) fail(ARCHIVE_FAILURE.COVERAGE, `shadowed seq ${seq} 不存在于会话事件日志`)
|
|
952
|
+
}
|
|
953
|
+
if (contiguousOk && shadowedSeqs.length > 0) {
|
|
954
|
+
const sliceSum = surface.slice(fromIndex, toIndex + 1).reduce((total, seq) => total + seq, 0)
|
|
955
|
+
const shadowedSum = shadowedSeqs.reduce((total, seq) => total + seq, 0)
|
|
956
|
+
if (sliceSum !== shadowedSum) fail(ARCHIVE_FAILURE.COVERAGE, 'shadowedSeqs 没有完整覆盖替换区间')
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// 3) 轮次覆盖证明:done|skipped 才允许归档。
|
|
960
|
+
const resolveStatus = statusResolver(source.turnStatuses)
|
|
961
|
+
let requiredTurns = normalizeTurnList(plan.requiredTurns)
|
|
962
|
+
if (requiredTurns.length === 0) requiredTurns = normalizeTurnList(plan.archivedTurns)
|
|
963
|
+
if (requiredTurns.length === 0) {
|
|
964
|
+
const shadowedSet = new Set(shadowedSeqs)
|
|
965
|
+
const boundaries = collectTurnBoundaries(events)
|
|
966
|
+
requiredTurns = boundaries
|
|
967
|
+
.filter(turn => turn.completed && turn.hasText && turn.hasUser)
|
|
968
|
+
.filter(turn => turn.seqs.some(seq => shadowedSet.has(seq)))
|
|
969
|
+
.map(turn => turn.turn)
|
|
970
|
+
}
|
|
971
|
+
for (const turn of requiredTurns) {
|
|
972
|
+
const status = resolveStatus(turn)
|
|
973
|
+
if (status !== 'done' && status !== 'skipped') {
|
|
974
|
+
fail(
|
|
975
|
+
ARCHIVE_FAILURE.TURN_NOT_INDEXED,
|
|
976
|
+
`第 ${turn} 轮尚未完成事实抽取(status=${status ?? 'missing'};只允许 done/skipped)`,
|
|
977
|
+
{ turn, status }
|
|
978
|
+
)
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// 5) tool 配对:替换区间两端都不能切断 tool-call/result。
|
|
983
|
+
const pairing = surfaceToolPairing(events, surface)
|
|
984
|
+
if (pairing.corrupt) {
|
|
985
|
+
fail(ARCHIVE_FAILURE.TOOL_PAIRING, '当前 surface 的 tool-call/tool-result 配对已损坏(出现无调用的结果)')
|
|
986
|
+
} else if (fromIndex >= 0 && toIndex >= fromIndex && toIndex < surface.length) {
|
|
987
|
+
if (!pairing.cutBalanced[fromIndex]) {
|
|
988
|
+
fail(ARCHIVE_FAILURE.TOOL_PAIRING, `替换区间起点(surface 下标 ${fromIndex})切断了未完成的 tool-call/result 配对`)
|
|
989
|
+
}
|
|
990
|
+
if (!pairing.cutBalanced[toIndex + 1]) {
|
|
991
|
+
fail(ARCHIVE_FAILURE.TOOL_PAIRING, `替换区间终点(surface 下标 ${toIndex})切断了未完成的 tool-call/result 配对`)
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// 6a) marker 折叠:旧 marker 必须落在替换区间里一起替换,不能留在区间前或保留区。
|
|
996
|
+
const markers = findArchiveMarkers(events, surface)
|
|
997
|
+
const foldedActual = markers.filter(marker => marker.surfaceIndex >= fromIndex && marker.surfaceIndex <= toIndex)
|
|
998
|
+
const leakedBefore = markers.filter(marker => marker.surfaceIndex < fromIndex)
|
|
999
|
+
const leakedAfter = markers.filter(marker => marker.surfaceIndex > toIndex)
|
|
1000
|
+
if (leakedBefore.length > 0) {
|
|
1001
|
+
fail(ARCHIVE_FAILURE.MARKER_FOLD, `替换区间之前还有 ${leakedBefore.length} 个旧归档 marker,必须一并折叠替换`)
|
|
1002
|
+
}
|
|
1003
|
+
if (leakedAfter.length > 0) {
|
|
1004
|
+
fail(ARCHIVE_FAILURE.MARKER_FOLD, `保留区里有 ${leakedAfter.length} 个归档 marker(不会本次替换,后续会堆积)`)
|
|
1005
|
+
}
|
|
1006
|
+
if (Array.isArray(plan.foldedMarkerSeqs)) {
|
|
1007
|
+
const planned = new Set(plan.foldedMarkerSeqs.filter(seq => Number.isSafeInteger(seq)))
|
|
1008
|
+
const actual = new Set(foldedActual.map(marker => marker.seq))
|
|
1009
|
+
let mismatch = planned.size !== actual.size
|
|
1010
|
+
if (!mismatch) {
|
|
1011
|
+
for (const seq of actual) {
|
|
1012
|
+
if (!planned.has(seq)) {
|
|
1013
|
+
mismatch = true
|
|
1014
|
+
break
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
if (mismatch) {
|
|
1019
|
+
fail(ARCHIVE_FAILURE.MARKER_FOLD, '计划声明的 foldedMarkerSeqs 与 surface 上的旧 marker 不一致')
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
// 6b) 内置压缩锁:未闭合的 compaction/start 存在时不允许改 surface。
|
|
1024
|
+
const locks = openCompactionLocks(events)
|
|
1025
|
+
if (locks.length > 0) {
|
|
1026
|
+
fail(ARCHIVE_FAILURE.COMPACTION_LOCK, `会话存在未闭合的 compaction 事务(${locks.slice(0, 3).join(', ')})`)
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
return {
|
|
1030
|
+
ok: failures.length === 0,
|
|
1031
|
+
failures,
|
|
1032
|
+
details: {
|
|
1033
|
+
fromIndex,
|
|
1034
|
+
toIndex,
|
|
1035
|
+
shadowedCount: shadowedSeqs.length,
|
|
1036
|
+
foldedMarkers: foldedActual.map(marker => marker.seq),
|
|
1037
|
+
requiredTurns,
|
|
1038
|
+
locks,
|
|
1039
|
+
surfaceNodeCount: surface.length
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
}
|