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/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  本项目的所有值得记录的变更都写在这里。版本号遵循语义化版本。
4
4
 
5
+ ## 0.6.0 (2026-12-02)
6
+
7
+ **feat(会话归档):每回合落一版可回放归档 + handoff 规则摘要 + 重启注入一次 —— 「重启不从零理解任务」。新增对外契约面(`./archive` 子路径、三条只读路由、锚点追加 `archive` 字段),按 semver 记为 **minor**;旧 consumer 零改动(`ANCHOR_VERSION` 仍为 1,只追加字段/路由/命令)。**
8
+
9
+ - **为什么**:板状态本来就在宿主 KV 里(`storages/progress_union/sessions/*.json`),所以「重启从零」不是落盘缺失,而是**没有版本链、没有可读摘要、没有注入**。`persist()` 是覆盖写,只有当前态。
10
+ - **新模块 `archive.js`(零依赖 ESM)**:`ARCHIVE_VERSION=1`、`ARCHIVE_ROUTES`(latest/versions/version)、`ARCHIVE_KEEP_VERSIONS=10`、`ARCHIVE_KEEP_DAYS=7`、`isArchive`(宽松形状)、`archiveLine`、`archiveDir`(`sha256(sessionId)` 前 16 hex)、`archiveVersionPath`(`v000007.json`)、`pickRestoreTarget`(head → head-1 → null)、`computeChecksum/verifyChecksum`(除 checksum 外全字段稳定序列化+`sha256`)、`truncateArchive`(先砍 `doneSoFar` 再砍 `filesTouched`)、`pruneArchives`。
11
+ - **写入面**:`turn/end` 延后一个 `queueMicrotask` 落 `reason:'turn'`(避开宿主 `commit()` 的 `appending` 窗口,CCI 0.17 `manifest-failed` 即此);`applyChanges` 成功后 200ms 去抖落 `reason:'revision'`(同 revision 已归档则跳过);`session/disposed` 与插件卸载同步落 `reason:'dispose'`。顺序固定「先版本文件、后 `index.json`」,崩溃最多多一个孤儿版本,索引不脏。
12
+ - **handoff 纯规则**(不调模型):`objective / doneSoFar / inFlight / nextItems / filesTouched / openUnits / lastTurn`;事件原料来自 `session/event` 的 240 条环形缓冲(只收 tool/assistant/turn/user 四类,不把大 payload 常驻内存);宿主事件面缺失时降级 `generatedBy:'rules-board-only'`。
13
+ - **恢复**:head checksum 坏 → 自动回退 head-1 且 `degraded:true`;两者都坏 → null + `degraded`,**绝不把「读不到」当「从零开始」**。每实例每会话首个模型请求注入一次 `<progress_resume seq revision reason at>`(objective / 正在做 / 接下来 / 已完成 / 涉及文件 / 未闭合单元 / 恢复说明),之后不再注入;`/progress-resume [seq]` 命令兜底(纯文本,不写板)。
14
+ - **保留策略**:每会话 ≤10 版、只留 7 天内;head 与 head-1 无条件保留(闲置超 7 天收敛到 2 版);复用既有 4s sweep 定时器、默认 24h 扫一次,磁盘上限约 `10 × 32KB/会话`。
15
+ - **对外面**:`ctx.provide('progressAnchor')` 新增 `.archive(sid)` / `.handoff(sid)`;锚点安装追加 `archive:{seq,revision,at,reason,handoff,degraded}`;HTTP 三路由(非 GET → 405、缺参 → 400、读失败 → 200 `{ok:false,degraded}`)。
16
+ - **配置**(六键,全部 default,老 profile 零迁移):`archiveEnabled=true`、`archiveKeepVersions=10`、`archiveKeepDays=7`、`archiveHandoffTurns=3`、`archiveInjectOnResume=true`、`archiveMaxBytes=32768`。
17
+ - **R9 失败不阻断**:归档任何失败只写 `state.archiveError`(快照 `archive.error` 回显),绝不阻断板写入、绝不抛到宿主。
18
+ - **测试**:新增 `test/archive.test.mjs`(契约/路径/校验和/原子序/保留策略/裁剪)、`test/archive-restore.test.mjs`(head 坏→head-1→null、三路由 405/400)、`test/archive-inject.test.mjs`(turn 落版/revision 去抖/dispose 兜底/一次注入/degraded 文案/命令/失败不阻断/大板裁剪/sweep prune 接线),全量 **154 条通过**(0.5.14 的 125 条无回归)。
19
+
5
20
  ## 0.5.14 (2026-12-02)
6
21
 
7
22
  **fix(快捷入口):`close()` 传的是注册 kind 而不是页签 id —— 0.5.12 起「点头部图标收起,再展开右栏,任务板页签还在」。**
@@ -323,4 +338,4 @@ W2 better-sidebar 页签(`ctx.betterSidebar.registerTab`):
323
338
 
324
339
  - board 槽位真相源(用户可编辑、revision/diff/ack 增量、staleness nudge);
325
340
  - 鲸程时间引擎(step 计数、elapsed、ETA 四档 board > todo > local > prior);
326
- - 只读三层进度锚点 `progressAnchor`(service + HTTP 双平面),供压缩类插件消费。
341
+ - 只读三层进度锚点 `progressAnchor`(service + HTTP 双平面),供压缩类插件消费。
package/README.md CHANGED
@@ -73,6 +73,58 @@ import { ANCHOR_VERSION, ANCHOR_ROUTES, isAnchor, anchorLine } from 'dsh-progres
73
73
 
74
74
  自 **v0.3.0** 起,板变更会镜像到宿主官方 todo(设置页三段开关 `off` / `mirror` / `reconcile`,默认 `reconcile` 会覆盖模型写的清单,属行为变更,可在设置页关掉或切到 `off`);详见 [CHANGELOG](CHANGELOG.md#030-2026-11-26)。
75
75
 
76
+ ## 会话归档(v0.6.0)
77
+
78
+ 重启后「从零理解任务」不是落盘缺失,而是**没有版本链、没有可读摘要、没有注入**。归档把「板 + 目标 + 任务理解摘要(handoff)」按版本写盘,会话重新挂载后的首个模型请求注入一次 `<progress_resume>`,之后交给 `/progress-resume` 兜底。
79
+
80
+ ### 持久化三处,别读错
81
+
82
+ | 位置 | 内容 | 谁写 | 用途 |
83
+ | --- | --- | --- | --- |
84
+ | `$DSH_HOME/storages/progress_union/sessions/*.json` | 板当前态(KV per-record,覆盖写) | 宿主 `persist()` | 真相源;无版本链 |
85
+ | `$DSH_HOME/dsh-progress-archive/<sha256(sid) 前16>/vNNNNNN.json` | 归档版本链 + `index.json` + 同名 `.md` | 本插件(turn / revision 去抖 / dispose) | 重启找回任务理解;外部脚本/CCI 可直读 |
86
+ | `$DSH_HOME/dsh-progress/<sid>.json` | 旧文件上报协议(鲸程兼容层) | 模型/旧插件 | 仅板关闭时生效,与归档无关 |
87
+
88
+ ### 什么时候落版
89
+
90
+ - `turn/end`:延后一个 `queueMicrotask` 写一版 `reason:'turn'`(避开宿主 `commit()` 的 `appending` 窗口)。
91
+ - `progress_update` 改板:200ms 去抖合并成一版 `reason:'revision'`,同 revision 已归档则跳过。
92
+ - `session/disposed` 与插件卸载:同步写一版 `reason:'dispose'`,覆盖 DSH 正常退出。
93
+ - 每 24h(复用既有 sweep 定时器):按「每会话 10 版 / 7 天 / head 与 head-1 永不删」清理——超 7 天只留最新两版,目录上限约 `10 × 32KB/会话`。
94
+
95
+ ### 恢复与注入
96
+
97
+ - 恢复链:`head → head-1 → null`。head 的 checksum 不匹配自动回退 head-1 并标 `degraded`;两者都坏时如实返回 null,**绝不把「读不到」当成「从零开始」**。
98
+ - 注入一次:每个插件实例、每个会话只在重新挂载后的首个模型请求注入 `<progress_resume seq revision reason at>`(objective / 正在做 / 接下来 / 已完成 / 涉及文件 / 未闭合单元 / 恢复说明)。
99
+ - 命令兜底:`/progress-resume [seq]` 打印最新或指定版本的 handoff(纯文本,不写板)。
100
+
101
+ ### handoff 规则(不调模型)
102
+
103
+ `objective / doneSoFar / inFlight / nextItems / filesTouched / openUnits / lastTurn` 全部从板 + 最近 `archiveHandoffTurns` 个 turn 的工具调用/尾段输出里规则抽取,零延迟、零失败点;宿主事件面缺失时退化成 `generatedBy:'rules-board-only'`(仅板)。单版超 `archiveMaxBytes`(默认 32KB)先砍 `doneSoFar` 尾部、再砍 `filesTouched`,标 `truncated:true`。
104
+
105
+ ### 对外读面
106
+
107
+ 同一份 `archive.js` 契约(`ARCHIVE_VERSION=1`、`ARCHIVE_ROUTES`、`isArchive`、`archiveLine`、`archiveDir`、`archiveVersionPath`、`pickRestoreTarget`、`computeChecksum/verifyChecksum`)供 consumer `import 'dsh-progress-union/archive'`:
108
+
109
+ ```bash
110
+ curl "http://127.0.0.1:<web-port>/progress-union/archive/latest?sessionId=<sid>"
111
+ curl "http://127.0.0.1:<web-port>/progress-union/archive/versions?sessionId=<sid>&limit=5"
112
+ curl "http://127.0.0.1:<web-port>/progress-union/archive/version?sessionId=<sid>&seq=7"
113
+ ```
114
+
115
+ `progressAnchor` 锚点只**追加** `archive: { seq, revision, at, reason, handoff, degraded }`;`ANCHOR_VERSION` 仍为 1,老 consumer 可选链读取即可。失败只写 `archiveError`(快照 `archive.error` 回显),绝不阻断板写入。
116
+
117
+ ### 配置(设置 → 插件,全部有默认值、老 profile 零迁移)
118
+
119
+ | key | 默认 | 说明 |
120
+ | --- | --- | --- |
121
+ | `archiveEnabled` | `true` | 总开关 |
122
+ | `archiveKeepVersions` | `10` | 每会话保留版本数(含 head 与 head-1,最小 2) |
123
+ | `archiveKeepDays` | `7` | 版本保留天数;超期只留最新两版 |
124
+ | `archiveHandoffTurns` | `3` | handoff 回看 turn 数 |
125
+ | `archiveInjectOnResume` | `true` | 重启后自动注入一次 |
126
+ | `archiveMaxBytes` | `32768` | 单版上限 |
127
+
76
128
  ## 使用
77
129
 
78
130
  - `/progress`(on)/ `/progress off`:语义与 board 原版一致——开过一次持续启用,收起侧栏不关闭。
@@ -216,5 +268,5 @@ assistant:
216
268
  ## 开发与测试
217
269
 
218
270
  ```bash
219
- npm test # node --test test/*.test.mjs(51 用例,纯 mock ctx,无需宿主进程)
220
- ```
271
+ npm test # node --test test/*.test.mjs(154 用例,纯 mock ctx,无需宿主进程)
272
+ ```
package/archive.js ADDED
@@ -0,0 +1,356 @@
1
+ /**
2
+ * dsh-progress-union/archive — 零依赖归档契约,供其他插件 import。
3
+ *
4
+ * 会话归档:每次 turn 收尾 / 板 revision 去抖 / 退出兜底把「板 + 目标 + 任务理解摘要
5
+ * (handoff)」写成一版可回放文件,重启后注入一次,避免「从零理解任务」。
6
+ *
7
+ * 存储布局(home = $DSH_HOME):
8
+ * <home>/dsh-progress-archive/<sha256(sessionId) 前 16 hex>/
9
+ * index.json { version, sessionId, headSeq, updatedAt, versions:[...] }
10
+ * v000007.json 单版归档(tmp → rename 原子写)
11
+ * v000007.md 人类可读版(面板/排障用,不进模型上下文)
12
+ *
13
+ * 写入顺序固定「先版本文件、后 index.json」:中途崩溃最多多一个孤儿版本文件,
14
+ * 索引永不会指向不存在的版本;恢复链(head → head-1 → null)因此永远可走。
15
+ *
16
+ * 版本握手:consumer 读 ARCHIVE_VERSION 与归档里 version 相等才解析;新增字段只能追加。
17
+ */
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import crypto from 'node:crypto'
21
+
22
+ export const ARCHIVE_VERSION = 1
23
+
24
+ export const ARCHIVE_ROUTES = {
25
+ latest: '/progress-union/archive/latest',
26
+ versions: '/progress-union/archive/versions',
27
+ version: '/progress-union/archive/version',
28
+ }
29
+
30
+ /** 每会话保留版本数上限(含 head 与 head-1)。 */
31
+ export const ARCHIVE_KEEP_VERSIONS = 10
32
+ /** 版本保留天数;超期只留 head 与 head-1。 */
33
+ export const ARCHIVE_KEEP_DAYS = 7
34
+ /** 单版上限(字节):超限先砍 doneSoFar 尾部、再砍 filesTouched,标 truncated。 */
35
+ export const ARCHIVE_MAX_BYTES = 32 * 1024
36
+ /** 归档根目录名(与旧 dsh-progress/ 上报目录明确区分)。 */
37
+ export const ARCHIVE_ROOT_DIR = 'dsh-progress-archive'
38
+
39
+ function isObject(value) {
40
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
41
+ }
42
+
43
+ function num(value) {
44
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
45
+ }
46
+
47
+ function str(value) {
48
+ return typeof value === 'string' ? value : undefined
49
+ }
50
+
51
+ /** 形状校验:新旧归档都能过(必备骨架齐、新增字段不挑)。 */
52
+ export function isArchive(v) {
53
+ if (!isObject(v)) return false
54
+ if (typeof v.version !== 'number' || typeof v.sessionId !== 'string') return false
55
+ if (num(v.seq) === undefined || num(v.revision) === undefined || num(v.at) === undefined) return false
56
+ if (!isObject(v.board) || !isObject(v.board.summary)) return false
57
+ const s = v.board.summary
58
+ if (['total', 'done', 'percent'].some((k) => typeof s[k] !== 'number')) return false
59
+ if (!isObject(v.handoff)) return false
60
+ return true
61
+ }
62
+
63
+ /** 稳定序列化:对象键排序,数组保序(checksum 只依赖内容,不依赖键顺序)。 */
64
+ export function stableStringify(value) {
65
+ if (value === null) return 'null'
66
+ if (Array.isArray(value)) return '[' + value.map((v) => stableStringify(v === undefined ? null : v)).join(',') + ']'
67
+ if (typeof value === 'object') {
68
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort()
69
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + stableStringify(value[k])).join(',') + '}'
70
+ }
71
+ return JSON.stringify(value)
72
+ }
73
+
74
+ /** 对除 checksum 外的全部字段做 sha256:返回 'sha256:<hex>'。 */
75
+ export function computeChecksum(entry) {
76
+ const body = {}
77
+ for (const [key, value] of Object.entries(isObject(entry) ? entry : {})) {
78
+ if (key === 'checksum') continue
79
+ body[key] = value
80
+ }
81
+ const hex = crypto.createHash('sha256').update(stableStringify(body), 'utf8').digest('hex')
82
+ return 'sha256:' + hex
83
+ }
84
+
85
+ /** 校验 checksum;无 checksum 也算失败(坏版判定从严)。 */
86
+ export function verifyChecksum(entry) {
87
+ if (!isObject(entry) || typeof entry.checksum !== 'string' || !entry.checksum) return false
88
+ try {
89
+ return entry.checksum === computeChecksum(entry)
90
+ } catch (_err) {
91
+ return false
92
+ }
93
+ }
94
+
95
+ /** 归档根目录(<home>/dsh-progress-archive)。 */
96
+ export function archiveRoot(home) {
97
+ return path.join(String(home || ''), ARCHIVE_ROOT_DIR)
98
+ }
99
+
100
+ /** 目录名用 sha256(sessionId) 前 16 hex:避开 Windows 路径长度与非法字符。 */
101
+ export function archiveKey(sessionId) {
102
+ return crypto.createHash('sha256').update(String(sessionId || ''), 'utf8').digest('hex').slice(0, 16)
103
+ }
104
+
105
+ export function archiveDir(home, sessionId) {
106
+ return path.join(archiveRoot(home), archiveKey(sessionId))
107
+ }
108
+
109
+ export function archiveIndexPath(dir) {
110
+ return path.join(String(dir || ''), 'index.json')
111
+ }
112
+
113
+ /** v000007.json —— 6 位零填充,字典序即版本序。 */
114
+ export function archiveVersionPath(dir, seq) {
115
+ const n = Math.max(0, Math.trunc(Number(seq) || 0))
116
+ return path.join(String(dir || ''), 'v' + String(n).padStart(6, '0') + '.json')
117
+ }
118
+
119
+ function archiveMarkdownPath(dir, seq) {
120
+ return archiveVersionPath(dir, seq).replace(/\.json$/, '.md')
121
+ }
122
+
123
+ /** 日报式一行:rev 12 · 45% 3/7 · 2h前(缺值段省略)。 */
124
+ export function archiveLine(archive) {
125
+ if (!isArchive(archive)) return ''
126
+ const s = archive.board.summary
127
+ const bits = ['rev ' + archive.revision, s.percent + '% ' + s.done + '/' + s.total]
128
+ const age = ageLabel(archive.at)
129
+ if (age) bits.push(age)
130
+ return bits.join(' · ')
131
+ }
132
+
133
+ export function ageLabel(at, nowMs = Date.now()) {
134
+ const t = Number(at) || 0
135
+ if (t <= 0) return ''
136
+ const delta = Math.max(0, Number(nowMs) - t)
137
+ if (delta < 60 * 1000) return '刚刚'
138
+ if (delta < 60 * 60 * 1000) return Math.floor(delta / 60000) + 'm前'
139
+ if (delta < 48 * 60 * 60 * 1000) return Math.floor(delta / 3600000) + 'h前'
140
+ return Math.floor(delta / 86400000) + 'd前'
141
+ }
142
+
143
+ function readJson(file) {
144
+ try {
145
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
146
+ } catch (_err) {
147
+ return null
148
+ }
149
+ }
150
+
151
+ /** 读 index.json;缺失/损坏返回 null(调用方按「目录存在但索引坏了」处理)。 */
152
+ export function readIndex(dir) {
153
+ const idx = readJson(archiveIndexPath(dir))
154
+ if (!isObject(idx)) return null
155
+ if (!Number.isFinite(num(idx.headSeq))) return null
156
+ if (!Array.isArray(idx.versions)) return null
157
+ return idx
158
+ }
159
+
160
+ function writeIndex(dir, index) {
161
+ const target = archiveIndexPath(dir)
162
+ const tmp = target + '.tmp-' + process.pid + '-' + crypto.randomBytes(4).toString('hex')
163
+ fs.writeFileSync(tmp, JSON.stringify(index))
164
+ fs.renameSync(tmp, target)
165
+ }
166
+
167
+ /** 磁盘上的版本号(升序);坏文件名忽略。 */
168
+ export function listVersionSeqs(dir) {
169
+ let names = []
170
+ try {
171
+ names = fs.readdirSync(dir)
172
+ } catch (_err) {
173
+ return []
174
+ }
175
+ const seqs = []
176
+ for (const name of names) {
177
+ const m = /^v(\d{6})\.json$/.exec(name)
178
+ if (m) seqs.push(Number(m[1]))
179
+ }
180
+ return seqs.sort((a, b) => a - b)
181
+ }
182
+
183
+ /** 读单版并做形状 + checksum 校验;坏版返回 null。 */
184
+ export function readArchiveVersion(dir, seq) {
185
+ const entry = readJson(archiveVersionPath(dir, seq))
186
+ if (!isArchive(entry)) return null
187
+ return entry
188
+ }
189
+
190
+ /**
191
+ * 写出一个版本(seq 由索引 head + 1 分配,撞号则顺延),再原子更新 index.json。
192
+ * entry 可省略 seq(本函数分配并回填);返回 { seq, path, bytes, entry, index }。
193
+ */
194
+ export function writeArchiveVersion(dir, entry) {
195
+ if (!isObject(entry)) throw new Error('archive entry 必须是对象')
196
+ fs.mkdirSync(dir, { recursive: true })
197
+ const index = readIndex(dir) || {
198
+ version: ARCHIVE_VERSION,
199
+ sessionId: str(entry.sessionId) || '',
200
+ headSeq: 0,
201
+ updatedAt: 0,
202
+ versions: [],
203
+ }
204
+ let seq = Math.max(
205
+ Math.trunc(num(index.headSeq) || 0),
206
+ ...index.versions.map((v) => Math.trunc(num(v && v.seq) || 0)),
207
+ ) + 1
208
+ if (seq < 1) seq = 1
209
+ while (fs.existsSync(archiveVersionPath(dir, seq))) seq += 1
210
+
211
+ const record = { ...entry, version: ARCHIVE_VERSION, seq }
212
+ record.checksum = computeChecksum(record)
213
+ const target = archiveVersionPath(dir, seq)
214
+ const tmp = target + '.tmp-' + process.pid + '-' + crypto.randomBytes(4).toString('hex')
215
+ fs.writeFileSync(tmp, JSON.stringify(record))
216
+ fs.renameSync(tmp, target) // 先版本文件(原子)
217
+ try {
218
+ fs.writeFileSync(archiveMarkdownPath(dir, seq), renderMarkdown(record)) // 人读版,失败不算失败
219
+ } catch (_err) {}
220
+ const bytes = Buffer.byteLength(JSON.stringify(record))
221
+ const versions = index.versions
222
+ .filter((v) => Math.trunc(num(v && v.seq) || 0) !== seq)
223
+ .concat([{ seq, at: Math.trunc(num(record.at) || 0), revision: Math.trunc(num(record.revision) || 0), reason: str(record.reason) || '', checksum: record.checksum, bytes }])
224
+ .sort((a, b) => a.seq - b.seq)
225
+ const nextIndex = {
226
+ version: ARCHIVE_VERSION,
227
+ sessionId: str(entry.sessionId) || str(index.sessionId) || '',
228
+ headSeq: seq,
229
+ updatedAt: Date.now(),
230
+ versions,
231
+ }
232
+ writeIndex(dir, nextIndex) // 后索引(原子)
233
+ return { seq, path: target, bytes, entry: record, index: nextIndex }
234
+ }
235
+
236
+ /**
237
+ * 恢复目标:head → head-1 → null。have 可为版本号数组或 (seq)=>boolean。
238
+ * 只走两跳:更老的版本属审计需求,不在本归档的承诺范围(见 spec 非目标)。
239
+ */
240
+ export function pickRestoreTarget(index, have) {
241
+ if (!isObject(index)) return null
242
+ const head = Math.trunc(num(index.headSeq) || 0)
243
+ if (head < 1) return null
244
+ const present = typeof have === 'function' ? have : (seq) => Array.isArray(have) && have.includes(seq)
245
+ if (present(head)) return head
246
+ if (head - 1 >= 1 && present(head - 1)) return head - 1
247
+ return null
248
+ }
249
+
250
+ /**
251
+ * 保留策略:head 与 head-1 永不删;其余版本「age ≤ keepDays 且总数 < keep」才留。
252
+ * 删多余 .json/.md 后原子重写 index.json,返回 { kept, removed }。
253
+ */
254
+ export function pruneArchives(dir, keep = ARCHIVE_KEEP_VERSIONS, keepDays = ARCHIVE_KEEP_DAYS, nowMs = Date.now()) {
255
+ const index = readIndex(dir)
256
+ const files = listVersionSeqs(dir)
257
+ if (!index && files.length === 0) return { kept: [], removed: [] }
258
+ const maxKeep = Math.max(2, Math.trunc(Number(keep) || ARCHIVE_KEEP_VERSIONS))
259
+ const maxAgeMs = Math.max(0, num(keepDays) === undefined ? ARCHIVE_KEEP_DAYS : keepDays) * 86400000
260
+ const headSeq = index ? Math.trunc(num(index.headSeq) || 0) : Math.max(0, ...files)
261
+ const meta = new Map()
262
+ for (const v of (index && Array.isArray(index.versions) ? index.versions : [])) {
263
+ const seq = Math.trunc(num(v && v.seq) || 0)
264
+ if (seq) meta.set(seq, v)
265
+ }
266
+ const keepSet = new Set()
267
+ if (headSeq > 0) keepSet.add(headSeq)
268
+ if (headSeq > 1) keepSet.add(headSeq - 1)
269
+ const kept = files.filter((seq) => keepSet.has(seq))
270
+ const candidates = files.filter((seq) => !keepSet.has(seq)).sort((a, b) => b - a)
271
+ for (const seq of candidates) {
272
+ if (kept.length >= maxKeep) break
273
+ const at = Math.trunc(num(meta.get(seq) && meta.get(seq).at) || 0) || mtimeOf(dir, seq)
274
+ if (at > 0 && nowMs - at > maxAgeMs) break // 新的都超期,更老的只会更超期
275
+ kept.push(seq)
276
+ }
277
+ const keptSet = new Set(kept)
278
+ const removed = []
279
+ for (const seq of files) {
280
+ if (keptSet.has(seq)) continue
281
+ removed.push(seq)
282
+ try { fs.unlinkSync(archiveVersionPath(dir, seq)) } catch (_err) {}
283
+ try { fs.unlinkSync(archiveMarkdownPath(dir, seq)) } catch (_err) {}
284
+ }
285
+ if (index) {
286
+ const versions = (Array.isArray(index.versions) ? index.versions : [])
287
+ .filter((v) => keptSet.has(Math.trunc(num(v && v.seq) || 0)))
288
+ try {
289
+ writeIndex(dir, { ...index, version: ARCHIVE_VERSION, updatedAt: Date.now(), versions })
290
+ } catch (_err) {}
291
+ }
292
+ return { kept: kept.slice().sort((a, b) => a - b), removed: removed.sort((a, b) => a - b) }
293
+ }
294
+
295
+ function mtimeOf(dir, seq) {
296
+ try {
297
+ return Math.trunc(fs.statSync(archiveVersionPath(dir, seq)).mtimeMs)
298
+ } catch (_err) {
299
+ return 0
300
+ }
301
+ }
302
+
303
+ /**
304
+ * 裁剪到 maxBytes:先砍 doneSoFar 尾部、再砍 filesTouched、再砍 nextItems,
305
+ * 仍超限则减 board.items 与 lastTurn.summary,标 truncated:true。
306
+ */
307
+ export function truncateArchive(entry, maxBytes = ARCHIVE_MAX_BYTES) {
308
+ const limit = Math.trunc(num(maxBytes)) > 0 ? Math.trunc(num(maxBytes)) : ARCHIVE_MAX_BYTES
309
+ const out = { ...entry, handoff: { ...(isObject(entry.handoff) ? entry.handoff : {}) } }
310
+ const size = () => Buffer.byteLength(JSON.stringify(out))
311
+ if (size() <= limit) return out
312
+ out.truncated = true
313
+ for (const key of ['doneSoFar', 'filesTouched', 'nextItems']) {
314
+ const list = out.handoff[key]
315
+ if (!Array.isArray(list)) continue
316
+ out.handoff[key] = list.slice()
317
+ while (out.handoff[key].length > 0 && size() > limit) out.handoff[key].pop()
318
+ }
319
+ if (size() > limit && Array.isArray(out.board && out.board.items)) {
320
+ out.board = { ...out.board }
321
+ out.board.items = out.board.items.slice()
322
+ for (const cap of [20, 10, 5]) {
323
+ if (size() <= limit) break
324
+ out.board.items = out.board.items.slice(0, cap)
325
+ }
326
+ }
327
+ if (size() > limit && isObject(out.handoff.lastTurn)) {
328
+ out.handoff = { ...out.handoff, lastTurn: { ...out.handoff.lastTurn, summary: '' } }
329
+ }
330
+ return out
331
+ }
332
+
333
+ /** 人读版(面板/排障;不进模型上下文)。 */
334
+ export function renderMarkdown(archive) {
335
+ const lines = []
336
+ lines.push('# ' + ((archive.task && archive.task.title) || '未命名任务'))
337
+ lines.push('')
338
+ lines.push('- 版本:v' + String(archive.seq).padStart(6, '0') + ' · rev ' + archive.revision + ' · ' + (archive.reason || '') + ' · ' + new Date(Number(archive.at) || Date.now()).toISOString())
339
+ const s = (archive.board && archive.board.summary) || {}
340
+ lines.push('- 板:' + (s.percent || 0) + '% ' + (s.done || 0) + '/' + (s.total || 0) + '(doing ' + (s.doing || 0) + ',todo ' + (s.todo || 0) + ',blocked ' + (s.blocked || 0) + ')')
341
+ const h = isObject(archive.handoff) ? archive.handoff : {}
342
+ if (h.objective) {
343
+ lines.push('')
344
+ lines.push('## 目标')
345
+ lines.push(h.objective)
346
+ }
347
+ for (const [key, title] of [['inFlight', '正在做'], ['nextItems', '接下来'], ['doneSoFar', '已完成'], ['filesTouched', '涉及文件']]) {
348
+ const list = h[key]
349
+ if (!Array.isArray(list) || list.length === 0) continue
350
+ lines.push('')
351
+ lines.push('## ' + title)
352
+ for (const line of list) lines.push('- ' + (typeof line === 'string' ? line : JSON.stringify(line)))
353
+ }
354
+ lines.push('')
355
+ return lines.join('\n')
356
+ }
package/client.js CHANGED
@@ -14,16 +14,17 @@ window.__ModuleLoader__.load({
14
14
  const BS_TAB_ID = 'dsh-progress-union:board'
15
15
  const PROGRESS_EVENT = 'progress-union:changed';
16
16
 
17
- /* __STAR_INLINE_BEGIN__ — 手写内联 star 面板(v1→v2→v3 阶梯,_tools/star-row 计划)。
17
+ /* __STAR_INLINE_BEGIN__ — 手写内联 star 面板(v1→v2→v3→v4 阶梯,_tools/star-row 计划)。
18
18
  * 本仓浏览器半边是手写 JS/无 TS 构建,插不进 star-row-copy.ts,故内联等价实现
19
19
  * (沿用 dsh-preset-doctor 先例)。STAR_GEN / STAR_VERSION 由 _tools/star-row/ladder.mjs
20
- * 每次发版改写:v1 = 话术+★CTA+×隐藏;v2 = 一行页脚点过即收;v3 = 两行页脚「我已支持」才收。
20
+ * 每次发版改写:v1 = 话术+★CTA+×隐藏;v2 = 一行页脚点过即收;v3 = 两行页脚「我已支持」才收
21
+ * (冻结版见 gens/inline.star-panel.v3.js);v4 = 三动作描边胶囊 + v4.supported 键。
21
22
  * 契约由本仓 tests/star-panel.test.* 锁定(★/💬 跳转语义、写键、旧键不迁值、10 语)。 */
22
23
  (function () {
23
24
  var REPO_URL = "https://github.com/drscrewdriver/dsh-progress-union";
24
25
  var STAR_NS = "progress-union";
25
- var STAR_GEN = "v3"; /* ladder:gen */
26
- var STAR_VERSION = "0.5.14"; /* ladder:ver */
26
+ var STAR_GEN = "v4"; /* ladder:gen */
27
+ var STAR_VERSION = "0.6.1"; /* ladder:ver */
27
28
  var LANGS = ["zh", "en", "ja", "ko", "fr", "de", "it", "ru", "es", "pt"];
28
29
 
29
30
  // 三代共享:GitHub 单色 mark(octicon 轮廓,fill 随 currentColor)。
@@ -67,6 +68,7 @@ window.__ModuleLoader__.load({
67
68
  var K_V1 = "dsh.star." + STAR_NS + ".dismissed";
68
69
  var K_V2 = "dsh.star." + STAR_NS + ".v2.dismissed";
69
70
  var K_V3 = "dsh.star." + STAR_NS + ".v3.supported";
71
+ var K_V4 = "dsh.star." + STAR_NS + ".v4.supported";
70
72
  function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }
71
73
  function lsSet(k) { try { localStorage.setItem(k, "1"); } catch (e) {} }
72
74
  function lsRm(k) { try { if (localStorage.getItem(k) !== null) localStorage.removeItem(k); } catch (e) {} }
@@ -95,6 +97,12 @@ window.__ModuleLoader__.load({
95
97
  if (tag === "a" && href) { el.href = href; el.target = "_blank"; el.rel = "noopener noreferrer"; }
96
98
  el.textContent = text; return el;
97
99
  }
100
+ function footBtn(d, tag, text, href) {
101
+ var el = d.createElement(tag); el.className = "dsh-star-btn";
102
+ if (tag === "a" && href) { el.href = href; el.target = "_blank"; el.rel = "noopener noreferrer"; }
103
+ if (tag === "button") el.type = "button";
104
+ el.textContent = text; return el;
105
+ }
98
106
  function dot(d) { var x = d.createElement("span"); x.className = "dsh-star-dot"; x.textContent = "·"; return x; }
99
107
 
100
108
  function render(d) {
@@ -138,48 +146,57 @@ window.__ModuleLoader__.load({
138
146
  st2.addEventListener("click", collapse2); is2.addEventListener("click", collapse2);
139
147
  return r2;
140
148
  }
141
- // v3
149
+ // v4(v3 结构 + 三动作描边胶囊;STAR_GEN 仍为 v3 的仓走本分支即升级为 v4 语义)
142
150
  inject(d, "dsh-star-foot-style", FOOT +
143
- ".dsh-star-foot{display:flex;flex-direction:column;align-items:flex-start;gap:2px}.dsh-star-foot-line{display:flex;align-items:center;gap:6px;flex-wrap:wrap;min-width:0}" +
144
- ".dsh-star-foot .dsh-star-support{appearance:none;border:0;background:none;padding:0;margin:0;font:inherit;line-height:inherit;color:inherit;cursor:pointer;opacity:.72;text-decoration:underline;text-underline-offset:2px}.dsh-star-foot .dsh-star-support:hover{opacity:1}" +
145
- ".dsh-star-foot-collapsed{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px;line-height:1.6;color:inherit;opacity:.72;margin-top:10px}.dsh-star-foot-collapsed a{color:inherit;text-decoration:none}.dsh-star-foot-collapsed a:hover{text-decoration:underline}");
151
+ ".dsh-star-foot{display:flex;flex-direction:column;align-items:flex-start;gap:6px;opacity:.85}.dsh-star-foot-line{display:flex;align-items:center;gap:6px;flex-wrap:wrap;min-width:0}" +
152
+ ".dsh-star-foot .dsh-star-ask{opacity:.8}" +
153
+ ".dsh-star-btn{display:inline-flex;align-items:center;gap:4px;flex:none;appearance:none;font:inherit;font-size:11px;line-height:1.5;padding:2px 10px;border-radius:999px;border:1px solid currentColor;background:transparent;color:inherit;cursor:pointer;text-decoration:none;opacity:.75}" +
154
+ ".dsh-star-btn:hover{opacity:1;background:rgba(127,127,127,.12);text-decoration:none}" +
155
+ ".dsh-star-foot-collapsed{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px;line-height:1.6;color:inherit;opacity:.72;margin-top:10px}" +
156
+ ".dsh-star-foot-collapsed .dsh-star-row{display:inline-flex;align-items:center;gap:7px;color:inherit;text-decoration:none}" +
157
+ ".dsh-star-foot-collapsed a{color:inherit;text-decoration:none}");
146
158
  var n3 = neutralLink(d);
147
- lsRm(K_V2); lsRm(K_V1); // v3 加载即清两旧键,不迁值
159
+ lsRm(K_V3); lsRm(K_V2); lsRm(K_V1); // v4 加载即清三旧键,不迁值
148
160
  var iss = issuesUrl();
149
- if (lsGet(K_V3) === "1") {
161
+ if (lsGet(K_V4) === "1") {
150
162
  var box = d.createElement("div"); box.className = "dsh-star-foot-collapsed";
151
163
  n3.className = "dsh-star-row"; box.appendChild(n3);
152
- box.appendChild(footItem(d, "a", "💬 " + (ISSUE_TXT[L] || ISSUE_TXT.en), iss));
164
+ box.appendChild(footBtn(d, "a", "💬 " + (ISSUE_TXT[L] || ISSUE_TXT.en), iss));
153
165
  return box;
154
166
  }
155
167
  var r3 = d.createElement("div"); r3.className = "dsh-star-foot";
156
168
  var l1 = d.createElement("div"); l1.className = "dsh-star-foot-line";
157
169
  var v3 = d.createElement("span"); v3.className = "dsh-star-ver"; v3.textContent = "v" + STAR_VERSION; l1.appendChild(v3);
158
170
  l1.appendChild(dot(d)); l1.appendChild(footItem(d, "span", FASK[L] || FASK.en));
159
- l1.appendChild(footItem(d, "a", "⭐ " + (STAR_TXT[L] || STAR_TXT.en), REPO_URL));
171
+ l1.appendChild(footBtn(d, "a", "⭐ " + (STAR_TXT[L] || STAR_TXT.en), REPO_URL));
160
172
  l1.appendChild(dot(d));
161
- var sup = d.createElement("button"); sup.type = "button"; sup.className = "dsh-star-support"; sup.textContent = SUPPORT_TXT[L] || SUPPORT_TXT.en;
173
+ var sup = d.createElement("button"); sup.type = "button"; sup.className = "dsh-star-btn dsh-star-support"; sup.textContent = SUPPORT_TXT[L] || SUPPORT_TXT.en;
162
174
  sup.addEventListener("click", function () {
163
- lsSet(K_V3);
175
+ lsSet(K_V4);
164
176
  if (r3.parentNode) {
165
177
  var b = d.createElement("div"); b.className = "dsh-star-foot-collapsed";
166
178
  var nn = neutralLink(d); nn.className = "dsh-star-row"; b.appendChild(nn);
167
- b.appendChild(footItem(d, "a", "💬 " + (ISSUE_TXT[L] || ISSUE_TXT.en), iss));
179
+ b.appendChild(footBtn(d, "a", "💬 " + (ISSUE_TXT[L] || ISSUE_TXT.en), iss));
168
180
  r3.parentNode.replaceChild(b, r3);
169
181
  }
170
182
  });
171
183
  l1.appendChild(sup);
172
184
  var l2 = d.createElement("div"); l2.className = "dsh-star-foot-line";
173
- l2.appendChild(footItem(d, "a", "💬 " + (ISSUE_TXT[L] || ISSUE_TXT.en), iss));
185
+ l2.appendChild(footBtn(d, "a", "💬 " + (ISSUE_TXT[L] || ISSUE_TXT.en), iss));
174
186
  r3.appendChild(l1); r3.appendChild(l2);
175
187
  return r3;
176
188
  }
177
189
 
178
190
  // 暴露给宿主挂载:返回一个 DOM 元素,由各仓设置卡卡尾 append。
179
- window.__StarPanel = { mount: function (doc) { return render(doc || document); }, GEN: STAR_GEN, NS: STAR_NS };
191
+ // 部分仓(如 skill-harbor)的单测会在 Node 里 import 本模块,无 window 时只定义不导出全局。
192
+ var __starApi = { mount: function (doc) { return render(doc || (typeof document !== "undefined" ? document : null)); }, GEN: STAR_GEN, NS: STAR_NS };
193
+ if (typeof window !== "undefined") window.__StarPanel = __starApi;
194
+ if (typeof globalThis !== "undefined") globalThis.__StarPanel = __starApi;
180
195
  })();
181
196
  /* __STAR_INLINE_END__ */
182
197
 
198
+ ;
199
+
183
200
 
184
201
 
185
202
  function broadcastProgress(sessionId, snapshot) {