@aibyzero/cm-workflow 0.12.0 → 0.13.3

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 (121) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/AGENTS.md +1 -0
  3. package/CHANGELOG.md +60 -1
  4. package/README.md +36 -3
  5. package/VERSION +1 -1
  6. package/compat/claude-commands/cm-runtime.md +3 -0
  7. package/docs/installation.md +58 -1
  8. package/docs/js-workflow-control.md +63 -6
  9. package/docs/runtime-failover.md +97 -0
  10. package/docs/user-guide.md +50 -1
  11. package/install-codex.sh +5 -0
  12. package/install.ps1 +10 -2
  13. package/install.sh +5 -0
  14. package/package.json +2 -1
  15. package/runtime/js/cm-ai/claude-developer-proposal.schema.json +151 -0
  16. package/runtime/js/cm-ai/claude-review-stream.mjs +69 -8
  17. package/runtime/js/cm-ai/claude-tool-preview.mjs +6 -4
  18. package/runtime/js/cm-ai/cm-ai-admission.mjs +38 -16
  19. package/runtime/js/cm-ai/cm-ai-conversation-entry.mjs +44 -17
  20. package/runtime/js/cm-ai/cm-ai-qa-log.mjs +105 -12
  21. package/runtime/js/cm-ai/codex-config.mjs +6 -0
  22. package/runtime/js/cm-ai/codex-review-adapter.mjs +6 -2
  23. package/runtime/js/cm-ai/developer-adapter.mjs +41 -16
  24. package/runtime/js/cm-ai/durable-runner-state.mjs +72 -15
  25. package/runtime/js/cm-ai/effect-contract.mjs +10 -1
  26. package/runtime/js/cm-ai/fix-code-association.mjs +4 -1
  27. package/runtime/js/cm-ai/host-conversation-execution.mjs +112 -27
  28. package/runtime/js/cm-ai/host-documentation.mjs +4 -2
  29. package/runtime/js/cm-ai/host-qa-executor.mjs +17 -4
  30. package/runtime/js/cm-ai/host-qa-policy.mjs +6 -3
  31. package/runtime/js/cm-ai/host-role-routing.mjs +9 -5
  32. package/runtime/js/cm-ai/host-tool-bridge.mjs +10 -7
  33. package/runtime/js/cm-ai/host-workflow-capabilities.mjs +9 -4
  34. package/runtime/js/cm-ai/host.mjs +1 -1
  35. package/runtime/js/cm-ai/provider-review-observation.mjs +8 -4
  36. package/runtime/js/cm-ai/qa-attachment.mjs +30 -0
  37. package/runtime/js/cm-ai/review-package.mjs +76 -18
  38. package/runtime/js/cm-ai/review-runner.mjs +15 -3
  39. package/runtime/js/cm-ai/runtime-failover.mjs +75 -0
  40. package/runtime/js/cm-ai/specification-material.mjs +98 -0
  41. package/runtime/js/cm-ai/task-runner.mjs +57 -20
  42. package/runtime/js/cm-ai/worker-claude-developer.mjs +174 -0
  43. package/runtime/js/cm-ai/worker-claude.mjs +18 -5
  44. package/runtime/js/cm-ai/worker-codex-developer.mjs +15 -4
  45. package/runtime/js/cm-ai/worker-codex.mjs +8 -12
  46. package/runtime/js/cm-init/draft-generation.mjs +24 -4
  47. package/runtime/js/cm-init/draft-inspection.mjs +29 -1
  48. package/runtime/js/cm-prd/session.mjs +19 -2
  49. package/runtime/js/cm-prd/summary.mjs +46 -20
  50. package/runtime/review.md +11 -1
  51. package/runtime/workflow-config.md +39 -2
  52. package/runtime/workflow-routing.md +6 -1
  53. package/scripts/cm-ai-admission.test.mjs +99 -0
  54. package/scripts/cm-ai-batch-host.test.mjs +4 -1
  55. package/scripts/cm-ai-batch-run.test.mjs +7 -1
  56. package/scripts/cm-ai-bootstrap.test.mjs +9 -2
  57. package/scripts/cm-ai-fix-integration.test.mjs +2 -1
  58. package/scripts/cm-ai-host.mjs +81 -12
  59. package/scripts/cm-ai-host.test.mjs +527 -6
  60. package/scripts/cm-ai-multi-root.test.mjs +16 -4
  61. package/scripts/cm-ai-nested-execution.test.mjs +18 -5
  62. package/scripts/cm-ai-review-timeout.test.mjs +226 -0
  63. package/scripts/cm-ai-run.mjs +40 -13
  64. package/scripts/cm-ai-run.test.mjs +45 -9
  65. package/scripts/cm-check-host.test.mjs +8 -2
  66. package/scripts/cm-check-runtime.sh +51 -1
  67. package/scripts/cm-claude-developer-worker.test.mjs +236 -0
  68. package/scripts/cm-claude-probe.test.mjs +64 -1
  69. package/scripts/cm-claude-review-stream.test.mjs +236 -1
  70. package/scripts/cm-claude-worker.test.mjs +110 -1
  71. package/scripts/cm-codex-developer-adapter.test.mjs +50 -2
  72. package/scripts/cm-codex-developer-worker.test.mjs +84 -1
  73. package/scripts/cm-codex-review-progress.test.mjs +34 -6
  74. package/scripts/cm-failover.mjs +288 -0
  75. package/scripts/cm-failover.test.mjs +184 -0
  76. package/scripts/cm-fix-host-review.test.mjs +7 -1
  77. package/scripts/cm-host-qa-executor.test.mjs +277 -0
  78. package/scripts/cm-host-tool-bridge.test.mjs +31 -0
  79. package/scripts/cm-init-draft-generation.test.mjs +62 -0
  80. package/scripts/cm-init-draft-inspection.test.mjs +76 -0
  81. package/scripts/cm-init-host.mjs +4 -4
  82. package/scripts/cm-init-host.test.mjs +12 -7
  83. package/scripts/cm-init-session.test.mjs +50 -0
  84. package/scripts/cm-log-event.mjs +34 -5
  85. package/scripts/cm-prd-completion.test.mjs +9 -3
  86. package/scripts/cm-prd-host.mjs +39 -3
  87. package/scripts/cm-prd-host.test.mjs +52 -0
  88. package/scripts/cm-prd-review-gate.mjs +11 -2
  89. package/scripts/cm-prd-review-gate.test.mjs +62 -0
  90. package/scripts/cm-prd-session-recovery.test.mjs +167 -0
  91. package/scripts/cm-prd-summary.test.mjs +147 -0
  92. package/scripts/cm-review-dependency-snapshot.test.mjs +10 -0
  93. package/scripts/cm-review-inventory.test.mjs +189 -0
  94. package/scripts/cm-review-schema.test.mjs +35 -1
  95. package/scripts/cm-review-scope-recovery.test.mjs +63 -0
  96. package/scripts/cm-runtime-edit.mjs +104 -0
  97. package/scripts/cm-runtime-failover.test.mjs +130 -0
  98. package/scripts/cm-runtime-i18n.mjs +32 -0
  99. package/scripts/cm-runtime-install.mjs +68 -0
  100. package/scripts/cm-runtime.mjs +141 -0
  101. package/scripts/cm-runtime.test.mjs +218 -0
  102. package/scripts/cm-spec-manifest.mjs +24 -21
  103. package/scripts/cm-spec-manifest.test.mjs +19 -0
  104. package/scripts/cm-workflow-config.mjs +113 -5
  105. package/scripts/cm-workflow-config.test.mjs +124 -1
  106. package/scripts/fixtures/prd-review-gate-python-oracle.py +18 -2
  107. package/scripts/test-cm-prd-review-gate.py +30 -0
  108. package/scripts/test-shell-compat.sh +34 -0
  109. package/scripts/validate-public-repo.py +5 -0
  110. package/skills/cm-ai/references/N4-review.md +5 -4
  111. package/skills/cm-ai/references/js-host.md +36 -2
  112. package/skills/cm-check/SKILL.md +7 -3
  113. package/skills/cm-init/SKILL.md +4 -0
  114. package/skills/cm-init/references/js-host.md +2 -0
  115. package/skills/cm-init/references/runtime-declaration.md +26 -0
  116. package/skills/cm-prd/SKILL.md +3 -3
  117. package/skills/cm-prd/references/js-change-recovery.md +24 -3
  118. package/skills/cm-prd/references/summary-card.md +7 -0
  119. package/skills/cm-runtime/SKILL.md +53 -0
  120. package/templates/auto-update/cm-update.sh +1 -1
  121. package/templates/cm-workflow.yml +16 -0
@@ -1,4 +1,4 @@
1
- import test from 'node:test';
1
+ import test,{after} from 'node:test';
2
2
  import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
@@ -8,11 +8,17 @@ import {once} from 'node:events';
8
8
  import {createInterface} from 'node:readline';
9
9
  import {fileURLToPath} from 'node:url';
10
10
  import {createCmCheckHost} from '../runtime/js/cm-check/host.mjs';
11
+
12
+ // Keep runtime declarations and log mirrors independent of the invoking user's home.
13
+ const isolatedWorkflowHome=fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-host-home-'));
14
+ process.env.CM_WORKFLOW_HOME=path.join(isolatedWorkflowHome,'user');
15
+ process.env.CM_WORKFLOW_LOG_HOME=path.join(isolatedWorkflowHome,'logs');
16
+ after(()=>fs.rmSync(isolatedWorkflowHome,{recursive:true,force:true}));
11
17
  const root=fileURLToPath(new URL('..',import.meta.url));
12
18
  function fixture(t,exitCode=0){
13
19
  const dir=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-check-host-'))),project=path.join(dir,'project');fs.mkdirSync(project);
14
20
  t.after(()=>fs.rmSync(dir,{recursive:true,force:true}));
15
- for(const file of ['scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','runtime/js/cm-check/host.mjs',
21
+ for(const file of ['scripts/cm-check-entry.mjs','scripts/cm-check-host.mjs','scripts/cm-workflow-config.mjs','runtime/js/cm-check/host.mjs',
16
22
  'runtime/js/cm-ai/host-tool-bridge.mjs','runtime/js/cm-ai/host-session.mjs','runtime/js/cm-ai/effect-contract.mjs',
17
23
  'runtime/js/cm-ai/contracts.mjs','runtime/js/cm-init/draft-inspection.mjs','skills/cm-check/SKILL.md']){
18
24
  fs.mkdirSync(path.dirname(path.join(dir,file)),{recursive:true});fs.copyFileSync(path.join(root,file),path.join(dir,file));
@@ -9,6 +9,10 @@ fail() {
9
9
  FAILURES=$((FAILURES + 1))
10
10
  }
11
11
 
12
+ warn() {
13
+ echo "WARN: $*" >&2
14
+ }
15
+
12
16
  require_file() {
13
17
  [ -f "$ROOT/$1" ] || fail "missing $1"
14
18
  }
@@ -301,6 +305,23 @@ require_file "scripts/cm-task-gate.py"
301
305
  require_file "scripts/test-task-gate.py"
302
306
  require_file "scripts/cm-workflow-config.mjs"
303
307
  require_file "scripts/cm-workflow-config.test.mjs"
308
+ # Group 4: user runtimes.yml producers <-> authoritative consumer.
309
+ for asset in scripts/cm-runtime.mjs scripts/cm-runtime-edit.mjs scripts/cm-runtime-install.mjs scripts/cm-runtime.test.mjs skills/cm-init/references/runtime-declaration.md; do
310
+ require_file "$asset"
311
+ done
312
+ grep -Fq 'userRuntimesPath' "$ROOT/scripts/cm-runtime.mjs" &&
313
+ grep -Fq 'writeUserRuntime' "$ROOT/scripts/cm-runtime-install.mjs" &&
314
+ grep -Fq 'runtimes.yml' "$ROOT/scripts/cm-workflow-config.mjs" &&
315
+ grep -Fq 'loadUserRuntimes()' "$ROOT/scripts/cm-workflow-config.mjs" &&
316
+ grep -Fq 'runtimes_source' "$ROOT/skills/cm-init/references/runtime-declaration.md" ||
317
+ fail "user runtimes.yml producer/consumer pairing is incomplete"
318
+ if [ "$MODE" = "plugin" ]; then
319
+ for installer in install.sh install.ps1 install-codex.sh; do
320
+ grep -Fq 'scripts/cm-runtime-install.mjs' "$ROOT/$installer" ||
321
+ fail "user runtimes.yml prompt not wired in $installer"
322
+ done
323
+ fi
324
+
304
325
  require_file "scripts/cm_workflow_config.py"
305
326
  require_file "scripts/test-workflow-config.py"
306
327
  require_file "scripts/validate-test-cases.mjs"
@@ -357,6 +378,35 @@ if [ -n "$NODE_BIN" ]; then
357
378
  "$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" ||
358
379
  fail "project workflow config validation failed"
359
380
  fi
381
+ # Runtime declaration vs. this machine. The declaration is the user's word;
382
+ # the probe only says whether a CLI resolves (never whether quota is usable).
383
+ # Roles whose adapter names the other runtime are declared, not dispatched.
384
+ effective_json=""
385
+ if [ -n "$CONFIG_PATH" ]; then
386
+ effective_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --config "$CONFIG_PATH" --print-effective 2>/dev/null || true)
387
+ else
388
+ effective_json=$("$NODE_BIN" "$ROOT/scripts/cm-workflow-config.mjs" --project "$PROJECT_PATH" --print-effective 2>/dev/null || true)
389
+ fi
390
+ if [ -n "$effective_json" ]; then
391
+ declared=$(printf '%s' "$effective_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{const j=JSON.parse(d);process.stdout.write(String(j.runtimes&&j.runtimes.available||"unknown"));})' 2>/dev/null || echo unknown)
392
+ if [ "$declared" != "unknown" ]; then
393
+ probe_json=$("$NODE_BIN" "$ROOT/scripts/cm-failover.mjs" probe --json 2>/dev/null || true)
394
+ missing=$(printf '%s' "$probe_json" | "$NODE_BIN" -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>{let j={runtimes:[]};try{j=JSON.parse(d);}catch{}const want=process.argv[1]==="both"?["codex","claude"]:[process.argv[1]];const ok=new Set(j.runtimes.filter(r=>r.available).map(r=>r.runtime));process.stdout.write(want.filter(r=>!ok.has(r)).join(" "));})' "$declared" 2>/dev/null || true)
395
+ for rt in $missing; do
396
+ warn "runtimes.available 声明 ${declared},但本机 ${rt} CLI 不可解析(可解析≠配额可用)"
397
+ done
398
+ current_runtime="${CM_RUNTIME:-codex}"
399
+ for role in coder reviewer; do
400
+ if [ -n "$CONFIG_PATH" ]; then
401
+ 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
+ else
403
+ 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
+ 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)
406
+ [ -n "$role_line" ] && echo "runtime declaration [${declared}] ${role_line}"
407
+ done
408
+ fi
409
+ fi
360
410
  fi
361
411
  else
362
412
  fail "Node.js 18+ is required for CM workflow config validation"
@@ -580,7 +630,7 @@ for consumer in \
580
630
  fail "external-expert AUTO routing is not wired into $consumer"
581
631
  done
582
632
 
583
- for name in cm-idea cm-init cm-prd cm-ai cm-test cm-security cm-fix cm-refactor cm-check; do
633
+ for name in cm-idea cm-init cm-prd cm-ai cm-test cm-security cm-fix cm-refactor cm-check cm-runtime; do
584
634
  require_file "skills/$name/SKILL.md"
585
635
  require_file "compat/claude-commands/$name.md"
586
636
  wrapper="$ROOT/compat/claude-commands/$name.md"
@@ -0,0 +1,236 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import {spawn} from 'node:child_process';
7
+ import {claudeDeveloperWorker,claudeDeveloperArgs,validateClaudeProposal} from '../runtime/js/cm-ai/worker-claude-developer.mjs';
8
+ import {createProjectExecution} from '../runtime/js/cm-ai/host-project-execution.mjs';
9
+ import {buildClaudeDeveloperPrompt} from '../runtime/js/cm-ai/claude-developer-adapter.mjs';
10
+ import {protectedTextInstructions} from '../runtime/js/cm-ai/host-conversation-execution.mjs';
11
+ import {digest} from '../runtime/js/cm-ai/effect-contract.mjs';
12
+
13
+ const identity={repositoryId:'proposal-fixture',runId:'proposal-run',taskId:'T-001',attempt:1};
14
+ const proposal={status:'succeeded',value:{outcome:'implemented'},edits:[{path:'target.txt',beforeSha256:null,content:'safe text\n'}]};
15
+ function prompt(){
16
+ const body={version:1,invocationId:'dev-1',identity,role:'developer',provider:'claude',requestedModel:'fixture',
17
+ contextId:'author',payload:{scope:['target.txt'],requirements:[],priorReview:null}};
18
+ return buildClaudeDeveloperPrompt({...body,requestDigest:digest(body)})+protectedTextInstructions;
19
+ }
20
+ function fixture(t){
21
+ const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cm-claude-development-')));
22
+ t.after(()=>fs.rmSync(root,{recursive:true,force:true}));
23
+ return root;
24
+ }
25
+ function fakeWorker(cwd,{value=proposal,mode='normal',timeoutMs=3000,noticeEvents=[],noticeAt=1,onNotice,
26
+ resultFields={},toolName='Read',toolResultId='read-1',
27
+ assistantContent=[{type:'text',text:'proposal'}]}={}){
28
+ const source=`let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',()=>{
29
+ if(!input.includes('Return {status,value,edits}'))process.exit(9);
30
+ if(${JSON.stringify(mode)}==='timeout'){setInterval(()=>{},1000);return;}
31
+ const session_id='synthetic-claude-developer';
32
+ const value=${JSON.stringify(value)};
33
+ const events=[{type:'system',subtype:'init',session_id}];
34
+ if(${JSON.stringify(mode)}==='read')events.push(
35
+ {type:'assistant',session_id,parent_tool_use_id:null,message:{role:'assistant',content:[{type:'tool_use',id:'read-1',name:${JSON.stringify(toolName)},input:{file_path:'target.txt'}}]}},
36
+ {type:'user',session_id,message:{role:'user',content:[{type:'tool_result',tool_use_id:${JSON.stringify(toolResultId)},content:'fixture text'}]}});
37
+ events.push({type:'assistant',session_id,parent_tool_use_id:null,message:{role:'assistant',content:
38
+ ${JSON.stringify(mode)}==='write'?[{type:'tool_use',id:'bad',name:'Write',input:{}}]:${JSON.stringify(assistantContent)}}},
39
+ {type:'result',session_id,subtype:${JSON.stringify(mode)}==='failed'?'error_during_execution':'success',
40
+ is_error:${JSON.stringify(mode)}==='failed',num_turns:1,result:JSON.stringify(value),...${JSON.stringify(resultFields)}});
41
+ events.splice(${JSON.stringify(noticeAt)},0,...${JSON.stringify(noticeEvents)});
42
+ for(const event of events)process.stdout.write(JSON.stringify(event)+'\\n');
43
+ });`;
44
+ return claudeDeveloperWorker({cwd,model:'fixture',timeoutMs,onNotice,spawnProcess:(cli,args,options)=>{
45
+ assert.equal(cli,'claude');assert.equal(options.shell,false);assert.equal(options.detached,true);
46
+ assert.deepEqual(args,claudeDeveloperArgs('fixture'));
47
+ assert.equal(args[args.indexOf('--tools')+1],'Read,Grep,Glob');
48
+ assert.equal(args[args.indexOf('--allowedTools')+1],'Read,Grep,Glob');
49
+ const index=args.indexOf('--json-schema');assert.ok(index>0);assert.equal(args.lastIndexOf('--json-schema'),index);
50
+ const schema=JSON.parse(args[index+1]);assert.equal(Object.hasOwn(schema,'$schema'),false);assert.equal(Object.hasOwn(schema,'$id'),false);
51
+ assert.deepEqual(schema.properties.status.enum,['succeeded','failed']);
52
+ assert.equal(args[args.indexOf('--permission-mode')+1],'dontAsk');
53
+ for(const key of ['NODE_OPTIONS','ANTHROPIC_BASE_URL','HTTP_PROXY','CLAUDE_CODE_USE_BEDROCK'])assert.equal(options.env[key],undefined);
54
+ return spawn(process.execPath,['-e',source],options);
55
+ }});
56
+ }
57
+ const rateLimit=(overrides={})=>({type:'rate_limit_event',session_id:'synthetic-claude-developer',
58
+ rate_limit_info:{status:'allowed',rateLimitType:'five_hour',resetsAt:123,active:true,reason:null,
59
+ nested:{raw:'private'},list:['private']},...overrides});
60
+ test('developer forwards scalar notices while preserving proposals and read-tool state',async t=>{
61
+ const root=fixture(t),events=[],control={signal:new AbortController().signal,onEvent:e=>events.push(e)};
62
+ const baseline=await fakeWorker(root)({prompt:prompt()},control);
63
+ for(const [mode,noticeAt,count] of [['normal',1,1],['normal',2,8],['read',2,8]]){
64
+ const notices=[],noticeEvents=Array.from({length:count},()=>rateLimit());
65
+ const result=await fakeWorker(root,{mode,noticeAt,noticeEvents,onNotice:n=>notices.push(n)})({prompt:prompt()},control);
66
+ assert.deepEqual(result,baseline);
67
+ assert.deepEqual(notices,Array.from({length:count},()=>({kind:'rate_limit',info:{status:'allowed',
68
+ rateLimitType:'five_hour',resetsAt:123,active:true,reason:null}})));
69
+ }
70
+ for(const onNotice of [undefined,()=>{throw Error('notice consumer');}]){
71
+ const result=await fakeWorker(root,{noticeEvents:[rateLimit()],onNotice})({prompt:prompt()},control);
72
+ assert.deepEqual(result,baseline);
73
+ }
74
+ assert.deepEqual(events,[]);assert.deepEqual(fs.readdirSync(root),[]);
75
+ });
76
+ const thinkingTokens=()=>({type:'system',subtype:'thinking_tokens',session_id:'synthetic-claude-developer',estimated_tokens:10});
77
+ const thoughts={type:'assistant',session_id:'synthetic-claude-developer',parent_tool_use_id:null,
78
+ message:{role:'assistant',content:[{type:'thinking',thinking:'private',signature:'sig'},{type:'redacted_thinking',data:'private'}]}};
79
+ test('developer thinking events preserve proposal and read tool pairing with developer schema',async t=>{
80
+ const root=fixture(t),control={signal:new AbortController().signal};
81
+ const baseline=await fakeWorker(root)({prompt:prompt()},control);
82
+ for(const [mode,noticeAt,count] of [['normal',1,2],['normal',2,64],['read',2,2]]){
83
+ const result=await fakeWorker(root,{mode,noticeAt,
84
+ noticeEvents:[rateLimit(),...Array.from({length:count},thinkingTokens),thoughts],
85
+ assistantContent:[...thoughts.message.content,{type:'text',text:'proposal'}]})({prompt:prompt()},control);
86
+ assert.deepEqual(result,baseline);
87
+ }
88
+ const mixed=await fakeWorker(root,{assistantContent:[...thoughts.message.content,
89
+ {type:'tool_use',id:'forbidden',name:'Bash',input:{}}]})({prompt:prompt()},control);
90
+ assert.equal(mixed.code,'unexpected_tool_or_content');
91
+ assert.deepEqual(fs.readdirSync(root),[]);
92
+ });
93
+ test('developer thinking preserves initial, terminal, count and unknown-system rejection',async t=>{
94
+ const root=fixture(t),control={signal:new AbortController().signal};
95
+ for(const [noticeEvents,noticeAt,code] of [
96
+ [Array.from({length:65},thinkingTokens),1,'unexpected_event'],
97
+ [[{...thinkingTokens(),subtype:'unknown'}],1,'unexpected_event'],
98
+ [[{...thinkingTokens(),subtype:'init'}],1,'unexpected_event'],
99
+ [[{...thinkingTokens(),session_id:'other'}],1,'session_mismatch'],
100
+ [[thinkingTokens()],0,'missing_init'],
101
+ [[thinkingTokens()],3,'invalid_event'],
102
+ ]){
103
+ const result=await fakeWorker(root,{noticeEvents,noticeAt})({prompt:prompt()},control);
104
+ assert.deepEqual(result,{status:'unknown',code});
105
+ }
106
+ const result=await fakeWorker(root,{assistantContent:thoughts.message.content})({prompt:prompt()},control);
107
+ assert.deepEqual(result,{status:'unknown',code:'unexpected_result'});
108
+ });
109
+ test('developer rejects mismatched, excessive, unknown and terminal rate limit events',async t=>{
110
+ const root=fixture(t);
111
+ for(const [noticeEvents,noticeAt,code,count] of [
112
+ [[rateLimit({session_id:'other'})],1,'session_mismatch',0],
113
+ [Array.from({length:9},()=>rateLimit()),1,'unexpected_event',8],
114
+ [[rateLimit({type:'foo_event'})],1,'unexpected_event',0],
115
+ [[rateLimit()],0,'missing_init',0],
116
+ [[rateLimit()],3,'invalid_event',0],
117
+ ]){
118
+ const notices=[],result=await fakeWorker(root,{noticeEvents,noticeAt,onNotice:n=>notices.push(n)})
119
+ ({prompt:prompt()},{signal:new AbortController().signal});
120
+ assert.deepEqual(result,{status:'unknown',code});assert.equal(notices.length,count);
121
+ }
122
+ assert.deepEqual(fs.readdirSync(root),[]);
123
+ });
124
+ for(const mode of ['normal','read'])test(`Claude ${mode} process returns a proposal without writing files`,async t=>{
125
+ const root=fixture(t),worker=fakeWorker(root,{mode});
126
+ const result=await worker({prompt:prompt()},{signal:new AbortController().signal});
127
+ assert.equal(result.status,'succeeded');assert.deepEqual(result.edits,proposal.edits);
128
+ assert.equal(result.providerThread,'synthetic-claude-developer');assert.deepEqual(fs.readdirSync(root),[]);
129
+ assert.equal((await worker({prompt:prompt()},{signal:new AbortController().signal})).code,'worker_dispatch_limit');
130
+ });
131
+ for(const [mode,code] of [['timeout','timeout'],['failed','provider_failed'],['write','unexpected_tool_or_content']])test(`Claude ${mode} fails closed`,async t=>{
132
+ const root=fixture(t),result=await fakeWorker(root,{mode,timeoutMs:mode==='timeout'?100:3000})({prompt:prompt()},{signal:new AbortController().signal});
133
+ assert.equal(result.code,code);assert.equal(result.status,mode==='failed'?'unavailable':'unknown');assert.deepEqual(fs.readdirSync(root),[]);
134
+ });
135
+ test('spawn throw and asynchronous missing executable are unavailable; aborted calls never spawn',async t=>{
136
+ const cwd=fixture(t);
137
+ for(const options of [{spawnProcess(){throw Error('fixture');}},{cli:path.join(cwd,'missing')}]){
138
+ const result=await claudeDeveloperWorker({cwd,model:'fixture',...options})({prompt:prompt()},{signal:new AbortController().signal});
139
+ assert.deepEqual(result,{status:'unavailable',code:'spawn_failed'});
140
+ }
141
+ const controller=new AbortController();controller.abort();
142
+ const result=await claudeDeveloperWorker({cwd,model:'fixture',spawnProcess(){assert.fail('spawn');}})({prompt:prompt()},{signal:controller.signal});
143
+ assert.equal(result.status,'cancelled');
144
+ });
145
+ for(const content of ['binary\0data','x'.repeat(65536),'bad\ud800text'])test(`invalid text proposal rejected (${content.length} characters)`,async t=>{
146
+ const cwd=fixture(t),value={...proposal,edits:[{...proposal.edits[0],content}]};
147
+ const result=await fakeWorker(cwd,{value})({prompt:prompt()},{signal:new AbortController().signal});
148
+ assert.notEqual(result.status,'succeeded');assert.deepEqual(fs.readdirSync(cwd),[]);
149
+ });
150
+ test('actual proposal cannot escape scope or use stale expected hashes at host commit',async t=>{
151
+ const root=fixture(t),codeProject=path.join(root,'code'),specsDir=path.join(codeProject,'specs');fs.mkdirSync(specsDir,{recursive:true});
152
+ const project=createProjectExecution({definition:{codeProject,specsDir},protection:{timeoutMs:3000,
153
+ checkCommands:[{id:'syntax',command:[process.execPath,'--version']}]}});
154
+ const scope=['target.txt'],expected=project.expected(scope),signal=new AbortController().signal;
155
+ for(const edit of [{path:'../escape',beforeSha256:null,content:'bad'},{path:'target.txt',beforeSha256:'0'.repeat(64),content:'bad'}]){
156
+ const result=await fakeWorker(codeProject,{value:{...proposal,edits:[edit]}})({prompt:prompt()},{signal});
157
+ assert.equal(result.status,'succeeded');
158
+ await assert.rejects(project.commit({scope,expected,identity,signal,edits:result.edits}),{code:edit.path==='target.txt'?'protected_edit_stale':'out_of_scope'});
159
+ assert(!fs.existsSync(path.join(codeProject,'target.txt')));assert(!fs.existsSync(path.join(root,'escape')));
160
+ }
161
+ });
162
+
163
+ test('developer arguments carry the dedicated schema and exact success/failure prompt',()=>{
164
+ const args=claudeDeveloperArgs('fixture');
165
+ const schema=JSON.parse(args[args.indexOf('--json-schema')+1]);
166
+ assert.deepEqual(schema,JSON.parse(fs.readFileSync(new URL('../runtime/js/cm-ai/claude-developer-proposal.schema.json',import.meta.url),'utf8')));
167
+ assert.deepEqual(schema.required,['status']);assert.equal(schema.additionalProperties,false);
168
+ assert.equal(schema.properties.edits.maxItems,64);
169
+ assert.match(protectedTextInstructions,/status must be exactly "succeeded" on success \(with value and edits\) or "failed" \(with code\)/);
170
+ assert.match(protectedTextInstructions,/structured output schema; never wrap it in markdown fences/);
171
+ });
172
+ test('developer pairs StructuredOutput and prefers its proposal over fenced text',async t=>{
173
+ const root=fixture(t),control={signal:new AbortController().signal};
174
+ for(const toolName of ['Read','Grep','Glob','StructuredOutput']){
175
+ const result=await fakeWorker(root,{mode:'read',toolName,
176
+ resultFields:{structured_output:proposal,result:'```json\n{"status":"ok"}\n```'}})({prompt:prompt()},control);
177
+ assert.deepEqual(result,{...proposal,providerThread:'synthetic-claude-developer'});
178
+ }
179
+ const mismatch=await fakeWorker(root,{mode:'read',toolName:'StructuredOutput',toolResultId:'unknown',
180
+ resultFields:{structured_output:proposal}})({prompt:prompt()},control);
181
+ assert.deepEqual(mismatch,{status:'unknown',code:'unexpected_tool_or_content'});
182
+ const unpaired=await fakeWorker(root,{assistantContent:[{type:'tool_use',id:'schema-1',name:'StructuredOutput',input:proposal}],
183
+ resultFields:{structured_output:proposal}})({prompt:prompt()},control);
184
+ assert.deepEqual(unpaired,{status:'unknown',code:'unexpected_result'});
185
+ for(const toolName of ['Bash','Write','Edit','Task','WebFetch']){
186
+ const result=await fakeWorker(root,{mode:'read',toolName,resultFields:{structured_output:proposal}})({prompt:prompt()},control);
187
+ assert.deepEqual(result,{status:'unknown',code:'unexpected_tool_or_content'});
188
+ }
189
+ assert.deepEqual(fs.readdirSync(root),[]);
190
+ });
191
+ test('developer explicitly classifies malformed fallback JSON and rejects invalid structured output',async t=>{
192
+ const root=fixture(t),control={signal:new AbortController().signal};
193
+ for(const result of ['```json\n'+JSON.stringify(proposal)+'\n```','{broken','']){
194
+ assert.deepEqual(await fakeWorker(root,{resultFields:{result}})({prompt:prompt()},control),
195
+ {status:'unknown',code:'invalid_output_json'});
196
+ }
197
+ for(const value of [{...proposal,status:'ok'},{status:'ok',code:'bad'}]){
198
+ assert.throws(()=>validateClaudeProposal(value),{code:'invalid_result'});
199
+ assert.deepEqual(await fakeWorker(root,{value})({prompt:prompt()},control),{status:'unknown',code:'invalid_result'});
200
+ }
201
+ for(const structured_output of [null,{status:'ok',code:'bad'}]){
202
+ assert.deepEqual(await fakeWorker(root,{resultFields:{structured_output}})({prompt:prompt()},control),
203
+ {status:'unknown',code:'invalid_result'});
204
+ }
205
+ const failed={status:'failed',code:'implementation_blocked'};
206
+ assert.deepEqual(await fakeWorker(root,{resultFields:{structured_output:failed}})({prompt:prompt()},control),
207
+ {...failed,providerThread:'synthetic-claude-developer'});
208
+ });
209
+ test('proposal validation preserves schema fields and strict success/failure branches',()=>{
210
+ const candidate={classification:'structured',trigger:'retry',action:'check',evidence:['target.txt']};
211
+ const learning={...proposal,value:{outcome:'implemented',application:{status:'applied',note:'checked'},
212
+ retrospective:{status:'lesson_candidate',candidates:[candidate],reason:null}}};
213
+ for(const valid of [proposal,{status:'failed',code:'blocked'},learning,
214
+ {...proposal,value:{outcome:'blocked'}},
215
+ {...proposal,value:{outcome:'implemented',application:{status:'no_relevant_lesson',note:null},
216
+ retrospective:{status:'no_new_lesson',candidates:[],reason:null}}},
217
+ {...learning,value:{...learning.value,retrospective:{status:'writeback_pending',candidates:[{...candidate,classification:'memory_only'}],reason:'pending'}}},
218
+ {...proposal,edits:Array.from({length:64},()=>({...proposal.edits[0],beforeSha256:'a'.repeat(64),content:null}))}]){
219
+ assert.deepEqual(validateClaudeProposal(valid),valid);
220
+ }
221
+ for(const invalid of [null,{},[],{status:'failed'}, {status:'failed',code:''},{status:'failed',code:1},
222
+ {status:'failed',code:'blocked',edits:[]},{status:'succeeded',value:proposal.value},
223
+ {...proposal,code:'extra'},{...proposal,value:{outcome:'ok'}},{...proposal,value:{outcome:'implemented',extra:true}},
224
+ {...proposal,value:{outcome:'implemented',application:{status:'unknown',note:null}}},
225
+ {...proposal,value:{outcome:'implemented',application:{status:'applied',note:42}}},
226
+ ...[{status:'unknown',candidates:[],reason:null},{status:'no_new_lesson',candidates:[],reason:1},
227
+ {status:'lesson_candidate',candidates:Array(4).fill(candidate),reason:null},
228
+ ...[{...candidate,classification:'other'},{...candidate,evidence:[42]},{...candidate,trigger:42},{...candidate,extra:true}]
229
+ .map(c=>({status:'lesson_candidate',candidates:[c],reason:null}))]
230
+ .map(retrospective=>({...proposal,value:{outcome:'implemented',retrospective}})),
231
+ {...proposal,edits:Array(65).fill(proposal.edits[0])},
232
+ ...[{path:''},{beforeSha256:'A'.repeat(64)},{beforeSha256:'a'.repeat(63)},{beforeSha256:1},{content:1},{extra:true}]
233
+ .map(edit=>({...proposal,edits:[{...proposal.edits[0],...edit}]}))]){
234
+ assert.throws(()=>validateClaudeProposal(invalid),undefined,JSON.stringify(invalid));
235
+ }
236
+ });
@@ -8,7 +8,69 @@ import {spawn} from 'node:child_process';
8
8
  import {fileURLToPath} from 'node:url';
9
9
  import {previewClaudeTools,claudeProbeSandbox} from '../runtime/js/cm-ai/claude-tool-preview.mjs';
10
10
 
11
- test('diagnostic stops the process after exactly one tool-free local request',
11
+ test('probe accepts only empty tools or one internal StructuredOutput tool',
12
+ {skip:process.platform!=='darwin'},async()=>{
13
+ for(const [tools,passed] of [[[],true],[[{name:'StructuredOutput'}],true],[[{name:'Bash'}],false],
14
+ [[{name:'StructuredOutput'},{name:'Bash'}],false],[[{name:'StructuredOutput'},{name:'StructuredOutput'}],false],
15
+ [[null],false],['StructuredOutput',false]]){
16
+ const source=`let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',async()=>{
17
+ const response=await fetch(process.env.ANTHROPIC_BASE_URL+'/v1/messages',{method:'POST',
18
+ headers:{'x-api-key':'cm-synthetic-local-probe'},
19
+ body:JSON.stringify({model:'fixture',messages:[{role:'user',content:input}],tools:${JSON.stringify(tools)}})});
20
+ await response.text();process.exit(1);
21
+ });`;
22
+ const result=await previewClaudeTools({cwd:process.cwd(),model:'fixture',
23
+ spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,'-e',source],options)});
24
+ assert.equal(result.preflight.passed,passed,JSON.stringify(tools));
25
+ assert.equal(result.preflight.message_requests,1);
26
+ assert.equal(result.preflight.message_requests_expected,'1-2');
27
+ assert.equal(result.preflight.listener_closed,true);
28
+ assert.equal(result.preflight.request_checks[0].tools_allowed,passed);
29
+ assert.equal('tools_empty' in result.preflight.request_checks[0],false);
30
+ }
31
+ });
32
+
33
+ test('probe accepts at most two compliant requests and validates every request',
34
+ {skip:process.platform!=='darwin'},async t=>{
35
+ const empty={model:'fixture',tools:[]};
36
+ const structured={model:'fixture',tools:[{name:'StructuredOutput'}]};
37
+ const cases=[
38
+ ['two empty tool lists',[empty,empty],true],
39
+ ['two StructuredOutput tool lists',[structured,structured],true],
40
+ ['empty and StructuredOutput tool lists',[empty,structured],true],
41
+ ['second request includes Bash',[structured,{...empty,tools:[{name:'Bash'}]}],false],
42
+ ['second request changes model',[empty,{...empty,model:'different-model'}],false],
43
+ ['three compliant requests',[empty,structured,empty],false],
44
+ ];
45
+ for(const [name,requests,passed] of cases)await t.test(name,async()=>{
46
+ // Keep the fixture alive after SIGTERM so the worker's real cleanup captures
47
+ // the entire sequence deterministically, without delaying the probe's abort.
48
+ const source=`process.on('SIGTERM',()=>{});setInterval(()=>{},1000);
49
+ let input='';process.stdin.on('data',s=>input+=s);process.stdin.on('end',async()=>{
50
+ for(const request of ${JSON.stringify(requests)}){
51
+ const response=await fetch(process.env.ANTHROPIC_BASE_URL+'/v1/messages',{method:'POST',
52
+ headers:{'x-api-key':'cm-synthetic-local-probe'},
53
+ body:JSON.stringify({...request,messages:[{role:'user',content:input}]})});
54
+ await response.text();
55
+ }
56
+ });`;
57
+ const {preflight}=await previewClaudeTools({cwd:process.cwd(),model:'fixture',
58
+ spawnProcess:(command,args,options)=>spawn(command,[...args.slice(0,2),process.execPath,'-e',source],options)});
59
+ assert.equal(preflight.message_requests,requests.length);
60
+ assert.equal(preflight.local_requests,requests.length);
61
+ assert.equal(preflight.message_requests_expected,'1-2');
62
+ assert.equal(preflight.passed,passed);
63
+ assert.equal(preflight.stopped_by_probe,true);
64
+ assert.equal(preflight.process_code,'cancelled');
65
+ assert.equal(preflight.listener_closed,true);
66
+ assert.deepEqual(preflight.request_checks.map(checks=>checks.tools_allowed),
67
+ requests.map(request=>request.tools.every(tool=>tool.name==='StructuredOutput')));
68
+ assert.deepEqual(preflight.request_checks.map(checks=>checks.model_matches),
69
+ requests.map(request=>request.model==='fixture'));
70
+ });
71
+ });
72
+
73
+ test('diagnostic still accepts one tool-free message request from an older CLI',
12
74
  {skip:process.platform!=='darwin'},async()=>{
13
75
  const fixture=fileURLToPath(new URL('./fixtures/claude-review-process.mjs',import.meta.url));
14
76
  const result=await previewClaudeTools({cwd:process.cwd(),model:'fixture-plain-error',
@@ -19,6 +81,7 @@ test('diagnostic stops the process after exactly one tool-free local request',
19
81
  }});
20
82
  assert.equal(result.preflight.passed,true);assert.equal(result.preflight.local_requests,2);
21
83
  assert.equal(result.preflight.message_requests,1);
84
+ assert.equal(result.preflight.message_requests_expected,'1-2');
22
85
  assert.equal(result.preflight.stopped_by_probe,true);assert.equal(result.preflight.listener_closed,true);
23
86
  });
24
87
  test('probe sandbox denies sibling writes and connections to a different loopback port',