@aibyzero/cm-workflow 0.21.6 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +18 -3
  4. package/VERSION +1 -1
  5. package/docs/architecture.md +9 -0
  6. package/docs/cm-acceptance-completion.md +3 -1
  7. package/docs/cm-control-policy-v2.md +35 -3
  8. package/docs/execution-optimizations.md +1 -1
  9. package/docs/external-models.md +1 -0
  10. package/docs/human-correction.md +1 -1
  11. package/docs/installation.md +42 -16
  12. package/docs/js-workflow-control.md +65 -30
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +5 -3
  15. package/docs/user-guide.md +6 -6
  16. package/package.json +1 -1
  17. package/runtime/js/cm-ai/batch-location.mjs +14 -0
  18. package/runtime/js/cm-ai/batch-plan.mjs +6 -2
  19. package/runtime/js/cm-ai/checkpoint-package-material.mjs +9 -2
  20. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  21. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  22. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  23. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  24. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  25. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  26. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  27. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  28. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  29. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  30. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  31. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  32. package/runtime/js/cm-ai/host-check.mjs +4 -2
  33. package/runtime/js/cm-ai/host-conversation-execution.mjs +23 -2
  34. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  35. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  36. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  37. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  38. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  39. package/runtime/js/cm-ai/host-session.mjs +1 -1
  40. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  41. package/runtime/js/cm-ai/host.mjs +1 -1
  42. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  43. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  44. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  45. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  46. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  47. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  48. package/runtime/js/cm-ai/review-package.mjs +25 -4
  49. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  50. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  51. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  52. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  53. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  54. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  55. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  56. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  57. package/runtime/js/cm-ai/tool-preview.mjs +6 -0
  58. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  59. package/runtime/js/cm-fix/execution.mjs +47 -9
  60. package/runtime/js/cm-fix/finish.mjs +9 -1
  61. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  62. package/runtime/js/cm-idea/session.mjs +22 -3
  63. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  64. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  65. package/runtime/js/cm-prd/analysis.mjs +27 -9
  66. package/runtime/js/cm-prd/change.mjs +29 -8
  67. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  68. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  69. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  70. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  71. package/runtime/js/cm-prd/self-check.mjs +121 -9
  72. package/runtime/js/cm-prd/session.mjs +55 -13
  73. package/runtime/js/cm-prd/summary.mjs +34 -6
  74. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  75. package/runtime/js/cm-refactor/records.mjs +82 -11
  76. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  77. package/runtime/js/executor-version.mjs +81 -0
  78. package/runtime/js/python-log-writer.mjs +15 -0
  79. package/runtime/js/run-analysis.mjs +136 -11
  80. package/runtime/logging.md +6 -0
  81. package/runtime/review.md +3 -1
  82. package/runtime/workflow-config.md +1 -1
  83. package/scripts/ci-test-weights.json +1 -0
  84. package/scripts/cm-ai-admission.mjs +27 -1
  85. package/scripts/cm-ai-admission.test.mjs +34 -2
  86. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  87. package/scripts/cm-ai-batch-drive.mjs +54 -17
  88. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  89. package/scripts/cm-ai-batch-host.mjs +55 -9
  90. package/scripts/cm-ai-batch-host.test.mjs +22 -3
  91. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  92. package/scripts/cm-ai-batch-merge.mjs +102 -0
  93. package/scripts/cm-ai-batch-plan.mjs +55 -2
  94. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  95. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  96. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  97. package/scripts/cm-ai-batch-run.mjs +435 -33
  98. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  99. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  100. package/scripts/cm-ai-checkpoint-package-material.test.mjs +28 -0
  101. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  102. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  103. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  104. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  105. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  106. package/scripts/cm-ai-drive.mjs +66 -14
  107. package/scripts/cm-ai-drive.test.mjs +13 -3
  108. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  109. package/scripts/cm-ai-host.mjs +16 -8
  110. package/scripts/cm-ai-host.test.mjs +12 -0
  111. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  112. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  113. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  114. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  115. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  116. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  117. package/scripts/cm-ai-run.mjs +42 -11
  118. package/scripts/cm-ai-run.test.mjs +26 -0
  119. package/scripts/cm-ai-supersede.test.mjs +10 -2
  120. package/scripts/cm-capability-gate.test.mjs +1 -1
  121. package/scripts/cm-check-runtime.sh +9 -0
  122. package/scripts/cm-codex-clean-env.test.mjs +40 -0
  123. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  124. package/scripts/cm-developer-self-review.test.mjs +27 -0
  125. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  126. package/scripts/cm-efficiency-response.test.mjs +2 -1
  127. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  128. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  129. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  130. package/scripts/cm-executor-version-records.test.mjs +256 -0
  131. package/scripts/cm-executor-version.test.mjs +250 -0
  132. package/scripts/cm-external-model-host.test.mjs +6 -1
  133. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  134. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  135. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  136. package/scripts/cm-fix-drive.mjs +7 -2
  137. package/scripts/cm-fix-drive.test.mjs +45 -0
  138. package/scripts/cm-fix-entry.mjs +5 -2
  139. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  140. package/scripts/cm-fix-host.mjs +9 -2
  141. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  142. package/scripts/cm-host-check.test.mjs +12 -0
  143. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  144. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  145. package/scripts/cm-idea-drive.mjs +5 -2
  146. package/scripts/cm-idea-entry.mjs +5 -2
  147. package/scripts/cm-idea-host.mjs +3 -1
  148. package/scripts/cm-init-drive.mjs +8 -5
  149. package/scripts/cm-init-entry.mjs +5 -2
  150. package/scripts/cm-init-host.mjs +6 -2
  151. package/scripts/cm-log-event.mjs +10 -2
  152. package/scripts/cm-log-event.test.mjs +29 -0
  153. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  154. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  155. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  156. package/scripts/cm-prd-completion.test.mjs +67 -4
  157. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  158. package/scripts/cm-prd-drive.mjs +89 -20
  159. package/scripts/cm-prd-drive.test.mjs +109 -4
  160. package/scripts/cm-prd-entry.mjs +5 -2
  161. package/scripts/cm-prd-host.mjs +89 -20
  162. package/scripts/cm-prd-host.test.mjs +17 -8
  163. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  164. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  165. package/scripts/cm-prd-review-gate.mjs +11 -4
  166. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  167. package/scripts/cm-prd-self-check.test.mjs +1 -1
  168. package/scripts/cm-refactor-drive.mjs +10 -4
  169. package/scripts/cm-refactor-entry.mjs +5 -2
  170. package/scripts/cm-refactor-host.mjs +3 -1
  171. package/scripts/cm-run-analysis.test.mjs +373 -1
  172. package/scripts/cm-runtime-i18n.mjs +3 -3
  173. package/scripts/cm-runtime-install.mjs +19 -10
  174. package/scripts/cm-runtime.mjs +2 -4
  175. package/scripts/cm-runtime.test.mjs +55 -13
  176. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  177. package/scripts/cm-skill-hints-exam.mjs +3 -1
  178. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  179. package/scripts/cm-skill-hints.mjs +106 -10
  180. package/scripts/cm-skill-hints.test.mjs +162 -6
  181. package/scripts/cm-skill-judge.mjs +2 -1
  182. package/scripts/cm-statusline.test.mjs +54 -0
  183. package/scripts/cm-task-gate.mjs +88 -18
  184. package/scripts/cm-task-scope.test.mjs +1 -1
  185. package/scripts/cm-test-drive.mjs +13 -8
  186. package/scripts/cm-test-entry.mjs +5 -2
  187. package/scripts/cm-test-host.mjs +3 -1
  188. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  189. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  190. package/scripts/fixtures/prd-review-gate-python-oracle.py +9 -0
  191. package/scripts/policy-binding-compat.test.mjs +3 -2
  192. package/scripts/test-cm-prd-review-gate.py +25 -0
  193. package/skills/cm-ai/SKILL.md +1 -1
  194. package/skills/cm-ai/references/N1-init.md +4 -3
  195. package/skills/cm-ai/references/N4-review.md +6 -3
  196. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  197. package/skills/cm-ai/references/js-host-recovery.md +4 -1
  198. package/skills/cm-ai/references/js-host.md +25 -5
  199. package/skills/cm-fix/references/js-host.md +20 -0
  200. package/skills/cm-fix/references/test-extension.md +1 -1
  201. package/skills/cm-prd/SKILL.md +8 -6
  202. package/skills/cm-prd/references/ai-draft.md +81 -0
  203. package/skills/cm-prd/references/change-mode.md +2 -0
  204. package/skills/cm-prd/references/greenfield.md +2 -0
  205. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  206. package/skills/cm-prd/references/js-host.md +9 -6
  207. package/skills/cm-prd/references/light-mode.md +19 -0
  208. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  209. package/skills/cm-prd/references/spec-self-check.md +1 -0
  210. package/skills/cm-prd/references/summary-card.md +1 -0
  211. package/skills/cm-runtime/SKILL.md +6 -6
  212. package/templates/statusline/cm-statusline.sh +63 -1
@@ -5,7 +5,7 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import {spawnSync} from 'node:child_process';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {withHostProgress,startHostProgress} from '../runtime/js/cm-ai/host-progress.mjs';
8
+ import {withHostProgress,startHostProgress,recordCheckReuse} from '../runtime/js/cm-ai/host-progress.mjs';
9
9
  import {recordCmAiQaDecision,recordCmAiQaRun} from '../runtime/js/cm-ai/cm-ai-qa-log.mjs';
10
10
  import {analyzeRunRows,inspectRunAnalysis,runAnalysisLines} from '../runtime/js/run-analysis.mjs';
11
11
  const cli=fileURLToPath(new URL('./cm-run-analysis.mjs',import.meta.url));
@@ -118,3 +118,375 @@ test('global event identity collisions across runs are rejected before usage ded
118
118
  assert.throws(()=>analyzeRunRows([a,b]),/log_invalid/);
119
119
  assert.throws(()=>analyzeRunRows([a,b],{runId:'run-1'}),/log_invalid/);
120
120
  });
121
+ // Process facts behind the 2026-11-28 speedup plan: spec time, approval wait,
122
+ // executed vs reused checks, and why runs were restarted.
123
+ test('reports spec time, approval waits, executed vs reused checks and restart causes',()=>{
124
+ const ai={workflow:'cm-ai',run_id:'run-ai',feature:'1.f',task:'T-001',attempt:1};
125
+ const check=(id,phase,time)=>({...ai,event:'progress',phase,operation_id:id,phase_name:'checking',at:`2026-01-01T01:${time}Z`,...(phase==='complete'?{outcome:'returned'}:{})});
126
+ const report=analyzeRunRows([
127
+ progress('start','00:00'),progress('complete','10:00'),
128
+ {run_id:'run-1',workflow:'cm-prd',event:'spec_approval',phase:'written',approval_kind:'response',wait_ms:3000},
129
+ {run_id:'run-1',workflow:'cm-prd',event:'spec_approval',phase:'written',approval_kind:'standing',wait_ms:1000},
130
+ check('c1','start','00:00'),check('c1','complete','01:00'),check('c2','start','02:00'),check('c2','complete','03:00'),
131
+ {...ai,event:'check_reuse',phase:'reused',check_count:2},
132
+ check('c3','start','04:00'),{...check('c3','complete','05:00'),outcome:'failed'},
133
+ {...ai,event:'supersede',reason:'free text',record_digest:'d1'},
134
+ {...ai,event:'supersede_cause',diagnostic:true,record_digest:'d1',causes:{'blocked/review_limit_reached':1}},
135
+ {...ai,event:'supersede_cause',diagnostic:true,record_digest:'d1',causes:{unreadable:1}},
136
+ {...ai,event:'supersede',reason:'restart'},
137
+ ]);
138
+ assert.equal(report.timing.specActiveMs,600000);assert.equal(report.timing.specRuns,1);
139
+ assert.deepEqual(report.process.approvals,{status:'observed',count:2,kinds:{response:1,standing:1},observedWaits:2,
140
+ totalWaitMs:4000,medianWaitMs:1000,maxWaitMs:3000});
141
+ assert.deepEqual(report.process.checks,{status:'observed',returnedCheckCalls:2,reusedBatches:1});
142
+ assert.deepEqual(report.process.reopens,{status:'observed',count:2,recordedCauses:1,causes:{'blocked/review_limit_reached':1}});
143
+ const lines=runAnalysisLines(report).join('\n');
144
+ assert.match(lines,/检查:调用正常返回 2 次.*完成前复用 1 批/);assert.match(lines,/blocked\/review_limit_reached=1/);
145
+ assert.match(lines,/规格审批:2 次/);
146
+ // A log without these facts reads as not recorded, never as zero.
147
+ const empty=runAnalysisLines(analyzeRunRows([{run_id:'run-old',workflow:'cm-ai',event:'run_start'}])).join('\n');
148
+ assert.match(empty,/检查:未记录/);assert.match(empty,/规格审批:未记录/);assert.match(empty,/重开:未记录/);
149
+ });
150
+
151
+ test('actual check reuse producer writes the row the analysis counts',async t=>{
152
+ const dir=fixture(t,[]),codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
153
+ const definition={specsDir:dir,codeProject,feature:'1.example'},identity={repositoryId:'analysis-fixture',runId:'run-ai-reuse',taskId:'T-001',attempt:2};
154
+ await withHostProgress({definition,identity,stage:'checking',signal:new AbortController().signal},async()=>({}));
155
+ recordCheckReuse({definition,identity,checkCount:3});
156
+ const row=fs.readFileSync(path.join(dir,'运行日志.jsonl'),'utf8').trim().split('\n').map(JSON.parse).find(x=>x.event==='check_reuse');
157
+ assert.equal(row.task,'T-001');assert.equal(row.attempt,2);assert.equal(row.check_count,3);assert.equal(row.feature,'1.example');
158
+ assert.deepEqual(inspectRunAnalysis({specs:dir}).process.checks,{status:'observed',returnedCheckCalls:1,reusedBatches:1});
159
+ });
160
+
161
+ // Dogfood 17 (2026-12-01): the analysis showed only a `review_starting` stage total,
162
+ // so nobody could see how long each review took. Each review is listed on its own;
163
+ // a review whose end event is missing stays unavailable and is never estimated.
164
+ test('per-review duration pairs start with result end and keeps missing end unavailable',()=>{
165
+ const ai={workflow:'cm-ai',run_id:'run-ai',feature:'1.f',task:'T-001',attempt:1};
166
+ const review=(id,phase,time,extra={})=>({...ai,event:'progress',phase,operation_id:id,phase_name:'review_starting',
167
+ at:`2026-01-01T02:${time}Z`,...(phase==='complete'?{outcome:'returned'}:{}),...extra});
168
+ const report=analyzeRunRows([review('r1','start','00:00'),review('r1','complete','01:30'),
169
+ review('r2','start','05:00'),review('r2','complete','05:40',{outcome:'failed'}),
170
+ review('r3','start','10:00'),review('r4','complete','12:00',{task:'T-002'})]);
171
+ const r=report.timing.reviews;
172
+ assert.equal(r.status,'partial');assert.equal(r.observed,2);assert.equal(r.unavailable,2);
173
+ assert.deepEqual(r.items.map(x=>[x.task,x.round,x.durationMs,x.outcome,x.reason]),[
174
+ ['T-001',1,90000,'returned',null],['T-001',2,40000,'failed',null],
175
+ ['T-001',3,null,null,'end_event_missing'],['T-002',1,null,'returned','start_event_missing']]);
176
+ const lines=runAnalysisLines(report).join('\n');
177
+ assert.match(lines,/审查耗时(审查调用从开始到结束,含失败或中断):已配对 2 次,不可用 2 次/);
178
+ assert.match(lines,/run-ai \/ T-001 第 1 次审查:90000 ms(结束事件 returned)/);
179
+ assert.match(lines,/run-ai \/ T-001 第 3 次审查:unavailable(日志缺结束事件,不估算)/);
180
+ assert.match(lines,/run-ai \/ 审查(review_starting):130000 ms/);
181
+ const none=runAnalysisLines(analyzeRunRows([{run_id:'run-old',workflow:'cm-ai',event:'run_start'}])).join('\n');
182
+ assert.match(none,/审查耗时:未记录/);
183
+ });
184
+
185
+ test('actual review progress producer writes the start and end the review duration pairs',async t=>{
186
+ const dir=fixture(t,[]),codeProject=path.join(dir,'code');fs.mkdirSync(codeProject);
187
+ const definition={specsDir:dir,codeProject,feature:'1.example'},identity={repositoryId:'analysis-fixture',runId:'run-ai-review',taskId:'T-001',attempt:1};
188
+ await withHostProgress({definition,identity,stage:'review_starting',signal:new AbortController().signal},async()=>({}));
189
+ const reviews=inspectRunAnalysis({specs:dir}).timing.reviews;
190
+ assert.equal(reviews.status,'observed');assert.equal(reviews.items.length,1);
191
+ assert.equal(reviews.items[0].outcome,'returned');assert(Number.isSafeInteger(reviews.items[0].durationMs));
192
+ });
193
+
194
+ test('token line explains a log without usage rows instead of estimating',()=>{
195
+ const lines=runAnalysisLines(analyzeRunRows([{run_id:'run-old',workflow:'cm-ai',event:'run_start'}])).join('\n');
196
+ assert.match(lines,/Token:unavailable/);assert.match(lines,/日志里没有模型用量记录,原因未知.*当前会话模式不上报用量.*不估算/);
197
+ const observed=runAnalysisLines(analyzeRunRows([claim('a'),usage('a')])).join('\n');
198
+ assert.doesNotMatch(observed,/当前会话模式不上报用量/);
199
+ });
200
+
201
+ const fixStep=(operation,start,end,extra={})=>{
202
+ const started=`2026-01-01T00:${start}.000Z`,ended=`2026-01-01T00:${end}.000Z`;
203
+ return {run_id:'run-fix',workflow:'cm-fix',event:'step_timing',phase:'complete',diagnostic:true,schema:2,operation,outcome:'returned',failure:null,
204
+ stage_after:null,state_after:null,started_at:started,ended_at:ended,duration_ms:Date.parse(ended)-Date.parse(started),answered:[],...extra};
205
+ };
206
+ // The run log decides which runs exist; timing rows come from their own files.
207
+ const fixRun={run_id:'run-fix',workflow:'cm-fix',event:'run_start'};
208
+ const fixSteps=(rows,{log=[fixRun],unreadable=0,runId=null}={})=>analyzeRunRows(log,{runId,fixTiming:{rows,unreadable}});
209
+ test('cm-fix step timing splits each step from the gap before it, per operation',()=>{
210
+ const f=fixSteps([fixStep('advance','00:00','01:00',{answered:['fix_learning','fix_diagnose']}),fixStep('repair','06:00','06:30'),
211
+ fixStep('final_review','07:00','15:00',{outcome:'error'}),fixStep('final_review','16:00','22:00'),
212
+ fixStep('regression','30:00','40:00',{outcome:'failed',failure:'host_exited'})]).fixSteps;
213
+ assert.equal(f.status,'observed');assert.equal(f.runs,1);assert.equal(f.stepMs,(60+30+480+360+600)*1000);assert.equal(f.gapMs,(300+30+60+480)*1000);
214
+ const repair=f.operations.find(x=>x.operation==='repair');assert.deepEqual([repair.stepMs,repair.gapMs,repair.calls],[30000,300000,1]);
215
+ const review=f.operations.find(x=>x.operation==='final_review');assert.deepEqual([review.calls,review.errors,review.gapMs],[2,1,90000]);
216
+ // A step that ended without a result keeps its own time out of the gap.
217
+ const regression=f.operations.find(x=>x.operation==='regression');assert.deepEqual([regression.stepMs,regression.gapMs,regression.errors],[600000,480000,1]);
218
+ assert.ok(runAnalysisLines(fixSteps([fixStep('repair','06:00','06:30')]))
219
+ .includes('cm-fix 步骤耗时:observed;各调用耗时合计 0.5 分钟,步骤之间(会话准备答案或等人)0.0 分钟'));
220
+ // Timing of a run that is not in the analysed log is left out, not shown.
221
+ assert.equal(fixSteps([fixStep('repair','00:00','01:00',{run_id:'other-run'})]).fixSteps.status,'unavailable');
222
+ assert.equal(fixSteps([fixStep('repair','00:00','01:00')],{log:[fixRun,{...fixRun,run_id:'run-b'}],runId:'run-b'}).fixSteps.status,'unavailable');
223
+ });
224
+ test('cm-fix step timing rejects malformed rows and unreadable files, and never counts an overlap as a negative gap',()=>{
225
+ const bad=[fixStep('bad op','00:00','01:00'),fixStep('repair','02:00','01:00'),fixStep('repair','00:00','01:00',{duration_ms:5}),
226
+ fixStep('repair','00:00','01:00',{diagnostic:false}),fixStep('repair','00:00','01:00',{schema:1}),fixStep('repair','00:00','01:00',{phase:'start'}),
227
+ fixStep('repair','00:00','01:00',{stage_after:'Bad Stage'}),fixStep('repair','00:00','01:00',{started_at:'2026-02-30T00:00:00.000Z'}),
228
+ fixStep('repair','00:00','01:00',{started_at:'2026-01-01T00:00:00Z'}),fixStep('repair','00:00','01:00',{answered:'fix_repair'}),
229
+ fixStep('repair','00:00','01:00',{outcome:'lost'}),fixStep('repair','00:00','01:00',{failure:'Bad Code'}),
230
+ fixStep('repair','00:00','01:00',{failure:undefined}),fixStep('repair','00:00','01:00',{run_id:{toString:null}}),
231
+ fixStep('repair','00:00','01:00',{event:'run_start'}),null];
232
+ const f=fixSteps([fixStep('repair','00:00','05:00'),fixStep('regression','03:00','04:00'),...bad]).fixSteps;
233
+ assert.equal(f.status,'partial');assert.equal(f.invalidRows,bad.length);assert.equal(f.overlappingCalls,1);assert.equal(f.gapMs,0);
234
+ // The impossible date alone (end after start) is still rejected by the round trip.
235
+ assert.equal(fixSteps([fixStep('repair','00:00','01:00',{started_at:'2025-12-32T00:00:00.000Z'})]).fixSteps.invalidRows,1);
236
+ assert.equal(fixSteps([bad[0]]).fixSteps.status,'invalid');
237
+ assert.equal(fixSteps([],{unreadable:1}).fixSteps.status,'invalid');
238
+ assert.equal(fixSteps([fixStep('repair','00:00','01:00')],{unreadable:1}).fixSteps.status,'partial');
239
+ assert.ok(runAnalysisLines(fixSteps([bad[0]],{unreadable:2})).some(line=>line.includes('无效记录 1 条,读不了的计时文件 2 个')));
240
+ assert.equal(analyzeRunRows([]).fixSteps.status,'unavailable');
241
+ assert.ok(!runAnalysisLines(analyzeRunRows([])).some(line=>line.startsWith('cm-fix')));
242
+ });
243
+ test('cm-fix driver timing row: pure reads skipped, failed steps timed to the close, only safe tokens kept',async()=>{
244
+ const {fixStepTimingRow}=await import('../runtime/js/cm-fix/step-timing.mjs');
245
+ const base={operation:'repair',sentAt:Date.parse('2026-01-01T00:00:00Z'),finalAt:Date.parse('2026-01-01T00:02:00Z')};
246
+ assert.equal(fixStepTimingRow({...base,operation:'status',row:{result:{}}}),null);
247
+ assert.equal(fixStepTimingRow({...base,row:null}),null);
248
+ assert.equal(fixStepTimingRow({...base,finalAt:base.sentAt-1,row:{result:{}}}),null);
249
+ assert.deepEqual(fixStepTimingRow({...base,row:{result:{stage:'regression_required',state:'Weird State'}},answered:['fix_repair','Bad Kind',7]}),
250
+ {operation:'repair',outcome:'returned',failure:null,stage_after:'regression_required',state_after:null,started_at:'2026-01-01T00:00:00.000Z',
251
+ ended_at:'2026-01-01T00:02:00.000Z',duration_ms:120000,answered:['fix_repair']});
252
+ assert.equal(fixStepTimingRow({...base,row:{error:{code:'x'}}}).outcome,'error');
253
+ const failed=fixStepTimingRow({operation:'regression',sentAt:base.sentAt,finalAt:null,closedAt:base.sentAt+1800000,row:null,failureCode:'host_exited'});
254
+ assert.deepEqual([failed.outcome,failed.failure,failed.duration_ms],['failed','host_exited',1800000]);
255
+ // A refused answer is a failure even when the host still returned a final result.
256
+ assert.equal(fixStepTimingRow({...base,row:{result:{}},failureCode:'host_response_rejected'}).outcome,'failed');
257
+ });
258
+ test('actual cm-fix driver timing writes its own per-run file, never the run log, and refuses symlinks',async t=>{
259
+ const dir=fixture(t,[{run_id:'run-fix-drive',workflow:'cm-fix',event:'run_start'}]),code=path.join(dir,'code');fs.mkdirSync(code);
260
+ const {recordFixStepTiming,fixTimingSpecsRoot,readFixStepTimingFiles}=await import('../runtime/js/cm-fix/step-timing.mjs');
261
+ const identity={runId:'run-fix-drive',taskId:'T-FIX-sample',attempt:1};
262
+ const timing={operation:'repair',sentAt:Date.parse('2026-01-01T00:00:00Z'),finalAt:Date.parse('2026-01-01T00:02:00Z'),
263
+ row:{requestId:'drive',result:{stage:'regression_required'}},answered:['fix_repair']};
264
+ const errors=[];const stderr=line=>errors.push(line);
265
+ const log=path.join(dir,'运行日志.jsonl'),before=fs.readFileSync(log,'utf8');
266
+ // A relative specsRoot is resolved where the host runs (PLAN.cwd), not in the driver's directory.
267
+ const config={specsRoot:path.relative(code,dir),identity,reproduction:{cwd:code}};
268
+ const specsRoot=fixTimingSpecsRoot(config,code);assert.equal(specsRoot,dir);
269
+ // Bare projects are not timed (their run log is not readable by the analysis).
270
+ assert.equal(fixTimingSpecsRoot({identity,reproduction:{cwd:code}},code),null);
271
+ assert.equal(await recordFixStepTiming({config,specsRoot:null,planCwd:code,timing,stderr}),false);
272
+ assert.equal(fs.existsSync(path.join(dir,'.reviews')),false);
273
+ // Only where the host keeps this run's own store: a specs root the host did not run in gets nothing.
274
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:code,timing,stderr}),false);
275
+ assert.equal(fs.existsSync(path.join(dir,'.reviews','cm-fix-step-timing')),false);
276
+ fs.mkdirSync(path.join(dir,'.reviews','.execution','run-fix-drive','writer.sqlite'),{recursive:true});
277
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:code,timing,stderr}),false);
278
+ fs.rmdirSync(path.join(dir,'.reviews','.execution','run-fix-drive','writer.sqlite'));
279
+ errors.length=0;
280
+ fs.writeFileSync(path.join(dir,'.reviews','.execution','run-fix-drive','writer.sqlite'),'');
281
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:code,timing,stderr}),true);
282
+ assert.equal(fs.readFileSync(log,'utf8'),before);
283
+ const file=path.join(dir,'.reviews','cm-fix-step-timing','run-fix-drive.jsonl');
284
+ const row=JSON.parse(fs.readFileSync(file,'utf8'));
285
+ assert.deepEqual([row.diagnostic,row.schema,row.run_id,row.operation,row.duration_ms,row.answered,row.stage_after],
286
+ [true,2,'run-fix-drive','repair',120000,['fix_repair'],'regression_required']);
287
+ assert.equal(fs.statSync(file).mode&0o777,0o600);
288
+ const f=inspectRunAnalysis({specs:dir}).fixSteps;assert.deepEqual([f.status,f.stepMs],['observed',120000]);
289
+ assert.deepEqual(inspectRunAnalysis({specs:dir,runId:'run-fix-drive'}).fixSteps.stepMs,120000);
290
+ assert.deepEqual(errors,[]);
291
+ // A symlinked timing directory is refused: nothing is written outside the specs.
292
+ const outside=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-timing-outside-')));t.after(()=>fs.rmSync(outside,{recursive:true,force:true}));
293
+ fs.rmSync(path.join(dir,'.reviews','cm-fix-step-timing'),{recursive:true});fs.symlinkSync(outside,path.join(dir,'.reviews','cm-fix-step-timing'));
294
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:code,timing,stderr}),false);
295
+ assert.deepEqual(fs.readdirSync(outside),[]);
296
+ assert.deepEqual(errors,['[drive] 步骤计时没有记上;修复结果不受影响']);
297
+ assert.equal(inspectRunAnalysis({specs:dir}).fixSteps.status,'invalid');
298
+ // A symlinked timing file is refused too, and counted unreadable by the analysis.
299
+ fs.rmSync(path.join(dir,'.reviews','cm-fix-step-timing'));fs.mkdirSync(path.join(dir,'.reviews','cm-fix-step-timing'));
300
+ fs.symlinkSync(path.join(outside,'target.jsonl'),file);
301
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:code,timing,stderr}),false);
302
+ assert.deepEqual(fs.readdirSync(outside),[]);
303
+ assert.equal(inspectRunAnalysis({specs:dir}).fixSteps.unreadableFiles,1);
304
+ // A FIFO with no reader is refused at once, never blocking the driver.
305
+ fs.rmSync(file);spawnSync('mkfifo',[file]);
306
+ const began=Date.now();assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:code,timing,stderr}),false);assert.ok(Date.now()-began<2000);
307
+ fs.rmSync(file);
308
+ // An invalid run id is never turned into a file name.
309
+ assert.equal(await recordFixStepTiming({config:{...config,identity:{...identity,runId:'../escape'}},specsRoot,planCwd:code,timing,stderr}),false);
310
+ // Listing problems and files beyond the cap are counted, never fatal or silently dropped.
311
+ const readRows=()=>{};
312
+ for(const id of ['a1','a2','a3'])fs.writeFileSync(path.join(dir,'.reviews','cm-fix-step-timing',`${id}.jsonl`),'');
313
+ assert.equal(readFixStepTimingFiles(dir,null,{maxFiles:2,readRows,toStep:()=>null}).unreadable,1);
314
+ // One total byte budget across files: past it, files are counted, not read.
315
+ fs.writeFileSync(path.join(dir,'.reviews','cm-fix-step-timing','a1.jsonl'),'x'.repeat(40));
316
+ fs.writeFileSync(path.join(dir,'.reviews','cm-fix-step-timing','a2.jsonl'),'x'.repeat(40));
317
+ assert.equal(readFixStepTimingFiles(dir,null,{maxTotalBytes:50,readRows,toStep:()=>null}).unreadable,1);
318
+ fs.chmodSync(path.join(dir,'.reviews','cm-fix-step-timing'),0o300);
319
+ t.after(()=>{try{fs.chmodSync(path.join(dir,'.reviews','cm-fix-step-timing'),0o700);}catch{}});
320
+ if(process.getuid?.()!==0){
321
+ assert.equal(readFixStepTimingFiles(dir,null,{readRows,toStep:()=>null}).unreadable,1);
322
+ assert.equal(inspectRunAnalysis({specs:dir}).fixSteps.status,'invalid');
323
+ }
324
+ fs.chmodSync(path.join(dir,'.reviews','cm-fix-step-timing'),0o700);
325
+ });
326
+ // Shared setup: a specs folder that holds the store of run-fix-drive, ready to be timed.
327
+ async function timedSpecs(t,{runs=['run-fix-drive']}={}){
328
+ const dir=fixture(t,runs.map(run_id=>({run_id,workflow:'cm-fix',event:'run_start'}))),code=path.join(dir,'code');fs.mkdirSync(code);
329
+ for(const run of runs){fs.mkdirSync(path.join(dir,'.reviews','.execution',run),{recursive:true});fs.writeFileSync(path.join(dir,'.reviews','.execution',run,'writer.sqlite'),'');}
330
+ const timing={operation:'repair',sentAt:Date.parse('2026-01-01T00:00:00Z'),finalAt:Date.parse('2026-01-01T00:02:00Z'),row:{requestId:'drive',result:{}},answered:[]};
331
+ const identity={runId:runs[0],taskId:'T-FIX-sample',attempt:1};
332
+ return {dir,code,timing,identity,config:{specsRoot:dir,identity,reproduction:{cwd:code}},timingDir:path.join(dir,'.reviews','cm-fix-step-timing')};
333
+ }
334
+ test('a hung timing write never holds the driver: it is let go after the bound and the process exits',async t=>{
335
+ const {code,timing,config,dir}=await timedSpecs(t);
336
+ // A writer stuck like a hung file system (it gives up by itself later, so the test leaves nothing running).
337
+ const stuck=path.join(dir,'stuck-writer.mjs');fs.writeFileSync(stuck,'setTimeout(()=>process.exit(0),8000);process.stdin.resume();');
338
+ const module=JSON.stringify(new URL('../runtime/js/cm-fix/step-timing.mjs',import.meta.url).href);
339
+ const wrapper=path.join(dir,'record.mjs');
340
+ fs.writeFileSync(wrapper,`import {recordFixStepTiming} from ${module};
341
+ const ok=await recordFixStepTiming({config:${JSON.stringify(config)},specsRoot:${JSON.stringify(dir)},planCwd:${JSON.stringify(code)},
342
+ timing:${JSON.stringify(timing)},timeoutMs:300,writer:${JSON.stringify(stuck)}});process.stderr.write('RESULT '+ok+'\\n');`);
343
+ const began=Date.now(),result=spawnSync(process.execPath,[wrapper],{encoding:'utf8',timeout:6000});
344
+ assert.equal(result.status,0,result.stderr);assert.ok(Date.now()-began<4000,'the driver waited for the hung writer');
345
+ // The driver itself touches no file-system path before the bound starts: a hung specs path in it would hold the driver.
346
+ const hung=path.join(dir,'record-hung.mjs');
347
+ fs.writeFileSync(hung,`import fs from 'node:fs';const block=()=>{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5000);throw Error('hung');};
348
+ for(const name of ['realpathSync','lstatSync','statSync','existsSync','readdirSync','openSync'])fs[name]=block;
349
+ `+fs.readFileSync(wrapper,'utf8'));
350
+ const began2=Date.now(),hungResult=spawnSync(process.execPath,[hung],{encoding:'utf8',timeout:8000});
351
+ assert.equal(hungResult.status,0,hungResult.stderr);assert.ok(Date.now()-began2<4000,'the driver ran a file-system call outside the bound');
352
+ assert.match(hungResult.stderr,/已不再等待/);
353
+ assert.match(result.stderr,/RESULT false/);assert.match(result.stderr,/步骤计时 1 秒内没写完.*已不再等待;修复结果不受影响/);
354
+ });
355
+ test('timing is not written when the specs link moved during the step, even if both folders hold the run',async t=>{
356
+ const a=await timedSpecs(t),b=await timedSpecs(t);
357
+ const link=path.join(a.code,'specs-link');fs.symlinkSync(a.dir,link);
358
+ const config={...a.config,specsRoot:'specs-link'};
359
+ const {fixTimingSpecsRoot,recordFixStepTiming}=await import('../runtime/js/cm-fix/step-timing.mjs');
360
+ const specsRoot=fixTimingSpecsRoot(config,a.code);assert.equal(specsRoot,a.dir);
361
+ fs.rmSync(link);fs.symlinkSync(b.dir,link);
362
+ const errors=[];
363
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:a.code,timing:a.timing,stderr:line=>errors.push(line)}),false);
364
+ assert.equal(fs.existsSync(a.timingDir),false);assert.equal(fs.existsSync(b.timingDir),false);
365
+ assert.deepEqual(errors,['[drive] 步骤计时没有记上;修复结果不受影响']);
366
+ // Unmoved, the same call writes.
367
+ fs.rmSync(link);fs.symlinkSync(a.dir,link);
368
+ assert.equal(await recordFixStepTiming({config,specsRoot,planCwd:a.code,timing:a.timing,stderr:line=>errors.push(line)}),true);
369
+ });
370
+ test('a timing file created while its directory was swapped is reported as possibly left behind, never removed by path',async t=>{
371
+ const {dir,timingDir}=await timedSpecs(t);
372
+ const {appendFixStepTiming}=await import('../runtime/js/cm-fix/step-timing.mjs');
373
+ const moved=path.join(dir,'moved');
374
+ await assert.rejects(appendFixStepTiming(dir,'run-fix-drive',{phase:'complete'},{afterOpen:()=>{fs.renameSync(timingDir,moved);fs.mkdirSync(timingDir);}}),
375
+ error=>error.leftover===true);
376
+ // The created empty file stays where it went; the new directory got nothing.
377
+ assert.deepEqual(fs.readdirSync(moved),['run-fix-drive.jsonl']);assert.deepEqual(fs.readdirSync(timingDir),[]);
378
+ // Swapped for a symlink to the moved directory: the file is still reachable by path, yet never removed through the link.
379
+ fs.rmSync(timingDir,{recursive:true});fs.rmSync(moved,{recursive:true});
380
+ await assert.rejects(appendFixStepTiming(dir,'run-fix-drive',{phase:'complete'},{afterOpen:()=>{fs.renameSync(timingDir,moved);fs.symlinkSync(moved,timingDir);}}),
381
+ error=>error.leftover===true);
382
+ assert.deepEqual(fs.readdirSync(moved),['run-fix-drive.jsonl']);fs.rmSync(timingDir);
383
+ // With the directory in place, a refused new file is removed and nothing is reported as left.
384
+ fs.rmSync(moved,{recursive:true});
385
+ await assert.rejects(appendFixStepTiming(dir,'run-fix-drive',{phase:'complete'},{afterOpen:()=>fs.linkSync(path.join(timingDir,'run-fix-drive.jsonl'),path.join(dir,'extra-link'))}),
386
+ error=>error.message==='step_timing_path_unsafe'&&!error.leftover);
387
+ assert.deepEqual(fs.readdirSync(timingDir),[]);
388
+ });
389
+ test('timing files are checked line by line: junk lines are counted, not kept, and a row filed under another run is invalid',async t=>{
390
+ const {dir,timingDir}=await timedSpecs(t,{runs:['run-a','run-b']});fs.mkdirSync(timingDir);
391
+ const row=(run,start,end)=>JSON.stringify(fixStep('repair',start,end,{run_id:run}));
392
+ fs.writeFileSync(path.join(timingDir,'run-a.jsonl'),[row('run-a','00:00','01:00'),'{}','{}',row('run-b','05:00','06:00')].join('\n')+'\n');
393
+ fs.writeFileSync(path.join(timingDir,'run-b.jsonl'),row('run-b','05:00','06:00')+'\n');
394
+ const f=inspectRunAnalysis({specs:dir}).fixSteps;
395
+ // The run-b row inside run-a's file is not counted a second time.
396
+ assert.deepEqual([f.status,f.invalidRows,f.stepMs],['partial',3,120000]);
397
+ // Many junk lines stop at the row cap: the file is unreadable, nothing is kept.
398
+ fs.writeFileSync(path.join(timingDir,'run-a.jsonl'),'{}\n'.repeat(200000));
399
+ const {readFixStepTimingFiles}=await import('../runtime/js/cm-fix/step-timing.mjs');
400
+ const kept=[];
401
+ const read=readFixStepTimingFiles(dir,['run-a'],{toStep:row=>{kept.push(row);return null;},
402
+ readRows:(file,{select})=>{for(const line of fs.readFileSync(file,'utf8').split('\n'))if(line)select(JSON.parse(line));}});
403
+ assert.deepEqual([read.unreadable,read.invalid,read.steps.length],[1,0,0]);assert.equal(kept.length,100000);
404
+ // The failed file used none of the budget: the next file is still read.
405
+ const g=inspectRunAnalysis({specs:dir}).fixSteps;assert.deepEqual([g.unreadableFiles,g.invalidRows,g.stepMs],[1,0,60000]);
406
+ // One run asked for by id is checked against the name on disk, exactly as in the full listing.
407
+ fs.rmSync(path.join(timingDir,'run-a.jsonl'));fs.writeFileSync(path.join(timingDir,'Run-A.jsonl'),row('run-a','00:00','01:00')+'\n');
408
+ const only=readFixStepTimingFiles(dir,['run-a'],{toStep:row=>({runId:row.run_id}),readRows:(file,{select})=>{select(JSON.parse(fs.readFileSync(file,'utf8')));}});
409
+ // A case-sensitive disk has no run-a.jsonl at all: that run is simply not timed.
410
+ const insensitive=fs.existsSync(path.join(timingDir,'run-a.jsonl'));
411
+ assert.deepEqual([only.invalid,only.steps.length,only.unreadable],[insensitive?1:0,0,0]);
412
+ fs.rmSync(path.join(timingDir,'Run-A.jsonl'));fs.writeFileSync(path.join(timingDir,'run-a.jsonl'),row('run-a','00:00','01:00')+'\n');
413
+ const exact=readFixStepTimingFiles(dir,['run-a'],{toStep:row=>({runId:row.run_id}),readRows:(file,{select})=>{select(JSON.parse(fs.readFileSync(file,'utf8')));}});
414
+ assert.deepEqual([exact.invalid,exact.steps.length],[0,1]);
415
+ // One run is opened by name: search permission is enough, and other runs' files are never read.
416
+ fs.writeFileSync(path.join(timingDir,'run-b.jsonl'),'{}\n'.repeat(10));
417
+ const byName=(ids,options={})=>readFixStepTimingFiles(dir,ids,{toStep:row=>({runId:row.run_id}),readRows:(file,{select})=>{for(const line of fs.readFileSync(file,'utf8').split('\n'))if(line)select(JSON.parse(line));},...options});
418
+ assert.deepEqual([byName(['run-a'],{maxRows:1}).steps.length,byName(['run-a'],{maxRows:1}).unreadable],[1,0]);
419
+ if(process.getuid?.()!==0){
420
+ fs.chmodSync(timingDir,0o100);t.after(()=>{try{fs.chmodSync(timingDir,0o700);}catch{}});
421
+ const searchOnly=byName(['run-a']);fs.chmodSync(timingDir,0o700);
422
+ assert.deepEqual([searchOnly.steps.length,searchOnly.unreadable],[1,0]);
423
+ }
424
+ // Case aliases of one file are read once; a file found and then gone is counted, not taken as untimed.
425
+ if(insensitive){
426
+ assert.equal(byName(['run-a','RUN-A']).steps.length,1);
427
+ fs.renameSync(path.join(timingDir,'run-a.jsonl'),path.join(timingDir,'run-a.JSONL'));
428
+ assert.deepEqual([byName(['run-a']).steps.length,byName(['run-a']).unreadable],[0,0]); // as the full listing, which skips *.JSONL
429
+ fs.renameSync(path.join(timingDir,'run-a.JSONL'),path.join(timingDir,'run-a.jsonl'));
430
+ // Also a link named *.JSONL: skipped as in the full listing, not counted unreadable.
431
+ fs.symlinkSync(path.join(timingDir,'run-a.jsonl'),path.join(timingDir,'run-c.JSONL'));
432
+ const link=byName(['run-c']);assert.deepEqual([link.steps.length,link.unreadable,link.invalid],[0,0,0]);fs.rmSync(path.join(timingDir,'run-c.JSONL'));
433
+ // A case-sensitive disk listing both names (the other first): the exact name is used, so the link is still read and reported.
434
+ fs.symlinkSync(path.join(timingDir,'run-a.jsonl'),path.join(timingDir,'run-c.jsonl'));
435
+ const readdir=fs.readdirSync;fs.readdirSync=(dirPath,...rest)=>dirPath===timingDir?['run-c.JSONL',...readdir(dirPath,...rest)]:readdir(dirPath,...rest);
436
+ // Read as the real reader does: a link is refused (unreadable), never followed.
437
+ const refuseLinks=(file,{select})=>{if(fs.lstatSync(file).isSymbolicLink())throw Error('link');select(JSON.parse(fs.readFileSync(file,'utf8')));};
438
+ try{const both=byName(['run-c'],{readRows:refuseLinks});assert.deepEqual([both.unreadable,both.invalid,both.steps.length],[1,0,0]);}finally{fs.readdirSync=readdir;fs.rmSync(path.join(timingDir,'run-c.jsonl'));}
439
+ }
440
+ const realpath=fs.realpathSync.native;
441
+ fs.realpathSync.native=file=>{if(file.endsWith('run-a.jsonl'))throw Object.assign(Error('gone'),{code:'ENOENT'});return realpath(file);};
442
+ try{assert.equal(byName(['run-a']).unreadable,1);}finally{fs.realpathSync.native=realpath;}
443
+ // More requested runs than the file cap: the excess is counted, never silently dropped.
444
+ assert.equal(byName(['run-a','run-x','run-y'],{maxFiles:1}).unreadable,2);
445
+ });
446
+ test('shared driver core reports step timing once, after the host has closed, also when the host exits without a result',t=>{
447
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-step-timing-')));t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
448
+ const run=mode=>{
449
+ const hostFile=path.join(root,`host-${mode}.mjs`),wrapper=path.join(root,`drive-${mode}.mjs`),closed=path.join(root,`closed-${mode}`);
450
+ fs.writeFileSync(hostFile,`import fsHost from 'node:fs';process.stdout.write(JSON.stringify({type:'host_ready',sessionId:'s'})+'\\n');
451
+ let text='',asked=false;process.stdin.on('data',chunk=>{text+=chunk;let at;while((at=text.indexOf('\\n'))>=0){const line=text.slice(0,at);text=text.slice(at+1);
452
+ if(!line)continue;const row=JSON.parse(line);
453
+ if(row.requestId==='drive'&&!asked){asked=true;process.stdout.write(JSON.stringify({type:'host_request',sessionId:'s',callId:'c1',kind:'fix_repair',requestDigest:'d',payload:{}})+'\\n');}
454
+ else if(row.type==='host_result'){
455
+ if(${JSON.stringify(mode)}==='exit'){fsHost.writeFileSync(${JSON.stringify(closed)},'1');process.exit(3);}
456
+ if(${JSON.stringify(mode)}==='reject'){process.stdout.write(JSON.stringify({type:'host_response',accepted:false,code:'host_result_invalid'})+'\\n');return;}
457
+ process.stdout.write(JSON.stringify({requestId:'drive',result:{stage:'regression_required'}})+'\\n');}
458
+ else if(row.type==='host_close'){
459
+ // A forced close still answers the open request with a final (unknown) result, as the real host does.
460
+ if(${JSON.stringify(mode)}==='stuck')return;
461
+ if(${JSON.stringify(mode)}==='unanswered')process.stdout.write(JSON.stringify({requestId:'drive',result:{stage:'unknown'}})+'\\n');
462
+ fsHost.writeFileSync(${JSON.stringify(closed)},'1');process.exit(0);}}});
463
+ if(${JSON.stringify(mode)}==='stuck')setInterval(()=>{},1000);
464
+ process.stdin.on('end',()=>{if(${JSON.stringify(mode)}==='stuck')return;fsHost.writeFileSync(${JSON.stringify(closed)},'1');process.exit(0);});`);
465
+ const core=JSON.stringify(new URL('../runtime/js/cm-ai/drive-core.mjs',import.meta.url).href);
466
+ fs.writeFileSync(wrapper,`import fs from 'node:fs';import {driveHost} from ${core};
467
+ driveHost({host:${JSON.stringify(hostFile)},args:[],cwd:${JSON.stringify(root)},operation:'repair',answers:{},answerFor:()=>(['unanswered','stuck'].includes(${JSON.stringify(mode)})?null:{outcome:'repaired'}),
468
+ liveness:{closeMs:2000,killMs:200},onStepTiming:timing=>{process.stderr.write('TIMING '+JSON.stringify({...timing,hostClosed:fs.existsSync(${JSON.stringify(closed)})})+'\\n');}});`);
469
+ const result=spawnSync(process.execPath,[wrapper],{encoding:'utf8',timeout:20000,env:{...process.env,CM_NOTIFY_OFF:'1',CM_WORKFLOW_HOME:path.join(root,'home')}});
470
+ const lines=result.stderr.split('\n').filter(line=>line.startsWith('TIMING '));assert.equal(lines.length,1,result.stderr);
471
+ return {result,timing:JSON.parse(lines[0].slice(7))};
472
+ };
473
+ const ok=run('ok');
474
+ assert.equal(ok.result.status,0,ok.result.stderr);assert.equal(JSON.parse(ok.result.stdout).result.stage,'regression_required');
475
+ assert.equal(ok.timing.hostClosed,true);assert.equal(ok.timing.operation,'repair');assert.deepEqual(ok.timing.answered,['fix_repair']);
476
+ assert.ok(Number.isSafeInteger(ok.timing.sentAt)&&ok.timing.finalAt>=ok.timing.sentAt&&ok.timing.closedAt>=ok.timing.finalAt);
477
+ assert.equal(ok.timing.row.result.stage,'regression_required');assert.equal(ok.timing.failureCode,null);
478
+ // Host died after the answer: no final row, but the step is still reported, timed to the close.
479
+ const exited=run('exit');
480
+ assert.notEqual(exited.result.status,0);assert.equal(exited.timing.row,null);assert.equal(exited.timing.failureCode,'host_exited');
481
+ assert.ok(exited.timing.closedAt>=exited.timing.sentAt);assert.equal(exited.timing.hostClosed,true);
482
+ // A refused answer is not listed as answered.
483
+ const rejected=run('reject');
484
+ assert.equal(rejected.result.status,1,rejected.result.stderr);assert.deepEqual(rejected.timing.answered,[]);
485
+ assert.equal(rejected.timing.failureCode,'host_response_rejected');
486
+ // An unanswered request is a failure even if the host still sent a final result.
487
+ const unanswered=run('unanswered');
488
+ assert.equal(unanswered.result.status,1,unanswered.result.stderr);assert.equal(unanswered.timing.failureCode,'host_request_unanswered');
489
+ // A host that then also fails to close keeps the first cause: the unanswered request.
490
+ const stuck=run('stuck');
491
+ assert.match(stuck.result.stderr,/host_close_timeout/);assert.equal(stuck.timing.failureCode,'host_request_unanswered');
492
+ });
@@ -9,8 +9,8 @@ export const messages={
9
9
  menu:{zh:'运行时配置:[1] 保留当前配置(推荐,默认) [2] 修改运行时预设 [3] 查看高级模型配置说明 [1]: ',en:'Runtime configuration: [1] Keep current configuration (recommended, default) [2] Change runtime preset [3] Advanced model configuration [1]: '},
10
10
  kept:{zh:'已保留当前配置,未写入文件。\n',en:'Kept current configuration; no files written.\n'},
11
11
  builtin:{zh:'内置默认(未声明)',en:'Built-in defaults (undeclared)'},
12
- tools:{zh:'你手上有哪个 AI 工具?[1] 只有 Codex [2] 只有 Claude [3] 两个都有: ',en:'Which AI tools do you have? [1] Codex only [2] Claude only [3] Both: '},
13
- coder:{zh:'谁写代码?[1] Codex(Claude 审,推荐) [2] Claude(Codex 审): ',en:'Who writes code? [1] Codex (Claude reviews, recommended) [2] Claude (Codex reviews): '},
12
+ tools:{zh:'你手上有哪个 AI 工具?[1] 只有 Codex [2] 只有 Claude(默认) [3] 两个都有: ',en:'Which AI tools do you have? [1] Codex only [2] Claude only (default) [3] Both: '},
13
+ coder:{zh:'谁写代码?[1] Codex(Claude 审) [2] Claude(Codex 审,默认): ',en:'Who writes code? [1] Codex (Claude reviews) [2] Claude (Codex reviews, default): '},
14
14
  scope:{zh:'改哪一层?[1] 当前项目({project}) [2] 用户级默认({user}) [{default}]: ',en:'Which scope? [1] Current project ({project}) [2] User default ({user}) [{default}]: '},
15
15
  create:{zh:'将从模板新建项目配置:{file}\n',en:'Will create project configuration from the template: {file}\n'},
16
16
  current:{zh:'当前用户级默认: {available} / {preset}\n',en:'Current user default: {available} / {preset}\n'},
@@ -26,7 +26,7 @@ export const messages={
26
26
  drift:{zh:'预览后的配置已改变: {file};未保存,请重新预览并确认。',en:'Configuration changed after preview: {file}; not saved. Generate a fresh preview and confirm again.'},
27
27
  advanced:{zh:'高级模型配置说明:建议保留当前默认,仅在有明确需要时手工编辑项目 .cm-workflow.yml 的模型别名。\n合同说明: {doc}\n校验: node "{validator}" --project "<项目路径>" --print-effective\n校验不证明 provider 兼容或配额可用;预设切换保留模型别名。\nunset --user 只删除用户默认,项目声明仍优先,不是恢复所有默认值。\n',en:'Advanced model configuration: keep current defaults unless you have a specific need; edit model aliases manually in the project .cm-workflow.yml.\nContract: {doc}\nValidate: node "{validator}" --project "<project path>" --print-effective\nValidation does not prove provider compatibility or quota; preset changes preserve model aliases.\nunset --user removes only user defaults; project declarations still win. It is not a reset of all settings.\n'},
28
28
  absent:{zh:'未声明',en:'Undeclared'},
29
- confirm:{zh:'确认?[y/N] ',en:'Confirm? [y/N] '},
29
+ confirm:{zh:'输入确认码 {code} 保存;其他输入或直接回车取消: ',en:'Type confirmation code {code} to save; anything else cancels: '},
30
30
  cancelled:{zh:'已放弃,未修改运行时声明。\n',en:'Cancelled; runtime declaration unchanged.\n'},
31
31
  installed:{zh:'✓ 用户级运行时默认已写入 {file} ({preset})\n',en:'✓ User runtime default saved to {file} ({preset})\n'},
32
32
  comment:{zh:'用 cm-runtime set --user <preset> 修改用户级默认。',en:'Use cm-runtime set --user <preset> to change the user default.'},
@@ -4,6 +4,7 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import {fileURLToPath} from 'node:url';
6
6
  import {createInterface} from 'node:readline';
7
+ import {randomBytes} from 'node:crypto';
7
8
  import {userRuntimesPath,readConfigText,parseUserRuntimes} from './cm-workflow-config.mjs';
8
9
  import {writeUserRuntime,prepareRuntimePreview,formatRuntimePreview} from './cm-runtime.mjs';
9
10
  import {runtimeLanguage,runtimeText as t} from './cm-runtime-i18n.mjs';
@@ -12,32 +13,41 @@ export class PromptCancelled extends Error {}
12
13
  // Queue lines so injected streams and pasted answers cannot lose later responses.
13
14
  export function runtimeQuestions(input,output,lang=runtimeLanguage()){
14
15
  const rl=createInterface({input,output,terminal:false});
15
- const queue=[];let pending=null,closed=false,cancelled=false;
16
+ const queue=[];let pending=null,closed=false,cancelled=false,unterminated=false;
17
+ // 输入最后一行没回车就结束(EOF),那一行不算数:防止未提交的 y 被当成确认。
18
+ input.on('data',chunk=>{const text=String(chunk);if(text.length)unterminated=!text.endsWith('\n');});
16
19
  rl.on('line',line=>{if(pending){const resolve=pending;pending=null;resolve(line);}else queue.push(line);});
17
20
  const close=()=>{closed=true;if(pending){pending(null);pending=null;}};
18
21
  rl.on('close',close);
19
22
  const interrupt=()=>{cancelled=true;queue.length=0;rl.close();close();};
20
23
  rl.on('SIGINT',interrupt);process.on('SIGINT',interrupt);
21
24
  return {
22
- async ask(question){
25
+ // fresh=true(确认题):确认码是此刻才生成的,提问显示前已排队的行一律丢弃。
26
+ async ask(question,{fresh=false}={}){
27
+ if(fresh)queue.length=0;
23
28
  if(cancelled||closed&&!queue.length)throw new PromptCancelled();
24
29
  output.write(question);
25
30
  const answer=queue.length?queue.shift():await new Promise(resolve=>{pending=resolve;});
26
31
  if(answer===null||cancelled)throw new PromptCancelled();
32
+ if(closed&&!queue.length&&unterminated)throw new PromptCancelled();
27
33
  return answer.trim();
28
34
  },
29
35
  close(){process.removeListener('SIGINT',interrupt);rl.close();},
30
36
  };
31
37
  }
38
+ // 保存确认:必须输入本次提问随机生成的 8 位确认码(每次提问重新生成,不由预览内容算出,
39
+ // 所以重复预览、提前粘贴都复用不了)。回车、n、y 等其他输入一律取消,不写。
40
+ export const newConfirmCode=()=>randomBytes(4).toString('hex'); // 8 位十六进制,碰撞概率约 1/43 亿
41
+ export async function askConfirm(ask,preview,lang=runtimeLanguage(),code=newConfirmCode()){
42
+ return (await ask(t('confirm',lang,{code}),{fresh:true})).toLowerCase()===code;
43
+ }
32
44
  export async function askRuntimePreset(ask,lang=runtimeLanguage()){
33
- let choice,empty=0;
34
- do{
35
- choice=await ask(t('tools',lang));
36
- if(choice===''){if(++empty===3)throw new PromptCancelled();}else empty=0;
37
- }while(!['1','2','3'].includes(choice));
45
+ // 空回车默认选 Claude(工具题=只有 Claude,写代码题=Claude 写)。
46
+ let choice;
47
+ do{choice=await ask(t('tools',lang));if(choice==='')choice='2';}while(!['1','2','3'].includes(choice));
38
48
  if(choice!=='3')return choice==='1'?'codex-only':'claude-only';
39
49
  let coder;
40
- do{coder=await ask(t('coder',lang));}while(!['','1','2'].includes(coder));
50
+ do{coder=await ask(t('coder',lang));if(coder==='')coder='2';}while(!['1','2'].includes(coder));
41
51
  return coder==='2'?'claude-codes':'codex-codes';
42
52
  }
43
53
  export async function promptRuntime(argv=process.argv.slice(2),input=process.stdin,output=process.stdout){
@@ -61,8 +71,7 @@ export async function promptRuntime(argv=process.argv.slice(2),input=process.std
61
71
  const preset=await askRuntimePreset(ask,lang);
62
72
  const preview=prepareRuntimePreview(null,preset,{user:true,lang});
63
73
  output.write(formatRuntimePreview(preview,lang));
64
- let confirm;do{confirm=(await ask(t('confirm',lang))).toLowerCase();}while(!['','y','n'].includes(confirm));
65
- if(confirm!=='y')throw new PromptCancelled();
74
+ if(!await askConfirm(ask,preview,lang))throw new PromptCancelled();
66
75
  output.write(t('installed',lang,{file:writeUserRuntime(preset,{lang,preview}),preset}));
67
76
  }catch(error){if(error instanceof PromptCancelled)output.write(t('cancelled',lang));else throw error;}
68
77
  finally{questions.close();}
@@ -10,7 +10,7 @@ import {ConfigError,findConfig,loadConfig,readConfigText,parseUserRuntimes,
10
10
  CONFIG_FILENAMES,previewUserRuntimeConfig} from './cm-workflow-config.mjs';
11
11
  import {editRuntimeDeclaration} from './cm-runtime-edit.mjs';
12
12
  import {runtimeLanguage,runtimeText as t} from './cm-runtime-i18n.mjs';
13
- import {askRuntimePreset,runtimeQuestions,PromptCancelled} from './cm-runtime-install.mjs';
13
+ import {askRuntimePreset,askConfirm,runtimeQuestions,PromptCancelled} from './cm-runtime-install.mjs';
14
14
  export {askRuntimePreset} from './cm-runtime-install.mjs';
15
15
  import {probeRuntimes} from './cm-failover.mjs';
16
16
 
@@ -188,9 +188,7 @@ export async function interactiveRuntime(project,{input=process.stdin,output=pro
188
188
  const preset=await askRuntimePreset(ask,lang);
189
189
  const preview=prepareRuntimePreview(root,preset,{user,lang});
190
190
  output.write(formatRuntimePreview(preview,lang));
191
- let confirm;
192
- do{confirm=(await ask(t('confirm',lang))).toLowerCase();}while(!['','y','n'].includes(confirm));
193
- if(confirm!=='y')throw new PromptCancelled();
191
+ if(!await askConfirm(ask,preview,lang))throw new PromptCancelled();
194
192
  saveRuntime(root,preset,user,lang,output,preview);
195
193
  output.write(showRuntime(root,{lang})+'\n');return 0;
196
194
  }catch(error){if(error instanceof PromptCancelled){output.write(t('cancelled',lang));return 0;}throw error;}