@aibyzero/cm-workflow 0.21.7 → 0.25.1

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 (227) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +64 -0
  3. package/README.md +15 -1
  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 +63 -19
  12. package/docs/js-workflow-control.md +67 -31
  13. package/docs/next-steps.md +10 -0
  14. package/docs/runtime-failover.md +2 -2
  15. package/docs/user-guide.md +1 -1
  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/claude-probe-diagnosis.mjs +21 -0
  20. package/runtime/js/cm-ai/claude-review-stream.mjs +20 -7
  21. package/runtime/js/cm-ai/claude-tool-preview.mjs +4 -2
  22. package/runtime/js/cm-ai/cm-ai-admission.mjs +9 -3
  23. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +51 -8
  24. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +30 -4
  25. package/runtime/js/cm-ai/codex-review-adapter.mjs +2 -4
  26. package/runtime/js/cm-ai/delivery-evidence.mjs +3 -1
  27. package/runtime/js/cm-ai/developer-adapter.mjs +15 -1
  28. package/runtime/js/cm-ai/drive-core.mjs +50 -6
  29. package/runtime/js/cm-ai/drive-next-step.mjs +61 -0
  30. package/runtime/js/cm-ai/durable-runner-state.mjs +85 -23
  31. package/runtime/js/cm-ai/execution-snapshot.mjs +5 -2
  32. package/runtime/js/cm-ai/execution-store.mjs +21 -3
  33. package/runtime/js/cm-ai/external-run-guard.mjs +9 -1
  34. package/runtime/js/cm-ai/host-check.mjs +4 -2
  35. package/runtime/js/cm-ai/host-conversation-execution.mjs +29 -2
  36. package/runtime/js/cm-ai/host-handoff.mjs +7 -0
  37. package/runtime/js/cm-ai/host-progress.mjs +18 -0
  38. package/runtime/js/cm-ai/host-qa-executor.mjs +47 -15
  39. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +11 -2
  40. package/runtime/js/cm-ai/host-qa-policy.mjs +24 -14
  41. package/runtime/js/cm-ai/host-session.mjs +1 -1
  42. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +1 -1
  43. package/runtime/js/cm-ai/host.mjs +1 -1
  44. package/runtime/js/cm-ai/operator-guidance.mjs +126 -2
  45. package/runtime/js/cm-ai/project-qa-gate.mjs +13 -2
  46. package/runtime/js/cm-ai/provider-review-observation.mjs +7 -3
  47. package/runtime/js/cm-ai/qa-plan-notes.mjs +106 -0
  48. package/runtime/js/cm-ai/review-continuation.mjs +102 -0
  49. package/runtime/js/cm-ai/review-evidence-file.mjs +11 -0
  50. package/runtime/js/cm-ai/review-package.mjs +25 -4
  51. package/runtime/js/cm-ai/review-presentation.mjs +31 -14
  52. package/runtime/js/cm-ai/review-runner.mjs +5 -4
  53. package/runtime/js/cm-ai/review-verdict-rules.mjs +7 -0
  54. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +30 -1
  55. package/runtime/js/cm-ai/task-commit-codec.mjs +11 -1
  56. package/runtime/js/cm-ai/task-commit.mjs +7 -4
  57. package/runtime/js/cm-ai/task-owner.mjs +5 -2
  58. package/runtime/js/cm-ai/task-runner.mjs +343 -52
  59. package/runtime/js/cm-ai/worker-claude-developer.mjs +3 -1
  60. package/runtime/js/cm-ai/worker-claude.mjs +5 -1
  61. package/runtime/js/cm-check/host.mjs +13 -3
  62. package/runtime/js/cm-fix/diagnosis.mjs +16 -3
  63. package/runtime/js/cm-fix/execution.mjs +47 -9
  64. package/runtime/js/cm-fix/finish.mjs +9 -1
  65. package/runtime/js/cm-fix/step-timing.mjs +222 -0
  66. package/runtime/js/cm-idea/session.mjs +22 -3
  67. package/runtime/js/cm-init/review-evidence.mjs +20 -7
  68. package/runtime/js/cm-prd/ai-draft.mjs +260 -0
  69. package/runtime/js/cm-prd/analysis.mjs +27 -9
  70. package/runtime/js/cm-prd/change.mjs +29 -8
  71. package/runtime/js/cm-prd/failed-correction.mjs +24 -4
  72. package/runtime/js/cm-prd/narrow-review.mjs +63 -3
  73. package/runtime/js/cm-prd/review-channels.mjs +5 -0
  74. package/runtime/js/cm-prd/review-correction.mjs +65 -5
  75. package/runtime/js/cm-prd/review-disposition.mjs +10 -1
  76. package/runtime/js/cm-prd/review-publication.mjs +2 -1
  77. package/runtime/js/cm-prd/self-check.mjs +121 -9
  78. package/runtime/js/cm-prd/session.mjs +55 -13
  79. package/runtime/js/cm-prd/summary.mjs +34 -6
  80. package/runtime/js/cm-prd/task-scope-record.mjs +40 -15
  81. package/runtime/js/cm-refactor/records.mjs +82 -11
  82. package/runtime/js/cm-refactor/workflow.mjs +3 -1
  83. package/runtime/js/executor-version.mjs +81 -0
  84. package/runtime/js/python-log-writer.mjs +15 -0
  85. package/runtime/js/run-analysis.mjs +136 -11
  86. package/runtime/logging.md +6 -0
  87. package/runtime/review.md +2 -1
  88. package/scripts/ci-test-weights.json +1 -0
  89. package/scripts/cm-ai-admission.mjs +27 -1
  90. package/scripts/cm-ai-admission.test.mjs +34 -2
  91. package/scripts/cm-ai-answer-gap-recheck.test.mjs +3 -2
  92. package/scripts/cm-ai-batch-drive.mjs +54 -17
  93. package/scripts/cm-ai-batch-drive.test.mjs +123 -6
  94. package/scripts/cm-ai-batch-host.mjs +64 -11
  95. package/scripts/cm-ai-batch-host.test.mjs +23 -3
  96. package/scripts/cm-ai-batch-location.test.mjs +22 -1
  97. package/scripts/cm-ai-batch-merge.mjs +102 -0
  98. package/scripts/cm-ai-batch-plan.mjs +55 -2
  99. package/scripts/cm-ai-batch-plan.test.mjs +228 -6
  100. package/scripts/cm-ai-batch-run-fixture.mjs +239 -15
  101. package/scripts/cm-ai-batch-run-parallel.test.mjs +23 -1
  102. package/scripts/cm-ai-batch-run.mjs +437 -34
  103. package/scripts/cm-ai-batch-session-member.test.mjs +85 -0
  104. package/scripts/cm-ai-check-recheck-cancellation.test.mjs +23 -2
  105. package/scripts/cm-ai-completion-summary.test.mjs +2 -1
  106. package/scripts/cm-ai-control-v2-drive.test.mjs +39 -9
  107. package/scripts/cm-ai-direct-review.test.mjs +1 -1
  108. package/scripts/cm-ai-disk-edits.test.mjs +229 -0
  109. package/scripts/cm-ai-drive-next-step.test.mjs +191 -0
  110. package/scripts/cm-ai-drive.mjs +66 -14
  111. package/scripts/cm-ai-drive.test.mjs +13 -3
  112. package/scripts/cm-ai-host-cli-workflow.test.mjs +4 -2
  113. package/scripts/cm-ai-host.mjs +20 -9
  114. package/scripts/cm-ai-host.test.mjs +12 -0
  115. package/scripts/cm-ai-operator-guidance.test.mjs +132 -1
  116. package/scripts/cm-ai-project-qa-gate.test.mjs +26 -0
  117. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +18 -0
  118. package/scripts/cm-ai-review-continuation.test.mjs +335 -0
  119. package/scripts/cm-ai-review-failure.test.mjs +13 -10
  120. package/scripts/cm-ai-review-timeout.test.mjs +1 -1
  121. package/scripts/cm-ai-run.mjs +42 -11
  122. package/scripts/cm-ai-run.test.mjs +26 -0
  123. package/scripts/cm-ai-supersede.test.mjs +10 -2
  124. package/scripts/cm-capability-gate.test.mjs +1 -1
  125. package/scripts/cm-check-host.test.mjs +54 -0
  126. package/scripts/cm-check-runtime.sh +27 -15
  127. package/scripts/cm-check-update.mjs +83 -8
  128. package/scripts/cm-check-update.test.mjs +114 -1
  129. package/scripts/cm-claude-developer-worker.test.mjs +29 -1
  130. package/scripts/cm-claude-managed-preflight.test.mjs +126 -0
  131. package/scripts/cm-claude-probe.test.mjs +5 -0
  132. package/scripts/cm-claude-review-stream.test.mjs +4 -1
  133. package/scripts/cm-claude-worker.test.mjs +29 -0
  134. package/scripts/cm-codex-prompt-input.test.mjs +2 -1
  135. package/scripts/cm-developer-self-review.test.mjs +27 -0
  136. package/scripts/cm-efficiency-presentation-delta.test.mjs +4 -3
  137. package/scripts/cm-efficiency-response.test.mjs +2 -1
  138. package/scripts/cm-executor-version-draft.test.mjs +251 -0
  139. package/scripts/cm-executor-version-entries.test.mjs +93 -0
  140. package/scripts/cm-executor-version-prd.test.mjs +154 -0
  141. package/scripts/cm-executor-version-records.test.mjs +256 -0
  142. package/scripts/cm-executor-version.test.mjs +250 -0
  143. package/scripts/cm-external-model-host.test.mjs +6 -1
  144. package/scripts/cm-external-review-reconciliation.test.mjs +1 -1
  145. package/scripts/cm-fix-closeout-preflight.test.mjs +123 -0
  146. package/scripts/cm-fix-diagnosis-module-correction.test.mjs +5 -1
  147. package/scripts/cm-fix-drive.mjs +7 -2
  148. package/scripts/cm-fix-drive.test.mjs +45 -0
  149. package/scripts/cm-fix-entry.mjs +5 -2
  150. package/scripts/cm-fix-frozen-baseline.test.mjs +50 -0
  151. package/scripts/cm-fix-host.mjs +9 -2
  152. package/scripts/cm-fix-review-preflight.mjs +2 -0
  153. package/scripts/cm-fix-review-verification-integration.test.mjs +19 -0
  154. package/scripts/cm-fix-test-extension.test.mjs +30 -2
  155. package/scripts/cm-host-check.test.mjs +12 -0
  156. package/scripts/cm-host-qa-executor.test.mjs +172 -1
  157. package/scripts/cm-host-qa-policy.test.mjs +55 -1
  158. package/scripts/cm-idea-drive.mjs +5 -2
  159. package/scripts/cm-idea-entry.mjs +5 -2
  160. package/scripts/cm-idea-host.mjs +3 -1
  161. package/scripts/cm-init-drive.mjs +8 -5
  162. package/scripts/cm-init-entry.mjs +5 -2
  163. package/scripts/cm-init-host.mjs +6 -2
  164. package/scripts/cm-log-event.mjs +10 -2
  165. package/scripts/cm-log-event.test.mjs +29 -0
  166. package/scripts/cm-prd-ai-draft-fixture.mjs +18 -0
  167. package/scripts/cm-prd-ai-draft.test.mjs +505 -0
  168. package/scripts/cm-prd-answer-gaps.test.mjs +110 -5
  169. package/scripts/cm-prd-completion.test.mjs +67 -4
  170. package/scripts/cm-prd-design-phase.test.mjs +48 -13
  171. package/scripts/cm-prd-drive.mjs +91 -21
  172. package/scripts/cm-prd-drive.test.mjs +126 -4
  173. package/scripts/cm-prd-entry.mjs +5 -2
  174. package/scripts/cm-prd-host.mjs +89 -20
  175. package/scripts/cm-prd-host.test.mjs +17 -8
  176. package/scripts/cm-prd-narrow-review.test.mjs +49 -1
  177. package/scripts/cm-prd-review-disposition.test.mjs +94 -1
  178. package/scripts/cm-prd-review-gate.mjs +13 -5
  179. package/scripts/cm-prd-review-publication.test.mjs +34 -0
  180. package/scripts/cm-prd-self-check-rules.test.mjs +175 -10
  181. package/scripts/cm-prd-self-check.test.mjs +1 -1
  182. package/scripts/cm-refactor-drive.mjs +10 -4
  183. package/scripts/cm-refactor-entry.mjs +5 -2
  184. package/scripts/cm-refactor-host.mjs +3 -1
  185. package/scripts/cm-release-smoke.sh +3 -2
  186. package/scripts/cm-run-analysis.test.mjs +373 -1
  187. package/scripts/cm-skill-hints-autowire.test.mjs +1 -1
  188. package/scripts/cm-skill-hints-exam.mjs +3 -1
  189. package/scripts/cm-skill-hints-install.test.mjs +1 -1
  190. package/scripts/cm-skill-hints.mjs +106 -10
  191. package/scripts/cm-skill-hints.test.mjs +162 -6
  192. package/scripts/cm-skill-judge.mjs +2 -1
  193. package/scripts/cm-task-gate.mjs +88 -18
  194. package/scripts/cm-task-scope.test.mjs +1 -1
  195. package/scripts/cm-test-drive.mjs +13 -8
  196. package/scripts/cm-test-entry.mjs +5 -2
  197. package/scripts/cm-test-host.mjs +3 -1
  198. package/scripts/cm-upgrade-compat-batch.test.mjs +62 -9
  199. package/scripts/cm-workflow-config.test.mjs +8 -3
  200. package/scripts/fixtures/fresh-completion-checks.mjs +8 -0
  201. package/scripts/fixtures/prd-review-gate-python-oracle.py +10 -1
  202. package/scripts/policy-binding-compat.test.mjs +3 -2
  203. package/scripts/scan-public-safety.py +1 -0
  204. package/scripts/shell-pipe-early-exit.test.mjs +96 -0
  205. package/scripts/test-cm-prd-review-gate.py +55 -0
  206. package/scripts/test-shell-compat.sh +7 -5
  207. package/skills/cm-ai/SKILL.md +1 -1
  208. package/skills/cm-ai/references/N1-init.md +1 -1
  209. package/skills/cm-ai/references/N4-review.md +2 -2
  210. package/skills/cm-ai/references/N6-qa-eval.md +3 -1
  211. package/skills/cm-ai/references/js-host-recovery.md +5 -1
  212. package/skills/cm-ai/references/js-host.md +17 -8
  213. package/skills/cm-check/SKILL.md +3 -0
  214. package/skills/cm-fix/references/isolated-review.md +1 -1
  215. package/skills/cm-fix/references/js-host.md +20 -0
  216. package/skills/cm-fix/references/test-extension.md +1 -1
  217. package/skills/cm-prd/SKILL.md +8 -6
  218. package/skills/cm-prd/references/ai-draft.md +81 -0
  219. package/skills/cm-prd/references/change-mode.md +2 -0
  220. package/skills/cm-prd/references/greenfield.md +2 -0
  221. package/skills/cm-prd/references/js-change-recovery.md +2 -2
  222. package/skills/cm-prd/references/js-host.md +9 -6
  223. package/skills/cm-prd/references/light-mode.md +19 -0
  224. package/skills/cm-prd/references/requirement-grilling.md +2 -0
  225. package/skills/cm-prd/references/spec-self-check.md +1 -0
  226. package/skills/cm-prd/references/summary-card.md +1 -0
  227. package/templates/auto-update/cm-update.sh +2 -2
@@ -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
+ });
@@ -50,7 +50,7 @@ test('first install wires only its own host, records it and says how to turn it
50
50
  assert.match(claude.out,/关掉提醒:在 .* 写 \{"enabled": false\}/);
51
51
  assert.match(claude.out,/--no-skill-hints 只是不自动挂,不会摘掉已挂的钩子/);
52
52
  assert.doesNotMatch(claude.out,/或重装时加 --no-skill-hints/);
53
- assert.match(claude.out,/TypeSafe.*500/);
53
+ assert.match(claude.out,/默认只用本机关键词判断,不外发;在本地文件写 "judge": true 且有 TypeSafe 密钥时,才把消息前 500 字/);
54
54
  assert.doesNotMatch(claude.out,/信任/);
55
55
 
56
56
  const codex=await b.run('codex');
@@ -80,7 +80,9 @@ export async function runExam({exam=readExam(),fetchImpl,key='exam-key',keywords
80
80
  for(const item of exam.cases){
81
81
  const home=fs.mkdtempSync(path.join(os.tmpdir(),'cm-skill-exam-'));
82
82
  try{
83
- if(keywordsOnly)fs.writeFileSync(path.join(home,'skill-hints.local.json'),JSON.stringify({judge:false}));
83
+ // Jev is off unless asked for, so the exam turns it on explicitly, and only with a
84
+ // transport the caller passed in: without one the judge would fall back to real fetch.
85
+ fs.writeFileSync(path.join(home,'skill-hints.local.json'),JSON.stringify({judge:!keywordsOnly&&Boolean(fetchImpl)}));
84
86
  const env={HOME:home,CM_WORKFLOW_HOME:home,CM_WORKFLOW_LOG_HOME:path.join(home,'logs')};
85
87
  const transport=fetchImpl&&(async(url,options)=>{
86
88
  const response=await fetchImpl(url,options);
@@ -99,7 +99,7 @@ for (const [script, scripts, host] of [
99
99
  assert.match(bytesOf(own) ?? '', new RegExp(`skill-hints/cm-skill-hints\\.mjs hook --host ${host}`));
100
100
  assert.doesNotMatch(bytesOf(other) ?? '', /cm-skill-hints/);
101
101
  assert.ok(fs.existsSync(path.join(box.copy, 'cm-skill-hints.mjs')));
102
- assert.match(output(result), /已给 (Claude|Codex) 挂上技能提醒钩子.*--no-skill-hints.*TypeSafe/);
102
+ assert.match(output(result), /已给 (Claude|Codex) 挂上技能提醒钩子.*--no-skill-hints.*默认只用本机关键词判断,不外发;在本地文件写 "judge": true 且有 TypeSafe 密钥时/);
103
103
  if (host === 'codex') assert.match(output(result), /确认信任/);
104
104
  assert.ok(!fs.existsSync(box.trust) || !/cm-skill-hints/.test(bytesOf(box.trust)), 'CM never trusts the hook for the user');
105
105
  });