@aibyzero/cm-workflow 0.16.2 → 0.16.4

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 (155) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +4 -0
  3. package/CHANGELOG.md +147 -0
  4. package/README.md +44 -3
  5. package/VERSION +1 -1
  6. package/docs/installation.md +1 -1
  7. package/docs/js-workflow-control.md +46 -7
  8. package/docs/next-steps.md +100 -0
  9. package/docs/untested-branches.md +24 -18
  10. package/package.json +1 -1
  11. package/runtime/js/cm-ai/claude-review-stream.mjs +18 -0
  12. package/runtime/js/cm-ai/claude-tool-preview.mjs +45 -6
  13. package/runtime/js/cm-ai/cm-ai-admission.mjs +7 -1
  14. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +22 -12
  15. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +70 -5
  16. package/runtime/js/cm-ai/cm-ai-run-finalizer.mjs +5 -5
  17. package/runtime/js/cm-ai/drive-core.mjs +68 -0
  18. package/runtime/js/cm-ai/durable-runner-state.mjs +42 -9
  19. package/runtime/js/cm-ai/effect-contract.mjs +4 -3
  20. package/runtime/js/cm-ai/execution-snapshot.mjs +40 -0
  21. package/runtime/js/cm-ai/host-conversation-execution.mjs +8 -5
  22. package/runtime/js/cm-ai/host-handoff.mjs +9 -14
  23. package/runtime/js/cm-ai/host-qa-fix-owner.mjs +12 -7
  24. package/runtime/js/cm-ai/host-session.mjs +10 -3
  25. package/runtime/js/cm-ai/host.mjs +1 -1
  26. package/runtime/js/cm-ai/qa-config-revision.mjs +85 -0
  27. package/runtime/js/cm-ai/review-evidence-file.mjs +18 -1
  28. package/runtime/js/cm-ai/reviewed-evidence-supersede.mjs +144 -0
  29. package/runtime/js/cm-ai/reviewed-evidence-supersession-record.mjs +34 -0
  30. package/runtime/js/cm-ai/task-runner.mjs +41 -8
  31. package/runtime/js/cm-ai/worker-claude-developer.mjs +16 -7
  32. package/runtime/js/cm-fix/cause-invocation.mjs +9 -5
  33. package/runtime/js/cm-fix/cause-package.mjs +21 -0
  34. package/runtime/js/cm-fix/dossier.mjs +40 -1
  35. package/runtime/js/cm-fix/execution.mjs +360 -83
  36. package/runtime/js/cm-fix/host.mjs +7 -3
  37. package/runtime/js/cm-fix/layout.mjs +14 -6
  38. package/runtime/js/cm-fix/progress.mjs +14 -0
  39. package/runtime/js/cm-fix/protected-edits.mjs +1 -1
  40. package/runtime/js/cm-fix/red-test.mjs +7 -6
  41. package/runtime/js/cm-fix/regression-evidence.mjs +6 -3
  42. package/runtime/js/cm-fix/regression.mjs +16 -10
  43. package/runtime/js/cm-fix/repair.mjs +16 -13
  44. package/runtime/js/cm-fix/test-author.mjs +2 -1
  45. package/runtime/js/cm-fix/test-extension.mjs +45 -0
  46. package/runtime/js/cm-prd/accepted-design.mjs +28 -9
  47. package/runtime/js/cm-prd/analysis.mjs +68 -16
  48. package/runtime/js/cm-prd/change.mjs +21 -1
  49. package/runtime/js/cm-prd/draft-save.mjs +96 -2
  50. package/runtime/js/cm-prd/failed-correction.mjs +51 -0
  51. package/runtime/js/cm-prd/inputs-replaced.mjs +122 -0
  52. package/runtime/js/cm-prd/review-correction.mjs +3 -0
  53. package/runtime/js/cm-prd/review-disposition.mjs +33 -15
  54. package/runtime/js/cm-prd/review-findings.mjs +2 -2
  55. package/runtime/js/cm-prd/review-host.mjs +2 -0
  56. package/runtime/js/cm-prd/review-preparation.mjs +28 -1
  57. package/runtime/js/cm-prd/review-publication.mjs +4 -2
  58. package/runtime/js/cm-prd/self-check-revision.mjs +81 -0
  59. package/runtime/js/cm-prd/session.mjs +5 -5
  60. package/runtime/js/cm-prd/split-design.mjs +67 -0
  61. package/runtime/js/cm-prd/summary.mjs +57 -10
  62. package/runtime/js/cm-refactor/workflow.mjs +100 -19
  63. package/runtime/js/specs-status.mjs +6 -2
  64. package/scripts/cm-ai-admission.mjs +2 -0
  65. package/scripts/cm-ai-batch-drive.mjs +251 -0
  66. package/scripts/cm-ai-batch-drive.test.mjs +159 -0
  67. package/scripts/cm-ai-batch-host.mjs +13 -5
  68. package/scripts/cm-ai-batch-host.test.mjs +25 -0
  69. package/scripts/cm-ai-contracts.test.mjs +30 -0
  70. package/scripts/cm-ai-conversation-entry-ops.test.mjs +62 -0
  71. package/scripts/cm-ai-drive.mjs +335 -0
  72. package/scripts/cm-ai-drive.test.mjs +258 -0
  73. package/scripts/cm-ai-fix-integration.test.mjs +1 -1
  74. package/scripts/cm-ai-host.mjs +48 -20
  75. package/scripts/cm-ai-host.test.mjs +79 -0
  76. package/scripts/cm-ai-qa-config-revision.test.mjs +328 -0
  77. package/scripts/cm-ai-qa-fix-cross-session.test.mjs +255 -0
  78. package/scripts/cm-ai-qa-fix-policy.test.mjs +79 -0
  79. package/scripts/cm-ai-review-timeout.test.mjs +30 -0
  80. package/scripts/cm-ai-run.mjs +59 -11
  81. package/scripts/cm-ai-runner-error-code-regression.test.mjs +29 -0
  82. package/scripts/cm-ai-session-chain.test.mjs +261 -0
  83. package/scripts/cm-ai-supersede.test.mjs +320 -0
  84. package/scripts/cm-check-drive.mjs +94 -0
  85. package/scripts/cm-check-drive.test.mjs +78 -0
  86. package/scripts/cm-check-entry.mjs +13 -2
  87. package/scripts/cm-check-host.mjs +2 -2
  88. package/scripts/cm-check-host.test.mjs +103 -0
  89. package/scripts/cm-check-runtime.sh +15 -6
  90. package/scripts/cm-claude-developer-worker.test.mjs +40 -1
  91. package/scripts/cm-claude-probe.test.mjs +117 -2
  92. package/scripts/cm-claude-review-stream.test.mjs +43 -0
  93. package/scripts/cm-fix-abandon.test.mjs +383 -0
  94. package/scripts/cm-fix-cause-package.test.mjs +31 -1
  95. package/scripts/cm-fix-cross-session-host.test.mjs +17 -5
  96. package/scripts/cm-fix-drive.mjs +168 -0
  97. package/scripts/cm-fix-drive.test.mjs +117 -0
  98. package/scripts/cm-fix-escalation.test.mjs +214 -0
  99. package/scripts/cm-fix-execution.test.mjs +26 -0
  100. package/scripts/cm-fix-host.mjs +4 -2
  101. package/scripts/cm-fix-observation-dossier.test.mjs +34 -9
  102. package/scripts/cm-fix-qa-source.test.mjs +3 -3
  103. package/scripts/cm-fix-session-chain.test.mjs +244 -0
  104. package/scripts/cm-fix-test-extension.test.mjs +246 -0
  105. package/scripts/cm-fix-visual-carrier.test.mjs +66 -0
  106. package/scripts/cm-host-handoff.test.mjs +37 -0
  107. package/scripts/cm-idea-drive.mjs +99 -0
  108. package/scripts/cm-idea-drive.test.mjs +50 -0
  109. package/scripts/cm-init-drive.mjs +191 -0
  110. package/scripts/cm-init-drive.test.mjs +59 -0
  111. package/scripts/cm-log-event.mjs +9 -0
  112. package/scripts/cm-prd-completion.test.mjs +30 -2
  113. package/scripts/cm-prd-design-phase.test.mjs +355 -15
  114. package/scripts/cm-prd-drive.mjs +314 -0
  115. package/scripts/cm-prd-drive.test.mjs +164 -0
  116. package/scripts/cm-prd-host.mjs +46 -17
  117. package/scripts/cm-prd-inputs-replaced.test.mjs +237 -0
  118. package/scripts/cm-prd-review-disposition.test.mjs +133 -7
  119. package/scripts/cm-prd-review-gate.mjs +23 -4
  120. package/scripts/cm-prd-self-check-revision.test.mjs +302 -0
  121. package/scripts/cm-prd-summary.test.mjs +79 -4
  122. package/scripts/cm-refactor-drive.mjs +237 -0
  123. package/scripts/cm-refactor-drive.test.mjs +77 -0
  124. package/scripts/cm-refactor-gaps.test.mjs +276 -0
  125. package/scripts/cm-refactor-host.test.mjs +1 -48
  126. package/scripts/cm-refactor-judge-revision.test.mjs +253 -0
  127. package/scripts/cm-specs-status.test.mjs +19 -0
  128. package/scripts/cm-test-drive.mjs +132 -0
  129. package/scripts/cm-test-drive.test.mjs +91 -0
  130. package/scripts/cm-test-session.test.mjs +117 -0
  131. package/scripts/correction-check.test.mjs +38 -0
  132. package/scripts/fixtures/claude-model-marker.mjs +6 -0
  133. package/scripts/fixtures/claude-review-process.mjs +7 -0
  134. package/scripts/fixtures/cm-refactor.mjs +56 -0
  135. package/scripts/test-shell-compat.sh +67 -0
  136. package/skills/cm-ai/SKILL.md +1 -1
  137. package/skills/cm-ai/references/N4-review.md +2 -0
  138. package/skills/cm-ai/references/N8-finish.md +1 -0
  139. package/skills/cm-ai/references/js-host.md +85 -3
  140. package/skills/cm-check/SKILL.md +6 -1
  141. package/skills/cm-check/references/js-host.md +4 -2
  142. package/skills/cm-fix/SKILL.md +11 -4
  143. package/skills/cm-fix/references/js-host.md +67 -2
  144. package/skills/cm-fix/references/test-extension.md +57 -0
  145. package/skills/cm-idea/references/js-host.md +2 -0
  146. package/skills/cm-init/references/js-host.md +2 -0
  147. package/skills/cm-prd/SKILL.md +8 -8
  148. package/skills/cm-prd/references/js-change-recovery.md +71 -0
  149. package/skills/cm-prd/references/js-host.md +64 -2
  150. package/skills/cm-prd/references/spec-self-check.md +14 -2
  151. package/skills/cm-refactor/SKILL.md +5 -0
  152. package/skills/cm-refactor/references/js-batch.md +3 -1
  153. package/skills/cm-refactor/references/js-host.md +49 -0
  154. package/skills/cm-test/references/js-host.md +5 -0
  155. package/skills/cm-test/references/unit-coverage.md +2 -2
@@ -54,6 +54,53 @@ test('mechanical failure stops semantics, repeated start never retries',async t=
54
54
  const value=await host.handle({requestId:'start',operation:'start'});assert.equal(value.result.overall,'FAILED');assert.equal(value.result.semanticChecked,false);
55
55
  assert.match(value.mechanical.output,/original stderr/);await assert.rejects(()=>host.handle({requestId:'again',operation:'start'}),/check_already_started/);assert.equal(calls,1);
56
56
  });
57
+ for(const {name,statuses,core,overall} of [
58
+ {name:'all configured',statuses:['configured'],core:'passed',overall:'PASSED'},
59
+ {name:'all degraded',statuses:['degraded'],core:'passed',overall:'PASSED'},
60
+ {name:'all unknown',statuses:['unknown'],core:'passed',overall:'PASSED'},
61
+ {name:'mixed statuses',statuses:['unknown','configured','degraded'],core:'passed',overall:'PASSED'},
62
+ {name:'configured cannot mask a failed check',statuses:['configured'],core:'failed',overall:'FAILED'},
63
+ ])test(`optional report preserves order and reasons without changing core: ${name}`,async t=>{
64
+ const f=fixture(t);let expectedOptional;
65
+ const host=createCmCheckHost(f.input,{call:async(kind,payload)=>{
66
+ if(kind==='check_runtime')return mechanical(payload);
67
+ const value=assessment(payload);
68
+ // Deliberately report a different order and distinct reasons, including surrounding whitespace.
69
+ value.optional.reverse().forEach((row,i)=>{
70
+ row.status=statuses[i%statuses.length];row.reason=` Synthetic ${row.id}: ${row.status} (${i}) `;
71
+ });
72
+ expectedOptional=structuredClone(value.optional);
73
+ if(core==='failed'){value.checks[1].status='failed';value.checks[1].findings=['Synthetic reproducible broken link'];}
74
+ return value;
75
+ }});
76
+ const report=await host.handle({requestId:'optional',operation:'start'});
77
+ assert.equal(report.result.overall,overall,JSON.stringify(report.result));
78
+ assert.equal(report.result.semanticChecked,true);
79
+ assert.deepEqual(report.result.optional,expectedOptional);
80
+ assert.equal(report.result.checks[1].status,core);
81
+ assert.equal(report.result.findingsCount,core==='failed'?1:0);
82
+ });
83
+
84
+ for(const {name,mutate,reason} of [
85
+ {name:'unknown status enabled',mutate:rows=>{rows[0].status='enabled';},reason:'check_optional_invalid'},
86
+ {name:'uppercase status CONFIGURED',mutate:rows=>{rows[0].status='CONFIGURED';},reason:'check_optional_invalid'},
87
+ {name:'empty reason',mutate:rows=>{rows[0].reason='';},reason:'check_optional_invalid'},
88
+ {name:'whitespace reason',mutate:rows=>{rows[0].reason=' \t\n ';},reason:'check_optional_invalid'},
89
+ {name:'missing id',mutate:rows=>{rows.pop();},reason:'check_optional_incomplete'},
90
+ {name:'duplicate id at unchanged length',mutate:rows=>{rows[1].id=rows[0].id;},reason:'check_optional_incomplete'},
91
+ {name:'extra id',mutate:rows=>{rows.push({id:'unrecognized_tool',status:'configured',reason:'Synthetic extra tool'});},reason:'check_optional_incomplete'},
92
+ {name:'unknown id at unchanged length',mutate:rows=>{rows[0].id='unrecognized_tool';},reason:'check_optional_invalid'},
93
+ ])test(`invalid optional report blocks with exact reason: ${name}`,async t=>{
94
+ const f=fixture(t);
95
+ const host=createCmCheckHost(f.input,{call:async(kind,payload)=>{
96
+ if(kind==='check_runtime')return mechanical(payload);
97
+ const value=assessment(payload);mutate(value.optional);return value;
98
+ }});
99
+ const report=await host.handle({requestId:'optional-invalid',operation:'start'});
100
+ assert.equal(report.result.overall,'BLOCKED',JSON.stringify(report.result));
101
+ assert.equal(report.result.reason,reason);
102
+ });
103
+
57
104
  test('coverage, evidence, stale source/config, core findings and cancellation preserve honest verdicts',async t=>{
58
105
  for(const mode of ['missing','bad-line','stale','source-drift','config-drift','failed','blocked','cancel']){
59
106
  const f=fixture(t);let host;host=createCmCheckHost(f.input,{call:async(kind,payload)=>{
@@ -164,3 +211,59 @@ test('quick mode still reports an actual mechanical failure',{timeout:5000},asyn
164
211
  assert.equal(report.result.overall,'FAILED','quick mode must not swallow a failing checker');
165
212
  assert.equal(report.result.semanticChecked,false);
166
213
  });
214
+
215
+ test('an explicit runtime reaches the checker; omitting it never claims a dispatch verdict',{timeout:5000},async t=>{
216
+ const f=fixture(t),seen=[];
217
+ for(const runtime of ['codex','claude']){
218
+ const host=createCmCheckHost({...f.input,runtime,quick:true},{call:async(kind,payload)=>{
219
+ seen.push(payload.invocation.args);return mechanical(payload);
220
+ }});
221
+ const report=await host.handle({requestId:`r-${runtime}`,operation:'start'});
222
+ assert.equal(report.result.overall,'MECHANICAL_ONLY');
223
+ }
224
+ assert.deepEqual(seen,[
225
+ ['--project',f.input.project,'--runtime','codex','--print-effective'],
226
+ ['--project',f.input.project,'--runtime','claude','--print-effective']
227
+ ],'the checker must be told which runtime is actually running it');
228
+ const plain=[];
229
+ const host=createCmCheckHost({...f.input,quick:true},{call:async(kind,payload)=>{
230
+ plain.push(payload.invocation.args);return mechanical(payload);
231
+ }});
232
+ await host.handle({requestId:'r-none',operation:'start'});
233
+ assert.deepEqual(plain,[['--project',f.input.project,'--print-effective']],'an unnamed runtime must not be substituted with a guess');
234
+ });
235
+
236
+ test('an unsupported runtime is rejected instead of silently defaulting',{timeout:5000},async t=>{
237
+ const f=fixture(t);
238
+ for(const runtime of ['pi','CODEX','unknown','',null]){
239
+ assert.throws(()=>createCmCheckHost({...f.input,runtime},{call:async()=>{throw Error('must not run');}}),
240
+ error=>error.code==='runtime_invalid',`runtime ${JSON.stringify(runtime)} must not reach the checker`);
241
+ }
242
+ });
243
+
244
+ test('the JSONL CLI accepts --runtime once and rejects a malformed one',{timeout:5000},async t=>{
245
+ const f=fixture(t),cli=path.join(f.dir,'scripts/cm-check-host.mjs');
246
+ const base=['serve','--skill-dir',f.input.skillDir,'--project',f.input.project];
247
+ for(const extra of [['--runtime'],['--runtime','claude','--runtime','codex']]){
248
+ const bad=spawnSync(process.execPath,[cli,...base,...extra],{encoding:'utf8',input:''});
249
+ assert.equal(bad.status,1,`${extra.join(' ')} must not start a session`);
250
+ assert.match(bad.stderr,/invalid_arguments/);
251
+ }
252
+ const help=spawnSync(process.execPath,[cli,'--help'],{encoding:'utf8'});
253
+ assert.match(help.stdout,/--runtime codex\|claude/,'the documented usage must name the option');
254
+ });
255
+
256
+ test('the standalone mechanical entry CLI takes the runtime flag and validates it',{timeout:5000},async t=>{
257
+ const f=fixture(t),cli=path.join(f.dir,'scripts/cm-check-entry.mjs');
258
+ const base=['--skill-dir',f.input.skillDir,'--project',f.input.project];
259
+ const ok=spawnSync(process.execPath,[cli,...base,'--runtime','claude','--print-effective'],{encoding:'utf8'});
260
+ assert.equal(ok.status,0,ok.stderr);
261
+ assert.match(ok.stdout,/original checker output/,'the real checker must still be the one that runs');
262
+ for(const extra of [['--runtime','pi'],['--runtime','unknown']]){
263
+ const bad=spawnSync(process.execPath,[cli,...base,...extra,'--print-effective'],{encoding:'utf8'});
264
+ assert.equal(bad.status,2,`${extra.join(' ')} must not run the checker`);
265
+ assert.match(bad.stderr,/runtime_invalid/);
266
+ }
267
+ const dup=spawnSync(process.execPath,[cli,...base,'--runtime','codex','--runtime','claude','--print-effective'],{encoding:'utf8'});
268
+ assert.equal(dup.status,2);assert.match(dup.stderr,/invalid_arguments/);
269
+ });
@@ -184,29 +184,38 @@ PROJECT_PATH="$PWD"
184
184
  CONFIG_PATH=""
185
185
  REQUESTED_MODE=""
186
186
  PRINT_EFFECTIVE=0
187
+ CHECK_RUNTIME=""
187
188
  while [ "$#" -gt 0 ]; do
188
189
  case "$1" in
189
190
  --project)
190
- [ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
191
+ [ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
191
192
  PROJECT_PATH="$2"
192
193
  shift 2
193
194
  ;;
194
195
  --config)
195
- [ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
196
+ [ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
196
197
  CONFIG_PATH="$2"
197
198
  shift 2
198
199
  ;;
199
200
  --routing-fixtures|--log-fixtures)
200
- [ -z "$REQUESTED_MODE" ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
201
+ [ -z "$REQUESTED_MODE" ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
201
202
  REQUESTED_MODE="$1"
202
203
  shift
203
204
  ;;
205
+ --runtime)
206
+ [ "$#" -ge 2 ] || { echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2; }
207
+ case "$2" in
208
+ codex|claude) CHECK_RUNTIME="$2" ;;
209
+ *) echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2; exit 2 ;;
210
+ esac
211
+ shift 2
212
+ ;;
204
213
  --print-effective)
205
214
  PRINT_EFFECTIVE=1
206
215
  shift
207
216
  ;;
208
217
  *)
209
- echo "Usage: $0 [--project PATH] [--config PATH] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2
218
+ echo "Usage: $0 [--project PATH] [--config PATH] [--runtime codex|claude] [--print-effective] [--routing-fixtures|--log-fixtures]" >&2
210
219
  exit 2
211
220
  ;;
212
221
  esac
@@ -395,14 +404,14 @@ if [ -n "$NODE_BIN" ]; then
395
404
  for rt in $missing; do
396
405
  warn "runtimes.available 声明 ${declared},但本机 ${rt} CLI 不可解析(可解析≠配额可用)"
397
406
  done
398
- current_runtime="${CM_RUNTIME:-codex}"
407
+ current_runtime="${CHECK_RUNTIME:-${CM_RUNTIME:-unknown}}"
399
408
  for role in coder reviewer; do
400
409
  if [ -n "$CONFIG_PATH" ]; then
401
410
  role_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --config "$CONFIG_PATH" --role "$role" --runtime "$current_runtime" --print-role 2>/dev/null || true)
402
411
  else
403
412
  role_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --role "$role" --runtime "$current_runtime" --print-role 2>/dev/null || true)
404
413
  fi
405
- role_line=$(printf '%s' "$role_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={};try{j=JSON.parse(d);}catch{}const tag=j.route_state==="declared-adapter"?"(已声明未派发)":"";process.stdout.write(`${j.role||"?"}: adapter=${j.adapter||"?"} route_state=${j.route_state||"?"}${tag}`);})' 2>/dev/null || true)
414
+ role_line=$(printf '%s' "$role_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={};try{j=JSON.parse(d);}catch{}const unknown=process.argv[1]==="unknown";const state=unknown?"未判定":(j.route_state||"?");const tag=unknown?"(当前运行时未指定,用 --runtime 或 CM_RUNTIME 指定后才能判断)":(j.route_state==="declared-adapter"?"(已声明未派发)":"");process.stdout.write(`${j.role||"?"}: adapter=${j.adapter||"?"} route_state=${state}${tag}`);})' "$current_runtime" 2>/dev/null || true)
406
415
  [ -n "$role_line" ] && echo "runtime declaration [${declared}] ${role_line}"
407
416
  done
408
417
  fi
@@ -57,6 +57,45 @@ function fakeWorker(cwd,{value=proposal,mode='normal',timeoutMs=3000,noticeEvent
57
57
  const rateLimit=(overrides={})=>({type:'rate_limit_event',session_id:'synthetic-claude-developer',
58
58
  rate_limit_info:{status:'allowed',rateLimitType:'five_hour',resetsAt:123,active:true,reason:null,
59
59
  nested:{raw:'private'},list:['private']},...overrides});
60
+ const devIntent=(sessionId='synthetic-claude-developer')=>JSON.parse(
61
+ `{"type":"system","subtype":"dev_intent","kind":"ios_app","trigger":"project_scan","uuid":"fixture-uuid","session_id":"${sessionId}"}`,
62
+ );
63
+ test('developer accepts dev_intent on either side of init with a sanitized notice',async t=>{
64
+ const root=fixture(t),control={signal:new AbortController().signal};
65
+ const baseline=await fakeWorker(root)({prompt:prompt()},control);
66
+ for(const noticeAt of [0,1,2]){
67
+ const notices=[],result=await fakeWorker(root,{noticeAt,noticeEvents:[devIntent()],onNotice:n=>notices.push(n)})
68
+ ({prompt:prompt()},control);
69
+ assert.deepEqual(result,baseline);
70
+ assert.deepEqual(notices,[{kind:'claude_system_notice',subtype:'dev_intent'}]);
71
+ }
72
+ for(const onNotice of [undefined,()=>{throw Error('notice consumer');}]){
73
+ const result=await fakeWorker(root,{noticeAt:0,noticeEvents:[devIntent()],onNotice})({prompt:prompt()},control);
74
+ assert.deepEqual(result,baseline);
75
+ }
76
+ });
77
+ test('developer dev_intent binds init session and shares a 32-notice budget',async t=>{
78
+ const root=fixture(t),control={signal:new AbortController().signal};
79
+ for(const [noticeEvents,noticeAt,code] of [
80
+ [[devIntent('other')],0,'session_mismatch'],
81
+ [[devIntent('other')],1,'session_mismatch'],
82
+ [[devIntent('')],0,'invalid_session'],
83
+ [[devIntent(' '.repeat(3))],0,'invalid_session'],
84
+ [[devIntent('x'.repeat(129))],0,'invalid_session'],
85
+ [[{...devIntent(),subtype:'api_retry'}],0,'missing_init'],
86
+ [[{...devIntent(),subtype:'future_notice'}],1,'unexpected_event'],
87
+ [Array.from({length:33},()=>devIntent()),0,'unexpected_event'],
88
+ ]){
89
+ const result=await fakeWorker(root,{noticeEvents,noticeAt})({prompt:prompt()},control);
90
+ assert.deepEqual(result,{status:'unknown',code});
91
+ }
92
+ const notices=[],baseline=await fakeWorker(root)({prompt:prompt()},control);
93
+ const result=await fakeWorker(root,{noticeAt:1,
94
+ noticeEvents:[devIntent(),...Array.from({length:30},()=>devIntent()),rateLimit()],
95
+ onNotice:n=>notices.push(n)})({prompt:prompt()},control);
96
+ assert.deepEqual(result,baseline);
97
+ assert.equal(notices.length,32);
98
+ });
60
99
  test('developer forwards scalar notices while preserving proposals and read-tool state',async t=>{
61
100
  const root=fixture(t),events=[],control={signal:new AbortController().signal,onEvent:e=>events.push(e)};
62
101
  const baseline=await fakeWorker(root)({prompt:prompt()},control);
@@ -110,7 +149,7 @@ test('developer rejects mismatched, excessive, unknown and terminal rate limit e
110
149
  const root=fixture(t);
111
150
  for(const [noticeEvents,noticeAt,code,count] of [
112
151
  [[rateLimit({session_id:'other'})],1,'session_mismatch',0],
113
- [Array.from({length:9},()=>rateLimit()),1,'unexpected_event',8],
152
+ [Array.from({length:33},()=>rateLimit()),1,'unexpected_event',32],
114
153
  [[rateLimit({type:'foo_event'})],1,'unexpected_event',0],
115
154
  [[rateLimit()],0,'missing_init',0],
116
155
  [[rateLimit()],3,'invalid_event',0],
@@ -4,9 +4,71 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import http from 'node:http';
7
- import {spawn} from 'node:child_process';
7
+ import * as zlib from 'node:zlib';
8
+ import {spawn,spawnSync} from 'node:child_process';
8
9
  import {fileURLToPath} from 'node:url';
9
- import {previewClaudeTools,claudeProbeSandbox} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
10
+ import {buildManifest} from './cm-spec-manifest.mjs';
11
+ import {previewClaudeTools,claudeProbeSandbox,createClaudeModelMarkerDetector} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
12
+ import {previewPromptTransport,writePreviewPrompt} from '../runtime/js/cm-ai/tool-preview.mjs';
13
+
14
+ test('tool preview argument transport preserves a long Unicode argv prompt without stdin',()=>{
15
+ const prompt='参数\n🚀'+'界'.repeat(10000);
16
+ const transport=previewPromptTransport('argument',prompt);
17
+ assert.equal(transport.argument,prompt);assert.equal(transport.stdin,null);
18
+ assert.deepEqual(transport.stdio,['ignore','pipe','pipe']);
19
+ let stdinAccesses=0;
20
+ const cleanup=writePreviewPrompt({get stdin(){stdinAccesses++;throw Error('stdin accessed');}},
21
+ 'argument',prompt,()=>assert.fail('argument transport wrote stdin'));
22
+ cleanup();assert.equal(stdinAccesses,0);
23
+ });
24
+
25
+ test('fake Claude process stderr marker yields only its reported model',async()=>{
26
+ const fixture=fileURLToPath(new URL('./fixtures/claude-model-marker.mjs',import.meta.url));
27
+ for(const [model,expected] of [['fixture-unrecognized-model','fixture-unrecognized-model'],
28
+ ['fixture-recognized-model',null]]){
29
+ const child=spawn(process.execPath,[fixture,'--model',model],{stdio:['ignore','pipe','pipe']});
30
+ let found=null,stdout='';
31
+ const detector=createClaudeModelMarkerDetector(value=>{found=value;});
32
+ child.stderr.on('data',chunk=>detector.accept(chunk));
33
+ child.stdout.on('data',chunk=>stdout+=chunk);
34
+ const code=await new Promise((resolve,reject)=>{child.once('error',reject);child.once('close',resolve);});
35
+ detector.finish();
36
+ assert.equal(code,0);
37
+ assert.deepEqual(found,expected===null?null:{reported_model:expected});
38
+ assert.deepEqual(JSON.parse(stdout),{type:'result',result:''});
39
+ }
40
+ });
41
+
42
+ // Authored without local execution; verification by reviewer outside the sandbox is pending.
43
+ // The sink intentionally retains protocol checks, never the decoded body bytes.
44
+ for(const encoding of ['gzip','zstd','br'])test(`Claude probe ${encoding} body reaches only its declared decoder`,
45
+ {skip:process.platform!=='darwin'||(encoding==='zstd'&&typeof zlib.zstdCompressSync!=='function')},async()=>{
46
+ const payload={model:'fixture',messages:[{role:'user',content:`synthetic ${encoding} payload`}],tools:[]};
47
+ const source=`let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',async()=>{
48
+ const zlib=require('node:zlib');const body=Buffer.from(JSON.stringify(${JSON.stringify(payload)}));
49
+ const encoded=${JSON.stringify(encoding)}==='gzip'?zlib.gzipSync(body):
50
+ ${JSON.stringify(encoding)}==='zstd'?zlib.zstdCompressSync(body):body;
51
+ await fetch(process.env.ANTHROPIC_BASE_URL+'/v1/messages',{method:'POST',
52
+ headers:{'x-api-key':'cm-synthetic-local-probe','content-encoding':${JSON.stringify(encoding)}},body:encoded});
53
+ process.exit(1);
54
+ });`;
55
+ const {preflight}=await previewClaudeTools({cwd:process.cwd(),model:'fixture',
56
+ spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,'-e',source],options)});
57
+ assert.equal(preflight.message_requests,1);
58
+ assert.equal(preflight.listener_closed,true);
59
+ if(encoding==='br'){
60
+ assert.equal(preflight.passed,false);
61
+ assert.equal(preflight.request_checks[0].encoding_supported,false);
62
+ assert.equal(preflight.request_checks[0].json,false);
63
+ }else{
64
+ assert.equal(preflight.passed,true);
65
+ assert.equal(preflight.request_checks[0].json,true);
66
+ assert.equal(preflight.request_checks[0].model_matches,true);
67
+ assert.equal(preflight.request_checks[0].messages_array,true);
68
+ assert.equal(preflight.request_checks[0].tools_allowed,true);
69
+ assert.equal(preflight.request_checks[0].synthetic_auth,true);
70
+ }
71
+ });
10
72
 
11
73
  test('probe accepts only empty tools or one internal StructuredOutput tool',
12
74
  {skip:process.platform!=='darwin'},async()=>{
@@ -84,6 +146,59 @@ test('diagnostic still accepts one tool-free message request from an older CLI',
84
146
  assert.equal(result.preflight.message_requests_expected,'1-2');
85
147
  assert.equal(result.preflight.stopped_by_probe,true);assert.equal(result.preflight.listener_closed,true);
86
148
  });
149
+ for(const [model,recognized] of [['fixture-unrecognized-model',false],['fixture-recognized-model',true]])
150
+ test(`Claude preflight ${recognized?'accepts':'rejects'} fake CLI ${recognized?'without':'with'} unrecognized_model stderr`,
151
+ {skip:process.platform!=='darwin'},async()=>{
152
+ const fixture=fileURLToPath(new URL('./fixtures/claude-review-process.mjs',import.meta.url));
153
+ const result=await previewClaudeTools({cwd:process.cwd(),model,
154
+ spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,fixture,...args.slice(3)],options)});
155
+ assert.equal(result.preflight.message_requests,1);
156
+ // The fixture's /api/hello HEAD is recorded first as {startup:true}; the message check follows it.
157
+ const message=result.preflight.request_checks.find(check=>Object.hasOwn(check,'model_matches'));
158
+ assert.equal(message?.model_matches,true);
159
+ assert.equal(result.preflight.passed,recognized);
160
+ const marker=result.preflight.request_checks.filter(check=>Object.hasOwn(check,'model_recognized'));
161
+ if(recognized)assert.deepEqual(marker,[]);
162
+ else assert.deepEqual(marker,[{model_recognized:false,reported_model:model}]);
163
+ if(!recognized)assert.deepEqual(result.preflight.request_checks.at(-1),{model_recognized:false,reported_model:model});
164
+ assert.equal(JSON.stringify(result).includes('CM-PROBE-001'),false);
165
+ });
166
+ test('Claude preflight CLI exits 1 with model_recognized false and leaves normal receipt unchanged',
167
+ {skip:process.platform!=='darwin'},()=>{
168
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-claude-model-cli-')));
169
+ try{
170
+ const codeProject=path.join(root,'code'),specsDir=path.join(root,'specs'),feature='1.work';
171
+ fs.mkdirSync(codeProject);fs.mkdirSync(path.join(specsDir,feature),{recursive:true});
172
+ for(const name of ['requirements.md','design.md'])
173
+ fs.writeFileSync(path.join(specsDir,feature,name),'# Fixture\n');
174
+ fs.writeFileSync(path.join(specsDir,feature,'tasks.md'),'- [ ] T-001: fixture\n');
175
+ fs.writeFileSync(path.join(specsDir,'.cm-specs-status'),JSON.stringify({status:'approved',features:[feature],
176
+ specFiles:buildManifest(specsDir)}));
177
+ fs.writeFileSync(path.join(codeProject,'requirements.md'),'# Fixture\n');
178
+ const config=path.join(root,'run.json');
179
+ fs.writeFileSync(config,JSON.stringify({version:1,specsDir,codeProject,feature,
180
+ identity:{repositoryId:'model-fixture',runId:'model-fixture-run',taskId:'T-001',attempt:1},
181
+ scope:['target.mjs'],requirements:['requirements.md']}));
182
+ const bin=path.join(root,'bin');fs.mkdirSync(bin);
183
+ const fake=path.join(bin,'claude');
184
+ fs.copyFileSync(fileURLToPath(new URL('./fixtures/claude-review-process.mjs',import.meta.url)),fake);
185
+ fs.chmodSync(fake,0o700);
186
+ const cli=fileURLToPath(new URL('./cm-ai-host.mjs',import.meta.url));
187
+ for(const [model,expectedExit] of [['fixture-unrecognized-model',1],['fixture-recognized-model',0]]){
188
+ const run=spawnSync(process.execPath,[cli,'preflight','--config',config,'--review-model',model,'--runtime','claude'],
189
+ {encoding:'utf8',env:{...process.env,PATH:bin+path.delimiter+process.env.PATH},timeout:10000});
190
+ assert.equal(run.status,expectedExit,run.stderr);
191
+ assert.ok(run.stdout.trim(),run.stderr);
192
+ const receipt=JSON.parse(run.stdout);
193
+ assert.equal(receipt.preflight.passed,expectedExit===0);
194
+ assert.equal(receipt.preflight.request_checks.find(check=>Object.hasOwn(check,'model_matches'))?.model_matches,true);
195
+ if(expectedExit===1)assert.deepEqual(receipt.preflight.request_checks.at(-1),
196
+ {model_recognized:false,reported_model:model});
197
+ else assert.equal(receipt.preflight.request_checks.some(check=>Object.hasOwn(check,'model_recognized')),false);
198
+ assert.equal(run.stdout.includes('CM-PROBE-001'),false);
199
+ }
200
+ }finally{fs.rmSync(root,{recursive:true,force:true});}
201
+ });
87
202
  test('probe sandbox denies sibling writes and connections to a different loopback port',
88
203
  {skip:process.platform!=='darwin'},async()=>{
89
204
  const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-probe-isolation-')));
@@ -170,12 +170,55 @@ test('rate limit session, count, whitelist and terminal boundaries fail closed',
170
170
  });
171
171
 
172
172
  const systemNotice = (subtype='api_retry',extra={}) => ({type:'system',subtype,session_id:'fresh-review',...extra});
173
+ const devIntent = (sessionId='fresh-review') => JSON.parse(
174
+ `{"type":"system","subtype":"dev_intent","kind":"ios_app","trigger":"project_scan","uuid":"fixture-uuid","session_id":"${sessionId}"}`,
175
+ );
173
176
  function observe(messages,callback) {
174
177
  const events=[],notices=[];
175
178
  const stream=createClaudeReviewStream(e=>events.push(e),callback ?? (n=>notices.push(n)));
176
179
  messages.forEach(m=>stream.accept(m));
177
180
  return {result:stream.finish(),events,notices};
178
181
  }
182
+ test('dev_intent before or after init preserves review result and emits only its subtype',()=>{
183
+ const [init,assistant,result]=transcript(),baseline=observe(transcript());
184
+ for(const messages of [
185
+ [devIntent(),init,assistant,result],
186
+ [init,devIntent(),assistant,result],
187
+ [init,assistant,devIntent(),result],
188
+ ]){
189
+ const actual=observe(messages);
190
+ assert.deepEqual(actual.result,baseline.result);
191
+ assert.deepEqual(actual.events,baseline.events);
192
+ assert.deepEqual(actual.notices,[{kind:'claude_system_notice',subtype:'dev_intent'}]);
193
+ }
194
+ for(const callback of [undefined,()=>{throw Error('notice consumer');}]){
195
+ const stream=createClaudeReviewStream(()=>{},callback);
196
+ [devIntent(),init,assistant,result].forEach(message=>stream.accept(message));
197
+ assert.deepEqual(stream.finish(),baseline.result);
198
+ }
199
+ });
200
+ test('dev_intent binds session across init and shares the 32-notice budget',()=>{
201
+ const [init,assistant,result]=transcript();
202
+ for(const messages of [
203
+ [devIntent('other'),init],
204
+ [init,devIntent('other')],
205
+ ])assert.throws(()=>decode(messages),{code:'session_mismatch'});
206
+ for(const sessionId of ['', ' '.repeat(3), 'x'.repeat(257)]){
207
+ const stream=createClaudeReviewStream(()=>{});
208
+ assert.throws(()=>stream.accept(devIntent(sessionId)),{code:'invalid_session'});
209
+ }
210
+ assert.throws(()=>decode([systemNotice('api_retry'),init]),{code:'missing_init'});
211
+ assert.throws(()=>decode([init,systemNotice('future_notice')]),{code:'unexpected_event'});
212
+ const notices=[],stream=createClaudeReviewStream(()=>{},notice=>notices.push(notice));
213
+ [devIntent(),...Array.from({length:30},()=>devIntent()),init,rateLimit(),assistant,result]
214
+ .forEach(message=>stream.accept(message));
215
+ assert.equal(stream.finish().status,'succeeded');
216
+ assert.equal(notices.length,32);
217
+ const overflow=createClaudeReviewStream(()=>{});
218
+ [devIntent(),init,...Array.from({length:31},()=>devIntent())]
219
+ .forEach(message=>overflow.accept(message));
220
+ assert.throws(()=>overflow.accept(devIntent()),{code:'unexpected_event'});
221
+ });
179
222
  test('88-heartbeat dogfood event counts preserve structured findings and exact observation',()=>{
180
223
  const [init,text,result]=transcript();
181
224
  const value={verdict:'changes_requested',packageDigest:'a'.repeat(64),examinedPaths:['code.mjs'],