dsh-progress-union 0.5.13 → 0.6.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -21,6 +21,11 @@ import os from 'node:os'
21
21
  import path from 'node:path'
22
22
  import z from '@deepseek-ai/schemastery'
23
23
  import { ANCHOR_VERSION, ANCHOR_ROUTES, BOARD_STATUSES } from './anchor.js'
24
+ import {
25
+ ARCHIVE_VERSION, ARCHIVE_ROUTES, ARCHIVE_KEEP_VERSIONS, ARCHIVE_KEEP_DAYS, ARCHIVE_MAX_BYTES,
26
+ archiveDir, archiveRoot, writeArchiveVersion, readIndex, readArchiveVersion, verifyChecksum,
27
+ pickRestoreTarget, truncateArchive, pruneArchives,
28
+ } from './archive.js'
24
29
 
25
30
  // 设置页可见性:0.1.7+ 宿主把 composition entry 当设置节,直接按导出的 Config
26
31
  // **逐叶子**的 .volatile() 标记生成「设置 → 插件」里的表单,并把 volatile 字段以
@@ -66,6 +71,13 @@ export const Config = z.object({
66
71
  rescanMs: z.number().step(1000).min(1000).default(5000).volatile(),
67
72
  echoBack: z.boolean().default(true).volatile(),
68
73
  }).default({}),
74
+ // v0.6.0:会话归档(每回合落一版 + handoff + 重启注入一次)。
75
+ archiveEnabled: z.boolean().default(true).volatile(),
76
+ archiveKeepVersions: z.number().step(1).min(2).default(10).volatile(),
77
+ archiveKeepDays: z.number().step(1).min(0).default(7).volatile(),
78
+ archiveHandoffTurns: z.number().step(1).min(0).default(3).volatile(),
79
+ archiveInjectOnResume: z.boolean().default(true).volatile(),
80
+ archiveMaxBytes: z.number().step(1024).min(4096).default(32 * 1024).volatile(),
69
81
  })
70
82
 
71
83
  // —— 路由与存储标识 ——
@@ -221,6 +233,9 @@ function emptyState(sessionId) {
221
233
  todoMirror: null, // v0.3.0:自家镜像写入的 hash/at/count,回环识别用
222
234
  planSlug: '', // v0.5.0:显式绑定的 plan 目录名(空=按 mtime 自动选)
223
235
  goal: emptyGoal(),
236
+ // v0.6.0:会话归档(版号 / 最近一次归档失败原因;只回显,不阻断板)
237
+ archiveSeq: 0,
238
+ archiveError: '',
224
239
  }
225
240
  }
226
241
 
@@ -832,6 +847,15 @@ const DEFAULT_CONFIG = {
832
847
  rescanMs: 5000,
833
848
  echoBack: true,
834
849
  },
850
+ // v0.6.0:会话归档。archiveRoot / archivePruneMs 是测试与运维 seam(不进设置卡)。
851
+ archiveEnabled: true,
852
+ archiveKeepVersions: 10,
853
+ archiveKeepDays: 7,
854
+ archiveHandoffTurns: 3,
855
+ archiveInjectOnResume: true,
856
+ archiveMaxBytes: 32 * 1024,
857
+ archiveRoot: '',
858
+ archivePruneMs: 24 * 60 * 60 * 1000,
835
859
  // 辅助 LLM(审查/监视 + 槽位管理 + 轮次草案):
836
860
  // mode: 'registered' 走宿主 llm.stream(选已注册 llm-pi-ai provider/model);
837
861
  // 'direct' 走自建 OpenAI 兼容端点(baseUrl/apiKey/model);'' 关。
@@ -948,6 +972,16 @@ export async function apply(ctx, config) {
948
972
  return out
949
973
  }
950
974
  Object.defineProperty(cfg, 'plan', { get: planNow, configurable: true, enumerable: true })
975
+ // v0.6.0:归档六键逐叶子解包(设置页改完立即生效);archiveRoot/archivePruneMs 是
976
+ // 测试与运维 seam,只在 config 里读普通值,不进设置卡。
977
+ for (const key of ['archiveEnabled', 'archiveKeepVersions', 'archiveKeepDays', 'archiveHandoffTurns', 'archiveInjectOnResume', 'archiveMaxBytes']) {
978
+ const raw = config && typeof config === 'object' ? config[key] : undefined
979
+ Object.defineProperty(cfg, key, {
980
+ get: () => readVolatile(raw, DEFAULT_CONFIG[key]),
981
+ configurable: true,
982
+ enumerable: true,
983
+ })
984
+ }
951
985
  const now = () => Date.now()
952
986
 
953
987
  // —— 状态容器 ——
@@ -1054,7 +1088,14 @@ export async function apply(ctx, config) {
1054
1088
  }
1055
1089
  for (const item of state.items) {
1056
1090
  if (typeof item.approach !== 'string') item.approach = ''
1091
+ // v0.6.0:归档侧元数据(不影响板公开快照;老数据零迁移)。
1092
+ if (typeof item.unit !== 'string') item.unit = ''
1093
+ if (!Number.isSafeInteger(item.targetTurns) || item.targetTurns < 1) item.targetTurns = 2
1094
+ if (!Number.isFinite(item.closedAt) || item.closedAt < 0) item.closedAt = 0
1095
+ if (!Number.isSafeInteger(item.startedTurn) || item.startedTurn < 0) item.startedTurn = 0
1057
1096
  }
1097
+ if (!Number.isSafeInteger(state.archiveSeq) || state.archiveSeq < 0) state.archiveSeq = 0
1098
+ if (typeof state.archiveError !== 'string') state.archiveError = ''
1058
1099
  if (typeof state.enabled !== 'boolean') state.enabled = false
1059
1100
  if (state.todoMirror !== null && !isObject(state.todoMirror)) state.todoMirror = null
1060
1101
  if (!isObject(state.goal)) state.goal = emptyGoal()
@@ -1297,6 +1338,8 @@ export async function apply(ctx, config) {
1297
1338
  }
1298
1339
  })(),
1299
1340
  serverTime: now(),
1341
+ // v0.6.0:归档回声(seq 用于对账;失败只回显原因,不阻断板)
1342
+ archive: { seq: Math.trunc(Number(state.archiveSeq) || 0), error: String(state.archiveError || '') || null },
1300
1343
  }
1301
1344
  }
1302
1345
 
@@ -1358,6 +1401,11 @@ export async function apply(ctx, config) {
1358
1401
  order: state.items.length,
1359
1402
  updatedAt: at,
1360
1403
  updatedBy: origin,
1404
+ // v0.6.0:归档侧元数据(closedAt 用于 done 倒序;startedTurn 用 turn 数判未闭合单元)
1405
+ closedAt: 0,
1406
+ unit: '',
1407
+ targetTurns: 2,
1408
+ startedTurn: archiveMemoOf(state.sessionId).turn,
1361
1409
  }
1362
1410
  state.items.push(item)
1363
1411
  records.push({
@@ -1400,6 +1448,10 @@ export async function apply(ctx, config) {
1400
1448
  if (normalized === 'done') {
1401
1449
  record('percent', existing.percent, 100)
1402
1450
  existing.percent = 100
1451
+ if (!existing.closedAt) existing.closedAt = at
1452
+ } else {
1453
+ existing.closedAt = 0
1454
+ if (normalized === 'doing') existing.startedTurn = archiveMemoOf(state.sessionId).turn
1403
1455
  }
1404
1456
  }
1405
1457
  }
@@ -1508,6 +1560,8 @@ export async function apply(ctx, config) {
1508
1560
  if (revisionChanged) notifyAnchor(sessionId, working.revision)
1509
1561
  // 唯一写板入口:持久化之后调度 todo 镜像(200ms 去抖,off 时直接返回)。
1510
1562
  if (revisionChanged) scheduleTodoMirror(sessionId)
1563
+ // v0.6.0:同 revision 归并成一版归档(200ms 去抖,同 revision 已归档则跳过)。
1564
+ if (revisionChanged) scheduleArchive(sessionId)
1511
1565
  // v0.5.0:sync 模式下把已完成的项回勾到 tasks.md(默认 read 时内部直接返回 0)。
1512
1566
  if (revisionChanged) {
1513
1567
  try { maybeEchoBack(sessionId) } catch (_err) {}
@@ -2914,11 +2968,34 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2914
2968
  }))
2915
2969
  } catch (_err) {}
2916
2970
 
2971
+ try {
2972
+ disposers.push(ctx.on('session/disposed', (session) => {
2973
+ // v0.6.0:会话销毁兜底——同步写一版 reason:'dispose'(覆盖 DSH 正常退出)。
2974
+ const sid = String((session && session.id) || (session && session.session && session.session.id) || '')
2975
+ if (!sid) return
2976
+ const timer = archiveTimers.get(sid)
2977
+ if (timer) {
2978
+ clearTimeout(timer)
2979
+ archiveTimers.delete(sid)
2980
+ }
2981
+ try { captureArchive(sid, 'dispose') } catch (_err) {}
2982
+ }))
2983
+ } catch (_err) {}
2984
+
2917
2985
  disposers.push(ctx.on('session/event', (session, event) => {
2918
2986
  try {
2919
2987
  if (!event) return
2920
2988
  const sid = session && session.id ? String(session.id) : 'default'
2921
2989
  const type = event.type
2990
+ // v0.6.0:归档原料(事件环 + turn 计数 + 工具路径)+ 回合收尾落一版。
2991
+ // 延后一个 microtask:宿主 commit() 在 try/finally 里 appending=true,
2992
+ // 观察者内做写操作有被拒风险(CCI 0.17 manifest-failed 教训)。
2993
+ recordArchiveEvent(sid, type, event.data)
2994
+ if (type === 'turn/end') {
2995
+ queueMicrotask(() => {
2996
+ try { captureArchive(sid, 'turn') } catch (_err) {}
2997
+ })
2998
+ }
2922
2999
  // plan 扫描的 cwd 来源:会话事件流里的 session 对象(顶层带 cwd)。只记一次。
2923
3000
  if (!cwdBySession.has(sid)) {
2924
3001
  const c = sessionCwd(session)
@@ -3106,16 +3183,407 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3106
3183
  } catch (_err) {}
3107
3184
 
3108
3185
  // 周期兜底:turn 打开但 10 分钟无活动 → 视为卡死结束。
3186
+ // v0.6.0:同一 tick 兼做归档保留策略(默认 24h 一次)。
3187
+ let archivePrunedAt = 0
3109
3188
  const sweepTimer = setInterval(() => {
3110
3189
  try {
3111
3190
  const atMs = now()
3112
3191
  for (const [sid, t] of taskMap) {
3113
3192
  if (t.active && t.open === true && atMs - t.lastActivityAt > IDLE_END_MS) endTask(sid)
3114
3193
  }
3194
+ // v0.6.0:归档保留策略,默认每 24h 扫一遍(archivePruneMs 可调,测试用 0)。
3195
+ const rawInterval = Number(cfg.archivePruneMs)
3196
+ const interval = Number.isFinite(rawInterval) && rawInterval >= 0 ? rawInterval : 24 * 60 * 60 * 1000
3197
+ if (interval === 0 || !archivePrunedAt || atMs - archivePrunedAt >= interval) {
3198
+ archivePrunedAt = atMs
3199
+ pruneAllArchives()
3200
+ }
3115
3201
  } catch (_err) {}
3116
3202
  }, SWEEP_MS)
3117
3203
  if (typeof sweepTimer?.unref === 'function') sweepTimer.unref()
3118
3204
 
3205
+ // ==========================================================================
3206
+ // C2. v0.6.0:会话归档(版本链 + handoff 规则抽取 + 重启注入一次)
3207
+ // 写入面:turn/end(microtask 延后,避开宿主 commit 的 appending 窗口)/
3208
+ // applyChanges 成功后 200ms 去抖 revision / 退出兜底同步 dispose。
3209
+ // R9:任何失败只写 state.archiveError 回显,绝不阻断板写入、绝不抛到宿主。
3210
+ // ==========================================================================
3211
+
3212
+ const archiveTimers = new Map() // sessionId -> revision 去抖 timer
3213
+ const archiveMemoMap = new Map() // sessionId -> { turn, lastSeq, filesTouched, turnSummaries }
3214
+ const archiveEventsMap = new Map() // sessionId -> 最近事件环(handoff 原料)
3215
+ const resumeInjected = new Set() // 本进程已注入过归档的会话(一次性)
3216
+ const archiveHeadCache = new Map() // sessionId -> 归档头视图 | null(锚点面内存头)
3217
+ const ARCHIVE_EVENT_RING = 240
3218
+
3219
+ // 测试进程默认不落盘(避免污染真实 $DSH_HOME);落盘用例显式传 config.archiveRoot。
3220
+ function archiveRootOverride() {
3221
+ const raw = config && typeof config === 'object' ? config.archiveRoot : undefined
3222
+ return typeof raw === 'string' && raw.trim() ? raw.trim() : ''
3223
+ }
3224
+ function archiveHomeDir() {
3225
+ const override = archiveRootOverride()
3226
+ if (override) return override
3227
+ if (process.env.NODE_TEST_CONTEXT) return null
3228
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
3229
+ }
3230
+ function archiveDirOf(sessionId) {
3231
+ const home = archiveHomeDir()
3232
+ return home ? archiveDir(home, String(sessionId || '')) : null
3233
+ }
3234
+
3235
+ function archiveMemoOf(sessionId) {
3236
+ const sid = String(sessionId || '')
3237
+ let m = archiveMemoMap.get(sid)
3238
+ if (!m) {
3239
+ m = { turn: 0, lastSeq: 0, filesTouched: [], turnSummaries: [] }
3240
+ archiveMemoMap.set(sid, m)
3241
+ }
3242
+ return m
3243
+ }
3244
+
3245
+ function eventsOf(sessionId) {
3246
+ const list = archiveEventsMap.get(String(sessionId || ''))
3247
+ return Array.isArray(list) ? list : []
3248
+ }
3249
+
3250
+ function pushArchiveFile(sessionId, value) {
3251
+ const p = String(value || '').trim()
3252
+ if (!p || p.length > 300 || !/[\\/.]/.test(p)) return
3253
+ const m = archiveMemoOf(sessionId)
3254
+ if (m.filesTouched.includes(p)) return
3255
+ m.filesTouched.push(p)
3256
+ if (m.filesTouched.length > 40) m.filesTouched.splice(0, m.filesTouched.length - 40)
3257
+ }
3258
+
3259
+ function collectArchiveFiles(sessionId, payload) {
3260
+ let args = payload && payload.arguments
3261
+ if (typeof args === 'string') {
3262
+ const raw = args
3263
+ try { args = JSON.parse(raw) } catch (_err) { args = null }
3264
+ if (!args) {
3265
+ // shell 命令行:只抽以盘符/斜杠开头的绝对路径,避免误伤 URL 与普通词。
3266
+ const re = /(?:^|[\s"'=])((?:[A-Za-z]:[\\/]|\/|\.{1,2}\/)[^\s"'|;&>)]+)/g
3267
+ let match
3268
+ while ((match = re.exec(raw)) !== null) pushArchiveFile(sessionId, match[1])
3269
+ return
3270
+ }
3271
+ }
3272
+ if (!isObject(args)) return
3273
+ for (const key of ['file_path', 'path', 'filePath', 'notebook_path', 'target', 'output_path']) {
3274
+ if (typeof args[key] === 'string') pushArchiveFile(sessionId, args[key])
3275
+ }
3276
+ for (const key of ['paths', 'files']) {
3277
+ if (Array.isArray(args[key])) for (const item of args[key]) if (typeof item === 'string') pushArchiveFile(sessionId, item)
3278
+ }
3279
+ }
3280
+
3281
+ // 事件环只收 handoff 用得上的类型(tool 调用 / assistant 输出 / turn 边界 / 用户消息),
3282
+ // 其余事件不落环——避免把大 payload(工具结果)常驻内存。
3283
+ function recordArchiveEvent(sessionId, type, data) {
3284
+ const sid = String(sessionId || '')
3285
+ if (!sid) return
3286
+ const t = String(type || '')
3287
+ const m = archiveMemoOf(sid)
3288
+ if (t === 'turn/end') m.turn += 1
3289
+ const interesting = t === 'tool/call' || t === 'tool/ptc-dispatch' || t === 'assistant/message' || t === 'turn/end' || t === 'turn/start' || t === 'user/message'
3290
+ if (!interesting) return
3291
+ let list = archiveEventsMap.get(sid)
3292
+ if (!list) {
3293
+ list = []
3294
+ archiveEventsMap.set(sid, list)
3295
+ }
3296
+ let payload = null
3297
+ if (t === 'assistant/message') {
3298
+ const msg = data && data.message ? data.message : data
3299
+ payload = { text: String(textOf(msg) || '').replace(/\s+/g, ' ').slice(0, 400) }
3300
+ } else if (t === 'tool/call' || t === 'tool/ptc-dispatch') {
3301
+ const d = data || {}
3302
+ let argsText = ''
3303
+ if (typeof d.arguments === 'string') argsText = d.arguments.slice(0, 800)
3304
+ else if (d.arguments && typeof d.arguments === 'object') {
3305
+ try { argsText = JSON.stringify(d.arguments).slice(0, 800) } catch (_err) {}
3306
+ }
3307
+ payload = { name: String(d.name || ''), arguments: argsText, isError: d.isError === true }
3308
+ } else if (t === 'user/message') {
3309
+ payload = { text: String(textOf(data) || '').replace(/\s+/g, ' ').slice(0, 400) }
3310
+ }
3311
+ list.push({ type: t, at: now(), data: payload })
3312
+ if (list.length > ARCHIVE_EVENT_RING) list.splice(0, list.length - ARCHIVE_EVENT_RING)
3313
+ if (t === 'tool/call' || t === 'tool/ptc-dispatch') collectArchiveFiles(sid, payload)
3314
+ if (t === 'assistant/message' && payload && payload.text) {
3315
+ m.turnSummaries.push(payload.text)
3316
+ if (m.turnSummaries.length > 6) m.turnSummaries.shift()
3317
+ }
3318
+ }
3319
+
3320
+ // —— handoff:纯规则抽取(不调模型;零延迟、零失败点)——
3321
+ function recentTurnEvents(sessionId) {
3322
+ const events = eventsOf(sessionId)
3323
+ const turns = Math.max(0, Math.trunc(Number(cfg.archiveHandoffTurns) || 0))
3324
+ if (turns <= 0 || events.length === 0) return []
3325
+ let seen = 0
3326
+ let start = 0
3327
+ for (let i = events.length - 1; i >= 0; i -= 1) {
3328
+ if (events[i].type !== 'turn/end') continue
3329
+ seen += 1
3330
+ if (seen >= turns) {
3331
+ start = i
3332
+ break
3333
+ }
3334
+ }
3335
+ return events.slice(start)
3336
+ }
3337
+
3338
+ function buildHandoff(state, sessionId) {
3339
+ const items = Array.isArray(state.items) ? state.items : []
3340
+ const m = archiveMemoOf(sessionId)
3341
+ const events = recentTurnEvents(sessionId)
3342
+ const titleOf = (item) => String(item.title || '').trim() || '(未命名)'
3343
+ const goalText = text(state.goal && state.goal.objective, 600)
3344
+ const objective = goalText || String(state.taskTitle || '').trim() || (items[0] ? titleOf(items[0]) : '') || '未命名任务'
3345
+ const done = items
3346
+ .filter((item) => item.status === 'done')
3347
+ .sort((a, b) => (Number(b.closedAt) || Number(b.updatedAt) || 0) - (Number(a.closedAt) || Number(a.updatedAt) || 0))
3348
+ const doneSoFar = done.slice(0, 5).map(titleOf)
3349
+ const writeLines = []
3350
+ for (const ev of events) {
3351
+ if (ev.type !== 'tool/call' && ev.type !== 'tool/ptc-dispatch') continue
3352
+ const d = ev.data || {}
3353
+ if (!/^(shell|bash|write|edit|apply_patch|run_code|str_replace_editor|create_file)$/i.test(String(d.name || ''))) continue
3354
+ const brief = briefArgs(d.arguments)
3355
+ if (brief) writeLines.push(String(d.name) + ': ' + brief)
3356
+ }
3357
+ for (const line of writeLines.slice(-3)) if (!doneSoFar.includes(line)) doneSoFar.push(line)
3358
+ const inFlight = items
3359
+ .filter((item) => item.status === 'doing' || item.status === 'blocked')
3360
+ .slice(0, 6)
3361
+ .map((item) => ({ title: titleOf(item), current: String(item.current || ''), next: String(item.next || '') }))
3362
+ const nextItems = items.filter((item) => item.status === 'todo').slice(0, 3).map(titleOf)
3363
+ const filesTouched = m.filesTouched.slice(-12)
3364
+ const openUnits = items
3365
+ .filter((item) => item.status !== 'done')
3366
+ .map((item) => ({
3367
+ id: String(item.id || ''),
3368
+ title: titleOf(item),
3369
+ unit: String(item.unit || ''),
3370
+ overTurns: Math.max(0, (Number(m.turn) || 0) - (Math.trunc(Number(item.startedTurn) || 0))),
3371
+ targetTurns: Math.max(1, Math.trunc(Number(item.targetTurns) || 2)),
3372
+ }))
3373
+ .filter((unit) => unit.overTurns > unit.targetTurns)
3374
+ .map((unit) => ({ id: unit.id, title: unit.title, unit: unit.unit, overTurns: unit.overTurns }))
3375
+ .slice(0, 5)
3376
+ let lastText = ''
3377
+ for (let i = events.length - 1; i >= 0; i -= 1) {
3378
+ if (events[i].type !== 'assistant/message') continue
3379
+ const t = events[i].data && events[i].data.text
3380
+ if (t) { lastText = String(t); break }
3381
+ }
3382
+ const lastTurn = {
3383
+ turn: Number(m.turn) || 0,
3384
+ startSeq: 0,
3385
+ endSeq: 0,
3386
+ summary: lastText ? lastText.slice(0, 200) : (m.turnSummaries.length ? String(m.turnSummaries[m.turnSummaries.length - 1]).slice(0, 200) : ''),
3387
+ }
3388
+ const boardOnly = events.length === 0
3389
+ return {
3390
+ objective,
3391
+ doneSoFar,
3392
+ inFlight,
3393
+ nextItems,
3394
+ filesTouched,
3395
+ openUnits,
3396
+ lastTurn,
3397
+ generatedBy: boardOnly ? 'rules-board-only' : 'rules',
3398
+ }
3399
+ }
3400
+
3401
+ function buildArchiveEntry(sessionId, state, reason) {
3402
+ const items = state.items.slice().sort((a, b) => a.order - b.order)
3403
+ const handoff = buildHandoff(state, sessionId)
3404
+ const goal = isObject(state.goal) ? state.goal : {}
3405
+ const entry = {
3406
+ version: ARCHIVE_VERSION,
3407
+ sessionId: String(sessionId),
3408
+ seq: 0, // 由 writeArchiveVersion 分配(索引 head + 1,撞号顺延)
3409
+ revision: Math.trunc(Number(state.revision) || 0),
3410
+ at: now(),
3411
+ reason: String(reason || 'turn'),
3412
+ task: {
3413
+ title: String(handoff.objective || '未命名任务').slice(0, 120),
3414
+ goal: {
3415
+ objective: String(goal.objective || ''),
3416
+ phase: GOAL_PHASES.has(goal.phase) ? goal.phase : 'idle',
3417
+ roundsStarted: Math.trunc(Number(goal.roundsStarted) || 0),
3418
+ },
3419
+ },
3420
+ board: {
3421
+ enabled: state.enabled === true,
3422
+ summary: summarize(items),
3423
+ items: items.map((item) => ({
3424
+ id: String(item.id || ''),
3425
+ title: String(item.title || ''),
3426
+ status: String(item.status || 'todo'),
3427
+ percent: Math.trunc(Number(item.percent) || 0),
3428
+ current: String(item.current || ''),
3429
+ next: String(item.next || ''),
3430
+ order: Math.trunc(Number(item.order) || 0),
3431
+ unit: String(item.unit || ''),
3432
+ targetTurns: Math.max(1, Math.trunc(Number(item.targetTurns) || 2)),
3433
+ closedAt: Math.trunc(Number(item.closedAt) || 0),
3434
+ })),
3435
+ },
3436
+ handoff,
3437
+ truncated: false,
3438
+ }
3439
+ const maxBytes = Math.trunc(Number(cfg.archiveMaxBytes) || 0) || ARCHIVE_MAX_BYTES
3440
+ return truncateArchive(entry, maxBytes)
3441
+ }
3442
+
3443
+ /** 归档一版。失败只写 state.archiveError 回显(R9:绝不阻断板、绝不抛到宿主)。 */
3444
+ function captureArchive(sessionId, reason) {
3445
+ if (cfg.archiveEnabled === false) return null
3446
+ const sid = String(sessionId || '')
3447
+ if (!sid) return null
3448
+ try {
3449
+ const state = states.get(sid)
3450
+ if (!state || state.enabled !== true) return null
3451
+ const dir = archiveDirOf(sid)
3452
+ if (!dir) return null
3453
+ const entry = buildArchiveEntry(sid, state, reason)
3454
+ const result = writeArchiveVersion(dir, entry)
3455
+ state.archiveSeq = result.seq
3456
+ state.archiveError = ''
3457
+ archiveMemoOf(sid).lastSeq = result.seq
3458
+ archiveHeadCache.set(sid, { seq: result.seq, revision: entry.revision, at: entry.at, reason: entry.reason, handoff: entry.handoff, degraded: false })
3459
+ return result
3460
+ } catch (error) {
3461
+ try {
3462
+ const state = states.get(sid)
3463
+ if (state) state.archiveError = '归档失败:' + (error instanceof Error ? error.message : String(error))
3464
+ } catch (_err) {}
3465
+ return null
3466
+ }
3467
+ }
3468
+
3469
+ /** revision 去抖(200ms,照 scheduleTodoMirror 形状):同 revision 已归档则跳过。 */
3470
+ function scheduleArchive(sessionId) {
3471
+ if (cfg.archiveEnabled === false) return
3472
+ const sid = String(sessionId || '')
3473
+ const state = states.get(sid)
3474
+ if (!state || state.enabled !== true) return
3475
+ const prev = archiveTimers.get(sid)
3476
+ if (prev) clearTimeout(prev)
3477
+ const timer = setTimeout(() => {
3478
+ archiveTimers.delete(sid)
3479
+ try {
3480
+ const cur = states.get(sid)
3481
+ if (!cur || cur.enabled !== true) return
3482
+ const head = archiveHeadCache.get(sid)
3483
+ if (head && Number(head.revision) === Number(cur.revision)) return
3484
+ captureArchive(sid, 'revision')
3485
+ } catch (_err) {}
3486
+ }, 200)
3487
+ if (typeof timer?.unref === 'function') timer.unref()
3488
+ archiveTimers.set(sid, timer)
3489
+ }
3490
+
3491
+ /** 恢复链:head → head-1 → null;checksum 坏版自动降级,绝不把「读不到」当「从零」。 */
3492
+ function loadLatestArchive(sessionId) {
3493
+ const sid = String(sessionId || '')
3494
+ if (!sid) return { archive: null, degraded: false, reason: 'no-session' }
3495
+ const dir = archiveDirOf(sid)
3496
+ if (!dir) return { archive: null, degraded: false, reason: 'disabled' }
3497
+ const index = readIndex(dir)
3498
+ if (!index) return { archive: null, degraded: false, reason: 'missing' }
3499
+ const present = (seq) => {
3500
+ const entry = readArchiveVersion(dir, seq)
3501
+ return Boolean(entry && verifyChecksum(entry))
3502
+ }
3503
+ const target = pickRestoreTarget(index, present)
3504
+ if (!target) return { archive: null, degraded: true, reason: 'unreadable' }
3505
+ const archive = readArchiveVersion(dir, target)
3506
+ if (!archive) return { archive: null, degraded: true, reason: 'unreadable' }
3507
+ const headSeq = Math.trunc(Number(index.headSeq) || 0)
3508
+ return { archive, degraded: target !== headSeq, reason: target === headSeq ? 'head' : 'fallback', seq: target }
3509
+ }
3510
+
3511
+ function archiveViewOf(sessionId) {
3512
+ const sid = String(sessionId || '')
3513
+ if (!sid) return null
3514
+ if (archiveHeadCache.has(sid)) return archiveHeadCache.get(sid)
3515
+ const loaded = loadLatestArchive(sid)
3516
+ if (!loaded.archive) {
3517
+ archiveHeadCache.set(sid, null)
3518
+ return null
3519
+ }
3520
+ const view = {
3521
+ seq: loaded.archive.seq,
3522
+ revision: loaded.archive.revision,
3523
+ at: loaded.archive.at,
3524
+ reason: loaded.archive.reason,
3525
+ handoff: loaded.archive.handoff,
3526
+ degraded: loaded.degraded === true,
3527
+ }
3528
+ archiveHeadCache.set(sid, view)
3529
+ return view
3530
+ }
3531
+
3532
+ /** <progress_resume> 注入块(模型侧一次性;/progress-resume 命令复用同一渲染)。 */
3533
+ function renderResumeBlock(loaded) {
3534
+ const archive = loaded && loaded.archive
3535
+ if (!archive) return ''
3536
+ const h = isObject(archive.handoff) ? archive.handoff : {}
3537
+ const s = isObject(archive.board && archive.board.summary) ? archive.board.summary : {}
3538
+ const lines = []
3539
+ lines.push('<progress_resume seq="' + String(archive.seq) + '" revision="' + String(archive.revision) + '" reason="' + String(archive.reason || '') + '" at="' + new Date(Number(archive.at) || Date.now()).toISOString() + '">')
3540
+ if (loaded.degraded === true) lines.push('注意:以下来自上一版归档(head 版损坏或缺失),可能落后于最新板;先按当前板对账再动手。')
3541
+ lines.push('任务目标:' + String(h.objective || '(未记录)'))
3542
+ lines.push('板:' + (Number(s.percent) || 0) + '% ' + (Number(s.done) || 0) + '/' + (Number(s.total) || 0) + '(doing ' + (Number(s.doing) || 0) + ',todo ' + (Number(s.todo) || 0) + ',blocked ' + (Number(s.blocked) || 0) + ')')
3543
+ const flight = Array.isArray(h.inFlight) ? h.inFlight : []
3544
+ if (flight.length) {
3545
+ lines.push('正在做:' + flight.slice(0, 3).map((f) => String(f.title || '') + (f.current ? ' — current: ' + String(f.current) : '') + (f.next ? ' / next: ' + String(f.next) : '')).join(';'))
3546
+ }
3547
+ if (Array.isArray(h.nextItems) && h.nextItems.length) lines.push('接下来:' + h.nextItems.slice(0, 3).join(';'))
3548
+ if (Array.isArray(h.doneSoFar) && h.doneSoFar.length) lines.push('已确认/已完成:' + h.doneSoFar.slice(0, 5).join(';'))
3549
+ if (Array.isArray(h.filesTouched) && h.filesTouched.length) lines.push('涉及文件:' + h.filesTouched.slice(0, 8).join('、'))
3550
+ if (Array.isArray(h.openUnits) && h.openUnits.length) lines.push('未闭合单元:' + h.openUnits.slice(0, 5).map((u) => String(u.title || '') + '(' + (Number(u.overTurns) || 0) + ' turn 未闭合)').join(';'))
3551
+ lines.push('恢复说明:以上来自会话归档(非从零重建);需要完整原文时用 /progress-resume <seq>。')
3552
+ lines.push('</progress_resume>')
3553
+ return lines.join('\n')
3554
+ }
3555
+
3556
+ /** 一次性注入:本进程每会话只注入一次(首个模型请求;无归档则静默)。 */
3557
+ function resumeContext(sessionId) {
3558
+ if (cfg.archiveInjectOnResume === false) return ''
3559
+ const sid = String(sessionId || '')
3560
+ if (!sid || resumeInjected.has(sid)) return ''
3561
+ resumeInjected.add(sid)
3562
+ try {
3563
+ return renderResumeBlock(loadLatestArchive(sid))
3564
+ } catch (_err) {
3565
+ return ''
3566
+ }
3567
+ }
3568
+
3569
+ /** 保留策略:扫归档根下每个会话目录(含已闲置会话),head/head-1 永不删。 */
3570
+ function pruneAllArchives() {
3571
+ const home = archiveHomeDir()
3572
+ if (!home) return
3573
+ let names = []
3574
+ try {
3575
+ names = fs.readdirSync(archiveRoot(home), { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name)
3576
+ } catch (_err) {
3577
+ return
3578
+ }
3579
+ const keep = Math.trunc(Number(cfg.archiveKeepVersions) || 0) || ARCHIVE_KEEP_VERSIONS
3580
+ const daysValue = Number(cfg.archiveKeepDays)
3581
+ const days = Number.isFinite(daysValue) ? daysValue : ARCHIVE_KEEP_DAYS
3582
+ for (const name of names) {
3583
+ try { pruneArchives(path.join(archiveRoot(home), name), keep, days, now()) } catch (_err) {}
3584
+ }
3585
+ }
3586
+
3119
3587
  // ==========================================================================
3120
3588
  // D. progressAnchor 只读锚点面(service + HTTP 双平面,同一 builder)
3121
3589
  // 消费契约(保护区必嵌 / userEdits 硬约束 / rev 对账 / staleMin 标注)见 README。
@@ -3189,6 +3657,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3189
3657
  persistent: Boolean(unit) && !storageError.includes('失败'),
3190
3658
  // 预留位:prime-memory 关闭槽位尾迹扇出(定性方案见 docs/,本轮恒 null)。
3191
3659
  slotTrail: null,
3660
+ // v0.6.0:会话归档头(只追加字段;ANCHOR_VERSION 保持 1,老 consumer 忽略即可)。
3661
+ archive: archiveViewOf(sessionId),
3192
3662
  }
3193
3663
  }
3194
3664
 
@@ -3204,6 +3674,14 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3204
3674
  const ids = new Set([...states.keys(), ...taskMap.keys()])
3205
3675
  return [...ids].map((sid) => buildAnchor(sid, finiteNumber(atMs) ?? now()))
3206
3676
  },
3677
+ // v0.6.0:会话归档读面(CCI 等 consumer 拿 handoff 当「工作预期」)。
3678
+ archive(sessionId) {
3679
+ return archiveViewOf(String(sessionId || ''))
3680
+ },
3681
+ handoff(sessionId) {
3682
+ const view = archiveViewOf(String(sessionId || ''))
3683
+ return view ? view.handoff : null
3684
+ },
3207
3685
  subscribe(listener, sessionId) {
3208
3686
  if (typeof listener !== 'function') return () => {}
3209
3687
  if (sessionId === undefined) {
@@ -3365,6 +3843,106 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3365
3843
  }),
3366
3844
  )
3367
3845
 
3846
+ // v0.6.0:会话归档三路由(只读;consumer 按 capability absence 降级读)。
3847
+ routeDisposers.push(
3848
+ webServer.register({
3849
+ kind: 'exact',
3850
+ path: ARCHIVE_ROUTES.latest,
3851
+ handler: (req, res) => {
3852
+ if (req.method !== 'GET') {
3853
+ res.writeHead(405, { allow: 'GET' })
3854
+ res.end()
3855
+ return
3856
+ }
3857
+ const sessionId = readSessionId(req)
3858
+ if (!sessionId) {
3859
+ sendJson(res, 400, { ok: false, error: '缺少有效的 sessionId' })
3860
+ return
3861
+ }
3862
+ try {
3863
+ const loaded = loadLatestArchive(sessionId)
3864
+ if (!loaded.archive) {
3865
+ sendJson(res, 200, { ok: false, degraded: loaded.degraded === true, reason: loaded.reason })
3866
+ return
3867
+ }
3868
+ sendJson(res, 200, { ok: true, degraded: loaded.degraded === true, archive: loaded.archive })
3869
+ } catch (error) {
3870
+ sendJson(res, 200, { ok: false, degraded: true, error: error instanceof Error ? error.message : String(error) })
3871
+ }
3872
+ },
3873
+ }),
3874
+ )
3875
+
3876
+ routeDisposers.push(
3877
+ webServer.register({
3878
+ kind: 'exact',
3879
+ path: ARCHIVE_ROUTES.versions,
3880
+ handler: (req, res) => {
3881
+ if (req.method !== 'GET') {
3882
+ res.writeHead(405, { allow: 'GET' })
3883
+ res.end()
3884
+ return
3885
+ }
3886
+ const sessionId = readSessionId(req)
3887
+ if (!sessionId) {
3888
+ sendJson(res, 400, { ok: false, error: '缺少有效的 sessionId' })
3889
+ return
3890
+ }
3891
+ try {
3892
+ const dir = archiveDirOf(sessionId)
3893
+ const index = dir ? readIndex(dir) : null
3894
+ if (!index) {
3895
+ sendJson(res, 200, { ok: false, degraded: false, reason: 'missing', versions: [] })
3896
+ return
3897
+ }
3898
+ const url = new URL(req.url || '/', 'http://localhost')
3899
+ const limitRaw = Math.trunc(Number(url.searchParams.get('limit')))
3900
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(limitRaw, 100) : 20
3901
+ const versions = index.versions.slice().sort((a, b) => b.seq - a.seq).slice(0, limit)
3902
+ sendJson(res, 200, { ok: true, headSeq: index.headSeq, versions })
3903
+ } catch (error) {
3904
+ sendJson(res, 200, { ok: false, degraded: true, error: error instanceof Error ? error.message : String(error) })
3905
+ }
3906
+ },
3907
+ }),
3908
+ )
3909
+
3910
+ routeDisposers.push(
3911
+ webServer.register({
3912
+ kind: 'exact',
3913
+ path: ARCHIVE_ROUTES.version,
3914
+ handler: (req, res) => {
3915
+ if (req.method !== 'GET') {
3916
+ res.writeHead(405, { allow: 'GET' })
3917
+ res.end()
3918
+ return
3919
+ }
3920
+ const sessionId = readSessionId(req)
3921
+ if (!sessionId) {
3922
+ sendJson(res, 400, { ok: false, error: '缺少有效的 sessionId' })
3923
+ return
3924
+ }
3925
+ const url = new URL(req.url || '/', 'http://localhost')
3926
+ const seqValue = Math.trunc(Number(url.searchParams.get('seq')))
3927
+ if (!Number.isFinite(seqValue) || seqValue < 1) {
3928
+ sendJson(res, 400, { ok: false, error: 'seq 必须是正整数' })
3929
+ return
3930
+ }
3931
+ try {
3932
+ const dir = archiveDirOf(sessionId)
3933
+ const archive = dir ? readArchiveVersion(dir, seqValue) : null
3934
+ if (!archive) {
3935
+ sendJson(res, 200, { ok: false, degraded: false, reason: 'missing' })
3936
+ return
3937
+ }
3938
+ sendJson(res, 200, { ok: true, degraded: !verifyChecksum(archive), archive })
3939
+ } catch (error) {
3940
+ sendJson(res, 200, { ok: false, degraded: true, error: error instanceof Error ? error.message : String(error) })
3941
+ }
3942
+ },
3943
+ }),
3944
+ )
3945
+
3368
3946
  // 鲸程兼容状态面(悬浮条轮询)
3369
3947
  routeDisposers.push(
3370
3948
  webServer.register({
@@ -3669,6 +4247,43 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3669
4247
  )
3670
4248
  }
3671
4249
 
4250
+ if (commands) {
4251
+ ctx.effect(
4252
+ () =>
4253
+ commands.register({
4254
+ name: 'progress-resume',
4255
+ description: '打印本会话最新(或指定 seq)归档的 handoff,纯文本不写板',
4256
+ input: { hint: '[seq]' },
4257
+ handler: ({ agent, rawInput }) => {
4258
+ try {
4259
+ const sid = sessionOfAgent(agent)
4260
+ const dir = archiveDirOf(sid)
4261
+ const raw = String(rawInput || '').trim()
4262
+ if (/^\d+$/.test(raw)) {
4263
+ const seq = Math.trunc(Number(raw))
4264
+ const archive = dir ? readArchiveVersion(dir, seq) : null
4265
+ if (!archive) return { kind: 'error', text: '找不到 seq=' + String(seq) + ' 的归档' }
4266
+ return { kind: 'success', text: renderResumeBlock({ archive, degraded: !verifyChecksum(archive) }) }
4267
+ }
4268
+ const loaded = loadLatestArchive(sid)
4269
+ if (!loaded.archive) {
4270
+ return {
4271
+ kind: 'error',
4272
+ text: loaded.degraded
4273
+ ? '归档不可读(head 与 head-1 都坏了),不敢当作从零开始;用 /progress 开板后跑一回合重建。'
4274
+ : '本会话还没有归档(板启用后跑一回合即生成)。',
4275
+ }
4276
+ }
4277
+ return { kind: 'success', text: renderResumeBlock(loaded) }
4278
+ } catch (err) {
4279
+ return { kind: 'error', text: err instanceof Error ? err.message : String(err) }
4280
+ }
4281
+ },
4282
+ }),
4283
+ 'progress-union: /progress-resume command',
4284
+ )
4285
+ }
4286
+
3672
4287
  // —— 模型侧 progress_goal_report 工具(报告轮次状态;助手草案不自动调这里)——
3673
4288
  ctx.effect(
3674
4289
  () =>
@@ -3777,6 +4392,12 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3777
4392
  order: 61,
3778
4393
  text: () => kickoffContext(sessionId),
3779
4394
  })
4395
+ // v0.6.0:重启恢复块——每进程每会话只注入一次(首个模型请求)。
4396
+ const offResume = agent.ctx.systemPrompt.context({
4397
+ name: 'progress-union-resume',
4398
+ order: 59,
4399
+ text: () => resumeContext(sessionId),
4400
+ })
3780
4401
  // 观察块:清单 + 最近输出/动作 + 滞后催办(每请求重建,不累积)
3781
4402
  const offObserver = agent.ctx.systemPrompt.context({
3782
4403
  name: 'progress-union-observer',
@@ -3787,6 +4408,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3787
4408
  offPolicy()
3788
4409
  offContext()
3789
4410
  offKickoff()
4411
+ offResume()
3790
4412
  offObserver()
3791
4413
  }
3792
4414
  },
@@ -3816,6 +4438,17 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
3816
4438
  }, 'progress-union: agent contexts')
3817
4439
 
3818
4440
  ctx.effect(() => () => {
4441
+ // v0.6.0:插件卸载兜底——所有启板会话同步写一版 reason:'dispose'(不依赖异步 flush)。
4442
+ try {
4443
+ for (const [sid, state] of states) {
4444
+ if (!state || state.enabled !== true) continue
4445
+ const head = archiveHeadCache.get(sid)
4446
+ if (head && Number(head.revision) === Number(state.revision)) continue
4447
+ captureArchive(sid, 'dispose')
4448
+ }
4449
+ } catch (_err) {}
4450
+ for (const timer of archiveTimers.values()) clearTimeout(timer)
4451
+ archiveTimers.clear()
3819
4452
  clearInterval(sweepTimer)
3820
4453
  for (const timer of goalKickTimers.values()) clearTimeout(timer)
3821
4454
  goalKickTimers.clear()