@aibyzero/cm-workflow 0.16.7 → 0.16.9

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.
Files changed (182) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +39 -3
  4. package/VERSION +1 -1
  5. package/assets/readme/workflow-recovery-detailed.png +0 -0
  6. package/assets/readme/workflow-stages-detailed.png +0 -0
  7. package/compat/claude-commands/cm-notify.md +3 -0
  8. package/docs/installation.md +1 -1
  9. package/docs/js-workflow-control.md +61 -4
  10. package/docs/next-steps.md +8 -2
  11. package/docs/user-guide.md +204 -0
  12. package/package.json +2 -1
  13. package/runtime/js/cm-ai/claude-review-stream.mjs +49 -13
  14. package/runtime/js/cm-ai/cm-ai-admission.mjs +3 -1
  15. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +138 -26
  16. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +142 -21
  17. package/runtime/js/cm-ai/code-projects.mjs +4 -1
  18. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -1
  19. package/runtime/js/cm-ai/developer-adapter.mjs +7 -0
  20. package/runtime/js/cm-ai/drive-core.mjs +26 -4
  21. package/runtime/js/cm-ai/durable-runner-state.mjs +951 -43
  22. package/runtime/js/cm-ai/effect-abandon-log.mjs +5 -2
  23. package/runtime/js/cm-ai/effect-contract.mjs +6 -1
  24. package/runtime/js/cm-ai/execution-store.mjs +4 -2
  25. package/runtime/js/cm-ai/external-run-guard.mjs +18 -7
  26. package/runtime/js/cm-ai/host-check.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +11 -4
  28. package/runtime/js/cm-ai/host-documentation.mjs +53 -12
  29. package/runtime/js/cm-ai/host-project-execution.mjs +2 -2
  30. package/runtime/js/cm-ai/host-qa-executor.mjs +86 -17
  31. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +44 -9
  32. package/runtime/js/cm-ai/host-session.mjs +47 -7
  33. package/runtime/js/cm-ai/host-tool-bridge.mjs +55 -6
  34. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +4 -2
  35. package/runtime/js/cm-ai/operator-guidance.mjs +112 -3
  36. package/runtime/js/cm-ai/provider-review-observation.mjs +50 -0
  37. package/runtime/js/cm-ai/qa-resource-release.mjs +46 -0
  38. package/runtime/js/cm-ai/qa-round-budget.mjs +13 -0
  39. package/runtime/js/cm-ai/review-dispatch-limits.mjs +18 -0
  40. package/runtime/js/cm-ai/review-package.mjs +10 -1
  41. package/runtime/js/cm-ai/reviewed-deliveries.mjs +29 -6
  42. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +1 -1
  43. package/runtime/js/cm-ai/task-commit.mjs +39 -0
  44. package/runtime/js/cm-ai/task-runner.mjs +636 -65
  45. package/runtime/js/cm-ai/worker-claude-developer.mjs +9 -0
  46. package/runtime/js/cm-ai/worker-claude.mjs +10 -3
  47. package/runtime/js/cm-ai/worker-process-identity.mjs +43 -0
  48. package/runtime/js/cm-fix/cause-package.mjs +37 -8
  49. package/runtime/js/cm-fix/diagnosis.mjs +43 -0
  50. package/runtime/js/cm-fix/execution.mjs +356 -187
  51. package/runtime/js/cm-fix/host.mjs +2 -1
  52. package/runtime/js/cm-fix/investigation.mjs +25 -9
  53. package/runtime/js/cm-fix/pinned-baseline.mjs +24 -0
  54. package/runtime/js/cm-fix/progress.mjs +15 -3
  55. package/runtime/js/cm-fix/protected-edits.mjs +10 -3
  56. package/runtime/js/cm-fix/repair.mjs +11 -3
  57. package/runtime/js/cm-fix/test-author.mjs +10 -3
  58. package/runtime/js/cm-idea/session.mjs +67 -4
  59. package/runtime/js/cm-prd/review-correction.mjs +10 -4
  60. package/runtime/js/cm-prd/session.mjs +43 -0
  61. package/runtime/js/cm-refactor/records.mjs +98 -8
  62. package/runtime/js/cm-refactor/workflow.mjs +79 -9
  63. package/runtime/js/cm-test/host.mjs +10 -3
  64. package/runtime/js/cm-test/session.mjs +45 -6
  65. package/runtime/js/notify-run.mjs +26 -0
  66. package/runtime/js/notify-safe-read.mjs +49 -0
  67. package/runtime/js/notify-send.mjs +312 -0
  68. package/runtime/js/notify.mjs +492 -0
  69. package/runtime/js/policy-binding-compat.mjs +54 -0
  70. package/runtime/model-efficiency.md +17 -0
  71. package/scripts/ci-test-shards.mjs +67 -0
  72. package/scripts/ci-test-shards.test.mjs +64 -0
  73. package/scripts/ci-test-weights.json +222 -0
  74. package/scripts/cm-ai-abandon-effect-position.test.mjs +70 -2
  75. package/scripts/cm-ai-answer-gap-dispatch.test.mjs +86 -0
  76. package/scripts/cm-ai-answer-gap-driver.test.mjs +51 -0
  77. package/scripts/cm-ai-answer-gap-fixture.mjs +96 -0
  78. package/scripts/cm-ai-answer-gap-recheck.test.mjs +70 -0
  79. package/scripts/cm-ai-answer-gap-redo.test.mjs +103 -0
  80. package/scripts/cm-ai-batch-drive.mjs +55 -10
  81. package/scripts/cm-ai-batch-drive.test.mjs +65 -0
  82. package/scripts/cm-ai-batch-host.mjs +132 -13
  83. package/scripts/cm-ai-batch-host.test.mjs +255 -7
  84. package/scripts/cm-ai-batch-run-fixture.mjs +499 -0
  85. package/scripts/cm-ai-batch-run-member-stops.test.mjs +38 -0
  86. package/scripts/cm-ai-batch-run-parallel.test.mjs +7 -0
  87. package/scripts/cm-ai-batch-run-reschedule.test.mjs +17 -0
  88. package/scripts/cm-ai-batch-run.mjs +189 -22
  89. package/scripts/cm-ai-batch-run.test.mjs +22 -334
  90. package/scripts/cm-ai-develop-answer-invalid.test.mjs +104 -0
  91. package/scripts/cm-ai-develop-call-timeout.test.mjs +153 -0
  92. package/scripts/cm-ai-develop-driver-gaps.test.mjs +4 -3
  93. package/scripts/cm-ai-documentation-sync-gap.test.mjs +424 -0
  94. package/scripts/cm-ai-drive.mjs +68 -23
  95. package/scripts/cm-ai-drive.test.mjs +37 -2
  96. package/scripts/cm-ai-fix-run-delivery.test.mjs +138 -0
  97. package/scripts/cm-ai-host-cli-workflow.test.mjs +271 -0
  98. package/scripts/cm-ai-host-fixture.mjs +268 -0
  99. package/scripts/cm-ai-host-protected.test.mjs +251 -0
  100. package/scripts/cm-ai-host.mjs +28 -16
  101. package/scripts/cm-ai-host.test.mjs +17 -759
  102. package/scripts/cm-ai-light-modules.test.mjs +57 -0
  103. package/scripts/cm-ai-operator-guidance.test.mjs +30 -5
  104. package/scripts/cm-ai-project-qa-gate.test.mjs +71 -4
  105. package/scripts/cm-ai-protected-scope.test.mjs +7 -3
  106. package/scripts/cm-ai-qa-answer-gaps.test.mjs +99 -0
  107. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +78 -11
  108. package/scripts/cm-ai-qa-rerun-timeouts.test.mjs +127 -8
  109. package/scripts/cm-ai-review-dispatch-exit.test.mjs +475 -0
  110. package/scripts/cm-ai-review-failure.test.mjs +124 -13
  111. package/scripts/cm-ai-review-timeout.test.mjs +188 -10
  112. package/scripts/cm-ai-run.mjs +15 -6
  113. package/scripts/cm-ai-supersede.test.mjs +486 -41
  114. package/scripts/cm-check-drive-files.mjs +8 -0
  115. package/scripts/cm-check-drive.test.mjs +2 -5
  116. package/scripts/cm-check-runtime.sh +4 -2
  117. package/scripts/cm-claude-developer-worker.test.mjs +15 -0
  118. package/scripts/cm-claude-review-stream.test.mjs +21 -16
  119. package/scripts/cm-claude-review-synthetic.test.mjs +155 -0
  120. package/scripts/cm-claude-worker.test.mjs +18 -2
  121. package/scripts/cm-external-model-recovery.test.mjs +29 -3
  122. package/scripts/cm-fix-abandon.test.mjs +249 -10
  123. package/scripts/cm-fix-cause-package.test.mjs +33 -0
  124. package/scripts/cm-fix-drive-unprotected.test.mjs +37 -0
  125. package/scripts/cm-fix-drive.mjs +34 -8
  126. package/scripts/cm-fix-host.mjs +8 -7
  127. package/scripts/cm-fix-rediagnosis.test.mjs +71 -4
  128. package/scripts/cm-fix-review-budget.test.mjs +13 -0
  129. package/scripts/cm-fix-review-recovery.test.mjs +35 -0
  130. package/scripts/cm-host-answer-timeout.test.mjs +65 -0
  131. package/scripts/cm-host-call-kinds.test.mjs +28 -0
  132. package/scripts/cm-host-documentation.test.mjs +49 -0
  133. package/scripts/cm-host-qa-executor.test.mjs +143 -10
  134. package/scripts/cm-idea-answer-gaps.test.mjs +164 -0
  135. package/scripts/cm-idea-drive.mjs +49 -11
  136. package/scripts/cm-idea-drive.test.mjs +66 -0
  137. package/scripts/cm-idea-host.mjs +106 -16
  138. package/scripts/cm-init-answer-gaps.test.mjs +258 -0
  139. package/scripts/cm-init-drive.mjs +41 -7
  140. package/scripts/cm-init-host.mjs +61 -12
  141. package/scripts/cm-log-event.mjs +49 -12
  142. package/scripts/cm-notify-command.test.mjs +900 -0
  143. package/scripts/cm-notify-read-drift.test.mjs +205 -0
  144. package/scripts/cm-notify.mjs +469 -0
  145. package/scripts/cm-notify.test.mjs +685 -0
  146. package/scripts/cm-patrol.mjs +83 -0
  147. package/scripts/cm-patrol.test.mjs +161 -0
  148. package/scripts/cm-prd-answer-gaps.test.mjs +216 -0
  149. package/scripts/cm-prd-drive.mjs +18 -5
  150. package/scripts/cm-prd-drive.test.mjs +15 -0
  151. package/scripts/cm-prd-host.mjs +37 -4
  152. package/scripts/cm-prd-review-disposition.test.mjs +6 -1
  153. package/scripts/cm-prd-review-gate.mjs +56 -0
  154. package/scripts/cm-refactor-answer-gaps.test.mjs +206 -0
  155. package/scripts/cm-refactor-drive.mjs +52 -8
  156. package/scripts/cm-refactor-drive.test.mjs +44 -0
  157. package/scripts/cm-refactor-host.test.mjs +10 -6
  158. package/scripts/cm-release-smoke.sh +2 -0
  159. package/scripts/cm-test-answer-gaps.test.mjs +151 -0
  160. package/scripts/cm-test-drive.mjs +21 -5
  161. package/scripts/cm-token-report.mjs +497 -0
  162. package/scripts/cm-token-report.test.mjs +346 -0
  163. package/scripts/fixtures/claude-review-process.mjs +1 -1
  164. package/scripts/policy-binding-compat.test.mjs +99 -0
  165. package/scripts/scan-public-safety.py +4 -0
  166. package/scripts/validate-public-repo.py +4 -0
  167. package/skills/cm-ai/SKILL.md +7 -3
  168. package/skills/cm-ai/references/N6-qa-eval.md +2 -2
  169. package/skills/cm-ai/references/js-host-modes.md +90 -0
  170. package/skills/cm-ai/references/js-host-qa-recovery.md +136 -0
  171. package/skills/cm-ai/references/js-host-recovery.md +311 -0
  172. package/skills/cm-ai/references/js-host.md +76 -331
  173. package/skills/cm-check/SKILL.md +3 -3
  174. package/skills/cm-fix/SKILL.md +2 -0
  175. package/skills/cm-fix/references/js-host.md +56 -10
  176. package/skills/cm-idea/references/js-host.md +27 -2
  177. package/skills/cm-init/references/js-host.md +16 -3
  178. package/skills/cm-notify/SKILL.md +34 -0
  179. package/skills/cm-prd/SKILL.md +2 -0
  180. package/skills/cm-prd/references/js-change-recovery.md +35 -1
  181. package/skills/cm-refactor/references/js-host.md +17 -0
  182. package/skills/cm-test/references/js-host.md +14 -1
@@ -0,0 +1,685 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn,spawnSync} from 'node:child_process';
7
+ import {notify,readNotifyConfig,parseNotifyConfig,buildNotifyMessage,normalizeNotifyText,driveNotice,NOTIFY_LIMITS,NOTIFY_WORKFLOWS,DEFAULT_NOTIFY_TEXT} from '../runtime/js/notify.mjs';
8
+
9
+ const NOW=Date.parse('2026-10-08T08:00:00.000Z');
10
+ const DRIVE_CORE=new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href;
11
+ const BRIDGE=new URL('../runtime/js/cm-ai/host-tool-bridge.mjs',import.meta.url).href;
12
+ const HOST_SESSION=new URL('../runtime/js/cm-ai/host-session.mjs',import.meta.url).href;
13
+
14
+ // A temp CM_WORKFLOW_HOME with notify.json pointing at a fake command that
15
+ // appends its environment message and stdin payload to sent.jsonl.
16
+ function home(t,{exit=0,sleepMs=0,config={}}={}){
17
+ const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-')));
18
+ t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
19
+ const sent=path.join(dir,'sent.jsonl'),script=path.join(dir,'fake-notify.mjs');
20
+ fs.writeFileSync(script,`import fs from 'node:fs';let input='';process.stdin.on('data',c=>input+=c);
21
+ process.stdin.on('end',()=>{setTimeout(()=>{fs.appendFileSync(${JSON.stringify(sent)},JSON.stringify({title:process.env.CM_NOTIFY_TITLE,
22
+ body:process.env.CM_NOTIFY_BODY,stdin:JSON.parse(input),at:Date.now()})+'\\n');process.exit(${exit});},${sleepMs});});`);
23
+ fs.writeFileSync(path.join(dir,'notify.json'),JSON.stringify({version:1,command:[process.execPath,script],...config}));
24
+ const env={...process.env,CM_WORKFLOW_HOME:dir};
25
+ const rows=()=>fs.existsSync(sent)?fs.readFileSync(sent,'utf8').trim().split('\n').map(line=>JSON.parse(line)):[];
26
+ const log=()=>fs.existsSync(path.join(dir,'notify.log'))?fs.readFileSync(path.join(dir,'notify.log'),'utf8'):'';
27
+ const until=async(check,ms=8000)=>{const end=Date.now()+ms;while(!check()&&Date.now()<end)await new Promise(r=>setTimeout(r,25));return check();};
28
+ return {dir,env,rows,log,until};
29
+ }
30
+ const fields=(key,over={})=>({key,event:'stuck',project:'/srv/work/demo-app',workflow:'cm-fix',runId:'run-1',
31
+ task:'T-001',stage:'blocked',code:'checks_not_passed',nextAction:'核对 reason 后恢复原运行',...over});
32
+
33
+ test('off without notify.json, and off under node --test unless CM_WORKFLOW_HOME is explicit',async t=>{
34
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'cm-notify-empty-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
35
+ assert.equal(readNotifyConfig({CM_WORKFLOW_HOME:dir}),null);
36
+ assert.deepEqual(notify(fields('a'),{env:{CM_WORKFLOW_HOME:dir},now:NOW}),{sent:false,reason:'off'});
37
+ assert.deepEqual(fs.readdirSync(dir),[]);
38
+ assert.equal(readNotifyConfig({NODE_TEST_CONTEXT:'child-v8'}),null);
39
+ });
40
+
41
+ test('invalid config turns the feature off: relative command, bad version, bad waitMinutes',t=>{
42
+ const h=home(t);const file=path.join(h.dir,'notify.json');
43
+ for(const value of [{version:1,command:['notify.sh']},{version:2,command:['/bin/true']},{version:1,command:[]},
44
+ {version:1,command:['/bin/true'],waitMinutes:0},'not json']){
45
+ fs.writeFileSync(file,typeof value==='string'?value:JSON.stringify(value));
46
+ assert.equal(readNotifyConfig(h.env),null,JSON.stringify(value));
47
+ }
48
+ assert.match(h.log(),/config - key=- off invalid_config command_not_absolute/);
49
+ fs.writeFileSync(file,JSON.stringify({version:1,command:['/bin/true'],waitMinutes:0.5}));
50
+ assert.deepEqual(readNotifyConfig(h.env),{command:['/bin/true'],waitMs:30000,checkWaitMs:2700000,idleMs:2700000});
51
+ });
52
+
53
+ // The runtime reads notify.json through the same safe boundary as /cm:notify:
54
+ // no symlink, regular file only, 64 KiB cap, non-blocking open. Every refusal
55
+ // turns notices off with one notify.log line; nothing throws or waits.
56
+ // Each probe runs in its own process: the log line is once per process, and a
57
+ // build that blocks on a FIFO fails by timeout instead of hanging the suite.
58
+ const posix=process.platform!=='win32';
59
+ const CONFIG={version:1,command:['/bin/true']},PARSED={command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000};
60
+ const NOTIFY_URL=new URL('../runtime/js/notify.mjs',import.meta.url).href;
61
+ function probe(h){
62
+ const child=spawnSync(process.execPath,['--input-type=module','-e',
63
+ `import {readNotifyConfig,notify} from ${JSON.stringify(NOTIFY_URL)};
64
+ console.log(JSON.stringify({config:readNotifyConfig(process.env),sent:notify({key:'k'},{env:process.env})}));`],
65
+ {env:{...process.env,CM_WORKFLOW_HOME:h.dir},encoding:'utf8',timeout:5000,killSignal:'SIGKILL'});
66
+ assert.equal(child.error,undefined,'reading notify.json made the runtime wait');
67
+ assert.equal(child.status,0,child.stderr);
68
+ return JSON.parse(child.stdout);
69
+ }
70
+ const OFF={config:null,sent:{sent:false,reason:'off'}};
71
+ const unreadable=(h,reason)=>assert.match(h.log(),new RegExp(`config - key=- off invalid_config unreadable_${reason}\\n$`));
72
+
73
+ test('runtime read: notify.json that is a symlink is never read, even to a valid config; a normal file still is',{skip:!posix},t=>{
74
+ const h=home(t);const file=path.join(h.dir,'notify.json'),real=path.join(h.dir,'real-config.json');
75
+ fs.writeFileSync(real,JSON.stringify(CONFIG));fs.rmSync(file);fs.symlinkSync(real,file);
76
+ assert.deepEqual(probe(h),OFF);unreadable(h,'not_regular_file');assert.equal(h.rows().length,0);
77
+ // A dangling link is a link too: refused and logged, not treated as "missing".
78
+ const dangling=home(t);fs.rmSync(path.join(dangling.dir,'notify.json'));fs.symlinkSync(path.join(dangling.dir,'nowhere.json'),path.join(dangling.dir,'notify.json'));
79
+ assert.deepEqual(probe(dangling),OFF);unreadable(dangling,'not_regular_file');
80
+ // The same content as a regular file reads exactly as before.
81
+ fs.rmSync(file);fs.writeFileSync(file,JSON.stringify(CONFIG));
82
+ assert.deepEqual(probe(h).config,PARSED);
83
+ });
84
+
85
+ test('runtime read: a FIFO at notify.json is refused at once, never waited on',{skip:!posix},t=>{
86
+ const h=home(t);const file=path.join(h.dir,'notify.json');
87
+ fs.rmSync(file);assert.equal(spawnSync('mkfifo',['-m','600',file]).status,0);
88
+ assert.deepEqual(probe(h),OFF);unreadable(h,'not_regular_file');
89
+ });
90
+
91
+ test('runtime read: notify.json over 64 KiB is refused; exactly 64 KiB is still read',{skip:!posix},t=>{
92
+ const json=JSON.stringify(CONFIG),pad=n=>json+' '.repeat(n-Buffer.byteLength(json));
93
+ const over=home(t);fs.writeFileSync(path.join(over.dir,'notify.json'),pad(64*1024+1));
94
+ assert.deepEqual(probe(over),OFF);unreadable(over,'too_large');
95
+ const exact=home(t);fs.writeFileSync(path.join(exact.dir,'notify.json'),pad(64*1024));
96
+ assert.deepEqual(probe(exact).config,PARSED);assert.equal(exact.log(),'');
97
+ });
98
+
99
+ test('runtime read: a missing file stays silent, a directory is a logged off, a BOM file behaves as before (not_json)',{skip:!posix},t=>{
100
+ const missing=home(t);fs.rmSync(path.join(missing.dir,'notify.json'));
101
+ assert.deepEqual(probe(missing),OFF);assert.equal(missing.log(),'');
102
+ const dir=home(t);fs.rmSync(path.join(dir.dir,'notify.json'));fs.mkdirSync(path.join(dir.dir,'notify.json'));
103
+ assert.deepEqual(probe(dir),OFF);unreadable(dir,'not_regular_file');
104
+ // Same as the plain read it replaces: the BOM is not stripped, JSON.parse rejects it.
105
+ const bom=home(t);fs.writeFileSync(path.join(bom.dir,'notify.json'),'\uFEFF'+JSON.stringify(CONFIG));
106
+ assert.deepEqual(probe(bom),OFF);assert.match(bom.log(),/config - key=- off invalid_config not_json\n$/);
107
+ // Invalid UTF-8 never throws; it is just an invalid file.
108
+ const bad=home(t);fs.writeFileSync(path.join(bad.dir,'notify.json'),Buffer.from([0x7b,0xff,0xfe,0x7d]));
109
+ assert.deepEqual(probe(bad),OFF);assert.match(bad.log(),/off invalid_config not_json\n$/);
110
+ });
111
+
112
+ test('message is bounded and built only from the structured fields',()=>{
113
+ const long='x'.repeat(2000);
114
+ const message=buildNotifyMessage({...fields('k'),workflow:long,project:'/very/secret/path/'+long,runId:long,task:long,
115
+ stage:long,code:long,nextAction:`读 /srv/private/push.env 和 ~/secret/file 后\n${long}`,
116
+ diff:'DIFF-CONTENT',log:'LOG-CONTENT',env:{TOKEN:'SECRET'}},{now:NOW});
117
+ assert(Array.from(message.title).length<=NOTIFY_LIMITS.titleChars);
118
+ assert(Array.from(message.body).length<=NOTIFY_LIMITS.bodyChars);
119
+ for(const forbidden of ['DIFF-CONTENT','LOG-CONTENT','SECRET','push.env','/srv/','/very/secret','~/secret','\0'])
120
+ assert(!message.body.includes(forbidden)&&!message.title.includes(forbidden),forbidden);
121
+ assert.match(message.body,/<路径>/);
122
+ const short=buildNotifyMessage(fields('k'),{now:NOW,timeZone:'Asia/Shanghai'});
123
+ assert.equal(short.title,'CM cm-fix 需要人处理 · demo-app');
124
+ assert.equal(short.body,'下一步:核对 reason 后恢复原运行\n项目:demo-app\n流程:cm-fix\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n时间:16:00');
125
+ assert.doesNotMatch(short.body,/运行:|run-1|CM 不会自动继续/);
126
+ });
127
+
128
+ test('done shows only project, task and local time; empty fields are left out',()=>{
129
+ const done=buildNotifyMessage(fields('k',{event:'done',stage:'run_done',code:'run_done',nextAction:'建议在新会话里开始下一个任务'}),
130
+ {now:NOW,timeZone:'Asia/Shanghai'});
131
+ assert.equal(done.title,'CM cm-fix 流程已结束 · demo-app');
132
+ assert.equal(done.body,'项目:demo-app\n任务:T-001\n时间:16:00');
133
+ assert.equal(buildNotifyMessage(fields('k',{event:'done',task:null}),{now:NOW,timeZone:'UTC'}).body,'项目:demo-app\n时间:08:00');
134
+ assert.equal(buildNotifyMessage({workflow:'cm-ai',event:'waiting'},{now:NOW,timeZone:'America/New_York'}).body,'流程:cm-ai\n时间:04:00');
135
+ assert.equal(buildNotifyMessage({workflow:'cm-ai'},{now:Date.parse('2026-10-08T16:05:00.000Z'),timeZone:'Asia/Shanghai'}).body,'流程:cm-ai\n时间:00:05');
136
+ });
137
+
138
+ test('without an injected time zone the clock follows the process TZ',()=>{
139
+ const script=`import {buildNotifyMessage} from ${JSON.stringify(new URL('../runtime/js/notify.mjs',import.meta.url).href)};
140
+ process.stdout.write(buildNotifyMessage({workflow:'cm-ai',event:'done',project:'/p/demo'},{now:${NOW}}).body);`;
141
+ for(const [tz,clock] of [['Asia/Shanghai','16:00'],['UTC','08:00'],['America/Los_Angeles','01:00']]){
142
+ const run=spawnSync(process.execPath,['--input-type=module','-e',script],{encoding:'utf8',env:{...process.env,TZ:tz}});
143
+ assert.equal(run.status,0,run.stderr);assert.equal(run.stdout,`项目:demo\n时间:${clock}`);
144
+ }
145
+ });
146
+
147
+ // Optional notify.json `text`. Expected strings below are written out by hand
148
+ // from the default layout, not computed by the code under test.
149
+ const EVENTS=[['done','流程已结束'],['waiting','等待会话应答'],['idle','疑似空转'],['idle_waiting','在等你'],
150
+ ['dead','宿主已退出未收尾'],['stuck','需要人处理'],[undefined,'需要人处理']];
151
+ test('custom text: without `text` (or with an empty one) every event is byte-identical to the default',()=>{
152
+ const at={now:NOW,timeZone:'Asia/Shanghai'};
153
+ for(const [event,headline] of EVENTS){
154
+ const base=buildNotifyMessage(fields('k',{event}),at);
155
+ assert.equal(base.title,`CM cm-fix ${headline} · demo-app`,String(event));
156
+ assert.equal(base.body,event==='done'?'项目:demo-app\n任务:T-001\n时间:16:00'
157
+ :'下一步:核对 reason 后恢复原运行\n项目:demo-app\n流程:cm-fix\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n时间:16:00');
158
+ for(const text of [{},DEFAULT_NOTIFY_TEXT,null,normalizeNotifyText({}).text])
159
+ assert.deepEqual(buildNotifyMessage(fields('k',{event}),{...at,text}),base,`${event} ${JSON.stringify(text)}`);
160
+ }
161
+ const plainConfig=parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true']}));
162
+ assert.deepEqual(plainConfig,{config:{command:['/bin/true'],waitMs:600000,checkWaitMs:2700000,idleMs:2700000}});
163
+ assert.equal(Object.hasOwn(plainConfig.config,'text'),false);
164
+ });
165
+
166
+ test('custom text: prefix, headlines, field order (runId included) and labels',()=>{
167
+ const at={now:NOW,timeZone:'Asia/Shanghai'};
168
+ const text={titlePrefix:'【工作流】',headlines:{done:'完工',waiting:'等你回话',idle:'没动静',idle_waiting:'该你了',dead:'宿主没了',default:'卡住了'},
169
+ fields:{default:['code','runId','time'],done:['time','task']},labels:{code:'代码',runId:'编号',time:'时刻',task:'工单'}};
170
+ const parsed=parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],text}));
171
+ assert.equal(parsed.textReason,undefined);
172
+ const custom=parsed.config.text;
173
+ const want={done:'完工',waiting:'等你回话',idle:'没动静',idle_waiting:'该你了',dead:'宿主没了',stuck:'卡住了'};
174
+ for(const [event,headline] of Object.entries(want)){
175
+ const message=buildNotifyMessage(fields('k',{event}),{...at,text:custom});
176
+ assert.equal(message.title,`【工作流】 cm-fix ${headline} · demo-app`);
177
+ assert.equal(message.body,event==='done'?'时刻:16:00\n工单:T-001':'代码:checks_not_passed\n编号:run-1\n时刻:16:00');
178
+ }
179
+ // Partial text: only what is given changes; an empty prefix drops it from the title.
180
+ const partial=buildNotifyMessage(fields('k'),{...at,text:{titlePrefix:'',labels:{nextAction:'先做'}}});
181
+ assert.equal(partial.title,'cm-fix 需要人处理 · demo-app');
182
+ assert.equal(partial.body,'先做:核对 reason 后恢复原运行\n项目:demo-app\n流程:cm-fix\n任务:T-001\n阶段:blocked\n原因:checks_not_passed\n时间:16:00');
183
+ assert.equal(buildNotifyMessage(fields('k',{event:'waiting'}),{...at,text:{headlines:{waiting:'等'}}}).title,'CM cm-fix 等 · demo-app');
184
+ assert.equal(buildNotifyMessage(fields('k',{event:'idle'}),{...at,text:{headlines:{waiting:'等'}}}).title,'CM cm-fix 疑似空转 · demo-app');
185
+ // Empty field values are still left out under a custom order.
186
+ assert.equal(buildNotifyMessage({workflow:'cm-ai'},{...at,text:{fields:{default:['runId','workflow','time']}}}).body,'流程:cm-ai\n时间:16:00');
187
+ });
188
+
189
+ test('custom text strings are cleaned like field values: paths redacted, control characters removed, each capped',()=>{
190
+ const at={now:NOW,timeZone:'UTC'};
191
+ const text=normalizeNotifyText({titlePrefix:'CM\u0007/Users/example/secret',
192
+ headlines:{default:'卡住\n见/srv/private/push.env\u001b[31m'},labels:{nextAction:'C:\\Users\\example\\a.txt\u0000下一步',project:'~/proj',code:'\\\\srv\\share\\x'}}).text;
193
+ const message=buildNotifyMessage(fields('k'),{...at,text});
194
+ for(const forbidden of ['/Users','example\\','secret','/srv/','push.env','~/proj','\\\\srv','\u0007','\u001b','\u0000','\n见'])
195
+ assert(!message.title.includes(forbidden)&&!message.body.split('\n').map(line=>line.split(':')[0]).join('|').includes(forbidden),JSON.stringify(forbidden));
196
+ assert.equal(message.title,'CM <路径> cm-fix 卡住 见<路径> [31m · demo-app');
197
+ assert.equal(message.body.split('\n')[0],'<路径> 下一步:核对 reason 后恢复原运行');
198
+ assert.match(message.body,/\n<路径>:demo-app\n/);
199
+ assert.match(message.body,/\n<路径>:checks_not_passed\n/);
200
+ // Caps: prefix 16, headline 24, label 12 characters (… included); title 60, body 500.
201
+ const long=normalizeNotifyText({titlePrefix:'前'.repeat(40),headlines:{default:'标'.repeat(40)},labels:{nextAction:'签'.repeat(40)}}).text;
202
+ assert.equal(long.titlePrefix,'前'.repeat(15)+'…');assert.equal(long.headlines.default,'标'.repeat(23)+'…');
203
+ assert.equal(long.labels.nextAction,'签'.repeat(11)+'…');
204
+ const huge='x'.repeat(2000);
205
+ const big=buildNotifyMessage({...fields('k'),workflow:huge,project:huge,runId:huge,task:huge,stage:huge,code:huge,nextAction:huge},
206
+ {...at,text:{...long,fields:{default:['nextAction','runId','project','workflow','task','stage','code','time']}}});
207
+ assert.equal(Array.from(big.title).length,NOTIFY_LIMITS.titleChars);
208
+ assert(Array.from(big.body).length<=NOTIFY_LIMITS.bodyChars);
209
+ assert.match(big.body,/^签{11}…:x{199}…\n/);
210
+ assert.match(big.body,/\n运行:x{63}…\n/);
211
+ });
212
+
213
+ test('custom text loses bidi and zero-width characters; a string left with nothing visible is invalid',()=>{
214
+ const at={now:NOW,timeZone:'UTC'};
215
+ const hidden=['‪','‫','‬','‭','‮','⁦','⁧','⁨','⁩','‎','‏','؜',
216
+ '​','‌','‍','⁠','','­','\u{e0041}'];
217
+ const text=normalizeNotifyText({titlePrefix:`C${hidden.join('')}M`,headlines:{default:`‮卡住⁦了⁩`},
218
+ labels:{code:'‮原因',task:'​工‍单'}}).text;
219
+ const message=buildNotifyMessage(fields('k'),{...at,text});
220
+ for(const char of hidden)assert(!message.title.includes(char)&&!message.body.includes(char),`U+${char.codePointAt(0).toString(16)}`);
221
+ assert.equal(message.title,'CM cm-fix 卡住了 · demo-app');
222
+ assert.match(message.body,/\n工单:T-001\n/);assert.match(message.body,/\n原因:checks_not_passed\n/);
223
+ // Nothing visible left: the whole text is invalid and the default text is used.
224
+ for(const [value,reason] of [[{headlines:{default:'​⁦⁩'}},'headlines'],[{labels:{code:'‮ ‏'}},'labels'],
225
+ [{titlePrefix:'​'},'title_prefix'],[{titlePrefix:' '},'title_prefix'],[{headlines:{done:'̀'}},'headlines']]){
226
+ assert.equal(normalizeNotifyText(value).reason,reason,JSON.stringify(value));
227
+ assert.equal(parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],text:value})).textReason,reason);
228
+ assert.deepEqual(buildNotifyMessage(fields('k'),{...at,text:value}),buildNotifyMessage(fields('k'),at));
229
+ }
230
+ // Field values are not part of the text layer: the default path is unchanged.
231
+ assert.equal(buildNotifyMessage(fields('k',{task:'T​-1'}),at).body.split('\n')[3],'任务:T​-1');
232
+ });
233
+
234
+ test('custom text redacts absolute paths even when letters touch them; field values keep the shared rule',()=>{
235
+ const at={now:NOW,timeZone:'UTC'};
236
+ for(const [raw,want] of [['see/Users/example/key','see<路径>'],['seeC:\\Users\\example\\key','see<路径>'],['seeC:/Users/example/key','see<路径>'],
237
+ ['see\\\\srv\\share\\key','see<路径>'],['see~/proj/key','see<路径>'],['卡在/srv/a,再看','卡在<路径>,再看'],
238
+ ['x1/etc/passwd y','x1<路径> y'],['CI/CD','CI<路径>'],['停\u0007/tmp/a','停 <路径>'],['停\u200b/tmp/a','停<路径>'],
239
+ ['相对 a\\b 保留','相对 a\\b 保留']]){
240
+ const text=normalizeNotifyText({headlines:{default:raw},labels:{code:raw}}).text;
241
+ assert.equal(text.headlines.default,want,raw);assert.equal(text.labels.code,want.slice(0,12),raw);
242
+ const message=buildNotifyMessage(fields('k'),{...at,text});
243
+ assert.equal(message.title,`CM cm-fix ${want} · demo-app`,raw);
244
+ for(const leak of ['/Users','Users\\','\\\\srv','/srv','~/proj','/etc','/tmp'])assert(!message.title.includes(leak)&&!message.body.includes(leak),`${raw} ${leak}`);
245
+ }
246
+ // The shared rule for field values (and so the default text) is unchanged.
247
+ assert.equal(buildNotifyMessage(fields('k',{task:'see/Users/example/key'}),at).body.split('\n')[3],'任务:see/Users/example/key');
248
+ assert.equal(buildNotifyMessage(fields('k',{task:'见 /Users/example/key'}),at).body.split('\n')[3],'任务:见 <路径>');
249
+ });
250
+
251
+ test('invalid text falls back to the default text with one text_config log line; notices stay on',async t=>{
252
+ const bad=[[null,'text'],['标题','text'],[[],'text'],[{subject:'x'},'text_key'],[{titlePrefix:7},'title_prefix'],
253
+ [{titlePrefix:'\u0007'},'title_prefix'],[{headlines:{stuck:'x'}},'headlines'],[{headlines:{done:''}},'headlines'],
254
+ [{headlines:{done:'\u0001\u0002'}},'headlines'],[{headlines:'x'},'headlines'],[{labels:{secret:'x'}},'labels'],
255
+ [{labels:{task:3}},'labels'],[{fields:{default:['nextAction','diff']}},'fields'],[{fields:{default:[]}},'fields'],
256
+ [{fields:{default:['task','task']}},'fields'],[{fields:{stuck:['task']}},'fields'],[{fields:{done:'task'}},'fields'],
257
+ [{fields:{done:['toString']}},'fields']];
258
+ for(const [text,reason] of bad){
259
+ const parsed=parseNotifyConfig(JSON.stringify({version:1,command:['/bin/true'],text}));
260
+ assert.equal(parsed.reason,undefined,JSON.stringify(text));assert.equal(parsed.textReason,reason,JSON.stringify(text));
261
+ assert.equal(parsed.config.text,undefined);assert.deepEqual(parsed.config.command,['/bin/true']);
262
+ assert.deepEqual(buildNotifyMessage(fields('k'),{now:NOW,timeZone:'UTC',text}),buildNotifyMessage(fields('k'),{now:NOW,timeZone:'UTC'}));
263
+ }
264
+ // End to end: the typo does not silence the notice, it goes out in the default text, and notify.log says why once.
265
+ const h=home(t,{config:{text:{fields:{default:['nextAction','diff']}}}});
266
+ assert.equal(readNotifyConfig(h.env).text,undefined);
267
+ assert.deepEqual(notify(fields('typo'),{env:h.env,now:NOW}),{sent:true,reason:'launched'});
268
+ assert(await h.until(()=>h.rows().length===1));
269
+ assert.equal(h.rows()[0].title,'CM cm-fix 需要人处理 · demo-app');
270
+ assert.match(h.rows()[0].body,/^下一步:核对 reason 后恢复原运行\n项目:demo-app\n/);
271
+ readNotifyConfig(h.env);
272
+ const lines=h.log().split('\n').filter(line=>line.includes('text_config'));
273
+ assert.equal(lines.length,1,h.log());assert.match(lines[0],/ config - key=- default_text text_config fields$/);
274
+ assert.doesNotMatch(h.log(),/off invalid_config/);
275
+ });
276
+
277
+ test('custom text reaches the command in CM_NOTIFY_TITLE/BODY and the stdin JSON',async t=>{
278
+ const h=home(t,{config:{text:{titlePrefix:'提醒',headlines:{default:'卡住了'},fields:{default:['task','code']},labels:{task:'工单'}}}});
279
+ assert.equal(notify(fields('custom'),{env:h.env,now:NOW}).sent,true);
280
+ assert(await h.until(()=>h.rows().length===1));
281
+ const [row]=h.rows();
282
+ assert.equal(row.title,'提醒 cm-fix 卡住了 · demo-app');assert.equal(row.body,'工单:T-001\n原因:checks_not_passed');
283
+ assert.equal(row.stdin.title,row.title);assert.equal(row.stdin.body,row.body);assert.equal(row.stdin.runId,'run-1');
284
+ });
285
+
286
+ test('sends through env and stdin once per key; the same key within 6 hours is skipped',async t=>{
287
+ const h=home(t);
288
+ assert.deepEqual(notify(fields('same'),{env:h.env,now:NOW}),{sent:true,reason:'launched'});
289
+ assert.deepEqual(notify(fields('same'),{env:h.env,now:NOW+5*3600*1000}),{sent:false,reason:'duplicate'});
290
+ assert(await h.until(()=>h.rows().length===1));
291
+ const [row]=h.rows();
292
+ assert.equal(row.title,'CM cm-fix 需要人处理 · demo-app');assert.equal(row.stdin.title,row.title);assert.equal(row.stdin.body,row.body);
293
+ assert.equal(row.stdin.project,'demo-app');assert.equal(row.stdin.code,'checks_not_passed');assert.equal(row.stdin.key,undefined);
294
+ assert.equal(notify(fields('same'),{env:h.env,now:NOW+6*3600*1000+1}).sent,true);
295
+ assert(await h.until(()=>h.rows().length===2));
296
+ assert.equal(h.rows()[0].stdin.CM_NOTIFY_PAYLOAD,undefined);
297
+ const state=JSON.parse(fs.readFileSync(path.join(h.dir,'notify-state.json'),'utf8'));
298
+ assert.equal(JSON.stringify(state).includes('same'),false);
299
+ assert(!fs.existsSync(path.join(h.dir,'notify-state.lock')));
300
+ });
301
+
302
+ test('at most 4 per rolling minute and 150 per day across keys',async t=>{
303
+ const h=home(t);
304
+ for(let i=0;i<4;i++)assert.equal(notify(fields(`m${i}`),{env:h.env,now:NOW+i}).sent,true);
305
+ assert.deepEqual(notify(fields('m4'),{env:h.env,now:NOW+10}),{sent:false,reason:'rate_minute'});
306
+ assert.equal(notify(fields('m4'),{env:h.env,now:NOW+60010}).sent,true);
307
+ assert.match(h.log(),/skipped rate_minute/);
308
+ const sends=Array.from({length:150},(_,i)=>NOW+120000+i*60000);
309
+ fs.writeFileSync(path.join(h.dir,'notify-state.json'),JSON.stringify({version:1,keys:{},sends}));
310
+ assert.deepEqual(notify(fields('day'),{env:h.env,now:NOW+200*60000}),{sent:false,reason:'rate_day'});
311
+ assert.equal(notify(fields('day'),{env:h.env,now:NOW+120000+24*3600*1000}).sent,true);
312
+ assert(await h.until(()=>h.rows().length===6));
313
+ });
314
+
315
+ test('command failure, timeout and broken state never throw; they log one line without content',async t=>{
316
+ const failing=home(t,{exit:3});
317
+ assert.deepEqual(notify(fields('f'),{env:failing.env,now:NOW}),{sent:true,reason:'launched'});
318
+ assert(await failing.until(()=>failing.log()!==''));
319
+ assert.match(failing.log(),/^\S+ stuck cm-fix key=[0-9a-f]{16} failed exit_3\n$/);
320
+ const slow=home(t,{sleepMs:5000});
321
+ assert.equal(notify(fields('s'),{env:slow.env,now:NOW,timeoutMs:200}).sent,true);
322
+ assert(await slow.until(()=>/failed timeout/.test(slow.log())));
323
+ const missing=home(t);fs.writeFileSync(path.join(missing.dir,'notify.json'),JSON.stringify({version:1,command:['/nonexistent/notify-cmd']}));
324
+ assert.equal(notify(fields('n'),{env:missing.env,now:NOW}).sent,true);assert(await missing.until(()=>/failed spawn_enoent/.test(missing.log())));
325
+ const broken=home(t);fs.writeFileSync(path.join(broken.dir,'notify-state.json'),'{');
326
+ assert.deepEqual(notify(fields('b'),{env:broken.env,now:NOW}),{sent:false,reason:'state_invalid'});
327
+ await new Promise(r=>setTimeout(r,300));
328
+ for(const h of [slow,missing,broken])assert.equal(h.rows().length,0);
329
+ for(const h of [failing,slow,missing,broken])assert(!/demo-app|T-001|核对|run-1/.test(h.log()));
330
+ });
331
+
332
+ // Lock contention never waits; only a provably stale lock is reclaimed, and
333
+ // a live lock is never removed.
334
+ test('lock: a live lock skips at once and is kept; a stale lock is reclaimed safely',async t=>{
335
+ const live=home(t),lockFile=path.join(live.dir,'notify-state.lock');
336
+ const liveBody=JSON.stringify({pid:process.pid,at:Date.now(),token:'other'});fs.writeFileSync(lockFile,liveBody);
337
+ const started=performance.now();
338
+ assert.deepEqual(notify(fields('l'),{env:live.env,now:NOW}),{sent:false,reason:'state_busy'});
339
+ assert(performance.now()-started<50,'no synchronous waiting on contention');
340
+ assert.equal(fs.readFileSync(lockFile,'utf8'),liveBody);assert.match(live.log(),/skipped state_busy/);
341
+ const partial=home(t);fs.writeFileSync(path.join(partial.dir,'notify-state.lock'),'');
342
+ assert.equal(notify(fields('p'),{env:partial.env,now:NOW}).reason,'state_busy');
343
+ const dead=spawnSync(process.execPath,['-e','console.log(process.pid)'],{encoding:'utf8'}).stdout.trim();
344
+ for(const body of [{pid:Number(dead),at:Date.now(),token:'gone'},{pid:process.pid,at:Date.now()-60000,token:'old'}]){
345
+ const old=home(t),file=path.join(old.dir,'notify-state.lock');fs.writeFileSync(file,JSON.stringify(body));
346
+ assert.equal(notify(fields('o'),{env:old.env,now:NOW}).sent,true,JSON.stringify(body));
347
+ assert(!fs.existsSync(file));assert.deepEqual(fs.readdirSync(old.dir).filter(name=>name.includes('.lock.')),[]);
348
+ assert(await old.until(()=>old.rows().length===1));
349
+ }
350
+ });
351
+
352
+ test('respects CM_WORKFLOW_HOME: config, state and log stay in that directory',async t=>{
353
+ const a=home(t),b=home(t);fs.rmSync(path.join(b.dir,'notify.json'));
354
+ assert.equal(notify(fields('h'),{env:b.env,now:NOW}).reason,'off');
355
+ assert.equal(notify(fields('h'),{env:a.env,now:NOW}).sent,true);
356
+ assert(await a.until(()=>a.rows().length===1));
357
+ assert(fs.existsSync(path.join(a.dir,'notify-state.json')));assert(!fs.existsSync(path.join(b.dir,'notify-state.json')));
358
+ });
359
+
360
+ // Table-driven: each workflow's real result contract (host named per row)
361
+ // maps to stuck (a person must act), done (run ended) or null (progress).
362
+ const id={runId:'run-1',taskId:'T-001',attempt:1};
363
+ const ai=(over)=>({version:1,workflow:'cm-ai',operation:'advance',identity:id,packageDigest:'d',...over});
364
+ const CASES=[
365
+ // cm-ai: cm-ai-conversation-entry.mjs / operator-guidance.mjs / task-runner.mjs / host-qa-fix-owner.mjs
366
+ ['cm-ai','advance',ai({outcome:'finalized',state:'run_done',code:'run_done',pendingAction:'none'}),'done'],
367
+ ['cm-ai','advance',ai({outcome:'finalized',state:'run_done',code:'run_done_degraded',pendingAction:'none'}),'done'],
368
+ ['cm-ai','advance',ai({outcome:'refreshed',state:'fixture_completed',code:'context_refreshed',pendingAction:'start_next_task'}),null],
369
+ ['cm-ai','start',ai({outcome:'advanced',state:'awaiting_review',code:null,pendingAction:'decision'}),null],
370
+ ['cm-ai','advance',ai({outcome:'advanced',state:'changes_requested',code:null,pendingAction:'resume'}),null],
371
+ ['cm-ai','complete',ai({outcome:'advanced',state:'fixture_completed',code:null,pendingAction:'qa'}),null],
372
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'fixture_completed',code:'documentation_sync_required',pendingAction:'documentation_sync'}),null],
373
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'changes_requested',code:'revision_answer_required',pendingAction:'resume'}),null],
374
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'awaiting_review',code:'decision_required',pendingAction:'decision'}),'stuck'],
375
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'fixture_completed',code:'qa_decision_required',pendingAction:'qa'}),'stuck'],
376
+ ['cm-ai','advance',ai({outcome:'awaiting',state:'awaiting_spec_approval',code:'specs_not_approved',pendingAction:'none'}),'stuck'],
377
+ ['cm-ai','advance',ai({outcome:'recorded',state:'fixture_completed',code:'qa_triggered',pendingAction:'qa_execution'}),'stuck'],
378
+ ['cm-ai','advance',ai({outcome:'verified',state:'fixture_completed',code:'qa_failed',pendingAction:'fix_authorization'}),'stuck'],
379
+ ['cm-ai','advance',ai({outcome:'advanced',state:'blocked',code:'review_limit',pendingAction:'none'}),'stuck'],
380
+ ['cm-ai','advance',ai({outcome:'advanced',state:'pending_review',code:'review_transport_timeout',pendingAction:'resume'}),'stuck'],
381
+ ['cm-ai','advance',ai({outcome:'advanced',state:'unknown',code:'execution_error',pendingAction:'reconcile'}),'stuck'],
382
+ ['cm-ai','decision',ai({outcome:'rejected',state:null,code:'stale_decision',pendingAction:'none'}),'stuck'],
383
+ ['cm-ai','fix_advance',{outcome:'blocked',code:'qa_fix_incomplete',fixStage:'cause_review_required'},null],
384
+ ['cm-ai','fix_advance',{outcome:'blocked',code:'qa_fix_incomplete',fixStage:'repair_blocked'},'stuck'],
385
+ ['cm-ai','fix_run',{outcome:'verified',code:'qa_fix_completed'},null],
386
+ ['cm-ai','status',ai({outcome:'reported',state:'blocked',code:'review_limit',pendingAction:'none'}),null],
387
+ // cm-ai-batch: cm-ai-batch-run.mjs
388
+ ['cm-ai-batch','advance',{...ai({outcome:'finalized',state:'run_done',code:'run_done',pendingAction:'none'}),batchId:'b1',task_commit:'abc'},'done'],
389
+ ['cm-ai-batch','advance',{outcome:'blocked',code:'merge_conflict',batchId:'b1',files:['a.js']},'stuck'],
390
+ ['cm-ai-batch','advance',{outcome:'blocked',code:'batch_task_scope_required'},'stuck'],
391
+ ['cm-ai-batch','advance',{outcome:'cancelled',code:'cancelled',batchId:'b1'},'stuck'],
392
+ ['cm-ai-batch','advance',{...ai({outcome:'advanced',state:'awaiting_review',code:null,pendingAction:'decision'}),batchId:'b1'},null],
393
+ // cm-fix: execution.mjs / progress.mjs
394
+ ['cm-fix','finish',{identity:id,stage:'completed',completionEligible:true},'done'],
395
+ ['cm-fix','advance',{identity:id,stage:'cause_review_required'},null],
396
+ ['cm-fix','cause_review',{identity:id,stage:'cause_review_required',reason:'permission_denied'},'stuck'],
397
+ ['cm-fix','final_review',{identity:id,stage:'final_review_required',reason:'permission_denied'},'stuck'],
398
+ ['cm-fix','final_review',{identity:id,stage:'revision_final_review_required',reason:'permission_denied'},'stuck'],
399
+ ['cm-fix','repair',{identity:id,stage:'revision_regression_required'},null],
400
+ ['cm-fix','repair',{identity:id,stage:'unknown',pending:'repair'},'stuck'],
401
+ ['cm-fix','cause_review',{identity:id,stage:'rediagnosis_review_limit_reached'},'stuck'],
402
+ ['cm-fix','regression',{identity:id,stage:'regression_blocked'},'stuck'],
403
+ ['cm-fix','finish',{identity:id,stage:'escalated',escalationRunEnded:true},'stuck'],
404
+ ['cm-fix','completion_evidence',{identity:id,stage:'unknown'},null],
405
+ // cm-prd: analysis.mjs / change.mjs / summary.mjs / draft-save.mjs / review-*.mjs
406
+ ['cm-prd','start',{stage:'awaiting_user',result:{status:'question',question:'q'},runId:'prd-1'},'stuck'],
407
+ ['cm-prd','advance',{stage:'analysis_ready',runId:'prd-1'},null],
408
+ ['cm-prd','plan',{stage:'self_check_needs_human',runId:'prd-1'},'stuck'],
409
+ ['cm-prd','plan',{stage:'draft_self_check_failed',runId:'prd-1'},null],
410
+ ['cm-prd','advance',{mode:'change',stage:'change_design',question:'which?',round:1},'stuck'],
411
+ ['cm-prd','advance',{mode:'change',stage:'change_check_failed',round:1},null],
412
+ ['cm-prd','advance',{mode:'change',stage:'change_check_failed',round:2},'stuck'],
413
+ ['cm-prd','advance',{mode:'change',stage:'change_confirmation'},'stuck'],
414
+ ['cm-prd','save_draft',{status:'draft_save_unknown'},'stuck'],
415
+ ['cm-prd','prepare_summary',{status:'human_summary_prepared',readyForAwaitingReview:false},'stuck'],
416
+ ['cm-prd','final_review',{stage:'draft_ready',reviewState:{status:'review_recorded',verdict:'blocked'}},'stuck'],
417
+ ['cm-prd','final_review',{stage:'draft_ready',reviewState:{status:'review_recorded',verdict:'approved'}},null],
418
+ ['cm-prd','publish_summary',{status:'awaiting_review',next:'human_review_then_explicit_cm_ai'},'done'],
419
+ ['cm-prd','save_draft',{status:'blocked',reason:'prd_host_result_unknown'},'stuck'],
420
+ // cm-idea: cm-idea-host.mjs
421
+ ['cm-idea','start',{stage:'awaiting_user',reply:{status:'question',question:'q',productType:null}},'stuck'],
422
+ ['cm-idea','advance',{stage:'draft_ready',reply:{status:'draft'}},'stuck'],
423
+ ['cm-idea','prepare_save',{stage:'draft_ready',confirmationRequired:true},null],
424
+ ['cm-idea','finish',{stage:'saved',saved:{maturity:'L1'}},'done'],
425
+ // cm-init: cm-init-host.mjs / draft-generation.mjs
426
+ ['cm-init','start',{stage:'analysis_ready'},null],
427
+ ['cm-init','start',{stage:'analysis_blocked'},'stuck'],
428
+ ['cm-init','advance',{workflow:'cm-init',status:'draft_generated'},null],
429
+ ['cm-init','advance',{workflow:'cm-init',status:'blocked',reason:'host_generation_blocked'},'stuck'],
430
+ ['cm-init','advance',{stage:'verification_blocked'},'stuck'],
431
+ ['cm-init','advance',{stage:'confirmation_required'},'stuck'],
432
+ ['cm-init','advance',{stage:'review_required'},null],
433
+ ['cm-init','advance',{stage:'rules_written'},'done'],
434
+ // cm-refactor: workflow.mjs
435
+ ['cm-refactor','resume',{stage:'awaiting_finish',runId:'refactor-1'},'stuck'],
436
+ ['cm-refactor','resume',{stage:'blocked',reason:'refactor_review_exhausted',runId:'refactor-1'},'stuck'],
437
+ ['cm-refactor','prepare_judge_revision',{stage:'judge_revision_prepared',runId:'refactor-1'},null],
438
+ ['cm-refactor','finish',{stage:'done',runId:'refactor-1'},'done'],
439
+ ['cm-refactor','start',{stage:'not_needed',runId:'refactor-1'},'done'],
440
+ // cm-test: cm-test/host.mjs
441
+ ['cm-test','start',{stage:'reported',runId:'test-1',overall:'FAIL'},'stuck'],
442
+ ['cm-test','start',{stage:'reported',runId:'test-1',overall:'BLOCKED'},'stuck'],
443
+ ['cm-test','start',{stage:'reported',runId:'test-1',overall:'PASS'},'done'],
444
+ ['cm-test','start',{stage:'interrupted',runId:'test-1',pending:{key:'1'}},'stuck'],
445
+ ['cm-test','resume',{stage:'reported',runId:'test-1',overall:'FAIL',historical:true},null],
446
+ // cm-check: cm-check/host.mjs
447
+ ['cm-check','start',{stage:'reported',result:{overall:'FAILED'}},'stuck'],
448
+ ['cm-check','start',{stage:'reported',result:{overall:'BLOCKED'}},'stuck'],
449
+ ['cm-check','start',{stage:'reported',result:{overall:'PASSED'}},'done'],
450
+ ['cm-check','start',{stage:'reported',result:{overall:'MECHANICAL_ONLY'}},'done'],
451
+ ['cm-check','start',{stage:'blocked',result:{overall:'BLOCKED',reason:'check_source_changed'}},'stuck'],
452
+ ];
453
+ test('driver classification follows each workflow contract (table)',()=>{
454
+ assert.deepEqual([...new Set(CASES.map(([workflow])=>workflow))].sort(),[...NOTIFY_WORKFLOWS].sort());
455
+ for(const [workflow,operation,result,expected] of CASES){
456
+ const notice=driveNotice({host:`/x/scripts/${workflow}-host.mjs`,cwd:'/work/demo-app',args:['serve'],operation,
457
+ row:{requestId:'drive',result}});
458
+ assert.equal(notice?.event??null,expected,`${workflow} ${operation} ${JSON.stringify(result)}`);
459
+ if(expected==='done')assert.match(notice.nextAction,/新会话/,`${workflow} done suggests a fresh session`);
460
+ }
461
+ for(const workflow of NOTIFY_WORKFLOWS){
462
+ assert.equal(driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',operation:'advance',row:{requestId:'drive',error:{code:'host_request_failed'}}}).event,'stuck');
463
+ assert.equal(driveNotice({host:`${workflow}-host.mjs`,cwd:'/w/p',operation:'advance',failure:'host_exited'}).code,'host_exited');
464
+ }
465
+ const blocked=driveNotice({host:'/x/scripts/cm-ai-host.mjs',cwd:'/work/demo-app',args:['serve'],operation:'advance',
466
+ row:{requestId:'drive',result:ai({outcome:'advanced',state:'blocked',code:'develop_checks_not_passed',pendingAction:'resume',
467
+ guidance:{nextStep:'修复后 advance'}})}});
468
+ assert.deepEqual({...blocked},{key:'cm-ai|run-1|T-001|1|blocked|develop_checks_not_passed',event:'stuck',workflow:'cm-ai',
469
+ project:'demo-app',runId:'run-1',task:'T-001',stage:'blocked',code:'develop_checks_not_passed',nextAction:'修复后 advance'});
470
+ const batch=driveNotice({host:'cm-ai-batch-host.mjs',cwd:'/w/p',args:['a'],operation:'advance',
471
+ row:{requestId:'drive',result:{outcome:'blocked',code:'merge_conflict',batchId:'b1'}}});
472
+ assert.equal(batch.runId,'b1');assert.equal(batch.code,'merge_conflict');
473
+ assert.match(driveNotice({host:'cm-ai-host.mjs',cwd:'/w/p',operation:'advance',failure:'host_exited'}).key,/^cm-ai\|args:[0-9a-f]{16}\|/);
474
+ });
475
+
476
+ // Shared driver core (scripts/*-drive.mjs all use driveHost) with a host that
477
+ // stops on blocked: one notice; repeating the identical run sends nothing new.
478
+ // The notify command takes 3 s, yet the driver exits without waiting for it.
479
+ test('driver ending in blocked notifies exactly once, never waits for the command, and an identical run does not resend',async t=>{
480
+ const h=home(t,{sleepMs:3000});
481
+ const host=path.join(h.dir,'cm-ai-host.mjs'),wrapper=path.join(h.dir,'cm-ai-drive.mjs'),project=path.join(h.dir,'demo-app');
482
+ fs.mkdirSync(project);
483
+ fs.writeFileSync(host,`process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'s'})+'\\n');
484
+ process.stdin.on('data',chunk=>{for(const line of String(chunk).split('\\n').filter(Boolean)){const row=JSON.parse(line);
485
+ if(row.requestId==='drive')process.stdout.write(JSON.stringify({requestId:'drive',result:{workflow:'cm-ai',outcome:'advanced',state:'blocked',
486
+ code:'checks_not_passed',pendingAction:'none',identity:{runId:'run-7',taskId:'T-001',attempt:1}}})+'\\n');}});
487
+ process.stdin.on('end',()=>process.exit(0));`);
488
+ fs.writeFileSync(wrapper,`import {driveHost} from ${JSON.stringify(DRIVE_CORE)};
489
+ driveHost({host:${JSON.stringify(host)},args:['serve'],cwd:${JSON.stringify(project)},operation:'advance',answers:{},answerFor:()=>null});`);
490
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
491
+ for(let i=0;i<2;i++){
492
+ const started=performance.now(),run=spawnSync(process.execPath,[wrapper],{encoding:'utf8',env,timeout:20000});
493
+ assert.equal(run.status,0,run.stderr);assert.equal(JSON.parse(run.stdout).result.state,'blocked');
494
+ assert(performance.now()-started<2000,`driver exit waited on the notify command: ${performance.now()-started} ms`);
495
+ assert.equal(h.rows().length,0,`run ${i}: the command is still running in the background`);
496
+ }
497
+ assert(await h.until(()=>h.rows().length===1));
498
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,1);
499
+ const [row]=h.rows();
500
+ assert.equal(row.title,'CM cm-ai 需要人处理 · demo-app');assert.equal(row.stdin.runId,'run-7');assert.equal(row.stdin.code,'checks_not_passed');
501
+ });
502
+
503
+ // Host bridge: a host_request outstanding past waitMinutes notifies once;
504
+ // an answer before then clears it; neither the timer nor a fired, slow
505
+ // notify command keeps the host alive.
506
+ test('host wait timer notifies once per call, is cleared on answer and does not keep the process alive',async t=>{
507
+ const h=home(t,{config:{waitMinutes:0.003}});
508
+ const script=path.join(h.dir,'cm-demo-host.mjs');
509
+ fs.writeFileSync(script,`import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
510
+ const mode=process.argv[2],bridge=createHostToolBridge();const sent=[];bridge.attach(row=>{sent.push(row);});
511
+ const answer=()=>{const r=sent.find(row=>row.type==='host_request');bridge.accept({type:'host_result',sessionId:r.sessionId,callId:r.callId,requestDigest:r.requestDigest,result:{ok:true}});};
512
+ const wait=ms=>new Promise(resolve=>setTimeout(resolve,ms));
513
+ if(mode==='late'){const p=bridge.call('qa_browser',{},new AbortController().signal);await wait(1000);answer();await p;}
514
+ if(mode==='early'){const p=bridge.call('qa_logic',{},new AbortController().signal);await wait(20);answer();await p;await wait(1200);}
515
+ if(mode==='hang')bridge.call('develop',{},new AbortController().signal).catch(()=>{});`);
516
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
517
+ const late=spawnSync(process.execPath,[script,'late'],{encoding:'utf8',env,timeout:20000});
518
+ assert.equal(late.status,0,late.stderr);
519
+ assert(await h.until(()=>h.rows().length===1));
520
+ assert.equal(h.rows()[0].title,'CM cm-demo 等待会话应答 · '+path.basename(process.cwd()));
521
+ assert.equal(h.rows()[0].stdin.stage,'qa_browser');assert.equal(h.rows()[0].stdin.code,'waiting_session_answer');
522
+ const early=spawnSync(process.execPath,[script,'early'],{encoding:'utf8',env,timeout:20000});
523
+ assert.equal(early.status,0,early.stderr);await new Promise(resolve=>setTimeout(resolve,300));assert.equal(h.rows().length,1);
524
+ const slow=home(t,{sleepMs:3000,config:{waitMinutes:0.003}});
525
+ const fired=spawnSync(process.execPath,[script,'late'],{encoding:'utf8',env:{...env,CM_WORKFLOW_HOME:slow.dir},timeout:20000});
526
+ assert.equal(fired.status,0,fired.stderr);assert.equal(slow.rows().length,0,'host exited before the slow command finished');
527
+ assert(await slow.until(()=>slow.rows().length===1));
528
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({version:1,command:['/bin/true'],waitMinutes:10}));
529
+ const started=Date.now(),hang=spawnSync(process.execPath,[script,'hang'],{encoding:'utf8',env,timeout:20000});
530
+ assert.equal(hang.status,0,hang.stderr);assert(Date.now()-started<5000);
531
+ });
532
+
533
+ // A check request waits for the session to run the project's check commands,
534
+ // which normally takes tens of minutes: it uses checkWaitMinutes, not waitMinutes.
535
+ test('check requests use checkWaitMinutes so normal long checks are not reported as waiting',async t=>{
536
+ const h=home(t,{config:{waitMinutes:0.003}});
537
+ const script=path.join(h.dir,'cm-demo-host.mjs');
538
+ fs.writeFileSync(script,`import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
539
+ const kind=process.argv[2],bridge=createHostToolBridge();const sent=[];bridge.attach(row=>{sent.push(row);});
540
+ const p=bridge.call(kind,{},new AbortController().signal);await new Promise(resolve=>setTimeout(resolve,1000));
541
+ const r=sent.find(row=>row.type==='host_request');bridge.accept({type:'host_result',sessionId:r.sessionId,callId:r.callId,requestDigest:r.requestDigest,result:{ok:true}});await p;`);
542
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
543
+ for(const kind of ['check','verification_precheck','init_verify']){
544
+ const run=spawnSync(process.execPath,[script,kind],{encoding:'utf8',env,timeout:20000});assert.equal(run.status,0,run.stderr);
545
+ }
546
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,0,'default 45-minute check threshold');
547
+ const cfg=JSON.parse(fs.readFileSync(path.join(h.dir,'notify.json'),'utf8'));
548
+ fs.writeFileSync(path.join(h.dir,'notify.json'),JSON.stringify({...cfg,waitMinutes:10,checkWaitMinutes:0.003}));
549
+ const run=spawnSync(process.execPath,[script,'check'],{encoding:'utf8',env,timeout:20000});assert.equal(run.status,0,run.stderr);
550
+ assert(await h.until(()=>h.rows().length===1));assert.equal(h.rows()[0].stdin.stage,'check');
551
+ });
552
+ test('checkWaitMinutes is validated like waitMinutes',t=>{
553
+ const h=home(t,{config:{checkWaitMinutes:0}});
554
+ assert.equal(readNotifyConfig(h.env),null);
555
+ });
556
+
557
+ // Host session: after an operation replies, nothing is in flight and the
558
+ // session sends no next operation for idleMinutes, one notice says so. A last
559
+ // result that waits on a person says "在等你" instead. Any next operation or
560
+ // session end clears it; status polls are not progress.
561
+ function idleHost(h){
562
+ const script=path.join(h.dir,'cm-prd-host.mjs');
563
+ fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
564
+ const host={handle:async request=>{
565
+ if(request.slowMs)await new Promise(resolve=>setTimeout(resolve,request.slowMs));
566
+ if(['status','fix_status'].includes(request.operation))return {stage:'status_only',doneAt:Date.now()};
567
+ return request.answer;}};
568
+ await serveCmAiHost({host,input:process.stdin,output:process.stdout});`);
569
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
570
+ // steps: [delayMs, request object | raw line string | null to end stdin];
571
+ // delay 'reply:<id>' waits until that requestId has been answered instead.
572
+ return async steps=>{
573
+ const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
574
+ let stdout='';child.stdout.on('data',chunk=>{stdout+=chunk;});
575
+ const exited=new Promise(resolve=>child.on('close',code=>resolve(code)));
576
+ const replied=id=>stdout.includes(`"requestId":"${id}"`);
577
+ for(const [delay,request] of steps){
578
+ if(typeof delay==='string'){
579
+ const id=delay.slice(6),deadline=Date.now()+15000;
580
+ while(!replied(id)){if(Date.now()>deadline){child.kill();throw new Error(`no reply for ${id}`);}await new Promise(resolve=>setTimeout(resolve,10));}
581
+ }
582
+ else await new Promise(resolve=>setTimeout(resolve,delay));
583
+ if(request===null){child.stdin.end();break;}
584
+ if(request!==undefined)child.stdin.write((typeof request==='string'?request:JSON.stringify(request))+'\n');
585
+ }
586
+ const started=Date.now(),code=await exited;
587
+ return {code,stdout,exitMs:Date.now()-started};
588
+ };
589
+ }
590
+ const op=(n,answer,extra={})=>({requestId:`r${n}`,operation:'advance',answer,...extra});
591
+
592
+ test('host session idle after a finished step notifies once: 疑似空转 for progress, 在等你 for a person',async t=>{
593
+ const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
594
+ const progress=await run([[0,op(1,{stage:'requirements_analysis',runId:'prd-1'})],[900,null]]);
595
+ assert.equal(progress.code,0);
596
+ assert(await h.until(()=>h.rows().length===1));
597
+ const [idle]=h.rows();
598
+ assert.equal(idle.title,'CM cm-prd 疑似空转 · '+path.basename(process.cwd()));
599
+ assert.equal(idle.stdin.event,'idle');assert.equal(idle.stdin.code,'no_next_step');
600
+ assert.equal(idle.stdin.runId,'prd-1');assert.equal(idle.stdin.stage,'requirements_analysis');
601
+ const waiting=home(t,{config:{idleMinutes:0.003}});
602
+ const review=await idleHost(waiting)([[0,op(1,{stage:'awaiting_user',runId:'prd-2'})],[900,null]]);
603
+ assert.equal(review.code,0);
604
+ assert(await waiting.until(()=>waiting.rows().length===1));
605
+ assert.equal(waiting.rows()[0].title,'CM cm-prd 在等你 · '+path.basename(process.cwd()));
606
+ assert.equal(waiting.rows()[0].stdin.event,'idle_waiting');assert.equal(waiting.rows()[0].stdin.code,'waiting_for_you');
607
+ await new Promise(resolve=>setTimeout(resolve,300));
608
+ assert.equal(h.rows().length,1);assert.equal(waiting.rows().length,1);
609
+ });
610
+
611
+ test('host session idle: next step, in-flight step and session end clear it; status polls do not',async t=>{
612
+ const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
613
+ // Steady progress: each next operation arrives before the threshold.
614
+ const steady=[];for(let n=1;n<=6;n++)steady.push([n===1?0:60,op(n,{stage:'requirements_analysis'})]);
615
+ assert.equal((await run([...steady,[60,null]])).code,0);
616
+ // A long in-flight operation is not idleness; ending right after its reply clears the timer.
617
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:900})],[950,null]])).code,0);
618
+ // A slow next operation: its arrival clears the timer armed by the previous reply.
619
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,op(2,{stage:'requirements_analysis'},{slowMs:900})],[950,null]])).code,0);
620
+ // A cancel reply while another operation is still in flight does not arm it.
621
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'},{slowMs:900})],[60,{requestId:'c1',operation:'cancel'}],[900,null]])).code,0);
622
+ // Driver shape: EOF right after the reply arrived.
623
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],['reply:r1',null]])).code,0);
624
+ // A line the host rejects (not JSON, unknown operation) is still the session's next step.
625
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,'not json'],[900,null]])).code,0);
626
+ assert.equal((await run([[0,op(1,{stage:'requirements_analysis'})],[60,{requestId:'x',operation:'no_such_op'}],[900,null]])).code,0);
627
+ await new Promise(resolve=>setTimeout(resolve,500));
628
+ assert.equal(h.rows().length,0,h.log());
629
+ // Polls (status via the control path, fix_status via the normal path) neither
630
+ // hold the timer off nor replace the last real step's result.
631
+ for(const poll of ['status','fix_status']){
632
+ const polls=[[0,op(1,{stage:'requirements_analysis',runId:`run-${poll}`})]];
633
+ for(let n=0;n<12;n++)polls.push([60,{requestId:`s${n}`,operation:poll}]);
634
+ assert.equal((await run([...polls,[60,null]])).code,0);
635
+ assert(await h.until(()=>h.rows().some(row=>row.stdin.runId===`run-${poll}`)));
636
+ const row=h.rows().find(row=>row.stdin.runId===`run-${poll}`);
637
+ assert.equal(row.stdin.event,'idle');assert.equal(row.stdin.stage,'requirements_analysis');
638
+ }
639
+ assert.equal(h.rows().length,2);
640
+ });
641
+
642
+ // A poll that is still running when the deadline passes holds the notice; it
643
+ // goes out right after the poll replies, not during it.
644
+ test('host session idle: a slow status in flight holds the notice until it replies',async t=>{
645
+ const h=home(t,{config:{idleMinutes:0.003}}),run=idleHost(h);
646
+ const result=await run([[0,op(1,{stage:'requirements_analysis'})],[60,{requestId:'s1',operation:'status',slowMs:700}],['reply:s1',undefined],[400,null]]);
647
+ assert.equal(result.code,0);
648
+ const doneAt=JSON.parse(result.stdout.split('\n').find(line=>line.includes('"requestId":"s1"'))).result.doneAt;
649
+ assert(await h.until(()=>h.rows().length===1));
650
+ assert(h.rows()[0].at>=doneAt,`notice at ${h.rows()[0].at} before status finished at ${doneAt}`);
651
+ assert.equal(h.rows()[0].stdin.stage,'requirements_analysis');
652
+ });
653
+
654
+ // Tool-bridge sessions end with host_close from the driver: exit 0, no notice.
655
+ test('host session idle: host_close ends the session cleanly without a notice',async t=>{
656
+ const h=home(t,{config:{idleMinutes:0.003}});
657
+ const script=path.join(h.dir,'cm-demo-host.mjs');
658
+ fs.writeFileSync(script,`import {serveCmAiHost} from ${JSON.stringify(HOST_SESSION)};
659
+ import {createHostToolBridge} from ${JSON.stringify(BRIDGE)};
660
+ const bridge=createHostToolBridge();
661
+ const host={handle:async()=>({stage:'awaiting_review',asked:await bridge.call('develop',{},new AbortController().signal)})};
662
+ await serveCmAiHost({host,input:process.stdin,output:process.stdout,toolBridge:bridge});`);
663
+ const env={...h.env};delete env.NODE_TEST_CONTEXT;
664
+ const child=spawn(process.execPath,[script],{env,stdio:['pipe','pipe','pipe']});
665
+ let stdout='';child.stdout.on('data',chunk=>{stdout+=chunk;});
666
+ const exited=new Promise(resolve=>child.on('close',resolve));
667
+ const lines=()=>stdout.split('\n').filter(Boolean).map(line=>JSON.parse(line));
668
+ child.stdin.write(JSON.stringify({requestId:'r1',operation:'advance'})+'\n');
669
+ await h.until(()=>lines().some(row=>row.type==='host_request'));
670
+ const ask=lines().find(row=>row.type==='host_request');
671
+ child.stdin.write(JSON.stringify({type:'host_result',sessionId:ask.sessionId,callId:ask.callId,requestDigest:ask.requestDigest,result:{ok:true}})+'\n');
672
+ await h.until(()=>lines().some(row=>row.requestId==='r1'));
673
+ child.stdin.write(JSON.stringify({type:'host_close',sessionId:ask.sessionId})+'\n');
674
+ assert.equal(await exited,0);
675
+ assert.deepEqual(lines().map(row=>row.type??row.requestId),['host_ready','host_request','host_response','r1','host_response']);
676
+ await new Promise(resolve=>setTimeout(resolve,500));assert.equal(h.rows().length,0);
677
+ });
678
+
679
+ test('host session idle timer never delays exit and idleMinutes is validated',async t=>{
680
+ const h=home(t,{config:{idleMinutes:600}}),run=idleHost(h);
681
+ const result=await run([[0,op(1,{stage:'requirements_analysis'})],[100,null]]);
682
+ assert.equal(result.code,0);assert(result.exitMs<3000);assert.match(result.stdout,/"requestId":"r1"/);
683
+ assert.equal(h.rows().length,0);
684
+ for(const idleMinutes of [0,-1,1441,'45'])assert.equal(readNotifyConfig(home(t,{config:{idleMinutes}}).env),null);
685
+ });