dsh-progress-union 0.1.9 → 0.3.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/index.js CHANGED
@@ -45,6 +45,11 @@ export const Config = z.object({
45
45
  autoSyncThrottleMs: z.number().step(1000).min(0).default(60000).volatile(),
46
46
  maxItems: z.number().step(1).min(1).default(12).volatile(),
47
47
  }).default({}),
48
+ todoSync: z.union(['off', 'mirror', 'reconcile']).default('reconcile').volatile(),
49
+ todo: z.object({
50
+ maxReconcileIntervalMs: z.number().step(1000).min(0).default(60000).volatile(),
51
+ mirrorThrottleMs: z.number().step(1).min(0).default(200).volatile(),
52
+ }).default({}),
48
53
  })
49
54
 
50
55
  // —— 路由与存储标识 ——
@@ -120,6 +125,17 @@ const ASSISTANT_SYSTEM = 'You are a progress assistant for a task board in a lon
120
125
  'Emit at most 8 changes. If nothing needs changing, use {"board":{"changes":[]},"round":{...},"note":"..."}. ' +
121
126
  'Respond with the JSON object only — no prose, no code fences.'
122
127
 
128
+ // v0.3.0 todo 裁决 system:只做差异裁决,不改写事实;输出严格三选一。
129
+ const TODO_RECONCILE_SYSTEM = 'You reconcile a task board with an external official todo list. ' +
130
+ 'The board is the user-facing source of truth; the todo list is the model work list. ' +
131
+ 'Given both lists plus recent assistant output/tool activity, decide ONE resolution: ' +
132
+ '"adopt-todo" (todo is newer/correct, replace board), "keep-board" (board is correct, re-mirror it), ' +
133
+ 'or "merge" (apply incremental board.changes without dropping board facts). ' +
134
+ 'Output strictly ONE JSON object: ' +
135
+ '{"resolution":"adopt-todo|keep-board|merge","board":{"changes":[{"id"?:string,"kind"?:string,"title"?:string,"status"?:string}]},"todo":{"todos"?:[]},"note":"<one line>"}. ' +
136
+ 'For "merge", board.changes must use the same shape as the board assistant changes. ' +
137
+ 'Emit at most 8 changes. Respond with the JSON object only — no prose, no code fences.'
138
+
123
139
  // ============================================================================
124
140
  // 通用工具(board fork)
125
141
  // ============================================================================
@@ -158,6 +174,7 @@ function emptyState(sessionId) {
158
174
  updatedAt: now,
159
175
  items: [],
160
176
  userChanges: [],
177
+ todoMirror: null, // v0.3.0:自家镜像写入的 hash/at/count,回环识别用
161
178
  goal: emptyGoal(),
162
179
  }
163
180
  }
@@ -202,6 +219,54 @@ function summarize(items) {
202
219
  }
203
220
  }
204
221
 
222
+ // —— v0.3.0:板 → 官方 todo 的纯映射(content 唯一非空、in_progress ≤1)——
223
+ function boardToTodos(state, maxItems) {
224
+ const limit = Math.max(1, Number(maxItems) || 12)
225
+ const items = (Array.isArray(state && state.items) ? state.items : [])
226
+ .slice()
227
+ .sort((a, b) => a.order - b.order || a.updatedAt - b.updatedAt || a.id.localeCompare(b.id))
228
+ .slice(0, limit)
229
+ const todos = []
230
+ const seen = new Set()
231
+ let doingSeen = false
232
+ for (const item of items) {
233
+ const content = String(item && item.title || '').trim()
234
+ if (!content || seen.has(content)) continue
235
+ seen.add(content)
236
+ let status = 'pending'
237
+ if (item.status === 'done') status = 'completed'
238
+ else if (item.status === 'doing') {
239
+ if (!doingSeen) { status = 'in_progress'; doingSeen = true }
240
+ }
241
+ todos.push({ content, status })
242
+ }
243
+ return todos
244
+ }
245
+
246
+ // 稳定内容哈希(顺序敏感):同一批 todos 同值,顺序变化不同值。
247
+ function hashTodos(todos) {
248
+ const stable = JSON.stringify((Array.isArray(todos) ? todos : []).map((t) => [String(t && t.content || ''), String(t && t.status || '')]))
249
+ let h1 = 0x811c9dc5
250
+ let h2 = 0x01000193
251
+ for (let i = 0; i < stable.length; i += 1) {
252
+ const c = stable.charCodeAt(i)
253
+ h1 = Math.imul(h1 ^ c, 16777619) >>> 0
254
+ h2 = Math.imul(h2 + c + i, 2246822519) >>> 0
255
+ }
256
+ return h1.toString(36) + h2.toString(36)
257
+ }
258
+
259
+ function todoMirrorOf(state) {
260
+ const m = state && state.todoMirror
261
+ if (!isObject(m)) return null
262
+ return {
263
+ hash: typeof m.hash === 'string' ? m.hash : '',
264
+ at: finiteNumber(m.at) ?? 0,
265
+ count: finiteNumber(m.count) ?? 0,
266
+ unsupported: m.unsupported === true,
267
+ }
268
+ }
269
+
205
270
  function normalizeItems(items) {
206
271
  items.sort((a, b) => a.order - b.order || a.updatedAt - b.updatedAt || a.id.localeCompare(b.id))
207
272
  items.forEach((item, index) => {
@@ -508,6 +573,9 @@ const DEFAULT_CONFIG = {
508
573
  maxTools: 3,
509
574
  maxItems: 12,
510
575
  },
576
+ // v0.3.0:板 → 官方 todo 镜像与冲突裁决。默认 reconcile;不想要行为变更可在设置页关。
577
+ todoSync: 'reconcile', // off | mirror | reconcile
578
+ todo: { maxReconcileIntervalMs: 60_000, mirrorThrottleMs: 200 },
511
579
  // 辅助 LLM(审查/监视 + 槽位管理 + 轮次草案):
512
580
  // mode: 'registered' 走宿主 llm.stream(选已注册 llm-pi-ai provider/model);
513
581
  // 'direct' 走自建 OpenAI 兼容端点(baseUrl/apiKey/model);'' 关。
@@ -579,6 +647,25 @@ export async function apply(ctx, config) {
579
647
  return out
580
648
  }
581
649
  cfg.assistant = assistantNow()
650
+ // todoSync / todo 叶子同样逐次解包:设置页改完立即生效。
651
+ const todoSyncRaw = config && typeof config === 'object' ? config.todoSync : undefined
652
+ Object.defineProperty(cfg, 'todoSync', {
653
+ get: () => readVolatile(todoSyncRaw, DEFAULT_CONFIG.todoSync),
654
+ configurable: true, enumerable: true,
655
+ })
656
+ const todoRaw = config && typeof config === 'object' ? config.todo : undefined
657
+ function todoNow() {
658
+ const base = DEFAULT_CONFIG.todo
659
+ const raw = unwrapLive(todoRaw)
660
+ if (!isObject(raw)) return { ...base }
661
+ const out = { ...base }
662
+ for (const key of Object.keys(base)) {
663
+ const v = unwrapLive(raw[key])
664
+ if (v !== undefined) out[key] = v
665
+ }
666
+ return out
667
+ }
668
+ Object.defineProperty(cfg, 'todo', { get: todoNow, configurable: true, enumerable: true })
582
669
  const now = () => Date.now()
583
670
 
584
671
  // —— 状态容器 ——
@@ -687,6 +774,7 @@ export async function apply(ctx, config) {
687
774
  if (typeof item.approach !== 'string') item.approach = ''
688
775
  }
689
776
  if (typeof state.enabled !== 'boolean') state.enabled = false
777
+ if (state.todoMirror !== null && !isObject(state.todoMirror)) state.todoMirror = null
690
778
  if (!isObject(state.goal)) state.goal = emptyGoal()
691
779
  else {
692
780
  const g = state.goal
@@ -716,6 +804,174 @@ export async function apply(ctx, config) {
716
804
  return writeChain
717
805
  }
718
806
 
807
+ // —— v0.3.0:官方 todo 镜像 + 冲突裁决(全在 apply 闭包内,共享 states/cfg)——
808
+ const agentOfSession = new Map() // sessionId → agent(installAgentHook 时写入,disposed 清理)
809
+ const todoMirrorTimers = new Map()
810
+ const lastReconcileAt = new Map()
811
+ const reconcileCallsThisTurn = new Map()
812
+
813
+ function writeTodoMirror(sessionId, at) {
814
+ const state = states.get(sessionId)
815
+ if (!state || !state.enabled) return false
816
+ const todos = boardToTodos(state, cfg.observer.maxItems)
817
+ const hash = hashTodos(todos)
818
+ const agent = agentOfSession.get(sessionId)
819
+ if (!agent || !agent.session || typeof agent.session.append !== 'function') {
820
+ // 旧宿主 / 测试基座无 append:静默降级,板与迷你条照旧。
821
+ state.todoMirror = { hash: '', at, count: todos.length, unsupported: true }
822
+ void persist(sessionId)
823
+ return false
824
+ }
825
+ state.todoMirror = { hash, at, count: todos.length, unsupported: false }
826
+ try {
827
+ const result = agent.session.append('todo/write', { todos })
828
+ if (result && typeof result.catch === 'function') void result.catch(() => {})
829
+ } catch (_err) {
830
+ state.todoMirror = { hash: '', at, count: todos.length, unsupported: true }
831
+ }
832
+ void persist(sessionId)
833
+ return true
834
+ }
835
+
836
+ function scheduleTodoMirror(sessionId) {
837
+ if (String(cfg.todoSync || 'off') === 'off') return
838
+ const state = states.get(sessionId)
839
+ if (!state || !state.enabled) return
840
+ const delay = Math.max(0, Number(cfg.todo.mirrorThrottleMs) || 0)
841
+ const prev = todoMirrorTimers.get(sessionId)
842
+ if (prev) clearTimeout(prev)
843
+ const timer = setTimeout(() => {
844
+ todoMirrorTimers.delete(sessionId)
845
+ try { writeTodoMirror(sessionId, now()) } catch (_err) {}
846
+ }, delay)
847
+ todoMirrorTimers.set(sessionId, timer)
848
+ }
849
+
850
+ function parseReconcile(raw) {
851
+ const value = parseProposal(raw)
852
+ if (!value) return null
853
+ const resolution = String(value.resolution || '')
854
+ if (!['adopt-todo', 'keep-board', 'merge'].includes(resolution)) return null
855
+ const board = isObject(value.board) ? value.board : {}
856
+ const changes = Array.isArray(board.changes) ? board.changes : []
857
+ const todo = isObject(value.todo) ? value.todo : {}
858
+ return {
859
+ resolution,
860
+ board: { changes },
861
+ todo: Array.isArray(todo.todos) ? { todos: todo.todos } : undefined,
862
+ note: String(value.note || '').slice(0, 200),
863
+ }
864
+ }
865
+
866
+ function todoItemsToBoardChanges(state, todos) {
867
+ const changes = state.items.slice()
868
+ .sort((a, b) => a.order - b.order)
869
+ .map((item) => ({ id: item.id, remove: true }))
870
+ const seen = new Set()
871
+ for (const t of todos.slice(0, Math.max(0, MAX_CHANGES - changes.length))) {
872
+ if (!isObject(t)) continue
873
+ const title = text(String(t.content ?? ''), MAX_TITLE)
874
+ if (!title || seen.has(title)) continue
875
+ seen.add(title)
876
+ const st = String(t.status || '')
877
+ const status = st === 'completed' ? 'done' : st === 'in_progress' ? 'doing' : 'todo'
878
+ changes.push({ title, status })
879
+ }
880
+ return changes.slice(0, MAX_CHANGES)
881
+ }
882
+
883
+ async function maybeReconcileTodo(sid, incomingTodos, incomingHash) {
884
+ if (String(cfg.todoSync || '') !== 'reconcile') return
885
+ if (!assistantReady() || !isEnabled(sid)) return
886
+ const mirror = todoMirrorOf(states.get(sid))
887
+ if (mirror && !mirror.unsupported && incomingHash === mirror.hash) return
888
+ const at = now()
889
+ if (at - (lastReconcileAt.get(sid) || 0) < Math.max(0, Number(cfg.todo.maxReconcileIntervalMs) || 0)) return
890
+ if ((reconcileCallsThisTurn.get(sid) || 0) >= 1) return
891
+ reconcileCallsThisTurn.set(sid, (reconcileCallsThisTurn.get(sid) || 0) + 1)
892
+ lastReconcileAt.set(sid, at)
893
+ const a = liveAssistant()
894
+ const state = states.get(sid)
895
+ const o = obsOf(sid)
896
+ const todoLines = incomingTodos.slice(0, cfg.observer.maxItems)
897
+ .map((t, i) => `${i + 1}. [${String(t && t.status || '')}] ${String(t && t.content || '')}`)
898
+ const lastOutput = o.outputs[o.outputs.length - 1]
899
+ const lines = [
900
+ '进度板(真相源):',
901
+ ...renderChecklist(state, cfg.observer.maxItems),
902
+ '官方 todo(外部改动):',
903
+ ...todoLines,
904
+ lastOutput ? `最近输出:${lastOutput.text}` : '最近输出:—',
905
+ o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
906
+ ]
907
+ try {
908
+ const raw = await callAssistant({ system: TODO_RECONCILE_SYSTEM, user: lines.join('\n'), a })
909
+ const decision = parseReconcile(raw)
910
+ if (!decision) throw new Error('reconcile-unparsable')
911
+ if (decision.resolution === 'adopt-todo') {
912
+ await applyChanges({ sessionId: sid, changes: todoItemsToBoardChanges(state, incomingTodos), origin: 'assistant' })
913
+ } else if (decision.resolution === 'merge') {
914
+ const g = applyAssistantSlotChanges(state, sid, decision, a)
915
+ if (g.count > 0) await applyChanges({ sessionId: sid, changes: g.changes, origin: 'assistant', ackUserRevision: g.ackUserRevision })
916
+ }
917
+ // keep-board 不改板;三支都重写镜像(落地后 todo 与板一致)。
918
+ writeTodoMirror(sid, now())
919
+ o.assistantNote = `todo 裁决:${decision.resolution}${decision.note ? ' · ' + decision.note : ''}`
920
+ o.assistantError = ''
921
+ } catch (err) {
922
+ // 失败/超时/坏 JSON:两侧均不改,只记错误;观察块给漂移行。
923
+ o.assistantError = err instanceof Error ? err.message : String(err)
924
+ }
925
+ }
926
+
927
+ // 通用助手传输:registered 走 llm.stream,direct 走 fetch;两条链路共用。
928
+ async function callAssistant({ system, user, a }) {
929
+ const controller = new AbortController()
930
+ const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(a.timeoutMs) || 20000))
931
+ try {
932
+ if (a.mode === 'registered') {
933
+ // system 必须走 options.system;content 必须是 ContentBlock[](0.1.7 契约回归)。
934
+ const stream = llm.stream({
935
+ provider: String(a.provider),
936
+ model: String(a.model),
937
+ system,
938
+ messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
939
+ signal: controller.signal,
940
+ })
941
+ let raw = ''
942
+ for await (const chunk of stream) {
943
+ if (controller.signal.aborted) break
944
+ if (chunk && chunk.type === 'text-delta' && typeof chunk.text === 'string') raw += chunk.text
945
+ else if (chunk && chunk.type === 'finish' && chunk.reason && chunk.reason.kind !== 'stop' && chunk.reason.kind !== 'max-tokens') {
946
+ throw new Error(`assistant finish: ${chunk.reason.kind}`)
947
+ }
948
+ }
949
+ if (raw.trim() === '') throw new Error('assistant-empty')
950
+ return raw
951
+ }
952
+ const base = String(a.baseUrl || '').replace(/\/+$/, '')
953
+ const response = await fetch(`${base}/chat/completions`, {
954
+ method: 'POST',
955
+ headers: {
956
+ 'content-type': 'application/json',
957
+ ...(String(a.apiKey || '') !== '' ? { authorization: `Bearer ${a.apiKey}` } : {}),
958
+ },
959
+ body: JSON.stringify({
960
+ model: a.model,
961
+ temperature: 0,
962
+ max_tokens: 600,
963
+ messages: [{ role: 'system', content: system }, { role: 'user', content: user }],
964
+ }),
965
+ signal: controller.signal,
966
+ })
967
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
968
+ const body = await response.json()
969
+ return String(body?.choices?.[0]?.message?.content ?? '')
970
+ } finally {
971
+ clearTimeout(timer)
972
+ }
973
+ }
974
+
719
975
  function publicSnapshot(state) {
720
976
  const items = state.items.slice().sort((a, b) => a.order - b.order).map(itemView)
721
977
  return {
@@ -731,6 +987,16 @@ export async function apply(ctx, config) {
731
987
  storageError: storageError || null,
732
988
  items,
733
989
  summary: summarize(items),
990
+ // v0.3.0:官方 todo 同步状态回声
991
+ todo: (() => {
992
+ const m = todoMirrorOf(state)
993
+ return {
994
+ sync: String(cfg.todoSync || 'off'),
995
+ mirroredAt: m ? m.at : 0,
996
+ count: m ? m.count : 0,
997
+ unsupported: m ? m.unsupported : false,
998
+ }
999
+ })(),
734
1000
  // /progress-goal 迷你目标域回声
735
1001
  goal: state.goal ? goalView(state.sessionId) : null,
736
1002
  // 辅助 LLM 的配置回声:只回非机密字段,apiKey 只回布尔
@@ -940,6 +1206,8 @@ export async function apply(ctx, config) {
940
1206
  if (revisionChanged || (origin === 'agent' && ackUserRevision !== undefined)) {
941
1207
  states.set(sessionId, working)
942
1208
  await persist(sessionId)
1209
+ // 唯一写板入口:持久化之后调度 todo 镜像(200ms 去抖,off 时直接返回)。
1210
+ if (revisionChanged) scheduleTodoMirror(sessionId)
943
1211
  }
944
1212
  // 任何 agent 调用(含 changes=[] 确认)都算一次"模型已看板":重置催办计时;
945
1213
  // 观察者自己的 autoSync(origin='observer')只刷新板新鲜度,不抵消模型催办。
@@ -1520,51 +1788,8 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1520
1788
  o.tools.length ? `最近动作:${o.tools.slice(-cfg.observer.maxTools).map((x) => x.name).join(' → ')}` : '最近动作:—',
1521
1789
  files.length ? `最近改动:${files.join(' · ')}` : '最近改动:—',
1522
1790
  ]
1523
- const controller = new AbortController()
1524
- const timer = setTimeout(() => controller.abort(), Math.max(2000, Number(a.timeoutMs) || 20000))
1525
1791
  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
- }
1792
+ const raw = await callAssistant({ system: ASSISTANT_SYSTEM, user: lines.join('\n'), a })
1568
1793
  const proposal = parseProposal(raw)
1569
1794
  if (!proposal) throw new Error('proposal-unparsable')
1570
1795
  o.assistantError = ''
@@ -1578,8 +1803,6 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1578
1803
  }
1579
1804
  } catch (err) {
1580
1805
  o.assistantError = err instanceof Error ? err.message : String(err)
1581
- } finally {
1582
- clearTimeout(timer)
1583
1806
  }
1584
1807
  }
1585
1808
 
@@ -1620,8 +1843,12 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1620
1843
  // 机械对比(算术,非语义):两套清单完成数漂移 → 让模型自己核对
1621
1844
  const boardDone = state.items.filter((item) => item.status === 'done').length
1622
1845
  if (t.todoDone !== boardDone) {
1846
+ // 旧对比行保留(既有 observer 用例断言逐字匹配),新漂移行按 spec 追加。
1623
1847
  lines.push(`对比:官方 todo 完成 ${t.todoDone}/${t.todoTotal} · 板完成 ${boardDone}/${state.items.length}(进度不一致,核对后修正一处)`)
1848
+ lines.push(`[todo 漂移] 官方 ${t.todoDone}/${t.todoTotal} · 板 ${boardDone}/${state.items.length}(待裁决)`)
1624
1849
  }
1850
+ const mirror = todoMirrorOf(state)
1851
+ if (mirror && !mirror.unsupported) lines.push(`[todo 镜像] 已同步 rev=${state.revision} · ${mirror.count} 条`)
1625
1852
  }
1626
1853
  const files = Array.isArray(o.files) ? o.files.slice(-4) : []
1627
1854
  if (files.length) lines.push(`最近改动:${files.map((f) => `${shortPath(f.path)}(${f.tool})`).join(' · ')}`)
@@ -1655,6 +1882,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
1655
1882
  if (!agent || !agent.id || !agent.ctx) return
1656
1883
  if (hookedAgents.has(agent)) return
1657
1884
  hookedAgents.add(agent)
1885
+ agentOfSession.set(sessionOfAgent(agent), agent)
1658
1886
  try {
1659
1887
  agent.ctx.on('agent/pre-step', async (payload, next) => {
1660
1888
  const sid = String(agent.session?.id ?? agent.id)
@@ -2095,6 +2323,12 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2095
2323
  .filter(Boolean)
2096
2324
  .slice(0, 8)
2097
2325
  tk.lastActivityAt = now()
2326
+ // 回环识别:自家镜像写入(hash 命中)只更新 ETA 原料,不触发裁决。
2327
+ const mirror = todoMirrorOf(states.get(sid))
2328
+ const incomingHash = hashTodos(todos)
2329
+ if (!mirror || mirror.unsupported || incomingHash !== mirror.hash) {
2330
+ void maybeReconcileTodo(sid, todos, incomingHash)
2331
+ }
2098
2332
  }
2099
2333
  return
2100
2334
  }
@@ -2124,6 +2358,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2124
2358
  return
2125
2359
  }
2126
2360
  if (type === 'turn/start') {
2361
+ reconcileCallsThisTurn.set(sid, 0)
2127
2362
  const task = taskOf(sid)
2128
2363
  markLineage(task, session)
2129
2364
  const pendingText = userTextMap.get(sid) || ''
@@ -2810,6 +3045,7 @@ ${reason}。本回合开始前先用 progress_update 处理进度板:用户这
2810
3045
  for (const agent of agents?.list?.() ?? []) bindAgentContext(agent)
2811
3046
  const offCreated = ctx.on('agent/created', ({ agent }) => bindAgentContext(agent))
2812
3047
  const offDisposed = ctx.on('agent/disposed', ({ agent }) => {
3048
+ agentOfSession.delete(sessionOfAgent(agent))
2813
3049
  const dispose = agentDisposers.get(sessionOfAgent(agent))
2814
3050
  if (dispose) {
2815
3051
  dispose()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-progress-union",
3
- "version": "0.1.9",
3
+ "version": "0.3.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",
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,19 +58,22 @@ 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`)
62
65
  }
63
66
  })
64
67
 
65
- test('客户端:设置卡注册到 settings.section 且走 configForms 句柄', () => {
68
+ test('客户端:设置卡双座位(settings.section + plugins.bundle.config)且走 configForms 句柄', () => {
66
69
  const file = new URL('../client.js', import.meta.url).pathname.replace(/^\//, '')
67
70
  const src = fs.readFileSync(file, 'utf8')
68
- assert.match(src, /name: 'settings\.section'/, '必须注册 settings.section 槽')
71
+ assert.match(src, /registerSettingsSeat\('settings\.section'/, '必须注册 settings.section 槽')
69
72
  assert.match(src, /id: 'dsh-progress-union'/, '分节 id 必须固定')
73
+ assert.match(src, /registerSettingsSeat\('plugins\.bundle\.config'/, 'bundle 详情页也要有配置卡(keyed by 包名)')
74
+ assert.match(src, /key: 'dsh-progress-union'/, 'bundle 座位 key 必须是包名')
70
75
  assert.match(src, /configForms/, '必须经宿主 configForms 读写配置')
71
76
  assert.match(src, /function ProgressUnionSettings\(/, '设置卡组件必须在')
72
77
  assert.match(src, /scope\.subscribe/, '设置卡要订阅句柄快照')
78
+ assert.match(src, /function ensureUnionSettingsStyle\(/, '样式要注入 document.head,否则设置页里裸奔')
73
79
  })
@@ -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
+ })