dsh-progress-union 0.1.6 → 0.1.8

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.
@@ -0,0 +1,210 @@
1
+ /**
2
+ * 共享 mock 基座:纯内存 services 驱动 apply(),不起真宿主。
3
+ * 形状对齐 l3j3y3/dsh-progress-board test/host.test.mjs 的 createHarness。
4
+ */
5
+ import { apply } from '../index.js'
6
+
7
+ export const SESSION = 'session-union-test'
8
+
9
+ export function createHarness({ seed = {}, config = {}, withProjection = true, withProvide = true, storageless = false, llm = undefined, settings = undefined } = {}) {
10
+ const records = { ...seed }
11
+ const routes = new Map()
12
+ const toolMap = new Map()
13
+ const commandMap = new Map()
14
+ const sections = new Map()
15
+ const contexts = new Map()
16
+ const listeners = []
17
+ const agentHooks = []
18
+ const provided = new Map()
19
+ const projections = new Map()
20
+
21
+ const unit = {
22
+ async loadAll() {
23
+ return { tables: { sessions: { ...records } } }
24
+ },
25
+ async putRecord(_table, key, record) {
26
+ records[key] = record
27
+ },
28
+ async close() {},
29
+ }
30
+
31
+ const storage = storageless
32
+ ? { backend: { names: () => [], get: () => ({}) } }
33
+ : {
34
+ backend: {
35
+ names: () => ['json'],
36
+ get: () => ({ kv: { open: async () => unit } }),
37
+ },
38
+ }
39
+
40
+ const webServer = {
41
+ register(route) {
42
+ routes.set(route.path, route)
43
+ return () => routes.delete(route.path)
44
+ },
45
+ }
46
+
47
+ const tools = {
48
+ register(definition, options) {
49
+ toolMap.set(definition.name, { definition, options })
50
+ return () => toolMap.delete(definition.name)
51
+ },
52
+ }
53
+
54
+ const commands = {
55
+ register(definition) {
56
+ commandMap.set(definition.name, definition)
57
+ return () => commandMap.delete(definition.name)
58
+ },
59
+ }
60
+
61
+ const systemPrompt = {}
62
+
63
+ const agent = {
64
+ id: SESSION,
65
+ session: { id: SESSION },
66
+ ctx: {
67
+ effect(fn) {
68
+ return fn()
69
+ },
70
+ systemPrompt: {
71
+ section({ name, text }) {
72
+ sections.set(name, text)
73
+ return () => sections.delete(name)
74
+ },
75
+ context({ name, text }) {
76
+ contexts.set(name, text)
77
+ return () => contexts.delete(name)
78
+ },
79
+ },
80
+ on(type, handler) {
81
+ agentHooks.push({ type, handler })
82
+ return () => {
83
+ const index = agentHooks.findIndex((h) => h.type === type && h.handler === handler)
84
+ if (index >= 0) agentHooks.splice(index, 1)
85
+ }
86
+ },
87
+ },
88
+ }
89
+
90
+ const agents = { list: () => [agent] }
91
+
92
+ const ctx = {
93
+ get(name) {
94
+ return { storage, webServer, systemPrompt, tools, agents, commands, llm, settings }[name]
95
+ },
96
+ on(type, handler) {
97
+ listeners.push({ type, handler })
98
+ return () => {
99
+ const index = listeners.findIndex((h) => h.type === type && h.handler === handler)
100
+ if (index >= 0) listeners.splice(index, 1)
101
+ }
102
+ },
103
+ effect(fn) {
104
+ const dispose = fn()
105
+ return () => {
106
+ if (typeof dispose === 'function') dispose()
107
+ }
108
+ },
109
+ inject(deps, callback) {
110
+ if (withProjection && deps.includes('sessionProjections')) {
111
+ callback({
112
+ sessionProjections: {
113
+ register(definition) {
114
+ projections.set(definition.key, definition)
115
+ return () => projections.delete(definition.key)
116
+ },
117
+ },
118
+ })
119
+ } else {
120
+ callback({})
121
+ }
122
+ },
123
+ }
124
+ if (withProvide) {
125
+ ctx.provide = (name, factory) => {
126
+ provided.set(name, factory())
127
+ return () => provided.delete(name)
128
+ }
129
+ }
130
+
131
+ return {
132
+ ctx,
133
+ config,
134
+ agent,
135
+ records,
136
+ routes,
137
+ toolMap,
138
+ commandMap,
139
+ sections,
140
+ contexts,
141
+ listeners,
142
+ agentHooks,
143
+ provided,
144
+ projections,
145
+ run: () => apply(ctx, config),
146
+ /** 按 (session, {type, data}) 派发一条 session/event */
147
+ emit(type, data, session) {
148
+ for (const h of listeners.filter((l) => l.type === 'session/event')) h.handler(session ?? { id: SESSION }, { type, data })
149
+ },
150
+ }
151
+ }
152
+
153
+ export function jsonReq(method, url, body) {
154
+ const payload = Buffer.from(JSON.stringify(body))
155
+ return {
156
+ method,
157
+ url,
158
+ headers: { 'content-type': 'application/json' },
159
+ async *[Symbol.asyncIterator]() {
160
+ yield payload
161
+ },
162
+ }
163
+ }
164
+
165
+ export function getReq(url) {
166
+ return { method: 'GET', url, headers: {} }
167
+ }
168
+
169
+ export function fakeRes() {
170
+ return {
171
+ status: 0,
172
+ body: '',
173
+ writeHead(status) {
174
+ this.status = status
175
+ },
176
+ end(text) {
177
+ this.body = text
178
+ },
179
+ json() {
180
+ return JSON.parse(this.body || '{}')
181
+ },
182
+ }
183
+ }
184
+
185
+ export async function callRoute(harness, path, req) {
186
+ const route = harness.routes.get(path)
187
+ if (!route) throw new Error(`route not registered: ${path}`)
188
+ const res = fakeRes()
189
+ await route.handler(req, res)
190
+ return res
191
+ }
192
+
193
+ export function withClock(fn) {
194
+ const real = Date.now
195
+ let offset = 0
196
+ Date.now = () => real() + offset
197
+ const advance = (ms) => {
198
+ offset += ms
199
+ }
200
+ const restore = () => {
201
+ Date.now = real
202
+ }
203
+ return { advance, restore, real }
204
+ }
205
+
206
+ export async function flush() {
207
+ // 让 persist 写链落完
208
+ await new Promise((resolve) => setImmediate(resolve))
209
+ await new Promise((resolve) => setImmediate(resolve))
210
+ }
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Phase 1 验收:board 增量协议 + ack 语义(fork 自 dsh-progress-board 的协议断言)。
3
+ */
4
+ import assert from 'node:assert/strict'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import test from 'node:test'
9
+
10
+ // 先钉住 DSH_HOME 再动态引入(index.js 模块求值时即读环境变量),避免测试碰真机 stats。
11
+ process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'union-test-'))
12
+ const { SESSION, createHarness, jsonReq, callRoute, flush } = await import('./harness.mjs')
13
+
14
+ async function booted(config) {
15
+ const harness = createHarness({ config })
16
+ await harness.run()
17
+ // 启用板(走 active 路由的 command 源,等价 /progress on)
18
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
19
+ return harness
20
+ }
21
+
22
+ function execUpdate(harness, args) {
23
+ const tool = harness.toolMap.get('progress_update')
24
+ return tool.definition.execute(args, { agent: harness.agent })
25
+ }
26
+
27
+ test('when 门控:默认不加载工具,启用后可见', async () => {
28
+ const harness = createHarness()
29
+ await harness.run()
30
+ const tool = harness.toolMap.get('progress_update')
31
+ assert.equal(tool.options.when({ agent: harness.agent }), false, '未启用时 when 必须为 false')
32
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
33
+ assert.equal(tool.options.when({ agent: harness.agent }), true)
34
+ })
35
+
36
+ test('新增/按 id 更新/删除:只回变化项与紧凑摘要', async () => {
37
+ const harness = await booted()
38
+ const added = await execUpdate(harness, {
39
+ changes: [
40
+ { title: '步骤一', status: 'doing', current: '正在做一', next: '二' },
41
+ { title: '步骤二' },
42
+ ],
43
+ })
44
+ assert.equal(added.ok, true)
45
+ assert.equal(added.revision, 1)
46
+ assert.equal(added.changed.length, 2)
47
+ assert.deepEqual(added.summary, { total: 2, done: 0, doing: 1, todo: 1, blocked: 0, percent: 0 })
48
+
49
+ const firstId = added.changed[0].id
50
+ const edited = await execUpdate(harness, { changes: [{ id: firstId, status: 'done' }] })
51
+ assert.equal(edited.revision, 2)
52
+ assert.deepEqual(edited.changed[0].fields.sort(), ['percent', 'status'])
53
+ assert.equal(edited.summary.done, 1)
54
+ // done 强制 100%
55
+ assert.equal(edited.summary.percent, 50)
56
+
57
+ const removed = await execUpdate(harness, { changes: [{ id: firstId, remove: true }] })
58
+ assert.equal(removed.changed[0].removed, true)
59
+ assert.equal(removed.summary.total, 1)
60
+ })
61
+
62
+ test('按精确 title 更新;单命中正常、新增不误伤', async () => {
63
+ const harness = await booted()
64
+ await execUpdate(harness, { changes: [{ title: '唯一名' }] })
65
+ const byTitle = await execUpdate(harness, { changes: [{ title: '唯一名', status: 'doing' }] })
66
+ assert.equal(byTitle.changed[0].change, 'edit')
67
+ const added = await execUpdate(harness, { changes: [{ title: '不存在的名' }] })
68
+ assert.equal(added.changed[0].change, 'add')
69
+ })
70
+
71
+ test('历史重名数据歧义:按 title 更新报错要求 id', async () => {
72
+ const mkItem = (id, order) => ({
73
+ id, title: '重名', status: 'todo', percent: 0, current: '', next: '', approach: '', note: '',
74
+ group: '', order, updatedAt: 1, updatedBy: 'user',
75
+ })
76
+ const key = Buffer.from(SESSION, 'utf8').toString('base64url')
77
+ const harness = createHarness({
78
+ seed: {
79
+ [key]: {
80
+ record: {
81
+ version: 1, sessionId: SESSION, revision: 3, userRevision: 0, agentSeenRevision: 0,
82
+ enabled: true, createdAt: 1, updatedAt: 1, items: [mkItem('p_a', 0), mkItem('p_b', 1)], userChanges: [],
83
+ },
84
+ },
85
+ },
86
+ })
87
+ await harness.run()
88
+ await assert.rejects(
89
+ () => execUpdate(harness, { changes: [{ title: '重名', status: 'done' }] }),
90
+ /对应多个任务/,
91
+ )
92
+ })
93
+
94
+ test('批量全成全败:坏条目不得让前半批落盘', async () => {
95
+ const harness = await booted()
96
+ const before = await execUpdate(harness, { changes: [{ title: '已有任务' }] })
97
+ await assert.rejects(
98
+ () => execUpdate(harness, { changes: [{ title: '新增成功' }, { id: 'p_不存在', remove: true }] }),
99
+ /找不到要删除的任务/,
100
+ )
101
+ const snapshot = harness.provided.get('progressAnchor').get(SESSION)
102
+ assert.equal(snapshot.revision, before.revision, '失败批次不得推 revision')
103
+ assert.equal(snapshot.board.summary.total, 1, '失败批次不得留下半应用条目')
104
+ })
105
+
106
+ test('409:expectedRevision 过期拒写并回快照', async () => {
107
+ const harness = await booted()
108
+ await execUpdate(harness, { changes: [{ title: 'A' }] })
109
+ const res = await callRoute(
110
+ harness,
111
+ '/progress-union/action',
112
+ jsonReq('POST', '/progress-union/action', { sessionId: SESSION, expectedRevision: 0, changes: [{ title: 'B' }] }),
113
+ )
114
+ assert.equal(res.status, 409)
115
+ assert.match(res.json().error, /已被更新/)
116
+ })
117
+
118
+ test('ack 语义:用户改动未确认时 pending>0,ackUserRevision 后归零', async () => {
119
+ const harness = await booted()
120
+ const added = await execUpdate(harness, { changes: [{ title: '任务一' }] })
121
+ const itemId = added.changed[0].id
122
+
123
+ // 用户在面板改状态(origin=user 走 action 路由)
124
+ const userRes = await callRoute(
125
+ harness,
126
+ '/progress-union/action',
127
+ jsonReq('POST', '/progress-union/action', { sessionId: SESSION, changes: [{ id: itemId, status: 'blocked', note: '在等确认' }] }),
128
+ )
129
+ assert.equal(userRes.status, 200)
130
+ const anchorAfterUserEdit = harness.provided.get('progressAnchor').get(SESSION)
131
+ assert.equal(anchorAfterUserEdit.board.pendingUserChanges, 1)
132
+ assert.equal(anchorAfterUserEdit.userEdits.length, 1)
133
+ assert.equal(anchorAfterUserEdit.userEdits[0].kind, 'edit')
134
+
135
+ // 注入面出现"用户改动"文本,且带 ackUserRevision 指引
136
+ const userEditsText = harness.contexts.get('progress-union-user-edits')()
137
+ assert.match(userEditsText, /progress-board-user-edits/)
138
+ assert.match(userEditsText, new RegExp(`ackUserRevision=${anchorAfterUserEdit.revision}`))
139
+
140
+ // agent 确认(changes=[] + ack),revision 不再增长
141
+ const acked = await execUpdate(harness, { changes: [], ackUserRevision: anchorAfterUserEdit.revision })
142
+ assert.equal(acked.revision, anchorAfterUserEdit.revision)
143
+ const anchorAfterAck = harness.provided.get('progressAnchor').get(SESSION)
144
+ assert.equal(anchorAfterAck.board.pendingUserChanges, 0)
145
+ assert.equal(anchorAfterAck.userEdits.length, 0)
146
+ assert.equal(harness.contexts.get('progress-union-user-edits')(), '')
147
+ })
148
+
149
+ test('ack 越界钳制:ackUserRevision 超过 userRevision 时被钳到 userRevision', async () => {
150
+ const harness = await booted()
151
+ const added = await execUpdate(harness, { changes: [{ title: '任务一' }] })
152
+ const itemId = added.changed[0].id
153
+ await callRoute(
154
+ harness,
155
+ '/progress-union/action',
156
+ jsonReq('POST', '/progress-union/action', { sessionId: SESSION, changes: [{ id: itemId, note: 'x' }] }),
157
+ )
158
+ await execUpdate(harness, { changes: [], ackUserRevision: 999 })
159
+ const anchor = harness.provided.get('progressAnchor').get(SESSION)
160
+ assert.equal(anchor.board.pendingUserChanges, 0)
161
+ })
162
+
163
+ test('面板卸载不关掉工具;/progress off(command 源)才关', async () => {
164
+ const harness = await booted()
165
+ // panel 源的 active=false:不是用户决定,必须忽略
166
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: false, source: 'panel' }))
167
+ assert.equal(harness.toolMap.get('progress_update').options.when({ agent: harness.agent }), true)
168
+ // command 源的 off:真关
169
+ const cmd = harness.commandMap.get('progress')
170
+ cmd.handler({ agent: harness.agent, rawInput: 'off' })
171
+ await flush()
172
+ assert.equal(harness.toolMap.get('progress_update').options.when({ agent: harness.agent }), false)
173
+ // 关板后三块投影全部静默(0 token 回归)
174
+ assert.equal(harness.sections.get('progress-union-policy')(), '')
175
+ assert.equal(harness.contexts.get('progress-union-kickoff')(), '')
176
+ assert.equal(harness.contexts.get('progress-union-user-edits')(), '')
177
+ })
178
+
179
+ test('旧前缀别名 /progress-board/* 仍可用一版', async () => {
180
+ const harness = await booted()
181
+ const res = await callRoute(harness, '/progress-board/snapshot', { method: 'GET', url: `/progress-board/snapshot?sessionId=${SESSION}`, headers: {} })
182
+ assert.equal(res.status, 200)
183
+ assert.equal(res.json().enabled, true)
184
+ })
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Phase 7 验收:观察者(辅助观察最近输出/清单;板滞后及时补与催办)。
3
+ */
4
+ import assert from 'node:assert/strict'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import test from 'node:test'
9
+
10
+ process.env.DSH_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'union-test-'))
11
+ const { SESSION, createHarness, jsonReq, callRoute, flush } = await import('./harness.mjs')
12
+
13
+ async function booted() {
14
+ const harness = createHarness()
15
+ await harness.run()
16
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
17
+ return harness
18
+ }
19
+
20
+ function execUpdate(harness, args) {
21
+ return harness.toolMap.get('progress_update').definition.execute(args, { agent: harness.agent })
22
+ }
23
+
24
+ function observerText(harness) {
25
+ const fn = harness.contexts.get('progress-union-observer')
26
+ assert.ok(fn, 'progress-union-observer 上下文必须注册')
27
+ return fn()
28
+ }
29
+
30
+ test('观察块:清单标记 + 最近输出 + 最近动作 + 官方 todo 行', async () => {
31
+ const harness = await booted()
32
+ await execUpdate(harness, {
33
+ changes: [
34
+ { title: '接口改造', status: 'done' },
35
+ { title: '补集成测试', status: 'doing', current: '写 observer 用例', next: '跑全量' },
36
+ { title: '发版', status: 'todo' },
37
+ ],
38
+ })
39
+ harness.emit('assistant/message', { message: { content: [{ type: 'text', text: '接口改造已完成,接下来补测试。' }] } })
40
+ harness.emit('tool/call', { name: 'Bash', arguments: JSON.stringify({ command: 'npm test' }) })
41
+ harness.emit('todo/write', { todos: [
42
+ { content: '接口改造', status: 'completed' },
43
+ { content: '补集成测试', status: 'in_progress' },
44
+ { content: '发版', status: 'pending' },
45
+ ] })
46
+
47
+ const text = observerText(harness)
48
+ assert.match(text, /<progress-observer revision="1"/)
49
+ assert.match(text, /\[x\] 接口改造/)
50
+ assert.match(text, /\[~\] 补集成测试(0%) · 当前:写 observer 用例 · 下一步:跑全量/)
51
+ assert.match(text, /\[ \] 发版/)
52
+ assert.match(text, /最近输出:「接口改造已完成,接下来补测试。/)
53
+ assert.match(text, /最近动作:Bash/)
54
+ assert.match(text, /\[官方todo\] 完成 1\/3,未完:补集成测试、发版/)
55
+ assert.doesNotMatch(text, /滞后/, '未超阈值不得催办')
56
+ })
57
+
58
+ test('滞后刚需:超 N 步未写板 → 催办出现;模型写板后消失', async () => {
59
+ const harness = await booted()
60
+ await execUpdate(harness, { changes: [{ title: '唯一任务', status: 'doing' }] })
61
+ for (let i = 0; i < 6; i++) harness.emit('step/start', {})
62
+ const text = observerText(harness)
63
+ assert.match(text, /⚠ 进度已滞后(6 步前)/)
64
+ assert.match(text, /先调用 progress_update 同步再继续/)
65
+
66
+ // 模型自己同步(无变化确认也算)→ 催办消失
67
+ await execUpdate(harness, { changes: [] })
68
+ assert.doesNotMatch(observerText(harness), /滞后/)
69
+ })
70
+
71
+ test('观察者自动补 current:事实性最近动作写入 doing 项(updatedBy=observer),不抵消催办', async () => {
72
+ const harness = await booted()
73
+ const added = await execUpdate(harness, { changes: [{ title: '造帧', status: 'doing', current: '热身' }] })
74
+ const itemId = added.changed[0].id
75
+ harness.emit('tool/call', { name: 'Bash', arguments: JSON.stringify({ command: 'render --frames 900' }) })
76
+ for (let i = 0; i < 6; i++) harness.emit('step/start', {})
77
+ await flush()
78
+
79
+ const snap = (await callRoute(harness, '/progress-union/snapshot', { method: 'GET', url: `/progress-union/snapshot?sessionId=${SESSION}`, headers: {} })).json()
80
+ const item = snap.items.find((x) => x.id === itemId)
81
+ assert.match(item.current, /^自动同步:Bash · command=render --frames 900/)
82
+ assert.equal(item.updatedBy, 'observer')
83
+ assert.equal(item.status, 'doing', '观察者不得改状态')
84
+ assert.ok(snap.revision >= 2)
85
+
86
+ // 自动补不重置\"模型同步\"计数:催办仍在(状态/百分比仍需模型确认)
87
+ assert.match(observerText(harness), /⚠ 进度已滞后/)
88
+ })
89
+
90
+ test('progress_update 拉通道:返回 inFlight 明细 + time 字段', async () => {
91
+ const harness = await booted()
92
+ const r = await execUpdate(harness, {
93
+ changes: [
94
+ { title: '甲', status: 'done' },
95
+ { title: '乙', status: 'doing', current: '做乙', next: '做丙' },
96
+ { title: '丙', status: 'blocked', note: '等确认' },
97
+ ],
98
+ })
99
+ assert.equal(r.inFlight.length, 2)
100
+ assert.deepEqual(r.inFlight.map((x) => x.status), ['doing', 'blocked'])
101
+ assert.equal(typeof r.time.etaBasis, 'string')
102
+ assert.equal(typeof r.time.steps, 'number')
103
+ assert.equal(typeof r.time.staleMin, 'number')
104
+ })
105
+
106
+ test('最近改动:带路径的工具调用入块,同路径去重、只留最近 4 个', async () => {
107
+ const harness = await booted()
108
+ await execUpdate(harness, { changes: [{ title: '改代码', status: 'doing' }] })
109
+ const call = (file, tool = 'Edit') => harness.emit('tool/call', { name: tool, arguments: JSON.stringify({ file_path: file }) })
110
+ call('E:\\proj\\src\\a.ts')
111
+ call('E:\\proj\\src\\b.ts', 'Write')
112
+ call('E:\\proj\\src\\a.ts') // 同路径去重,留最新
113
+ call('E:\\proj\\src\\c.ts')
114
+ call('E:\\proj\\src\\d.ts')
115
+ call('E:\\proj\\src\\e.ts')
116
+
117
+ const text = observerText(harness)
118
+ const line = text.split('\n').find((l) => l.startsWith('最近改动:'))
119
+ assert.ok(line, '最近改动行必须存在')
120
+ assert.equal((line.match(/(/g) || []).length, 4, '最多 4 条')
121
+ assert.doesNotMatch(line, /b\.ts/, '被后 4 条挤出(上限保留最近)')
122
+ assert.match(line, /a\.ts(Edit)/, '同路径重写后保留最新一条')
123
+ assert.equal((line.match(/a\.ts/g) || []).length, 1, '同路径只出现一次(去重)')
124
+ })
125
+
126
+ test('清单对比:todo 与板完成数漂移才出对比行(算术,非语义)', async () => {
127
+ const harness = await booted()
128
+ await execUpdate(harness, {
129
+ changes: [{ title: '甲', status: 'done' }, { title: '乙', status: 'doing' }, { title: '丙', status: 'todo' }],
130
+ })
131
+ harness.emit('todo/write', { todos: [
132
+ { content: '甲', status: 'completed' },
133
+ { content: '乙', status: 'completed' },
134
+ { content: '丙', status: 'pending' },
135
+ ] })
136
+ const drifted = observerText(harness)
137
+ assert.match(drifted, /对比:官方 todo 完成 2\/3 · 板完成 1\/3(进度不一致/)
138
+
139
+ // 对齐后不再出对比行
140
+ await execUpdate(harness, { changes: [{ title: '乙', status: 'done' }] })
141
+ assert.doesNotMatch(observerText(harness), /对比:/)
142
+ })
143
+
144
+ test('观察者自补的 current 在块里标注待确认', async () => {
145
+ const harness = await booted()
146
+ await execUpdate(harness, { changes: [{ title: '造帧', status: 'doing', current: '热身' }] })
147
+ harness.emit('tool/call', { name: 'Bash', arguments: JSON.stringify({ command: 'render' }) })
148
+ for (let i = 0; i < 6; i++) harness.emit('step/start', {})
149
+ await flush()
150
+ assert.match(observerText(harness), /当前:自动同步:Bash · command=render(观察者补,待确认)/)
151
+ })
152
+
153
+ test('门控:关板/全完成/空板时观察块为空(0 token)', async () => {
154
+ const harness = createHarness()
155
+ await harness.run()
156
+ assert.equal(observerText(harness), '', '未启用不得注入')
157
+
158
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
159
+ assert.equal(observerText(harness), '', '空板不注入(kickoff 负责)')
160
+
161
+ await execUpdate(harness, { changes: [{ title: '唯一任务', status: 'done' }] })
162
+ assert.equal(observerText(harness), '', '全完成不打扰')
163
+ })
164
+
165
+ test('可关:observer.enabled=false 时零注入', async () => {
166
+ const harness = createHarness({ config: { observer: { enabled: false } } })
167
+ await harness.run()
168
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
169
+ await execUpdate(harness, { changes: [{ title: '任务', status: 'doing' }] })
170
+ assert.equal(observerText(harness), '')
171
+ })
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Should-Pass 验收:stats 学习链兼容——读鲸程(dsh-progress-task-bar)既有
3
+ * `$DSH_HOME/dsh-progress-stats.json` 样本:不迁移、不改路径、不损坏原样本,
4
+ * 新样本只在原数组尾部追加并按同一 schema 回写。
5
+ */
6
+ import assert from 'node:assert/strict'
7
+ import fs from 'node:fs'
8
+ import os from 'node:os'
9
+ import path from 'node:path'
10
+ import test from 'node:test'
11
+
12
+ const HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'union-stats-'))
13
+ process.env.DSH_HOME = HOME
14
+ const STATS = path.join(HOME, 'dsh-progress-stats.json')
15
+
16
+ // 鲸程原样写出的文件:s=第几步,r=当时离任务结束还剩几秒。
17
+ const LEGACY = Array.from({ length: 25 }, (_, i) => ({ s: 1, r: 60 + i * 10 }))
18
+ fs.writeFileSync(STATS, JSON.stringify({ version: 1, updatedAt: 1000, samples: LEGACY }))
19
+
20
+ const { SESSION, createHarness, jsonReq, callRoute, withClock } = await import('./harness.mjs')
21
+
22
+ test('既有样本被读取成本机学习档,且新样本追加回写不损坏原样本', async () => {
23
+ const clock = withClock()
24
+ try {
25
+ const harness = createHarness()
26
+ await harness.run()
27
+ await callRoute(harness, '/progress-union/active', jsonReq('POST', '/progress-union/active', { sessionId: SESSION, active: true, source: 'command' }))
28
+
29
+ harness.emit('turn/start', {})
30
+ harness.emit('step/start', {})
31
+ clock.advance(30000)
32
+
33
+ // 25 条 s=1 样本 → bucket [1,2) 满 20 条,etaBasis 应从 'prior' 升到 'local'
34
+ const learned = harness.provided.get('progressAnchor').get(SESSION)
35
+ assert.equal(learned.time.etaBasis, 'local')
36
+ assert.equal(learned.time.etaP75Min, 4) // p75 = 240s
37
+
38
+ // 结束回合:产生一条真实样本 { s: 1, r: 30 }
39
+ harness.emit('turn/end', {})
40
+
41
+ const saved = JSON.parse(fs.readFileSync(STATS, 'utf8'))
42
+ assert.equal(saved.version, 1, 'schema version 保持 1(未迁移)')
43
+ assert.ok(saved.updatedAt > 1000, 'updatedAt 已刷新')
44
+ assert.deepEqual(saved.samples.slice(0, LEGACY.length), LEGACY, '既有 25 条原样保留')
45
+ assert.deepEqual(saved.samples.at(-1), { s: 1, r: 30 }, '新样本追加在尾部')
46
+ assert.equal(saved.samples.length, LEGACY.length + 1)
47
+
48
+ // 不迁移:DSH_HOME 里没有第二份 stats 文件
49
+ const extra = fs.readdirSync(HOME).filter((f) => /progress.*stats/.test(f) && f !== path.basename(STATS))
50
+ assert.deepEqual(extra, [], '没有生成迁移副本')
51
+ } finally {
52
+ clock.restore()
53
+ }
54
+ })