dsh-progress-union 0.5.14 → 0.6.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/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.5.14",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
- "description": "进度结合原型:dsh-progress-board 槽位真相源 × 鲸程 widget 时间/ETA 引擎,另向压缩插件暴露只读三层进度锚点(service + HTTP 双平面)。基于 l3j3y3/dsh-progress-board (MIT) 与 uuhihj/task-progress-bar dsh-progress-widget (MIT)。",
5
+ "description": "进度结合原型:dsh-progress-board 槽位真相源 × 鲸程 widget 时间/ETA 引擎;向压缩插件暴露只读三层进度锚点(service + HTTP 双平面);0.6.0 起每回合落一版会话归档(handoff + 重启注入一次)。基于 l3j3y3/dsh-progress-board (MIT) 与 uuhihj/task-progress-bar dsh-progress-widget (MIT)。",
6
6
  "license": "MIT",
7
7
  "publishConfig": {
8
8
  "registry": "https://registry.npmjs.org",
@@ -17,6 +17,7 @@
17
17
  ".": "./index.js",
18
18
  "./client": "./client.js",
19
19
  "./anchor": "./anchor.js",
20
+ "./archive": "./archive.js",
20
21
  "./cordis.patch.yml": "./cordis.patch.yml",
21
22
  "./package.json": "./package.json"
22
23
  },
@@ -25,6 +26,7 @@
25
26
  "LICENSE",
26
27
  "index.js",
27
28
  "anchor.js",
29
+ "archive.js",
28
30
  "client.js",
29
31
  "cordis.patch.yml",
30
32
  "dsh.plugin.json",
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Phase 2/4 验收:采集钩子(turn / revision 去抖 / dispose 兜底)+ 一次性注入 + 命令 + 失败不阻断。
3
+ */
4
+ import assert from 'node:assert/strict'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import test from 'node:test'
9
+
10
+ import { ARCHIVE_VERSION, archiveDir, archiveVersionPath, writeArchiveVersion, readIndex, readArchiveVersion, isArchive, verifyChecksum } from '../archive.js'
11
+
12
+ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'union-inject-'))
13
+ const { SESSION, createHarness, jsonReq, callRoute, flush } = await import('./harness.mjs')
14
+
15
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
16
+
17
+ async function boot(config = {}) {
18
+ const harness = createHarness({ config: { archiveRoot: TMP, ...config } })
19
+ await harness.run()
20
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
21
+ return harness
22
+ }
23
+
24
+ function execUpdate(harness, args) {
25
+ const tool = harness.toolMap.get('progress_update')
26
+ return tool.definition.execute(args, { agent: harness.agent })
27
+ }
28
+
29
+ function dirOf(root) {
30
+ return archiveDir(root, SESSION)
31
+ }
32
+
33
+ test('turn/end:microtask 后落一版 reason=turn(index + md + checksum 全对)', async () => {
34
+ const root = path.join(TMP, 'turn')
35
+ const harness = await boot({ archiveRoot: root })
36
+ await execUpdate(harness, { changes: [{ title: '步骤一', status: 'doing', current: '做', next: '继续' }, { title: '步骤二' }] })
37
+ harness.emit('turn/end', {})
38
+ await flush()
39
+ const dir = dirOf(root)
40
+ const index = readIndex(dir)
41
+ assert.ok(index, 'index.json 已落地')
42
+ assert.equal(index.headSeq, 1)
43
+ assert.equal(index.sessionId, SESSION)
44
+ const entry = readArchiveVersion(dir, 1)
45
+ assert.equal(isArchive(entry), true)
46
+ assert.equal(verifyChecksum(entry), true)
47
+ assert.equal(entry.reason, 'turn')
48
+ assert.equal(entry.version, ARCHIVE_VERSION)
49
+ assert.equal(entry.board.summary.total, 2)
50
+ assert.equal(entry.board.items.length, 2)
51
+ assert.deepEqual(Object.keys(entry.handoff).sort(), ['doneSoFar', 'filesTouched', 'generatedBy', 'inFlight', 'lastTurn', 'nextItems', 'objective', 'openUnits'])
52
+ assert.equal(entry.handoff.generatedBy, 'rules', '有 turn 事件时走规则抽取')
53
+ assert.ok(fs.existsSync(path.join(dir, 'v000001.md')), '人读版存在')
54
+ // 同 revision 的 revision 去抖版本被跳过:等过 200ms 仍只有 1 版
55
+ await sleep(260)
56
+ assert.equal(readIndex(dir).versions.length, 1)
57
+ })
58
+
59
+ test('revision 去抖:连续 3 次 progress_update 只产出 1 版且 revision 为最后一次', async () => {
60
+ const root = path.join(TMP, 'debounce')
61
+ const harness = await boot({ archiveRoot: root })
62
+ await execUpdate(harness, { changes: [{ title: '甲' }] })
63
+ await execUpdate(harness, { changes: [{ title: '乙' }] })
64
+ await execUpdate(harness, { changes: [{ title: '丙', status: 'doing' }] })
65
+ await sleep(320)
66
+ const dir = dirOf(root)
67
+ const index = readIndex(dir)
68
+ assert.ok(index, '去抖后落盘')
69
+ assert.equal(index.versions.length, 1, '3 次改板合并成 1 版')
70
+ const entry = readArchiveVersion(dir, index.headSeq)
71
+ assert.equal(entry.reason, 'revision')
72
+ assert.equal(entry.revision, 3)
73
+ })
74
+
75
+ test('重启注入一次:首请求含 <progress_resume>(objective/正在做/涉及文件),第二请求为空', async () => {
76
+ const root = path.join(TMP, 'resume-once')
77
+ const first = await boot({ archiveRoot: root })
78
+ await execUpdate(first, {
79
+ changes: [
80
+ { title: '实现归档', status: 'doing', current: '写 archive.js', next: '接钩子' },
81
+ { title: '补测试' },
82
+ ],
83
+ })
84
+ first.emit('tool/call', { name: 'write', arguments: JSON.stringify({ file_path: 'E:/repo/archive.js' }) })
85
+ first.emit('turn/end', {})
86
+ await flush()
87
+
88
+ // 模拟重启:新插件实例、同一归档目录
89
+ const second = await boot({ archiveRoot: root })
90
+ const text = second.contexts.get('progress-union-resume')
91
+ assert.equal(typeof text, 'function')
92
+ const block = text()
93
+ assert.match(block, /<progress_resume seq="1" revision="1" reason="turn"/)
94
+ assert.match(block, /任务目标:实现归档|任务目标:.*实现归档/)
95
+ assert.match(block, /正在做:实现归档 — current: 写 archive\.js/)
96
+ assert.match(block, /涉及文件:E:\/repo\/archive\.js/)
97
+ assert.equal(first.contexts.get('progress-union-resume') && true, true)
98
+ assert.equal(text(), '', '第二请求不再注入')
99
+ assert.equal(text(), '', '后续请求同样为空')
100
+ })
101
+
102
+ test('degraded:head 坏 → 注入上一版并显式标注「可能落后」', async () => {
103
+ const root = path.join(TMP, 'degraded')
104
+ const first = await boot({ archiveRoot: root })
105
+ await execUpdate(first, { changes: [{ title: '任务A', status: 'doing' }] })
106
+ first.emit('turn/end', {})
107
+ await flush()
108
+ first.emit('turn/end', {})
109
+ await flush()
110
+ const dir = dirOf(root)
111
+ const index = readIndex(dir)
112
+ assert.equal(index.headSeq, 2)
113
+ const headFile = archiveVersionPath(dir, 2)
114
+ const parsed = JSON.parse(fs.readFileSync(headFile, 'utf8'))
115
+ parsed.revision = 999
116
+ fs.writeFileSync(headFile, JSON.stringify(parsed))
117
+
118
+ const second = await boot({ archiveRoot: root })
119
+ const block = second.contexts.get('progress-union-resume')()
120
+ assert.match(block, /上一版归档/)
121
+ assert.match(block, /seq="1"/)
122
+ })
123
+
124
+ test('/progress-resume:打印最新/指定 seq 的 handoff,纯文本不写板', async () => {
125
+ const root = path.join(TMP, 'command')
126
+ const harness = await boot({ archiveRoot: root })
127
+ await execUpdate(harness, { changes: [{ title: '命令行任务', status: 'doing', current: '跑' }] })
128
+ harness.emit('turn/end', {})
129
+ await flush()
130
+ const cmd = harness.commandMap.get('progress-resume')
131
+ assert.ok(cmd)
132
+ const out = cmd.handler({ agent: harness.agent, rawInput: '' })
133
+ assert.equal(out.kind, 'success')
134
+ assert.match(out.text, /seq="1"/)
135
+ assert.match(out.text, /任务目标:命令行任务/)
136
+ const bySeq = cmd.handler({ agent: harness.agent, rawInput: '1' })
137
+ assert.equal(bySeq.kind, 'success')
138
+ const missing = cmd.handler({ agent: harness.agent, rawInput: '9' })
139
+ assert.equal(missing.kind, 'error')
140
+ const board = (await callRoute(harness, '/progress-union/snapshot', { method: 'GET', url: '/progress-union/snapshot?sessionId=' + SESSION, headers: {} })).json()
141
+ assert.equal(board.revision, 1, '命令不写板')
142
+ })
143
+
144
+ test('归档失败不阻断板:坏目录下板照常前进,archive.error 可见', async () => {
145
+ const blocker = path.join(TMP, 'blocker-file')
146
+ fs.writeFileSync(blocker, 'not a dir')
147
+ const harness = await boot({ archiveRoot: path.join(blocker, 'roots') })
148
+ const added = await execUpdate(harness, { changes: [{ title: '仍要写板' }] })
149
+ assert.equal(added.revision, 1)
150
+ harness.emit('turn/end', {})
151
+ await flush()
152
+ const snap = (await callRoute(harness, '/progress-union/snapshot', { method: 'GET', url: '/progress-union/snapshot?sessionId=' + SESSION, headers: {} })).json()
153
+ assert.equal(snap.revision, 1)
154
+ assert.match(String(snap.archive.error), /归档失败/)
155
+ assert.equal(snap.archive.seq, 0)
156
+ const next = await execUpdate(harness, { changes: [{ title: '第二项' }] })
157
+ assert.equal(next.revision, 2, '板 revision 照常前进')
158
+ })
159
+
160
+ test('session/disposed:同步落一版 reason=dispose', async () => {
161
+ const root = path.join(TMP, 'dispose')
162
+ const harness = await boot({ archiveRoot: root })
163
+ await execUpdate(harness, { changes: [{ title: '退出前任务', status: 'doing' }] })
164
+ for (const listener of harness.listeners.filter((l) => l.type === 'session/disposed')) listener.handler({ id: SESSION })
165
+ const index = readIndex(dirOf(root))
166
+ assert.ok(index)
167
+ const entry = readArchiveVersion(dirOf(root), index.headSeq)
168
+ assert.equal(entry.reason, 'dispose')
169
+ assert.equal(entry.revision, 1)
170
+ assert.equal(entry.handoff.generatedBy, 'rules-board-only')
171
+ })
172
+
173
+ test('大板裁剪:40 项板 + 小上限 → 单版 ≤ 上限且 truncated=true', async () => {
174
+ const root = path.join(TMP, 'big')
175
+ const harness = await boot({ archiveRoot: root, archiveMaxBytes: 4096 })
176
+ const changes = Array.from({ length: 40 }, (_, i) => ({ title: '任务 ' + i + ' ' + 'x'.repeat(40), status: i % 3 === 0 ? 'done' : 'todo', current: 'c'.repeat(60) }))
177
+ await execUpdate(harness, { changes })
178
+ for (let i = 0; i < 20; i += 1) harness.emit('tool/call', { name: 'write', arguments: JSON.stringify({ file_path: '/tmp/very-long-directory-name/file-' + i + '-' + 'y'.repeat(80) + '.js' }) })
179
+ harness.emit('turn/end', {})
180
+ await flush()
181
+ const dir = dirOf(root)
182
+ const entry = readArchiveVersion(dir, readIndex(dir).headSeq)
183
+ assert.equal(entry.truncated, true)
184
+ const bytes = Buffer.byteLength(JSON.stringify(entry))
185
+ assert.ok(bytes <= 4096, '裁剪后 ' + bytes + ' ≤ 4096')
186
+ assert.equal(verifyChecksum(entry), true, '裁剪后 checksum 仍与内容一致')
187
+ })
188
+ test('prune 定时器接线:sweep 一拍后旧版本被清理(head/head-1 不动)', async () => {
189
+ const root = path.join(TMP, 'sweep')
190
+ const dir = dirOf(root)
191
+ const now = Date.now()
192
+ for (let i = 1; i <= 12; i += 1) {
193
+ writeArchiveVersion(dir, {
194
+ version: 1, sessionId: SESSION, seq: 0, revision: i, at: now - 30 * 86400000 + i * 1000, reason: 'turn',
195
+ task: { title: 'sweep', goal: { objective: 'sweep', phase: 'active', roundsStarted: 0 } },
196
+ board: { enabled: true, summary: { total: 1, done: 1, doing: 0, todo: 0, blocked: 0, percent: 100 }, items: [] },
197
+ handoff: { objective: 'sweep', doneSoFar: [], inFlight: [], nextItems: [], filesTouched: [], openUnits: [], lastTurn: { turn: 1, startSeq: 0, endSeq: 0, summary: '' }, generatedBy: 'rules' },
198
+ truncated: false,
199
+ })
200
+ }
201
+ assert.equal(readIndex(dir).versions.length, 12)
202
+ await boot({ archiveRoot: root, archivePruneMs: 0 })
203
+ await sleep(4300) // SWEEP_MS=4000:等一拍定时器
204
+ const left = readIndex(dir).versions.map((v) => v.seq).sort((a, b) => a - b)
205
+ assert.deepEqual(left, [11, 12], '全部超过 7 天:只留 head 与 head-1')
206
+ assert.deepEqual(fs.readdirSync(dir).filter((n) => /^v\d{6}\.json$/.test(n)).sort(), ['v000011.json', 'v000012.json'])
207
+ })
208
+ test('老数据零迁移:无 archive/unit/closedAt 字段的旧记录补齐默认值并落进归档', async () => {
209
+ const root = path.join(TMP, 'migrate')
210
+ const key = Buffer.from(SESSION, 'utf8').toString('base64url')
211
+ const oldItem = { id: 'p_old', title: '老任务', status: 'done', percent: 100, current: '', next: '', approach: '', note: '', group: '', order: 0, updatedAt: 1, updatedBy: 'user' }
212
+ const harness = createHarness({
213
+ config: { archiveRoot: root },
214
+ seed: {
215
+ [key]: {
216
+ record: {
217
+ version: 1, sessionId: SESSION, revision: 2, userRevision: 0, agentSeenRevision: 0,
218
+ enabled: true, createdAt: 1, updatedAt: 1, items: [oldItem], userChanges: [],
219
+ },
220
+ },
221
+ },
222
+ })
223
+ await harness.run()
224
+ harness.emit('turn/end', {})
225
+ await flush()
226
+ const dir = dirOf(root)
227
+ const entry = readArchiveVersion(dir, readIndex(dir).headSeq)
228
+ const item = entry.board.items[0]
229
+ assert.equal(item.id, 'p_old')
230
+ assert.equal(item.unit, '')
231
+ assert.equal(item.targetTurns, 2)
232
+ assert.equal(item.closedAt, 0)
233
+ assert.equal(item.status, 'done')
234
+ const snap = (await callRoute(harness, '/progress-union/snapshot', { method: 'GET', url: '/progress-union/snapshot?sessionId=' + SESSION, headers: {} })).json()
235
+ assert.equal(snap.revision, 2, '板本身不被迁移改写')
236
+ })
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Phase 4 验收:恢复链(head → head-1 → null degraded)+ 契约面(HTTP 三路由 / 锚点 archive 字段)。
3
+ */
4
+ import assert from 'node:assert/strict'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import test from 'node:test'
9
+
10
+ import { archiveDir, archiveVersionPath, writeArchiveVersion, readIndex, isArchive } from '../archive.js'
11
+ import { isAnchor } from '../anchor.js'
12
+
13
+ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'union-restore-'))
14
+ const { SESSION, createHarness, getReq, fakeRes } = await import('./harness.mjs')
15
+
16
+ function makeEntry(rev, over = {}) {
17
+ return {
18
+ version: 1, sessionId: SESSION, seq: 0, revision: rev, at: Date.now(), reason: 'turn',
19
+ task: { title: '恢复测试', goal: { objective: '恢复目标', phase: 'active', roundsStarted: 0 } },
20
+ board: { enabled: true, summary: { total: 1, done: 1, doing: 0, todo: 0, blocked: 0, percent: 100 }, items: [] },
21
+ handoff: { objective: '恢复目标', doneSoFar: ['甲'], inFlight: [], nextItems: [], filesTouched: [], openUnits: [], lastTurn: { turn: rev, startSeq: 0, endSeq: 0, summary: '' }, generatedBy: 'rules' },
22
+ truncated: false,
23
+ ...over,
24
+ }
25
+ }
26
+
27
+ function seedVersions(root, revs) {
28
+ const d = archiveDir(root, SESSION)
29
+ fs.rmSync(d, { recursive: true, force: true })
30
+ const seqs = revs.map((rev) => writeArchiveVersion(d, makeEntry(rev)).seq)
31
+ return { dir: d, seqs }
32
+ }
33
+
34
+ async function boot(root) {
35
+ const harness = createHarness({ config: { archiveRoot: root } })
36
+ await harness.run()
37
+ return harness
38
+ }
39
+
40
+ async function get(harness, url) {
41
+ const route = harness.routes.get(new URL(url, 'http://x').pathname)
42
+ const res = fakeRes()
43
+ await route.handler(getReq(url), res)
44
+ return res
45
+ }
46
+
47
+ test('head 正常:/archive/latest 返回 head 且 degraded=false', async () => {
48
+ const root = path.join(TMP, 'normal')
49
+ const { seqs } = seedVersions(root, [11, 12])
50
+ const harness = await boot(root)
51
+ const res = await get(harness, '/progress-union/archive/latest?sessionId=' + SESSION)
52
+ assert.equal(res.status, 200)
53
+ const body = res.json()
54
+ assert.equal(body.ok, true)
55
+ assert.equal(body.degraded, false)
56
+ assert.equal(isArchive(body.archive), true, 'GET 返回体通过 isArchive')
57
+ assert.equal(body.archive.seq, seqs.at(-1))
58
+ assert.equal(body.archive.handoff.objective, '恢复目标')
59
+ })
60
+
61
+ test('head 坏(checksum 不匹配)→ 自动回退 head-1 且 degraded=true', async () => {
62
+ const root = path.join(TMP, 'head-broken')
63
+ const { dir, seqs } = seedVersions(root, [21, 22])
64
+ const headFile = archiveVersionPath(dir, seqs.at(-1))
65
+ const parsed = JSON.parse(fs.readFileSync(headFile, 'utf8'))
66
+ parsed.board.summary.percent = 7
67
+ fs.writeFileSync(headFile, JSON.stringify(parsed))
68
+ const harness = await boot(root)
69
+ const body = (await get(harness, '/progress-union/archive/latest?sessionId=' + SESSION)).json()
70
+ assert.equal(body.ok, true)
71
+ assert.equal(body.degraded, true)
72
+ assert.equal(body.archive.seq, seqs.at(-2), '回退到 head-1')
73
+ })
74
+
75
+ test('head 与 head-1 都坏 → 返回 null + degraded(绝不当作从零开始)', async () => {
76
+ const root = path.join(TMP, 'both-broken')
77
+ const { dir, seqs } = seedVersions(root, [31, 32])
78
+ for (const seq of seqs) {
79
+ const file = archiveVersionPath(dir, seq)
80
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
81
+ parsed.reason = 'tampered'
82
+ fs.writeFileSync(file, JSON.stringify(parsed))
83
+ }
84
+ const harness = await boot(root)
85
+ const body = (await get(harness, '/progress-union/archive/latest?sessionId=' + SESSION)).json()
86
+ assert.equal(body.ok, false)
87
+ assert.equal(body.degraded, true)
88
+ assert.equal(body.archive, undefined)
89
+ })
90
+
91
+ test('目录不存在 → ok=false、degraded=false、reason=missing(没有归档 ≠ 坏版)', async () => {
92
+ const harness = await boot(path.join(TMP, 'no-dir'))
93
+ const body = (await get(harness, '/progress-union/archive/latest?sessionId=' + SESSION)).json()
94
+ assert.equal(body.ok, false)
95
+ assert.equal(body.degraded, false)
96
+ assert.equal(body.reason, 'missing')
97
+ })
98
+
99
+ test('路由契约:非 GET → 405;缺 sessionId → 400;versions 倒序且 limit 生效', async () => {
100
+ const root = path.join(TMP, 'routes')
101
+ const { seqs } = seedVersions(root, [41, 42, 43])
102
+ const harness = await boot(root)
103
+
104
+ const post = await get(harness, '/progress-union/archive/latest?sessionId=' + SESSION)
105
+ assert.equal(post.status, 200) // GET 正常
106
+ const route = harness.routes.get('/progress-union/archive/latest')
107
+ const res405 = fakeRes()
108
+ await route.handler({ method: 'POST', url: '/progress-union/archive/latest', headers: {} }, res405)
109
+ assert.equal(res405.status, 405)
110
+
111
+ const res400 = await get(harness, '/progress-union/archive/latest')
112
+ assert.equal(res400.status, 400)
113
+
114
+ const versions = (await get(harness, '/progress-union/archive/versions?sessionId=' + SESSION + '&limit=2')).json()
115
+ assert.equal(versions.ok, true)
116
+ assert.equal(versions.headSeq, seqs.at(-1))
117
+ assert.deepEqual(versions.versions.map((v) => v.seq), [seqs[2], seqs[1]])
118
+
119
+ const one = (await get(harness, '/progress-union/archive/version?sessionId=' + SESSION + '&seq=' + seqs[0])).json()
120
+ assert.equal(one.ok, true)
121
+ assert.equal(one.archive.seq, seqs[0])
122
+
123
+ const badSeq = await get(harness, '/progress-union/archive/version?sessionId=' + SESSION + '&seq=abc')
124
+ assert.equal(badSeq.status, 400)
125
+ })
126
+
127
+ test('锚点面:isAnchor 对新增 archive 字段仍 true;archive.handoff 可读;ANCHOR_VERSION 不变', async () => {
128
+ const root = path.join(TMP, 'anchor')
129
+ seedVersions(root, [51])
130
+ const harness = await boot(root)
131
+ const anchor = harness.provided.get('progressAnchor').get(SESSION)
132
+ assert.equal(isAnchor(anchor), true)
133
+ assert.equal(anchor.version, 1)
134
+ assert.equal(anchor.archive.seq, 1)
135
+ assert.equal(anchor.archive.handoff.objective, '恢复目标')
136
+ assert.equal(harness.provided.get('progressAnchor').handoff(SESSION).objective, '恢复目标')
137
+ assert.equal(harness.provided.get('progressAnchor').archive('no-such-session'), null)
138
+ })
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Phase 1/2 验收:归档契约 + 存储(形状 / 路径 / 校验和 / 原子序 / 保留策略 / 裁剪)。
3
+ * 纯函数 + 临时目录,不起宿主。
4
+ */
5
+ import assert from 'node:assert/strict'
6
+ import fs from 'node:fs'
7
+ import os from 'node:os'
8
+ import path from 'node:path'
9
+ import test from 'node:test'
10
+
11
+ import {
12
+ ARCHIVE_VERSION, ARCHIVE_ROUTES, ARCHIVE_KEEP_VERSIONS, ARCHIVE_KEEP_DAYS,
13
+ isArchive, archiveDir, archiveVersionPath, computeChecksum, verifyChecksum,
14
+ writeArchiveVersion, readIndex, readArchiveVersion, pickRestoreTarget,
15
+ pruneArchives, truncateArchive, archiveLine, listVersionSeqs,
16
+ } from '../archive.js'
17
+
18
+ const SID = 'session-archive-test'
19
+ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'union-archive-'))
20
+ const DAY = 86400000
21
+
22
+ function makeEntry(over = {}) {
23
+ return {
24
+ version: ARCHIVE_VERSION,
25
+ sessionId: SID,
26
+ seq: 0,
27
+ revision: 1,
28
+ at: Date.now(),
29
+ reason: 'turn',
30
+ task: { title: '归档测试', goal: { objective: '把会话归档做完', phase: 'active', roundsStarted: 0 } },
31
+ board: {
32
+ enabled: true,
33
+ summary: { total: 2, done: 1, doing: 1, todo: 0, blocked: 0, percent: 50 },
34
+ items: [{ id: 'p_1', title: '一', status: 'done', percent: 100, current: '', next: '', order: 0, unit: '', targetTurns: 2, closedAt: 1 }],
35
+ },
36
+ handoff: {
37
+ objective: '把会话归档做完',
38
+ doneSoFar: ['一'],
39
+ inFlight: [{ title: '二', current: 'c', next: 'n' }],
40
+ nextItems: ['三'],
41
+ filesTouched: ['archive.js'],
42
+ openUnits: [],
43
+ lastTurn: { turn: 1, startSeq: 0, endSeq: 0, summary: '开工' },
44
+ generatedBy: 'rules',
45
+ },
46
+ truncated: false,
47
+ ...over,
48
+ }
49
+ }
50
+
51
+ function freshDir(name) {
52
+ const d = path.join(TMP, name)
53
+ fs.mkdirSync(d, { recursive: true })
54
+ return d
55
+ }
56
+
57
+ test('契约常量:版本 1、三条路由、10 版 / 7 天', () => {
58
+ assert.equal(ARCHIVE_VERSION, 1)
59
+ assert.deepEqual(Object.keys(ARCHIVE_ROUTES).sort(), ['latest', 'version', 'versions'])
60
+ assert.equal(ARCHIVE_KEEP_VERSIONS, 10)
61
+ assert.equal(ARCHIVE_KEEP_DAYS, 7)
62
+ })
63
+
64
+ test('isArchive 宽松校验:必备骨架齐即过,新增字段不为难,坏 board 判否', () => {
65
+ assert.equal(isArchive(makeEntry()), true)
66
+ assert.equal(isArchive(makeEntry({ futureField: { x: 1 } })), true, '新增字段不失败')
67
+ assert.equal(isArchive(makeEntry({ handoff: undefined })), false, '缺 handoff')
68
+ assert.equal(isArchive(makeEntry({ board: { enabled: true, summary: { total: 1 } } })), false, 'summary 缺 percent')
69
+ assert.equal(isArchive(makeEntry({ seq: '7' })), false, 'seq 非数字')
70
+ assert.equal(isArchive(null), false)
71
+ })
72
+
73
+ test('archiveDir:sha256 前 16 hex;同 sid 稳定、不同 sid 不同、目录名无非法字符', () => {
74
+ const home = path.join(TMP, 'home')
75
+ const a = archiveDir(home, SID)
76
+ const b = archiveDir(home, SID)
77
+ assert.equal(a, b)
78
+ assert.notEqual(archiveDir(home, 'session-other'), a)
79
+ assert.equal(path.dirname(a), path.join(home, 'dsh-progress-archive'))
80
+ const seg = path.basename(a)
81
+ assert.match(seg, /^[0-9a-f]{16}$/)
82
+ // 原始 sessionId 里的 ':' '..' '\\\\' 一律不进路径
83
+ const evil = archiveDir(home, 'session:../..\\evil')
84
+ assert.equal(path.basename(evil), path.basename(archiveDir(home, 'session:../..\\evil')))
85
+ assert.match(path.basename(evil), /^[0-9a-f]{16}$/)
86
+ assert.deepEqual(Array.from(new Set([seg, path.basename(evil)])).length, 2)
87
+ })
88
+
89
+ test('archiveVersionPath:6 位零填充,字典序即版本序', () => {
90
+ const d = path.join(TMP, 'any')
91
+ assert.ok(archiveVersionPath(d, 7).endsWith('v000007.json'))
92
+ assert.ok(archiveVersionPath(d, 123456).endsWith('v123456.json'))
93
+ assert.ok(archiveVersionPath(d, 7) < archiveVersionPath(d, 8))
94
+ })
95
+
96
+ test('checksum:稳定序列化(键序无关)+ 改字段即失效', () => {
97
+ const a = makeEntry()
98
+ const b = makeEntry()
99
+ b.checksum = computeChecksum(b)
100
+ assert.equal(verifyChecksum(b), true)
101
+ // 键序打乱不影响
102
+ const reordered = { board: b.board, handoff: b.handoff, at: b.at, revision: b.revision, seq: b.seq, sessionId: b.sessionId, version: b.version, task: b.task, truncated: false, reason: b.reason, checksum: b.checksum }
103
+ assert.equal(verifyChecksum(reordered), true)
104
+ b.board.summary.percent = 99
105
+ assert.equal(verifyChecksum(b), false, '改 percent 后校验失败')
106
+ assert.equal(verifyChecksum(makeEntry()), false, '无 checksum 视为坏版')
107
+ })
108
+
109
+ test('写入顺序:先版本文件后索引;索引写入失败时磁盘留孤儿版本但索引不脏', () => {
110
+ const d = freshDir('atomic')
111
+ const prev = makeEntry({ at: Date.now() - 1000 })
112
+ const first = writeArchiveVersion(d, prev)
113
+ assert.equal(first.seq, 1)
114
+ assert.equal(readIndex(d).headSeq, 1)
115
+ assert.ok(fs.existsSync(archiveVersionPath(d, 1)))
116
+ assert.ok(fs.existsSync(path.join(d, 'v000001.md')), '人读版同时落地')
117
+
118
+ // 让 index.json 落不下来:清掉旧索引后在该路径放同名目录 → rename 必失败
119
+ fs.unlinkSync(path.join(d, 'index.json'))
120
+ fs.mkdirSync(path.join(d, 'index.json'))
121
+ assert.throws(() => writeArchiveVersion(d, makeEntry({ revision: 2 })))
122
+ assert.ok(fs.existsSync(archiveVersionPath(d, 2)), '版本文件已先落地(孤儿可接受)')
123
+ assert.equal(readIndex(d), null, '索引没有指向半成品')
124
+ assert.deepEqual(listVersionSeqs(d), [1, 2])
125
+ fs.rmdirSync(path.join(d, 'index.json'))
126
+ })
127
+
128
+ test('读回:head 可读、checksum 坏版 readArchiveVersion 仍返形状但 verify 判否', () => {
129
+ const d = freshDir('readback')
130
+ const w = writeArchiveVersion(d, makeEntry())
131
+ const entry = readArchiveVersion(d, w.seq)
132
+ assert.equal(isArchive(entry), true)
133
+ assert.equal(verifyChecksum(entry), true)
134
+ // 损坏文件
135
+ const file = archiveVersionPath(d, w.seq)
136
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
137
+ parsed.board.summary.percent = 3
138
+ fs.writeFileSync(file, JSON.stringify(parsed))
139
+ assert.equal(verifyChecksum(readArchiveVersion(d, w.seq)), false)
140
+ })
141
+
142
+ test('pickRestoreTarget:head → head-1 → null', () => {
143
+ assert.equal(pickRestoreTarget({ headSeq: 7, versions: [] }, [7]), 7)
144
+ assert.equal(pickRestoreTarget({ headSeq: 7, versions: [] }, [6]), 6)
145
+ assert.equal(pickRestoreTarget({ headSeq: 7, versions: [] }, [5]), null)
146
+ assert.equal(pickRestoreTarget({ headSeq: 1, versions: [] }, [1]), 1)
147
+ assert.equal(pickRestoreTarget({ headSeq: 1, versions: [] }, []), null)
148
+ assert.equal(pickRestoreTarget(null, [1]), null)
149
+ assert.equal(pickRestoreTarget({ headSeq: 7, versions: [] }, (seq) => seq === 6), 6)
150
+ })
151
+
152
+ test('prune:14 版(8 条 8 天前 + 6 条 5 天内)→ 留 head、head-1 与 5 天内版本,总数 ≤10', () => {
153
+ const d = freshDir('prune-14')
154
+ const now = Date.now()
155
+ for (let i = 1; i <= 14; i += 1) {
156
+ const at = i <= 8 ? now - 8 * DAY : now - 5 * DAY
157
+ writeArchiveVersion(d, makeEntry({ at, revision: i }))
158
+ }
159
+ assert.equal(listVersionSeqs(d).length, 14)
160
+ const result = pruneArchives(d, 10, 7, now)
161
+ const left = listVersionSeqs(d)
162
+ assert.ok(left.length <= 10, '总数 ≤10,实际 ' + left.length)
163
+ assert.ok(left.includes(14), 'head 保留')
164
+ assert.ok(left.includes(13), 'head-1 无条件保留')
165
+ assert.ok(left.every((seq) => seq >= 9), '超过 7 天的 1..8 全部清理(只留 head/head-1 的 13/14)')
166
+ assert.equal(left.filter((seq) => seq === 14 || seq === 13).length, 2)
167
+ assert.deepEqual(result.removed.sort((a, b) => a - b), [1, 2, 3, 4, 5, 6, 7, 8])
168
+ const index = readIndex(d)
169
+ assert.deepEqual(index.versions.map((v) => v.seq).sort((a, b) => a - b), left, 'index 同步裁剪')
170
+ assert.equal(index.headSeq, 14)
171
+ })
172
+
173
+ test('prune:全部版本 >7 天 → 只剩 head 与 head-1(2 版)', () => {
174
+ const d = freshDir('prune-old')
175
+ const now = Date.now()
176
+ for (let i = 1; i <= 5; i += 1) writeArchiveVersion(d, makeEntry({ at: now - 30 * DAY, revision: i }))
177
+ pruneArchives(d, 10, 7, now)
178
+ assert.deepEqual(listVersionSeqs(d), [4, 5])
179
+ assert.deepEqual(readIndex(d).versions.map((v) => v.seq), [4, 5])
180
+ })
181
+
182
+ test('prune:keep=3 生效;keepDays=0 只剩 head+head-1', () => {
183
+ const d = freshDir('prune-keep3')
184
+ const now = Date.now()
185
+ for (let i = 1; i <= 6; i += 1) writeArchiveVersion(d, makeEntry({ at: now - i * 1000, revision: i }))
186
+ pruneArchives(d, 3, 7, now)
187
+ const left = listVersionSeqs(d)
188
+ assert.ok(left.length <= 3, 'keep=3,实际 ' + left.length)
189
+ assert.ok(left.includes(6) && left.includes(5))
190
+
191
+ const d2 = freshDir('prune-0days')
192
+ for (let i = 1; i <= 5; i += 1) writeArchiveVersion(d2, makeEntry({ at: now - i * 1000, revision: i }))
193
+ pruneArchives(d2, 10, 0, now + 1000)
194
+ assert.deepEqual(listVersionSeqs(d2), [4, 5])
195
+ })
196
+
197
+ test('truncateArchive:40 项板 + 20 个路径 → 先砍 doneSoFar/filesTouched,标 truncated 且 ≤ 上限', () => {
198
+ const items = Array.from({ length: 40 }, (_, i) => ({
199
+ id: 'p_' + i, title: '步骤 ' + i + ' ' + 'x'.repeat(60), status: i % 3 === 0 ? 'done' : 'doing',
200
+ percent: 40, current: 'c'.repeat(80), next: 'n'.repeat(80), order: i, unit: '', targetTurns: 2, closedAt: 0,
201
+ }))
202
+ const entry = makeEntry({
203
+ board: { enabled: true, summary: { total: 40, done: 14, doing: 26, todo: 0, blocked: 0, percent: 40 }, items },
204
+ handoff: {
205
+ objective: '大板', doneSoFar: Array.from({ length: 20 }, (_, i) => 'done ' + i + ' ' + 'y'.repeat(80)),
206
+ inFlight: [], nextItems: Array.from({ length: 10 }, (_, i) => 'next ' + i), filesTouched: Array.from({ length: 20 }, (_, i) => '/tmp/file-' + i + '-' + 'z'.repeat(60) + '.js'),
207
+ openUnits: [], lastTurn: { turn: 3, startSeq: 0, endSeq: 0, summary: 's' }, generatedBy: 'rules',
208
+ },
209
+ })
210
+ assert.ok(Buffer.byteLength(JSON.stringify(entry)) > 8192, '原始超过 8KB(实测 ' + Buffer.byteLength(JSON.stringify(entry)) + ')')
211
+ const small = truncateArchive(entry, 4096)
212
+ assert.equal(small.truncated, true)
213
+ assert.ok(Buffer.byteLength(JSON.stringify(small)) <= 4096, '裁剪后 ≤ 上限(实测 ' + Buffer.byteLength(JSON.stringify(small)) + ')')
214
+ assert.ok(small.handoff.doneSoFar.length < entry.handoff.doneSoFar.length, '先砍 doneSoFar')
215
+ const roomy = truncateArchive(entry, 32768)
216
+ assert.ok(Buffer.byteLength(JSON.stringify(roomy)) <= 32768)
217
+ })
218
+
219
+ test('archiveLine:rev/百分比/年龄三段;坏形状返回空串', () => {
220
+ const now = Date.now()
221
+ const line = archiveLine(makeEntry({ revision: 12, at: now - 2 * 3600 * 1000 }))
222
+ assert.match(line, /^rev 12 · 50% 1\/2 · 2h前$/)
223
+ assert.equal(archiveLine({}), '')
224
+ })