@jjh32456/longlive 2.0.0 → 2.2.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.
@@ -11,7 +11,7 @@
11
11
 
12
12
  import { memoryError, memoryRootFromConfig } from './paths.js';
13
13
  import { memoryRecall } from './recall.js';
14
- import { scanCards } from './index.js';
14
+ import { scanCards, RECALL_SCAN_DIRS } from './index.js';
15
15
  import { appendAuditRecord } from './audit-records.js';
16
16
  // M11: 统一召回入口(brain.mjs)——空命中时给出候选线索,不改变 hits/证据门形状。
17
17
  import { selectCards as brainSelectCards } from '../recall/brain.mjs';
@@ -132,7 +132,8 @@ export function recallV2(args = {}, config = {}) {
132
132
  const root = memoryRootFromConfig(config);
133
133
 
134
134
  const recalled = memoryRecall({ query, topK: Math.max(topK, 5), status: includeForgotten ? 'any' : 'active' }, { memoryRoot: root });
135
- const cards = new Map((scanCards(root) || []).map((card) => [card.rel, card]));
135
+ // 召回面与 memoryRecall 一致:topics + journal + procedures(程序卡)。
136
+ const cards = new Map((scanCards(root, { dirs: RECALL_SCAN_DIRS }) || []).map((card) => [card.rel, card]));
136
137
  let hits = [];
137
138
  for (const row of Array.isArray(recalled.results) ? recalled.results : []) {
138
139
  if (row?.type === 'event') continue; // D2: event/AutoCard layer is cold archive, not recalled.
@@ -169,7 +170,8 @@ export function recallV2(args = {}, config = {}) {
169
170
  }
170
171
  const gate = evidenceGate({ hits, question: query });
171
172
  // 1.8.2 D2: no auto-card read; hits are curated cards only.
172
- const curatedHits = hits.slice(0, Math.min(2, topK));
173
+ // 2.2.0 lane-B:hits 截断 2→3,避免 procedure 命中被 topics 挤掉。
174
+ const curatedHits = hits.slice(0, Math.min(3, topK));
173
175
  hits = [...curatedHits].slice(0, topK);
174
176
  const finalGate = evidenceGate({ hits, question: query });
175
177
  const fastAnswer = finalGate.fastEligible ? buildFastAnswer({ question: query, hit: hits[0], gate: finalGate }) : null;
@@ -10,7 +10,7 @@
10
10
  // "never decay or merge", not "hidden".
11
11
 
12
12
  import { memoryError, memoryRootFromConfig } from './paths.js';
13
- import { scanCards } from './index.js';
13
+ import { scanCards, RECALL_SCAN_DIRS } from './index.js';
14
14
  import { readVerifiedCardAnchors } from './card-anchors.js';
15
15
  import { searchEventsReadOnly } from './event-index.js';
16
16
  import { isHistoricalQuery, readLifecycle } from './lifecycle.js';
@@ -24,6 +24,9 @@ export const RECALL_STATUSES = Object.freeze(['active', 'locked', 'archived', 'a
24
24
  // SPEC-1.8.11 D9:historical 卡在工具层同样要沉层(与 pre-step 注入的 lifecycleRank 一致),
25
25
  // 但工具层不改条数/过滤:只按权重改分数,同一 lifecycle 内原有分数序不变。
26
26
  export const HISTORICAL_SCORE_WEIGHT = 0.3;
27
+ // 程序卡(procedures/)在召回面给固定加成:动作类 query(发布/安装/回滚/删除…)
28
+ // 必中 procedure 卡;固定系数,不引入概率/阈值判据(工作区 AGENTS.md 第 21 条)。
29
+ export const PROCEDURE_SCORE_WEIGHT = 1.15;
27
30
 
28
31
  const CJK_RUN = /[\u3400-\u9fff]+/g;
29
32
  const ASCII_WORD = /[a-z0-9_]{2,}/g;
@@ -189,7 +192,8 @@ export function memoryRecall(args, config = {}) {
189
192
  // 显式历史查询(以前/旧版/被取代…)不降权;普通查询把 historical 卡乘权重沉下去。
190
193
  const historyQuery = isHistoricalQuery(query);
191
194
 
192
- const scanned = scanCards(root);
195
+ // 召回面扫 topics + journal + procedures(程序卡);索引面 memoryIndex 仍不含 procedures。
196
+ const scanned = scanCards(root, { dirs: RECALL_SCAN_DIRS });
193
197
  const sidecar = readVerifiedCardAnchors({ memoryRoot: root }).links;
194
198
  const includeAuto = args?.includeAuto === true || args?.archive === true;
195
199
  const results = [];
@@ -202,8 +206,10 @@ export function memoryRecall(args, config = {}) {
202
206
  const { score, hits } = scoreCard(query, card);
203
207
  if (score <= 0 || hits.length === 0) continue;
204
208
  const lifecycle = readLifecycle(card);
205
- // historical 只在非历史查询里降权;canonical/普通卡不变(权重 1)。
206
- const weight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
209
+ // historical 只在非历史查询里降权;程序卡给固定加成;canonical/普通卡权重 1。
210
+ const lifecycleWeight = lifecycle === 'historical' && !historyQuery ? HISTORICAL_SCORE_WEIGHT : 1;
211
+ const procedureWeight = card.procedure === true ? PROCEDURE_SCORE_WEIGHT : 1;
212
+ const weight = lifecycleWeight * procedureWeight;
207
213
  const weightedScore = weight === 1 ? score : Math.round(score * weight * 100) / 100;
208
214
  const link = sidecar.get(card.rel);
209
215
  results.push({
@@ -181,7 +181,12 @@ export function selectProcedures(memoryRoot, queryText, maxItems = 2) {
181
181
  const total = totalWeight(queryWeights);
182
182
  const score = Math.min(1, matchedWeight(queryWeights, tokenSet(trigger)) / total);
183
183
  if (score <= 0) continue;
184
- scored.push({ name: String(card.name ?? ''), trigger: Array.isArray(card.trigger) ? card.trigger.slice(0, 4) : [String(card.trigger ?? '')], score });
184
+ scored.push({
185
+ name: String(card.name ?? ''),
186
+ trigger: Array.isArray(card.trigger) ? card.trigger.slice(0, 4) : [String(card.trigger ?? '')],
187
+ path: String(card.rel ?? ''),
188
+ score,
189
+ });
185
190
  }
186
191
  scored.sort((left, right) => right.score - left.score || left.name.localeCompare(right.name));
187
192
  return scored.slice(0, Math.max(0, maxItems));
@@ -206,6 +211,22 @@ function textOf(message) {
206
211
  return parts.length > 0 ? parts.join('\n') : '';
207
212
  }
208
213
 
214
+ /**
215
+ * 当前步最后一条真实用户消息的首段文本。与 recall/index.js 里 firstTextOf(lastUserMessage)
216
+ * 同源口径(取首个 content text 块,回退 data.text),供 continuity-volatile 匹配动作动词
217
+ * 选程序卡;注入消息 / 子代理消息不算用户消息(isRealUserMessage 过滤)。
218
+ */
219
+ export function lastUserTextFromMessages(messages) {
220
+ const list = Array.isArray(messages) ? messages : [];
221
+ const lastUserMessage = [...list].reverse().find((message) => isRealUserMessage(message)) ?? null;
222
+ if (!lastUserMessage) return '';
223
+ const content = Array.isArray(lastUserMessage.content) ? lastUserMessage.content : [];
224
+ const block = content.find((item) => item?.type === 'text' && typeof item.text === 'string');
225
+ if (block) return block.text;
226
+ if (typeof lastUserMessage.text === 'string') return lastUserMessage.text;
227
+ return '';
228
+ }
229
+
209
230
  function normalizeTurn(payload) {
210
231
  const value = Number(payload?.turn);
211
232
  return Number.isFinite(value) ? value : null;
@@ -391,13 +412,30 @@ export function renderPendingBlock({ pending, items = [], procedures = [], scann
391
412
  return { hit: true, block };
392
413
  }
393
414
 
394
- function hardgateEvidence({ pending, items = 0, procedures = 0, scanned = 0, extra = [] } = {}) {
415
+ function hardgateEvidence({
416
+ pending,
417
+ items = 0,
418
+ procedures = 0,
419
+ scanned = 0,
420
+ procedureNames = [],
421
+ procedurePaths = [],
422
+ extra = [],
423
+ } = {}) {
424
+ // 2.2.0 lane-B:程序卡回执(供 lane-C 动作门做匹配)。格式稳定:key=value,
425
+ // 最多 2 项、'|' 分隔、相对路径;无程序卡命中时不写这两行(旧行 sha 不变)。
426
+ const names = (Array.isArray(procedureNames) ? procedureNames : [])
427
+ .filter((name) => typeof name === 'string' && name !== '').slice(0, 2);
428
+ const paths = (Array.isArray(procedurePaths) ? procedurePaths : [])
429
+ .filter((item) => typeof item === 'string' && item !== '').slice(0, 2);
395
430
  return [
396
431
  `recallId=${pending?.recallId ?? 'unknown'}`,
397
432
  `items=${items}`,
398
433
  `procedures=${procedures}`,
399
434
  `scanned=${scanned}`,
400
435
  ...(Array.isArray(extra) ? extra : []),
436
+ // 仅追加在既有字段之后,2.1.0 面板按 key=value 读,旧字段位置不变。
437
+ ...(names.length > 0 ? [`procedureNames=${names.join('|')}`] : []),
438
+ ...(paths.length > 0 ? [`procedurePaths=${paths.join('|')}`] : []),
401
439
  ];
402
440
  }
403
441
 
@@ -412,6 +450,8 @@ export function finishPendingInjection({
412
450
  items = 0,
413
451
  procedures = 0,
414
452
  scanned = 0,
453
+ procedureNames = [],
454
+ procedurePaths = [],
415
455
  extra = [],
416
456
  metrics = null,
417
457
  warn,
@@ -453,7 +493,7 @@ export function finishPendingInjection({
453
493
  turn: pending?.turn,
454
494
  decision: resultVerdict.decision,
455
495
  reason: resultVerdict.reason,
456
- evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
496
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, procedureNames, procedurePaths, extra }),
457
497
  metrics,
458
498
  warn,
459
499
  });
@@ -480,7 +520,9 @@ export function recordPendingFailure({ pending, reason = RECALL_FAIL_CODE_INJECT
480
520
  }
481
521
 
482
522
  /** 生产链尾命中/归档分支:文本已注入,只补写唯一一行 gate-log。 */
483
- export function recordPendingResult({ pending, hit, items = 0, procedures = 0, scanned = 0, extra = [], metrics = null, warn } = {}) {
523
+ export function recordPendingResult({
524
+ pending, hit, items = 0, procedures = 0, scanned = 0, procedureNames = [], procedurePaths = [], extra = [], metrics = null, warn,
525
+ } = {}) {
484
526
  // B3 P1 接线:ok/zero-hit 判决由统一判决函数给(命中 → ok/hit,零命中 → zero-hit/zero-hit)。
485
527
  const verdict = assertRecallInjectionDecision(resolveRecallInjectionDecision({ zeroHit: hit !== true }));
486
528
  return writeGateRow(pending?.memoryRoot ?? '', {
@@ -488,7 +530,7 @@ export function recordPendingResult({ pending, hit, items = 0, procedures = 0, s
488
530
  turn: pending?.turn,
489
531
  decision: verdict.decision,
490
532
  reason: verdict.reason,
491
- evidence: hardgateEvidence({ pending, items, procedures, scanned, extra }),
533
+ evidence: hardgateEvidence({ pending, items, procedures, scanned, procedureNames, procedurePaths, extra }),
492
534
  metrics,
493
535
  warn,
494
536
  });
@@ -0,0 +1,435 @@
1
+ // lane-core/continuity-log.mjs
2
+ // 2.1.0 P1b/P1e:`.longlive/continuity.jsonl` 每 turn 一行审计账。
3
+ //
4
+ // 契约来源:PLAN-v0.4.md §0 #08、§3、§4 F10(行/上限/校验)。
5
+ // - 每 turn 一行:{schema, at, turn, mode, steps, volatileBlocks, chars, volatileChars,
6
+ // cards, drop, fail, ms}(任务书字段 + schema/at 便于滚动与校验)。
7
+ // - 滚动上限:30 天 或 100000 行,两者先到先裁(裁最旧)。
8
+ // - 原子写:写 <file>.tmp-* → fsync → rename 覆盖;读回校验在 append 内完成(写后自检)。
9
+ // - 容错:已有坏行(非 JSON)跳过并计数,不阻断追加;输入行不合法则拒收(ok:false)。
10
+ // - 只写 memoryRoot 下的 .longlive/ 子目录;不写会话,不写其他文件。
11
+ //
12
+ // 该文件与 continuity-volatile.mjs 解耦:本模块不认识 record,只认字段齐全的 row;
13
+ // P1e 集成点用 createTurnAccumulator 汇总每步 record,turn 结束时 appendContinuityRow。
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+
18
+ export const CONTINUITY_LOG_SCHEMA = 'continuity-log/v1';
19
+
20
+ /** 行数上限(PLAN-v0.4 §0 #08)。 */
21
+ export const CONTINUITY_LOG_MAX_ROWS = 100000;
22
+
23
+ /** 天数上限(PLAN-v0.4 §0 #08)。 */
24
+ export const CONTINUITY_LOG_MAX_AGE_DAYS = 30;
25
+
26
+ /** 合法 mode 值(与 continuity-volatile 的 record.mode 对齐)。 */
27
+ export const CONTINUITY_MODES = Object.freeze(['volatile', 'degraded', 'fallback', 'fail', 'off']);
28
+
29
+ /** 行字段(固定顺序,便于 diff/审计)。 */
30
+ export const CONTINUITY_ROW_FIELDS = Object.freeze([
31
+ 'schema',
32
+ 'at',
33
+ 'turn',
34
+ 'mode',
35
+ 'steps',
36
+ 'volatileBlocks',
37
+ 'chars',
38
+ 'volatileChars',
39
+ 'cards',
40
+ 'drop',
41
+ 'fail',
42
+ 'ms',
43
+ ]);
44
+
45
+ const MS_PER_DAY = 86400000;
46
+ const MODE_RANK = Object.freeze({ volatile: 0, degraded: 1, fallback: 2, fail: 3, off: 4 });
47
+
48
+ function logError(code, message = '') {
49
+ const error = new Error(message || String(code));
50
+ error.code = String(code);
51
+ return error;
52
+ }
53
+
54
+ function nowMillis(clock) {
55
+ const value = typeof clock === 'function' ? clock() : clock;
56
+ if (value instanceof Date) return value.getTime();
57
+ const n = Number(value);
58
+ return Number.isFinite(n) ? n : Date.now();
59
+ }
60
+
61
+ function positiveInteger(value, fallback) {
62
+ const n = Number(value);
63
+ return Number.isInteger(n) && n > 0 ? n : fallback;
64
+ }
65
+
66
+ function nonNegativeInteger(value, fallback = 0) {
67
+ const n = Number(value);
68
+ return Number.isInteger(n) && n >= 0 ? n : fallback;
69
+ }
70
+
71
+ /** `.longlive/continuity.jsonl` 的绝对路径(不创建目录)。 */
72
+ export function continuityLogPath(memoryRoot) {
73
+ if (typeof memoryRoot !== 'string' || memoryRoot.trim() === '') {
74
+ throw logError('E_MEMORY_ROOT', 'memoryRoot 必须是非空字符串');
75
+ }
76
+ return path.join(path.resolve(memoryRoot), '.longlive', 'continuity.jsonl');
77
+ }
78
+
79
+ /**
80
+ * 校验并规范化一行。缺省 `at` 用当前时间;数值缺省 0;未知字段丢弃。
81
+ * 非法输入抛错(带 code),由 appendContinuityRow 转成 {ok:false}。
82
+ */
83
+ export function normalizeContinuityRow(input, { now = Date.now } = {}) {
84
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
85
+ throw logError('E_ROW_INVALID', 'continuity row 必须是对象');
86
+ }
87
+ const mode = typeof input.mode === 'string' ? input.mode.trim() : '';
88
+ if (mode === '') throw logError('E_ROW_MODE', 'continuity row.mode 缺失');
89
+ if (!CONTINUITY_MODES.includes(mode)) {
90
+ throw logError('E_ROW_MODE', `continuity row.mode 非法:${mode}`);
91
+ }
92
+ const field = (name, fallback = 0, validator = nonNegativeInteger) => {
93
+ const raw = input[name];
94
+ if (raw === undefined) return fallback;
95
+ const n = Number(raw);
96
+ if (!Number.isFinite(n) || n < 0 || !Number.isInteger(n)) {
97
+ throw logError('E_ROW_FIELD', `continuity row.${name} 必须是非负整数`);
98
+ }
99
+ return n;
100
+ };
101
+ const turn = field('turn', 0);
102
+ const steps = field('steps', 0);
103
+ const volatileBlocks = field('volatileBlocks', 0);
104
+ const chars = field('chars', 0);
105
+ const volatileChars = field('volatileChars', 0);
106
+ const cards = field('cards', 0);
107
+ const drop = field('drop', 0);
108
+ const fail = field('fail', 0);
109
+ const msRaw = input.ms === undefined ? 0 : Number(input.ms);
110
+ if (!Number.isFinite(msRaw) || msRaw < 0) {
111
+ throw logError('E_ROW_FIELD', 'continuity row.ms 必须是 >=0 的数字');
112
+ }
113
+ const atRaw = typeof input.at === 'string' ? input.at.trim() : '';
114
+ const atMs = atRaw === '' ? NaN : Date.parse(atRaw);
115
+ const at = Number.isFinite(atMs) ? new Date(atMs).toISOString() : new Date(nowMillis(now)).toISOString();
116
+ return {
117
+ schema: CONTINUITY_LOG_SCHEMA,
118
+ at,
119
+ turn,
120
+ mode,
121
+ steps,
122
+ volatileBlocks,
123
+ chars,
124
+ volatileChars,
125
+ cards,
126
+ drop,
127
+ fail,
128
+ ms: Math.round(msRaw),
129
+ };
130
+ }
131
+
132
+ /**
133
+ * 裁剪:先按 30 天年龄(at 无效的行保留,无法判龄),再做行数上限(从最旧裁)。
134
+ * 返回 {rows, dropped, droppedByAge, droppedByRows};不修改入参。
135
+ */
136
+ export function pruneContinuityRows(rows, options = {}) {
137
+ const list = Array.isArray(rows) ? rows : [];
138
+ const maxRows = positiveInteger(options.maxRows, CONTINUITY_LOG_MAX_ROWS);
139
+ const maxAgeDays = positiveInteger(options.maxAgeDays, CONTINUITY_LOG_MAX_AGE_DAYS);
140
+ const nowMs = nowMillis(options.now);
141
+ const cutoff = nowMs - maxAgeDays * MS_PER_DAY;
142
+ let droppedByAge = 0;
143
+ const kept = [];
144
+ for (const row of list) {
145
+ const atMs = row && typeof row.at === 'string' ? Date.parse(row.at) : NaN;
146
+ if (Number.isFinite(atMs) && atMs < cutoff) {
147
+ droppedByAge += 1;
148
+ continue;
149
+ }
150
+ kept.push(row);
151
+ }
152
+ const overflow = Math.max(0, kept.length - maxRows);
153
+ const resultRows = overflow > 0 ? kept.slice(overflow) : kept;
154
+ return {
155
+ rows: resultRows,
156
+ dropped: droppedByAge + overflow,
157
+ droppedByAge,
158
+ droppedByRows: overflow,
159
+ };
160
+ }
161
+
162
+ /**
163
+ * 把同一 turn 的每步 record 聚合成一行(P1e 集成点)。
164
+ * mode 取最严重(volatile < degraded < fallback < fail < off);
165
+ * chars/volatileChars/drop/fail/ms 求和,cards 取最大值(一 turn 只读一次卡)。
166
+ */
167
+ export function aggregateTurnRecords(records, options = {}) {
168
+ const list = Array.isArray(records) ? records : [];
169
+ let turn = Number.isInteger(options.turn) ? options.turn : null;
170
+ let mode = null;
171
+ let steps = 0;
172
+ let volatileBlocks = 0;
173
+ let chars = 0;
174
+ let volatileChars = 0;
175
+ let cards = 0;
176
+ let drop = 0;
177
+ let fail = 0;
178
+ let ms = 0;
179
+ for (const record of list) {
180
+ if (!record || typeof record !== 'object') continue;
181
+ steps += 1;
182
+ if (turn === null && Number.isInteger(record.turn)) turn = record.turn;
183
+ volatileBlocks += nonNegativeInteger(record.volatileBlocks, 0);
184
+ chars += nonNegativeInteger(record.chars, 0);
185
+ volatileChars += nonNegativeInteger(record.volatileChars, 0);
186
+ cards = Math.max(cards, nonNegativeInteger(record.cards, 0));
187
+ drop += nonNegativeInteger(record.drop, 0);
188
+ fail += nonNegativeInteger(record.fail, 0);
189
+ const recordMs = Number(record.ms);
190
+ if (Number.isFinite(recordMs) && recordMs >= 0) ms += recordMs;
191
+ const recordMode = CONTINUITY_MODES.includes(record.mode) ? record.mode : 'fail';
192
+ if (mode === null || MODE_RANK[recordMode] > MODE_RANK[mode]) mode = recordMode;
193
+ }
194
+ const at = typeof options.at === 'string'
195
+ ? new Date(Date.parse(options.at)).toISOString()
196
+ : new Date(nowMillis(options.now)).toISOString();
197
+ return {
198
+ schema: CONTINUITY_LOG_SCHEMA,
199
+ at,
200
+ turn: turn ?? 0,
201
+ mode: mode ?? 'off',
202
+ steps,
203
+ volatileBlocks,
204
+ chars,
205
+ volatileChars,
206
+ cards,
207
+ drop,
208
+ fail,
209
+ ms: Math.round(ms),
210
+ };
211
+ }
212
+
213
+ /** 逐 turn 累加器:record(每步) → finish() 得一行。finish 后计数清零(可复用)。 */
214
+ export function createTurnAccumulator(options = {}) {
215
+ const records = [];
216
+ let turn = Number.isInteger(options.turn) ? options.turn : null;
217
+ const clock = options.now ?? null;
218
+ return {
219
+ record(record) {
220
+ if (record && typeof record === 'object') records.push(record);
221
+ return records.length;
222
+ },
223
+ size() {
224
+ return records.length;
225
+ },
226
+ snapshot(extra = {}) {
227
+ return aggregateTurnRecords(records, {
228
+ turn: extra.turn !== undefined ? extra.turn : turn ?? undefined,
229
+ at: extra.at,
230
+ now: extra.now ?? clock,
231
+ });
232
+ },
233
+ finish(extra = {}) {
234
+ const row = this.snapshot(extra);
235
+ records.length = 0;
236
+ return row;
237
+ },
238
+ };
239
+ }
240
+
241
+ function defaultMissingResult(file) {
242
+ return { ok: true, present: false, file, rows: [], lines: 0, badLines: 0, bytes: 0 };
243
+ }
244
+
245
+ /**
246
+ * 读取整份审计账(只读)。坏行跳过并计入 badLines,不抛错。
247
+ * 返回 {ok, present, file, rows, lines, badLines, bytes} 或 {ok:false, code, message}。
248
+ */
249
+ export function readContinuityLog(memoryRoot) {
250
+ let file;
251
+ try {
252
+ file = continuityLogPath(memoryRoot);
253
+ } catch (error) {
254
+ return { ok: false, code: error.code ?? 'E_MEMORY_ROOT', message: error.message, rows: [], lines: 0, badLines: 0 };
255
+ }
256
+ let stat;
257
+ try {
258
+ stat = fs.statSync(file);
259
+ } catch (error) {
260
+ if (error && error.code === 'ENOENT') return defaultMissingResult(file);
261
+ return { ok: false, code: 'E_IO', message: String(error && error.message), file, rows: [], lines: 0, badLines: 0 };
262
+ }
263
+ if (!stat.isFile()) {
264
+ return { ok: false, code: 'E_IO', message: 'continuity.jsonl 不是普通文件', file, rows: [], lines: 0, badLines: 0 };
265
+ }
266
+ let raw;
267
+ try {
268
+ raw = fs.readFileSync(file, 'utf8');
269
+ } catch (error) {
270
+ return { ok: false, code: 'E_IO', message: String(error && error.message), file, rows: [], lines: 0, badLines: 0 };
271
+ }
272
+ const rows = [];
273
+ let badLines = 0;
274
+ let lines = 0;
275
+ for (const line of raw.split('\n')) {
276
+ if (line.trim() === '') continue;
277
+ lines += 1;
278
+ try {
279
+ const value = JSON.parse(line);
280
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
281
+ rows.push(value);
282
+ } else {
283
+ badLines += 1;
284
+ }
285
+ } catch {
286
+ badLines += 1;
287
+ }
288
+ }
289
+ return { ok: true, present: true, file, rows, lines, badLines, bytes: Buffer.byteLength(raw, 'utf8') };
290
+ }
291
+
292
+ function writeAtomic(file, text) {
293
+ fs.mkdirSync(path.dirname(file), { recursive: true });
294
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
295
+ let fd = null;
296
+ try {
297
+ fd = fs.openSync(tmp, 'w');
298
+ fs.writeFileSync(fd, text, 'utf8');
299
+ fs.fsyncSync(fd);
300
+ fs.closeSync(fd);
301
+ fd = null;
302
+ fs.renameSync(tmp, file);
303
+ } catch (error) {
304
+ if (fd !== null) {
305
+ try {
306
+ fs.closeSync(fd);
307
+ } catch {
308
+ // ignore
309
+ }
310
+ }
311
+ try {
312
+ fs.unlinkSync(tmp);
313
+ } catch {
314
+ // ignore
315
+ }
316
+ throw error;
317
+ }
318
+ }
319
+
320
+ /**
321
+ * 追加一行并滚动裁剪(原子写:tmp → fsync → rename)。返回 {ok, ...},不抛错。
322
+ * options:maxRows(默认 100000)、maxAgeDays(默认 30)、now(可注入时钟)。
323
+ */
324
+ export function appendContinuityRow(memoryRoot, input, options = {}) {
325
+ let row;
326
+ try {
327
+ row = normalizeContinuityRow(input, { now: options.now });
328
+ } catch (error) {
329
+ return { ok: false, code: error.code ?? 'E_ROW_INVALID', message: error.message };
330
+ }
331
+ let file;
332
+ try {
333
+ file = continuityLogPath(memoryRoot);
334
+ } catch (error) {
335
+ return { ok: false, code: error.code ?? 'E_MEMORY_ROOT', message: error.message };
336
+ }
337
+ const maxRows = positiveInteger(options.maxRows, CONTINUITY_LOG_MAX_ROWS);
338
+ const maxAgeDays = positiveInteger(options.maxAgeDays, CONTINUITY_LOG_MAX_AGE_DAYS);
339
+ const existing = readContinuityLog(memoryRoot);
340
+ if (!existing.ok) {
341
+ return { ok: false, code: existing.code ?? 'E_IO', message: existing.message ?? '读取 continuity.jsonl 失败' };
342
+ }
343
+ const pruned = pruneContinuityRows([...existing.rows, row], {
344
+ now: options.now,
345
+ maxRows,
346
+ maxAgeDays,
347
+ });
348
+ const text = pruned.rows.map((item) => JSON.stringify(item)).join('\n') + '\n';
349
+ try {
350
+ writeAtomic(file, text);
351
+ } catch (error) {
352
+ return { ok: false, code: 'E_IO', message: String(error && error.message) };
353
+ }
354
+ return {
355
+ ok: true,
356
+ file,
357
+ row,
358
+ rows: pruned.rows.length,
359
+ dropped: pruned.dropped,
360
+ droppedByAge: pruned.droppedByAge,
361
+ droppedByRows: pruned.droppedByRows,
362
+ badLines: existing.badLines,
363
+ bytes: Buffer.byteLength(text, 'utf8'),
364
+ };
365
+ }
366
+
367
+ /** 便捷入口:turns 的每步 records → 聚合一行 → 追加。 */
368
+ export function writeTurnRow(memoryRoot, records, options = {}) {
369
+ const row = aggregateTurnRecords(records, {
370
+ turn: options.turn,
371
+ at: options.at,
372
+ now: options.now,
373
+ });
374
+ return appendContinuityRow(memoryRoot, row, options);
375
+ }
376
+
377
+ /**
378
+ * gate-log evidence 片段(PLAN-v0.4 §3:每轮汇总带 cont:{mode,steps,chars,drop})。
379
+ * 输入为 row;缺字段按 0 处理,不抛错。
380
+ */
381
+ export function continuityEvidence(row) {
382
+ const value = row && typeof row === 'object' ? row : {};
383
+ const mode = CONTINUITY_MODES.includes(value.mode) ? value.mode : 'off';
384
+ const steps = nonNegativeInteger(value.steps, 0);
385
+ const chars = nonNegativeInteger(value.chars, 0);
386
+ const drop = nonNegativeInteger(value.drop, 0);
387
+ return `cont:{mode:${mode},steps:${steps},chars:${chars},drop:${drop}}`;
388
+ }
389
+
390
+ /**
391
+ * health daily 汇总(PLAN-v0.4 §3):读若干 row,给出 health.daily.continuity 所需字段。
392
+ * 返回 {rows, byMode, degradedRows, steps, volatileBlocks, chars, volatileChars, cards, drop, fail, lastAt}。
393
+ */
394
+ export function summarizeContinuityLog(rows) {
395
+ const list = Array.isArray(rows) ? rows : [];
396
+ const byMode = Object.fromEntries(CONTINUITY_MODES.map((mode) => [mode, 0]));
397
+ let steps = 0;
398
+ let volatileBlocks = 0;
399
+ let chars = 0;
400
+ let volatileChars = 0;
401
+ let cards = 0;
402
+ let drop = 0;
403
+ let fail = 0;
404
+ let degradedRows = 0;
405
+ let lastAt = null;
406
+ for (const row of list) {
407
+ if (!row || typeof row !== 'object') continue;
408
+ if (byMode[row.mode] !== undefined) byMode[row.mode] += 1;
409
+ if (row.mode === 'degraded' || row.mode === 'fallback' || row.mode === 'fail') degradedRows += 1;
410
+ steps += nonNegativeInteger(row.steps, 0);
411
+ volatileBlocks += nonNegativeInteger(row.volatileBlocks, 0);
412
+ chars += nonNegativeInteger(row.chars, 0);
413
+ volatileChars += nonNegativeInteger(row.volatileChars, 0);
414
+ cards += nonNegativeInteger(row.cards, 0);
415
+ drop += nonNegativeInteger(row.drop, 0);
416
+ fail += nonNegativeInteger(row.fail, 0);
417
+ if (typeof row.at === 'string') {
418
+ const atMs = Date.parse(row.at);
419
+ if (Number.isFinite(atMs) && (lastAt === null || atMs > lastAt)) lastAt = atMs;
420
+ }
421
+ }
422
+ return {
423
+ rows: list.length,
424
+ byMode,
425
+ degradedRows,
426
+ steps,
427
+ volatileBlocks,
428
+ chars,
429
+ volatileChars,
430
+ cards,
431
+ drop,
432
+ fail,
433
+ lastAt: lastAt === null ? null : new Date(lastAt).toISOString(),
434
+ };
435
+ }