@jjh32456/longlive 1.8.12 → 2.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.
Files changed (92) hide show
  1. package/CHANGELOG.md +258 -202
  2. package/QUICKSTART.md +10 -11
  3. package/README.en.md +13 -4
  4. package/README.md +61 -18
  5. package/SPEC.md +3 -3
  6. package/build-info.json +259 -129
  7. package/cordis.patch.yml +32 -1
  8. package/docs/ANSWER-GUARD.md +1 -1
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +5 -3
  11. package/docs/AUTO-RECALL.md +10 -4
  12. package/docs/CONFIG.md +46 -11
  13. package/docs/ERRORS.md +1 -1
  14. package/docs/FAQ.md +9 -9
  15. package/docs/FEATURES.md +19 -16
  16. package/docs/OPERATIONS.md +3 -3
  17. package/docs/PANEL-INTEGRATION.md +1 -1
  18. package/docs/PRIVACY.md +6 -6
  19. package/docs/QUICKSTART.md +5 -5
  20. package/docs/README.en.md +5 -3
  21. package/docs/TOOLS.md +1 -1
  22. package/docs/TROUBLESHOOTING.md +4 -4
  23. package/package.json +6 -3
  24. package/runbook.md +3 -3
  25. package/scripts/migrate-200.mjs +8 -0
  26. package/scripts/migrate-lifecycle.mjs +2 -2
  27. package/src/answer/claim-guard.mjs +234 -0
  28. package/src/backup.js +165 -1
  29. package/src/config.js +18 -7
  30. package/src/features.js +132 -5
  31. package/src/handoff/index.js +133 -0
  32. package/src/handoff/model.js +48 -0
  33. package/src/identity/handover.js +203 -15
  34. package/src/identity/inject-position.js +3 -1
  35. package/src/index.js +2 -2
  36. package/src/memory/a1-migration.js +72 -6
  37. package/src/memory/archive-cold-state.mjs +794 -0
  38. package/src/memory/archive-staging.mjs +305 -0
  39. package/src/memory/archive.mjs +415 -0
  40. package/src/memory/capture-host.js +71 -2
  41. package/src/memory/capture.js +45 -6
  42. package/src/memory/catchup.mjs +534 -0
  43. package/src/memory/conclusion-distill.js +51 -2
  44. package/src/memory/conclusion-drafts.js +7 -3
  45. package/src/memory/conflicts.js +915 -2
  46. package/src/memory/consolidate.js +20 -1
  47. package/src/memory/forget-v2.js +272 -2
  48. package/src/memory/forget.js +20 -1
  49. package/src/memory/frames-activation.js +3 -1
  50. package/src/memory/fts-query.js +2 -2
  51. package/src/memory/index.js +80 -7
  52. package/src/memory/land.mjs +743 -0
  53. package/src/memory/lifecycle.js +128 -0
  54. package/src/memory/maintenance.js +386 -22
  55. package/src/memory/memory-health.mjs +607 -0
  56. package/src/memory/memory-reader.mjs +1003 -0
  57. package/src/memory/migrate-200.js +1681 -0
  58. package/src/memory/migrate-lifecycle.js +3 -3
  59. package/src/memory/procedure-candidate.mjs +377 -0
  60. package/src/memory/procedure.js +20 -1
  61. package/src/memory/prospective-memory.mjs +362 -0
  62. package/src/memory/recall-feedback.mjs +406 -0
  63. package/src/memory/recall-v2.js +13 -1
  64. package/src/memory/recall.js +102 -1
  65. package/src/memory/reinforce.js +138 -2
  66. package/src/memory/retention.js +34 -0
  67. package/src/memory/turn-budget.mjs +290 -0
  68. package/src/memory/wake-bridge.mjs +2999 -0
  69. package/src/memory/working-frame.js +271 -8
  70. package/src/metrics/classify.mjs +3 -1
  71. package/src/recall/archive-config.mjs +130 -0
  72. package/src/recall/archive-fallback.mjs +174 -19
  73. package/src/recall/archive-search.mjs +3 -0
  74. package/src/recall/archive-state.mjs +588 -0
  75. package/src/recall/brain.mjs +501 -0
  76. package/src/recall/continuity-log.mjs +435 -0
  77. package/src/recall/continuity-volatile.mjs +1001 -0
  78. package/src/recall/current-line.mjs +110 -0
  79. package/src/recall/edges.js +21 -2
  80. package/src/recall/explain.mjs +10 -0
  81. package/src/recall/gate-log.mjs +280 -0
  82. package/src/recall/gate-metrics.mjs +191 -0
  83. package/src/recall/index.js +663 -29
  84. package/src/recall/inject-order.mjs +3 -1
  85. package/src/recall/link-fastpath.mjs +662 -0
  86. package/src/recall/recall-core.mjs +74 -2
  87. package/src/recall/turn-budget-inject.mjs +154 -0
  88. package/src/retention/cold-gate.mjs +146 -0
  89. package/src/retention/config.js +58 -1
  90. package/src/retention/index.js +193 -35
  91. package/src/router/design-headings.json +10 -10
  92. package/src/tools.js +122 -6
@@ -0,0 +1,1001 @@
1
+ // lane-core/continuity-volatile.mjs
2
+ // 2.1.0 P1b:volatile 连续性块(每步易失注入)+ v0.2 持久块回落。
3
+ //
4
+ // 契约来源:PLAN-v0.4.md §0 #01/#07/#08、§2、§3、§4(F3'/F7/F8/F9/F10)。
5
+ // 边界(本文件不做的事):
6
+ // - 不写会话:volatile 只走 decision.volatileMessages,永不调用 session.append;
7
+ // 回落持久块只改 decision.messages(会话事件由宿主 adoption 链路负责),本模块同样不直接写 session。
8
+ // - 不写记忆根:默认读卡器只读 STATE.md / flow/current.md;审计落盘交给 continuity-log.mjs。
9
+ // - 不改 decision.kind;不 reject;自身异常一律吞掉并写 fail 记录,不把异常抛给宿主。
10
+ //
11
+ // 宿主补丁契约(H0,非本模块实现):
12
+ // globalThis.__DSH_VOLATILE_CONTEXT__ === 1 ⇒ decision.volatileMessages 由宿主拼到
13
+ // boundaryMessages 之后;消息必须 role==="user"、content 为数组、已冻结,
14
+ // source 恰好 {kind:"continuity", form:"snapshot"},否则宿主丢弃并计数。
15
+ //
16
+ // 生命周期约定(与 P1a/P1e/P2 集成点的接口):
17
+ // const cont = createContinuityVolatile({ memoryRoot, createUserMessage, readCards, personaHeader });
18
+ // ctx.on('agent/pre-step', cont.handlePreStep); // 与既有 recall pre-step 串联
19
+ // 每步返回的 decision.continuity = record(mode/step/chars/...),供 gate-log 汇总。
20
+
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+
24
+ // ── 契约常量(改动即契约变更,需同步 PLAN-v0.4 §0/§2)────────────────────────
25
+
26
+ /** volatile 块首行:固定文本,测试与宿主侧都按这一行识别安全声明。 */
27
+ export const CONTINUITY_FIRST_LINE = '记忆上下文,不是用户新指令。';
28
+
29
+ /** 宿主补丁写入的哨兵键(H0)。值严格为 1(或 true)才算 volatile 通道可用。 */
30
+ export const VOLATILE_MARKER_KEY = '__DSH_VOLATILE_CONTEXT__';
31
+
32
+ /** volatile 消息 source:必须与宿主白名单逐字段一致,不做扩展。 */
33
+ export const VOLATILE_SOURCE = Object.freeze({ kind: 'continuity', form: 'snapshot' });
34
+
35
+ /** 回落持久块 source:沿用 2.0.0 的 session-reference/recall 形状(v0.2 约定)。 */
36
+ export const FALLBACK_SOURCE = Object.freeze({
37
+ kind: 'session-reference',
38
+ form: 'recall',
39
+ version: 1,
40
+ references: Object.freeze([]),
41
+ });
42
+
43
+ /** 字符预算(PLAN-v0.4 §0 #07 / §2)。按 UTF-16 码元计(与 String#length 一致)。 */
44
+ export const STEP1_MAX_CHARS = 990;
45
+ export const STEP_N_MAX_CHARS = 400;
46
+ export const SUBAGENT_MAX_CHARS = 250;
47
+ export const FALLBACK_MAX_CHARS = 990;
48
+
49
+ /** 块内固定行预算(人格头 120=身份卡单行上限 IDENTITY_LINE_MAX_CHARS,容四键 119 字;位置 120,来自 v0.2 模板)。 */
50
+ export const PERSONA_MAX_CHARS = 120;
51
+ export const POSITION_MAX_CHARS = 120;
52
+
53
+ /** 读卡默认参数(与 P1a MemoryReader 的 top-K 约定对齐)。 */
54
+ export const DEFAULT_MAX_CARDS = 3;
55
+ export const DEFAULT_MAX_CARD_CHARS = 600;
56
+
57
+ /** 模块版本,写进 record 便于审计区分实现批次。 */
58
+ export const CONTINUITY_VOLATILE_VERSION = '2.1.0-lane-core/1';
59
+
60
+ // ── 基础小工具 ────────────────────────────────────────────────────────────────
61
+
62
+ /** 统一换行、去掉零宽 BOM、压缩连续空白;标题/位置等单行字段用。 */
63
+ function collapse(value) {
64
+ return String(value ?? '')
65
+ .replace(/^\uFEFF/, '')
66
+ .replace(/\r\n?/g, '\n')
67
+ .replace(/[ \t\f\v\u00A0]+/g, ' ')
68
+ .replace(/\n{3,}/g, '\n\n')
69
+ .trim();
70
+ }
71
+
72
+ /** 单行字段:在 collapse 基础上把换行压成空格。 */
73
+ function collapseLine(value) {
74
+ return collapse(value).replace(/\n+/g, ' ').trim();
75
+ }
76
+
77
+ /** 按 UTF-16 码元裁剪;超长补省略号,保证返回值长度 ≤ max。 */
78
+ function hardTrim(value, max) {
79
+ const text = String(value ?? '');
80
+ const cap = Math.max(0, Math.floor(Number(max)));
81
+ if (cap === 0) return '';
82
+ if (text.length <= cap) return text;
83
+ if (cap === 1) return '…';
84
+ return `${text.slice(0, cap - 1)}…`;
85
+ }
86
+
87
+ function toInt(value, fallback = 0) {
88
+ const n = Number(value);
89
+ return Number.isInteger(n) ? n : fallback;
90
+ }
91
+
92
+ function positiveInt(value, fallback) {
93
+ const n = Number(value);
94
+ return Number.isInteger(n) && n > 0 ? n : fallback;
95
+ }
96
+
97
+ function nowMillis(clock) {
98
+ const source = typeof clock === 'function' ? clock() : clock;
99
+ if (source instanceof Date) return source.getTime();
100
+ const n = Number(source);
101
+ return Number.isFinite(n) ? n : Date.now();
102
+ }
103
+
104
+ function errorCode(error, fallback = 'E_UNKNOWN') {
105
+ if (error && typeof error === 'object') {
106
+ if (typeof error.code === 'string' && error.code !== '') return error.code;
107
+ if (typeof error.message === 'string' && error.message !== '') return fallback;
108
+ }
109
+ return fallback;
110
+ }
111
+
112
+ /** 构造带 code 的 Error,供失败路径留痕(code 进 record.reason)。 */
113
+ export function continuityError(code, message = '') {
114
+ const error = new Error(message || String(code));
115
+ error.code = String(code);
116
+ return error;
117
+ }
118
+
119
+ function assertBudget(text, cap, label = 'block') {
120
+ const size = typeof text === 'string' ? text.length : -1;
121
+ if (size < 0 || size > cap) {
122
+ throw continuityError(
123
+ 'E_BUDGET',
124
+ `${label} 超预算:${size} > ${cap}(UTF-16 chars)`,
125
+ );
126
+ }
127
+ return size;
128
+ }
129
+
130
+ // ── 宿主哨兵探测 / payload 判定 ──────────────────────────────────────────────
131
+
132
+ /**
133
+ * 探测 volatile 宿主通道。严格判定:值必须 === 1(或 true)。
134
+ * H0 补丁只写 1;任何字符串/对象都视为不可用,避免误用未实现协议。
135
+ */
136
+ export function probeVolatileHost(scope = globalThis) {
137
+ try {
138
+ const marker = scope ? scope[VOLATILE_MARKER_KEY] : undefined;
139
+ return marker === 1 || marker === true;
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+
145
+ /** 子代理判定:与 2.0.0 recall/index.js:166 的 isSubagent 同口径(多一个 payload.origin)。 */
146
+ export function isSubagentPayload(payload) {
147
+ if (!payload || typeof payload !== 'object') return false;
148
+ const agent = payload.agent;
149
+ return Boolean(
150
+ (agent && agent.session && agent.session.header && agent.session.header.origin === 'subagent') ||
151
+ (agent && agent.origin === 'subagent') ||
152
+ payload.origin === 'subagent',
153
+ );
154
+ }
155
+
156
+ /** 会话 id:与 2.0.0 sessionKey 同口径;缺失时 'unknown'。 */
157
+ export function sessionIdOf(payload) {
158
+ const agent = payload && typeof payload === 'object' ? payload.agent : null;
159
+ const id = agent ? (agent.session ? agent.session.id : agent.id) : null;
160
+ return typeof id === 'string' && id.trim() !== '' ? id.trim() : 'unknown';
161
+ }
162
+
163
+ /** 位置行:turn/step/会话短 id/模式;不含 query 原文(隐私边界,F8)。 */
164
+ export function buildPositionLine({ turn, step, sessionId, mode }) {
165
+ const sid = collapseLine(sessionId) || 'unknown';
166
+ const shortSid = sid.length <= 16 ? sid : `${sid.slice(0, 15)}…`;
167
+ return `你在哪:turn=${toInt(turn, 0)} step=${toInt(step, 1)} 会话=${shortSid} 模式=${collapseLine(mode) || 'volatile'}`;
168
+ }
169
+
170
+ /** 回放补偿行:上一轮连续性不可回放的声明 + mode。 */
171
+ export function buildReplayLine(reason, mode) {
172
+ return `上一轮连续性不可回放:mode=${collapseLine(mode) || 'volatile'}(原因=${collapseLine(reason) || 'unknown'})`;
173
+ }
174
+
175
+ /** 回放原因判定:turn<=1 / 换会话首步 / 进程内首次观测到该会话(重启补偿)。 */
176
+ export function replayReasonFor({ turn, step, firstObservation, previousSession, sessionId, sessionSwitch }) {
177
+ if (step !== 1) return null;
178
+ if (toInt(turn, 0) <= 1) return 'turn<=1';
179
+ if (sessionSwitch) return 'session-switch';
180
+ if (firstObservation && previousSession !== null && previousSession !== sessionId) return 'session-switch';
181
+ if (firstObservation) return 'first-observation';
182
+ return null;
183
+ }
184
+
185
+ // ── 块构造 ───────────────────────────────────────────────────────────────────
186
+
187
+ function pushLine(state, raw) {
188
+ const line = collapseLine(raw);
189
+ if (line === '') return false;
190
+ const room = state.cap - state.text.length - (state.text === '' ? 0 : 1);
191
+ if (room <= 0) return false;
192
+ state.text += `${state.text === '' ? '' : '\n'}${hardTrim(line, room)}`;
193
+ return true;
194
+ }
195
+
196
+ function pushSegment(state, raw, perSegmentMax) {
197
+ const segment = collapse(raw);
198
+ if (segment === '') return false;
199
+ const room = state.cap - state.text.length - (state.text === '' ? 0 : 1);
200
+ if (room <= 1) return false;
201
+ const limit = Math.min(room, Math.max(1, Math.floor(Number(perSegmentMax) || room)));
202
+ const clipped = hardTrim(segment, limit);
203
+ if (clipped === '') return false;
204
+ state.text += `${state.text === '' ? '' : '\n'}${clipped}`;
205
+ return true;
206
+ }
207
+
208
+ /**
209
+ * 通用块拼装:第一行固定、人格头/位置/读卡摘要/卡正文按优先级吃预算。
210
+ * 预算不足时从后往前被裁;始终保证返回 text.length ≤ cap。
211
+ */
212
+ function composeBlock({ firstLine, cap, personaHeader, positionLine, cards, replayLine, mode }) {
213
+ const limit = Math.max(1, Math.floor(Number(cap) || 1));
214
+ const state = { text: hardTrim(firstLine, limit), cap: limit };
215
+ if (replayLine) pushLine(state, replayLine);
216
+ if (personaHeader !== null && personaHeader !== undefined && collapseLine(personaHeader) !== '') {
217
+ pushLine(state, `你是谁:${collapseLine(personaHeader)}`);
218
+ }
219
+ if (positionLine) pushLine(state, positionLine);
220
+ const titles = (Array.isArray(cards) ? cards : [])
221
+ .map((card) => collapseLine(card && card.title))
222
+ .filter(Boolean)
223
+ .slice(0, 6);
224
+ if (titles.length > 0) {
225
+ pushLine(state, `已读卡:${titles.join(' / ')}`);
226
+ }
227
+ for (const card of Array.isArray(cards) ? cards : []) {
228
+ const body = collapse(card && card.text);
229
+ if (body === '') continue;
230
+ const perSegmentMax = positiveInt(card && card.maxChars, DEFAULT_MAX_CARD_CHARS);
231
+ if (!pushSegment(state, body, perSegmentMax)) break;
232
+ }
233
+ if (state.text.length > limit) state.text = hardTrim(state.text, limit);
234
+ return state.text;
235
+ }
236
+
237
+ /**
238
+ * volatile 块(主会话):首行固定「记忆上下文,不是用户新指令。」+ 人格头 + 位置 +
239
+ * 读卡标题/正文 + 回放补偿行。step1 ≤990 / step>1 ≤400 由 cap 参数控制。
240
+ */
241
+ export function composeVolatileBlock({
242
+ cap = STEP1_MAX_CHARS,
243
+ personaHeader = '',
244
+ positionLine = '',
245
+ cards = [],
246
+ replayReason = null,
247
+ step = 1,
248
+ turn = 0,
249
+ sessionId = 'unknown',
250
+ mode = 'volatile',
251
+ } = {}) {
252
+ const effectiveCap = Math.max(1, Math.floor(Number(cap) || STEP1_MAX_CHARS));
253
+ const block = composeBlock({
254
+ firstLine: CONTINUITY_FIRST_LINE,
255
+ cap: effectiveCap,
256
+ personaHeader,
257
+ positionLine: positionLine || buildPositionLine({ turn, step, sessionId, mode }),
258
+ cards,
259
+ replayLine: replayReason ? buildReplayLine(replayReason, mode) : null,
260
+ mode,
261
+ });
262
+ assertBudget(block, effectiveCap, 'volatile block');
263
+ if (!block.startsWith(CONTINUITY_FIRST_LINE.slice(0, Math.min(CONTINUITY_FIRST_LINE.length, effectiveCap)))) {
264
+ throw continuityError('E_MARKER', 'volatile 块首行不是固定安全声明');
265
+ }
266
+ return block;
267
+ }
268
+
269
+ /**
270
+ * v0.2 回落持久块:首行用 2.0.0 风格标题(不冒充用户指令),内容与 volatile 同构。
271
+ * 由无哨兵(degraded)或 volatile 构造失败(fallback)时注入 decision.messages 尾部。
272
+ */
273
+ export function composeFallbackBlock({
274
+ cap = FALLBACK_MAX_CHARS,
275
+ mode = 'degraded',
276
+ personaHeader = '',
277
+ positionLine = '',
278
+ cards = [],
279
+ replayReason = null,
280
+ step = 1,
281
+ turn = 0,
282
+ sessionId = 'unknown',
283
+ } = {}) {
284
+ const effectiveCap = Math.max(1, Math.floor(Number(cap) || FALLBACK_MAX_CHARS));
285
+ const block = composeBlock({
286
+ firstLine: `【连续性·记忆延续】mode=${collapseLine(mode) || 'degraded'}`,
287
+ cap: effectiveCap,
288
+ personaHeader,
289
+ positionLine: positionLine || buildPositionLine({ turn, step, sessionId, mode }),
290
+ cards,
291
+ replayLine: replayReason ? buildReplayLine(replayReason, mode) : null,
292
+ mode,
293
+ });
294
+ assertBudget(block, effectiveCap, 'fallback block');
295
+ return block;
296
+ }
297
+
298
+ /**
299
+ * 子代理块(≤250):只输出身份头 + 任务名。不含主会话 query / 位置 / 读卡正文(F8)。
300
+ */
301
+ export function composeSubagentBlock({
302
+ cap = SUBAGENT_MAX_CHARS,
303
+ identity = '',
304
+ taskName = '',
305
+ step = 1,
306
+ turn = 0,
307
+ } = {}) {
308
+ const effectiveCap = Math.max(1, Math.floor(Number(cap) || SUBAGENT_MAX_CHARS));
309
+ const block = composeBlock({
310
+ firstLine: CONTINUITY_FIRST_LINE,
311
+ cap: effectiveCap,
312
+ personaHeader: null,
313
+ positionLine: null,
314
+ cards: [],
315
+ replayLine: null,
316
+ mode: 'volatile',
317
+ });
318
+ const bodyCapAt = effectiveCap;
319
+ let text = block;
320
+ const append = (value) => {
321
+ const line = collapseLine(value);
322
+ if (line === '') return;
323
+ const room = bodyCapAt - text.length - (text === '' ? 0 : 1);
324
+ if (room <= 0) return;
325
+ text += `${text === '' ? '' : '\n'}${hardTrim(line, room)}`;
326
+ };
327
+ append(`【子代理】身份:${collapseLine(identity) || '子代理'}`);
328
+ append(`任务:${collapseLine(taskName) || '(任务名未提供)'}`);
329
+ assertBudget(text, effectiveCap, 'subagent block');
330
+ return text;
331
+ }
332
+
333
+ // ── 消息构造 / 校验(宿主白名单的插件侧镜像)────────────────────────────────
334
+
335
+ function freezeDeep(message) {
336
+ if (!message || typeof message !== 'object') return message;
337
+ try {
338
+ if (Array.isArray(message.content)) {
339
+ for (const block of message.content) {
340
+ if (block && typeof block === 'object') Object.freeze(block);
341
+ }
342
+ Object.freeze(message.content);
343
+ }
344
+ if (message.source && typeof message.source === 'object') Object.freeze(message.source);
345
+ Object.freeze(message);
346
+ } catch {
347
+ // 冻结失败不抛出:交给 validateVolatileMessage 判 dropped。
348
+ }
349
+ return message;
350
+ }
351
+
352
+ /**
353
+ * 用注入的 createUserMessage 工厂构造 volatile 消息。
354
+ * 工厂缺失/抛错都转成 E_NO_FACTORY / E_CONSTRUCT,由调用方回落。
355
+ */
356
+ export function buildVolatileMessage(createUserMessage, text) {
357
+ if (typeof createUserMessage !== 'function') {
358
+ throw continuityError('E_NO_FACTORY', 'createUserMessage 工厂缺失,无法构造 volatile 消息');
359
+ }
360
+ const message = createUserMessage({
361
+ content: [{ type: 'text', text: String(text ?? '') }],
362
+ source: { kind: VOLATILE_SOURCE.kind, form: VOLATILE_SOURCE.form },
363
+ });
364
+ return freezeDeep(message);
365
+ }
366
+
367
+ /**
368
+ * 插件侧白名单镜像:宿主 H0 会再拒绝一次,这里先拒可让失败路径可审计(record.reason=E_WHITELIST)。
369
+ * 返回 {ok, errors[]};不抛错。
370
+ */
371
+ export function validateVolatileMessage(message) {
372
+ const errors = [];
373
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
374
+ return { ok: false, errors: ['not-object'] };
375
+ }
376
+ if (message.role !== 'user') errors.push('role');
377
+ if (!Array.isArray(message.content) || message.content.length === 0) {
378
+ errors.push('content');
379
+ } else {
380
+ const blocksOk = message.content.every(
381
+ (block) =>
382
+ block &&
383
+ typeof block === 'object' &&
384
+ block.type === 'text' &&
385
+ typeof block.text === 'string',
386
+ );
387
+ if (!blocksOk) errors.push('content-block');
388
+ }
389
+ if (!Object.isFrozen(message)) errors.push('not-frozen');
390
+ const source = message.source;
391
+ if (
392
+ !source ||
393
+ typeof source !== 'object' ||
394
+ source.kind !== VOLATILE_SOURCE.kind ||
395
+ source.form !== VOLATILE_SOURCE.form
396
+ ) {
397
+ errors.push('source');
398
+ }
399
+ return { ok: errors.length === 0, errors };
400
+ }
401
+
402
+ /** 回落持久消息:v0.2 的 source 形状(session-reference/recall),不冻结(正常 adoption)。 */
403
+ export function buildFallbackMessage(createUserMessage, text) {
404
+ if (typeof createUserMessage !== 'function') {
405
+ throw continuityError('E_NO_FACTORY', 'createUserMessage 工厂缺失,无法构造回落消息');
406
+ }
407
+ const message = createUserMessage({
408
+ content: [{ type: 'text', text: String(text ?? '') }],
409
+ source: {
410
+ kind: FALLBACK_SOURCE.kind,
411
+ form: FALLBACK_SOURCE.form,
412
+ version: FALLBACK_SOURCE.version,
413
+ references: [],
414
+ },
415
+ });
416
+ if (!message || typeof message !== 'object') {
417
+ throw continuityError('E_CONSTRUCT', '回落消息工厂返回非对象');
418
+ }
419
+ if (message.role !== 'user') {
420
+ throw continuityError('E_WHITELIST', '回落消息 role 不是 user');
421
+ }
422
+ if (
423
+ !Array.isArray(message.content) ||
424
+ message.content.length === 0 ||
425
+ !message.content.every((block) => block && block.type === 'text' && typeof block.text === 'string')
426
+ ) {
427
+ throw continuityError('E_WHITELIST', '回落消息 content 形状不合法');
428
+ }
429
+ return message;
430
+ }
431
+
432
+ // ── 默认读卡器(只读,stand-in for lane-read 的 MemoryReader)─────────────────
433
+
434
+ const DEFAULT_CARD_FILES = Object.freeze([
435
+ Object.freeze({ title: 'STATE', relative: 'STATE.md' }),
436
+ Object.freeze({ title: 'current', relative: 'flow/current.md' }),
437
+ ]);
438
+
439
+ /**
440
+ * 最小只读读卡器:读 <memoryRoot>/STATE.md 与 flow/current.md,裁剪到 maxCardChars。
441
+ * 缺文件/读失败跳过(不抛错);绝不写记忆根。集成时换成 lane-read 的 MemoryReader 即可。
442
+ */
443
+ export function defaultReadCards({ memoryRoot, maxCards = DEFAULT_MAX_CARDS, maxCardChars = DEFAULT_MAX_CARD_CHARS } = {}) {
444
+ const cards = [];
445
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
446
+ return { cards, dropped: 0, source: 'none' };
447
+ }
448
+ const root = path.resolve(memoryRoot);
449
+ for (const entry of DEFAULT_CARD_FILES) {
450
+ if (cards.length >= maxCards) break;
451
+ const file = path.join(root, entry.relative);
452
+ try {
453
+ const stat = fs.statSync(file);
454
+ if (!stat.isFile() || stat.size <= 0 || stat.size > 4 * 1024 * 1024) continue;
455
+ const raw = fs.readFileSync(file, 'utf8');
456
+ const text = raw.trim();
457
+ if (text === '') continue;
458
+ cards.push({
459
+ title: entry.title,
460
+ text: text.length <= maxCardChars ? text : `${text.slice(0, maxCardChars - 1)}…`,
461
+ maxChars: maxCardChars,
462
+ });
463
+ } catch {
464
+ // 缺文件/权限失败:跳过,不阻塞连续性注入。
465
+ }
466
+ }
467
+ return { cards, dropped: 0, source: 'memory-root' };
468
+ }
469
+
470
+ // ── 主模块 ───────────────────────────────────────────────────────────────────
471
+
472
+ export const DEFAULT_CONFIG = Object.freeze({
473
+ enabled: true,
474
+ memoryRoot: null,
475
+ createUserMessage: null,
476
+ readCards: null,
477
+ personaHeader: '',
478
+ subagentIdentity: '子代理',
479
+ subagentTaskName: '',
480
+ step1MaxChars: STEP1_MAX_CHARS,
481
+ stepNMaxChars: STEP_N_MAX_CHARS,
482
+ subagentMaxChars: SUBAGENT_MAX_CHARS,
483
+ fallbackMaxChars: FALLBACK_MAX_CHARS,
484
+ maxCards: DEFAULT_MAX_CARDS,
485
+ maxCardChars: DEFAULT_MAX_CARD_CHARS,
486
+ cacheCardsPerTurn: true,
487
+ });
488
+
489
+ function normalizeConfig(options = {}) {
490
+ const raw = options && typeof options === 'object' ? options : {};
491
+ const nested = raw.config && typeof raw.config === 'object' ? raw.config : {};
492
+ const merged = { ...DEFAULT_CONFIG, ...nested, ...raw };
493
+ return {
494
+ enabled: merged.enabled !== false,
495
+ memoryRoot: typeof merged.memoryRoot === 'string' && merged.memoryRoot.trim() !== '' ? merged.memoryRoot : null,
496
+ createUserMessage: typeof merged.createUserMessage === 'function' ? merged.createUserMessage : null,
497
+ readCards: typeof merged.readCards === 'function' ? merged.readCards : null,
498
+ personaHeader: merged.personaHeader,
499
+ subagentIdentity: typeof merged.subagentIdentity === 'string' ? merged.subagentIdentity : '子代理',
500
+ subagentTaskName: typeof merged.subagentTaskName === 'string' ? merged.subagentTaskName : '',
501
+ step1MaxChars: positiveInt(merged.step1MaxChars, STEP1_MAX_CHARS),
502
+ stepNMaxChars: positiveInt(merged.stepNMaxChars, STEP_N_MAX_CHARS),
503
+ subagentMaxChars: positiveInt(merged.subagentMaxChars, SUBAGENT_MAX_CHARS),
504
+ fallbackMaxChars: positiveInt(merged.fallbackMaxChars, FALLBACK_MAX_CHARS),
505
+ maxCards: positiveInt(merged.maxCards, DEFAULT_MAX_CARDS),
506
+ maxCardChars: positiveInt(merged.maxCardChars, DEFAULT_MAX_CARD_CHARS),
507
+ cacheCardsPerTurn: merged.cacheCardsPerTurn !== false,
508
+ probeVolatile: typeof raw.probeVolatile === 'function' ? raw.probeVolatile : null,
509
+ now: raw.now ?? null,
510
+ onRecord: typeof raw.onRecord === 'function' ? raw.onRecord : null,
511
+ };
512
+ }
513
+
514
+ function normalizeCardsPayload(payload) {
515
+ const list = Array.isArray(payload)
516
+ ? payload
517
+ : payload && Array.isArray(payload.cards)
518
+ ? payload.cards
519
+ : [];
520
+ let dropped = 0;
521
+ const cards = [];
522
+ for (const item of list) {
523
+ if (!item || typeof item !== 'object') {
524
+ dropped += 1;
525
+ continue;
526
+ }
527
+ const title = collapseLine(item.title ?? item.path ?? '');
528
+ const text = collapse(item.text ?? item.body ?? '');
529
+ if (title === '' && text === '') {
530
+ dropped += 1;
531
+ continue;
532
+ }
533
+ cards.push({ title: title || '未命名卡', text, maxChars: item.maxChars });
534
+ }
535
+ return { cards, dropped };
536
+ }
537
+
538
+ function resolvePersona(config, payload) {
539
+ const configured = config.personaHeader;
540
+ let value = '';
541
+ try {
542
+ value = typeof configured === 'function' ? configured(payload) : configured;
543
+ } catch {
544
+ value = '';
545
+ }
546
+ if (typeof value === 'string' && collapseLine(value) !== '') return collapseLine(value).slice(0, PERSONA_MAX_CHARS);
547
+ const header = payload && payload.agent && payload.agent.session ? payload.agent.session.header : null;
548
+ const candidate = header && typeof header.persona === 'string' ? collapseLine(header.persona) : '';
549
+ const persona = candidate.slice(0, PERSONA_MAX_CHARS);
550
+ // 人格头是块的固定组成部分(v0.2 模板);集成方未注入时用显式占位,避免被静默省略。
551
+ return persona === '' ? '(人格头未配置)' : persona;
552
+ }
553
+
554
+ function resolveSubagentTaskName(config, payload) {
555
+ const header = payload && payload.agent && payload.agent.session ? payload.agent.session.header : null;
556
+ const agent = payload && payload.agent ? payload.agent : null;
557
+ const candidates = [
558
+ header && header.title,
559
+ header && header.taskName,
560
+ header && header.task,
561
+ agent && agent.description,
562
+ agent && agent.task && agent.task.title,
563
+ agent && agent.taskName,
564
+ payload && payload.taskName,
565
+ config.subagentTaskName,
566
+ ];
567
+ for (const value of candidates) {
568
+ if (typeof value === 'string' && collapseLine(value) !== '') return collapseLine(value);
569
+ }
570
+ return '';
571
+ }
572
+
573
+ /**
574
+ * 创建 volatile 连续性模块。注入点:`ctx.on('agent/pre-step', cont.handlePreStep)`。
575
+ * options:
576
+ * memoryRoot / readCards / createUserMessage(必填,测试 mock)
577
+ * personaHeader(string|fn)、subagentIdentity、*MaxChars、maxCards、maxCardChars
578
+ * cacheCardsPerTurn(默认 true:每 turn 只读一次卡)
579
+ * probeVolatile(可选覆盖哨兵探测,仅测试/同构环境用)
580
+ * now(可注入时钟)、onRecord(每步 record 回调)
581
+ */
582
+ export function createContinuityVolatile(options = {}) {
583
+ const config = normalizeConfig(options);
584
+ const state = {
585
+ sessionsSeen: new Set(),
586
+ lastSessionId: null,
587
+ cardCache: new Map(),
588
+ lastRecord: null,
589
+ counts: { calls: 0, volatile: 0, degraded: 0, fallback: 0, fail: 0, off: 0 },
590
+ };
591
+
592
+ function clock() {
593
+ return nowMillis(config.now);
594
+ }
595
+
596
+ function probeHost(scope) {
597
+ if (typeof config.probeVolatile === 'function') {
598
+ try {
599
+ return Boolean(config.probeVolatile(scope));
600
+ } catch {
601
+ return false;
602
+ }
603
+ }
604
+ return probeVolatileHost(scope);
605
+ }
606
+
607
+ function emit(record) {
608
+ state.lastRecord = record;
609
+ if (Object.prototype.hasOwnProperty.call(state.counts, record.mode)) {
610
+ state.counts[record.mode] += 1;
611
+ }
612
+ state.counts.calls += 1;
613
+ if (typeof config.onRecord === 'function') {
614
+ try {
615
+ config.onRecord(record);
616
+ } catch {
617
+ // 审计回调自身异常不影响注入。
618
+ }
619
+ }
620
+ return record;
621
+ }
622
+
623
+ function trackSession(sessionId) {
624
+ const firstObservation = !state.sessionsSeen.has(sessionId);
625
+ const previousSession = state.lastSessionId;
626
+ state.sessionsSeen.add(sessionId);
627
+ state.lastSessionId = sessionId;
628
+ return {
629
+ firstObservation,
630
+ previousSession,
631
+ sessionSwitch: firstObservation && previousSession !== null && previousSession !== sessionId,
632
+ };
633
+ }
634
+
635
+ function attach(decision, ctx, startedAt) {
636
+ const record = {
637
+ version: CONTINUITY_VOLATILE_VERSION,
638
+ at: new Date(clock()).toISOString(),
639
+ step: ctx.step,
640
+ turn: ctx.turn,
641
+ sessionId: ctx.sessionId,
642
+ subagent: ctx.subagent,
643
+ mode: ctx.mode,
644
+ degraded: ctx.degraded,
645
+ reason: ctx.reason,
646
+ replay: ctx.replay,
647
+ injected: ctx.injected,
648
+ volatileBlocks: ctx.volatileBlocks,
649
+ chars: ctx.chars,
650
+ volatileChars: ctx.volatileChars,
651
+ cards: ctx.cards,
652
+ drop: ctx.drop,
653
+ fail: ctx.fail,
654
+ ms: Math.max(0, Math.round(clock() - startedAt)),
655
+ };
656
+ emit(record);
657
+ if (decision && typeof decision === 'object') return { ...decision, continuity: record };
658
+ return decision;
659
+ }
660
+
661
+ async function getCards(sessionId, turn) {
662
+ const key = `${sessionId}|${turn}`;
663
+ if (config.cacheCardsPerTurn && state.cardCache.has(key)) {
664
+ return state.cardCache.get(key);
665
+ }
666
+ const reader = config.readCards || defaultReadCards;
667
+ const raw = await reader({
668
+ memoryRoot: config.memoryRoot,
669
+ sessionId,
670
+ turn,
671
+ limit: config.maxCards,
672
+ maxCards: config.maxCards,
673
+ maxCardChars: config.maxCardChars,
674
+ });
675
+ const normalized = normalizeCardsPayload(raw);
676
+ const cards = normalized.cards.slice(0, config.maxCards);
677
+ const dropped = normalized.dropped + Math.max(0, normalized.cards.length - config.maxCards);
678
+ const result = { cards, dropped };
679
+ if (config.cacheCardsPerTurn) {
680
+ state.cardCache.set(key, result);
681
+ if (state.cardCache.size > 64) {
682
+ const oldest = state.cardCache.keys().next().value;
683
+ state.cardCache.delete(oldest);
684
+ }
685
+ }
686
+ return result;
687
+ }
688
+
689
+ async function fallbackPath(payload, decision, ctx, opts) {
690
+ const step1Only = opts.step1Only !== false;
691
+ const baseMode = opts.mode || 'degraded';
692
+ if (step1Only && ctx.step !== 1) {
693
+ ctx.mode = baseMode;
694
+ ctx.degraded = opts.degraded ?? null;
695
+ // 根因在 degraded(如 volatile-unavailable);这里记"为什么本步没注入",便于区分
696
+ // "step1 已回落注入"(reason=E_VOLATILE_UNAVAILABLE)与"step>1 按 v0.2 不注入"。
697
+ ctx.reason = 'E_FALLBACK_STEP_GT_1';
698
+ ctx.replay = null;
699
+ ctx.injected = false;
700
+ ctx.cards = 0;
701
+ ctx.drop = toInt(opts.drop, 0);
702
+ ctx.chars = 0;
703
+ ctx.volatileChars = 0;
704
+ ctx.volatileBlocks = 0;
705
+ return attach(decision, ctx, ctx.startedAt);
706
+ }
707
+ // 回落持久块同样要带"系统读卡正文":调用方没给 cards 时自行读一次(只读,不写记忆根)。
708
+ let cards = Array.isArray(opts.cards) ? opts.cards : null;
709
+ let dropped = toInt(opts.drop, 0);
710
+ let readFailure = false;
711
+ if (cards === null) {
712
+ cards = [];
713
+ if (!ctx.subagent) {
714
+ try {
715
+ const loaded = await getCards(ctx.sessionId, ctx.turn);
716
+ cards = loaded.cards;
717
+ dropped += loaded.dropped;
718
+ } catch {
719
+ readFailure = true;
720
+ }
721
+ }
722
+ }
723
+ const cap = ctx.subagent
724
+ ? config.subagentMaxChars
725
+ : ctx.step === 1
726
+ ? config.fallbackMaxChars
727
+ : config.stepNMaxChars;
728
+ let text;
729
+ try {
730
+ text = ctx.subagent
731
+ ? composeSubagentBlock({
732
+ cap,
733
+ identity: config.subagentIdentity,
734
+ taskName: resolveSubagentTaskName(config, payload),
735
+ })
736
+ : composeFallbackBlock({
737
+ cap,
738
+ mode: baseMode,
739
+ personaHeader: resolvePersona(config, payload),
740
+ positionLine: buildPositionLine({ turn: ctx.turn, step: ctx.step, sessionId: ctx.sessionId, mode: baseMode }),
741
+ cards,
742
+ replayReason: ctx.replay,
743
+ step: ctx.step,
744
+ turn: ctx.turn,
745
+ sessionId: ctx.sessionId,
746
+ });
747
+ assertBudget(text, cap, 'fallback block');
748
+ } catch (error) {
749
+ ctx.mode = 'fail';
750
+ ctx.degraded = opts.degraded ?? null;
751
+ ctx.reason = errorCode(error, 'E_FALLBACK_COMPOSE');
752
+ ctx.fail = 1;
753
+ ctx.injected = false;
754
+ ctx.chars = 0;
755
+ ctx.volatileChars = 0;
756
+ ctx.volatileBlocks = 0;
757
+ return attach(decision, ctx, ctx.startedAt);
758
+ }
759
+ const messages = Array.isArray(decision.messages) ? decision.messages : null;
760
+ if (messages === null) {
761
+ ctx.mode = 'fail';
762
+ ctx.degraded = opts.degraded ?? null;
763
+ ctx.reason = 'E_NO_MESSAGES';
764
+ ctx.fail = 1;
765
+ ctx.injected = false;
766
+ return attach(decision, ctx, ctx.startedAt);
767
+ }
768
+ try {
769
+ const message = buildFallbackMessage(config.createUserMessage, text);
770
+ ctx.mode = baseMode;
771
+ ctx.degraded = opts.degraded ?? (readFailure ? 'volatile-read-failed' : null);
772
+ ctx.reason = opts.reason ?? (readFailure ? 'E_READ_CARDS' : null);
773
+ ctx.fail = Math.max(toInt(opts.fail, 0), readFailure ? 1 : 0);
774
+ ctx.cards = cards.length;
775
+ ctx.drop = dropped;
776
+ ctx.chars = text.length;
777
+ ctx.volatileChars = 0;
778
+ ctx.volatileBlocks = 0;
779
+ ctx.injected = true;
780
+ return attach({ ...decision, messages: [...messages, message] }, ctx, ctx.startedAt);
781
+ } catch (error) {
782
+ ctx.mode = 'fail';
783
+ ctx.degraded = opts.degraded ?? null;
784
+ ctx.reason = errorCode(error, 'E_FALLBACK_CONSTRUCT');
785
+ ctx.fail = 1;
786
+ ctx.injected = false;
787
+ ctx.chars = 0;
788
+ return attach(decision, ctx, ctx.startedAt);
789
+ }
790
+ }
791
+
792
+ async function volatilePath(payload, decision, ctx) {
793
+ const cap = ctx.subagent
794
+ ? config.subagentMaxChars
795
+ : ctx.step === 1
796
+ ? config.step1MaxChars
797
+ : config.stepNMaxChars;
798
+
799
+ let cards = [];
800
+ let dropped = 0;
801
+ if (!ctx.subagent) {
802
+ try {
803
+ const loaded = await getCards(ctx.sessionId, ctx.turn);
804
+ cards = loaded.cards;
805
+ dropped = loaded.dropped;
806
+ } catch (error) {
807
+ return fallbackPath(payload, decision, ctx, {
808
+ mode: 'fallback',
809
+ degraded: 'volatile-read-failed',
810
+ reason: errorCode(error, 'E_READ_CARDS'),
811
+ fail: 1,
812
+ cards: [],
813
+ drop: 0,
814
+ step1Only: false,
815
+ });
816
+ }
817
+ }
818
+
819
+ let text;
820
+ try {
821
+ text = ctx.subagent
822
+ ? composeSubagentBlock({
823
+ cap,
824
+ identity: config.subagentIdentity,
825
+ taskName: resolveSubagentTaskName(config, payload),
826
+ })
827
+ : composeVolatileBlock({
828
+ cap,
829
+ personaHeader: resolvePersona(config, payload),
830
+ positionLine: buildPositionLine({ turn: ctx.turn, step: ctx.step, sessionId: ctx.sessionId, mode: 'volatile' }),
831
+ cards,
832
+ replayReason: ctx.replay,
833
+ step: ctx.step,
834
+ turn: ctx.turn,
835
+ sessionId: ctx.sessionId,
836
+ mode: 'volatile',
837
+ });
838
+ assertBudget(text, cap, 'volatile block');
839
+ } catch (error) {
840
+ return fallbackPath(payload, decision, ctx, {
841
+ mode: 'fallback',
842
+ degraded: 'volatile-construct-failed',
843
+ reason: errorCode(error, 'E_COMPOSE'),
844
+ fail: 1,
845
+ cards,
846
+ drop: dropped,
847
+ step1Only: false,
848
+ });
849
+ }
850
+
851
+ let message;
852
+ try {
853
+ message = buildVolatileMessage(config.createUserMessage, text);
854
+ } catch (error) {
855
+ return fallbackPath(payload, decision, ctx, {
856
+ mode: 'fallback',
857
+ degraded: 'volatile-construct-failed',
858
+ reason: errorCode(error, 'E_CONSTRUCT'),
859
+ fail: 1,
860
+ cards,
861
+ drop: dropped,
862
+ step1Only: false,
863
+ });
864
+ }
865
+
866
+ const verdict = validateVolatileMessage(message);
867
+ if (!verdict.ok) {
868
+ return fallbackPath(payload, decision, ctx, {
869
+ mode: 'fallback',
870
+ degraded: 'volatile-whitelist-rejected',
871
+ reason: 'E_WHITELIST',
872
+ fail: 1,
873
+ cards,
874
+ drop: dropped + 1,
875
+ step1Only: false,
876
+ });
877
+ }
878
+
879
+ ctx.mode = 'volatile';
880
+ ctx.degraded = null;
881
+ ctx.reason = null;
882
+ ctx.volatileBlocks = 1;
883
+ ctx.chars = text.length;
884
+ ctx.volatileChars = text.length;
885
+ ctx.cards = cards.length;
886
+ ctx.drop = dropped;
887
+ ctx.fail = 0;
888
+ ctx.injected = true;
889
+ return attach({ ...decision, volatileMessages: [message] }, ctx, ctx.startedAt);
890
+ }
891
+
892
+ /**
893
+ * 处理一步:对 step>1(或有哨兵时任意步)构造块。
894
+ * - 有哨兵:每步注入 decision.volatileMessages(step1≤990 / step>1≤400 / 子代理≤250)。
895
+ * - 无哨兵:仅 step1 回落 v0.2 持久块(degraded),step>1 不注入。
896
+ * - 任何构造失败:尝试回落持久块(fallback + fail 记录);再失败则原样返回、只写 fail 记录。
897
+ * 返回的 decision 上挂 `continuity` record;绝不抛错(next() 的异常除外)。
898
+ */
899
+ async function inject(payload, decision) {
900
+ const startedAt = clock();
901
+ const step = Math.max(1, toInt(payload && payload.step, 1));
902
+ const turn = Math.max(0, toInt(payload && payload.turn, 0));
903
+ const sessionId = sessionIdOf(payload);
904
+ const subagent = isSubagentPayload(payload);
905
+ const ctx = {
906
+ startedAt,
907
+ step,
908
+ turn,
909
+ sessionId,
910
+ subagent,
911
+ mode: 'off',
912
+ degraded: null,
913
+ reason: null,
914
+ replay: null,
915
+ injected: false,
916
+ volatileBlocks: 0,
917
+ chars: 0,
918
+ volatileChars: 0,
919
+ cards: 0,
920
+ drop: 0,
921
+ fail: 0,
922
+ };
923
+ try {
924
+ if (!decision || typeof decision !== 'object') {
925
+ ctx.reason = 'E_NO_DECISION';
926
+ return attach(decision, ctx, startedAt);
927
+ }
928
+ if (!config.enabled) {
929
+ ctx.reason = 'E_DISABLED';
930
+ return attach(decision, ctx, startedAt);
931
+ }
932
+ if (decision.kind === 'reject') {
933
+ ctx.reason = 'E_REJECTED_DECISION';
934
+ return attach(decision, ctx, startedAt);
935
+ }
936
+
937
+ const tracking = trackSession(sessionId);
938
+ const replay = replayReasonFor({
939
+ turn,
940
+ step,
941
+ firstObservation: tracking.firstObservation,
942
+ previousSession: tracking.previousSession,
943
+ sessionId,
944
+ sessionSwitch: tracking.sessionSwitch,
945
+ });
946
+ ctx.replay = replay;
947
+
948
+ const hostVolatile = probeHost(typeof globalThis !== 'undefined' ? globalThis : undefined);
949
+ if (hostVolatile) {
950
+ return await volatilePath(payload, decision, ctx);
951
+ }
952
+ return await fallbackPath(payload, decision, ctx, {
953
+ mode: 'degraded',
954
+ degraded: 'volatile-unavailable',
955
+ reason: 'E_VOLATILE_UNAVAILABLE',
956
+ fail: 0,
957
+ step1Only: true,
958
+ });
959
+ } catch (error) {
960
+ ctx.mode = 'fail';
961
+ ctx.reason = errorCode(error, 'E_INTERNAL');
962
+ ctx.fail = 1;
963
+ ctx.injected = false;
964
+ return attach(decision, ctx, startedAt);
965
+ }
966
+ }
967
+
968
+ /** agent/pre-step 监听器:先 await next(),再在返回的 decision 上追加。 */
969
+ async function handlePreStep(payload, next) {
970
+ const decision = await next();
971
+ return inject(payload, decision);
972
+ }
973
+
974
+ function inspect() {
975
+ return {
976
+ version: CONTINUITY_VOLATILE_VERSION,
977
+ config: {
978
+ enabled: config.enabled,
979
+ memoryRoot: config.memoryRoot,
980
+ step1MaxChars: config.step1MaxChars,
981
+ stepNMaxChars: config.stepNMaxChars,
982
+ subagentMaxChars: config.subagentMaxChars,
983
+ fallbackMaxChars: config.fallbackMaxChars,
984
+ maxCards: config.maxCards,
985
+ maxCardChars: config.maxCardChars,
986
+ cacheCardsPerTurn: config.cacheCardsPerTurn,
987
+ },
988
+ counts: { ...state.counts },
989
+ sessionsSeen: [...state.sessionsSeen],
990
+ lastRecord: state.lastRecord,
991
+ };
992
+ }
993
+
994
+ return {
995
+ version: CONTINUITY_VOLATILE_VERSION,
996
+ config,
997
+ inject,
998
+ handlePreStep,
999
+ inspect,
1000
+ };
1001
+ }