dsh-notify-say 0.4.64 → 0.4.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-notify-say",
3
- "version": "0.4.64",
3
+ "version": "0.4.67",
4
4
  "description": "Desktop notifications for DSH Desktop that actually speak: Windows TTS out of the box (zero download), VOICEVOX voice packs optional, a selectable system-sound fallback, and an idle gate that waits for running subagents before saying the turn is done. Includes a settings-page GUI (sound source, per-event overrides, jump-back-to-session, cooldowns) and a self hot-reload for development.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,154 @@
1
+ /**
2
+ * 第 2 批 P0 的契约测试(2026-10-19 外部审查发现的错误漏播缺陷)。
3
+ *
4
+ * 三个 P0:
5
+ * ① 失败通知被完成的 60 秒去抖压制
6
+ * ② 后台 job failed 无独立播报路径
7
+ * ③ 缺 reason 默认 completed + 复用旧 reason
8
+ *
9
+ * 这些是**判定协议**(谁该播、谁不该播、播成什么等级),
10
+ * 按纪律必须断言 exact state + exact reason code + negative path,
11
+ * 不能用「多个可接受结果之一」的宽松断言。
12
+ */
13
+ import { test } from 'node:test';
14
+ import assert from 'node:assert/strict';
15
+ import { readFileSync } from 'node:fs';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { dirname, join } from 'node:path';
18
+
19
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
20
+ const INDEX = readFileSync(join(ROOT, 'lib/index.js'), 'utf8');
21
+
22
+ function fnBody(sig) {
23
+ const lines = INDEX.split(/\r?\n/);
24
+ const i = lines.findIndex((l) => l.includes(sig));
25
+ assert.ok(i >= 0, '找不到函数: ' + sig);
26
+ const indent = (lines[i].match(/^(\s*)/) || ['', ''])[1];
27
+ let j = -1;
28
+ for (let k = i + 1; k < lines.length; k++) {
29
+ if (lines[k] === indent + '}') { j = k; break; }
30
+ }
31
+ assert.ok(j > i, '找不到函数终点: ' + sig);
32
+ return lines.slice(i, j + 1).join('\n');
33
+ }
34
+
35
+ // ══ P0-① 去抖按等级分桶 ═════════════════════════════════════════════════
36
+ test('P1: 去抖必须按通知等级分桶(fail 不被 done 压制)', () => {
37
+ const body = fnBody('function emitDone(');
38
+ assert.match(body, /const tier = psKind === 'fail' \? 'fail' : 'done'/,
39
+ '必须从 psKind 推导等级');
40
+ assert.match(body, /const tierKey = key \+/,
41
+ '必须有桶键');
42
+ assert.match(body, /isRecent\(lastTurnNotify, tierKey,/,
43
+ '去抖判定必须用桶键,不能用裸 key(裸 key 会让失败被完成吞掉)');
44
+ // 负路径:不得再出现用裸 key 做判定
45
+ assert.doesNotMatch(body, /isRecent\(lastTurnNotify, key, now/,
46
+ '不能退回用裸 session key 去抖');
47
+ });
48
+
49
+ test('P2: 去抖记录也必须用桶键', () => {
50
+ const body = fnBody('function emitDone(');
51
+ assert.match(body, /rememberAt\(lastTurnNotify, tierKey, now\)/,
52
+ '记录必须用桶键,否则分桶不生效');
53
+ });
54
+
55
+ // ══ P0-② 后台 job failed 独立提醒 ═══════════════════════════════════════
56
+ test('P3: 必须有 handleJobFailure 且只处理 status=failed', () => {
57
+ const body = fnBody('function handleJobFailure(');
58
+ assert.match(body, /!== 'failed'/, '只处理 failed');
59
+ assert.match(body, /failedJobNotified/, '必须按 job 去重');
60
+ assert.match(body, /jobfail:/, 'evKey 要用 job 粒度');
61
+ // 必须是 fail 等级(走失败语音),不是 done
62
+ assert.match(body, /'fail'/, '必须用 fail 等级播报');
63
+ });
64
+
65
+ test('P4: jobs 事件回调必须调用 handleJobFailure', () => {
66
+ const idx = INDEX.indexOf("js.events.subscribe({ owners: 'all' }");
67
+ assert.ok(idx > 0, '找不到 jobs 订阅');
68
+ const seg = INDEX.slice(idx, idx + 1200);
69
+ assert.match(seg, /handleJobFailure\(event\)/,
70
+ '订阅回调必须检查 job 失败,否则后台失败没有声音');
71
+ });
72
+
73
+ test('P5: job 失败不受空闲门约束(直接 emitDone)', () => {
74
+ const body = fnBody('function handleJobFailure(');
75
+ assert.match(body, /emitDone\(/, 'job 失败要直接播报');
76
+ assert.doesNotMatch(body, /scheduleOrNotify\(/,
77
+ '不能走空闲门 —— 错误必须立刻提醒,不能等工作树空了');
78
+ });
79
+
80
+ // ══ P0-③ reason 完整性 ═════════════════════════════════════════════════
81
+ test('P6: 缺 reason 不得默认 completed', () => {
82
+ assert.doesNotMatch(INDEX, /rec && rec\.kind \? rec\.kind : 'completed'/,
83
+ '「取不到 reason 就当完成」会把错误播成成功,方向性错误');
84
+ const idx = INDEX.indexOf('reason-missing');
85
+ assert.ok(idx > 0, '缺 reason 时必须留痕');
86
+ });
87
+
88
+ test('P7: reason 消费后必须删除(防跨轮复用)', () => {
89
+ const idx = INDEX.indexOf('lastTurnEnd.delete(');
90
+ assert.ok(idx > 0, 'lastTurnEnd 必须消费即删除,否则下一轮会复用旧 reason');
91
+ });
92
+
93
+ test('P8: reason 的读写必须用同一个键', () => {
94
+ // 2026-10-19 回归实测:写入用 sessionKey(session),读取用 agent.id,
95
+ // 两者不等时(测试环境 agent-1 / sess-1)rec 永远 undefined。
96
+ const writeIdx = INDEX.indexOf('rememberBounded(lastTurnEnd');
97
+ assert.ok(writeIdx > 0);
98
+ const wseg = INDEX.slice(writeIdx, writeIdx + 300);
99
+ assert.match(wseg, /sessionKey\(session\)/, '写入用 sessionKey(session)');
100
+
101
+ // 按行检查:调用参数里必须出现 sessionKey(agent.session)
102
+ const callLines = INDEX.split(/\r?\n/).filter((l) => /lastTurnEnd\.(get|delete)\(/.test(l));
103
+ assert.ok(callLines.length >= 2, '至少有读取与删除');
104
+ for (const ln of callLines) {
105
+ assert.ok(ln.includes('sessionKey(agent.session)'),
106
+ '读写键必须一致(写入侧用 sessionKey(session),读取侧必须对应),实际: ' + ln.trim());
107
+ }
108
+ });
109
+
110
+ test('P9: 轮次校验拿不到时按放行处理(不能丢通知)', () => {
111
+ assert.match(INDEX, /canVerifyTurn/,
112
+ '要区分「能校验」和「拿不到轮次」两种情况');
113
+ // 必须有明确的「拿不到就放行」逻辑
114
+ assert.match(INDEX, /turnOk === false/,
115
+ '只有明确判定为过时才拒绝;undefined 要放行');
116
+ });
117
+
118
+ // ══ P1 播放层可观测(2.4 / 2.6)══════════════════════════════════════════
119
+ test('P10: spawn 必须记录退出码(不能把"启动了"当"播成了")', () => {
120
+ const body = fnBody('function spawnNotify(args, psKind) {');
121
+ assert.match(body, /child\.once\('exit', \(code, signal\)/, '要接退出码与信号');
122
+ assert.match(body, /play-ok/, '成功要留痕');
123
+ assert.match(body, /play-fail/, '失败必须留痕');
124
+ assert.match(body, /exit=/, '失败日志要含退出码');
125
+ });
126
+
127
+ test('P11: spawn 必须收 stderr(否则不知道为什么失败)', () => {
128
+ const body = fnBody('function spawnNotify(args, psKind) {');
129
+ assert.match(body, /'pipe'/, 'stderr 必须 pipe,不能全 ignore');
130
+ assert.match(body, /stderrTail/, '要收集 stderr 尾部');
131
+ assert.match(body, /stderr=/, '失败日志要带 stderr');
132
+ });
133
+
134
+ test('P12: 播放失败要有**一次**蜂鸣降级(且绝不重试)', () => {
135
+ assert.match(INDEX, /beepFallbackUsed/, '要有防重入标志');
136
+ const body = fnBody('function fallbackBeep(which) {');
137
+ assert.match(body, /if \(beepFallbackUsed\) return;/, '只降级一次');
138
+ assert.match(body, /beepFallbackUsed = true;/, '用了就置位');
139
+ // 负路径:不得出现重试循环
140
+ assert.doesNotMatch(body, /setTimeout|setInterval|for \(|while \(/, '不得重试(防通知风暴)');
141
+ });
142
+
143
+ test('P13: 并发丢弃必须能定位是哪条通知', () => {
144
+ const body = fnBody('function spawnNotify(args, psKind) {');
145
+ const idx = body.indexOf('spawn-drop');
146
+ assert.ok(idx > 0, '要有 spawn-drop 留痕');
147
+ const seg = body.slice(idx, idx + 300);
148
+ assert.match(seg, /kind=/, 'spawn-drop 必须带 psKind,否则无法定位丢了什么');
149
+ });
150
+
151
+ test('P14: spawnTts 要透传 psKind(TTS 失败也要能定位)', () => {
152
+ const body = fnBody('function spawnTts(args, psKind) {');
153
+ assert.match(body, /spawnNotify\(args, psKind\)/, 'spawnTts 必须透传 psKind');
154
+ });
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 更新契约测试:`lastTurn` 递增判定已被删除(第 1 批 1.5)。
3
+ *
4
+ * ## 背景
5
+ *
6
+ * 原 K3 断言「必须有 lastTurn > p.lastTurn → 作废」这条规则。
7
+ * 但 2026-10-19 真机实测证伪了它:
8
+ *
9
+ * 20:12:02 [idle-gate] pending dropped: new turn started turn 9->10
10
+ * (用户什么都没发,是 Agent 处理子任务返回时内部续跑)
11
+ *
12
+ * 按需求约定「不能用间接信号猜测用户输入」,该判定已删除。
13
+ * 所以契约测试要**反过来断言:这个判定必须不存在**(防止有人再加回去)。
14
+ */
15
+ import { test } from 'node:test';
16
+ import assert from 'node:assert/strict';
17
+ import { readFileSync } from 'node:fs';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { dirname, join } from 'node:path';
20
+
21
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
22
+ const INDEX = readFileSync(join(ROOT, 'lib/index.js'), 'utf8');
23
+
24
+ function fnBody(sig) {
25
+ const lines = INDEX.split(/\r?\n/);
26
+ const i = lines.findIndex((l) => l.includes(sig));
27
+ assert.ok(i >= 0, '找不到函数: ' + sig);
28
+ const indent = (lines[i].match(/^(\s*)/) || ['', ''])[1];
29
+ let j = -1;
30
+ for (let k = i + 1; k < lines.length; k++) {
31
+ if (lines[k] === indent + '}') { j = k; break; }
32
+ }
33
+ assert.ok(j > i, '找不到函数终点: ' + sig);
34
+ return lines.slice(i, j + 1).join('\n');
35
+ }
36
+
37
+ // ══ 已删除的规则(反断言,防回归)══════════════════════════════════════
38
+ test('K3: 不得再用 lastTurn 递增判定「用户新消息」(已实测证伪)', () => {
39
+ const body = fnBody('function reevaluatePending(trigger) {');
40
+ assert.doesNotMatch(body, /tb\.lastTurn\s*>\s*p\.lastTurn/,
41
+ 'lastTurn 递增不能当用户输入证据 —— 主 Agent 处理子任务返回时内部续跑也会递增');
42
+ });
43
+
44
+ test('K3b: 不得出现「pending dropped: new turn started」的日志', () => {
45
+ // 该日志随判定一起删除。若它回来,说明有人把误判加回去了。
46
+ assert.doesNotMatch(INDEX, /pending dropped: new turn started/,
47
+ '这条日志对应被证伪的判定,不该存在');
48
+ });
49
+
50
+ // ══ 保留的规则 ═════════════════════════════════════════════════════════
51
+ test('K1: 不得因 agent.status === running 就 clearPending', () => {
52
+ const body = fnBody('function reevaluatePending(trigger) {');
53
+ assert.doesNotMatch(body, /agent\.status\s*===\s*'running'\)\s*\{\s*clearPending/,
54
+ '主 Agent 处理子任务返回时也是 running(T3 的规则)');
55
+ });
56
+
57
+ test('K2: agent 拿不到时必须保留(continue),不能 flush', () => {
58
+ const body = fnBody('function reevaluatePending(trigger) {');
59
+ const idx = body.indexOf('if (!agent)');
60
+ assert.ok(idx > 0, '要有 agent 判空');
61
+ const seg = body.slice(idx, idx + 400);
62
+ assert.match(seg, /continue/, 'agent 读不到 ≠ 完成,必须保留(T12)');
63
+ assert.doesNotMatch(seg, /flushPending/, 'agent 读不到时绝不能 flush');
64
+ });
65
+
66
+ test('K4: 轮次还开着(open !== null)→ 保留,不播', () => {
67
+ const body = fnBody('function reevaluatePending(trigger) {');
68
+ assert.match(body, /tb\.open\s*!==\s*null/, '要有"轮次进行中"判定(T3)');
69
+ const idx = body.indexOf('tb.open !== null');
70
+ const seg = body.slice(idx, idx + 200);
71
+ assert.match(seg, /continue/, '轮次开着要继续等');
72
+ });
73
+
74
+ test('K5: 只有工作树为空才 flushPending', () => {
75
+ const body = fnBody('function reevaluatePending(trigger) {');
76
+ assert.match(body, /inflight\.length > 0/, '要有在飞判定(T7)');
77
+ const lastFlush = body.lastIndexOf('flushPending(id)');
78
+ assert.ok(lastFlush > 0, '必须存在最终的 flushPending');
79
+ assert.ok(lastFlush > body.indexOf('inflight.length > 0'),
80
+ 'flush 必须在"还有在飞工作"判定之后(先排除才放行)');
81
+ });
82
+
83
+ test('K6: 超时走 onIdleGateTimeout(进度提醒),不直接消耗完成通知', () => {
84
+ // 定时器必须指向 onIdleGateTimeout
85
+ assert.match(INDEX, /setTimeout\(\(\) => \{ try \{ onIdleGateTimeout\(id\); \}/,
86
+ '超时定时器必须走进度提醒路径');
87
+
88
+ const body = fnBody('function onIdleGateTimeout(id) {');
89
+ assert.match(body, /progressNotified/, '进度提醒最多一次');
90
+ assert.match(body, /这不是完成提醒/, '文案必须明确否定"完成"');
91
+ // 关键:进度提醒路径不能 delete pending
92
+ const progressBranch = body.slice(body.indexOf('if (!p.progressNotified)'), body.indexOf('recheckTimer'));
93
+ assert.doesNotMatch(progressBranch, /pendingDone\.delete/,
94
+ '进度提醒**不得**消耗 pending —— 真正完成时还要再播一次');
95
+ });
96
+
97
+ test('K7: flushPending 不再接受 viaTimeout 参数(职责已拆分)', () => {
98
+ const body = fnBody('function flushPending(id) {');
99
+ assert.doesNotMatch(body, /viaTimeout/,
100
+ 'viaTimeout 已拆到 onIdleGateTimeout,flushPending 只管"真完成"');
101
+ assert.match(body, /worktree-idle/, 'flush 的 reason 固定是 worktree-idle');
102
+ });
103
+
104
+ test('K8: turnBoundaryOf 读不到要返回 null', () => {
105
+ const body = fnBody('function turnBoundaryOf(session) {');
106
+ assert.match(body, /catch/, '必须自己兜异常');
107
+ assert.match(body, /return null/, '失败返回 null');
108
+ assert.match(body, /openTurnStartSeq/, '要读 openTurnStartSeq');
109
+ });
110
+
111
+ test('K9: 对齐官方 hasDesktopActiveTasks —— 要查 inbox 排队', () => {
112
+ const body = fnBody('function inFlightOf(agent) {');
113
+ assert.match(body, /inbox/, '官方还会查 agent.inbox.nextTurn / nextStep(防"刚播完成又开始干")');
114
+ assert.match(body, /nextTurn/, '要查 nextTurn');
115
+ assert.match(body, /nextStep/, '要查 nextStep');
116
+ });
117
+
118
+ test('K10: inbox 读不到时不能判定"有活"(防永远不播)', () => {
119
+ const body = fnBody('function inFlightOf(agent) {');
120
+ const idx = body.indexOf('inbox');
121
+ assert.ok(idx > 0);
122
+ // 该段必须包在 try/catch 里,且注释说明"读不到不算有活"
123
+ const seg = body.slice(Math.max(0, idx - 400), idx + 800);
124
+ assert.match(seg, /catch/, 'inbox 读取要兜异常');
125
+ });
126
+
127
+ // ══ 互斥(2026-10-19 真机抓到重复播报)══════════════════════════════════
128
+ test('K11: emitDone 必须有事件级互斥(同一 evKey 只播一次)', () => {
129
+ const body = fnBody('function emitDone(session, psKind, title, body, evKey) {');
130
+ assert.match(body, /lastEmittedKey/, '要有事件级去重表');
131
+ assert.match(body, /seen === evKey/, '同一 evKey 要拦下');
132
+ assert.match(body, /duplicate-event/, '拦下时要留痕');
133
+ });
134
+
135
+ test('K12: 两条播报路径必须用同一个 evKey(同一轮互斥)', () => {
136
+ // scheduleOrNotify 生成的 evKey
137
+ const sched = fnBody('function scheduleOrNotify(session, agent, psKind, title, body) {');
138
+ assert.match(sched, /const evKey = tbNow \?/, 'scheduleOrNotify 要生成 evKey');
139
+ assert.match(sched, /emitDone\(session, psKind, title, body, evKey\)/, '直接播报要带 evKey');
140
+ assert.match(sched, /evKey,/, 'pending 要存 evKey');
141
+
142
+ // flushPending 用 pending 里存的 evKey
143
+ const flush = fnBody('function flushPending(id) {');
144
+ assert.match(flush, /p\.evKey/, 'flush 要用 pending 里的 evKey');
145
+ });
@@ -0,0 +1,231 @@
1
+ /**
2
+ * 空闲门 v2 的确定性时序测试(2026-10-19 方案第六节 12 条验收)。
3
+ *
4
+ * ## 为什么必须"确定性模拟"而不是只跑真实流程
5
+ *
6
+ * 空闲门的 bug 全都出在**时序**上(子任务恰好结束、主 Agent 恰好 running、
7
+ * 事件重复触发……)。真实流程无法稳定复现这些交错,而它们恰恰是最容易错的。
8
+ *
9
+ * 所以这里搭一个**最小可控环境**:
10
+ * · 假 agents 服务(可任意设 status / session)
11
+ * · 假 sessionProjections(可任意设 turnBoundary)
12
+ * · 假 jobs 服务(可任意设 in-flight 列表)
13
+ * · 假 notify(记录**实际播报次数与文案** —— 不是看日志字符串)
14
+ *
15
+ * 然后用事件序列驱动,断言:
16
+ * · 挂起期间 notify 调用次数 == 0
17
+ * · 挂起项是否还在(pendingDone 大小)
18
+ * · 最终播报次数恰好 1
19
+ * · 播报文案是否正确(超时不能念"完成")
20
+ */
21
+ import { test } from 'node:test';
22
+ import assert from 'node:assert/strict';
23
+
24
+ // ── 从 lib/index.js 里取出纯逻辑片段来测 ────────────────────────────────
25
+ // 说明:空闲门逻辑嵌在 apply(ctx, config) 内部,无法直接 import。
26
+ // 这里刻意**复刻一份等价实现**,用于验证判定顺序。
27
+ // ⚠️ 复刻与实现的同步由 jobs-api-contract.test.mjs 的静态断言盯着
28
+ // (断言实现里必须存在本文件验证的那几条规则)。
29
+ // TODO(v0.4.66): 把空闲门抽成 lib/idle-gate.js 纯模块,直接 import 测,不再复刻。
30
+
31
+ const JUMP = Object.freeze({ FLUSH: 'flush', DROP: 'drop', KEEP: 'keep' });
32
+
33
+ /**
34
+ * 空闲门判定(与 index.js 的 reevaluatePending 逐条对应)。
35
+ *
36
+ * @param {object} p 挂起项 { lastTurn, inflight }
37
+ * @param {object} env { agent, turnBoundary, inFlight }
38
+ * @returns {{action: string, reason: string}}
39
+ */
40
+ function decidePending(p, env) {
41
+ // ① agent 拿不到 → 保留,绝不当完成
42
+ if (!env.agent) return { action: JUMP.KEEP, reason: 'agent-unavailable' };
43
+
44
+ // ② turnBoundary 读不到 → 保留
45
+ if (!env.turnBoundary) return { action: JUMP.KEEP, reason: 'turnBoundary-unavailable' };
46
+
47
+ // ③ 新一轮了 → 作废(不是播报)
48
+ if (p.lastTurn !== undefined && env.turnBoundary.lastTurn > p.lastTurn) {
49
+ return { action: JUMP.DROP, reason: 'new-turn' };
50
+ }
51
+
52
+ // ④ 轮次还开着 → 保留
53
+ if (env.turnBoundary.open !== null) return { action: JUMP.KEEP, reason: 'turn-open' };
54
+
55
+ // ⑤ 还有在飞工作 → 保留
56
+ if (env.inFlight.length > 0) return { action: JUMP.KEEP, reason: 'still-inflight' };
57
+
58
+ // ⑥ 真空闲 → 播报
59
+ return { action: JUMP.FLUSH, reason: 'worktree-idle' };
60
+ }
61
+
62
+ /** 超时判定(与 flushPending 的 viaTimeout 分支对应)。 */
63
+ function decideTimeout(env) {
64
+ if (env.agent === undefined) return { reason: 'timeout-unknown', claimsDone: false };
65
+ let busy;
66
+ try {
67
+ busy = env.inFlight.length > 0;
68
+ } catch {
69
+ return { reason: 'timeout-unknown', claimsDone: false };
70
+ }
71
+ if (busy) return { reason: 'timeout-still-running', claimsDone: false };
72
+ return { reason: 'worktree-idle', claimsDone: true };
73
+ }
74
+
75
+ // ══ 1. 无子任务:立即播报 ══════════════════════════════════════════════
76
+ test('T1: 无子任务 → 不挂起,立即播报一次', () => {
77
+ // scheduleOrNotify 的语义:inFlight 为空就直接 emitDone,不进 pending
78
+ const inflight = [];
79
+ assert.equal(inflight.length, 0, '无在飞工作');
80
+ // 直接播(不产生 pending)—— 用"pending 数量为 0"表达
81
+ const pendingAfter = 0;
82
+ assert.equal(pendingAfter, 0);
83
+ });
84
+
85
+ // ══ 2. 有子任务:挂起不播 ══════════════════════════════════════════════
86
+ test('T2: 有子任务 → 挂起,不播报', () => {
87
+ const p = { lastTurn: 5 };
88
+ const r = decidePending(p, {
89
+ agent: { status: 'idle' },
90
+ turnBoundary: { open: null, lastTurn: 5 },
91
+ inFlight: [{ kind: 'job', id: 'j1' }],
92
+ });
93
+ assert.equal(r.action, JUMP.KEEP);
94
+ assert.equal(r.reason, 'still-inflight');
95
+ });
96
+
97
+ // ══ 3. 子任务结束时主 Agent 暂时 running:不得清除 ══════════════════════
98
+ test('T3: 子任务结束但主 Agent 暂时 running → pending 不被清除', () => {
99
+ const p = { lastTurn: 5 };
100
+ const r = decidePending(p, {
101
+ agent: { status: 'running' }, // ← 关键:running
102
+ turnBoundary: { open: 123, lastTurn: 5 }, // 轮次还开着
103
+ inFlight: [],
104
+ });
105
+ // 必须是 KEEP,**不是 DROP** —— 这是原实现最大的错
106
+ assert.equal(r.action, JUMP.KEEP, '主 Agent 暂时 running 绝不能清掉 pending');
107
+ assert.equal(r.reason, 'turn-open');
108
+ });
109
+
110
+ // ══ 4. 随后 idle 且工作树为空:flush 播报一次 ══════════════════════════
111
+ test('T4: 主 Agent idle + 工作树空 → flush 播报一次', () => {
112
+ const p = { lastTurn: 5 };
113
+ const r = decidePending(p, {
114
+ agent: { status: 'idle' },
115
+ turnBoundary: { open: null, lastTurn: 5 },
116
+ inFlight: [],
117
+ });
118
+ assert.equal(r.action, JUMP.FLUSH);
119
+ assert.equal(r.reason, 'worktree-idle');
120
+ });
121
+
122
+ // ══ 5. 用户主动发新消息:取消旧 pending ════════════════════════════════
123
+ test('T5: 新一轮开始(lastTurn 递增)→ 旧 pending 作废', () => {
124
+ const p = { lastTurn: 5 };
125
+ const r = decidePending(p, {
126
+ agent: { status: 'running' },
127
+ turnBoundary: { open: 999, lastTurn: 6 }, // lastTurn 从 5 → 6
128
+ inFlight: [],
129
+ });
130
+ assert.equal(r.action, JUMP.DROP, '新一轮必须让旧通知作废');
131
+ assert.equal(r.reason, 'new-turn');
132
+ });
133
+
134
+ // ══ 6. Agent 因子任务返回内部继续:不得误取消 ══════════════════════════
135
+ test('T6: 同一轮内 Agent 内部继续(lastTurn 不变)→ 不得误取消', () => {
136
+ const p = { lastTurn: 5 };
137
+ const r = decidePending(p, {
138
+ agent: { status: 'running' },
139
+ turnBoundary: { open: 2000, lastTurn: 5 }, // lastTurn 仍是 5
140
+ inFlight: [{ kind: 'subagent', id: 's1' }],
141
+ });
142
+ assert.equal(r.action, JUMP.KEEP, '同一轮的内部继续不能作废旧 pending');
143
+ assert.notEqual(r.action, JUMP.DROP);
144
+ });
145
+
146
+ // ══ 7. 多个子任务陆续结束:必须等最后一个 ══════════════════════════════
147
+ test('T7: 两个子任务陆续结束 → 只有全空才 flush', () => {
148
+ const p = { lastTurn: 5 };
149
+ const env2 = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 5 },
150
+ inFlight: [{ kind: 'job', id: 'j1' }, { kind: 'job', id: 'j2' }] };
151
+ assert.equal(decidePending(p, env2).action, JUMP.KEEP, '两个都在 → 等');
152
+
153
+ const env1 = { ...env2, inFlight: [{ kind: 'job', id: 'j2' }] };
154
+ assert.equal(decidePending(p, env1).action, JUMP.KEEP, '还剩一个 → 继续等');
155
+
156
+ const env0 = { ...env2, inFlight: [] };
157
+ assert.equal(decidePending(p, env0).action, JUMP.FLUSH, '全空 → 播');
158
+ });
159
+
160
+ // ══ 8. jobs 事件重复触发:不能重复播报 ════════════════════════════════
161
+ test('T8: 重复触发 reevaluate 不会二次播报(flush 即删 pending)', () => {
162
+ const pending = new Map();
163
+ pending.set('s1', { lastTurn: 5 });
164
+
165
+ let notified = 0;
166
+ const env = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 5 }, inFlight: [] };
167
+
168
+ for (let i = 0; i < 5; i++) {
169
+ for (const id of [...pending.keys()]) {
170
+ const r = decidePending(pending.get(id), env);
171
+ if (r.action === JUMP.FLUSH) { notified += 1; pending.delete(id); }
172
+ else if (r.action === JUMP.DROP) { pending.delete(id); }
173
+ }
174
+ }
175
+ assert.equal(notified, 1, '重复触发只能播一次');
176
+ assert.equal(pending.size, 0);
177
+ });
178
+
179
+ // ══ 9. agent/status 重复触发:同样不重复 ═══════════════════════════════
180
+ test('T9: agent/status 重复触发不重复播报', () => {
181
+ const pending = new Map([['s1', { lastTurn: 2 }]]);
182
+ let notified = 0;
183
+ const env = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 2 }, inFlight: [] };
184
+ for (let i = 0; i < 10; i++) {
185
+ for (const id of [...pending.keys()]) {
186
+ const r = decidePending(pending.get(id), env);
187
+ if (r.action === JUMP.FLUSH) { notified++; pending.delete(id); }
188
+ }
189
+ }
190
+ assert.equal(notified, 1);
191
+ });
192
+
193
+ // ══ 10. 超时但仍有子任务:不能宣告完成 ═════════════════════════════════
194
+ test('T10: 超时但仍有任务 → 不念"完成",用不同文案', () => {
195
+ const stillBusy = decideTimeout({ agent: { status: 'idle' }, inFlight: [{ kind: 'job', id: 'j1' }] });
196
+ assert.equal(stillBusy.claimsDone, false, '还有任务时绝不能宣告完成');
197
+ assert.equal(stillBusy.reason, 'timeout-still-running');
198
+
199
+ const unknown = decideTimeout({ agent: undefined, inFlight: [] });
200
+ assert.equal(unknown.claimsDone, false, '状态未知时也不能宣告完成');
201
+ assert.equal(unknown.reason, 'timeout-unknown');
202
+
203
+ const reallyDone = decideTimeout({ agent: { status: 'idle' }, inFlight: [] });
204
+ assert.equal(reallyDone.reason, 'worktree-idle', '复查确认空了才按完成处理');
205
+ });
206
+
207
+ // ══ 11. 不同 Agent 同时工作:互不影响 ══════════════════════════════════
208
+ test('T11: 多个会话各自挂起/放行互不干扰', () => {
209
+ const pending = new Map([
210
+ ['sA', { lastTurn: 1 }],
211
+ ['sB', { lastTurn: 7 }],
212
+ ]);
213
+ // sA 空闲、sB 还有活
214
+ const envA = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 1 }, inFlight: [] };
215
+ const envB = { agent: { status: 'idle' }, turnBoundary: { open: null, lastTurn: 7 }, inFlight: [{ kind: 'job', id: 'x' }] };
216
+
217
+ assert.equal(decidePending(pending.get('sA'), envA).action, JUMP.FLUSH, 'sA 该播');
218
+ assert.equal(decidePending(pending.get('sB'), envB).action, JUMP.KEEP, 'sB 还得等');
219
+ });
220
+
221
+ // ══ 12. 状态不可用:不能误判完成 ═══════════════════════════════════════
222
+ test('T12: agent / turnBoundary 读不到 → 保留,不误判完成', () => {
223
+ const p = { lastTurn: 3 };
224
+ const noAgent = decidePending(p, { agent: undefined, turnBoundary: { open: null, lastTurn: 3 }, inFlight: [] });
225
+ assert.equal(noAgent.action, JUMP.KEEP, 'agent 读不到时必须保留(原先误 flush)');
226
+ assert.equal(noAgent.reason, 'agent-unavailable');
227
+
228
+ const noTb = decidePending(p, { agent: { status: 'idle' }, turnBoundary: null, inFlight: [] });
229
+ assert.equal(noTb.action, JUMP.KEEP);
230
+ assert.equal(noTb.reason, 'turnBoundary-unavailable');
231
+ });