dsh-extra-plan 0.0.0-stage → 1.7.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -2
  3. package/assets/presets/extra-plan/agent.cordis.yml +580 -0
  4. package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
  5. package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
  6. package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
  7. package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
  8. package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
  9. package/assets/presets/extra-plan/preset.yml +2 -0
  10. package/cordis.patch.yml +7 -0
  11. package/index.js +1671 -0
  12. package/lib/agent-runtime.js +172 -0
  13. package/lib/agent-session.js +65 -0
  14. package/lib/assembly-presentation.js +267 -0
  15. package/lib/client-carrier.js +7 -0
  16. package/lib/client.js +314 -0
  17. package/lib/extra-plan-gate-tool.js +387 -0
  18. package/lib/gate-decisions.js +744 -0
  19. package/lib/gate-words.js +108 -0
  20. package/lib/live-config.js +293 -0
  21. package/lib/log-retention.js +132 -0
  22. package/lib/model-routing.js +648 -0
  23. package/lib/path-policy.js +464 -0
  24. package/lib/plan-draft-tool.js +294 -0
  25. package/lib/planner-budget.js +136 -0
  26. package/lib/preset-defaults.generated.js +17 -0
  27. package/lib/preset-settings.js +3 -0
  28. package/lib/preset-sync.js +809 -0
  29. package/lib/preset-yaml.js +438 -0
  30. package/lib/role-contract.js +11 -0
  31. package/lib/run-code-scanner.js +360 -0
  32. package/lib/run-code-static.js +621 -0
  33. package/lib/runtime-diagnostics.js +89 -0
  34. package/lib/runtime-lifecycle.js +162 -0
  35. package/lib/runtime-static.js +23 -0
  36. package/lib/save-contract.js +263 -0
  37. package/lib/save-persistence.js +223 -0
  38. package/lib/save-plan-markdown-parser.js +369 -0
  39. package/lib/save-plan-validation-diagnostics.js +49 -0
  40. package/lib/save-plan-validation.js +812 -0
  41. package/lib/save-probe-validation.js +173 -0
  42. package/lib/save-source-verification.js +195 -0
  43. package/lib/save-tool-factories.js +270 -0
  44. package/lib/sdk-text-cache.js +161 -0
  45. package/lib/settings-contract.js +191 -0
  46. package/lib/settings.js +369 -0
  47. package/lib/shell-mutation.js +484 -0
  48. package/lib/usage-ledger-background.js +214 -0
  49. package/lib/usage-ledger-worker.js +116 -0
  50. package/lib/usage-ledger.js +1393 -0
  51. package/locale/en.json +6 -0
  52. package/locale/settings/en.json +6 -0
  53. package/locale/settings/zh.json +6 -0
  54. package/locale/zh.json +6 -0
  55. package/package.json +56 -4
  56. package/scripts/generate-runtime-defaults.mjs +796 -0
@@ -0,0 +1,1393 @@
1
+ // 用量账本(改造11 三模块合并)——本文件是账本唯一实现,四段职责:
2
+ // ① 常量与身份键;
3
+ // ② 扫描(改造11 前在独立扫描模块:枚举 sessions/<ws>/<sid>/session.v4.jsonl.zstd、node:zlib 多帧解压、
4
+ // 事件提取、白名单过滤、身份聚合);
5
+ // ③ 写入(改造11 前在独立归档模块:读现有 archive、按身份覆盖式更新、单调性保护、说明行、temp→rename 原子发布);
6
+ // ④ 同步直调 archiveLedger、启动归档 startupArchive;启动归档由 settings Worker 调度。
7
+ // 同步直调 archiveLedger 不承担进程互斥;改造11 相对合并前(291+543+1000=1834 行)删除:createUsageLedger 空壳、
8
+ // 整套跨进程锁(等待轮询、死 PID 接管、stale-lock 告警)、双文件事务、逆序回滚、active 相关分支。
9
+ // 启动归档写入互斥只剩一次 O_EXCL 建 <archive>.lock:锁忙即跳过本次启动归档写入并留痕,不等待、不接管、不删他人锁;单 archive 经 temp→rename 原子发布,不承诺 CLI 手工归档。
10
+ import { appendFileSync, closeSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync } from 'node:fs'
11
+ import { randomUUID } from 'node:crypto'
12
+ import { basename, dirname, join } from 'node:path'
13
+ import { zstdDecompressSync } from 'node:zlib'
14
+ import { ROLE_IDS, USAGE_ROLE_BY_PRESET } from './role-contract.js'
15
+ import { createPathContext, resolveHostPath, prepareWriteTarget, validateReadTarget } from './path-policy.js'
16
+ import { errorCodeOf, errorText as errorMessageOf } from './runtime-static.js'
17
+
18
+
19
+ // ── ① 常量区 ─────────────────────────────────────────────────────────────────
20
+ const SESSIONS_DIRECTORY = 'sessions'
21
+ const SESSION_LOG_FILE_NAME = 'session.v4.jsonl.zstd'
22
+ const SUPPORTED_SESSION_VERSION = 4
23
+ const USAGE_PRESET = 'extra-plan'
24
+
25
+ // 严格白名单:主预设 extra-plan 与 role-contract 的四个角色预设 id(executor/planner/reviewer/prober)。
26
+ // 预设不在白名单的会话整体跳过,不产出任何行。
27
+ export const ALLOWED_PRESETS = Object.freeze([USAGE_PRESET, ...ROLE_IDS])
28
+
29
+ export const IDENTITY_KEYS = Object.freeze([
30
+ 'schemaVersion',
31
+ 'rootSessionId',
32
+ 'sessionId',
33
+ 'parentSessionId',
34
+ 'agentPreset',
35
+ 'delegationDepth',
36
+ 'role',
37
+ 'model',
38
+ 'provider',
39
+ ])
40
+
41
+ const TOKEN_KEYS = Object.freeze([
42
+ 'inputTokens',
43
+ 'cacheReadTokens',
44
+ 'cacheWriteTokens',
45
+ 'outputTokens',
46
+ ])
47
+
48
+ // 主会话目录名是 session-<uuid>,子代理会话目录名是裸 <uuid>(目录名即会话 id);
49
+ // 两者都是会话目录,其余目录(临时/缓存等)整体跳过。
50
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
51
+ const SESSION_ID_PREFIX = 'session-'
52
+ const MAX_PARENT_DEPTH = 8
53
+
54
+ // 只用字符串前缀判断行里是否可能是目标事件:整行 JSON.parse 前先做 O(n) 子串过滤,
55
+ // 避免为几乎全部内容型事件(assistant 正文、工具输出)付解析代价。
56
+ const EVENT_MARKERS = Object.freeze({
57
+ session: '"session"',
58
+ usage: '"assistant/message"',
59
+ presetSelected: '"agent-preset/selected"',
60
+ requestHeader: '"request/header"',
61
+ })
62
+
63
+ // ── ①b 账本常量(由旧归档模块迁入)────────────────────────────────────
64
+ const STARTUP_ARCHIVE_BUDGET_MS = 3000
65
+
66
+ const ARCHIVE_FILE_NAME = 'extra-plan-usage-ledger.jsonl'
67
+ const LEDGER_DIRECTORY = join('logs', 'dsh-extra-plan')
68
+ const DIAGNOSTIC_FILE_NAME = 'extra-plan-usage-errors.jsonl'
69
+ const LEDGER_PURPOSE = 'usage-ledger'
70
+
71
+ const V2_KEYS = Object.freeze([
72
+ 'schemaVersion',
73
+ 'ts',
74
+ 'sessionId',
75
+ 'parentSessionId',
76
+ 'rootSessionId',
77
+ 'agentPreset',
78
+ 'delegationDepth',
79
+ 'role',
80
+ 'model',
81
+ 'provider',
82
+ 'inputTokens',
83
+ 'cacheReadTokens',
84
+ 'cacheWriteTokens',
85
+ 'outputTokens',
86
+ 'seq',
87
+ ])
88
+
89
+ // 归档首行说明行:kind 固定为「账本说明」,说明 给人类读口径,键 是数据行 15 个键的逗号展开。
90
+ // 说明行只允许唯一一条出现在首行,统计与归档一律跳过;判定必须三字段全形,避免把只有 kind 的垃圾行当说明行静默吞掉。
91
+ export const SCHEMA_DOC_KIND = '账本说明'
92
+ export const SCHEMA_DOC_ROW = Object.freeze({
93
+ kind: SCHEMA_DOC_KIND,
94
+ 说明: '一行等于一个完整身份累计行;总消耗为四桶相加;inputTokens 是未命中缓存输入,cacheReadTokens 是命中输入,'
95
+ + 'cacheWriteTokens 可为非零,outputTokens 为输出;seq 是会话内事件水位,不可当主键;'
96
+ + 'ts 是该会话日志上次被解析时的最后修改时间(文件时间点);增量判定锚点:日志当前 mtime 与该值一致则跳过重扫;delegationDepth 0 主会话、1 一级委派;parentSessionId 空串为主会话;'
97
+ + 'role 取值含 main、child 及 executor/planner/reviewer/prober 四角色;agentPreset 是预设名;model 与 provider 分别为模型名与供应商名。',
98
+ 键: V2_KEYS.join(','),
99
+ })
100
+ export const SCHEMA_DOC_LINE = JSON.stringify(SCHEMA_DOC_ROW)
101
+
102
+ export function isSchemaDocRow(row) {
103
+ return isPlainObject(row) && row.kind === SCHEMA_DOC_KIND && typeof row.说明 === 'string' && typeof row.键 === 'string'
104
+ }
105
+
106
+ const DEFAULT_FS_OPS = Object.freeze({
107
+ mkdirSync,
108
+ readdirSync,
109
+ readFileSync,
110
+ renameSync,
111
+ unlinkSync,
112
+ writeFileSync,
113
+ appendFileSync,
114
+ })
115
+
116
+ function archiveError(code, message) {
117
+ const error = new Error(message)
118
+ error.code = code
119
+ return error
120
+ }
121
+
122
+ function checkArchiveCancellation(options) {
123
+ if (isPlainObject(options) && typeof options.shouldCancel === 'function' && options.shouldCancel() === true) {
124
+ throw archiveError('archive-cancelled', '归档已协作取消')
125
+ }
126
+ }
127
+
128
+ function isPlainObject(value) {
129
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
130
+ }
131
+
132
+ function bytesOf(value) {
133
+ if (Buffer.isBuffer(value)) return Buffer.from(value)
134
+ if (value instanceof Uint8Array) return Buffer.from(value)
135
+ return Buffer.from(String(value === undefined || value === null ? '' : value), 'utf8')
136
+ }
137
+
138
+ function textOfBytes(value) {
139
+ return bytesOf(value).toString('utf8')
140
+ }
141
+
142
+ // ── ② 路径枚举 ───────────────────────────────────────────────────────────────
143
+ function isSessionDirectoryName(name) {
144
+ if (typeof name !== 'string' || name === '') return false
145
+ const candidate = name.startsWith(SESSION_ID_PREFIX) ? name.slice(SESSION_ID_PREFIX.length) : name
146
+ return UUID_PATTERN.test(candidate)
147
+ }
148
+
149
+ function sessionReadPath(pathContext, path, expectedType) {
150
+ const target = resolveHostPath(pathContext, path, { purpose: LEDGER_PURPOSE })
151
+ return validateReadTarget(pathContext, target, { expectedType, purpose: LEDGER_PURPOSE }).realPath
152
+ }
153
+
154
+ function sessionPathMissing(error) {
155
+ const code = errorCodeOf(error)
156
+ return code === 'ENOENT' || code === 'TARGET_MISSING'
157
+ }
158
+
159
+ function listEntries(pathContext, directory, readEntries) {
160
+ try {
161
+ return readEntries(sessionReadPath(pathContext, directory, 'directory'), { withFileTypes: true })
162
+ } catch (error) {
163
+ if (sessionPathMissing(error)) return []
164
+ throw error
165
+ }
166
+ }
167
+
168
+ // 遍历 sessions/<workspace>/<sessionId>/session.v4.jsonl.zstd;逐层列举,跳过非会话目录与非目标文件名。
169
+ export function enumerateSessionLogs({ hostRoot, shouldCancel, pathContext, fsOps } = {}) {
170
+ const root = typeof hostRoot === 'string' && hostRoot.trim() !== '' ? hostRoot : ''
171
+ const logFiles = []
172
+ let skippedEntries = 0
173
+ checkArchiveCancellation({ shouldCancel })
174
+ if (root === '') return { logFiles, skippedEntries, root }
175
+ const context = pathContext ?? createPathContext({ hostDataRoot: root })
176
+ const readEntries = fsOps?.readdirSync ?? readdirSync
177
+ const sessionsRoot = join(root, SESSIONS_DIRECTORY)
178
+ const workspaceEntries = listEntries(context, sessionsRoot, readEntries)
179
+ checkArchiveCancellation({ shouldCancel })
180
+ for (const workspaceEntry of workspaceEntries) {
181
+ checkArchiveCancellation({ shouldCancel })
182
+ if (!workspaceEntry.isDirectory()) {
183
+ skippedEntries += 1
184
+ continue
185
+ }
186
+ const workspacePath = join(sessionsRoot, workspaceEntry.name)
187
+ const sessionEntries = listEntries(context, workspacePath, readEntries)
188
+ checkArchiveCancellation({ shouldCancel })
189
+ for (const sessionEntry of sessionEntries) {
190
+ checkArchiveCancellation({ shouldCancel })
191
+ if (!sessionEntry.isDirectory() || !isSessionDirectoryName(sessionEntry.name)) {
192
+ skippedEntries += 1
193
+ continue
194
+ }
195
+ const logPath = join(workspacePath, sessionEntry.name, SESSION_LOG_FILE_NAME)
196
+ let logStat
197
+ try {
198
+ logStat = statSync(sessionReadPath(context, logPath, 'file'))
199
+ } catch (error) {
200
+ if (!sessionPathMissing(error) && errorCodeOf(error) !== 'TARGET_TYPE') throw error
201
+ skippedEntries += 1
202
+ continue
203
+ }
204
+ if (!logStat.isFile()) { skippedEntries += 1; continue }
205
+ checkArchiveCancellation({ shouldCancel })
206
+ // 枚举结果自带大小与 mtime,读取侧不再对同一 logPath 二次 statSync。
207
+ logFiles.push({ workspace: workspaceEntry.name, sessionDirectory: sessionEntry.name, logPath, size: logStat.size, mtimeMs: logStat.mtimeMs })
208
+ }
209
+ }
210
+ checkArchiveCancellation({ shouldCancel })
211
+ return { logFiles, skippedEntries, root }
212
+ }
213
+
214
+ // ── ③ 解码:zstd 多帧 ───────────────────────────────────────────────────────
215
+ // 帧切分的最小实现(不 import 任何测试目录模块):返回这一帧的结束偏移,缺损/非法块边界返回 null。
216
+ function frameEndAt(bytes, start) {
217
+ let cursor = start + 4
218
+ const descriptor = bytes[cursor]
219
+ if (descriptor === undefined) return null
220
+ cursor += 1
221
+ const singleSegment = (descriptor >> 5) & 1
222
+ const frameContentSizeFlag = (descriptor >> 6) & 3
223
+ const dictionaryFlag = descriptor & 3
224
+ const checksumFlag = (descriptor >> 2) & 1
225
+ if (!singleSegment) cursor += 1
226
+ cursor += dictionaryFlag === 1 ? 1 : dictionaryFlag === 2 ? 2 : dictionaryFlag === 3 ? 4 : 0
227
+ if (frameContentSizeFlag !== 0) cursor += frameContentSizeFlag === 1 ? 2 : frameContentSizeFlag === 2 ? 4 : 8
228
+ else if (singleSegment) cursor += 1
229
+ let last = false
230
+ while (!last) {
231
+ if (cursor + 3 > bytes.length) return null
232
+ const blockHeader = bytes.readUIntLE(cursor, 3)
233
+ const blockType = (blockHeader >> 1) & 3
234
+ const blockSize = blockHeader >> 3
235
+ if (blockType === 3 || blockSize > 0x20000) return null
236
+ last = (blockHeader & 1) === 1
237
+ // RLE 块的 Block_Size 是解压后长度,压缩载荷仅 1 字节。
238
+ const payloadSize = blockType === 1 ? 1 : blockSize
239
+ if (cursor + 3 + payloadSize > bytes.length) return null
240
+ cursor += 3 + payloadSize
241
+ }
242
+ if (checksumFlag !== 0) cursor += 4
243
+ return cursor <= bytes.length ? cursor : null
244
+ }
245
+
246
+ const ZSTD_MAGIC = 0xfd2fb528
247
+ const SKIPPABLE_MAGIC_MIN = 0x184d2a50
248
+ const SKIPPABLE_MAGIC_MAX = 0x184d2a5f
249
+
250
+ // 多帧输入按帧边界循环解压;帧间可能有 skippable frame,逐帧跳过。UTF-8 跨帧用流式解码器续接。
251
+ function* decodedLinesOf(bytes, shouldCancel) {
252
+ if (!Buffer.isBuffer(bytes)) throw new TypeError('decodedLinesOf requires a Buffer')
253
+ const decoder = new TextDecoder('utf-8')
254
+ let cursor = 0
255
+ let frames = 0
256
+ let pending = ''
257
+ let linesSinceCheck = 0
258
+ checkArchiveCancellation({ shouldCancel })
259
+ while (cursor < bytes.length) {
260
+ checkArchiveCancellation({ shouldCancel })
261
+ if (bytes.length - cursor < 4) throw new Error('truncated zstd frame header at byte ' + cursor)
262
+ const magic = bytes.readUInt32LE(cursor)
263
+ if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) {
264
+ if (bytes.length - cursor < 8) throw new Error('truncated skippable frame header at byte ' + cursor)
265
+ const end = cursor + 8 + bytes.readUInt32LE(cursor + 4)
266
+ if (end > bytes.length) throw new Error('truncated skippable frame at byte ' + cursor)
267
+ cursor = end
268
+ checkArchiveCancellation({ shouldCancel })
269
+ continue
270
+ }
271
+ if (magic !== ZSTD_MAGIC) throw new Error('unexpected bytes at byte ' + cursor)
272
+ const end = frameEndAt(bytes, cursor)
273
+ if (end === null) throw new Error('incomplete zstd frame at byte ' + cursor)
274
+ let chunk
275
+ try {
276
+ checkArchiveCancellation({ shouldCancel })
277
+ chunk = zstdDecompressSync(bytes.subarray(cursor, end))
278
+ } catch (error) {
279
+ if (errorCodeOf(error) === 'archive-cancelled') throw error
280
+ throw new Error('zstd frame decode failed at byte ' + cursor + ': ' + (error instanceof Error ? error.message : String(error)))
281
+ }
282
+ checkArchiveCancellation({ shouldCancel })
283
+ frames += 1
284
+ cursor = end
285
+ pending += decoder.decode(chunk, { stream: true })
286
+ let newline = pending.indexOf('\n')
287
+ while (newline !== -1) {
288
+ yield pending.slice(0, newline)
289
+ pending = pending.slice(newline + 1)
290
+ newline = pending.indexOf('\n')
291
+ linesSinceCheck += 1
292
+ if (linesSinceCheck >= 32) {
293
+ linesSinceCheck = 0
294
+ checkArchiveCancellation({ shouldCancel })
295
+ }
296
+ }
297
+ }
298
+ checkArchiveCancellation({ shouldCancel })
299
+ if (frames === 0) throw new Error('no complete zstd frame')
300
+ pending += decoder.decode()
301
+ if (pending !== '') yield pending
302
+ checkArchiveCancellation({ shouldCancel })
303
+ }
304
+
305
+ // ── ④ 事件提取 ──────────────────────────────────────────────────────────────
306
+ function finiteNumberOrZero(value) {
307
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : 0
308
+ }
309
+
310
+ function stringOrEmpty(value) {
311
+ return typeof value === 'string' ? value : ''
312
+ }
313
+
314
+ function intOrNull(value) {
315
+ return Number.isInteger(value) && value >= 0 ? value : null
316
+ }
317
+
318
+ function isoOf(epochMs) {
319
+ const value = typeof epochMs === 'number' && Number.isFinite(epochMs) ? epochMs : Date.now()
320
+ return new Date(value).toISOString()
321
+ }
322
+
323
+ // session 事件:会话身份与血缘(id/cwd/agentPreset/delegationDepth/parentSession/origin)。
324
+ function sessionMetaOf(event, directoryName) {
325
+ const id = stringOrEmpty(event.id) !== '' ? stringOrEmpty(event.id) : directoryName
326
+ const parentSessionId = stringOrEmpty(event.parentSession)
327
+ const delegationDepth = intOrNull(event.delegationDepth)
328
+ return {
329
+ version: Number.isInteger(event.version) ? event.version : null,
330
+ sessionId: id,
331
+ cwd: stringOrEmpty(event.cwd),
332
+ createdAt: typeof event.createdAt === 'number' && Number.isFinite(event.createdAt) ? event.createdAt : null,
333
+ parentSessionId,
334
+ delegationDepth: delegationDepth === null ? 0 : delegationDepth,
335
+ hasExplicitDepth: delegationDepth !== null,
336
+ agentPreset: stringOrEmpty(event.agentPreset),
337
+ origin: stringOrEmpty(event.origin),
338
+ }
339
+ }
340
+
341
+ // assistant/message 事件:四桶 + model/provider;四桶全 0 的事件与账本折叠口径一致地跳过。
342
+ function usageOf(event) {
343
+ const data = event.data
344
+ if (!isPlainObject(data)) return null
345
+ const usage = data.usage
346
+ if (!isPlainObject(usage)) return null
347
+ const tokens = TOKEN_KEYS.map((key) => finiteNumberOrZero(usage[key]))
348
+ let total = 0
349
+ for (const token of tokens) total += token
350
+ if (total === 0) return null
351
+ const message = data.message
352
+ const source = isPlainObject(message) ? message.source : undefined
353
+ return {
354
+ tokens,
355
+ model: isPlainObject(source) ? stringOrEmpty(source.model) : '',
356
+ provider: isPlainObject(source) ? stringOrEmpty(source.provider) : '',
357
+ seq: intOrNull(event.seq),
358
+ ts: isoOf(event.time),
359
+ }
360
+ }
361
+
362
+ // agent-preset/selected 事件:会话中途切换预设时以最后一次为准(多种载荷形状都认,取不到就忽略)。
363
+ function presetOfSelectedEvent(event) {
364
+ const candidates = [event.agentPreset, event.preset]
365
+ if (isPlainObject(event.data)) candidates.push(event.data.agentPreset, event.data.preset, event.data.id)
366
+ for (const candidate of candidates) {
367
+ if (typeof candidate === 'string' && candidate !== '') return candidate
368
+ }
369
+ return ''
370
+ }
371
+
372
+ // request/header 事件:parentSession/delegationDepth 的兜底来源(session 事件缺失这两项时才用)。
373
+ function lineageOfRequestHeader(event) {
374
+ const data = event.data
375
+ const header = isPlainObject(data) ? data.header : undefined
376
+ if (!isPlainObject(header)) return null
377
+ const parentSessionId = stringOrEmpty(header.parentSession)
378
+ const delegationDepth = intOrNull(header.delegationDepth)
379
+ if (parentSessionId === '' && delegationDepth === null) return null
380
+ return { parentSessionId, delegationDepth }
381
+ }
382
+
383
+ // 单文件扫描:只保留会话元信息与用量事件,其余事件一律丢弃。
384
+ function scanLogText(lines, directoryName, shouldCancel) {
385
+ const state = {
386
+ meta: null,
387
+ selectedPreset: '',
388
+ requestHeader: null,
389
+ usageEvents: [],
390
+ parseErrors: 0,
391
+ }
392
+ for (const line of lines) {
393
+ checkArchiveCancellation({ shouldCancel })
394
+ if (line.trim() === '') continue
395
+ const maybeSession = line.includes(EVENT_MARKERS.session)
396
+ const maybeUsage = line.includes(EVENT_MARKERS.usage)
397
+ const maybePreset = line.includes(EVENT_MARKERS.presetSelected)
398
+ const maybeHeader = line.includes(EVENT_MARKERS.requestHeader)
399
+ if (!maybeSession && !maybeUsage && !maybePreset && !maybeHeader) continue
400
+ let event
401
+ try {
402
+ event = JSON.parse(line)
403
+ } catch (error) {
404
+ state.parseErrors += 1
405
+ continue
406
+ }
407
+ if (!isPlainObject(event)) continue
408
+ if (event.type === 'session') {
409
+ if (state.meta === null) state.meta = sessionMetaOf(event, directoryName)
410
+ continue
411
+ }
412
+ if (event.type === 'assistant/message') {
413
+ const usage = usageOf(event)
414
+ if (usage !== null) state.usageEvents.push(usage)
415
+ continue
416
+ }
417
+ if (event.type === 'agent-preset/selected') {
418
+ const preset = presetOfSelectedEvent(event)
419
+ if (preset !== '') state.selectedPreset = preset
420
+ continue
421
+ }
422
+ if (event.type === 'request/header') {
423
+ const lineage = lineageOfRequestHeader(event)
424
+ if (lineage !== null) state.requestHeader = lineage
425
+ }
426
+ }
427
+ checkArchiveCancellation({ shouldCancel })
428
+ return state
429
+ }
430
+
431
+ // ── ⑤⑥ 白名单过滤与身份聚合 ─────────────────────────────────────────────────
432
+ function hasOwn(object, key) {
433
+ return Object.prototype.hasOwnProperty.call(object, key)
434
+ }
435
+
436
+ function identityValueOf(value, key) {
437
+ if (key === 'delegationDepth') return Number.isInteger(value) && value >= 0 ? value : ''
438
+ if (key === 'schemaVersion') return value
439
+ return typeof value === 'string' ? value : ''
440
+ }
441
+
442
+ function identityKeyOf(identity) {
443
+ const parts = []
444
+ for (const key of IDENTITY_KEYS) parts.push(identityValueOf(identity[key], key))
445
+ return JSON.stringify(parts)
446
+ }
447
+
448
+ // 血缘根:与 agent-runtime.usageRootOf 同口径(depth 1 直接取 parent;更深的沿 parent 链上溯,
449
+ // 链路缺失/成环一律返回空串)。
450
+ function rootSessionOf(sessionId, parentSessionId, delegationDepth, parentById) {
451
+ if (parentSessionId === '') return ''
452
+ if (delegationDepth === 1) return parentSessionId
453
+ const seen = new Set([sessionId])
454
+ let currentId = parentSessionId
455
+ for (let level = 0; level < MAX_PARENT_DEPTH; level += 1) {
456
+ if (currentId === '' || seen.has(currentId)) return ''
457
+ seen.add(currentId)
458
+ const parent = parentById.get(currentId)
459
+ if (parent === undefined) return ''
460
+ const nextId = parent.parentSessionId
461
+ if (nextId === '') return currentId
462
+ if (seen.has(nextId)) return ''
463
+ currentId = nextId
464
+ }
465
+ return ''
466
+ }
467
+
468
+ function isChildSession(meta) {
469
+ return meta.delegationDepth > 0 || meta.parentSessionId !== '' || meta.origin === 'subagent'
470
+ }
471
+
472
+ // 角色口径与 agent-runtime.usageContextOf 一致:主会话 main;子会话按预设映射到四角色,其余 child。
473
+ function roleOf(meta, child) {
474
+ if (!child) return 'main'
475
+ return hasOwn(USAGE_ROLE_BY_PRESET, meta.agentPreset) ? USAGE_ROLE_BY_PRESET[meta.agentPreset] : 'child'
476
+ }
477
+
478
+ function emptyGroup(identity) {
479
+ return {
480
+ schemaVersion: 2,
481
+ rootSessionId: identity.rootSessionId,
482
+ sessionId: identity.sessionId,
483
+ parentSessionId: identity.parentSessionId,
484
+ agentPreset: identity.agentPreset,
485
+ delegationDepth: identity.delegationDepth,
486
+ role: identity.role,
487
+ model: identity.model,
488
+ provider: identity.provider,
489
+ inputTokens: 0,
490
+ cacheReadTokens: 0,
491
+ cacheWriteTokens: 0,
492
+ outputTokens: 0,
493
+ calls: 0,
494
+ seq: null,
495
+ ts: '',
496
+ }
497
+ }
498
+
499
+ function compareValues(left, right) {
500
+ const a = String(left === undefined || left === null ? '' : left)
501
+ const b = String(right === undefined || right === null ? '' : right)
502
+ return a < b ? -1 : a > b ? 1 : 0
503
+ }
504
+
505
+ function rowSort(a, b) {
506
+ for (const key of IDENTITY_KEYS) {
507
+ const compared = compareValues(a[key], b[key])
508
+ if (compared !== 0) return compared
509
+ }
510
+ return compareValues(a.seq === null ? '' : a.seq, b.seq === null ? '' : b.seq)
511
+ }
512
+
513
+ function addUsageToGroups(groups, meta, usage) {
514
+ const identity = {
515
+ schemaVersion: 2,
516
+ rootSessionId: meta.rootSessionId,
517
+ sessionId: meta.sessionId,
518
+ parentSessionId: meta.parentSessionId,
519
+ agentPreset: meta.agentPreset,
520
+ delegationDepth: meta.delegationDepth,
521
+ role: meta.role,
522
+ model: usage.model,
523
+ provider: usage.provider,
524
+ }
525
+ const groupKey = identityKeyOf(identity)
526
+ let group = groups.get(groupKey)
527
+ if (group === undefined) group = emptyGroup(identity)
528
+ for (let index = 0; index < TOKEN_KEYS.length; index += 1) group[TOKEN_KEYS[index]] += usage.tokens[index]
529
+ group.calls += 1
530
+ if (usage.seq !== null && (group.seq === null || usage.seq >= group.seq)) {
531
+ group.seq = usage.seq
532
+ }
533
+ groups.set(groupKey, group)
534
+ }
535
+
536
+ function allowedOf(allowedPresets) {
537
+ if (allowedPresets === undefined || allowedPresets === null) return ALLOWED_PRESETS
538
+ if (allowedPresets instanceof Set) return [...allowedPresets]
539
+ return Array.isArray(allowedPresets) ? allowedPresets : ALLOWED_PRESETS
540
+ }
541
+
542
+ function scanUsageRowsOf(logFiles, options = {}) {
543
+ const settings = isPlainObject(options) ? options : {}
544
+ const shouldCancel = typeof settings.shouldCancel === 'function' ? settings.shouldCancel : undefined
545
+ checkArchiveCancellation({ shouldCancel })
546
+ const whitelist = new Set(allowedOf(settings.allowedPresets))
547
+ const trackOutcome = settings.trackOutcome === true
548
+ const scanOutcome = trackOutcome ? { failed: false, failedFiles: [], successfulFiles: [] } : null
549
+ const markFailed = (logFile, reason) => {
550
+ if (scanOutcome === null) return
551
+ scanOutcome.failed = true
552
+ scanOutcome.failedFiles.push({ logPath: logFile.logPath, reason })
553
+ }
554
+ const fingerprintStable = (logFile) => {
555
+ if (scanOutcome === null) return true
556
+ if (!Number.isFinite(logFile.size) || !Number.isFinite(logFile.mtimeMs)) {
557
+ markFailed(logFile, 'missing-fingerprint')
558
+ return false
559
+ }
560
+ try {
561
+ const stat = statSync(sessionReadPath(settings.pathContext, logFile.logPath, 'file'))
562
+ if (!stat.isFile() || stat.size !== logFile.size || stat.mtimeMs !== logFile.mtimeMs) {
563
+ markFailed(logFile, 'fingerprint-changed-during-read')
564
+ return false
565
+ }
566
+ } catch (error) {
567
+ markFailed(logFile, 'stat-failed-after-read')
568
+ return false
569
+ }
570
+ return true
571
+ }
572
+ const stats = { files: 0, sessions: 0, rows: 0, skipped: 0, enumerationSkipped: 0, whitelistSkipped: 0, decodeFailed: 0, unsupported: 0, parseErrors: 0 }
573
+ const scanned = []
574
+ const parentById = new Map(Array.isArray(settings.parentSessions) ? settings.parentSessions.map((item) => [item.sessionId, item]) : [])
575
+ for (const logFile of logFiles) {
576
+ checkArchiveCancellation({ shouldCancel })
577
+ stats.files += 1
578
+ let state
579
+ try { state = scanLogText(decodedLinesOf(readFileSync(sessionReadPath(settings.pathContext, logFile.logPath, 'file')), shouldCancel), logFile.sessionDirectory, shouldCancel) } catch (error) {
580
+ if (errorCodeOf(error) === 'archive-cancelled') throw error
581
+ stats.decodeFailed += 1
582
+ markFailed(logFile, 'decode-failed')
583
+ continue
584
+ }
585
+ checkArchiveCancellation({ shouldCancel })
586
+ stats.parseErrors += state.parseErrors
587
+ if (trackOutcome && state.parseErrors > 0) { markFailed(logFile, 'event-parse-errors'); continue }
588
+ const meta = state.meta
589
+ if (meta === null || (meta.version !== null && meta.version !== SUPPORTED_SESSION_VERSION)) {
590
+ stats.unsupported += 1
591
+ markFailed(logFile, meta === null ? 'missing-session-metadata' : 'unsupported-session-version')
592
+ continue
593
+ }
594
+ if (!fingerprintStable(logFile)) continue
595
+ stats.sessions += 1
596
+ const agentPreset = state.selectedPreset !== '' ? state.selectedPreset : meta.agentPreset
597
+ const lineage = state.requestHeader
598
+ const parentSessionId = meta.parentSessionId !== '' ? meta.parentSessionId : lineage === null ? '' : lineage.parentSessionId
599
+ const delegationDepth = meta.hasExplicitDepth ? meta.delegationDepth : lineage !== null && lineage.delegationDepth !== null ? lineage.delegationDepth : 0
600
+ const resolved = { ...meta, delegationDepth, parentSessionId, agentPreset }
601
+ parentById.set(resolved.sessionId, resolved)
602
+ scanned.push({ meta: resolved, usageEvents: state.usageEvents, mtimeMs: logFile.mtimeMs })
603
+ if (scanOutcome !== null) scanOutcome.successfulFiles.push(logFile.logPath)
604
+ }
605
+ const groups = new Map()
606
+ for (const session of scanned) {
607
+ checkArchiveCancellation({ shouldCancel })
608
+ const meta = session.meta
609
+ if (!whitelist.has(meta.agentPreset)) { stats.skipped += 1; stats.whitelistSkipped += 1; continue }
610
+ if (session.usageEvents.length === 0) continue
611
+ const child = isChildSession(meta)
612
+ const identityMeta = { ...meta, role: roleOf(meta, child), rootSessionId: child ? rootSessionOf(meta.sessionId, meta.parentSessionId, meta.delegationDepth, parentById) : meta.sessionId }
613
+ for (const usage of session.usageEvents) {
614
+ checkArchiveCancellation({ shouldCancel })
615
+ addUsageToGroups(groups, identityMeta, usage)
616
+ }
617
+ for (const group of groups.values()) if (group.sessionId === meta.sessionId && group.ts !== isoOf(session.mtimeMs)) group.ts = isoOf(session.mtimeMs)
618
+ }
619
+ const rows = [...groups.values()].map((group) => {
620
+ const copy = { ...group }
621
+ if (copy.seq === null) copy.seq = 0
622
+ return copy
623
+ }).sort(rowSort)
624
+ stats.rows = rows.length
625
+ const result = { rows, stats }
626
+ if (scanOutcome !== null) result.scanOutcome = scanOutcome
627
+ checkArchiveCancellation({ shouldCancel })
628
+ return result
629
+ }
630
+
631
+ // 全量公开扫描保持稳定签名,供 step-99 确定性对拍使用。
632
+ export function scanUsageRows(options = {}) {
633
+ const settings = isPlainObject(options) ? options : {}
634
+ const hostRoot = settings.hostRoot
635
+ const pathContext = typeof hostRoot === 'string' && hostRoot.trim() !== '' ? createPathContext({ hostDataRoot: hostRoot }) : undefined
636
+ const enumeration = enumerateSessionLogs({ hostRoot, pathContext, shouldCancel: settings.shouldCancel })
637
+ const result = scanUsageRowsOf(enumeration.logFiles, { ...settings, pathContext })
638
+ result.stats.skipped += enumeration.skippedEntries
639
+ result.stats.enumerationSkipped += enumeration.skippedEntries
640
+ return result
641
+ }
642
+
643
+ function firstFrameSessionOf(bytes, directoryName) {
644
+ const empty = { sessionId: directoryName, preset: '', parentSessionId: '', delegationDepth: 0 }
645
+ try {
646
+ let start = 0
647
+ if (bytes.length < 4) return empty
648
+ const magic = bytes.readUInt32LE(0)
649
+ if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) {
650
+ if (bytes.length < 8) return empty
651
+ start = 8 + bytes.readUInt32LE(4)
652
+ }
653
+ if (start + 4 > bytes.length || bytes.readUInt32LE(start) !== ZSTD_MAGIC) return empty
654
+ const end = frameEndAt(bytes, start)
655
+ if (end === null) return empty
656
+ const lines = zstdDecompressSync(bytes.subarray(start, end)).toString('utf8').split(/\r?\n/)
657
+ let sessionId = directoryName
658
+ let preset = ''
659
+ let parentSessionId = ''
660
+ let delegationDepth = 0
661
+ let hasExplicitDepth = false
662
+ let requestHeader = null
663
+ for (const line of lines) {
664
+ if (!line.includes(EVENT_MARKERS.session) && !line.includes(EVENT_MARKERS.presetSelected) && !line.includes(EVENT_MARKERS.requestHeader)) continue
665
+ try {
666
+ const event = JSON.parse(line)
667
+ if (event.type === 'session') {
668
+ sessionId = stringOrEmpty(event.id) || directoryName
669
+ preset = stringOrEmpty(event.agentPreset)
670
+ parentSessionId = stringOrEmpty(event.parentSession)
671
+ hasExplicitDepth = intOrNull(event.delegationDepth) !== null
672
+ delegationDepth = hasExplicitDepth ? intOrNull(event.delegationDepth) : 0
673
+ } else if (event.type === 'agent-preset/selected') {
674
+ const selected = presetOfSelectedEvent(event)
675
+ if (selected !== '') preset = selected
676
+ } else if (event.type === 'request/header') requestHeader = lineageOfRequestHeader(event)
677
+ } catch (error) { /* malformed first-frame event is ignored */ }
678
+ }
679
+ if (parentSessionId === '' && requestHeader !== null) parentSessionId = requestHeader.parentSessionId
680
+ if (!hasExplicitDepth && requestHeader !== null && requestHeader.delegationDepth !== null) delegationDepth = requestHeader.delegationDepth
681
+ return { sessionId, preset, parentSessionId, delegationDepth }
682
+ } catch (error) { return empty }
683
+ }
684
+
685
+ // 首帧窗口递进读取(M3):只为判白名单与身份读文件头部,512 → 8192 → 65536 → 整份逐级扩窗;
686
+ // 结构非法按空身份降级(preset 为空即非白名单,最终跳过),不抛错、不记为失败。
687
+ const FIRST_FRAME_WINDOW_SIZES = [512, 8192, 65536]
688
+
689
+ function emptyIdentityOf(directoryName) {
690
+ return { sessionId: directoryName, preset: '', parentSessionId: '', delegationDepth: 0 }
691
+ }
692
+
693
+ // 单窗口内的首帧边界:short=窗口不足需扩窗,invalid=结构非法直接降级,frame=窗口已含完整首帧。
694
+ function firstFrameRangeWithin(bytes, fileSize) {
695
+ if (bytes.length < 4) return { state: bytes.length < fileSize ? 'short' : 'invalid' }
696
+ let start = 0
697
+ const magic = bytes.readUInt32LE(0)
698
+ if (magic >= SKIPPABLE_MAGIC_MIN && magic <= SKIPPABLE_MAGIC_MAX) {
699
+ if (bytes.length < 8) return { state: bytes.length < fileSize ? 'short' : 'invalid' }
700
+ start = 8 + bytes.readUInt32LE(4)
701
+ }
702
+ if (start + 4 > bytes.length) return { state: start + 4 > fileSize ? 'invalid' : 'short' }
703
+ if (bytes.readUInt32LE(start) !== ZSTD_MAGIC) return { state: 'invalid' }
704
+ if (frameEndAt(bytes, start) === null) return { state: bytes.length < fileSize ? 'short' : 'invalid' }
705
+ return { state: 'frame' }
706
+ }
707
+
708
+ function readWindowOf(fd, length) {
709
+ const buffer = Buffer.allocUnsafe(length)
710
+ const read = readSync(fd, buffer, 0, length, 0)
711
+ return buffer.subarray(0, read)
712
+ }
713
+
714
+ function firstFrameSessionByPath(pathContext, logPath, directoryName, size) {
715
+ const fileSize = Number.isFinite(size) && size >= 0 ? Math.floor(size) : null
716
+ let fd = null
717
+ try {
718
+ const readPath = sessionReadPath(pathContext, logPath, 'file')
719
+ if (fileSize === null) return firstFrameSessionOf(readFileSync(readPath), directoryName)
720
+ fd = openSync(readPath, 'r')
721
+ for (const windowSize of FIRST_FRAME_WINDOW_SIZES) {
722
+ if (windowSize >= fileSize) break
723
+ const bytes = readWindowOf(fd, windowSize)
724
+ const range = firstFrameRangeWithin(bytes, fileSize)
725
+ if (range.state === 'frame') return firstFrameSessionOf(bytes, directoryName)
726
+ if (range.state === 'invalid') return emptyIdentityOf(directoryName)
727
+ }
728
+ const bytes = readWindowOf(fd, fileSize)
729
+ if (firstFrameRangeWithin(bytes, fileSize).state !== 'frame') return emptyIdentityOf(directoryName)
730
+ return firstFrameSessionOf(bytes, directoryName)
731
+ } catch (error) {
732
+ if (sessionPathMissing(error)) return null
733
+ throw archiveError('scan-failed', '读取会话日志首帧失败:' + errorMessageOf(error))
734
+ } finally {
735
+ if (fd !== null) { try { closeSync(fd) } catch (error) { /* fd 已关闭或不可关闭时保持降级 */ } }
736
+ }
737
+ }
738
+
739
+ // 只对 changed 文件读首帧窗口(M3):未变化文件零字节读取;size/mtimeMs 复用枚举结果,不再对同一 logPath 二次 statSync。
740
+ function scanSessionPresets({ logFiles, shouldCancel, identityOf }) {
741
+ checkArchiveCancellation({ shouldCancel })
742
+ const changedFiles = []
743
+ const stats = { sessions: 0, skipped: 0 }
744
+ for (const file of logFiles) {
745
+ checkArchiveCancellation({ shouldCancel })
746
+ const identity = identityOf(file)
747
+ checkArchiveCancellation({ shouldCancel })
748
+ if (identity === null) { stats.skipped += 1; continue }
749
+ changedFiles.push({ ...file, sessionId: identity.sessionId, preset: identity.preset, parentSessionId: identity.parentSessionId, delegationDepth: identity.delegationDepth })
750
+ }
751
+ checkArchiveCancellation({ shouldCancel })
752
+ return { logFiles: changedFiles, stats }
753
+ }
754
+
755
+ // ── ③a 归档读侧:严格解析、身份、分组、单调性覆盖(由旧归档模块迁入)──────
756
+ function mergedFsOps(fsOps) {
757
+ return { ...DEFAULT_FS_OPS, ...(isPlainObject(fsOps) ? fsOps : {}) }
758
+ }
759
+
760
+ function nowOf(clock) {
761
+ if (typeof clock === 'function') {
762
+ const value = Number(clock())
763
+ return Number.isFinite(value) ? value : Date.now()
764
+ }
765
+ if (clock !== null && typeof clock === 'object' && typeof clock.now === 'function') {
766
+ const value = Number(clock.now())
767
+ return Number.isFinite(value) ? value : Date.now()
768
+ }
769
+ return Date.now()
770
+ }
771
+
772
+ function hostRootOf(pathContext) {
773
+ if (!isPlainObject(pathContext)) return ''
774
+ const root = pathContext.hostDataRoot
775
+ if (typeof root !== 'string' || root.trim() === '') return ''
776
+ if (!isPlainObject(pathContext.hostCapabilities)) return ''
777
+ return root
778
+ }
779
+ function tokenNumber(row, key) {
780
+ return typeof row[key] === 'number' && Number.isFinite(row[key]) ? row[key] : 0
781
+ }
782
+
783
+ function identityValue(row, key) {
784
+ if (key === 'delegationDepth') return Number.isInteger(row[key]) && row[key] >= 0 ? row[key] : ''
785
+ if (key === 'schemaVersion') return row[key]
786
+ return typeof row[key] === 'string' ? row[key] : ''
787
+ }
788
+
789
+ function groupSort(a, b) {
790
+ for (const key of IDENTITY_KEYS) {
791
+ const compared = compareValues(a[key], b[key])
792
+ if (compared !== 0) return compared
793
+ }
794
+ return compareValues(a.maxSeq === null ? '' : a.maxSeq, b.maxSeq === null ? '' : b.maxSeq)
795
+ }
796
+
797
+ function validDedupeKey(row) {
798
+ return isPlainObject(row)
799
+ && typeof row.sessionId === 'string'
800
+ && row.sessionId.trim() !== ''
801
+ && Number.isInteger(row.seq)
802
+ && row.seq >= 0
803
+ }
804
+ // 生产严格解析与 step-99 诊断共用单行判据;空字符串表示通过。
805
+ export function validationIssue(row) {
806
+ if (!isPlainObject(row)) return '根值不是对象'
807
+ const actual = Object.keys(row).sort()
808
+ const expected = [...V2_KEYS].sort()
809
+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) return '必须严格包含固定' + V2_KEYS.length + '个键'
810
+ if (row.schemaVersion !== 2) return 'schemaVersion必须为2'
811
+ if (typeof row.ts !== 'string' || row.ts.trim() === '' || !Number.isFinite(Date.parse(row.ts))) return 'ts必须是有效时间字符串'
812
+ for (const key of ['sessionId', 'role']) {
813
+ if (typeof row[key] !== 'string' || row[key].trim() === '') return key + '必须是非空字符串'
814
+ }
815
+ for (const key of ['rootSessionId', 'agentPreset', 'parentSessionId', 'model', 'provider']) {
816
+ if (typeof row[key] !== 'string') return key + '必须是字符串'
817
+ }
818
+ if (!Number.isInteger(row.delegationDepth) || row.delegationDepth < 0) return 'delegationDepth必须是非负整数'
819
+ for (const key of TOKEN_KEYS) {
820
+ if (typeof row[key] !== 'number' || !Number.isFinite(row[key]) || row[key] < 0) return key + '必须是非负有限数'
821
+ }
822
+ if (!Number.isInteger(row.seq) || row.seq < 0) return 'seq必须是非负整数'
823
+ return ''
824
+ }
825
+
826
+ // strict 解析:坏行/非 V2/字段非法均视为失败,调用方据此放弃本次归档(账本原样不动)。
827
+ function parseStrictLedgerText(text, source, check) {
828
+ const rows = []
829
+ let lineNumber = 0
830
+ let schemaDocCount = 0
831
+ for (const line of String(text === undefined || text === null ? '' : text).split(/\r?\n/)) {
832
+ if (line.trim() === '') continue
833
+ if (typeof check === 'function') check()
834
+ lineNumber += 1
835
+ let row
836
+ try {
837
+ row = JSON.parse(line)
838
+ } catch (error) {
839
+ throw archiveError('bad-json', source + ' 第' + lineNumber + '行坏JSON;发布前未改写')
840
+ }
841
+ if (typeof check === 'function') check()
842
+ // 说明行只允许唯一一条且必须在首行:重复或错位一律判失败,避免说明行混进数据行改变统计口径。
843
+ if (isSchemaDocRow(row)) {
844
+ schemaDocCount += 1
845
+ if (schemaDocCount > 1 || rows.length !== 0) {
846
+ throw archiveError('schema-doc-misplaced', source + ' 第' + lineNumber + '行说明行位置非法(说明行只能唯一一条出现在首行);发布前未改写')
847
+ }
848
+ if (typeof check === 'function') check()
849
+ continue
850
+ }
851
+ if (!isPlainObject(row) || row.schemaVersion !== 2) {
852
+ const kind = isPlainObject(row) ? 'V1/非V2对象' : 'V1/非V2值'
853
+ throw archiveError('non-v2', source + ' 第' + lineNumber + '行' + kind + ';发布前未改写')
854
+ }
855
+ const issue = validationIssue(row)
856
+ if (issue !== '') throw archiveError('invalid-v2', source + ' 第' + lineNumber + '行非法V2:' + issue + ';发布前未改写')
857
+ rows.push(row)
858
+ if (typeof check === 'function') check()
859
+ }
860
+ return rows
861
+ }
862
+
863
+ function identityOf(row) {
864
+ const identity = {}
865
+ for (const key of IDENTITY_KEYS) identity[key] = identityValue(row, key)
866
+ return identity
867
+ }
868
+
869
+ function identityKeyOfRow(row) {
870
+ const identity = identityOf(row)
871
+ return JSON.stringify(IDENTITY_KEYS.map((key) => identity[key]))
872
+ }
873
+
874
+ function emptyGroupOf(row) {
875
+ const identity = identityOf(row)
876
+ return {
877
+ ...identity,
878
+ inputTokens: 0,
879
+ cacheReadTokens: 0,
880
+ cacheWriteTokens: 0,
881
+ outputTokens: 0,
882
+ maxSeq: null,
883
+ latestTs: '',
884
+ }
885
+ }
886
+
887
+ function groupFromArchiveRow(row) {
888
+ const group = emptyGroupOf(row)
889
+ for (const key of TOKEN_KEYS) group[key] = tokenNumber(row, key)
890
+ const seq = validDedupeKey(row) ? row.seq : null
891
+ if (seq !== null) {
892
+ group.maxSeq = seq
893
+ group.latestTs = typeof row.ts === 'string' ? row.ts : ''
894
+ }
895
+ return group
896
+ }
897
+
898
+ // 扫描行还原分组:四桶与 calls 取扫描值,maxSeq/latestTs 取扫描水位与最新事件时间。
899
+ function groupFromScanRow(row) {
900
+ const group = emptyGroupOf(row)
901
+ for (const key of TOKEN_KEYS) group[key] = tokenNumber(row, key)
902
+ const seq = Number.isInteger(row.seq) && row.seq >= 0 ? row.seq : null
903
+ if (seq !== null) {
904
+ group.maxSeq = seq
905
+ group.latestTs = typeof row.ts === 'string' && row.ts !== '' ? row.ts : ''
906
+ }
907
+ group.calls = Number.isInteger(row.calls) && row.calls >= 0 ? row.calls : null
908
+ return group
909
+ }
910
+
911
+ function tokenTotalOf(group) {
912
+ let total = 0
913
+ for (const key of TOKEN_KEYS) total += tokenNumber(group, key)
914
+ return total
915
+ }
916
+
917
+ // 覆盖式更新:现有 archive 行作基线,扫描行整体覆盖(四桶、calls、ts、seq 全用本次扫描值)。
918
+ // 单调性保护:本次扫描的 calls 或四桶合计小于基线时保留旧值并登记一条告警,绝不回退已记账消耗;
919
+ // 扫描里已不存在的身份(日志被删/迁移)原样保留,不删除 archive 行。
920
+ function mergedArchiveGroups(archiveRows, scanRows, options = {}) {
921
+ const refreshRegressedTimestamp = isPlainObject(options) && options.refreshRegressedTimestamp === true
922
+ const shouldCancel = isPlainObject(options) && typeof options.shouldCancel === 'function' ? options.shouldCancel : undefined
923
+ checkArchiveCancellation({ shouldCancel })
924
+ const groups = new Map()
925
+ for (const row of Array.isArray(archiveRows) ? archiveRows : []) {
926
+ checkArchiveCancellation({ shouldCancel })
927
+ groups.set(identityKeyOfRow(row), groupFromArchiveRow(row))
928
+ }
929
+ const monotonicWarnings = []
930
+ for (const scanRow of Array.isArray(scanRows) ? scanRows : []) {
931
+ checkArchiveCancellation({ shouldCancel })
932
+ const groupKey = identityKeyOfRow(scanRow)
933
+ const current = groups.get(groupKey)
934
+ if (current === undefined) {
935
+ groups.set(groupKey, groupFromScanRow(scanRow))
936
+ continue
937
+ }
938
+ // archive 行按归档契约只落 15 键,没有 calls;可在重复同身份扫描行时从扫描基线读到 calls,
939
+ // 此时 calls 单调性检查可生效。
940
+ const scanCalls = Number.isInteger(scanRow.calls) && scanRow.calls >= 0 ? scanRow.calls : null
941
+ const currentCalls = Number.isInteger(current.calls) && current.calls >= 0 ? current.calls : null
942
+ const regressed = tokenTotalOf(scanRow) < tokenTotalOf(current)
943
+ || (scanCalls !== null && currentCalls !== null && scanCalls < currentCalls)
944
+ if (regressed) {
945
+ monotonicWarnings.push({
946
+ sessionId: typeof scanRow.sessionId === 'string' ? scanRow.sessionId : '',
947
+ agentPreset: typeof scanRow.agentPreset === 'string' ? scanRow.agentPreset : '',
948
+ role: typeof scanRow.role === 'string' ? scanRow.role : '',
949
+ model: typeof scanRow.model === 'string' ? scanRow.model : '',
950
+ })
951
+ if (refreshRegressedTimestamp && typeof scanRow.ts === 'string' && scanRow.ts !== '') current.latestTs = scanRow.ts
952
+ } else {
953
+ for (const tokenKey of TOKEN_KEYS) current[tokenKey] = tokenNumber(scanRow, tokenKey)
954
+ current.calls = scanCalls
955
+ if (Number.isInteger(scanRow.seq) && scanRow.seq >= 0) {
956
+ current.maxSeq = scanRow.seq
957
+ }
958
+ current.latestTs = typeof scanRow.ts === 'string' && scanRow.ts !== '' ? scanRow.ts : current.latestTs
959
+ }
960
+ }
961
+ checkArchiveCancellation({ shouldCancel })
962
+ return { groups, monotonicWarnings }
963
+ }
964
+
965
+ function finalizedGroups(groups) {
966
+ return [...groups.values()].sort(groupSort)
967
+ }
968
+
969
+ function assertUniqueArchiveRows(rows, source, check) {
970
+ const seen = new Set()
971
+ for (const row of Array.isArray(rows) ? rows : []) {
972
+ if (check !== undefined) check()
973
+ const key = identityKeyOfRow(row)
974
+ if (seen.has(key)) throw archiveError('duplicate-archive', source + ' 同一完整身份出现多个累计行;发布前未改写')
975
+ seen.add(key)
976
+ }
977
+ }
978
+
979
+ function archiveRowOf(group) {
980
+ return {
981
+ schemaVersion: 2,
982
+ ts: group.latestTs,
983
+ sessionId: group.sessionId,
984
+ parentSessionId: group.parentSessionId,
985
+ rootSessionId: group.rootSessionId,
986
+ agentPreset: group.agentPreset,
987
+ delegationDepth: group.delegationDepth,
988
+ role: group.role,
989
+ model: group.model,
990
+ provider: group.provider,
991
+ inputTokens: group.inputTokens,
992
+ cacheReadTokens: group.cacheReadTokens,
993
+ cacheWriteTokens: group.cacheWriteTokens,
994
+ outputTokens: group.outputTokens,
995
+ seq: group.maxSeq,
996
+ }
997
+ }
998
+
999
+ function archiveTextOf(groups, check) {
1000
+ if (!Array.isArray(groups) || groups.length === 0) return ''
1001
+ const lines = [SCHEMA_DOC_LINE]
1002
+ for (const group of groups) {
1003
+ if (typeof check === 'function') check()
1004
+ lines.push(JSON.stringify(archiveRowOf(group)))
1005
+ if (typeof check === 'function') check()
1006
+ }
1007
+ return lines.join('\n') + '\n'
1008
+ }
1009
+
1010
+ function ensureLedgerDirectory(pathContext, purpose, fsOps) {
1011
+ const target = resolveHostPath(pathContext, LEDGER_DIRECTORY, { purpose })
1012
+ prepareWriteTarget(pathContext, target, { expectedType: 'any', purpose })
1013
+ // 目录创建优先走调用方注入的 fsOps(与同文件其它写操作同口径),未注入或缺失时回落模块级 mkdirSync。
1014
+ const makeDirectory = isPlainObject(fsOps) && typeof fsOps.mkdirSync === 'function' ? fsOps.mkdirSync : mkdirSync
1015
+ makeDirectory(target.path, { recursive: true })
1016
+ validateReadTarget(pathContext, target, { expectedType: 'directory', purpose })
1017
+ }
1018
+
1019
+ function authorizeWriteTarget(pathContext, target, purpose) {
1020
+ return prepareWriteTarget(pathContext, resolveHostPath(pathContext, target, { purpose }), { expectedType: 'file', purpose })
1021
+ }
1022
+
1023
+ function authorizeReadIfPresent(pathContext, target, purpose) {
1024
+ try {
1025
+ validateReadTarget(pathContext, resolveHostPath(pathContext, target, { purpose }), { expectedType: 'file', purpose })
1026
+ } catch (error) {
1027
+ if (errorCodeOf(error) !== 'TARGET_MISSING') throw error
1028
+ }
1029
+ }
1030
+
1031
+ function optionalRead(fsOps, filePath) {
1032
+ try {
1033
+ const bytes = bytesOf(fsOps.readFileSync(filePath))
1034
+ return { exists: true, bytes }
1035
+ } catch (error) {
1036
+ if (errorCodeOf(error) === 'ENOENT') return { exists: false, bytes: Buffer.alloc(0) }
1037
+ throw archiveError(errorCodeOf(error) || 'read-failed', '读取账本失败 ' + filePath + ': ' + errorMessageOf(error))
1038
+ }
1039
+ }
1040
+
1041
+ function recordDiagnostic(pathContext, fsOps, reason, message, purpose) {
1042
+ try {
1043
+ const directoryTarget = resolveHostPath(pathContext, LEDGER_DIRECTORY, { purpose })
1044
+ prepareWriteTarget(pathContext, directoryTarget, { expectedType: 'any', purpose })
1045
+ fsOps.mkdirSync(directoryTarget.path, { recursive: true })
1046
+ const logTarget = resolveHostPath(pathContext, join(LEDGER_DIRECTORY, DIAGNOSTIC_FILE_NAME), { purpose })
1047
+ prepareWriteTarget(pathContext, logTarget, { expectedType: 'file', purpose })
1048
+ const line = JSON.stringify({ ts: new Date().toISOString(), reason: String(reason), message: String(message) }) + '\n'
1049
+ fsOps.appendFileSync(logTarget.path, line, 'utf8')
1050
+ } catch (error) {
1051
+ // 诊断写失败仅忽略:启动归档绝不因留痕失败而阻断启动。
1052
+ }
1053
+ }
1054
+
1055
+ function reportFailure(pathContext, fsOps, error, purpose) {
1056
+ const reason = errorCodeOf(error) !== '' ? errorCodeOf(error) : 'archive-failed'
1057
+ const message = errorMessageOf(error)
1058
+ try {
1059
+ console.warn('[dsh-extra-plan] startup archive failed: ' + reason + ': ' + message)
1060
+ } catch (warnError) {
1061
+ // warning 通道不可用时忽略。
1062
+ }
1063
+ recordDiagnostic(pathContext, fsOps, reason, message, purpose)
1064
+ return { status: 'failed', reason, error }
1065
+ }
1066
+ // ── ③ 写入:原子发布、简易互斥、聚合与发布 ──────────────────────────────────
1067
+ // 单目标原子发布:写临时文件 → rename 覆盖 archive。rename 是同目录原子替换,读者要么看到完整旧版本
1068
+ // 要么看到完整新版本;失败只可能发生在 rename 之前,既有 archive 原样保留(不再备份/回滚)。
1069
+ function publishArchive({ archivePath, archiveText, fsOps, checkBudget, pathContext, purpose }) {
1070
+ const destination = authorizeWriteTarget(pathContext, archivePath, purpose).path
1071
+ const id = process.pid + '-' + Date.now() + '-' + randomUUID()
1072
+ const temp = authorizeWriteTarget(pathContext, join(dirname(destination), basename(destination) + '.tmp-' + id), purpose).path
1073
+ let written = false
1074
+ try {
1075
+ fsOps.writeFileSync(temp, archiveText, { encoding: 'utf8', flag: 'wx' })
1076
+ written = true
1077
+ checkBudget()
1078
+ fsOps.renameSync(temp, destination)
1079
+ // rename 已是 try 的最后一步:其后无可失败步骤,catch 只可能在 rename 之前触发,既有 archive 必未被改写。
1080
+ } catch (error) {
1081
+ if (written || errorCodeOf(error) !== 'EEXIST') {
1082
+ try { fsOps.unlinkSync(temp) } catch { /* 临时文件不存在或不可清理时保留现场 */ }
1083
+ }
1084
+ throw archiveError(errorCodeOf(error) || 'publish-failed', errorMessageOf(error) + ';发布前未改写既有 archive')
1085
+ }
1086
+ }
1087
+
1088
+ // 简易互斥(改造11):一次 O_EXCL 创建 <archive>.lock。Windows 下 'wx' 即 O_CREAT|O_EXCL|O_WRONLY,
1089
+ // 创建成功即独占;拿不到即视为另一实例正在写账本——本次启动扫描跳过并留痕,不等待、不接管死锁、不删他人锁。
1090
+ // 锁只挂在启动路径(startupArchive)上:直调入口 archiveLedger 只做给定路径的聚合与发布,不再承担进程互斥。
1091
+ function acquireArchiveLock(archivePath) {
1092
+ const lockPath = archivePath + '.lock'
1093
+ let fd
1094
+ try {
1095
+ fd = openSync(lockPath, 'wx')
1096
+ } catch (error) {
1097
+ if (errorCodeOf(error) !== 'EEXIST') return { acquired: false, lockPath, error }
1098
+ return { acquired: false, lockPath }
1099
+ }
1100
+ try {
1101
+ writeSync(fd, JSON.stringify({ pid: process.pid, token: randomUUID(), createdAt: new Date().toISOString() }))
1102
+ } catch (error) {
1103
+ // owner 元信息只是现场线索:写不进去也不影响互斥语义,锁已独占创建。
1104
+ } finally {
1105
+ try { closeSync(fd) } catch (error) { /* 关闭失败同样不影响互斥语义 */ }
1106
+ }
1107
+ return { acquired: true, lockPath }
1108
+ }
1109
+
1110
+ // 释放只用同一路径 unlink(try/finally 内调用):锁是本次 O_EXCL 独占创建的,失败只留现场,绝不抛给启动路径。
1111
+ function releaseArchiveLock(fsOps, lock) {
1112
+ try { fsOps.unlinkSync(lock.lockPath) } catch (error) { /* 释放失败不影响本次归档结果 */ }
1113
+ }
1114
+
1115
+ // 同步直调入口 archiveLedger:给定 archive 路径执行当前聚合与发布,与 startupArchive 共用本实现。
1116
+ // 语义:严格读现有 archive(可不存在)→ 取本次身份行(options.rows 注入优先,否则现场扫描 host 根下的会话日志)
1117
+ // → 按身份覆盖式更新 + 单调性保护 → 写说明行 → temp→rename 原子发布。
1118
+ // 不含 active 参数、不清空 active、无双文件合并、无逆序回滚、无 parse-active 阶段;预算阶段只有
1119
+ // start/parse-archive/unique/merge/serialize/publish。失败一律抛出带 code 的 Error;
1120
+ // 成功返回 { status, archivePath, rows, groups, scannedRows, scannedFiles, scannedSessions, monotonicWarnings, archiveBytes }。
1121
+ export function archiveLedger(archivePath, options = {}) {
1122
+ const settings = isPlainObject(options) ? options : {}
1123
+ if (typeof archivePath !== 'string' || archivePath === '') {
1124
+ throw archiveError('invalid-archive-path', '归档目标是空路径')
1125
+ }
1126
+ const fsOps = mergedFsOps(settings.fsOps)
1127
+ const purpose = typeof settings.purpose === 'string' && settings.purpose !== '' ? settings.purpose : LEDGER_PURPOSE
1128
+ const pathContext = settings.pathContext !== undefined && settings.pathContext !== null ? settings.pathContext : {}
1129
+ // 直调和启动归档共用授权目标的绝对路径;下游不得回到调用方的相对输入。
1130
+ try {
1131
+ archivePath = authorizeWriteTarget(pathContext, archivePath, purpose).path
1132
+ ensureLedgerDirectory(pathContext, purpose, fsOps)
1133
+ authorizeReadIfPresent(pathContext, archivePath, purpose)
1134
+ } catch (error) {
1135
+ throw archiveError(errorCodeOf(error) || 'path-not-authorized', '启动归档目标未获 H/W 双根授权:' + errorMessageOf(error))
1136
+ }
1137
+ const budgetMs = Number.isFinite(settings.budgetMs) && settings.budgetMs >= 0 ? settings.budgetMs : STARTUP_ARCHIVE_BUDGET_MS
1138
+ const startedAt = nowOf(settings.clock)
1139
+ const deadline = startedAt + budgetMs
1140
+ const onCheck = typeof settings.onCheck === 'function' ? settings.onCheck : undefined
1141
+ let currentPhase = 'start'
1142
+ const checkBudget = () => {
1143
+ checkArchiveCancellation(settings)
1144
+ if (onCheck !== undefined && onCheck(currentPhase) === true) {
1145
+ throw archiveError('budget-timeout', '启动归档预算超时(阶段' + currentPhase + ',约' + budgetMs + 'ms),发布前未改写')
1146
+ }
1147
+ if (nowOf(settings.clock) >= deadline) {
1148
+ throw archiveError('budget-timeout', '启动归档预算超时(约' + budgetMs + 'ms),发布前未改写')
1149
+ }
1150
+ }
1151
+ currentPhase = 'start'
1152
+ checkBudget()
1153
+ const archiveRead = optionalRead(fsOps, archivePath)
1154
+ currentPhase = 'parse-archive'
1155
+ checkBudget()
1156
+ const archiveRows = parseStrictLedgerText(textOfBytes(archiveRead.bytes), archivePath, checkBudget)
1157
+ currentPhase = 'unique'
1158
+ checkBudget()
1159
+ assertUniqueArchiveRows(archiveRows, archivePath, checkBudget)
1160
+ currentPhase = 'merge'
1161
+ let scanRows
1162
+ if (Array.isArray(settings.rows)) {
1163
+ scanRows = settings.rows
1164
+ } else {
1165
+ const hostRoot = hostRootOf(pathContext)
1166
+ if (hostRoot === '') throw archiveError('no-host-root', '归档缺少明确 host 根,无法扫描会话日志')
1167
+ scanRows = scanUsageRows({ hostRoot, shouldCancel: settings.shouldCancel }).rows
1168
+ }
1169
+ const merged = mergedArchiveGroups(archiveRows, scanRows, { refreshRegressedTimestamp: settings.scanSource === 'startup-file', shouldCancel: settings.shouldCancel })
1170
+ currentPhase = 'serialize'
1171
+ checkBudget()
1172
+ const archiveText = archiveTextOf(finalizedGroups(merged.groups), checkBudget)
1173
+ currentPhase = 'publish'
1174
+ checkBudget()
1175
+ publishArchive({ archivePath, archiveText, fsOps, checkBudget, pathContext, purpose })
1176
+ if (merged.monotonicWarnings.length > 0) {
1177
+ try {
1178
+ const labels = merged.monotonicWarnings.map((item) => item.sessionId + '/' + (item.agentPreset !== '' ? item.agentPreset : '-') + '/' + (item.role !== '' ? item.role : '-') + '/' + (item.model !== '' ? item.model : '-'))
1179
+ console.warn('[dsh-extra-plan] usage archive monotonic guard: ' + merged.monotonicWarnings.length + ' 个身份本次扫描小于 archive 现有值,保留旧值不覆盖:' + labels.join(', '))
1180
+ } catch (warnError) {
1181
+ // warning 通道不可用时忽略。
1182
+ }
1183
+ }
1184
+ const scanStats = isPlainObject(settings.scanStats) ? settings.scanStats : null
1185
+ return {
1186
+ status: 'archived',
1187
+ archivePath,
1188
+ rows: merged.groups.size,
1189
+ // groups 是 rows 的兼容别名:同值同源,保留只为不牵动既有 step-00:1518 的双断言;新消费者请只用 rows。
1190
+ groups: merged.groups.size,
1191
+ scannedRows: scanRows.length,
1192
+ scannedFiles: scanStats !== null && Number.isInteger(scanStats.files) ? scanStats.files : null,
1193
+ scannedSessions: scanStats !== null && Number.isInteger(scanStats.sessions) ? scanStats.sessions : null,
1194
+ scannedUsageSessions: scanStats !== null && Number.isInteger(scanStats.usageSessions) ? scanStats.usageSessions : scanStats !== null && Number.isInteger(scanStats.sessions) ? scanStats.sessions : null,
1195
+ monotonicWarnings: merged.monotonicWarnings.length,
1196
+ archiveBytes: Buffer.byteLength(archiveText, 'utf8'),
1197
+ }
1198
+ }
1199
+
1200
+ // 跳过也要留痕:扫描失败/无归档范围等需要诊断的状态写入 logs/dsh-extra-plan/extra-plan-usage-errors.jsonl;协作取消不记失败。
1201
+ function skipWithDiagnostic(pathContext, fsOps, reason, message, purpose) {
1202
+ try {
1203
+ console.warn('[dsh-extra-plan] startup archive skipped: ' + reason + ': ' + message)
1204
+ } catch (warnError) {
1205
+ // warning 通道不可用时忽略。
1206
+ }
1207
+ recordDiagnostic(pathContext, fsOps, reason, message, purpose)
1208
+ return { status: 'skipped', reason }
1209
+ }
1210
+
1211
+ // ── ④ 启动入口 ───────────────────────────────────────────────────────────────
1212
+ // startupArchive 保持同步 API;后台调用方由 Worker 调度,模式层白名单过滤后按日志 mtime 增量判定。
1213
+ // ts 使用会话日志文件时间点;聚合、单调性、说明行与账本原子发布仍由 archiveLedger 统一完成。
1214
+ function upToDateArchiveResult({ archivePath, archiveRead, archiveRows, mode, reason }) {
1215
+ return {
1216
+ status: 'up-to-date',
1217
+ reason,
1218
+ archivePath,
1219
+ rows: archiveRows.length,
1220
+ groups: archiveRows.length,
1221
+ scannedRows: 0,
1222
+ scannedFiles: 0,
1223
+ scannedSessions: mode.stats.sessions,
1224
+ scannedUsageSessions: 0,
1225
+ monotonicWarnings: 0,
1226
+ archiveBytes: archiveRead.bytes.length,
1227
+ }
1228
+ }
1229
+
1230
+ function startupArchiveUnsafe(pathContext, options) {
1231
+ const fsOps = mergedFsOps(options.fsOps)
1232
+ const shouldCancel = typeof options.shouldCancel === 'function' ? options.shouldCancel : undefined
1233
+ checkArchiveCancellation({ shouldCancel })
1234
+ const purpose = LEDGER_PURPOSE
1235
+ const hostRoot = hostRootOf(pathContext)
1236
+ if (hostRoot === '') {
1237
+ try { console.warn('[dsh-extra-plan] startup archive skipped: no-host-root') } catch (warnError) { /* warning channel unavailable */ }
1238
+ return { status: 'skipped', reason: 'no-host-root' }
1239
+ }
1240
+ const requestedArchivePath = typeof options.archivePath === 'string' && options.archivePath !== ''
1241
+ ? options.archivePath
1242
+ : resolveHostPath(pathContext, join(LEDGER_DIRECTORY, ARCHIVE_FILE_NAME), { purpose }).path
1243
+ let archivePath
1244
+ try {
1245
+ ensureLedgerDirectory(pathContext, purpose, fsOps)
1246
+ archivePath = authorizeWriteTarget(pathContext, requestedArchivePath, purpose).path
1247
+ authorizeReadIfPresent(pathContext, archivePath, purpose)
1248
+ } catch (error) {
1249
+ return reportFailure(pathContext, fsOps, archiveError(errorCodeOf(error) || 'path-not-authorized', '启动归档目标未获 H/W 双根授权:' + errorMessageOf(error)), purpose)
1250
+ }
1251
+ // 第一步:只枚举会话日志(自带 size 与 mtimeMs),不读任何日志内容。
1252
+ let enumeration
1253
+ try { enumeration = enumerateSessionLogs({ hostRoot, shouldCancel, pathContext, fsOps }) }
1254
+ catch (error) {
1255
+ if (errorCodeOf(error) === 'archive-cancelled') throw error
1256
+ return skipWithDiagnostic(pathContext, fsOps, 'scan-failed', '扫描会话日志失败:' + errorMessageOf(error), purpose)
1257
+ }
1258
+ // 第二步:读旧账本并构建 sessionId → ts 索引。
1259
+ const archiveRead = optionalRead(fsOps, archivePath)
1260
+ let archiveRows = []
1261
+ let archiveValid = true
1262
+ if (archiveRead.exists) {
1263
+ try {
1264
+ checkArchiveCancellation({ shouldCancel })
1265
+ archiveRows = parseStrictLedgerText(textOfBytes(archiveRead.bytes), archivePath)
1266
+ checkArchiveCancellation({ shouldCancel })
1267
+ assertUniqueArchiveRows(archiveRows, archivePath)
1268
+ } catch (error) {
1269
+ if (errorCodeOf(error) === 'archive-cancelled') throw error
1270
+ archiveValid = false
1271
+ }
1272
+ }
1273
+ const rowsBySession = new Map()
1274
+ for (const row of archiveRows) {
1275
+ checkArchiveCancellation({ shouldCancel })
1276
+ const group = rowsBySession.get(row.sessionId) || []
1277
+ group.push(Date.parse(row.ts))
1278
+ rowsBySession.set(row.sessionId, group)
1279
+ }
1280
+ // 第三步:changed 判定——用会话目录名查账本,ts 与文件 mtime 相等即未变化、一字节不读;
1281
+ // 目录名在账本里查不到时才读该文件首帧窗口取 identity.sessionId 再查一次。
1282
+ const identities = new Map()
1283
+ const identityOf = (file) => {
1284
+ if (identities.has(file.logPath)) return identities.get(file.logPath)
1285
+ const identity = firstFrameSessionByPath(pathContext, file.logPath, file.sessionDirectory, file.size)
1286
+ identities.set(file.logPath, identity)
1287
+ return identity
1288
+ }
1289
+ const ledgerHasTimestamp = (sessionId, fileMtimeMs) => {
1290
+ const timestamps = rowsBySession.get(sessionId)
1291
+ return timestamps !== undefined && timestamps.some((timestamp) => timestamp === fileMtimeMs)
1292
+ }
1293
+ const changed = []
1294
+ for (const file of enumeration.logFiles) {
1295
+ checkArchiveCancellation({ shouldCancel })
1296
+ if (!archiveRead.exists || !archiveValid) { changed.push(file); continue }
1297
+ const fileMtimeMs = new Date(file.mtimeMs).getTime()
1298
+ if (ledgerHasTimestamp(file.sessionDirectory, fileMtimeMs)) continue
1299
+ if (!rowsBySession.has(file.sessionDirectory)) {
1300
+ const identity = identityOf(file)
1301
+ if (identity === null || ledgerHasTimestamp(identity.sessionId, fileMtimeMs)) continue
1302
+ }
1303
+ changed.push(file)
1304
+ }
1305
+ // 第四步:只对 changed 文件读首帧窗口取 preset/父会话/深度,构造与既有同形的 logFiles;allowed 仍按 ALLOWED_PRESETS 过滤。
1306
+ let mode
1307
+ try { mode = scanSessionPresets({ logFiles: changed, shouldCancel, identityOf }) }
1308
+ catch (error) {
1309
+ if (errorCodeOf(error) === 'archive-cancelled') throw error
1310
+ return skipWithDiagnostic(pathContext, fsOps, 'scan-failed', '扫描会话日志失败:' + errorMessageOf(error), purpose)
1311
+ }
1312
+ mode.stats.sessions = enumeration.logFiles.length
1313
+ mode.stats.skipped += enumeration.skippedEntries
1314
+ const whitelist = new Set(ALLOWED_PRESETS)
1315
+ const allowed = mode.logFiles.filter((file) => whitelist.has(file.preset))
1316
+ const noChangedLogs = archiveRead.exists && archiveValid && allowed.length === 0
1317
+ checkArchiveCancellation({ shouldCancel })
1318
+ if (noChangedLogs) {
1319
+ return upToDateArchiveResult({ archivePath, archiveRead, archiveRows, mode, reason: 'no-changed-logs' })
1320
+ }
1321
+ // parentSessions:账本行与 changed 首帧的并集;深度≥2 且父会话缺失时惰性读该父目录日志首帧补齐,
1322
+ // 仍缺失则由既有断链规则把 rootSessionId 归空(rootSessionOf 对未知父返回空串)。
1323
+ const parentSessions = new Map()
1324
+ for (const row of archiveRows) {
1325
+ checkArchiveCancellation({ shouldCancel })
1326
+ if (!parentSessions.has(row.sessionId)) parentSessions.set(row.sessionId, { sessionId: row.sessionId, parentSessionId: row.parentSessionId, delegationDepth: row.delegationDepth })
1327
+ }
1328
+ for (const file of mode.logFiles) {
1329
+ checkArchiveCancellation({ shouldCancel })
1330
+ parentSessions.set(file.sessionId, { sessionId: file.sessionId, parentSessionId: file.parentSessionId, delegationDepth: file.delegationDepth })
1331
+ }
1332
+ const logFileByDirectory = new Map(enumeration.logFiles.map((file) => [file.sessionDirectory, file]))
1333
+ for (const file of mode.logFiles) {
1334
+ if (file.delegationDepth < 2 || file.parentSessionId === '') continue
1335
+ if (parentSessions.has(file.parentSessionId)) continue
1336
+ const parentFile = logFileByDirectory.get(file.parentSessionId)
1337
+ if (parentFile === undefined) continue
1338
+ checkArchiveCancellation({ shouldCancel })
1339
+ const identity = identityOf(parentFile)
1340
+ if (identity !== null && !parentSessions.has(identity.sessionId)) parentSessions.set(identity.sessionId, { sessionId: identity.sessionId, parentSessionId: identity.parentSessionId, delegationDepth: identity.delegationDepth })
1341
+ }
1342
+ checkArchiveCancellation({ shouldCancel })
1343
+ const scan = scanUsageRowsOf(allowed, { parentSessions: [...parentSessions.values()], trackOutcome: true, shouldCancel, pathContext })
1344
+ if (scan.scanOutcome !== undefined && scan.scanOutcome.failed === true) {
1345
+ const failedFiles = scan.scanOutcome.failedFiles.length
1346
+ return skipWithDiagnostic(pathContext, fsOps, 'scan-failed', '本轮扫描有' + failedFiles + '个日志未完整解码或指纹不稳定,保留既有archive并等待重试', purpose)
1347
+ }
1348
+ const usageSessions = scan.stats.sessions
1349
+ scan.stats.usageSessions = usageSessions
1350
+ scan.stats.sessions = mode.stats.sessions
1351
+ scan.stats.skipped += mode.stats.skipped
1352
+ scan.stats.enumerationSkipped += mode.stats.skipped
1353
+ scan.stats.files = allowed.length
1354
+ // Keep all enumerated sessions in parent resolution, while decoding only changed whitelisted logs.
1355
+ checkArchiveCancellation({ shouldCancel })
1356
+ const lock = acquireArchiveLock(archivePath)
1357
+ if (lock.acquired !== true) {
1358
+ if (lock.error !== undefined) return reportFailure(pathContext, fsOps, archiveError(errorCodeOf(lock.error) || 'lock-failed', '账本锁创建失败:' + errorMessageOf(lock.error)), purpose)
1359
+ return skipWithDiagnostic(pathContext, fsOps, 'lock-busy', '另一实例正在写账本,本次启动归档跳过', purpose)
1360
+ }
1361
+ let result
1362
+ let failure
1363
+ try {
1364
+ result = archiveLedger(archivePath, { ...options, fsOps, pathContext, purpose, scanSource: 'startup-file', rows: scan.rows, scanStats: scan.stats })
1365
+ } catch (error) { failure = error }
1366
+ finally { releaseArchiveLock(fsOps, lock) }
1367
+ if (failure !== undefined) {
1368
+ if (errorCodeOf(failure) === 'archive-cancelled') throw failure
1369
+ return reportFailure(pathContext, fsOps, failure, purpose)
1370
+ }
1371
+ return result
1372
+ }
1373
+
1374
+ // 启动归档唯一入口:同步API由settings Worker调用,返回带 status 的结构化结果供调用方留痕;
1375
+ // 任何异常都在内部消化,绝不向调用方抛出。
1376
+ export function startupArchive(pathContext, options = {}) {
1377
+ const settings = isPlainObject(options) ? options : {}
1378
+ try {
1379
+ return startupArchiveUnsafe(pathContext, settings)
1380
+ } catch (error) {
1381
+ const reason = errorCodeOf(error) || 'archive-failed'
1382
+ if (reason === 'archive-cancelled') return { status: 'cancelled', reason: 'cancel-requested' }
1383
+ const message = errorMessageOf(error)
1384
+ if (reason === 'scan-failed') return skipWithDiagnostic(pathContext, mergedFsOps(settings.fsOps), reason, message, LEDGER_PURPOSE)
1385
+ try {
1386
+ console.warn('[dsh-extra-plan] startup archive failed: ' + reason + ': ' + message)
1387
+ } catch (warnError) {
1388
+ // warning 通道不可用时忽略。
1389
+ }
1390
+ recordDiagnostic(pathContext, mergedFsOps(settings.fsOps), reason, message, LEDGER_PURPOSE)
1391
+ return { status: 'failed', reason, error }
1392
+ }
1393
+ }