dsh-progress-union 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  本项目的所有值得记录的变更都写在这里。版本号遵循语义化版本。
4
4
 
5
+ ## 0.4.0 (2026-11-26)
6
+
7
+ **锚点开放 `./anchor` 子路径与订阅面,附消费者指南。**
8
+
9
+ - feat(anchor):新增 `./anchor` 子路径(零依赖导出 `ANCHOR_VERSION` / `ANCHOR_ROUTES` / `BOARD_STATUSES` / `isAnchor` / `anchorLine` 常量、校验与单行摘要)供其他插件握手消费;`progressAnchor` service 新增 `subscribe(listener, sessionId?)` 订阅(回调 `{sessionId, revision}`,同一 revision 去重、退订 `off()`)。
10
+ - 新增 `docs/consumer-guide.md`:三种读法(service / HTTP / sessionProjection)、版本握手、订阅退订、四条消费规则、curl 示例与工具函数用法;README 增「给其他插件用」小节指向该指南。
11
+
12
+ ## 0.3.0 (2026-11-26)
13
+
14
+ **板变更镜像到官方 todo(可关)+ 助手冲突裁决。**
15
+
16
+ - feat(todo):板 → 官方 todo 镜像 + 助手冲突裁决。设置页三段开关 `off` / `mirror` / `reconcile`(默认 **`reconcile`**)——默认从 `mirror` 改为 `reconcile` 属**行为变更**:外部 todo 改动会触发助手裁决,`adopt-todo` 会覆盖模型写的清单,不想要就在设置页关掉或切 `off`;`mirror` 只做板 → todo 单向镜像;`reconcile` 还会据板与最近输出/动作做三选一裁决(adopt-todo / keep-board / merge)。
17
+ - hash 回环防护:自家镜像写入的 todos 由稳定内容哈希识别,命中只更新 ETA 原料、不触发裁决。
18
+ - 200ms 去抖:写板后调度镜像按 `mirrorThrottleMs`(默认 200ms)合并突发变更,避免逐帧写 todo。
19
+ - 助手不可用时只报漂移:无 registered/direct 助手或调用失败/超时/坏 JSON 时,两侧都不改,只在观察块记 `[todo 漂移]` 行,不阻断板与主流程。
20
+
5
21
  ## 0.1.8 (2026-11-26)
6
22
 
7
23
  **修复:registered 通道写错 DSH LLM 契约;配置面搬回宿主设置页。**
package/README.md CHANGED
@@ -62,6 +62,17 @@ Schema(version=1,字段名冻结):
62
62
 
63
63
  同态保证:同 `(revision, steps, now)` 锚点逐字节相等(无时间戳漂移、无随机),可直接当指纹用。
64
64
 
65
+ ### 给其他插件用
66
+
67
+ 上面的契约是"是什么",**怎么在自己的插件里读/订阅/降级/握手**见 [docs/consumer-guide.md](docs/consumer-guide.md)(三种读法、版本握手、订阅退订、四条消费规则、curl 示例、`isAnchor`/`anchorLine` 用法)。零依赖的 `./anchor` 子路径自 0.4.0 起可用:
68
+
69
+ ```js
70
+ import { ANCHOR_VERSION, ANCHOR_ROUTES, isAnchor, anchorLine } from 'dsh-progress-union/anchor'
71
+ // ANCHOR_VERSION 握手 · ANCHOR_ROUTES 三条只读路由 · isAnchor 形状校验 · anchorLine 单行摘要(形如 45% 3/7 · ETA 6m · stale 12m)
72
+ ```
73
+
74
+ 自 **v0.3.0** 起,板变更会镜像到宿主官方 todo(设置页三段开关 `off` / `mirror` / `reconcile`,默认 `reconcile` 会覆盖模型写的清单,属行为变更,可在设置页关掉或切到 `off`);详见 [CHANGELOG](CHANGELOG.md#030-2026-11-26)。
75
+
65
76
  ## 使用
66
77
 
67
78
  - `/progress`(on)/ `/progress off`:语义与 board 原版一致——开过一次持续启用,收起侧栏不关闭。
package/anchor.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * dsh-progress-union/anchor — 零依赖锚点契约,供其他插件 import。
3
+ * 版本握手:consumer 读 ANCHOR_VERSION,与 service.version 相等才解析字段。
4
+ */
5
+ export const ANCHOR_VERSION = 1
6
+
7
+ export const ANCHOR_ROUTES = {
8
+ anchor: '/progress-union/anchor',
9
+ snapshot: '/progress-union/snapshot',
10
+ status: '/dsh-progress/status',
11
+ }
12
+
13
+ export const BOARD_STATUSES = ['todo', 'doing', 'done', 'blocked']
14
+
15
+ function isObject(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
17
+ }
18
+
19
+ /** 形状校验:新旧快照都能过(version/board/time 必备,不挑新增字段)。 */
20
+ export function isAnchor(v) {
21
+ if (!isObject(v)) return false
22
+ if (typeof v.version !== 'number' || typeof v.sessionId !== 'string') return false
23
+ if (!isObject(v.board) || typeof v.board.enabled !== 'boolean' || !isObject(v.board.summary)) return false
24
+ if (!isObject(v.time)) return false
25
+ const s = v.board.summary
26
+ return ['total', 'done', 'percent'].every((k) => typeof s[k] === 'number')
27
+ }
28
+
29
+ /** 单行摘要:45% 3/7 · ETA 6m · stale 12m(缺值段省略)。 */
30
+ export function anchorLine(anchor) {
31
+ if (!isAnchor(anchor)) return ''
32
+ const s = anchor.board.summary
33
+ const bits = [`${s.percent}% ${s.done}/${s.total}`]
34
+ const eta = Number(anchor.time && anchor.time.etaMin)
35
+ if (Number.isFinite(eta) && eta > 0) bits.push(`ETA ${Math.round(eta)}m`)
36
+ const stale = Number(anchor.time && anchor.time.staleMin)
37
+ if (Number.isFinite(stale) && stale > 0) bits.push(`stale ${Math.round(stale)}m`)
38
+ return bits.join(' · ')
39
+ }
package/client.js CHANGED
@@ -245,6 +245,15 @@ window.__ModuleLoader__.load({
245
245
  setAutoSyncCurrent: '自动同步 current',
246
246
  setAutoSyncThrottleMs: '自动同步节流(毫秒)',
247
247
  setMaxItems: '清单条目上限',
248
+ setTodoGroup: '官方 todo 同步',
249
+ setTodoHint: '板变更后自动镜像到宿主官方 todo 清单(会覆盖模型写的清单,谨慎开启);外部改动可由辅助 LLM 裁决。',
250
+ setTodoSync: '同步模式',
251
+ setTodoOff: '关闭(不写 todo)',
252
+ setTodoMirror: '只镜像(板 → todo)',
253
+ setTodoReconcile: '镜像 + 裁决',
254
+ setTodoReconcileMs: '裁决最小间隔(毫秒)',
255
+ setTodoThrottleMs: '镜像去抖(毫秒)',
256
+ setTodoWriteNote: '写入事件:agent.session.append(\'todo/write\', { todos })(只读说明)',
248
257
  setSaved: '已保存',
249
258
  setFailed: '保存失败',
250
259
  setReadOnly: '当前 config 不可写',
@@ -402,7 +411,16 @@ window.__ModuleLoader__.load({
402
411
  setMaxIdleMs: 'Overdue time threshold (ms)',
403
412
  setAutoSyncCurrent: 'Auto-sync current',
404
413
  setAutoSyncThrottleMs: 'Auto-sync throttle (ms)',
405
- setMaxItems: 'Checklist item cap',
414
+ setMaxItems: 'Max checklist items',
415
+ setTodoGroup: 'Official todo sync',
416
+ setTodoHint: 'Mirror the board to the host official todo list after every board change (overwrites the model-written list — enable with care); external edits can be reconciled by the assistant LLM.',
417
+ setTodoSync: 'Sync mode',
418
+ setTodoOff: 'Off (no todo writes)',
419
+ setTodoMirror: 'Mirror only (board → todo)',
420
+ setTodoReconcile: 'Mirror + reconcile',
421
+ setTodoReconcileMs: 'Reconcile min interval (ms)',
422
+ setTodoThrottleMs: 'Mirror debounce (ms)',
423
+ setTodoWriteNote: 'Write event: agent.session.append(\'todo/write\', { todos }) (read-only)',
406
424
  setSaved: 'Saved',
407
425
  setFailed: 'Save failed',
408
426
  setReadOnly: 'Current config is not writable',
@@ -1791,12 +1809,13 @@ window.__ModuleLoader__.load({
1791
1809
  const asObject = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {})
1792
1810
  const assistant = asObject(value.assistant)
1793
1811
  const observer = asObject(value.observer)
1812
+ const todo = asObject(value.todo)
1794
1813
 
1795
1814
  // 文本/数字走草稿(避免逐字符写盘),开关与分段直接落盘(即时生效)。
1796
1815
  const readField = (group, key, fallback) => {
1797
1816
  const bucket = draft[group]
1798
1817
  if (bucket && Object.prototype.hasOwnProperty.call(bucket, key)) return bucket[key]
1799
- const stored = (group === 'assistant' ? assistant : observer)[key]
1818
+ const stored = (group === 'assistant' ? assistant : group === 'todo' ? todo : observer)[key]
1800
1819
  return stored === undefined || stored === null ? fallback : stored
1801
1820
  }
1802
1821
  const setDraftField = (group, key, v) => setDraft((prev) => ({ ...prev, [group]: { ...(prev[group] || {}), [key]: v } }))
@@ -1827,8 +1846,10 @@ window.__ModuleLoader__.load({
1827
1846
  const flush = async () => {
1828
1847
  const aKeys = dirtyKeys('assistant')
1829
1848
  const oKeys = dirtyKeys('observer')
1849
+ const todoKeys = dirtyKeys('todo')
1830
1850
  if (aKeys.length) await commit('assistant', { ...assistant, ...draft.assistant })
1831
1851
  if (oKeys.length) await commit('observer', { ...observer, ...draft.observer })
1852
+ if (todoKeys.length) await commit('todo', { ...todo, ...draft.todo })
1832
1853
  setDraft({})
1833
1854
  }
1834
1855
 
@@ -1882,7 +1903,7 @@ window.__ModuleLoader__.load({
1882
1903
  },
1883
1904
  })
1884
1905
 
1885
- const hasDirty = dirtyKeys('assistant').length > 0 || dirtyKeys('observer').length > 0
1906
+ const hasDirty = dirtyKeys('assistant').length > 0 || dirtyKeys('observer').length > 0 || dirtyKeys('todo').length > 0 || Object.prototype.hasOwnProperty.call(draft, 'todoSync')
1886
1907
  const mode = readField('assistant', 'mode', '')
1887
1908
  const authority = readField('assistant', 'authority', 'both')
1888
1909
 
@@ -1923,6 +1944,20 @@ window.__ModuleLoader__.load({
1923
1944
  h(SettingsRow, { label: t('setAutoSyncThrottleMs') }, numberInput('observer', 'autoSyncThrottleMs', 60000, 1000, 'ms')),
1924
1945
  h(SettingsRow, { label: t('setMaxItems') }, numberInput('observer', 'maxItems', 12, 1, '项')),
1925
1946
  ),
1947
+ h(
1948
+ SettingsCard,
1949
+ { title: t('setTodoGroup'), badge: t('setTodoSync'), hint: t('setTodoHint'), defaultOpen: false },
1950
+ h(SettingsRow, { label: t('setTodoSync') },
1951
+ h(SettingsSegment, {
1952
+ value: Object.prototype.hasOwnProperty.call(draft, 'todoSync') ? draft.todoSync : (value.todoSync === undefined ? 'reconcile' : value.todoSync),
1953
+ disabled: !writable || busy,
1954
+ options: [['off', t('setTodoOff')], ['mirror', t('setTodoMirror')], ['reconcile', t('setTodoReconcile')]],
1955
+ onChange: (v) => { setDraft((prev) => ({ ...prev, todoSync: v })); void commit('todoSync', v) },
1956
+ })),
1957
+ h(SettingsRow, { label: t('setTodoReconcileMs') }, numberInput('todo', 'maxReconcileIntervalMs', 60000, 1000, 'ms')),
1958
+ h(SettingsRow, { label: t('setTodoThrottleMs') }, numberInput('todo', 'mirrorThrottleMs', 200, 1, 'ms')),
1959
+ h('div', { className: 'dsu-hint' }, t('setTodoWriteNote')),
1960
+ ),
1926
1961
  h(
1927
1962
  SettingsCard,
1928
1963
  { title: t('setApiGroup'), badge: t('setApiBadge'), hint: t('setApiHint'), defaultOpen: false },
@@ -0,0 +1,210 @@
1
+ # 消费者指南(给其他插件用)
2
+
3
+ 本文面向**在自己插件里读进度锚点**的开发者:压缩插件、观察面板、状态侧栏、外部脚本等。锚点是**只读**的——它给你"任务干到哪、时间还剩多少、用户改了什么",不给你写板的能力(写板仍走 `progress_update` / `/progress-union/action`)。
4
+
5
+ > 依赖:`dsh-progress-union >= 0.4.0`(`./anchor` 子路径与 `subscribe` 自 0.4.0 起提供)。本文所有代码均为 JS(ESM)。
6
+
7
+ ## 0. 先做版本握手,再谈字段
8
+
9
+ 锚点契约有版本号。零依赖的 `./anchor` 子路径导出握手常量与工具,消费方**先比版本,相等才解析字段**;不等就当作不认识、跳过本次数据(不要猜测字段含义,也不要崩)。
10
+
11
+ ```js
12
+ import { ANCHOR_VERSION, ANCHOR_ROUTES, isAnchor, anchorLine } from 'dsh-progress-union/anchor'
13
+
14
+ // ANCHOR_VERSION === 1(当前锚点 schema 版本)
15
+ // ANCHOR_ROUTES = { anchor:'/progress-union/anchor', snapshot:'/progress-union/snapshot', status:'/dsh-progress/status' }
16
+
17
+ function useAnchor(anchor) {
18
+ if (!anchor || anchor.version !== ANCHOR_VERSION) return // 不认识的版本:跳过
19
+ if (!isAnchor(anchor)) return // 形状不对:也跳过
20
+ // ……到这里才安全读 anchor.board / anchor.time / anchor.userEdits
21
+ }
22
+ ```
23
+
24
+ `isAnchor(v)` 是**宽松形状校验**:只要求 `version` 是数字、`sessionId` 是字符串、`board.enabled` 是布尔、`board.summary` 是对象且 `total/done/percent` 是数字、`time` 是对象;**新增字段不会让它失败**(老快照也能过)。坏数据返回 `false`,用它当第一道闸门即可。
25
+
26
+ ## 1. 三种读法
27
+
28
+ ### 1.1 同进程 service(`ctx.get('progressAnchor')`)
29
+
30
+ 最快、零 I/O。宿主通过 `ctx.provide('progressAnchor')` 提供;**服务可能缺席**(宿主版本旧、provide 面形状不符、插件未按装),此时 `ctx.get('progressAnchor')` 返回空值——**静默降级**,不要抛、不要阻塞自己的插件。
31
+
32
+ ```js
33
+ function readAnchors(ctx, sessionId) {
34
+ let service
35
+ try {
36
+ service = ctx.get && ctx.get('progressAnchor')
37
+ } catch (_err) {
38
+ service = null // 取服务本身就失败:当缺席处理
39
+ }
40
+ if (!service || typeof service.get !== 'function') return null // 静默降级
41
+
42
+ // 握手:service.version 必须与 ANCHOR_VERSION 相等
43
+ if (service.version !== ANCHOR_VERSION) return null
44
+
45
+ const one = service.get(sessionId) // 同步返回单个锚点对象
46
+ const all = service.list() // 同步返回锚点数组(多会话聚合)
47
+ // 可选第二参 atMs(复现/测试用):service.get(sid, atMs) / service.list(atMs)
48
+ return { one, all }
49
+ }
50
+ ```
51
+
52
+ - `.get(sessionId, atMs?)` / `.list(atMs?)` 都是**同步**返回,不需要 `await`。
53
+ - `service.version` 与 `ANCHOR_VERSION` 相等才解析;不等按"不认识"跳过。
54
+ - 从未启用过板的会话也会返回合法锚点:`board.enabled === false`、summary 全 0、`time.etaBasis === 'none'`。**这不是错误**。
55
+
56
+ ### 1.2 HTTP(跨进程 / 外部脚本)
57
+
58
+ 三条只读路由(路径常量见 `ANCHOR_ROUTES`):
59
+
60
+ | 路由 | 用途 | 返回 |
61
+ | --- | --- | --- |
62
+ | `GET /progress-union/anchor?sessionId=<id>[&now=<ms>]` | 锚点主出口(压缩插件用) | `{ ok: true, anchor: {…} }` |
63
+ | `GET /progress-union/snapshot?sessionId=<id>` | 板快照(槽位明细) | 板的公开快照 |
64
+ | `GET /dsh-progress/status` | 鲸程兼容状态面 | `{ ok, task, tasks, live, activeCount, config }` |
65
+
66
+ - `GET` 纯只读、零副作用;其他方法返回 405。
67
+ - `sessionId` 必填且长度 ≤ 240,缺失/非法返回 400。
68
+ - `now` 仅供复现/测试;正常消费不要传,让服务端用当前时间。
69
+ - 服务缺席(路由未注册)时请求会 404,同样按"读不到就降级"处理。
70
+
71
+ 可照抄的 curl(假设宿主本地端口 `8729`,换成你的实际端口即可):
72
+
73
+ ```bash
74
+ # 锚点主出口(把 <sid> 换成真实 sessionId)
75
+ curl -s "http://127.0.0.1:8729/progress-union/anchor?sessionId=<sid>"
76
+
77
+ # 带 jq 取锚点本体并做版本握手
78
+ curl -s "http://127.0.0.1:8729/progress-union/anchor?sessionId=<sid>" \
79
+ | jq -c '.anchor | select(.version == 1)'
80
+
81
+ # 板快照
82
+ curl -s "http://127.0.0.1:8729/progress-union/snapshot?sessionId=<sid>"
83
+
84
+ # 鲸程状态面
85
+ curl -s "http://127.0.0.1:8729/dsh-progress/status"
86
+ ```
87
+
88
+ JS 里也可以用导出的路由常量拼 URL,避免硬编码:
89
+
90
+ ```js
91
+ import { ANCHOR_ROUTES, ANCHOR_VERSION } from 'dsh-progress-union/anchor'
92
+
93
+ const res = await fetch(`http://127.0.0.1:8729${ANCHOR_ROUTES.anchor}?sessionId=${encodeURIComponent(sid)}`)
94
+ if (!res.ok) return // 降级
95
+ const { anchor } = await res.json()
96
+ if (!anchor || anchor.version !== ANCHOR_VERSION) return // 握手不过:跳过
97
+ ```
98
+
99
+ ### 1.3 sessionProjection(键 `progressAnchor`)
100
+
101
+ 插件若已注入宿主的 `sessionProjections` 注册表,可用全局多会话聚合投影,键为 **`progressAnchor`**。它**只含 revision 稳定字段**(`version / agg / sessions[]`,每会话 `sessionId/enabled/revision/summary/pendingUserChanges/steps/startedAt/boardUpdatedAt`);**时间/ETA 字段不在投影里**,要走上面的 service 或 HTTP 现读。
102
+
103
+ 判脏用 **`agg`**(聚合版本号):宿主在 `apply(state)` 里比较 `aggregateVersion() === state.agg`,相等返回同引用(不 republish),不等才重建。消费方照此判断即可:
104
+
105
+ ```js
106
+ // 伪代码:拿到投影 state 后
107
+ if (state.version !== ANCHOR_VERSION) return // 握手
108
+ if (state.agg === lastSeenAgg) return // 没脏:复用缓存
109
+ lastSeenAgg = state.agg
110
+ for (const row of state.sessions) {
111
+ // row.revision 变了才需要重新去 service/HTTP 取该会话的完整时间层
112
+ }
113
+ ```
114
+
115
+ 注册表缺席时本插件**静默不注册**,消费方读不到 `progressAnchor` 投影也属正常,按 capability absence 降级即可。
116
+
117
+ ## 2. 订阅变更(0.4.0 新增)
118
+
119
+ 不用轮询:订阅 revision 变化,收到通知再去读锚点。
120
+
121
+ ```js
122
+ import { ANCHOR_VERSION } from 'dsh-progress-union/anchor'
123
+
124
+ let service
125
+ try { service = ctx.get('progressAnchor') } catch { service = null }
126
+ if (service && service.version === ANCHOR_VERSION && typeof service.subscribe === 'function') {
127
+ const off = service.subscribe(({ sessionId, revision }) => {
128
+ // 板 revision 变了 → 此刻再去读最新锚点
129
+ const anchor = service.get(sessionId)
130
+ // ……处理 anchor
131
+ }, sessionId) // 第二参省略则订阅全部会话
132
+
133
+ // 不再需要时务必退订
134
+ // off()
135
+ }
136
+ ```
137
+
138
+ - 回调参数是 `{ sessionId, revision }`(**只有这两个字段**,不含锚点本体——拿到通知后自行 `get`)。
139
+ - **同一 revision 不重复触发**:内部按会话记住上次推送的 revision,重复读/无关事件不会回调。
140
+ - 传 `sessionId` 只听该会话;不传(或 `undefined`)听全部会话,返回的 `off()` 会退订该订阅铺开的所有会话。
141
+ - **服务缺席静默降级**:`ctx.get('progressAnchor')` 为空、版本不符、或没有 `subscribe` 方法时,不要报错,安静跳过即可。
142
+ - 订阅期间板被关掉/会话结束不会再有新 revision;退订后零回调。
143
+
144
+ ## 3. 锚点对象形状(version=1,字段名冻结)
145
+
146
+ ```json
147
+ {
148
+ "version": 1, "sessionId": "", "revision": 0, "updatedAt": 0,
149
+ "board": {
150
+ "enabled": true,
151
+ "summary": { "total": 0, "done": 0, "doing": 0, "todo": 0, "blocked": 0, "percent": 0 },
152
+ "inFlight": [ { "id": "", "title": "", "status": "doing", "percent": 0, "current": "", "next": "" } ],
153
+ "pendingUserChanges": 0
154
+ },
155
+ "time": {
156
+ "startedAt": 0, "elapsedSec": 0, "steps": 0, "etaMin": 0,
157
+ "etaBasis": "board|todo|local|prior|none", "etaP75Min": 0, "overMin": 0,
158
+ "staleMin": 0, "todoDone": 0, "todoTotal": 0
159
+ },
160
+ "userEdits": [ { "revision": 0, "at": 0, "kind": "add|edit|remove", "itemId": "", "title": "", "fields": [] } ],
161
+ "persistent": true,
162
+ "slotTrail": null
163
+ }
164
+ ```
165
+
166
+ - `board.inFlight`:doing/blocked 项的明细(≤6 条),带 `current`/`next`。
167
+ - `board.pendingUserChanges` / `userEdits`:未确认的用户改动(最近 20 条),**硬约束**,见下。
168
+ - `time.etaMin` / `etaP75Min`:ETA 中位数 / P75(分钟);`etaBasis` 说明来源(board/todo/local/prior/none);`overMin` 已超时;`staleMin` 进度中断分钟数。
169
+ - `persistent`:板状态是否持久化成功;`slotTrail` 恒为 `null`(预留位)。
170
+
171
+ ## 4. 四条消费规则(压缩/摘要场景尤其重要)
172
+
173
+ 1. **只读不写**:消费方只能 `get/list`/HTTP GET/读投影,绝不代写锚点、板或 official todo。锚点是快照,不是输入面;写板走 `progress_update`,写 todo 由本插件的 `todoSync` 机制负责。
174
+ 2. **板禁用不是错误**:`board.enabled === false` 是正常的"该会话没开板"状态,summary 全 0、`time.etaBasis === 'none'`;静默按无进度处理,不要报错或注入噪声。
175
+ 3. **字段缺失按旧版本容忍**:`isAnchor` 只校验必备骨架;新版本可能增加字段,老快照可能没有新字段。用可选链读新增字段(`anchor.time?.etaP75Min`),缺失就当 0/空,不因缺少某个字段判整个锚点非法。
176
+ 4. **不要缓存 ETA 超过 staleMin**:`staleMin > 0` 表示真实进度已中断 N 分钟,此时 `etaMin` 是基于旧进度的推算,**不要当新节奏沿用**。缓存时间以 `staleMin` 为界——陈旧 ETA 读出来只作"历史参考",不要拿它给新计划兜底。`overMin > 0` 同理要如实转述"已超预估"。
177
+
178
+ > 压缩摘要的四条细则(保护区必嵌 / userEdits 硬约束 / revision 对账 / staleMin 标注)见主 [README](../README.md#给压缩插件的锚点契约只读)。
179
+
180
+ ## 5. 单行摘要 `anchorLine`
181
+
182
+ 给状态条、日志、notifier 用的一行文本,形如:
183
+
184
+ ```
185
+ 45% 3/7 · ETA 6m · stale 12m
186
+ ```
187
+
188
+ - 格式:`<percent>% <done>/<total>` + 可选 ` · ETA <n>m`(`etaMin > 0` 才有) + 可选 ` · stale <n>m`(`staleMin > 0` 才有)。
189
+ - 值四舍五入为整数分钟;缺值段自动省略;坏形状返回空串 `''`。
190
+
191
+ ```js
192
+ import { anchorLine } from 'dsh-progress-union/anchor'
193
+
194
+ const line = anchorLine(anchor)
195
+ // '45% 3/7 · ETA 6m · stale 12m'
196
+ // 老快照/无 ETA:'80% 4/5'
197
+ // 未启用板:'0% 0/0'
198
+ if (line) statusBar.text = line
199
+ ```
200
+
201
+ ## 6. 快速自检清单
202
+
203
+ - [ ] 先用 `ANCHOR_VERSION` 握手,不等就跳过
204
+ - [ ] 同进程读包在 try/catch 里,服务缺席静默降级
205
+ - [ ] HTTP 用 `ANCHOR_ROUTES` 拼路径,`GET` + `sessionId`
206
+ - [ ] 多会话用 projection 的 `agg` 判脏,时间字段现读
207
+ - [ ] 订阅后 `off()` 退订,同 revision 不重复
208
+ - [ ] `board.enabled=false` 当正常状态
209
+ - [ ] 新增字段可选链读取,缺失容忍
210
+ - [ ] ETA 缓存不超过 `staleMin`
package/dsh.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "dsh-external/dsh-progress-union",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "main": "./index.js",
5
5
  "description": "进度结合原型:board 槽位真相源(用户可编辑、diff+ack 增量同步、staleness nudge)× 鲸程时间引擎(step 计数、ETA 三档 board>todo>local>prior、悬浮迷你条),并向压缩插件暴露只读三层进度锚点 progressAnchor(board 语义锚 + time 时间锚 + userEdits 未确认改动,service 与 HTTP 双平面)。",
6
6
  "engines": {
package/index.js CHANGED
@@ -20,6 +20,7 @@ import fs from 'node:fs'
20
20
  import os from 'node:os'
21
21
  import path from 'node:path'
22
22
  import z from '@deepseek-ai/schemastery'
23
+ import { ANCHOR_VERSION, ANCHOR_ROUTES, BOARD_STATUSES } from './anchor.js'
23
24
 
24
25
  // 设置页可见性:0.1.7+ 宿主把 composition entry 当设置节,直接按导出的 Config
25
26
  // **逐叶子**的 .volatile() 标记生成「设置 → 插件」里的表单,并把 volatile 字段以
@@ -45,14 +46,20 @@ export const Config = z.object({
45
46
  autoSyncThrottleMs: z.number().step(1000).min(0).default(60000).volatile(),
46
47
  maxItems: z.number().step(1).min(1).default(12).volatile(),
47
48
  }).default({}),
49
+ todoSync: z.union(['off', 'mirror', 'reconcile']).default('reconcile').volatile(),
50
+ todo: z.object({
51
+ maxReconcileIntervalMs: z.number().step(1000).min(0).default(60000).volatile(),
52
+ mirrorThrottleMs: z.number().step(1).min(0).default(200).volatile(),
53
+ }).default({}),
48
54
  })
49
55
 
50
56
  // —— 路由与存储标识 ——
51
57
  const ROUTE_BASE = '/progress-union'
52
58
  const LEGACY_BASE = '/progress-board' // 别名保留一版,与 board 原面板/脚本兼容
53
- const WIDGET_STATUS_ROUTE = '/dsh-progress/status'
59
+ const WIDGET_STATUS_ROUTE = ANCHOR_ROUTES.status
60
+ const ANCHOR_ROUTE = ANCHOR_ROUTES.anchor
61
+ const SNAPSHOT_ROUTE = ANCHOR_ROUTES.snapshot
54
62
  const UNIT_NAME = 'progress_union'
55
- const ANCHOR_VERSION = 1
56
63
 
57
64
  // —— board 侧限额(fork 原值,不放宽)——
58
65
  const MAX_BODY_BYTES = 256 * 1024
@@ -66,7 +73,7 @@ const MAX_NOTE = 1600
66
73
  const MAX_GROUP = 80
67
74
  const STALE_MS = 10 * 60 * 1000
68
75
  const KICKOFF_COOLDOWN_MS = 60 * 1000
69
- const STATUSES = new Set(['todo', 'doing', 'done', 'blocked'])
76
+ const STATUSES = new Set(BOARD_STATUSES)
70
77
 
71
78
  // —— /progress-goal 迷你目标域常量(自建,不复用官方 goals 域)——
72
79
  const GOAL_PHASES = new Set(['idle', 'active', 'paused', 'blocked', 'complete'])
@@ -120,6 +127,17 @@ const ASSISTANT_SYSTEM = 'You are a progress assistant for a task board in a lon
120
127
  'Emit at most 8 changes. If nothing needs changing, use {"board":{"changes":[]},"round":{...},"note":"..."}. ' +
121
128
  'Respond with the JSON object only — no prose, no code fences.'
122
129
 
130
+ // v0.3.0 todo 裁决 system:只做差异裁决,不改写事实;输出严格三选一。
131
+ const TODO_RECONCILE_SYSTEM = 'You reconcile a task board with an external official todo list. ' +
132
+ 'The board is the user-facing source of truth; the todo list is the model work list. ' +
133
+ 'Given both lists plus recent assistant output/tool activity, decide ONE resolution: ' +
134
+ '"adopt-todo" (todo is newer/correct, replace board), "keep-board" (board is correct, re-mirror it), ' +
135
+ 'or "merge" (apply incremental board.changes without dropping board facts). ' +
136
+ 'Output strictly ONE JSON object: ' +
137
+ '{"resolution":"adopt-todo|keep-board|merge","board":{"changes":[{"id"?:string,"kind"?:string,"title"?:string,"status"?:string}]},"todo":{"todos"?:[]},"note":"<one line>"}. ' +
138
+ 'For "merge", board.changes must use the same shape as the board assistant changes. ' +
139
+ 'Emit at most 8 changes. Respond with the JSON object only — no prose, no code fences.'
140
+
123
141
  // ============================================================================
124
142
  // 通用工具(board fork)
125
143
  // ============================================================================
@@ -158,6 +176,7 @@ function emptyState(sessionId) {
158
176
  updatedAt: now,
159
177
  items: [],
160
178
  userChanges: [],
179
+ todoMirror: null, // v0.3.0:自家镜像写入的 hash/at/count,回环识别用
161
180
  goal: emptyGoal(),
162
181
  }
163
182
  }
@@ -202,6 +221,54 @@ function summarize(items) {
202
221
  }
203
222
  }
204
223
 
224
+ // —— v0.3.0:板 → 官方 todo 的纯映射(content 唯一非空、in_progress ≤1)——
225
+ function boardToTodos(state, maxItems) {
226
+ const limit = Math.max(1, Number(maxItems) || 12)
227
+ const items = (Array.isArray(state && state.items) ? state.items : [])
228
+ .slice()
229
+ .sort((a, b) => a.order - b.order || a.updatedAt - b.updatedAt || a.id.localeCompare(b.id))
230
+ .slice(0, limit)
231
+ const todos = []
232
+ const seen = new Set()
233
+ let doingSeen = false
234
+ for (const item of items) {
235
+ const content = String(item && item.title || '').trim()
236
+ if (!content || seen.has(content)) continue
237
+ seen.add(content)
238
+ let status = 'pending'
239
+ if (item.status === 'done') status = 'completed'
240
+ else if (item.status === 'doing') {
241
+ if (!doingSeen) { status = 'in_progress'; doingSeen = true }
242
+ }
243
+ todos.push({ content, status })
244
+ }
245
+ return todos
246
+ }
247
+
248
+ // 稳定内容哈希(顺序敏感):同一批 todos 同值,顺序变化不同值。
249
+ function hashTodos(todos) {
250
+ const stable = JSON.stringify((Array.isArray(todos) ? todos : []).map((t) => [String(t && t.content || ''), String(t && t.status || '')]))
251
+ let h1 = 0x811c9dc5
252
+ let h2 = 0x01000193
253
+ for (let i = 0; i < stable.length; i += 1) {
254
+ const c = stable.charCodeAt(i)
255
+ h1 = Math.imul(h1 ^ c, 16777619) >>> 0
256
+ h2 = Math.imul(h2 + c + i, 2246822519) >>> 0
257
+ }
258
+ return h1.toString(36) + h2.toString(36)
259
+ }
260
+
261
+ function todoMirrorOf(state) {
262
+ const m = state && state.todoMirror
263
+ if (!isObject(m)) return null
264
+ return {
265
+ hash: typeof m.hash === 'string' ? m.hash : '',
266
+ at: finiteNumber(m.at) ?? 0,
267
+ count: finiteNumber(m.count) ?? 0,
268
+ unsupported: m.unsupported === true,
269
+ }
270
+ }
271
+
205
272
  function normalizeItems(items) {
206
273
  items.sort((a, b) => a.order - b.order || a.updatedAt - b.updatedAt || a.id.localeCompare(b.id))
207
274
  items.forEach((item, index) => {
@@ -508,6 +575,9 @@ const DEFAULT_CONFIG = {
508
575
  maxTools: 3,
509
576
  maxItems: 12,
510
577
  },
578
+ // v0.3.0:板 → 官方 todo 镜像与冲突裁决。默认 reconcile;不想要行为变更可在设置页关。
579
+ todoSync: 'reconcile', // off | mirror | reconcile
580
+ todo: { maxReconcileIntervalMs: 60_000, mirrorThrottleMs: 200 },
511
581
  // 辅助 LLM(审查/监视 + 槽位管理 + 轮次草案):
512
582
  // mode: 'registered' 走宿主 llm.stream(选已注册 llm-pi-ai provider/model);
513
583
  // 'direct' 走自建 OpenAI 兼容端点(baseUrl/apiKey/model);'' 关。
@@ -579,6 +649,25 @@ export async function apply(ctx, config) {
579
649
  return out
580
650
  }
581
651
  cfg.assistant = assistantNow()
652
+ // todoSync / todo 叶子同样逐次解包:设置页改完立即生效。
653
+ const todoSyncRaw = config && typeof config === 'object' ? config.todoSync : undefined
654
+ Object.defineProperty(cfg, 'todoSync', {
655
+ get: () => readVolatile(todoSyncRaw, DEFAULT_CONFIG.todoSync),
656
+ configurable: true, enumerable: true,
657
+ })
658
+ const todoRaw = config && typeof config === 'object' ? config.todo : undefined
659
+ function todoNow() {
660
+ const base = DEFAULT_CONFIG.todo
661
+ const raw = unwrapLive(todoRaw)
662
+ if (!isObject(raw)) return { ...base }
663
+ const out = { ...base }
664
+ for (const key of Object.keys(base)) {
665
+ const v = unwrapLive(raw[key])
666
+ if (v !== undefined) out[key] = v
667
+ }
668
+ return out
669
+ }
670
+ Object.defineProperty(cfg, 'todo', { get: todoNow, configurable: true, enumerable: true })
582
671
  const now = () => Date.now()
583
672
 
584
673
  // —— 状态容器 ——
@@ -687,6 +776,7 @@ export async function apply(ctx, config) {
687
776
  if (typeof item.approach !== 'string') item.approach = ''
688
777
  }
689
778
  if (typeof state.enabled !== 'boolean') state.enabled = false
779
+ if (state.todoMirror !== null && !isObject(state.todoMirror)) state.todoMirror = null
690
780
  if (!isObject(state.goal)) state.goal = emptyGoal()
691
781
  else {
692
782
  const g = state.goal
@@ -716,6 +806,174 @@ export async function apply(ctx, config) {
716
806
  return writeChain
717
807
  }
718
808
 
809
+ // —— v0.3.0:官方 todo 镜像 + 冲突裁决(全在 apply 闭包内,共享 states/cfg)——
810
+ const agentOfSession = new Map() // sessionId → agent(installAgentHook 时写入,disposed 清理)
811
+ const todoMirrorTimers = new Map()
812
+ const lastReconcileAt = new Map()
813
+ const reconcileCallsThisTurn = new Map()
814
+
815
+ function writeTodoMirror(sessionId, at) {
816
+ const state = states.get(sessionId)
817
+ if (!state || !state.enabled) return false
818
+ const todos = boardToTodos(state, cfg.observer.maxItems)
819
+ const hash = hashTodos(todos)
820
+ const agent = agentOfSession.get(sessionId)
821
+ if (!agent || !agent.session || typeof agent.session.append !== 'function') {
822
+ // 旧宿主 / 测试基座无 append:静默降级,板与迷你条照旧。
823
+ state.todoMirror = { hash: '', at, count: todos.length, unsupported: true }
824
+ void persist(sessionId)
825
+ return false
826
+ }
827
+ state.todoMirror = { hash, at, count: todos.length, unsupported: false }
828
+ try {
829
+ const result = agent.session.append('todo/write', { todos })
830
+ if (result && typeof result.catch === 'function') void result.catch(() => {})
831
+ } catch (_err) {
832
+ state.todoMirror = { hash: '', at, count: todos.length, unsupported: true }
833
+ }
834
+ void persist(sessionId)
835
+ return true
836
+ }
837
+
838
+ function scheduleTodoMirror(sessionId) {
839
+ if (String(cfg.todoSync || 'off') === 'off') return
840
+ const state = states.get(sessionId)
841
+ if (!state || !state.enabled) return
842
+ const delay = Math.max(0, Number(cfg.todo.mirrorThrottleMs) || 0)
843
+ const prev = todoMirrorTimers.get(sessionId)
844
+ if (prev) clearTimeout(prev)
845
+ const timer = setTimeout(() => {
846
+ todoMirrorTimers.delete(sessionId)
847
+ try { writeTodoMirror(sessionId, now()) } catch (_err) {}
848
+ }, delay)
849
+ todoMirrorTimers.set(sessionId, timer)
850
+ }
851
+
852
+ function parseReconcile(raw) {
853
+ const value = parseProposal(raw)
854
+ if (!value) return null
855
+ const resolution = String(value.resolution || '')
856
+ if (!['adopt-todo', 'keep-board', 'merge'].includes(resolution)) return null
857
+ const board = isObject(value.board) ? value.board : {}
858
+ const changes = Array.isArray(board.changes) ? board.changes : []
859
+ const todo = isObject(value.todo) ? value.todo : {}
860
+ return {
861
+ resolution,
862
+ board: { changes },
863
+ todo: Array.isArray(todo.todos) ? { todos: todo.todos } : undefined,
864
+ note: String(value.note || '').slice(0, 200),
865
+ }
866
+ }
867
+
868
+ function todoItemsToBoardChanges(state, todos) {
869
+ const changes = state.items.slice()
870
+ .sort((a, b) => a.order - b.order)
871
+ .map((item) => ({ id: item.id, remove: true }))
872
+ const seen = new Set()
873
+ for (const t of todos.slice(0, Math.max(0, MAX_CHANGES - changes.length))) {
874
+ if (!isObject(t)) continue
875
+ const title = text(String(t.content ?? ''), MAX_TITLE)
876
+ if (!title || seen.has(title)) continue
877
+ seen.add(title)
878
+ const st = String(t.status || '')
879
+ const status = st === 'completed' ? 'done' : st === 'in_progress' ? 'doing' : 'todo'
880
+ changes.push({ title, status })
881
+ }
882
+ return changes.slice(0, MAX_CHANGES)
883
+ }
884
+
885
+ async function maybeReconcileTodo(sid, incomingTodos, incomingHash) {
886
+ if (String(cfg.todoSync || '') !== 'reconcile') return
887
+ if (!assistantReady() || !isEnabled(sid)) return
888
+ const mirror = todoMirrorOf(states.get(sid))
889
+ if (mirror && !mirror.unsupported && incomingHash === mirror.hash) return
890
+ const at = now()
891
+ if (at - (lastReconcileAt.get(sid) || 0) < Math.max(0, Number(cfg.todo.maxReconcileIntervalMs) || 0)) return
892
+ if ((reconcileCallsThisTurn.get(sid) || 0) >= 1) return
893
+ reconcileCallsThisTurn.set(sid, (reconcileCallsThisTurn.get(sid) || 0) + 1)
894
+ lastReconcileAt.set(sid, at)
895
+ const a = liveAssistant()
896
+ const state = states.get(sid)
897
+ const o = obsOf(sid)
898
+ const todoLines = incomingTodos.slice(0, cfg.observer.maxItems)
899
+ .map((t, i) => `${i + 1}. [${String(t && t.status || '')}] ${String(t && t.content || '')}`)
900
+ const lastOutput = o.outputs[o.outputs.length - 1]
901
+ const lines = [
902
+ '进度板(真相源):',
903
+ ...renderChecklist(state, cfg.observer.maxItems),
904
+ '官方 todo(外部改动):',
905
+ ...todoLines,
906
+ lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
907
+ o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
908
+ ]
909
+ try {
910
+ const raw = await callAssistant({ system: TODO_RECONCILE_SYSTEM, user: lines.join('\n'), a })
911
+ const decision = parseReconcile(raw)
912
+ if (!decision) throw new Error('reconcile-unparsable')
913
+ if (decision.resolution === 'adopt-todo') {
914
+ await applyChanges({ sessionId: sid, changes: todoItemsToBoardChanges(state, incomingTodos), origin: 'assistant' })
915
+ } else if (decision.resolution === 'merge') {
916
+ const g = applyAssistantSlotChanges(state, sid, decision, a)
917
+ if (g.count > 0) await applyChanges({ sessionId: sid, changes: g.changes, origin: 'assistant', ackUserRevision: g.ackUserRevision })
918
+ }
919
+ // keep-board 不改板;三支都重写镜像(落地后 todo 与板一致)。
920
+ writeTodoMirror(sid, now())
921
+ o.assistantNote = `todo 裁决:${decision.resolution}${decision.note ? ' · ' + decision.note : ''}`
922
+ o.assistantError = ''
923
+ } catch (err) {
924
+ // 失败/超时/坏 JSON:两侧均不改,只记错误;观察块给漂移行。
925
+ o.assistantError = err instanceof Error ? err.message : String(err)
926
+ }
927
+ }
928
+
929
+ // 通用助手传输:registered 走 llm.stream,direct 走 fetch;两条链路共用。
930
+ async function callAssistant({ system, user, a }) {
931
+ const controller = new AbortController()
932
+ const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(a.timeoutMs) || 20000))
933
+ try {
934
+ if (a.mode === 'registered') {
935
+ // system 必须走 options.system;content 必须是 ContentBlock[](0.1.7 契约回归)。
936
+ const stream = llm.stream({
937
+ provider: String(a.provider),
938
+ model: String(a.model),
939
+ system,
940
+ messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
941
+ signal: controller.signal,
942
+ })
943
+ let raw = ''
944
+ for await (const chunk of stream) {
945
+ if (controller.signal.aborted) break
946
+ if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') raw += chunk.text
947
+ else if (chunk && chunk.type === 'finish' && chunk.reason && chunk.reason.kind !== 'stop' && chunk.reason.kind !== 'max-tokens') {
948
+ throw new Error(`assistant finish: ${chunk.reason.kind}`)
949
+ }
950
+ }
951
+ if (raw.trim() === '') throw new Error('assistant-empty')
952
+ return raw
953
+ }
954
+ const base = String(a.baseUrl || '').replace(/\/+$/, '')
955
+ const response = await fetch(`${base}/chat/completions`, {
956
+ method: 'POST',
957
+ headers: {
958
+ 'content-type': 'application/json',
959
+ ...(String(a.apiKey || '') !== '' ? { authorization: `Bearer ${a.apiKey}` } : {}),
960
+ },
961
+ body: JSON.stringify({
962
+ model: a.model,
963
+ temperature: 0,
964
+ max_tokens: 600,
965
+ messages: [{ role: 'system', content: system }, { role: 'user', content: user }],
966
+ }),
967
+ signal: controller.signal,
968
+ })
969
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
970
+ const body = await response.json()
971
+ return String(body?.choices?.[0]?.message?.content ?? '')
972
+ } finally {
973
+ clearTimeout(timer)
974
+ }
975
+ }
976
+
719
977
  function publicSnapshot(state) {
720
978
  const items = state.items.slice().sort((a, b) => a.order - b.order).map(itemView)
721
979
  return {
@@ -731,6 +989,16 @@ export async function apply(ctx, config) {
731
989
  storageError: storageError || null,
732
990
  items,
733
991
  summary: summarize(items),
992
+ // v0.3.0:官方 todo 同步状态回声
993
+ todo: (() => {
994
+ const m = todoMirrorOf(state)
995
+ return {
996
+ sync: String(cfg.todoSync || 'off'),
997
+ mirroredAt: m ? m.at : 0,
998
+ count: m ? m.count : 0,
999
+ unsupported: m ? m.unsupported : false,
1000
+ }
1001
+ })(),
734
1002
  // /progress-goal 迷你目标域回声
735
1003
  goal: state.goal ? goalView(state.sessionId) : null,
736
1004
  // 辅助 LLM 的配置回声:只回非机密字段,apiKey 只回布尔
@@ -940,6 +1208,10 @@ export async function apply(ctx, config) {
940
1208
  if (revisionChanged || (origin === 'agent' && ackUserRevision !== undefined)) {
941
1209
  states.set(sessionId, working)
942
1210
  await persist(sessionId)
1211
+ // 锚点订阅:持久化后按 revision 去重推送(同一 revision 不重复)。
1212
+ if (revisionChanged) notifyAnchor(sessionId, working.revision)
1213
+ // 唯一写板入口:持久化之后调度 todo 镜像(200ms 去抖,off 时直接返回)。
1214
+ if (revisionChanged) scheduleTodoMirror(sessionId)
943
1215
  }
944
1216
  // 任何 agent 调用(含 changes=[] 确认)都算一次"模型已看板":重置催办计时;
945
1217
  // 观察者自己的 autoSync(origin='observer')只刷新板新鲜度,不抵消模型催办。
@@ -1520,51 +1792,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1520
1792
  o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1521
1793
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
1522
1794
  ]
1523
- const controller = new AbortController()
1524
- const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(a.timeoutMs) || 20000))
1525
1795
  try {
1526
- let raw = ''
1527
- if (a.mode === 'registered') {
1528
- // 应主 llm.stream 契约:system 必须走 options.system(adapter 才把它映射到
1529
- // provider 的 system 槽);写进 messages 的 role:'system' 会被忽略 → 请求实际
1530
- // 没有 system,DeepSeek 回落到内置 "You are a helpful assistant." 并把它当正文
1531
- // 吐回来。content 也必须是 ContentBlock[](块数组)而非裸字符串。
1532
- // 参考 dsh-media-lens/src/providers/registered.ts 的调用形状。
1533
- const stream = llm.stream({
1534
- provider: String(a.provider),
1535
- model: String(a.model),
1536
- system: ASSISTANT_SYSTEM,
1537
- messages: [{ role: 'user', content: [{ type: 'text', text: lines.join('\n') }] }],
1538
- signal: controller.signal,
1539
- })
1540
- for await (const chunk of stream) {
1541
- if (controller.signal.aborted) break
1542
- if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') raw += chunk.text
1543
- else if (chunk && chunk.type === 'finish' && chunk.reason && chunk.reason.kind !== 'stop' && chunk.reason.kind !== 'max-tokens') {
1544
- throw new Error(`assistant finish: ${chunk.reason.kind}`)
1545
- }
1546
- }
1547
- if (raw.trim() === '') throw new Error('assistant-empty')
1548
- } else {
1549
- const base = String(a.baseUrl || '').replace(/\/+$/, '')
1550
- const response = await fetch(`${base}/chat/completions`, {
1551
- method: 'POST',
1552
- headers: {
1553
- 'content-type': 'application/json',
1554
- ...(String(a.apiKey || '') !== '' ? { authorization: `Bearer ${a.apiKey}` } : {}),
1555
- },
1556
- body: JSON.stringify({
1557
- model: a.model,
1558
- temperature: 0,
1559
- max_tokens: 600,
1560
- messages: [{ role: 'system', content: ASSISTANT_SYSTEM }, { role: 'user', content: lines.join('\n') }],
1561
- }),
1562
- signal: controller.signal,
1563
- })
1564
- if (!response.ok) throw new Error(`HTTP ${response.status}`)
1565
- const body = await response.json()
1566
- raw = String(body?.choices?.[0]?.message?.content ?? '')
1567
- }
1796
+ const raw = await callAssistant({ system: ASSISTANT_SYSTEM, user: lines.join('\n'), a })
1568
1797
  const proposal = parseProposal(raw)
1569
1798
  if (!proposal) throw new Error('proposal-unparsable')
1570
1799
  o.assistantError = ''
@@ -1578,8 +1807,6 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1578
1807
  }
1579
1808
  } catch (err) {
1580
1809
  o.assistantError = err instanceof Error ? err.message : String(err)
1581
- } finally {
1582
- clearTimeout(timer)
1583
1810
  }
1584
1811
  }
1585
1812
 
@@ -1620,8 +1847,12 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1620
1847
  // 机械对比(算术,非语义):两套清单完成数漂移 → 让模型自己核对
1621
1848
  const boardDone = state.items.filter((item) => item.status === 'done').length
1622
1849
  if (t.todoDone !== boardDone) {
1850
+ // 旧对比行保留(既有 observer 用例断言逐字匹配),新漂移行按 spec 追加。
1623
1851
  lines.push(`对比:官方 todo 完成 ${t.todoDone}/${t.todoTotal} · 板完成 ${boardDone}/${state.items.length}(进度不一致,核对后修正一处)`)
1852
+ lines.push(`[todo 漂移] 官方 ${t.todoDone}/${t.todoTotal} · 板 ${boardDone}/${state.items.length}(待裁决)`)
1624
1853
  }
1854
+ const mirror = todoMirrorOf(state)
1855
+ if (mirror && !mirror.unsupported) lines.push(`[todo 镜像] 已同步 rev=${state.revision} · ${mirror.count} 条`)
1625
1856
  }
1626
1857
  const files = Array.isArray(o.files) ? o.files.slice(-4) : []
1627
1858
  if (files.length) lines.push(`最近改动:${files.map((f) => `${shortPath(f.path)}(${f.tool})`).join(' · ')}`)
@@ -1655,6 +1886,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1655
1886
  if (!agent || !agent.id || !agent.ctx) return
1656
1887
  if (hookedAgents.has(agent)) return
1657
1888
  hookedAgents.add(agent)
1889
+ agentOfSession.set(sessionOfAgent(agent), agent)
1658
1890
  try {
1659
1891
  agent.ctx.on('agent/pre-step', async (payload, next) => {
1660
1892
  const sid = String(agent.session?.id ?? agent.id)
@@ -2095,6 +2327,12 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2095
2327
  .filter(Boolean)
2096
2328
  .slice(0, 8)
2097
2329
  tk.lastActivityAt = now()
2330
+ // 回环识别:自家镜像写入(hash 命中)只更新 ETA 原料,不触发裁决。
2331
+ const mirror = todoMirrorOf(states.get(sid))
2332
+ const incomingHash = hashTodos(todos)
2333
+ if (!mirror || mirror.unsupported || incomingHash !== mirror.hash) {
2334
+ void maybeReconcileTodo(sid, todos, incomingHash)
2335
+ }
2098
2336
  }
2099
2337
  return
2100
2338
  }
@@ -2124,6 +2362,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2124
2362
  return
2125
2363
  }
2126
2364
  if (type === 'turn/start') {
2365
+ reconcileCallsThisTurn.set(sid, 0)
2127
2366
  const task = taskOf(sid)
2128
2367
  markLineage(task, session)
2129
2368
  const pendingText = userTextMap.get(sid) || ''
@@ -2294,6 +2533,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2294
2533
  }
2295
2534
 
2296
2535
  // —— service 平面(同进程零 I/O;宿主无 provide 面时静默只留 HTTP)——
2536
+ const anchorListeners = new Map() // sessionId -> Set<listener>
2537
+ const lastAnchorRevision = new Map() // sessionId -> 已推送的 revision
2297
2538
  const anchorApi = {
2298
2539
  version: ANCHOR_VERSION,
2299
2540
  get(sessionId, atMs) {
@@ -2303,6 +2544,30 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2303
2544
  const ids = new Set([...states.keys(), ...taskMap.keys()])
2304
2545
  return [...ids].map((sid) => buildAnchor(sid, finiteNumber(atMs) ?? now()))
2305
2546
  },
2547
+ subscribe(listener, sessionId) {
2548
+ if (typeof listener !== 'function') return () => {}
2549
+ if (sessionId === undefined) {
2550
+ const offs = [...states.keys(), ...taskMap.keys()].map((sid) => anchorApi.subscribe(listener, sid))
2551
+ return () => offs.forEach((off) => off())
2552
+ }
2553
+ const sid = String(sessionId)
2554
+ let set = anchorListeners.get(sid)
2555
+ if (!set) { set = new Set(); anchorListeners.set(sid, set) }
2556
+ set.add(listener)
2557
+ return () => {
2558
+ set.delete(listener)
2559
+ if (set.size === 0) anchorListeners.delete(sid)
2560
+ }
2561
+ },
2562
+ }
2563
+ function notifyAnchor(sessionId, revision) {
2564
+ const set = anchorListeners.get(sessionId)
2565
+ if (!set || set.size === 0) return
2566
+ if (lastAnchorRevision.get(sessionId) === revision) return
2567
+ lastAnchorRevision.set(sessionId, revision)
2568
+ for (const listener of [...set]) {
2569
+ try { listener({ sessionId, revision }) } catch (_err) {}
2570
+ }
2306
2571
  }
2307
2572
  if (typeof ctx.provide === 'function') {
2308
2573
  try {
@@ -2810,6 +3075,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2810
3075
  for (const agent of agents?.list?.() ?? []) bindAgentContext(agent)
2811
3076
  const offCreated = ctx.on('agent/created', ({ agent }) => bindAgentContext(agent))
2812
3077
  const offDisposed = ctx.on('agent/disposed', ({ agent }) => {
3078
+ agentOfSession.delete(sessionOfAgent(agent))
2813
3079
  const dispose = agentDisposers.get(sessionOfAgent(agent))
2814
3080
  if (dispose) {
2815
3081
  dispose()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "进度结合原型:dsh-progress-board 槽位真相源 × 鲸程 widget 时间/ETA 引擎,另向压缩插件暴露只读三层进度锚点(service + HTTP 双平面)。基于 l3j3y3/dsh-progress-board (MIT) 与 uuhihj/task-progress-bar dsh-progress-widget (MIT)。",
6
6
  "license": "MIT",
@@ -16,6 +16,7 @@
16
16
  "exports": {
17
17
  ".": "./index.js",
18
18
  "./client": "./client.js",
19
+ "./anchor": "./anchor.js",
19
20
  "./cordis.patch.yml": "./cordis.patch.yml",
20
21
  "./package.json": "./package.json"
21
22
  },
@@ -23,6 +24,7 @@
23
24
  "README.md",
24
25
  "LICENSE",
25
26
  "index.js",
27
+ "anchor.js",
26
28
  "client.js",
27
29
  "cordis.patch.yml",
28
30
  "dsh.plugin.json",
@@ -0,0 +1,101 @@
1
+ /**
2
+ * v0.4.0 消费者视角验收:
3
+ * - 经 service get/list 读锚点并断言字段;
4
+ * - 经 subscribe 拿到板变更通知(revision 递增、同 rev 不重复、退订后零回调);
5
+ * - isAnchor/anchorLine 对新旧快照都能工作(含未启用板场景)。
6
+ */
7
+ import assert from 'node:assert/strict'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import test from 'node:test'
12
+
13
+ process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'union-test-'))
14
+ const { SESSION, createHarness, jsonReq, callRoute } = await import('./harness.mjs')
15
+ const { ANCHOR_VERSION, ANCHOR_ROUTES, BOARD_STATUSES, isAnchor, anchorLine } = await import('../anchor.js')
16
+
17
+ function execUpdate(harness, args) {
18
+ return harness.toolMap.get('progress_update').definition.execute(args, { agent: harness.agent })
19
+ }
20
+
21
+ async function booted() {
22
+ const harness = createHarness()
23
+ await harness.run()
24
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
25
+ return harness
26
+ }
27
+
28
+ test('./anchor 子路径导出齐全;常量与 service.version 握手一致', async () => {
29
+ assert.equal(ANCHOR_VERSION, 1)
30
+ assert.deepEqual(ANCHOR_ROUTES, {
31
+ anchor: '/progress-union/anchor',
32
+ snapshot: '/progress-union/snapshot',
33
+ status: '/dsh-progress/status',
34
+ })
35
+ assert.deepEqual(BOARD_STATUSES, ['todo', 'doing', 'done', 'blocked'])
36
+ assert.equal(typeof isAnchor, 'function')
37
+ assert.equal(typeof anchorLine, 'function')
38
+ const harness = await booted()
39
+ assert.equal(harness.provided.get('progressAnchor').version, ANCHOR_VERSION, '握手:service.version === ANCHOR_VERSION')
40
+ })
41
+
42
+ test('消费者经 get/list 读锚点:字段齐、未启用板 board.enabled=false 不抛', async () => {
43
+ const harness = await booted()
44
+ const service = harness.provided.get('progressAnchor')
45
+ const anchor = service.get(SESSION)
46
+ assert.equal(isAnchor(anchor), true)
47
+ assert.equal(anchor.sessionId, SESSION)
48
+ assert.equal(typeof anchor.revision, 'number')
49
+ assert.equal(typeof anchor.board.enabled, 'boolean')
50
+ const listed = service.list()
51
+ assert.ok(Array.isArray(listed))
52
+ assert.ok(listed.some((a) => a.sessionId === SESSION))
53
+
54
+ const off = createHarness()
55
+ await off.run()
56
+ const disabled = off.provided.get('progressAnchor').get('session-never-enabled')
57
+ assert.equal(isAnchor(disabled), true, '未启用板仍是合法锚点')
58
+ assert.equal(disabled.board.enabled, false)
59
+ assert.equal(anchorLine(disabled), '0% 0/0', '未启用板不抛错,给 0 值摘要')
60
+ })
61
+
62
+ test('subscribe:板 revision 递增回调一次;同 revision 不重复;退订后零回调', async () => {
63
+ const harness = await booted()
64
+ const service = harness.provided.get('progressAnchor')
65
+ const events = []
66
+ const off = service.subscribe((evt) => events.push(evt), SESSION)
67
+
68
+ await execUpdate(harness, { changes: [{ title: '甲', status: 'doing' }] })
69
+ await execUpdate(harness, { changes: [{ title: '乙', status: 'todo' }] })
70
+ assert.equal(events.length, 2, '两次写板、两次不同 revision → 两次回调')
71
+ assert.ok(events[0].revision < events[1].revision)
72
+ assert.equal(events[0].sessionId, SESSION)
73
+
74
+ // 同 revision 不重复:先记下当前 revision,重复订阅探测不会因读操作再触发。
75
+ const rev = events[1].revision
76
+ assert.equal(events.filter((e) => e.revision === rev).length, 1)
77
+
78
+ off()
79
+ await execUpdate(harness, { changes: [{ title: '丙' }] })
80
+ assert.equal(events.length, 2, '退订后不再回调')
81
+
82
+ // 无参数订阅(全会话)也应可退订。
83
+ const all = []
84
+ const offAll = service.subscribe((evt) => all.push(evt))
85
+ await execUpdate(harness, { changes: [{ title: '丁', status: 'done' }] })
86
+ assert.equal(all.length, 1)
87
+ offAll()
88
+ await execUpdate(harness, { changes: [{ title: '戊' }] })
89
+ assert.equal(all.length, 1)
90
+ })
91
+
92
+ test('isAnchor/anchorLine:新旧快照都能工作(缺新字段不抛,坏形状返回空串)', async () => {
93
+ const modern = { version: 1, sessionId: 's', board: { enabled: true, summary: { percent: 45, done: 3, total: 7 } }, time: { etaMin: 6, staleMin: 12 } }
94
+ const legacy = { version: 1, sessionId: 's', board: { enabled: true, summary: { percent: 80, done: 4, total: 5, doing: 0, todo: 1, blocked: 0 } }, time: { staleMin: 0 } }
95
+ assert.equal(isAnchor(modern), true)
96
+ assert.equal(isAnchor(legacy), true)
97
+ assert.equal(anchorLine(modern), '45% 3/7 · ETA 6m · stale 12m')
98
+ assert.equal(anchorLine(legacy), '80% 4/5')
99
+ assert.equal(isAnchor({ version: 1, sessionId: 's', board: {}, time: {} }), false)
100
+ assert.equal(anchorLine(null), '')
101
+ })
package/test/harness.mjs CHANGED
@@ -60,9 +60,14 @@ export function createHarness({ seed = {}, config = {}, withProjection = true, w
60
60
 
61
61
  const systemPrompt = {}
62
62
 
63
+ const appends = []
63
64
  const agent = {
64
65
  id: SESSION,
65
- session: { id: SESSION },
66
+ // v0.3.0:todo 镜像写通道。默认记录调用;测试可覆写 append 注入失败。
67
+ session: {
68
+ id: SESSION,
69
+ append(type, data) { appends.push({ type, data }); return Promise.resolve() },
70
+ },
66
71
  ctx: {
67
72
  effect(fn) {
68
73
  return fn()
@@ -132,6 +137,7 @@ export function createHarness({ seed = {}, config = {}, withProjection = true, w
132
137
  ctx,
133
138
  config,
134
139
  agent,
140
+ appends,
135
141
  records,
136
142
  routes,
137
143
  toolMap,
@@ -47,6 +47,9 @@ test('Config:assistant / observer 的每个叶子都带 volatile(否则设
47
47
  'observer.autoSyncCurrent',
48
48
  'observer.autoSyncThrottleMs',
49
49
  'observer.maxItems',
50
+ 'todoSync',
51
+ 'todo.maxReconcileIntervalMs',
52
+ 'todo.mirrorThrottleMs',
50
53
  ]
51
54
  for (const key of expected) {
52
55
  assert.ok(key in leaves, `缺少配置键 ${key}`)
@@ -55,7 +58,7 @@ test('Config:assistant / observer 的每个叶子都带 volatile(否则设
55
58
  })
56
59
 
57
60
  test('Config:外层对象不得自己标 volatile(嵌套 volatile 会被宿主拒绝)', () => {
58
- for (const key of ['assistant', 'observer']) {
61
+ for (const key of ['assistant', 'observer', 'todo']) {
59
62
  const node = (Config.dict || Config.inner || {})[key]
60
63
  assert.ok(node, `缺少 ${key} 节点`)
61
64
  assert.equal((node.meta || {}).volatile, undefined, `${key} 这层不能标 volatile`)
@@ -0,0 +1,155 @@
1
+ /**
2
+ * v0.3.0 验收:板 → 官方 todo 镜像 + 助手冲突裁决。
3
+ * - 映射(done→completed / 首条 doing→in_progress / todo+blocked→pending、content 唯一);
4
+ * - 200ms 去抖单次写入、回环不触发裁决、off 不写、无 append 静默降级;
5
+ * - 三种 resolution 落地与助手失败两侧不改。
6
+ */
7
+ import assert from 'node:assert/strict'
8
+ import fs from 'node:fs'
9
+ import os from 'node:os'
10
+ import path from 'node:path'
11
+ import test from 'node:test'
12
+
13
+ process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'union-test-'))
14
+ const { SESSION, createHarness, jsonReq, callRoute } = await import('./harness.mjs')
15
+
16
+ async function booted(config = {}) {
17
+ const harness = createHarness({ config: { ...config, todo: { mirrorThrottleMs: 5, ...(config.todo || {}) } } })
18
+ await harness.run()
19
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
20
+ return harness
21
+ }
22
+
23
+ function execUpdate(harness, args) {
24
+ return harness.toolMap.get('progress_update').definition.execute(args, { agent: harness.agent })
25
+ }
26
+
27
+ async function settle(ms = 30) {
28
+ await new Promise((resolve) => setTimeout(resolve, ms))
29
+ }
30
+
31
+ function stubFetch(handler) {
32
+ const calls = []
33
+ const original = globalThis.fetch
34
+ globalThis.fetch = async (url, init) => {
35
+ calls.push({ url: String(url), init })
36
+ return handler(url, init, calls.length)
37
+ }
38
+ return { calls, restore: () => { globalThis.fetch = original } }
39
+ }
40
+
41
+ function proposal(content) {
42
+ return { ok: true, status: 200, async json() { return { choices: [{ message: { content } }] } } }
43
+ }
44
+
45
+ async function snapshot(harness) {
46
+ const res = await callRoute(harness, '/progress-union/snapshot', { method: 'GET', url: `/progress-union/snapshot?sessionId=${SESSION}`, headers: {} })
47
+ return res.json()
48
+ }
49
+
50
+ test('映射:done→completed、仅首条 doing→in_progress、todo/blocked→pending、content 去重、in_progress≤1', async () => {
51
+ const harness = await booted()
52
+ await execUpdate(harness, { changes: [
53
+ { title: '甲', status: 'done' },
54
+ { title: '乙', status: 'doing' },
55
+ { title: '丙', status: 'doing' },
56
+ { title: '丁', status: 'blocked' },
57
+ { title: '乙', status: 'todo' }, // 重复标题,需去重
58
+ ] })
59
+ await settle()
60
+ const writes = harness.appends.filter((w) => w.type === 'todo/write')
61
+ assert.equal(writes.length, 1, '去抖后只写一次')
62
+ const todos = writes[0].data.todos
63
+ assert.deepEqual(todos.map((t) => t.status), ['completed', 'pending', 'in_progress', 'pending'])
64
+ assert.deepEqual(todos.map((t) => t.content), ['甲', '乙', '丙', '丁'])
65
+ assert.equal(todos.filter((t) => t.status === 'in_progress').length, 1)
66
+ assert.equal((await snapshot(harness)).todo.sync, 'reconcile')
67
+ })
68
+
69
+ test('去抖与回环:连续写板 5 次只镜像一次;自家 hash 命中不触发裁决', async () => {
70
+ const harness = await booted({
71
+ assistant: { mode: 'direct', baseUrl: 'http://127.0.0.1:9999/v1', model: 'mini', minIntervalMs: 0 },
72
+ })
73
+ const stub = stubFetch(() => proposal('{"resolution":"keep-board","note":"no-op"}'))
74
+ try {
75
+ for (let i = 0; i < 5; i += 1) await execUpdate(harness, { changes: [{ title: `任务${i}`, status: i === 0 ? 'doing' : 'todo' }] })
76
+ await settle(50)
77
+ const writes = harness.appends.filter((w) => w.type === 'todo/write')
78
+ assert.equal(writes.length, 1, '5 次写板 → 1 次镜像')
79
+ // 把镜像内容当自家事件回灌:hash 命中,零裁决
80
+ harness.emit('todo/write', { todos: writes[0].data.todos })
81
+ await settle()
82
+ assert.equal(stub.calls.length, 0, '自家写入不得触发裁决')
83
+ } finally {
84
+ stub.restore()
85
+ }
86
+ })
87
+
88
+ test('reconcile 三支:adopt-todo 覆盖板、keep-board 重镜像、merge 增量落地', async () => {
89
+ for (const [resolution, body, expected] of [
90
+ ['adopt-todo', '{"resolution":"adopt-todo","board":{"changes":[]},"note":"todo 更新"}', (snap) => assert.deepEqual(snap.items.map((i) => i.title).sort(), ['新任务'])],
91
+ ['keep-board', '{"resolution":"keep-board","board":{"changes":[]},"note":"板为准"}', (snap) => assert.equal(snap.items[0].title, '原任务')],
92
+ ['merge', '{"resolution":"merge","board":{"changes":[{"id":"__SELF__","percent":80}]},"note":"合并"}', (snap) => assert.equal(snap.items[0].percent, 80)],
93
+ ]) {
94
+ const harness = await booted({
95
+ assistant: { mode: 'direct', baseUrl: 'http://127.0.0.1:9999/v1', model: 'mini', minIntervalMs: 0 },
96
+ todo: { maxReconcileIntervalMs: 0 },
97
+ })
98
+ const added = await execUpdate(harness, { changes: [{ title: '原任务', status: 'doing', percent: 10 }] })
99
+ const selfId = added.changed[0].id
100
+ await settle() // 先镜像落定
101
+ const stub = stubFetch(() => proposal(body.replace('__SELF__', selfId)))
102
+ try {
103
+ harness.emit('todo/write', { todos: [
104
+ { content: resolution === 'adopt-todo' ? '新任务' : '外部任务', status: 'in_progress' },
105
+ ] })
106
+ await settle(60)
107
+ const snap = await snapshot(harness)
108
+ expected(snap)
109
+ assert.match(harness.contexts.get('progress-union-observer')(), /todo 裁决:/)
110
+ } finally {
111
+ stub.restore()
112
+ }
113
+ }
114
+ })
115
+
116
+ test('助手失败/坏 JSON/未配置:两侧均不改,观察块出现漂移行', async () => {
117
+ const harness = await booted({
118
+ assistant: { mode: 'direct', baseUrl: 'http://127.0.0.1:9999/v1', model: 'mini', minIntervalMs: 0 },
119
+ todo: { maxReconcileIntervalMs: 0 },
120
+ })
121
+ await execUpdate(harness, { changes: [{ title: '原任务', status: 'doing', percent: 10 }] })
122
+ await settle()
123
+ const snapBefore = await snapshot(harness)
124
+ const stub = stubFetch(() => ({ ok: false, status: 503, async json() { return {} } }))
125
+ try {
126
+ harness.emit('todo/write', { todos: [
127
+ { content: '外部任务', status: 'in_progress' },
128
+ { content: '外部任务2', status: 'completed' },
129
+ ] })
130
+ await settle(60)
131
+ const snapAfter = await snapshot(harness)
132
+ assert.deepEqual(snapAfter.items, snapBefore.items, '失败不改板')
133
+ assert.equal(harness.appends.length, 1, '失败不重新镜像')
134
+ assert.match(harness.contexts.get('progress-union-observer')(), /\[todo 漂移\]/)
135
+ assert.match(harness.contexts.get('progress-union-observer')(), /助手审查失败:HTTP 503/)
136
+ } finally {
137
+ stub.restore()
138
+ }
139
+ })
140
+
141
+ test('todoSync=off 零写入;宿主无 session.append 静默降级', async () => {
142
+ const off = await booted({ todoSync: 'off' })
143
+ await execUpdate(off, { changes: [{ title: '任务', status: 'doing' }] })
144
+ await settle(30)
145
+ assert.equal(off.appends.length, 0, 'off 时零 todo/write')
146
+
147
+ const harness = createHarness({ config: { todo: { mirrorThrottleMs: 5 } } })
148
+ delete harness.agent.session.append // 旧宿主:无 append
149
+ await harness.run()
150
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
151
+ await execUpdate(harness, { changes: [{ title: '任务', status: 'doing' }] })
152
+ await settle(30)
153
+ assert.equal((await snapshot(harness)).items.length, 1, '板不受影响')
154
+ assert.equal((await snapshot(harness)).todo.unsupported, true, '快照标记 unsupported')
155
+ })